scordi-extension 1.15.12 → 1.15.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,256 @@
1
+ var aw=Object.defineProperty;var iw=(r,e,t)=>e in r?aw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var w=(r,e,t)=>iw(r,typeof e!="symbol"?e+"":e,t);import{i as ow,d as cw,e as lw,f as uw,g as dw}from"./internal-messages-CP1ANEcL.js";import{g as Ds,Z as L,a as vn,o as $r,s as In,b as Id,n as Rd,e as oa,C as xo,c as hw,l as fw,u as pw}from"./types-q2_wITfk.js";class mw{constructor(){w(this,"activeTabs",new Map);w(this,"closedTabs",new Set);w(this,"executingWorkflowTabs",new Map);this.initializeTabClosedListener(),this.initializeTabUpdatedListener()}initializeTabClosedListener(){chrome.tabs.onRemoved.addListener(e=>{console.log("[TabManager] Tab closed:",e),this.activeTabs.has(e)&&(console.log("[TabManager] Tracked tab was closed:",e),this.activeTabs.delete(e),this.closedTabs.add(e),this.executingWorkflowTabs.delete(e),setTimeout(()=>{this.closedTabs.delete(e)},6e4))})}initializeTabUpdatedListener(){chrome.tabs.onUpdated.addListener(async(e,t)=>{if(t.status==="complete"&&this.executingWorkflowTabs.has(e)){const n=this.executingWorkflowTabs.get(e);n&&(console.log("[TabManager] Page loaded in executing workflow tab, re-showing UI:",e),setTimeout(async()=>{await this.showExecutionStatus(e,n.message)},500))}})}isTabClosed(e){return this.closedTabs.has(e)}async createTab(e,t=!1,n=2e3){const s=await chrome.tabs.create({url:e,active:t});if(!s.id)throw new Error("Failed to create new tab");return this.activeTabs.set(s.id,{url:e,createdAt:Date.now()}),await this.waitForTabLoad(s.id),await new Promise(a=>setTimeout(a,n)),s}async closeTab(e){await chrome.tabs.remove(e),this.activeTabs.delete(e)}async waitForTabLoad(e,t=3e4){return new Promise((n,s)=>{const a=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(i),s(new Error("Tab load timeout"))},t),i=(o,c)=>{o===e&&c.status==="complete"&&(clearTimeout(a),chrome.tabs.onUpdated.removeListener(i),console.log("[8G TabManager] Tab loaded successfully:",e),n())};chrome.tabs.onUpdated.addListener(i)})}async showExecutionStatus(e,t){if(this.isTabClosed(e)){console.log("[TabManager] Cannot show execution status - tab was closed:",e);return}const n=t||"워크플로우 실행 중";this.executingWorkflowTabs.set(e,{message:n});const s={type:"SHOW_EXECUTION_STATUS",data:{message:n}};try{await chrome.tabs.sendMessage(e,s),console.log("[TabManager] Execution status shown")}catch(a){console.warn("[TabManager] Failed to show execution status:",a)}}async hideExecutionStatus(e){if(this.isTabClosed(e)){console.log("[TabManager] Cannot hide execution status - tab was closed:",e);return}this.executingWorkflowTabs.delete(e);const t={type:"HIDE_EXECUTION_STATUS"};try{await chrome.tabs.sendMessage(e,t),console.log("[TabManager] Execution status hidden")}catch(n){console.warn("[TabManager] Failed to hide execution status:",n)}}async executeBlock(e,t){return this.isTabClosed(t)?(console.log("[TabManager] Cannot execute block - tab was closed:",t),{hasError:!0,message:"Tab was closed by user",data:null}):this.executeBlockWithRetry(e,t,0)}async executeBlockWithRetry(e,t,n){return new Promise((a,i)=>{const o={isBlock:!0,type:"EXECUTE_BLOCK",data:e};chrome.tabs.sendMessage(t,o,async c=>{if(chrome.runtime.lastError){const l=chrome.runtime.lastError.message||"";if(console.log("[TabManager] Error sending message:",l),this.isTabClosed(t)){i(new Error("Tab was closed by user"));return}if((l.includes("Receiving end does not exist")||l.includes("message channel closed")||l.includes("back/forward cache"))&&n<3){console.log(`[TabManager] Page transition detected, waiting for reload and retrying (${n+1}/3)...`);try{await this.waitForTabLoad(t,1e4),await new Promise(h=>setTimeout(h,1e3));const d=await this.executeBlockWithRetry(e,t,n+1);a(d)}catch{i(new Error("Page load timeout after transition"))}}else i(new Error(l||"Communication error"))}else ow(c)?(console.log("[TabManager] Content script error:",c.message),i(new Error(c.message))):(console.log("[TabManager] Received response from content script"),a(c||{data:null}))})})}}var gw=Object.defineProperty,pe=(r,e)=>{for(var t in e)gw(r,t,{get:e[t],enumerable:!0})};function Wt(r){return typeof r=="object"&&r!==null&&"type"in r&&typeof r.type=="string"&&"source_type"in r&&(r.source_type==="url"||r.source_type==="base64"||r.source_type==="text"||r.source_type==="id")}function du(r){return Wt(r)&&r.source_type==="url"&&"url"in r&&typeof r.url=="string"}function hu(r){return Wt(r)&&r.source_type==="base64"&&"data"in r&&typeof r.data=="string"}function _w(r){return Wt(r)&&r.source_type==="text"&&"text"in r&&typeof r.text=="string"}function jp(r){return Wt(r)&&r.source_type==="id"&&"id"in r&&typeof r.id=="string"}function Dp(r){if(Wt(r)){if(r.source_type==="url")return{type:"image_url",image_url:{url:r.url}};if(r.source_type==="base64"){if(!r.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${r.mime_type};base64,${r.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function ml(r){const e=r.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${r}" - does not match type/subtype format.`);const t=e[0].trim(),n=e[1].trim();if(t===""||n==="")throw new Error(`Invalid mime type: "${r}" - type or subtype is empty.`);const s={};for(const a of r.split(";").slice(1)){const i=a.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${r}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${r}".`);s[o]=c}return{type:t,subtype:n,parameters:s}}function Zr({dataUrl:r,asTypedArray:e=!1}){const t=r.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let n;if(t){n=t[1].toLowerCase();const s=e?Uint8Array.from(atob(t[2]),a=>a.charCodeAt(0)):t[2];return{mime_type:n,data:s}}}function Fi(r,e){if(r.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(r)}if(r.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(r)}if(r.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(r)}if(r.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(r)}throw new Error(`Unable to convert content block type '${r.type}' to provider-specific format: not recognized.`)}function Up(r){return typeof r=="object"&&r!==null&&"type"in r&&"content"in r&&(typeof r.content=="string"||Array.isArray(r.content))}var Ao,Od;function yw(){return Od||(Od=1,Ao=function(r,e){if(typeof r!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,r.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}),Ao}var ww=yw();const bw=Ds(ww);var ca={exports:{}},$d;function vw(){if($d)return ca.exports;$d=1;const r=/[\p{Lu}]/u,e=/[\p{Ll}]/u,t=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,s=/[_.\- ]+/,a=new RegExp("^"+s.source),i=new RegExp(s.source+n.source,"gu"),o=new RegExp("\\d+"+n.source,"gu"),c=(h,f,p)=>{let g=!1,_=!1,b=!1;for(let m=0;m<h.length;m++){const y=h[m];g&&r.test(y)?(h=h.slice(0,m)+"-"+h.slice(m),g=!1,b=_,_=!0,m++):_&&b&&e.test(y)?(h=h.slice(0,m-1)+"-"+h.slice(m-1),b=_,_=!1,g=!0):(g=f(y)===y&&p(y)!==y,b=_,_=p(y)===y&&f(y)!==y)}return h},l=(h,f)=>(t.lastIndex=0,h.replace(t,p=>f(p))),u=(h,f)=>(i.lastIndex=0,o.lastIndex=0,h.replace(i,(p,g)=>f(g)).replace(o,p=>f(p))),d=(h,f)=>{if(!(typeof h=="string"||Array.isArray(h)))throw new TypeError("Expected the input to be `string | string[]`");if(f={pascalCase:!1,preserveConsecutiveUppercase:!1,...f},Array.isArray(h)?h=h.map(b=>b.trim()).filter(b=>b.length).join("-"):h=h.trim(),h.length===0)return"";const p=f.locale===!1?b=>b.toLowerCase():b=>b.toLocaleLowerCase(f.locale),g=f.locale===!1?b=>b.toUpperCase():b=>b.toLocaleUpperCase(f.locale);return h.length===1?f.pascalCase?g(h):p(h):(h!==p(h)&&(h=c(h,p,g)),h=h.replace(a,""),f.preserveConsecutiveUppercase?h=l(h,p):h=p(h),f.pascalCase&&(h=g(h.charAt(0))+h.slice(1)),u(h,g))};return ca.exports=d,ca.exports.default=d,ca.exports}vw();function Sw(r,e){return(e==null?void 0:e[r])||bw(r)}function Ew(r,e,t){const n={};for(const s in r)Object.hasOwn(r,s)&&(n[e(s,t)]=r[s]);return n}var Tw={};pe(Tw,{Serializable:()=>Rn,get_lc_unique_name:()=>fu});function Cd(r){return Array.isArray(r)?[...r]:{...r}}function xw(r,e){const t=Cd(r);for(const[n,s]of Object.entries(e)){const[a,...i]=n.split(".").reverse();let o=t;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=Cd(o[c]),o=o[c]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return t}function fu(r){const e=Object.getPrototypeOf(r);return typeof r.lc_name=="function"&&(typeof e.lc_name!="function"||r.lc_name()!==e.lc_name())?r.lc_name():r.name}var Rn=class Fp{constructor(e,...t){w(this,"lc_serializable",!1);w(this,"lc_kwargs");this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>{var s;return(s=this.lc_serializable_keys)==null?void 0:s.includes(n)})):this.lc_kwargs=e??{}}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,fu(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Fp||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},n=Object.keys(this.lc_kwargs).reduce((s,a)=>(s[a]=a in this?this[a]:this.lc_kwargs[a],s),{});for(let s=Object.getPrototypeOf(this);s;s=Object.getPrototypeOf(s))Object.assign(e,Reflect.get(s,"lc_aliases",this)),Object.assign(t,Reflect.get(s,"lc_secrets",this)),Object.assign(n,Reflect.get(s,"lc_attributes",this));return Object.keys(t).forEach(s=>{let a=this,i=n;const[o,...c]=s.split(".").reverse();for(const l of c.reverse()){if(!(l in a)||a[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof a[l]=="object"&&a[l]!=null?i[l]={}:Array.isArray(a[l])&&(i[l]=[])),a=a[l],i=i[l]}o in a&&a[o]!==void 0&&(i[o]=i[o]||a[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Ew(Object.keys(t).length?xw(n,t):n,Sw,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Q(r,e){return ce(r)&&r.type===e}function ce(r){return typeof r=="object"&&r!==null}function sr(r){return Array.isArray(r)}function U(r){return typeof r=="string"}function Mt(r){return typeof r=="number"}function pu(r){return r instanceof Uint8Array}function kd(r){try{return JSON.parse(r)}catch{return}}const Rs=r=>r();function Aw(r){if(r.type==="char_location"&&U(r.document_title)&&Mt(r.start_char_index)&&Mt(r.end_char_index)&&U(r.cited_text)){const{document_title:e,start_char_index:t,end_char_index:n,cited_text:s,...a}=r;return{...a,type:"citation",source:"char",title:e??void 0,startIndex:t,endIndex:n,citedText:s}}if(r.type==="page_location"&&U(r.document_title)&&Mt(r.start_page_number)&&Mt(r.end_page_number)&&U(r.cited_text)){const{document_title:e,start_page_number:t,end_page_number:n,cited_text:s,...a}=r;return{...a,type:"citation",source:"page",title:e??void 0,startIndex:t,endIndex:n,citedText:s}}if(r.type==="content_block_location"&&U(r.document_title)&&Mt(r.start_block_index)&&Mt(r.end_block_index)&&U(r.cited_text)){const{document_title:e,start_block_index:t,end_block_index:n,cited_text:s,...a}=r;return{...a,type:"citation",source:"block",title:e??void 0,startIndex:t,endIndex:n,citedText:s}}if(r.type==="web_search_result_location"&&U(r.url)&&U(r.title)&&U(r.encrypted_index)&&U(r.cited_text)){const{url:e,title:t,encrypted_index:n,cited_text:s,...a}=r;return{...a,type:"citation",source:"url",url:e,title:t,startIndex:Number(n),endIndex:Number(n),citedText:s}}if(r.type==="search_result_location"&&U(r.source)&&U(r.title)&&Mt(r.start_block_index)&&Mt(r.end_block_index)&&U(r.cited_text)){const{source:e,title:t,start_block_index:n,end_block_index:s,cited_text:a,...i}=r;return{...i,type:"citation",source:"search",url:e,title:t??void 0,startIndex:n,endIndex:s,citedText:a}}}function Bp(r){if(Q(r,"document")&&ce(r.source)&&"type"in r.source){if(r.source.type==="base64"&&U(r.source.media_type)&&U(r.source.data))return{type:"file",mimeType:r.source.media_type,data:r.source.data};if(r.source.type==="url"&&U(r.source.url))return{type:"file",url:r.source.url};if(r.source.type==="file"&&U(r.source.file_id))return{type:"file",fileId:r.source.file_id};if(r.source.type==="text"&&U(r.source.data))return{type:"file",mimeType:String(r.source.media_type??"text/plain"),data:r.source.data}}else if(Q(r,"image")&&ce(r.source)&&"type"in r.source){if(r.source.type==="base64"&&U(r.source.media_type)&&U(r.source.data))return{type:"image",mimeType:r.source.media_type,data:r.source.data};if(r.source.type==="url"&&U(r.source.url))return{type:"image",url:r.source.url};if(r.source.type==="file"&&U(r.source.file_id))return{type:"image",fileId:r.source.file_id}}}function Iw(r){function*e(){for(const t of r){const n=Bp(t);n?yield n:yield t}}return Array.from(e())}function Pd(r){function*e(){var n;const t=typeof r.content=="string"?[{type:"text",text:r.content}]:r.content;for(const s of t){if(Q(s,"text")&&U(s.text)){const{text:a,citations:i,...o}=s;if(sr(i)&&i.length){const c=i.reduce((l,u)=>{const d=Aw(u);return d?[...l,d]:l},[]);yield{...o,type:"text",text:a,annotations:c};continue}else{yield{...o,type:"text",text:a};continue}}else if(Q(s,"thinking")&&U(s.thinking)){const{thinking:a,signature:i,...o}=s;yield{...o,type:"reasoning",reasoning:a,signature:i};continue}else if(Q(s,"redacted_thinking")){yield{type:"non_standard",value:s};continue}else if(Q(s,"tool_use")&&U(s.name)&&U(s.id)){yield{type:"tool_call",id:s.id,name:s.name,args:s.input};continue}else if(Q(s,"input_json_delta")){if(Ow(r)&&((n=r.tool_call_chunks)!=null&&n.length)){const a=r.tool_call_chunks[0];yield{type:"tool_call_chunk",id:a.id,name:a.name,args:a.args,index:a.index};continue}}else if(Q(s,"server_tool_use")&&U(s.name)&&U(s.id)){const{name:a,id:i}=s;if(a==="web_search"){const o=Rs(()=>{if(typeof s.input=="string")return s.input;if(ce(s.input)&&U(s.input.query))return s.input.query;if(U(s.partial_json)){const c=kd(s.partial_json);if(c!=null&&c.query)return c.query}return""});yield{id:i,type:"server_tool_call",name:"web_search",args:{query:o}};continue}else if(s.name==="code_execution"){const o=Rs(()=>{if(typeof s.input=="string")return s.input;if(ce(s.input)&&U(s.input.code))return s.input.code;if(U(s.partial_json)){const c=kd(s.partial_json);if(c!=null&&c.code)return c.code}return""});yield{id:i,type:"server_tool_call",name:"code_execution",args:{code:o}};continue}}else if(Q(s,"web_search_tool_result")&&U(s.tool_use_id)&&sr(s.content)){const{content:a,tool_use_id:i}=s,o=a.reduce((c,l)=>Q(l,"web_search_result")?[...c,l.url]:c,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:i,status:"success",output:{urls:o}};continue}else if(Q(s,"code_execution_tool_result")&&U(s.tool_use_id)&&ce(s.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:s.tool_use_id,status:"success",output:s.content};continue}else if(Q(s,"mcp_tool_use")){yield{id:s.id,type:"server_tool_call",name:"mcp_tool_use",args:s.input};continue}else if(Q(s,"mcp_tool_result")&&U(s.tool_use_id)&&ce(s.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:s.tool_use_id,status:"success",output:s.content};continue}else if(Q(s,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:s.input};continue}else if(Q(s,"search_result")){yield{id:s.id,type:"non_standard",value:s};continue}else if(Q(s,"tool_result")){yield{id:s.id,type:"non_standard",value:s};continue}else{const a=Bp(s);if(a){yield a;continue}}yield{type:"non_standard",value:s}}}return Array.from(e())}const Rw={translateContent:Pd,translateContentChunk:Pd};function Ow(r){return typeof(r==null?void 0:r._getType)=="function"&&typeof r.concat=="function"&&r._getType()==="ai"}function $w(r){return du(r)?{type:r.type,mimeType:r.mime_type,url:r.url,metadata:r.metadata}:hu(r)?{type:r.type,mimeType:r.mime_type??"application/octet-stream",data:r.data,metadata:r.metadata}:jp(r)?{type:r.type,mimeType:r.mime_type,fileId:r.id,metadata:r.metadata}:r}function Cw(r){return r.map($w)}function kw(r){return!!(Q(r,"image_url")&&ce(r.image_url)||Q(r,"input_audio")&&ce(r.input_audio)||Q(r,"file")&&ce(r.file))}function Pw(r){if(Q(r,"image_url")&&ce(r.image_url)&&U(r.image_url.url)){const e=Zr({dataUrl:r.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:r.image_url.url}}else{if(Q(r,"input_audio")&&ce(r.input_audio)&&U(r.input_audio.data)&&U(r.input_audio.format))return{type:"audio",data:r.input_audio.data,mimeType:`audio/${r.input_audio.format}`};if(Q(r,"file")&&ce(r.file)&&U(r.file.data)){const e=Zr({dataUrl:r.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(U(r.file.file_id))return{type:"file",fileId:r.file.file_id}}}return r}function Nw(r){const e=[];typeof r.content=="string"?e.push({type:"text",text:r.content}):e.push(...mu(r.content));for(const t of r.tool_calls??[])e.push({type:"tool_call",id:t.id,name:t.name,args:t.args});return e}function Lw(r){const e=[];typeof r.content=="string"?e.push({type:"text",text:r.content}):e.push(...mu(r.content));for(const t of r.tool_calls??[])e.push({type:"tool_call",id:t.id,name:t.name,args:t.args});return e}function mu(r){const e=[];for(const t of r)kw(t)?e.push(Pw(t)):e.push(t);return e}function Mw(r){if(r.type==="url_citation"){const{url:e,title:t,start_index:n,end_index:s}=r;return{type:"citation",url:e,title:t,startIndex:n,endIndex:s}}if(r.type==="file_citation"){const{file_id:e,filename:t,index:n}=r;return{type:"citation",title:t,startIndex:n,endIndex:n,fileId:e}}return r}function qp(r){function*e(){var n;ce((n=r.additional_kwargs)==null?void 0:n.reasoning)&&sr(r.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:r.additional_kwargs.reasoning.summary.reduce((a,i)=>ce(i)&&U(i.text)?`${a}${i.text}`:a,"")});const t=typeof r.content=="string"?[{type:"text",text:r.content}]:r.content;for(const s of t)if(Q(s,"text")){const{text:a,annotations:i,...o}=s;Array.isArray(i)?yield{...o,type:"text",text:String(a),annotations:i.map(Mw)}:yield{...o,type:"text",text:String(a)}}for(const s of r.tool_calls??[])yield{type:"tool_call",id:s.id,name:s.name,args:s.args};if(ce(r.additional_kwargs)&&sr(r.additional_kwargs.tool_outputs))for(const s of r.additional_kwargs.tool_outputs){if(Q(s,"web_search_call")){yield{id:s.id,type:"server_tool_call",name:"web_search",args:{query:s.query}};continue}else if(Q(s,"file_search_call")){yield{id:s.id,type:"server_tool_call",name:"file_search",args:{query:s.query}};continue}else if(Q(s,"computer_call")){yield{type:"non_standard",value:s};continue}else if(Q(s,"code_interpreter_call")){if(U(s.code)&&(yield{id:s.id,type:"server_tool_call",name:"code_interpreter",args:{code:s.code}}),sr(s.outputs)){const a=Rs(()=>{if(s.status!=="in_progress"){if(s.status==="completed")return 0;if(s.status==="incomplete")return 127;if(s.status!=="interpreting"&&s.status==="failed")return 1}});for(const i of s.outputs)if(Q(i,"logs")){yield{type:"server_tool_call_result",toolCallId:s.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:a??0,stderr:[0,void 0].includes(a)?void 0:String(i.logs),stdout:[0,void 0].includes(a)?String(i.logs):void 0}};continue}}continue}else if(Q(s,"mcp_call")){yield{id:s.id,type:"server_tool_call",name:"mcp_call",args:s.input};continue}else if(Q(s,"mcp_list_tools")){yield{id:s.id,type:"server_tool_call",name:"mcp_list_tools",args:s.input};continue}else if(Q(s,"mcp_approval_request")){yield{type:"non_standard",value:s};continue}else if(Q(s,"image_generation_call")){yield{type:"non_standard",value:s};continue}ce(s)&&(yield{type:"non_standard",value:s})}}return Array.from(e())}function jw(r){function*e(){yield*qp(r);for(const t of r.tool_call_chunks??[])yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args}}return Array.from(e())}const Dw={translateContent:r=>typeof r.content=="string"?Nw(r):qp(r),translateContentChunk:r=>typeof r.content=="string"?Lw(r):jw(r)},Io=Symbol.for("langchain.message");function Qr(r,e){return typeof r=="string"?r===""?e:typeof e=="string"?r+e:Array.isArray(e)&&e.some(t=>Wt(t))?[{type:"text",source_type:"text",text:r},...e]:[{type:"text",text:r},...e]:Array.isArray(e)?Us(r,e)??[...r,...e]:e===""?r:Array.isArray(r)&&r.some(t=>Wt(t))?[...r,{type:"file",source_type:"text",text:e}]:[...r,{type:"text",text:e}]}function zp(r,e){return r==="error"||e==="error"?"error":"success"}function Uw(r,e){function t(n,s){if(typeof n!="object"||n===null||n===void 0)return n;if(s>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(i=>t(i,s+1));const a={};for(const i of Object.keys(n))a[i]=t(n[i],s+1);return a}return JSON.stringify(t(r,0),null,2)}var Mp,br=class extends Rn{constructor(e){const t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={});super(t);w(this,"lc_namespace",["langchain_core","messages"]);w(this,"lc_serializable",!0);w(this,Mp,!0);w(this,"id");w(this,"name");w(this,"content");w(this,"additional_kwargs");w(this,"response_metadata");this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}_getType(){return this.type}getType(){return this._getType()}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){const e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Cw,mu,Iw].reduce((s,a)=>a(s),e)}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(e){return typeof e=="object"&&e!==null&&Io in e&&e[Io]===!0&&Up(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(Mp=Io,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=Uw(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}};function Fw(r){return Array.isArray(r)&&r.every(e=>typeof e.index=="number")}function Ze(r={},e={}){const t={...r};for(const[n,s]of Object.entries(e))if(t[n]==null)t[n]=s;else{if(s==null)continue;if(typeof t[n]!=typeof s||Array.isArray(t[n])!==Array.isArray(s))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof t[n]=="string"){if(n==="type")continue;["id","name","output_version","model_provider"].includes(n)?t[n]=s:t[n]+=s}else if(typeof t[n]=="object"&&!Array.isArray(t[n]))t[n]=Ze(t[n],s);else if(Array.isArray(t[n]))t[n]=Us(t[n],s);else{if(t[n]===s)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return t}function Us(r,e){if(!(r===void 0&&e===void 0)){if(r===void 0||e===void 0)return r||e;{const t=[...r];for(const n of e)if(typeof n=="object"&&n!==null&&"index"in n&&typeof n.index=="number"){const s=t.findIndex(a=>{const i=typeof a=="object",o="index"in a&&a.index===n.index,c="id"in a&&"id"in n&&(a==null?void 0:a.id)===(n==null?void 0:n.id),l=!("id"in a)||!(a!=null&&a.id)||!("id"in n)||!(n!=null&&n.id);return i&&o&&(c||l)});s!==-1&&typeof t[s]=="object"&&t[s]!==null?t[s]=Ze(t[s],n):t.push(n)}else{if(typeof n=="object"&&n!==null&&"text"in n&&n.text==="")continue;t.push(n)}return t}}}function Hp(r,e){if(!r&&!e)throw new Error("Cannot merge two undefined objects.");if(!r||!e)return r||e;if(typeof r!=typeof e)throw new Error(`Cannot merge objects of different types.
2
+ Left ${typeof r}
3
+ Right ${typeof e}`);if(typeof r=="string"&&typeof e=="string")return r+e;if(Array.isArray(r)&&Array.isArray(e))return Us(r,e);if(typeof r=="object"&&typeof e=="object")return Ze(r,e);if(r===e)return r;throw new Error(`Can not merge objects of different types.
4
+ Left ${r}
5
+ Right ${e}`)}var en=class extends br{static isInstance(r){return super.isInstance(r)&&"concat"in r&&typeof r.concat=="function"}};function Wp(r){return typeof r.role=="string"}function pr(r){return typeof(r==null?void 0:r._getType)=="function"}function gu(r){return pr(r)&&typeof r.concat=="function"}function Gp(r,e){return Ze(r??{},e??{})}function Jp(r,e){const t={};return((r==null?void 0:r.audio)!==void 0||(e==null?void 0:e.audio)!==void 0)&&(t.audio=((r==null?void 0:r.audio)??0)+((e==null?void 0:e.audio)??0)),((r==null?void 0:r.image)!==void 0||(e==null?void 0:e.image)!==void 0)&&(t.image=((r==null?void 0:r.image)??0)+((e==null?void 0:e.image)??0)),((r==null?void 0:r.video)!==void 0||(e==null?void 0:e.video)!==void 0)&&(t.video=((r==null?void 0:r.video)??0)+((e==null?void 0:e.video)??0)),((r==null?void 0:r.document)!==void 0||(e==null?void 0:e.document)!==void 0)&&(t.document=((r==null?void 0:r.document)??0)+((e==null?void 0:e.document)??0)),((r==null?void 0:r.text)!==void 0||(e==null?void 0:e.text)!==void 0)&&(t.text=((r==null?void 0:r.text)??0)+((e==null?void 0:e.text)??0)),t}function Bw(r,e){const t={...Jp(r,e)};return((r==null?void 0:r.cache_read)!==void 0||(e==null?void 0:e.cache_read)!==void 0)&&(t.cache_read=((r==null?void 0:r.cache_read)??0)+((e==null?void 0:e.cache_read)??0)),((r==null?void 0:r.cache_creation)!==void 0||(e==null?void 0:e.cache_creation)!==void 0)&&(t.cache_creation=((r==null?void 0:r.cache_creation)??0)+((e==null?void 0:e.cache_creation)??0)),t}function qw(r,e){const t={...Jp(r,e)};return((r==null?void 0:r.reasoning)!==void 0||(e==null?void 0:e.reasoning)!==void 0)&&(t.reasoning=((r==null?void 0:r.reasoning)??0)+((e==null?void 0:e.reasoning)??0)),t}function Vp(r,e){return{input_tokens:((r==null?void 0:r.input_tokens)??0)+((e==null?void 0:e.input_tokens)??0),output_tokens:((r==null?void 0:r.output_tokens)??0)+((e==null?void 0:e.output_tokens)??0),total_tokens:((r==null?void 0:r.total_tokens)??0)+((e==null?void 0:e.total_tokens)??0),input_token_details:Bw(r==null?void 0:r.input_token_details,e==null?void 0:e.input_token_details),output_token_details:qw(r==null?void 0:r.output_token_details,e==null?void 0:e.output_token_details)}}var zw={};pe(zw,{ToolMessage:()=>gr,ToolMessageChunk:()=>Fs,defaultToolCallParser:()=>yu,isDirectToolOutput:()=>_u,isToolMessage:()=>Kp,isToolMessageChunk:()=>Zp});function _u(r){return r!=null&&typeof r=="object"&&"lc_direct_tool_output"in r&&r.lc_direct_tool_output===!0}var gr=class extends br{constructor(e,t,n){const s=typeof e=="string"||Array.isArray(e)?{content:e,name:n,tool_call_id:t}:e;super(s);w(this,"lc_direct_tool_output",!0);w(this,"type","tool");w(this,"status");w(this,"tool_call_id");w(this,"metadata");w(this,"artifact");this.tool_call_id=s.tool_call_id,this.artifact=s.artifact,this.status=s.status,this.metadata=s.metadata}static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Fs=class extends en{constructor(e){super(e);w(this,"type","tool");w(this,"tool_call_id");w(this,"status");w(this,"artifact");this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){const t=this.constructor;return new t({content:Qr(this.content,e.content),additional_kwargs:Ze(this.additional_kwargs,e.additional_kwargs),response_metadata:Ze(this.response_metadata,e.response_metadata),artifact:Hp(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:zp(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function yu(r){const e=[],t=[];for(const n of r)if(n.function){const s=n.function.name;try{const a=JSON.parse(n.function.arguments);e.push({name:s||"",args:a||{},id:n.id})}catch{t.push({name:s,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,t]}function Kp(r){return typeof r=="object"&&r!==null&&"getType"in r&&typeof r.getType=="function"&&r.getType()==="tool"}function Zp(r){return r._getType()==="tool"}function gl(r,e=Bi){r=r.trim();const t=r.indexOf("```");if(t===-1)return e(r);let n=r.substring(t+3);n.startsWith(`json
6
+ `)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
7
+ `)&&(n=n.substring(1));const s=n.indexOf("```");let a=n;return s!==-1&&(a=n.substring(0,s)),e(a.trim())}function Bi(r){if(typeof r>"u")return null;try{return JSON.parse(r)}catch{}let e="";const t=[];let n=!1,s=!1;for(let a of r){if(n)a==='"'&&!s?n=!1:a===`
8
+ `&&!s?a="\\n":a==="\\"?s=!s:s=!1;else if(a==='"')n=!0,s=!1;else if(a==="{")t.push("}");else if(a==="[")t.push("]");else if(a==="}"||a==="]")if(t&&t[t.length-1]===a)t.pop();else return null;e+=a}n&&(e+='"');for(let a=t.length-1;a>=0;a-=1)e+=t[a];try{return JSON.parse(e)}catch{return null}}function wu(r){switch(r){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 Hw(r){if(ce(r.document)&&ce(r.document.source)){const e=ce(r.document)&&U(r.document.format)?r.document.format:"",t=wu(e);if(ce(r.document.source)){if(ce(r.document.source.s3Location)&&U(r.document.source.s3Location.uri))return{type:"file",mimeType:t,fileId:r.document.source.s3Location.uri};if(pu(r.document.source.bytes))return{type:"file",mimeType:t,data:r.document.source.bytes};if(U(r.document.source.text))return{type:"file",mimeType:t,data:Buffer.from(r.document.source.text).toString("base64")};if(sr(r.document.source.content)){const n=r.document.source.content.reduce((s,a)=>ce(a)&&U(a.text)?s+a.text:s,"");return{type:"file",mimeType:t,data:n}}}}return{type:"non_standard",value:r}}function Ww(r){if(Q(r,"image")&&ce(r.image)){const e=ce(r.image)&&U(r.image.format)?r.image.format:"",t=wu(e);if(ce(r.image.source)){if(ce(r.image.source.s3Location)&&U(r.image.source.s3Location.uri))return{type:"image",mimeType:t,fileId:r.image.source.s3Location.uri};if(pu(r.image.source.bytes))return{type:"image",mimeType:t,data:r.image.source.bytes}}}return{type:"non_standard",value:r}}function Gw(r){if(Q(r,"video")&&ce(r.video)){const e=ce(r.video)&&U(r.video.format)?r.video.format:"",t=wu(e);if(ce(r.video.source)){if(ce(r.video.source.s3Location)&&U(r.video.source.s3Location.uri))return{type:"video",mimeType:t,fileId:r.video.source.s3Location.uri};if(pu(r.video.source.bytes))return{type:"video",mimeType:t,data:r.video.source.bytes}}}return{type:"non_standard",value:r}}function Nd(r){function*e(){const t=typeof r.content=="string"?[{type:"text",text:r.content}]:r.content;for(const n of t){if(Q(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(Q(n,"citations_content")&&ce(n.citationsContent)){const s=sr(n.citationsContent.content)?n.citationsContent.content.reduce((i,o)=>ce(o)&&U(o.text)?i+o.text:i,""):"",a=sr(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,o)=>{if(ce(o)){const c=sr(o.sourceContent)?o.sourceContent.reduce((u,d)=>ce(d)&&U(d.text)?u+d.text:u,""):"",l=Rs(()=>{if(ce(o.location)){const u=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(ce(u))return{source:Mt(u.documentIndex)?u.documentIndex.toString():void 0,startIndex:Mt(u.start)?u.start:void 0,endIndex:Mt(u.end)?u.end:void 0}}return{}});i.push({type:"citation",citedText:c,...l})}return i},[]):[];yield{type:"text",text:s,annotations:a};continue}else if(Q(n,"document")&&ce(n.document)){yield Hw(n);continue}else if(Q(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(Q(n,"image")&&ce(n.image)){yield Ww(n);continue}else if(Q(n,"reasoning_content")&&U(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(Q(n,"text")&&U(n.text)){yield{type:"text",text:n.text};continue}else if(Q(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(Q(n,"tool_call"))continue;if(Q(n,"video")&&ce(n.video)){yield Gw(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const Jw={translateContent:Nd,translateContentChunk:Nd};function Ld(r){function*e(){const t=typeof r.content=="string"?[{type:"text",text:r.content}]:r.content;for(const n of t){if(Q(n,"text")&&U(n.text)){yield{type:"text",text:n.text};continue}else if(Q(n,"inlineData")&&ce(n.inlineData)&&U(n.inlineData.mimeType)&&U(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(Q(n,"functionCall")&&ce(n.functionCall)&&U(n.functionCall.name)&&ce(n.functionCall.args)){yield{type:"tool_call",id:r.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(Q(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(Q(n,"fileData")&&ce(n.fileData)&&U(n.fileData.mimeType)&&U(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(Q(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(Q(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const Vw={translateContent:Ld,translateContentChunk:Ld};function Md(r){function*e(){const t=typeof r.content=="string"?[{type:"text",text:r.content}]:r.content;for(const n of t){if(Q(n,"reasoning")&&U(n.reasoning)){const s=Rs(()=>{var i;const a=t.indexOf(n);if(sr((i=r.additional_kwargs)==null?void 0:i.signatures)&&a>=0)return r.additional_kwargs.signatures.at(a)});U(s)?yield{type:"reasoning",reasoning:n.reasoning,signature:s}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(Q(n,"text")&&U(n.text)){yield{type:"text",text:n.text};continue}else if(Q(n,"image_url")){if(U(n.image_url))if(n.image_url.startsWith("data:")){const s=/^data:([^;]+);base64,(.+)$/,a=n.image_url.match(s);a?yield{type:"image",data:a[2],mimeType:a[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(Q(n,"media")&&U(n.mimeType)&&U(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const Kw={translateContent:Md,translateContentChunk:Md};globalThis.lc_block_translators_registry??(globalThis.lc_block_translators_registry=new Map([["anthropic",Rw],["bedrock-converse",Jw],["google-genai",Vw],["google-vertexai",Kw],["openai",Dw]]));function Xp(r){return globalThis.lc_block_translators_registry.get(r)}var St=class extends br{constructor(e){var n;let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;const s=(n=t.additional_kwargs)==null?void 0:n.tool_calls,a=t.tool_calls;s!=null&&s.length>0&&(a===void 0||a.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
9
+
10
+ Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(s!=null&&a===void 0){const[i,o]=yu(s);t.tool_calls=i??[],t.invalid_tool_calls=o??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(t.response_metadata!==void 0&&"output_version"in t.response_metadata&&t.response_metadata.output_version==="v1"&&(t.contentBlocks=t.content,t.content=void 0),t.contentBlocks!==void 0){t.contentBlocks.push(...t.tool_calls.map(o=>({type:"tool_call",id:o.id,name:o.name,args:o.args})));const i=t.contentBlocks.filter(o=>o.type==="tool_call").filter(o=>{var c;return!((c=t.tool_calls)!=null&&c.some(l=>l.id===o.id&&l.name===o.name))});i.length>0&&(t.tool_calls=i.map(o=>({type:"tool_call",id:o.id,name:o.name,args:o.args})))}}super(t);w(this,"type","ai");w(this,"tool_calls",[]);w(this,"invalid_tool_calls",[]);w(this,"usage_metadata");typeof t!="string"&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}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 t=Xp(this.response_metadata.model_provider);if(t)return t.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls){const t=this.tool_calls.filter(n=>!e.some(s=>s.id===n.id&&s.name===n.name));e.push(...t.map(n=>({...n,type:"tool_call",id:n.id,name:n.name,args:n.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};function _r(r){return r._getType()==="ai"}function _l(r){return r._getType()==="ai"}var ke=class extends en{constructor(e){var n,s;let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const a=e.tool_call_chunks.reduce((c,l)=>{const u=c.findIndex(([d])=>"id"in l&&l.id&&"index"in l&&l.index!==void 0?l.id===d.id&&l.index===d.index:"id"in l&&l.id?l.id===d.id:"index"in l&&l.index!==void 0?l.index===d.index:!1);return u!==-1?c[u].push(l):c.push([l]),c},[]),i=[],o=[];for(const c of a){let l=null;const u=((n=c[0])==null?void 0:n.name)??"",d=c.map(p=>p.args||"").join(""),h=d.length?d:"{}",f=(s=c[0])==null?void 0:s.id;try{if(l=Bi(h),!f||l===null||typeof l!="object"||Array.isArray(l))throw new Error("Malformed tool call chunk args.");i.push({name:u,args:l,id:f,type:"tool_call"})}catch{o.push({name:u,args:h,id:f,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:i,invalid_tool_calls:o,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t);w(this,"type","ai");w(this,"tool_calls",[]);w(this,"invalid_tool_calls",[]);w(this,"tool_call_chunks",[]);w(this,"usage_metadata");this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}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 t=Xp(this.response_metadata.model_provider);if(t)return t.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const t=this.content.filter(n=>n.type==="tool_call").map(n=>n.id);for(const n of this.tool_calls)n.id&&!t.includes(n.id)&&e.push({...n,type:"tool_call",id:n.id,name:n.name,args:n.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const t={content:Qr(this.content,e.content),additional_kwargs:Ze(this.additional_kwargs,e.additional_kwargs),response_metadata:Gp(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const s=Us(this.tool_call_chunks,e.tool_call_chunks);s!==void 0&&s.length>0&&(t.tool_call_chunks=s)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(t.usage_metadata=Vp(this.usage_metadata,e.usage_metadata));const n=this.constructor;return new n(t)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}},tn=class Yp extends br{constructor(t,n){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:n});super(t);w(this,"type","generic");w(this,"role");this.role=t.role}static lc_name(){return"ChatMessage"}static _chatMessageClass(){return Yp}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Bs=class extends en{constructor(e,t){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:t});super(e);w(this,"type","generic");w(this,"role");this.role=e.role}static lc_name(){return"ChatMessageChunk"}concat(e){const t=this.constructor;return new t({content:Qr(this.content,e.content),additional_kwargs:Ze(this.additional_kwargs,e.additional_kwargs),response_metadata:Ze(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function Zw(r){return r._getType()==="generic"}function Xw(r){return r._getType()==="generic"}var qi=class extends br{constructor(e){super(e);w(this,"type","function");w(this,"name");this.name=e.name}static lc_name(){return"FunctionMessage"}},qs=class extends en{constructor(){super(...arguments);w(this,"type","function")}static lc_name(){return"FunctionMessageChunk"}concat(e){const t=this.constructor;return new t({content:Qr(this.content,e.content),additional_kwargs:Ze(this.additional_kwargs,e.additional_kwargs),response_metadata:Ze(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function Yw(r){return r._getType()==="function"}function Qw(r){return r._getType()==="function"}var Gt=class extends br{constructor(e){super(e);w(this,"type","human")}static lc_name(){return"HumanMessage"}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},zs=class extends en{constructor(e){super(e);w(this,"type","human")}static lc_name(){return"HumanMessageChunk"}concat(e){const t=this.constructor;return new t({content:Qr(this.content,e.content),additional_kwargs:Ze(this.additional_kwargs,e.additional_kwargs),response_metadata:Ze(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}};function eb(r){return r.getType()==="human"}function tb(r){return r.getType()==="human"}var kr=class extends br{constructor(e){super(e);w(this,"type","system")}static lc_name(){return"SystemMessage"}static isInstance(e){return super.isInstance(e)&&e.type==="system"}},Pr=class extends en{constructor(e){super(e);w(this,"type","system")}static lc_name(){return"SystemMessageChunk"}concat(e){const t=this.constructor;return new t({content:Qr(this.content,e.content),additional_kwargs:Ze(this.additional_kwargs,e.additional_kwargs),response_metadata:Ze(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function rb(r){return r._getType()==="system"}function nb(r){return r._getType()==="system"}var oi=class extends br{constructor(e){super({...e,content:[]});w(this,"type","remove");w(this,"id");this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}};function Qp(r,e){return r.lc_error_code=e,r.message=`${r.message}
11
+
12
+ Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
13
+ `,r}function ws(r){return!!(r&&typeof r=="object"&&"type"in r&&r.type==="tool_call")}function sb(r){return!!(r&&typeof r=="object"&&"toolCall"in r&&r.toolCall!=null&&typeof r.toolCall=="object"&&"id"in r.toolCall&&typeof r.toolCall.id=="string")}var ci=class extends Error{constructor(e,t){super(e);w(this,"output");this.output=t}};const ab=r=>r();function ib(r){return ws(r)?r:typeof r.id=="string"&&r.type==="function"&&typeof r.function=="object"&&r.function!==null&&"arguments"in r.function&&typeof r.function.arguments=="string"&&"name"in r.function&&typeof r.function.name=="string"?{id:r.id,args:JSON.parse(r.function.arguments),name:r.function.name,type:"tool_call"}:r}function ob(r){return typeof r=="object"&&r!=null&&r.lc===1&&Array.isArray(r.id)&&r.kwargs!=null&&typeof r.kwargs=="object"}function Ro(r){let e,t;if(ob(r)){const n=r.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?e="user":n==="AIMessage"||n==="AIMessageChunk"?e="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?e="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?e="function":n==="ToolMessage"||n==="ToolMessageChunk"?e="tool":e="unknown",t=r.kwargs}else{const{type:n,...s}=r;e=n,t=s}if(e==="human"||e==="user")return new Gt(t);if(e==="ai"||e==="assistant"){const{tool_calls:n,...s}=t;if(!Array.isArray(n))return new St(t);const a=n.map(ib);return new St({...s,tool_calls:a})}else{if(e==="system")return new kr(t);if(e==="developer")return new kr({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in t)return new gr({...t,content:t.content,tool_call_id:t.tool_call_id,name:t.name});if(e==="remove"&&"id"in t&&typeof t.id=="string")return new oi({...t,id:t.id});throw Qp(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
14
+
15
+ Received: ${JSON.stringify(r,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function bs(r){if(typeof r=="string")return new Gt(r);if(pr(r))return r;if(Array.isArray(r)){const[e,t]=r;return Ro({type:e,content:t})}else if(Wp(r)){const{role:e,...t}=r;return Ro({...t,type:e})}else return Ro(r)}function bu(r,e="Human",t="AI"){const n=[];for(const s of r){let a;if(s._getType()==="human")a=e;else if(s._getType()==="ai")a=t;else if(s._getType()==="system")a="System";else if(s._getType()==="tool")a="Tool";else if(s._getType()==="generic")a=s.role;else throw new Error(`Got unsupported message type: ${s._getType()}`);const i=s.name?`${s.name}, `:"",o=typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2);n.push(`${a}: ${i}${o}`)}return n.join(`
16
+ `)}function cb(r){if(r.data!==void 0)return r;{const e=r;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function vu(r){const e=cb(r);switch(e.type){case"human":return new Gt(e.data);case"ai":return new St(e.data);case"system":return new kr(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new qi(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 gr(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new tn(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function lb(r){return r.map(vu)}function ub(r){return r.map(e=>e.toDict())}function li(r){var t;const e=r._getType();if(e==="human")return new zs({...r});if(e==="ai"){let n={...r};return"tool_calls"in n&&(n={...n,tool_call_chunks:(t=n.tool_calls)==null?void 0:t.map(s=>({...s,type:"tool_call_chunk",index:void 0,args:JSON.stringify(s.args)}))}),new ke({...n})}else{if(e==="system")return new Pr({...r});if(e==="function")return new qs({...r});if(tn.isInstance(r))return new Bs({...r});throw new Error("Unknown message type.")}}const em=Symbol.for("ls:tracing_async_local_storage"),vs=Symbol.for("lc:context_variables"),db=r=>{globalThis[em]=r},Os=()=>globalThis[em];var Oo={},hb={};pe(hb,{getEnv:()=>am,getEnvironmentVariable:()=>qt,getRuntimeEnvironment:()=>im,isBrowser:()=>tm,isDeno:()=>zi,isJsDom:()=>nm,isNode:()=>sm,isWebWorker:()=>rm});const tm=()=>typeof window<"u"&&typeof window.document<"u",rm=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",nm=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),zi=()=>typeof Deno<"u",sm=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!zi(),am=()=>{let r;return tm()?r="browser":sm()?r="node":rm()?r="webworker":nm()?r="jsdom":zi()?r="deno":r="other",r};let $o;function im(){return $o===void 0&&($o={library:"langchain-js",runtime:am()}),$o}function qt(r){try{return typeof process<"u"?Oo==null?void 0:Oo[r]:zi()?Deno==null?void 0:Deno.env.get(r):void 0}catch{return}}const fb=/^(?:[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 Ja(r){return typeof r=="string"&&fb.test(r)}var Ge=[];for(var Co=0;Co<256;++Co)Ge.push((Co+256).toString(16).slice(1));function pb(r,e=0){return(Ge[r[e+0]]+Ge[r[e+1]]+Ge[r[e+2]]+Ge[r[e+3]]+"-"+Ge[r[e+4]]+Ge[r[e+5]]+"-"+Ge[r[e+6]]+Ge[r[e+7]]+"-"+Ge[r[e+8]]+Ge[r[e+9]]+"-"+Ge[r[e+10]]+Ge[r[e+11]]+Ge[r[e+12]]+Ge[r[e+13]]+Ge[r[e+14]]+Ge[r[e+15]]).toLowerCase()}var la,mb=new Uint8Array(16);function gb(){if(!la&&(la=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!la))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return la(mb)}var _b=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const jd={randomUUID:_b};function dr(r,e,t){if(jd.randomUUID&&!r)return jd.randomUUID();r=r||{};var n=r.random||(r.rng||gb)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,pb(n)}var yb={};pe(yb,{BaseCallbackHandler:()=>Hs,callbackHandlerPrefersStreaming:()=>Su,isBaseCallbackHandler:()=>om});var wb=class{};function Su(r){return"lc_prefer_streaming"in r&&r.lc_prefer_streaming}var Hs=class extends wb{constructor(e){super();w(this,"lc_serializable",!1);w(this,"lc_kwargs");w(this,"ignoreLLM",!1);w(this,"ignoreChain",!1);w(this,"ignoreAgent",!1);w(this,"ignoreRetriever",!1);w(this,"ignoreCustomEvent",!1);w(this,"raiseError",!1);w(this,"awaitHandlers",qt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false");this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}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,fu(this.constructor)]}copy(){return new this.constructor(this)}toJSON(){return Rn.prototype.toJSON.call(this)}toJSONNotImplemented(){return Rn.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends Hs{constructor(){super();w(this,"name",dr());Object.assign(this,e)}}return new t}};const om=r=>{const e=r;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},bb=/^(?:[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 vb(r){return typeof r=="string"&&bb.test(r)}function Sb(r){if(!vb(r))throw TypeError("Invalid UUID");var e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var Je=[];for(var ko=0;ko<256;++ko)Je.push((ko+256).toString(16).slice(1));function cm(r,e=0){return(Je[r[e+0]]+Je[r[e+1]]+Je[r[e+2]]+Je[r[e+3]]+"-"+Je[r[e+4]]+Je[r[e+5]]+"-"+Je[r[e+6]]+Je[r[e+7]]+"-"+Je[r[e+8]]+Je[r[e+9]]+"-"+Je[r[e+10]]+Je[r[e+11]]+Je[r[e+12]]+Je[r[e+13]]+Je[r[e+14]]+Je[r[e+15]]).toLowerCase()}var ua,Eb=new Uint8Array(16);function Tb(){if(!ua&&(ua=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ua))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ua(Eb)}function xb(r){r=unescape(encodeURIComponent(r));for(var e=[],t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var Ab="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Ib="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Rb(r,e,t){function n(s,a,i,o){var c;if(typeof s=="string"&&(s=xb(s)),typeof a=="string"&&(a=Sb(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 l=new Uint8Array(16+s.length);if(l.set(a),l.set(s,a.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,i){o=o||0;for(var u=0;u<16;++u)i[o+u]=l[u];return i}return cm(l)}try{n.name=r}catch{}return n.DNS=Ab,n.URL=Ib,n}var Ob=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Dd={randomUUID:Ob};function pn(r,e,t){if(Dd.randomUUID&&!r)return Dd.randomUUID();r=r||{};var n=r.random||(r.rng||Tb)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,cm(n)}function $b(r,e,t,n){switch(r){case 0:return e&t^~e&n;case 1:return e^t^n;case 2:return e&t^e&n^t&n;case 3:return e^t^n}}function Po(r,e){return r<<e|r>>>32-e}function Cb(r){var e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof r=="string"){var n=unescape(encodeURIComponent(r));r=[];for(var s=0;s<n.length;++s)r.push(n.charCodeAt(s))}else Array.isArray(r)||(r=Array.prototype.slice.call(r));r.push(128);for(var a=r.length/4+2,i=Math.ceil(a/16),o=new Array(i),c=0;c<i;++c){for(var l=new Uint32Array(16),u=0;u<16;++u)l[u]=r[c*64+u*4]<<24|r[c*64+u*4+1]<<16|r[c*64+u*4+2]<<8|r[c*64+u*4+3];o[c]=l}o[i-1][14]=(r.length-1)*8/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=(r.length-1)*8&4294967295;for(var d=0;d<i;++d){for(var h=new Uint32Array(80),f=0;f<16;++f)h[f]=o[d][f];for(var p=16;p<80;++p)h[p]=Po(h[p-3]^h[p-8]^h[p-14]^h[p-16],1);for(var g=t[0],_=t[1],b=t[2],m=t[3],y=t[4],T=0;T<80;++T){var x=Math.floor(T/20),R=Po(g,5)+$b(x,_,b,m)+y+e[x]+h[T]>>>0;y=m,m=b,b=Po(_,30)>>>0,_=g,g=R}t[0]=t[0]+g>>>0,t[1]=t[1]+_>>>0,t[2]=t[2]+b>>>0,t[3]=t[3]+m>>>0,t[4]=t[4]+y>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}var Ud=Rb("v5",80,Cb);const kb="gen_ai.operation.name",Pb="gen_ai.system",Fd="gen_ai.request.model",Nb="gen_ai.response.model",Bd="gen_ai.usage.input_tokens",qd="gen_ai.usage.output_tokens",zd="gen_ai.usage.total_tokens",Lb="gen_ai.request.max_tokens",Mb="gen_ai.request.temperature",jb="gen_ai.request.top_p",Db="gen_ai.request.frequency_penalty",Ub="gen_ai.request.presence_penalty",Fb="gen_ai.response.finish_reasons",Bb="gen_ai.prompt",qb="gen_ai.completion",zb="gen_ai.request.extra_query",Hb="gen_ai.request.extra_body",Wb="gen_ai.serialized.name",Gb="gen_ai.serialized.signature",Jb="gen_ai.serialized.doc",Vb="gen_ai.response.id",Kb="gen_ai.response.service_tier",Zb="gen_ai.response.system_fingerprint",Xb="gen_ai.usage.input_token_details",Yb="gen_ai.usage.output_token_details",Qb="langsmith.trace.session_id",ev="langsmith.trace.session_name",tv="langsmith.span.kind",rv="langsmith.trace.name",nv="langsmith.metadata",Hd="langsmith.span.tags",sv="langsmith.request.streaming",av="langsmith.request.headers",iv=(...r)=>fetch(...r),lm=Symbol.for("ls:fetch_implementation"),ov=()=>{const r=globalThis[lm];return r?typeof r=="function"&&"Headers"in r&&"Request"in r&&"Response"in r:!1},cv=r=>async(...e)=>{if(r||ct("DEBUG")==="true"){const[n,s]=e;console.log(`→ ${(s==null?void 0:s.method)||"GET"} ${n}`)}const t=await(globalThis[lm]??iv)(...e);return(r||ct("DEBUG")==="true")&&console.log(`← ${t.status} ${t.statusText} ${t.url}`),t},um=()=>ct("PROJECT")??ir("LANGCHAIN_SESSION")??"default",dm="0.3.73";var Ss={};let Yt;const lv=()=>typeof window<"u"&&typeof window.document<"u",uv=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",dv=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),hm=()=>typeof Deno<"u",hv=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!hm(),fm=()=>Yt||(typeof Bun<"u"?Yt="bun":lv()?Yt="browser":hv()?Yt="node":uv()?Yt="webworker":dv()?Yt="jsdom":hm()?Yt="deno":Yt="other",Yt);let No;function pm(){if(No===void 0){const r=fm(),e=pv();No={library:"langsmith",runtime:r,sdk:"langsmith-js",sdk_version:dm,...e}}return No}function mm(){const r=fv(),e={},t=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[n,s]of Object.entries(r))typeof s=="string"&&!t.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[n]=s);return e}function fv(){const r={};try{if(typeof process<"u"&&Ss)for(const[e,t]of Object.entries(Ss))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&t!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof t=="string"?r[e]=t.slice(0,2)+"*".repeat(t.length-4)+t.slice(-2):r[e]=t)}catch{}return r}function ir(r){try{return typeof process<"u"?Ss==null?void 0:Ss[r]:void 0}catch{return}}function ct(r){return ir(`LANGSMITH_${r}`)||ir(`LANGCHAIN_${r}`)}let Lo;function pv(){if(Lo!==void 0)return Lo;const r=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const t of r){const n=ir(t);n!==void 0&&(e[t]=n)}return Lo=e,e}function gm(){return ir("OTEL_ENABLED")==="true"||ct("OTEL_ENABLED")==="true"}class mv{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&gm()&&(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 n;if(t.length===1&&typeof t[0]=="function"?n=t[0]:t.length===2&&typeof t[1]=="function"?n=t[1]:t.length===3&&typeof t[2]=="function"&&(n=t[2]),typeof n=="function")return n()}}class gv{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new mv})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class _v{active(){return{}}with(e,t){return t()}}const Mo=Symbol.for("ls:otel_trace"),jo=Symbol.for("ls:otel_context"),Wd=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),yv=new gv,wv=new _v;class bv{getTraceInstance(){return globalThis[Mo]??yv}getContextInstance(){return globalThis[jo]??wv}initializeGlobalInstances(e){globalThis[Mo]===void 0&&(globalThis[Mo]=e.trace),globalThis[jo]===void 0&&(globalThis[jo]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Wd]=e}getDefaultOTLPTracerComponents(){return globalThis[Wd]??void 0}}const Eu=new bv;function _m(){return Eu.getTraceInstance()}function vv(){return Eu.getContextInstance()}function Sv(){return Eu.getDefaultOTLPTracerComponents()}const Ev={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Tv(r){return Ev[r]||r}class xv{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(const n of e)try{if(!n.run)continue;if(n.operation==="post"){const s=this.createSpanForRun(n,n.run,t.get(n.id));s&&!n.run.end_time&&this.spans.set(n.id,s)}else this.updateSpanForRun(n,n.run)}catch(s){console.error(`Error processing operation ${n.id}:`,s)}}createSpanForRun(e,t,n){const s=n&&_m().getSpan(n);if(s)try{return this.finishSpanSetup(s,t,e)}catch(a){console.error(`Failed to create span for run ${e.id}:`,a);return}}finishSpanSetup(e,t,n){return this.setSpanAttributes(e,t,n),t.error?(e.setStatus({code:2}),e.recordException(new Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{const n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,t,e),t.error?(n.setStatus({code:2}),n.recordException(new Error(t.error))):n.setStatus({code:1});const s=t.end_time;s&&(n.end(new Date(s)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){var t;if((t=e.extra)!=null&&t.metadata){const n=e.extra.metadata;if(n.ls_model_name)return n.ls_model_name;if(n.invocation_params){const s=n.invocation_params;if(s.model)return s.model;if(s.model_name)return s.model_name}}}setSpanAttributes(e,t,n){var o;if("run_type"in t&&t.run_type){e.setAttribute(tv,t.run_type);const c=Tv(t.run_type||"chain");e.setAttribute(kb,c)}"name"in t&&t.name&&e.setAttribute(rv,t.name),"session_id"in t&&t.session_id&&e.setAttribute(Qb,t.session_id),"session_name"in t&&t.session_name&&e.setAttribute(ev,t.session_name),this.setGenAiSystem(e,t);const s=this.extractModelName(t);s&&e.setAttribute(Fd,s),"prompt_tokens"in t&&typeof t.prompt_tokens=="number"&&e.setAttribute(Bd,t.prompt_tokens),"completion_tokens"in t&&typeof t.completion_tokens=="number"&&e.setAttribute(qd,t.completion_tokens),"total_tokens"in t&&typeof t.total_tokens=="number"&&e.setAttribute(zd,t.total_tokens),this.setInvocationParameters(e,t);const a=((o=t.extra)==null?void 0:o.metadata)||{};for(const[c,l]of Object.entries(a))l!=null&&e.setAttribute(`${nv}.${c}`,String(l));const i=t.tags;if(i&&Array.isArray(i)?e.setAttribute(Hd,i.join(", ")):i&&e.setAttribute(Hd,String(i)),"serialized"in t&&typeof t.serialized=="object"){const c=t.serialized;c.name&&e.setAttribute(Wb,String(c.name)),c.signature&&e.setAttribute(Gb,String(c.signature)),c.doc&&e.setAttribute(Jb,String(c.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,t){let n="langchain";const s=this.extractModelName(t);if(s){const a=s.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?n="anthropic":a.includes("bedrock")?n="aws.bedrock":a.includes("azure")&&a.includes("openai")?n="az.ai.openai":a.includes("azure")&&a.includes("inference")?n="az.ai.inference":a.includes("cohere")?n="cohere":a.includes("deepseek")?n="deepseek":a.includes("gemini")?n="gemini":a.includes("groq")?n="groq":a.includes("watson")||a.includes("ibm")?n="ibm.watsonx.ai":a.includes("mistral")?n="mistral_ai":a.includes("gpt")||a.includes("openai")?n="openai":a.includes("perplexity")||a.includes("sonar")?n="perplexity":a.includes("vertex")?n="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(n="xai")}e.setAttribute(Pb,n)}setInvocationParameters(e,t){var s,a;if(!((a=(s=t.extra)==null?void 0:s.metadata)!=null&&a.invocation_params))return;const n=t.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(Lb,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Mb,n.temperature),n.top_p!==void 0&&e.setAttribute(jb,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Db,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(Ub,n.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{const n=t.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(Fd,n.model),n.stream!==void 0&&e.setAttribute(sv,n.stream),n.extra_headers&&e.setAttribute(av,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(zb,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Hb,JSON.stringify(n.extra_body))),e.setAttribute(Bb,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${t.id}`,n)}if(t.run.outputs)try{const n=t.run.outputs,s=this.getUnifiedRunTokens(n);if(s&&(e.setAttribute(Bd,s[0]),e.setAttribute(qd,s[1]),e.setAttribute(zd,s[0]+s[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Nb,String(n.model)),n.id&&e.setAttribute(Vb,n.id),n.choices&&Array.isArray(n.choices)){const a=n.choices.map(i=>i.finish_reason).filter(i=>i).map(String);a.length>0&&e.setAttribute(Fb,a.join(", "))}if(n.service_tier&&e.setAttribute(Kb,n.service_tier),n.system_fingerprint&&e.setAttribute(Zb,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){const a=n.usage_metadata;a.input_token_details&&e.setAttribute(Xb,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(Yb,JSON.stringify(a.output_token_details))}}e.setAttribute(qb,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${t.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;const n=Object.keys(e);for(const i of n){const o=e[i];if(!(!o||typeof o!="object")&&(t=this.extractUnifiedRunTokens(o.usage_metadata),t||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(t=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),t)))return t}const s=e.generations||[];if(!Array.isArray(s))return null;const a=Array.isArray(s[0])?s.flat():s;for(const i of a)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(t=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}var Un={exports:{}},Do={},Uo,Gd;function Av(){if(Gd)return Uo;Gd=1;function r(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return Uo=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var s=this;return this._timer=setTimeout(function(){s._attempts++,s._operationTimeoutCb&&(s._timeout=setTimeout(function(){s._operationTimeoutCb(s._attempts)},s._operationTimeout),s._options.unref&&s._timeout.unref()),s._fn(s._attempts)},n),this._options.unref&&this._timer.unref(),!0},r.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},r.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},r.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,s=0;s<this._errors.length;s++){var a=this._errors[s],i=a.message,o=(e[i]||0)+1;e[i]=o,o>=n&&(t=a,n=o)}return t},Uo}var Jd;function Iv(){return Jd||(Jd=1,(function(r){var e=Av();r.operation=function(t){var n=r.timeouts(t);return new e(n,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})},r.timeouts=function(t){if(t instanceof Array)return[].concat(t);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var s in t)n[s]=t[s];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var a=[],i=0;i<n.retries;i++)a.push(this.createTimeout(i,n));return t&&t.forever&&!a.length&&a.push(this.createTimeout(i,n)),a.sort(function(o,c){return o-c}),a},r.createTimeout=function(t,n){var s=n.randomize?Math.random()+1:1,a=Math.round(s*Math.max(n.minTimeout,1)*Math.pow(n.factor,t));return a=Math.min(a,n.maxTimeout),a},r.wrap=function(t,n,s){if(n instanceof Array&&(s=n,n=null),!s){s=[];for(var a in t)typeof t[a]=="function"&&s.push(a)}for(var i=0;i<s.length;i++){var o=s[i],c=t[o];t[o]=(function(u){var d=r.operation(n),h=Array.prototype.slice.call(arguments,1),f=h.pop();h.push(function(p){d.retry(p)||(p&&(arguments[0]=d.mainError()),f.apply(this,arguments))}),d.attempt(function(){u.apply(t,h)})}).bind(t,c),t[o].options=n}}})(Do)),Do}var Fo,Vd;function Rv(){return Vd||(Vd=1,Fo=Iv()),Fo}var Kd;function Ov(){if(Kd)return Un.exports;Kd=1;const r=Rv(),e=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class t extends Error{constructor(o){super(),o instanceof Error?(this.originalError=o,{message:o}=o):(this.originalError=new Error(o),this.originalError.stack=this.stack),this.name="AbortError",this.message=o}}const n=(i,o,c)=>{const l=c.retries-(o-1);return i.attemptNumber=o,i.retriesLeft=l,i},s=i=>e.includes(i),a=(i,o)=>new Promise((c,l)=>{o={onFailedAttempt:()=>{},retries:10,...o};const u=r.operation(o);u.attempt(async d=>{try{c(await i(d))}catch(h){if(!(h instanceof Error)){l(new TypeError(`Non-error was thrown: "${h}". You should only throw errors.`));return}if(h instanceof t)u.stop(),l(h.originalError);else if(h instanceof TypeError&&!s(h.message))u.stop(),l(h);else{n(h,d,o);try{await o.onFailedAttempt(h)}catch(f){l(f);return}u.retry(h)||l(u.mainError())}}})});return Un.exports=a,Un.exports.default=a,Un.exports.AbortError=t,Un.exports}var $v=Ov();const ui=Ds($v);var da={},Bo={exports:{}},Zd;function Cv(){return Zd||(Zd=1,(function(r){var e=Object.prototype.hasOwnProperty,t="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(t=!1));function s(c,l,u){this.fn=c,this.context=l,this.once=u||!1}function a(c,l,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new s(u,d||c,h),p=t?t+l:l;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],f]:c._events[p].push(f):(c._events[p]=f,c._eventsCount++),c}function i(c,l){--c._eventsCount===0?c._events=new n:delete c._events[l]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],u,d;if(this._eventsCount===0)return l;for(d in u=this._events)e.call(u,d)&&l.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(u)):l},o.prototype.listeners=function(l){var u=t?t+l:l,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,p=new Array(f);h<f;h++)p[h]=d[h].fn;return p},o.prototype.listenerCount=function(l){var u=t?t+l:l,d=this._events[u];return d?d.fn?1:d.length:0},o.prototype.emit=function(l,u,d,h,f,p){var g=t?t+l:l;if(!this._events[g])return!1;var _=this._events[g],b=arguments.length,m,y;if(_.fn){switch(_.once&&this.removeListener(l,_.fn,void 0,!0),b){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,u),!0;case 3:return _.fn.call(_.context,u,d),!0;case 4:return _.fn.call(_.context,u,d,h),!0;case 5:return _.fn.call(_.context,u,d,h,f),!0;case 6:return _.fn.call(_.context,u,d,h,f,p),!0}for(y=1,m=new Array(b-1);y<b;y++)m[y-1]=arguments[y];_.fn.apply(_.context,m)}else{var T=_.length,x;for(y=0;y<T;y++)switch(_[y].once&&this.removeListener(l,_[y].fn,void 0,!0),b){case 1:_[y].fn.call(_[y].context);break;case 2:_[y].fn.call(_[y].context,u);break;case 3:_[y].fn.call(_[y].context,u,d);break;case 4:_[y].fn.call(_[y].context,u,d,h);break;default:if(!m)for(x=1,m=new Array(b-1);x<b;x++)m[x-1]=arguments[x];_[y].fn.apply(_[y].context,m)}}return!0},o.prototype.on=function(l,u,d){return a(this,l,u,d,!1)},o.prototype.once=function(l,u,d){return a(this,l,u,d,!0)},o.prototype.removeListener=function(l,u,d,h){var f=t?t+l:l;if(!this._events[f])return this;if(!u)return i(this,f),this;var p=this._events[f];if(p.fn)p.fn===u&&(!h||p.once)&&(!d||p.context===d)&&i(this,f);else{for(var g=0,_=[],b=p.length;g<b;g++)(p[g].fn!==u||h&&!p[g].once||d&&p[g].context!==d)&&_.push(p[g]);_.length?this._events[f]=_.length===1?_[0]:_:i(this,f)}return this},o.prototype.removeAllListeners=function(l){var u;return l?(u=t?t+l:l,this._events[u]&&i(this,u)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o})(Bo)),Bo.exports}var Fn={exports:{}},qo,Xd;function kv(){return Xd||(Xd=1,qo=(r,e)=>(e=e||(()=>{}),r.then(t=>new Promise(n=>{n(e())}).then(()=>t),t=>new Promise(n=>{n(e())}).then(()=>{throw t})))),qo}var Yd;function Pv(){if(Yd)return Fn.exports;Yd=1;const r=kv();class e extends Error{constructor(s){super(s),this.name="TimeoutError"}}const t=(n,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(n);return}const c=setTimeout(()=>{if(typeof a=="function"){try{i(a())}catch(d){o(d)}return}const l=typeof a=="string"?a:`Promise timed out after ${s} milliseconds`,u=a instanceof Error?a:new e(l);typeof n.cancel=="function"&&n.cancel(),o(u)},s);r(n.then(i,o),()=>{clearTimeout(c)})});return Fn.exports=t,Fn.exports.default=t,Fn.exports.TimeoutError=e,Fn.exports}var ha={},fa={},Qd;function Nv(){if(Qd)return fa;Qd=1,Object.defineProperty(fa,"__esModule",{value:!0});function r(e,t,n){let s=0,a=e.length;for(;a>0;){const i=a/2|0;let o=s+i;n(e[o],t)<=0?(s=++o,a-=i+1):a=i}return s}return fa.default=r,fa}var eh;function Lv(){if(eh)return ha;eh=1,Object.defineProperty(ha,"__esModule",{value:!0});const r=Nv();class e{constructor(){this._queue=[]}enqueue(n,s){s=Object.assign({priority:0},s);const a={priority:s.priority,run:n};if(this.size&&this._queue[this.size-1].priority>=s.priority){this._queue.push(a);return}const i=r.default(this._queue,a,(o,c)=>c.priority-o.priority);this._queue.splice(i,0,a)}dequeue(){const n=this._queue.shift();return n==null?void 0:n.run}filter(n){return this._queue.filter(s=>s.priority===n.priority).map(s=>s.run)}get size(){return this._queue.length}}return ha.default=e,ha}var th;function Mv(){if(th)return da;th=1,Object.defineProperty(da,"__esModule",{value:!0});const r=Cv(),e=Pv(),t=Lv(),n=()=>{},s=new e.TimeoutError;class a extends r{constructor(o){var c,l,u,d;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=n,this._resolveIdle=n,o=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:t.default},o),!(typeof o.intervalCap=="number"&&o.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(l=(c=o.intervalCap)===null||c===void 0?void 0:c.toString())!==null&&l!==void 0?l:""}\` (${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=(u=o.interval)===null||u===void 0?void 0:u.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=n,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=n,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((l,u)=>{const d=async()=>{this._pendingCount++,this._intervalCount++;try{const h=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)&&u(s)});l(await h)}catch(h){u(h)}this._next()};this._queue.enqueue(d,c),this._tryToStartAnother(),this.emit("add")})}async addAll(o,c){return Promise.all(o.map(async l=>this.add(l,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 da.default=a,da}var jv=Mv();const mr=Ds(jv),Dv=[429,500,502,503,504];let rh=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in mr?this.queue=new mr.default({concurrency:this.maxConcurrency}):this.queue=new mr({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e==null?void 0:e.onFailedResponseHook}call(e,...t){const n=this.onFailedResponseHook;return this.queue.add(()=>ui(()=>e(...t).catch(s=>{throw s instanceof Error?s:new Error(s)}),{async onFailedAttempt(s){if(s.message.startsWith("Cancel")||s.message.startsWith("TimeoutError")||s.name==="TimeoutError"||s.message.startsWith("AbortError")||(s==null?void 0:s.code)==="ECONNABORTED")throw s;const a=s==null?void 0:s.response;if(n&&await n(a))return;const i=(a==null?void 0:a.status)??(s==null?void 0:s.status);if(i&&!Dv.includes(+i))throw s},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((s,a)=>{var i;(i=e.signal)==null||i.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(t,...n)}};function nh(r){return typeof(r==null?void 0:r._getType)=="function"}function sh(r){const e={type:r._getType(),data:{content:r.content}};return r!=null&&r.additional_kwargs&&Object.keys(r.additional_kwargs).length>0&&(e.data.additional_kwargs={...r.additional_kwargs}),e}const Uv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function le(r,e){if(!Uv.test(r)){const t=e!==void 0?`Invalid UUID for ${e}: ${r}`:`Invalid UUID: ${r}`;throw new Error(t)}return r}const ah={};function ym(r){ah[r]||(console.warn(r),ah[r]=!0)}var pa={exports:{}},zo,ih;function Hi(){if(ih)return zo;ih=1;const r="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,s=e-6;return zo={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},zo}var Ho,oh;function Wi(){if(oh)return Ho;oh=1;var r={};return Ho=typeof process=="object"&&r&&r.NODE_DEBUG&&/\bsemver\b/i.test(r.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{},Ho}var ch;function Ws(){return ch||(ch=1,(function(r,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:s}=Hi(),a=Wi();e=r.exports={};const i=e.re=[],o=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={};let d=0;const h="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",s],[h,n]],p=_=>{for(const[b,m]of f)_=_.split(`${b}*`).join(`${b}{0,${m}}`).split(`${b}+`).join(`${b}{1,${m}}`);return _},g=(_,b,m)=>{const y=p(b),T=d++;a(_,T,b),u[_]=T,c[T]=b,l[T]=y,i[T]=new RegExp(b,m?"g":void 0),o[T]=new RegExp(y,m?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),g("MAINVERSION",`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASE",`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${h}+`),g("BUILD",`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),g("FULL",`^${c[u.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),g("LOOSE",`^${c[u.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),g("XRANGE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),g("COERCE",`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),g("COERCERTL",c[u.COERCE],!0),g("COERCERTLFULL",c[u.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",g("TILDE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",g("CARET",`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(pa,pa.exports)),pa.exports}var Wo,lh;function Tu(){if(lh)return Wo;lh=1;const r=Object.freeze({loose:!0}),e=Object.freeze({});return Wo=n=>n?typeof n!="object"?r:n:e,Wo}var Go,uh;function wm(){if(uh)return Go;uh=1;const r=/^[0-9]+$/,e=(n,s)=>{if(typeof n=="number"&&typeof s=="number")return n===s?0:n<s?-1:1;const a=r.test(n),i=r.test(s);return a&&i&&(n=+n,s=+s),n===s?0:a&&!i?-1:i&&!a?1:n<s?-1:1};return Go={compareIdentifiers:e,rcompareIdentifiers:(n,s)=>e(s,n)},Go}var Jo,dh;function rt(){if(dh)return Jo;dh=1;const r=Wi(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=Hi(),{safeRe:n,t:s}=Ws(),a=Tu(),{compareIdentifiers:i}=wm();class o{constructor(l,u){if(u=a(u),l instanceof o){if(l.loose===!!u.loose&&l.includePrerelease===!!u.includePrerelease)return l;l=l.version}else if(typeof l!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof l}".`);if(l.length>e)throw new TypeError(`version is longer than ${e} characters`);r("SemVer",l,u),this.options=u,this.loose=!!u.loose,this.includePrerelease=!!u.includePrerelease;const d=l.trim().match(u.loose?n[s.LOOSE]:n[s.FULL]);if(!d)throw new TypeError(`Invalid Version: ${l}`);if(this.raw=l,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>t||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const f=+h;if(f>=0&&f<t)return f}return h}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(l){if(r("SemVer.compare",this.version,this.options,l),!(l instanceof o)){if(typeof l=="string"&&l===this.version)return 0;l=new o(l,this.options)}return l.version===this.version?0:this.compareMain(l)||this.comparePre(l)}compareMain(l){return l instanceof o||(l=new o(l,this.options)),this.major<l.major?-1:this.major>l.major?1:this.minor<l.minor?-1:this.minor>l.minor?1:this.patch<l.patch?-1:this.patch>l.patch?1:0}comparePre(l){if(l instanceof o||(l=new o(l,this.options)),this.prerelease.length&&!l.prerelease.length)return-1;if(!this.prerelease.length&&l.prerelease.length)return 1;if(!this.prerelease.length&&!l.prerelease.length)return 0;let u=0;do{const d=this.prerelease[u],h=l.prerelease[u];if(r("prerelease compare",u,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++u)}compareBuild(l){l instanceof o||(l=new o(l,this.options));let u=0;do{const d=this.build[u],h=l.build[u];if(r("build compare",u,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++u)}inc(l,u,d){if(l.startsWith("pre")){if(!u&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(u){const h=`-${u}`.match(this.options.loose?n[s.PRERELEASELOOSE]:n[s.PRERELEASE]);if(!h||h[1]!==u)throw new Error(`invalid identifier: ${u}`)}}switch(l){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",u,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",u,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",u,d),this.inc("pre",u,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",u,d),this.inc("pre",u,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const h=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(u===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(u){let f=[u,h];d===!1&&(f=[u]),i(this.prerelease[0],u)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${l}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return Jo=o,Jo}var Vo,hh;function kn(){if(hh)return Vo;hh=1;const r=rt();return Vo=(t,n,s=!1)=>{if(t instanceof r)return t;try{return new r(t,n)}catch(a){if(!s)return null;throw a}},Vo}var Ko,fh;function Fv(){if(fh)return Ko;fh=1;const r=kn();return Ko=(t,n)=>{const s=r(t,n);return s?s.version:null},Ko}var Zo,ph;function Bv(){if(ph)return Zo;ph=1;const r=kn();return Zo=(t,n)=>{const s=r(t.trim().replace(/^[=v]+/,""),n);return s?s.version:null},Zo}var Xo,mh;function qv(){if(mh)return Xo;mh=1;const r=rt();return Xo=(t,n,s,a,i)=>{typeof s=="string"&&(i=a,a=s,s=void 0);try{return new r(t instanceof r?t.version:t,s).inc(n,a,i).version}catch{return null}},Xo}var Yo,gh;function zv(){if(gh)return Yo;gh=1;const r=kn();return Yo=(t,n)=>{const s=r(t,null,!0),a=r(n,null,!0),i=s.compare(a);if(i===0)return null;const o=i>0,c=o?s:a,l=o?a:s,u=!!c.prerelease.length;if(!!l.prerelease.length&&!u){if(!l.patch&&!l.minor)return"major";if(l.compareMain(c)===0)return l.minor&&!l.patch?"minor":"patch"}const h=u?"pre":"";return s.major!==a.major?h+"major":s.minor!==a.minor?h+"minor":s.patch!==a.patch?h+"patch":"prerelease"},Yo}var Qo,_h;function Hv(){if(_h)return Qo;_h=1;const r=rt();return Qo=(t,n)=>new r(t,n).major,Qo}var ec,yh;function Wv(){if(yh)return ec;yh=1;const r=rt();return ec=(t,n)=>new r(t,n).minor,ec}var tc,wh;function Gv(){if(wh)return tc;wh=1;const r=rt();return tc=(t,n)=>new r(t,n).patch,tc}var rc,bh;function Jv(){if(bh)return rc;bh=1;const r=kn();return rc=(t,n)=>{const s=r(t,n);return s&&s.prerelease.length?s.prerelease:null},rc}var nc,vh;function Zt(){if(vh)return nc;vh=1;const r=rt();return nc=(t,n,s)=>new r(t,s).compare(new r(n,s)),nc}var sc,Sh;function Vv(){if(Sh)return sc;Sh=1;const r=Zt();return sc=(t,n,s)=>r(n,t,s),sc}var ac,Eh;function Kv(){if(Eh)return ac;Eh=1;const r=Zt();return ac=(t,n)=>r(t,n,!0),ac}var ic,Th;function xu(){if(Th)return ic;Th=1;const r=rt();return ic=(t,n,s)=>{const a=new r(t,s),i=new r(n,s);return a.compare(i)||a.compareBuild(i)},ic}var oc,xh;function Zv(){if(xh)return oc;xh=1;const r=xu();return oc=(t,n)=>t.sort((s,a)=>r(s,a,n)),oc}var cc,Ah;function Xv(){if(Ah)return cc;Ah=1;const r=xu();return cc=(t,n)=>t.sort((s,a)=>r(a,s,n)),cc}var lc,Ih;function Gi(){if(Ih)return lc;Ih=1;const r=Zt();return lc=(t,n,s)=>r(t,n,s)>0,lc}var uc,Rh;function Au(){if(Rh)return uc;Rh=1;const r=Zt();return uc=(t,n,s)=>r(t,n,s)<0,uc}var dc,Oh;function bm(){if(Oh)return dc;Oh=1;const r=Zt();return dc=(t,n,s)=>r(t,n,s)===0,dc}var hc,$h;function vm(){if($h)return hc;$h=1;const r=Zt();return hc=(t,n,s)=>r(t,n,s)!==0,hc}var fc,Ch;function Iu(){if(Ch)return fc;Ch=1;const r=Zt();return fc=(t,n,s)=>r(t,n,s)>=0,fc}var pc,kh;function Ru(){if(kh)return pc;kh=1;const r=Zt();return pc=(t,n,s)=>r(t,n,s)<=0,pc}var mc,Ph;function Sm(){if(Ph)return mc;Ph=1;const r=bm(),e=vm(),t=Gi(),n=Iu(),s=Au(),a=Ru();return mc=(o,c,l,u)=>{switch(c){case"===":return typeof o=="object"&&(o=o.version),typeof l=="object"&&(l=l.version),o===l;case"!==":return typeof o=="object"&&(o=o.version),typeof l=="object"&&(l=l.version),o!==l;case"":case"=":case"==":return r(o,l,u);case"!=":return e(o,l,u);case">":return t(o,l,u);case">=":return n(o,l,u);case"<":return s(o,l,u);case"<=":return a(o,l,u);default:throw new TypeError(`Invalid operator: ${c}`)}},mc}var gc,Nh;function Yv(){if(Nh)return gc;Nh=1;const r=rt(),e=kn(),{safeRe:t,t:n}=Ws();return gc=(a,i)=>{if(a instanceof r)return a;if(typeof a=="number"&&(a=String(a)),typeof a!="string")return null;i=i||{};let o=null;if(!i.rtl)o=a.match(i.includePrerelease?t[n.COERCEFULL]:t[n.COERCE]);else{const f=i.includePrerelease?t[n.COERCERTLFULL]:t[n.COERCERTL];let p;for(;(p=f.exec(a))&&(!o||o.index+o[0].length!==a.length);)(!o||p.index+p[0].length!==o.index+o[0].length)&&(o=p),f.lastIndex=p.index+p[1].length+p[2].length;f.lastIndex=-1}if(o===null)return null;const c=o[2],l=o[3]||"0",u=o[4]||"0",d=i.includePrerelease&&o[5]?`-${o[5]}`:"",h=i.includePrerelease&&o[6]?`+${o[6]}`:"";return e(`${c}.${l}.${u}${d}${h}`,i)},gc}var _c,Lh;function Qv(){if(Lh)return _c;Lh=1;class r{constructor(){this.max=1e3,this.map=new Map}get(t){const n=this.map.get(t);if(n!==void 0)return this.map.delete(t),this.map.set(t,n),n}delete(t){return this.map.delete(t)}set(t,n){if(!this.delete(t)&&n!==void 0){if(this.map.size>=this.max){const a=this.map.keys().next().value;this.delete(a)}this.map.set(t,n)}return this}}return _c=r,_c}var yc,Mh;function Xt(){if(Mh)return yc;Mh=1;const r=/\s+/g;class e{constructor(P,N){if(N=s(N),P instanceof e)return P.loose===!!N.loose&&P.includePrerelease===!!N.includePrerelease?P:new e(P.raw,N);if(P instanceof a)return this.raw=P.value,this.set=[[P]],this.formatted=void 0,this;if(this.options=N,this.loose=!!N.loose,this.includePrerelease=!!N.includePrerelease,this.raw=P.trim().replace(r," "),this.set=this.raw.split("||").map(W=>this.parseRange(W.trim())).filter(W=>W.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const W=this.set[0];if(this.set=this.set.filter(V=>!g(V[0])),this.set.length===0)this.set=[W];else if(this.set.length>1){for(const V of this.set)if(V.length===1&&_(V[0])){this.set=[V];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let P=0;P<this.set.length;P++){P>0&&(this.formatted+="||");const N=this.set[P];for(let W=0;W<N.length;W++)W>0&&(this.formatted+=" "),this.formatted+=N[W].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(P){const W=((this.options.includePrerelease&&f)|(this.options.loose&&p))+":"+P,V=n.get(W);if(V)return V;const z=this.options.loose,ee=z?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];P=P.replace(ee,Ae(this.options.includePrerelease)),i("hyphen replace",P),P=P.replace(c[l.COMPARATORTRIM],u),i("comparator trim",P),P=P.replace(c[l.TILDETRIM],d),i("tilde trim",P),P=P.replace(c[l.CARETTRIM],h),i("caret trim",P);let de=P.split(" ").map(me=>m(me,this.options)).join(" ").split(/\s+/).map(me=>H(me,this.options));z&&(de=de.filter(me=>(i("loose invalid filter",me,this.options),!!me.match(c[l.COMPARATORLOOSE])))),i("range list",de);const oe=new Map,ye=de.map(me=>new a(me,this.options));for(const me of ye){if(g(me))return[me];oe.set(me.value,me)}oe.size>1&&oe.has("")&&oe.delete("");const Ce=[...oe.values()];return n.set(W,Ce),Ce}intersects(P,N){if(!(P instanceof e))throw new TypeError("a Range is required");return this.set.some(W=>b(W,N)&&P.set.some(V=>b(V,N)&&W.every(z=>V.every(ee=>z.intersects(ee,N)))))}test(P){if(!P)return!1;if(typeof P=="string")try{P=new o(P,this.options)}catch{return!1}for(let N=0;N<this.set.length;N++)if(ft(this.set[N],P,this.options))return!0;return!1}}yc=e;const t=Qv(),n=new t,s=Tu(),a=Ji(),i=Wi(),o=rt(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:h}=Ws(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:p}=Hi(),g=M=>M.value==="<0.0.0-0",_=M=>M.value==="",b=(M,P)=>{let N=!0;const W=M.slice();let V=W.pop();for(;N&&W.length;)N=W.every(z=>V.intersects(z,P)),V=W.pop();return N},m=(M,P)=>(M=M.replace(c[l.BUILD],""),i("comp",M,P),M=R(M,P),i("caret",M),M=T(M,P),i("tildes",M),M=E(M,P),i("xrange",M),M=se(M,P),i("stars",M),M),y=M=>!M||M.toLowerCase()==="x"||M==="*",T=(M,P)=>M.trim().split(/\s+/).map(N=>x(N,P)).join(" "),x=(M,P)=>{const N=P.loose?c[l.TILDELOOSE]:c[l.TILDE];return M.replace(N,(W,V,z,ee,de)=>{i("tilde",M,W,V,z,ee,de);let oe;return y(V)?oe="":y(z)?oe=`>=${V}.0.0 <${+V+1}.0.0-0`:y(ee)?oe=`>=${V}.${z}.0 <${V}.${+z+1}.0-0`:de?(i("replaceTilde pr",de),oe=`>=${V}.${z}.${ee}-${de} <${V}.${+z+1}.0-0`):oe=`>=${V}.${z}.${ee} <${V}.${+z+1}.0-0`,i("tilde return",oe),oe})},R=(M,P)=>M.trim().split(/\s+/).map(N=>$(N,P)).join(" "),$=(M,P)=>{i("caret",M,P);const N=P.loose?c[l.CARETLOOSE]:c[l.CARET],W=P.includePrerelease?"-0":"";return M.replace(N,(V,z,ee,de,oe)=>{i("caret",M,V,z,ee,de,oe);let ye;return y(z)?ye="":y(ee)?ye=`>=${z}.0.0${W} <${+z+1}.0.0-0`:y(de)?z==="0"?ye=`>=${z}.${ee}.0${W} <${z}.${+ee+1}.0-0`:ye=`>=${z}.${ee}.0${W} <${+z+1}.0.0-0`:oe?(i("replaceCaret pr",oe),z==="0"?ee==="0"?ye=`>=${z}.${ee}.${de}-${oe} <${z}.${ee}.${+de+1}-0`:ye=`>=${z}.${ee}.${de}-${oe} <${z}.${+ee+1}.0-0`:ye=`>=${z}.${ee}.${de}-${oe} <${+z+1}.0.0-0`):(i("no pr"),z==="0"?ee==="0"?ye=`>=${z}.${ee}.${de}${W} <${z}.${ee}.${+de+1}-0`:ye=`>=${z}.${ee}.${de}${W} <${z}.${+ee+1}.0-0`:ye=`>=${z}.${ee}.${de} <${+z+1}.0.0-0`),i("caret return",ye),ye})},E=(M,P)=>(i("replaceXRanges",M,P),M.split(/\s+/).map(N=>J(N,P)).join(" ")),J=(M,P)=>{M=M.trim();const N=P.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return M.replace(N,(W,V,z,ee,de,oe)=>{i("xRange",M,W,V,z,ee,de,oe);const ye=y(z),Ce=ye||y(ee),me=Ce||y(de),S=me;return V==="="&&S&&(V=""),oe=P.includePrerelease?"-0":"",ye?V===">"||V==="<"?W="<0.0.0-0":W="*":V&&S?(Ce&&(ee=0),de=0,V===">"?(V=">=",Ce?(z=+z+1,ee=0,de=0):(ee=+ee+1,de=0)):V==="<="&&(V="<",Ce?z=+z+1:ee=+ee+1),V==="<"&&(oe="-0"),W=`${V+z}.${ee}.${de}${oe}`):Ce?W=`>=${z}.0.0${oe} <${+z+1}.0.0-0`:me&&(W=`>=${z}.${ee}.0${oe} <${z}.${+ee+1}.0-0`),i("xRange return",W),W})},se=(M,P)=>(i("replaceStars",M,P),M.trim().replace(c[l.STAR],"")),H=(M,P)=>(i("replaceGTE0",M,P),M.trim().replace(c[P.includePrerelease?l.GTE0PRE:l.GTE0],"")),Ae=M=>(P,N,W,V,z,ee,de,oe,ye,Ce,me,S)=>(y(W)?N="":y(V)?N=`>=${W}.0.0${M?"-0":""}`:y(z)?N=`>=${W}.${V}.0${M?"-0":""}`:ee?N=`>=${N}`:N=`>=${N}${M?"-0":""}`,y(ye)?oe="":y(Ce)?oe=`<${+ye+1}.0.0-0`:y(me)?oe=`<${ye}.${+Ce+1}.0-0`:S?oe=`<=${ye}.${Ce}.${me}-${S}`:M?oe=`<${ye}.${Ce}.${+me+1}-0`:oe=`<=${oe}`,`${N} ${oe}`.trim()),ft=(M,P,N)=>{for(let W=0;W<M.length;W++)if(!M[W].test(P))return!1;if(P.prerelease.length&&!N.includePrerelease){for(let W=0;W<M.length;W++)if(i(M[W].semver),M[W].semver!==a.ANY&&M[W].semver.prerelease.length>0){const V=M[W].semver;if(V.major===P.major&&V.minor===P.minor&&V.patch===P.patch)return!0}return!1}return!0};return yc}var wc,jh;function Ji(){if(jh)return wc;jh=1;const r=Symbol("SemVer ANY");class e{static get ANY(){return r}constructor(u,d){if(d=t(d),u instanceof e){if(u.loose===!!d.loose)return u;u=u.value}u=u.trim().split(/\s+/).join(" "),i("comparator",u,d),this.options=d,this.loose=!!d.loose,this.parse(u),this.semver===r?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?n[s.COMPARATORLOOSE]:n[s.COMPARATOR],h=u.match(d);if(!h)throw new TypeError(`Invalid comparator: ${u}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new o(h[2],this.options.loose):this.semver=r}toString(){return this.value}test(u){if(i("Comparator.test",u,this.options.loose),this.semver===r||u===r)return!0;if(typeof u=="string")try{u=new o(u,this.options)}catch{return!1}return a(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new c(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||a(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||a(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}wc=e;const t=Tu(),{safeRe:n,t:s}=Ws(),a=Sm(),i=Wi(),o=rt(),c=Xt();return wc}var bc,Dh;function Vi(){if(Dh)return bc;Dh=1;const r=Xt();return bc=(t,n,s)=>{try{n=new r(n,s)}catch{return!1}return n.test(t)},bc}var vc,Uh;function e0(){if(Uh)return vc;Uh=1;const r=Xt();return vc=(t,n)=>new r(t,n).set.map(s=>s.map(a=>a.value).join(" ").trim().split(" ")),vc}var Sc,Fh;function t0(){if(Fh)return Sc;Fh=1;const r=rt(),e=Xt();return Sc=(n,s,a)=>{let i=null,o=null,c=null;try{c=new e(s,a)}catch{return null}return n.forEach(l=>{c.test(l)&&(!i||o.compare(l)===-1)&&(i=l,o=new r(i,a))}),i},Sc}var Ec,Bh;function r0(){if(Bh)return Ec;Bh=1;const r=rt(),e=Xt();return Ec=(n,s,a)=>{let i=null,o=null,c=null;try{c=new e(s,a)}catch{return null}return n.forEach(l=>{c.test(l)&&(!i||o.compare(l)===1)&&(i=l,o=new r(i,a))}),i},Ec}var Tc,qh;function n0(){if(qh)return Tc;qh=1;const r=rt(),e=Xt(),t=Gi();return Tc=(s,a)=>{s=new e(s,a);let i=new r("0.0.0");if(s.test(i)||(i=new r("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 l=null;c.forEach(u=>{const d=new r(u.semver.version);switch(u.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!l||t(d,l))&&(l=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${u.operator}`)}}),l&&(!i||t(i,l))&&(i=l)}return i&&s.test(i)?i:null},Tc}var xc,zh;function s0(){if(zh)return xc;zh=1;const r=Xt();return xc=(t,n)=>{try{return new r(t,n).range||"*"}catch{return null}},xc}var Ac,Hh;function Ou(){if(Hh)return Ac;Hh=1;const r=rt(),e=Ji(),{ANY:t}=e,n=Xt(),s=Vi(),a=Gi(),i=Au(),o=Ru(),c=Iu();return Ac=(u,d,h,f)=>{u=new r(u,f),d=new n(d,f);let p,g,_,b,m;switch(h){case">":p=a,g=o,_=i,b=">",m=">=";break;case"<":p=i,g=c,_=a,b="<",m="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(s(u,d,f))return!1;for(let y=0;y<d.set.length;++y){const T=d.set[y];let x=null,R=null;if(T.forEach($=>{$.semver===t&&($=new e(">=0.0.0")),x=x||$,R=R||$,p($.semver,x.semver,f)?x=$:_($.semver,R.semver,f)&&(R=$)}),x.operator===b||x.operator===m||(!R.operator||R.operator===b)&&g(u,R.semver))return!1;if(R.operator===m&&_(u,R.semver))return!1}return!0},Ac}var Ic,Wh;function a0(){if(Wh)return Ic;Wh=1;const r=Ou();return Ic=(t,n,s)=>r(t,n,">",s),Ic}var Rc,Gh;function i0(){if(Gh)return Rc;Gh=1;const r=Ou();return Rc=(t,n,s)=>r(t,n,"<",s),Rc}var Oc,Jh;function o0(){if(Jh)return Oc;Jh=1;const r=Xt();return Oc=(t,n,s)=>(t=new r(t,s),n=new r(n,s),t.intersects(n,s)),Oc}var $c,Vh;function c0(){if(Vh)return $c;Vh=1;const r=Vi(),e=Zt();return $c=(t,n,s)=>{const a=[];let i=null,o=null;const c=t.sort((h,f)=>e(h,f,s));for(const h of c)r(h,n,s)?(o=h,i||(i=h)):(o&&a.push([i,o]),o=null,i=null);i&&a.push([i,null]);const l=[];for(const[h,f]of a)h===f?l.push(h):!f&&h===c[0]?l.push("*"):f?h===c[0]?l.push(`<=${f}`):l.push(`${h} - ${f}`):l.push(`>=${h}`);const u=l.join(" || "),d=typeof n.raw=="string"?n.raw:String(n);return u.length<d.length?u:n},$c}var Cc,Kh;function l0(){if(Kh)return Cc;Kh=1;const r=Xt(),e=Ji(),{ANY:t}=e,n=Vi(),s=Zt(),a=(d,h,f={})=>{if(d===h)return!0;d=new r(d,f),h=new r(h,f);let p=!1;e:for(const g of d.set){for(const _ of h.set){const b=c(g,_,f);if(p=p||b!==null,b)continue e}if(p)return!1}return!0},i=[new e(">=0.0.0-0")],o=[new e(">=0.0.0")],c=(d,h,f)=>{if(d===h)return!0;if(d.length===1&&d[0].semver===t){if(h.length===1&&h[0].semver===t)return!0;f.includePrerelease?d=i:d=o}if(h.length===1&&h[0].semver===t){if(f.includePrerelease)return!0;h=o}const p=new Set;let g,_;for(const E of d)E.operator===">"||E.operator===">="?g=l(g,E,f):E.operator==="<"||E.operator==="<="?_=u(_,E,f):p.add(E.semver);if(p.size>1)return null;let b;if(g&&_){if(b=s(g.semver,_.semver,f),b>0)return null;if(b===0&&(g.operator!==">="||_.operator!=="<="))return null}for(const E of p){if(g&&!n(E,String(g),f)||_&&!n(E,String(_),f))return null;for(const J of h)if(!n(E,String(J),f))return!1;return!0}let m,y,T,x,R=_&&!f.includePrerelease&&_.semver.prerelease.length?_.semver:!1,$=g&&!f.includePrerelease&&g.semver.prerelease.length?g.semver:!1;R&&R.prerelease.length===1&&_.operator==="<"&&R.prerelease[0]===0&&(R=!1);for(const E of h){if(x=x||E.operator===">"||E.operator===">=",T=T||E.operator==="<"||E.operator==="<=",g){if($&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===$.major&&E.semver.minor===$.minor&&E.semver.patch===$.patch&&($=!1),E.operator===">"||E.operator===">="){if(m=l(g,E,f),m===E&&m!==g)return!1}else if(g.operator===">="&&!n(g.semver,String(E),f))return!1}if(_){if(R&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===R.major&&E.semver.minor===R.minor&&E.semver.patch===R.patch&&(R=!1),E.operator==="<"||E.operator==="<="){if(y=u(_,E,f),y===E&&y!==_)return!1}else if(_.operator==="<="&&!n(_.semver,String(E),f))return!1}if(!E.operator&&(_||g)&&b!==0)return!1}return!(g&&T&&!_&&b!==0||_&&x&&!g&&b!==0||$||R)},l=(d,h,f)=>{if(!d)return h;const p=s(d.semver,h.semver,f);return p>0?d:p<0||h.operator===">"&&d.operator===">="?h:d},u=(d,h,f)=>{if(!d)return h;const p=s(d.semver,h.semver,f);return p<0?d:p>0||h.operator==="<"&&d.operator==="<="?h:d};return Cc=a,Cc}var kc,Zh;function u0(){if(Zh)return kc;Zh=1;const r=Ws(),e=Hi(),t=rt(),n=wm(),s=kn(),a=Fv(),i=Bv(),o=qv(),c=zv(),l=Hv(),u=Wv(),d=Gv(),h=Jv(),f=Zt(),p=Vv(),g=Kv(),_=xu(),b=Zv(),m=Xv(),y=Gi(),T=Au(),x=bm(),R=vm(),$=Iu(),E=Ru(),J=Sm(),se=Yv(),H=Ji(),Ae=Xt(),ft=Vi(),M=e0(),P=t0(),N=r0(),W=n0(),V=s0(),z=Ou(),ee=a0(),de=i0(),oe=o0(),ye=c0(),Ce=l0();return kc={parse:s,valid:a,clean:i,inc:o,diff:c,major:l,minor:u,patch:d,prerelease:h,compare:f,rcompare:p,compareLoose:g,compareBuild:_,sort:b,rsort:m,gt:y,lt:T,eq:x,neq:R,gte:$,lte:E,cmp:J,coerce:se,Comparator:H,Range:Ae,satisfies:ft,toComparators:M,maxSatisfying:P,minSatisfying:N,minVersion:W,validRange:V,outside:z,gtr:ee,ltr:de,intersects:oe,simplifyRange:ye,subset:Ce,SemVer:t,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers},kc}u0();function Er(r){if(!r||r.split("/").length>2||r.startsWith("/")||r.endsWith("/")||r.split(":").length>2)throw new Error(`Invalid identifier format: ${r}`);const[e,t]=r.split(":"),n=t||"latest";if(e.includes("/")){const[s,a]=e.split("/",2);if(!s||!a)throw new Error(`Invalid identifier format: ${r}`);return[s,a,n]}else{if(!e)throw new Error(`Invalid identifier format: ${r}`);return["-",e,n]}}class d0 extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function Z(r,e,t){let n;if(r.ok){t&&(n=await r.text());return}if(r.status===403)try{const i=await r.json();(i==null?void 0:i.error)==="org_scoped_key_requires_workspace"&&(n="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(`${r.status} ${r.statusText}`);throw o.status=r==null?void 0:r.status,o}if(n===void 0)try{n=await r.text()}catch{n=""}const s=`Failed to ${e}. Received status [${r.status}]: ${r.statusText}. Message: ${n}`;if(r.status===409)throw new d0(s);const a=new Error(s);throw a.status=r.status,a}const Em="ERR_CONFLICTING_ENDPOINTS";class h0 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:Em}),this.name="ConflictingEndpointsError"}}function f0(r){return typeof r=="object"&&r!==null&&r.code===Em}var Xh="[...]",p0={result:"[Circular]"},di=[],Sn=[];const m0=new TextEncoder;function g0(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function ma(r){return m0.encode(r)}function Tm(r){if(r&&typeof r=="object"&&r!==null){if(r instanceof Map)return Object.fromEntries(r);if(r instanceof Set)return Array.from(r);if(r instanceof Date)return r.toISOString();if(r instanceof RegExp)return r.toString();if(r instanceof Error)return{name:r.name,message:r.message}}else if(typeof r=="bigint")return r.toString();return r}function _0(r){return function(e,t){return Tm(t)}}function pt(r,e,t,n,s){var a;try{const i=JSON.stringify(r,_0(t),n);return ma(i)}catch(i){if(!((a=i.message)!=null&&a.includes("Converting circular structure to JSON")))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
17
+ Context: ${e}`:""}`),ma("[Unserializable]");ct("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
18
+ Context: ${e}`:""}`),typeof s>"u"&&(s=g0()),yl(r,"",0,[],void 0,0,s);let o;try{Sn.length===0?o=JSON.stringify(r,t,n):o=JSON.stringify(r,y0(t),n)}catch{return ma("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;di.length!==0;){const c=di.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return ma(o)}}function Pc(r,e,t,n){var s=Object.getOwnPropertyDescriptor(n,t);s.get!==void 0?s.configurable?(Object.defineProperty(n,t,{value:r}),di.push([n,t,e,s])):Sn.push([e,t,r]):(n[t]=r,di.push([n,t,e]))}function yl(r,e,t,n,s,a,i){a+=1;var o;if(typeof r=="object"&&r!==null){for(o=0;o<n.length;o++)if(n[o]===r){Pc(p0,r,e,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){Pc(Xh,r,e,s);return}if(typeof i.edgesLimit<"u"&&t+1>i.edgesLimit){Pc(Xh,r,e,s);return}if(n.push(r),Array.isArray(r))for(o=0;o<r.length;o++)yl(r[o],o,o,n,r,a,i);else{r=Tm(r);var c=Object.keys(r);for(o=0;o<c.length;o++){var l=c[o];yl(r[l],l,o,n,r,a,i)}}n.pop()}}function y0(r){return r=typeof r<"u"?r:function(e,t){return t},function(e,t){if(Sn.length>0)for(var n=0;n<Sn.length;n++){var s=Sn[n];if(s[1]===e&&s[0]===t){t=s[2],Sn.splice(n,1);break}}return r.call(this,e,t)}}function Yh(r,e){const t=pm(),n=e??mm(),s=r.extra??{},a=s.metadata;return r.extra={...s,runtime:{...t,...s==null?void 0:s.runtime},metadata:{...n,...n.revision_id||"revision_id"in r&&r.revision_id?{revision_id:("revision_id"in r?r.revision_id:void 0)??n.revision_id}:{},...a}},r}const w0=r=>{const e=(r==null?void 0:r.toString())??ct("TRACING_SAMPLING_RATE");if(e===void 0)return;const t=parseFloat(e);if(t<0||t>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},b0=r=>{const t=r.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return t==="localhost"||t==="127.0.0.1"||t==="::1"};async function v0(r){const e=[];for await(const t of r)e.push(t);return e}function ga(r){if(r!==void 0)return r.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const S0=async r=>{if((r==null?void 0:r.status)===429){const e=parseInt(r.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};function Qh(r){return typeof r=="number"?Number(r.toFixed(4)):r}class E0{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t;const n=new Promise(a=>{t=a}),s=pt(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:n,size:s}),this.sizeBytes+=s,n}pop({upToSizeBytes:e,upToSize:t}){var a;if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const n=[];let s=0;for(;s+(((a=this.peek())==null?void 0:a.size)??0)<e&&this.items.length>0&&n.length<t;){const i=this.items.shift();i&&(n.push(i),s+=i.size,this.sizeBytes-=i.size)}if(n.length===0&&this.items.length>0){const i=this.items.shift();n.push(i),s+=i.size,this.sizeBytes-=i.size}return[n.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl})),()=>n.forEach(i=>i.itemPromiseResolve())]}}const T0=24*1024*1024,x0=1e4,A0=100,ef="https://api.smith.langchain.com";class $s{get _fetch(){return this.fetchImplementation||cv(this.debug)}constructor(e={}){var n;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new E0}),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:ir("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:ir("LANGSMITH_DEBUG")==="true"});const t=$s.getDefaultClientConfig();if(this.tracingSampleRate=w0(e.tracingSamplingRate),this.apiUrl=ga(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=ga(e.apiKey??t.apiKey),this.webUrl=ga(e.webUrl??t.webUrl),(n=this.webUrl)!=null&&n.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=ga(e.workspaceId??ct("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new rh({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.batchIngestCaller=new rh({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:S0,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,gm()&&(this.langSmithToOTELTranslator=new xv),this.cachedLSEnvVarsForMetadata=mm()}static getDefaultClientConfig(){const e=ct("API_KEY"),t=ct("ENDPOINT")??ef,n=ct("HIDE_INPUTS")==="true",s=ct("HIDE_OUTPUTS")==="true";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:b0(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/${dm}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){const n=(t==null?void 0:t.toString())??"",s=`${this.apiUrl}${e}?${n}`;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 Z(i,`fetch ${e}`),i})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,n){let s=Number(t.get("offset"))||0;const a=Number(t.get("limit"))||100;for(;;){t.set("offset",String(s)),t.set("limit",String(a));const i=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{const l=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(l,`fetch ${e}`),l}),c=n?n(await o.json()):await o.json();if(c.length===0||(yield c,c.length<a))break;s+=c.length}}async*_getCursorPaginatedList(e,t=null,n="POST",s="runs"){const a=t?{...t}:{};for(;;){const i=JSON.stringify(a),c=await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await Z(u,`fetch ${e}`),u})).json();if(!c||!c[s])break;yield c[s];const l=c.cursors;if(!l||!l.next)break;a.cursor=l.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){const n=[];for(const s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):n.push(s);return n}else{const n=[];for(const s of e){const a=s.trace_id??s.id;this.filteredPostUuids.has(a)||(s.id===a?this._shouldSample()?n.push(s):this.filteredPostUuids.add(a):n.push(s))}return n}}async _getBatchSizeLimitBytes(){var t;const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??((t=e.batch_ingest_config)==null?void 0:t.size_limit_bytes)??T0}async _getBatchSizeLimit(){var t;const e=await this._ensureServerInfo();return this.batchSizeLimit??((t=e.batch_ingest_config)==null?void 0:t.size_limit)??A0}async _getDatasetExamplesMultiPartSupport(){var t;return((t=(await this._ensureServerInfo()).instance_flags)==null?void 0:t.dataset_examples_multipart_enabled)??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){const n=[];for(;this.autoBatchQueue.items.length>0;){const[s,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!s.length){a();break}const i=s.reduce((l,u)=>{const d=u.apiUrl??this.apiUrl,h=u.apiKey??this.apiKey,p=u.apiKey===this.apiKey&&u.apiUrl===this.apiUrl?"default":`${d}|${h}`;return l[p]||(l[p]=[]),l[p].push(u),l},{}),o=[];for(const[l,u]of Object.entries(i)){const d=this._processBatch(u,{apiUrl:l==="default"?void 0:l.split("|")[0],apiKey:l==="default"?void 0:l.split("|")[1]});o.push(d)}const c=Promise.all(o).finally(a);n.push(c)}return Promise.all(n)}async _processBatch(e,t){var n,s;if(e.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const a={runCreates:e.filter(o=>o.action==="create").map(o=>o.item),runUpdates:e.filter(o=>o.action==="update").map(o=>o.item)},i=await this._ensureServerInfo();if((n=i==null?void 0:i.batch_ingest_config)!=null&&n.use_multipart_endpoint){const o=(s=i==null?void 0:i.instance_flags)==null?void 0:s.gzip_body_enabled;await this.multipartIngestRuns(a,{...t,useGzip:o})}else await this.batchIngestRuns(a,t)}}catch(a){console.error("Error exporting batch:",a)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const t=new Map,n=[];for(const s of e)s.item.id&&s.otelContext&&(t.set(s.item.id,s.otelContext),s.action==="create"?n.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):n.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(n,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Yh(e.item,this.cachedLSEnvVarsForMetadata);const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const n=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const t=await(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(x0),...this.fetchOptions});return await Z(n,"get server info"),n})).json();return this.debug&&console.log(`
19
+ === LangSmith Server Configuration ===
20
+ `+JSON.stringify(t,null,2)+`
21
+ `),t}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){const e=_m(),t=vv();if(this.langSmithToOTELTranslator!==void 0){const n=e.getActiveSpan();if(n)return e.setSpan(t.active(),n)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;const n={...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:t==null?void 0:t.apiKey,apiUrl:t==null?void 0:t.apiUrl}).catch(console.error);return}const i=Yh(a,this.cachedLSEnvVarsForMetadata);(t==null?void 0:t.apiKey)!==void 0&&(n["x-api-key"]=t.apiKey),(t==null?void 0:t.workspaceId)!==void 0&&(n["x-tenant-id"]=t.workspaceId);const o=pt(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${(t==null?void 0:t.apiUrl)??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await Z(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;let s=await Promise.all((e==null?void 0:e.map(c=>this.prepareRunCreateOrUpdateInputs(c)))??[]),a=await Promise.all((t==null?void 0:t.map(c=>this.prepareRunCreateOrUpdateInputs(c)))??[]);if(s.length>0&&a.length>0){const c=s.reduce((u,d)=>(d.id&&(u[d.id]=d),u),{}),l=[];for(const u of a)u.id!==void 0&&c[u.id]?c[u.id]={...c[u.id],...u}:l.push(u);s=Object.values(c),a=l}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 l=c,u=i[l].reverse();let d=u.pop();for(;d!==void 0;)o[l].push(d),d=u.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(l=>l.id).concat(o.patch.map(l=>l.id)).join(",");await this._postBatchIngestRuns(pt(o,`Ingesting runs with ids: ${c}`),n)}}async _postBatchIngestRuns(e,t){const n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};(t==null?void 0:t.apiKey)!==void 0&&(n["x-api-key"]=t.apiKey),await this.batchIngestCaller.call(async()=>{const s=await this._fetch(`${(t==null?void 0:t.apiUrl)??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await Z(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;const s={};let a=[];for(const d of e??[]){const h=await this.prepareRunCreateOrUpdateInputs(d);h.id!==void 0&&h.attachments!==void 0&&(s[h.id]=h.attachments),delete h.attachments,a.push(h)}let i=[];for(const d of t??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(a.length>0&&i.length>0){const d=a.reduce((f,p)=>(p.id&&(f[p.id]=p),f),{}),h=[];for(const f of i)f.id!==void 0&&d[f.id]?d[f.id]={...d[f.id],...f}:h.push(f);a=Object.values(d),i=h}if(a.length===0&&i.length===0)return;const l=[],u=[];for(const[d,h]of[["post",a],["patch",i]])for(const f of h){const{inputs:p,outputs:g,events:_,extra:b,error:m,serialized:y,attachments:T,...x}=f,R={inputs:p,outputs:g,events:_,extra:b,error:m,serialized:y},$=pt(x,`Serializing for multipart ingestion of run with id: ${x.id}`);u.push({name:`${d}.${x.id}`,payload:new Blob([$],{type:`application/json; length=${$.length}`})});for(const[E,J]of Object.entries(R)){if(J===void 0)continue;const se=pt(J,`Serializing ${E} for multipart ingestion of run with id: ${x.id}`);u.push({name:`${d}.${x.id}.${E}`,payload:new Blob([se],{type:`application/json; length=${se.length}`})})}if(x.id!==void 0){const E=s[x.id];if(E){delete s[x.id];for(const[J,se]of Object.entries(E)){let H,Ae;if(Array.isArray(se)?[H,Ae]=se:(H=se.mimeType,Ae=se.data),J.includes(".")){console.warn(`Skipping attachment '${J}' for run ${x.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}u.push({name:`attachment.${x.id}.${J}`,payload:new Blob([Ae],{type:`${H}; length=${Ae.byteLength}`})})}}}l.push(`trace=${x.trace_id},id=${x.id}`)}await this._sendMultipartRequest(u,l.join("; "),n)}async _createNodeFetchBody(e,t){const n=[];for(const i of e)n.push(new Blob([`--${t}\r
22
+ `])),n.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
23
+ `,`Content-Type: ${i.payload.type}\r
24
+ \r
25
+ `])),n.push(i.payload),n.push(new Blob([`\r
26
+ `]));return n.push(new Blob([`--${t}--\r
27
+ `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,t){const n=new TextEncoder;return new ReadableStream({async start(a){const i=async o=>{typeof o=="string"?a.enqueue(n.encode(o)):a.enqueue(o)};for(const o of e){await i(`--${t}\r
28
+ `),await i(`Content-Disposition: form-data; name="${o.name}"\r
29
+ `),await i(`Content-Type: ${o.payload.type}\r
30
+ \r
31
+ `);const l=o.payload.stream().getReader();try{let u;for(;!(u=await l.read()).done;)a.enqueue(u.value)}finally{l.releaseLock()}await i(`\r
32
+ `)}await i(`--${t}--\r
33
+ `),a.close()}})}async _sendMultipartRequest(e,t,n){const s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=ov(),i=()=>this._createNodeFetchBody(e,s),o=()=>this._createMultipartStream(e,s),c=async l=>this.batchIngestCaller.call(async()=>{const u=await l(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${s}`};(n==null?void 0:n.apiKey)!==void 0&&(d["x-api-key"]=n.apiKey);let h=u;n!=null&&n.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(h=u.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const f=await this._fetch(`${(n==null?void 0:n.apiUrl)??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:h,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(f,"Failed to send multipart request",!0),f});try{let l,u=!1;!a&&!this.multipartStreamingDisabled&&fm()!=="bun"?(u=!0,l=await c(o)):l=await c(i),(!this.multipartStreamingDisabled||u)&&l.status===422&&((n==null?void 0:n.apiUrl)??this.apiUrl)!==ef&&(console.warn(`Streaming multipart upload to ${(n==null?void 0:n.apiUrl)??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${t}".`),this.multipartStreamingDisabled=!0,l=await c(i))}catch(l){console.warn(`${l.message.trim()}
34
+
35
+ Context: ${t}`)}}async updateRun(e,t,n){le(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const s={...t,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(t.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:n==null?void 0:n.apiKey,apiUrl:n==null?void 0:n.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:n==null?void 0:n.apiKey,apiUrl:n==null?void 0:n.apiUrl}).catch(console.error);return}const a={...this.headers,"Content-Type":"application/json"};(n==null?void 0:n.apiKey)!==void 0&&(a["x-api-key"]=n.apiKey),(n==null?void 0:n.workspaceId)!==void 0&&(a["x-tenant-id"]=n.workspaceId);const i=pt(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${(n==null?void 0:n.apiUrl)??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await Z(o,"update run",!0),o})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){le(e);let n=await this._get(`/runs/${e}`);return t&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:t,projectOpts:n}){if(t!==void 0){let s;t.session_id?s=t.session_id:n!=null&&n.projectName?s=(await this.readProject({projectName:n==null?void 0:n.projectName})).id:n!=null&&n.projectId?s=n==null?void 0:n.projectId:s=(await this.readProject({projectName:ct("PROJECT")||"default"})).id;const a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${s}/r/${t.id}?poll=true`}else if(e!==void 0){const s=await this.readRun(e);if(!s.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${s.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){var a;const t=await v0(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},s={};t.sort((i,o)=>((i==null?void 0:i.dotted_order)??"").localeCompare((o==null?void 0:o.dotted_order)??""));for(const i of t){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);(a=i.dotted_order)!=null&&a.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),s[i.id]=i)}e.child_runs=n[e.id]||[];for(const i in n)i!==e.id&&(s[i].child_runs=n[i]);return e}async*listRuns(e){const{projectId:t,projectName:n,parentRunId:s,traceId:a,referenceExampleId:i,startTime:o,executionOrder:c,isRoot:l,runType:u,error:d,id:h,query:f,filter:p,traceFilter:g,treeFilter:_,limit:b,select:m,order:y}=e;let T=[];if(t&&(T=Array.isArray(t)?t:[t]),n){const E=Array.isArray(n)?n:[n],J=await Promise.all(E.map(se=>this.readProject({projectName:se}).then(H=>H.id)));T.push(...J)}const x=["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"],R={session:T.length?T:null,run_type:u,reference_example:i,query:f,filter:p,trace_filter:g,tree_filter:_,execution_order:c,parent_run:s,start_time:o?o.toISOString():null,error:d,id:h,limit:b,trace:a,select:m||x,is_root:l,order:y};let $=0;for await(const E of this._getCursorPaginatedList("/runs/query",R))if(b){if($>=b)break;if(E.length+$>b){yield*E.slice(0,b-$);break}$+=E.length,yield*E}else yield*E}async*listGroupRuns(e){const{projectId:t,projectName:n,groupBy:s,filter:a,startTime:i,endTime:o,limit:c,offset:l}=e,d={session_id:t||(await this.readProject({projectName:n})).id,group_by:s,filter:a,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let h=Number(l)||0;const f="/runs/group",p=`${this.apiUrl}${f}`;for(;;){const g={...d,offset:h},_=Object.fromEntries(Object.entries(g).filter(([R,$])=>$!==void 0)),b=JSON.stringify(_),y=await(await this.caller.call(async()=>{const R=await this._fetch(p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await Z(R,`Failed to fetch ${f}`),R})).json(),{groups:T,total:x}=y;if(T.length===0)break;for(const R of T)yield R;if(h+=T.length,h>=x)break}}async getRunStats({id:e,trace:t,parentRun:n,runType:s,projectNames:a,projectIds:i,referenceExampleIds:o,startTime:c,endTime:l,error:u,query:d,filter:h,traceFilter:f,treeFilter:p,isRoot:g,dataSourceType:_}){let b=i||[];a&&(b=[...i||[],...await Promise.all(a.map($=>this.readProject({projectName:$}).then(E=>E.id)))]);const y=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:n,run_type:s,session:b,reference_example:o,start_time:c,end_time:l,error:u,query:d,filter:h,trace_filter:f,tree_filter:p,is_root:g,data_source_type:_}).filter(([$,E])=>E!==void 0)),T=JSON.stringify(y);return await(await this.caller.call(async()=>{const $=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:T});return await Z($,"get run stats"),$})).json()}async shareRun(e,{shareId:t}={}){const n={run_id:e,share_token:t||pn()};le(e);const s=JSON.stringify(n),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 Z(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){le(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(t,"unshare run",!0),t})}async readRunSharedLink(e){le(e);const n=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 Z(s,"read run shared link"),s})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){const n=new URLSearchParams({share_token:e});if(t!==void 0)for(const i of t)n.append("id",i);return le(e),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),le(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 Z(a,"read dataset shared schema"),a})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);const n={dataset_id:e};le(e);const s=JSON.stringify(n),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 Z(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){le(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(t,"unshare dataset",!0),t})}async readSharedDataset(e){return le(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 Z(s,"read shared dataset"),s})).json()}async listSharedExamples(e,t){const n={};t!=null&&t.exampleIds&&(n.id=t.exampleIds);const s=new URLSearchParams;Object.entries(n).forEach(([o,c])=>{Array.isArray(c)?c.forEach(l=>s.append(o,l)):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 Z(o,"list shared examples"),o}),i=await a.json();if(!a.ok)throw"detail"in i?new Error(`Failed to list shared examples.
36
+ Status: ${a.status}
37
+ Message: ${Array.isArray(i.detail)?i.detail.join(`
38
+ `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:n=null,upsert:s=!1,projectExtra:a=null,referenceDatasetId:i=null}){const o=s?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,l=a||{};n&&(l.metadata=n);const u={name:e,extra:l,description:t};i!==null&&(u.reference_dataset_id=i);const d=JSON.stringify(u);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 Z(p,"create project"),p})).json()}async updateProject(e,{name:t=null,description:n=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 l=JSON.stringify({name:t,extra:c,description:n,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const h=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Z(h,"update project"),h})).json()}async hasProject({projectId:e,projectName:t}){let n="/sessions";const s=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)le(e),n+=`/${e}`;else if(t!==void 0)s.append("name",t);else throw new Error("Must provide projectName or projectId");const a=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${n}?${s}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(i,"has project"),i});try{const i=await a.json();return a.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:t,includeStats:n}){let s="/sessions";const a=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)le(e),s+=`/${e}`;else if(t!==void 0)a.append("name",t);else throw new Error("Must provide projectName or projectId");n!==void 0&&a.append("include_stats",n.toString());const i=await this._get(s,a);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${e}, name=${t}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either projectName or projectId");const n=await this.readProject({projectId:e,projectName:t}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");const n=await this.readDataset({datasetId:e,datasetName:t}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:n,referenceDatasetId:s,referenceDatasetName:a,includeStats:i,datasetVersion:o,referenceFree:c,metadata:l}={}){const u=new URLSearchParams;if(e!==void 0)for(const d of e)u.append("id",d);if(t!==void 0&&u.append("name",t),n!==void 0&&u.append("name_contains",n),s!==void 0)u.append("reference_dataset",s);else if(a!==void 0){const d=await this.readDataset({datasetName:a});u.append("reference_dataset",d.id)}i!==void 0&&u.append("include_stats",i.toString()),o!==void 0&&u.append("dataset_version",o),c!==void 0&&u.append("reference_free",c.toString()),l!==void 0&&u.append("metadata",JSON.stringify(l));for await(const d of this._getPaginated("/sessions",u))yield*d}async deleteProject({projectId:e,projectName:t}){let n;if(e===void 0&&t===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:t})).id:n=e,le(n),await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(s,`delete session ${n} (${t})`,!0),s})}async uploadCsv({csvFile:e,fileName:t,inputKeys:n,outputKeys:s,description:a,dataType:i,name:o}){const c=`${this.apiUrl}/datasets/upload`,l=new FormData;return l.append("file",e,t),n.forEach(h=>{l.append("input_keys",h)}),s.forEach(h=>{l.append("output_keys",h)}),a&&l.append("description",a),i&&l.append("data_type",i),o&&l.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:l});return await Z(h,"upload CSV"),h})).json()}async createDataset(e,{description:t,dataType:n,inputsSchema:s,outputsSchema:a,metadata:i}={}){const o={name:e,description:t,extra:i?{metadata:i}:void 0};n&&(o.data_type=n),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 Z(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:t}){let n="/datasets";const s=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)le(e),n+=`/${e}`;else if(t)s.append("name",t);else throw new Error("Must provide datasetName or datasetId");const a=await this._get(n,s);let i;if(Array.isArray(a)){if(a.length===0)throw new Error(`Dataset[id=${e}, name=${t}] not found`);i=a[0]}else i=a;return i}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:n,toVersion:s}){let a=e;if(a===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:t})).id);const i=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${a}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){const n="/datasets";if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
39
+ `).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:n,datasetName:s,datasetNameContains:a,metadata:i}={}){const o="/datasets",c=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(n!==void 0)for(const l of n)c.append("id",l);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 l of this._getPaginated(o,c))yield*l}async updateDataset(e){const{datasetId:t,datasetName:n,...s}=e;if(!t&&!n)throw new Error("Must provide either datasetName or datasetId");const a=t??(await this.readDataset({datasetName:n})).id;le(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 Z(c,"update dataset"),c})).json()}async updateDatasetTag(e){const{datasetId:t,datasetName:n,asOf:s,tag:a}=e;if(!t&&!n)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:n})).id;le(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 Z(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:t}){let n="/datasets",s=e;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0&&(s=(await this.readDataset({datasetName:t})).id),s!==void 0)le(s),n+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const a=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(a,`delete ${n}`,!0),a})}async indexDataset({datasetId:e,datasetName:t,tag:n}){let s=e;if(!s&&!t)throw new Error("Must provide either datasetName or datasetId");if(s&&t)throw new Error("Must provide either datasetName or datasetId, not both");s||(s=(await this.readDataset({datasetName:t})).id),le(s);const i=JSON.stringify({tag:n});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 Z(c,"index dataset"),c})).json()}async similarExamples(e,t,n,{filter:s}={}){const a={limit:n,inputs:e};s!==void 0&&(a.filter=s),le(t);const i=JSON.stringify(a);return(await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${t}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await Z(l,"fetch similar examples"),l})).json()).examples}async createExample(e,t,n){var u;if(tf(e)&&(t!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=t?n==null?void 0:n.datasetId:e.dataset_id;const a=t?n==null?void 0:n.datasetName:e.dataset_name;if(s===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:a})).id);const i=(t?n==null?void 0:n.createdAt:e.created_at)||new Date;let o;tf(e)?o=e:o={inputs:e,outputs:t,created_at:i==null?void 0:i.toISOString(),id:n==null?void 0:n.exampleId,metadata:n==null?void 0:n.metadata,split:n==null?void 0:n.split,source_run_id:n==null?void 0:n.sourceRunId,use_source_run_io:n==null?void 0:n.useSourceRunIO,use_source_run_attachments:n==null?void 0:n.useSourceRunAttachments,attachments:n==null?void 0:n.attachments};const c=await this._uploadExamplesMultipart(s,[o]);return await this.readExample(((u=c.example_ids)==null?void 0:u[0])??pn())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const m=e;let y=m[0].dataset_id;const T=m[0].dataset_name;if(y===void 0&&T===void 0)throw new Error("Must provide either datasetName or datasetId");if(y!==void 0&&T!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");y===void 0&&(y=(await this.readDataset({datasetName:T})).id);const x=await this._uploadExamplesMultipart(y,m);return await Promise.all(x.example_ids.map($=>this.readExample($)))}const{inputs:t,outputs:n,metadata:s,splits:a,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:l,exampleIds:u,datasetId:d,datasetName:h}=e;if(t===void 0)throw new Error("Must provide inputs when using legacy parameters");let f=d;const p=h;if(f===void 0&&p===void 0)throw new Error("Must provide either datasetName or datasetId");if(f!==void 0&&p!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");f===void 0&&(f=(await this.readDataset({datasetName:p})).id);const g=t.map((m,y)=>({dataset_id:f,inputs:m,outputs:n==null?void 0:n[y],metadata:s==null?void 0:s[y],split:a==null?void 0:a[y],id:u==null?void 0:u[y],attachments:l==null?void 0:l[y],source_run_id:i==null?void 0:i[y],use_source_run_io:o==null?void 0:o[y],use_source_run_attachments:c==null?void 0:c[y]})),_=await this._uploadExamplesMultipart(f,g);return await Promise.all(_.example_ids.map(m=>this.readExample(m)))}async createLLMExample(e,t,n){return this.createExample({input:e},{output:t},n)}async createChatExample(e,t,n){const s=e.map(i=>nh(i)?sh(i):i),a=nh(t)?sh(t):t;return this.createExample({input:s},{output:a},n)}async readExample(e){le(e);const t=`/examples/${e}`,n=await this._get(t),{attachment_urls:s,...a}=n,i=a;return s&&(i.attachments=Object.entries(s).reduce((o,[c,l])=>(o[c.slice(11)]={presigned_url:l.presigned_url,mime_type:l.mime_type},o),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:n,asOf:s,splits:a,inlineS3Urls:i,metadata:o,limit:c,offset:l,filter:u,includeAttachments:d}={}){let h;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)h=e;else if(t!==void 0)h=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide a datasetName or datasetId");const f=new URLSearchParams({dataset:h}),p=s?typeof s=="string"?s:s==null?void 0:s.toISOString():void 0;p&&f.append("as_of",p);const g=i??!0;if(f.append("inline_s3_urls",g.toString()),n!==void 0)for(const b of n)f.append("id",b);if(a!==void 0)for(const b of a)f.append("splits",b);if(o!==void 0){const b=JSON.stringify(o);f.append("metadata",b)}c!==void 0&&f.append("limit",c.toString()),l!==void 0&&f.append("offset",l.toString()),u!==void 0&&f.append("filter",u),d===!0&&["attachment_urls","outputs","metadata"].forEach(b=>f.append("select",b));let _=0;for await(const b of this._getPaginated("/examples",f)){for(const m of b){const{attachment_urls:y,...T}=m,x=T;y&&(x.attachments=Object.entries(y).reduce((R,[$,E])=>(R[$.slice(11)]={presigned_url:E.presigned_url,mime_type:E.mime_type||void 0},R),{})),yield x,_++}if(c!==void 0&&_>=c)break}}async deleteExample(e){le(e);const t=`/examples/${e}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(n,`delete ${t}`,!0),n})}async updateExample(e,t){let n;t?n=e:n=e.id,le(n);let s;t?s={id:n,...t}:s=e;let a;return s.dataset_id!==void 0?a=s.dataset_id:a=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(a,[s])}async updateExamples(e){let t;return e[0].dataset_id===void 0?t=(await this.readExample(e[0].id)).dataset_id:t=e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:n,tag:s}){let a;if(e?a=e:a=(await this.readDataset({datasetName:t})).id,le(a),n&&s||!n&&!s)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return n!==void 0&&i.append("as_of",typeof n=="string"?n:n.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 Z(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:n}){let s;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:t})).id:s=e,le(s);const a=new URLSearchParams,i=n?typeof n=="string"?n:n==null?void 0:n.toISOString():void 0;return i&&a.append("as_of",i),await this._get(`/datasets/${s}/splits`,a)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:n,exampleIds:s,remove:a=!1}){let i;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:t})).id:i=e,le(i);const o={split_name:n,examples:s.map(l=>(le(l),l)),remove:a},c=JSON.stringify(o);await this.caller.call(async()=>{const l=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 Z(l,"update dataset splits",!0),l})}async evaluateRun(e,t,{sourceInfo:n,loadChildRuns:s,referenceExample:a}={loadChildRuns:!1}){ym("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let i;if(typeof e=="string")i=await this.readRun(e,{loadChildRuns:s});else if(typeof e=="object"&&"id"in e)i=e;else throw new Error(`Invalid run type: ${typeof e}`);i.reference_example_id!==null&&i.reference_example_id!==void 0&&(a=await this.readExample(i.reference_example_id));const o=await t.evaluateRun(i,a),[c,l]=await this._logEvaluationFeedback(o,i,n);return l[0]}async createFeedback(e,t,{score:n,value:s,correction:a,comment:i,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:l,feedbackId:u,feedbackConfig:d,projectId:h,comparativeExperimentId:f}){var m;if(!e&&!h)throw new Error("One of runId or projectId must be provided");if(e&&h)throw new Error("Only one of runId or projectId can be provided");const p={type:c??"api",metadata:o??{}};l!==void 0&&(p==null?void 0:p.metadata)!==void 0&&!p.metadata.__run&&(p.metadata.__run={run_id:l}),(p==null?void 0:p.metadata)!==void 0&&((m=p.metadata.__run)==null?void 0:m.run_id)!==void 0&&le(p.metadata.__run.run_id);const g={id:u??pn(),run_id:e,key:t,score:Qh(n),value:s,correction:a,comment:i,feedback_source:p,comparative_experiment_id:f,feedbackConfig:d,session_id:h},_=JSON.stringify(g),b=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const y=await this._fetch(b,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await Z(y,"create feedback",!0),y}),g}async updateFeedback(e,{score:t,value:n,correction:s,comment:a}){const i={};t!=null&&(i.score=Qh(t)),n!=null&&(i.value=n),s!=null&&(i.correction=s),a!=null&&(i.comment=a),le(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 Z(c,"update feedback",!0),c})}async readFeedback(e){le(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){le(e);const t=`/feedback/${e}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(n,`delete ${t}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:n}={}){const s=new URLSearchParams;if(e)for(const a of e)le(a),s.append("run",a);if(t)for(const a of t)s.append("key",a);if(n)for(const a of n)s.append("source",a);for await(const a of this._getPaginated("/feedback",s))yield*a}async createPresignedFeedbackToken(e,t,{expiration:n,feedbackConfig:s}={}){const a={run_id:e,feedback_key:t,feedback_config:s};n?typeof n=="string"?a.expires_at=n:(n!=null&&n.hours||n!=null&&n.minutes||n!=null&&n.days)&&(a.expires_in=n):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 Z(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:n,createdAt:s,description:a,metadata:i,id:o}){var d;if(t.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:t[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");const c={id:o,name:e,experiment_ids:t,reference_dataset_id:n,description:a,created_at:(d=s??new Date)==null?void 0:d.toISOString(),extra:{}};i&&(c.extra.metadata=i);const l=JSON.stringify(c);return(await this.caller.call(async()=>{const h=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:l});return await Z(h,"create comparative experiment"),h})).json()}async*listPresignedFeedbackTokens(e){le(e);const t=new URLSearchParams({run_id:e});for await(const n of this._getPaginated("/feedback/tokens",t))yield*n}_selectEvalResults(e){let t;return"results"in e?t=e.results:Array.isArray(e)?t=e:t=[e],t}async _logEvaluationFeedback(e,t,n){const s=this._selectEvalResults(e),a=[];for(const i of s){let o=n||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let c=null;i.targetRunId?c=i.targetRunId:t&&(c=t.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,t,n){const[s]=await this._logEvaluationFeedback(e,t,n);return s}async*listAnnotationQueues(e={}){const{queueIds:t,name:n,nameContains:s,limit:a}=e,i=new URLSearchParams;t&&t.forEach((c,l)=>{le(c,`queueIds[${l}]`),i.append("ids",c)}),n&&i.append("name",n),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:t,description:n,queueId:s,rubricInstructions:a}=e,i={name:t,description:n,id:s||pn(),rubric_instructions:a},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([l,u])=>u!==void 0)));return(await this.caller.call(async()=>{const l=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 Z(l,"create annotation queue"),l})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${le(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,t){const{name:n,description:s,rubricInstructions:a}=t,i=JSON.stringify({name:n,description:s,rubric_instructions:a});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${le(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await Z(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${le(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){const n=JSON.stringify(t.map((s,a)=>le(s,`runIds[${a}]`).toString()));await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/annotation-queues/${le(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await Z(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,t){const n=`/annotation-queues/${le(e,"queueId")}/run`;return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${n}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(a,"get run from annotation queue"),a})).json()}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${le(e,"queueId")}/runs/${le(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${le(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return e=="-"||t.tenant_handle===e}async _ownerConflictError(e,t){const n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
40
+
41
+ Current tenant: ${n.tenant_handle}
42
+
43
+ Requested tenant: ${t}`)}async _getLatestCommitHash(e){const n=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 Z(s,"get latest commit hash"),s})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[n,s,a]=Er(e),i=JSON.stringify({like:t});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${n}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await Z(c,`${t?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){const[t,n,s]=Er(e);if(await this._currentTenantIsOwner(t)){const a=await this._getSettings();return s!=="latest"?`${this.getHostUrl()}/prompts/${n}/${s.substring(0,8)}?organizationId=${a.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${a.id}`}else return s!=="latest"?`${this.getHostUrl()}/hub/${t}/${n}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,n=>n.commits))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",(e==null?void 0:e.sortField)??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!(e!=null&&e.isArchived)).toString()),(e==null?void 0:e.isPublic)!==void 0&&t.append("is_public",e.isPublic.toString()),e!=null&&e.query&&t.append("query",e.query);for await(const n of this._getPaginated("/repos",t,s=>s.repos))yield*n}async getPrompt(e){const[t,n,s]=Er(e),a=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return(o==null?void 0:o.status)===404?null:(await Z(o,"get prompt"),o)}),i=await(a==null?void 0:a.json());return i!=null&&i.repo?i.repo:null}async createPrompt(e,t){const n=await this._getSettings();if(t!=null&&t.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
44
+
45
+ creating a LangChain Hub handle.
46
+ You can add a handle by creating a public prompt at:
47
+
48
+ https://smith.langchain.com/prompts`);const[s,a,i]=Er(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);const o={repo_handle:a,...(t==null?void 0:t.description)&&{description:t.description},...(t==null?void 0:t.readme)&&{readme:t.readme},...(t==null?void 0:t.tags)&&{tags:t.tags},is_public:!!(t!=null&&t.isPublic)},c=JSON.stringify(o),l=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 Z(d,"create prompt"),d}),{repo:u}=await l.json();return u}async createCommit(e,t,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[s,a,i]=Er(e),o=(n==null?void 0:n.parentCommitHash)==="latest"||!(n!=null&&n.parentCommitHash)?await this._getLatestCommitHash(`${s}/${a}`):n==null?void 0:n.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},l=JSON.stringify(c),d=await(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/commits/${s}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Z(h,"create commit"),h})).json();return this._getPromptUrl(`${s}/${a}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){var i;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 n=new FormData;for(const o of t){const c=o.id,l={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},u=pt(l,`Serializing body for example with id: ${c}`),d=new Blob([u],{type:"application/json"});if(n.append(c,d),o.inputs){const h=pt(o.inputs,`Serializing inputs for example with id: ${c}`),f=new Blob([h],{type:"application/json"});n.append(`${c}.inputs`,f)}if(o.outputs){const h=pt(o.outputs,`Serializing outputs whle updating example with id: ${c}`),f=new Blob([h],{type:"application/json"});n.append(`${c}.outputs`,f)}if(o.attachments)for(const[h,f]of Object.entries(o.attachments)){let p,g;Array.isArray(f)?[p,g]=f:(p=f.mimeType,g=f.data);const _=new Blob([g],{type:`${p}; length=${g.byteLength}`});n.append(`${c}.attachment.${h}`,_)}if(o.attachments_operations){const h=pt(o.attachments_operations,`Serializing attachments while updating example with id: ${c}`),f=new Blob([h],{type:"application/json"});n.append(`${c}.attachments_operations`,f)}}const s=e??((i=t[0])==null?void 0:i.dataset_id);return(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await Z(o,"update examples"),o})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const a of t){const i=(a.id??pn()).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=pt(o,`Serializing body for uploaded example with id: ${i}`),l=new Blob([c],{type:"application/json"});if(n.append(i,l),a.inputs){const u=pt(a.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([u],{type:"application/json"});n.append(`${i}.inputs`,d)}if(a.outputs){const u=pt(a.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([u],{type:"application/json"});n.append(`${i}.outputs`,d)}if(a.attachments)for(const[u,d]of Object.entries(a.attachments)){let h,f;Array.isArray(d)?[h,f]=d:(h=d.mimeType,f=d.data);const p=new Blob([f],{type:`${h}; length=${f.byteLength}`});n.append(`${i}.attachment.${u}`,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:n});return await Z(a,"upload examples"),a})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,s]=Er(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);const a={};if((t==null?void 0:t.description)!==void 0&&(a.description=t.description),(t==null?void 0:t.readme)!==void 0&&(a.readme=t.readme),(t==null?void 0:t.tags)!==void 0&&(a.tags=t.tags),(t==null?void 0:t.isPublic)!==void 0&&(a.is_public=t.isPublic),(t==null?void 0:t.isArchived)!==void 0&&(a.is_archived=t.isArchived),Object.keys(a).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(a);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${n}/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await Z(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[t,n,s]=Er(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(i,"delete prompt"),i})).json()}async pullPromptCommit(e,t){const[n,s,a]=Er(e),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${n}/${s}/${a}${t!=null&&t.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Z(c,"pull prompt commit"),c})).json();return{owner:n,repo:s,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){const n=await this.pullPromptCommit(e,{includeModel:t==null?void 0:t.includeModel});return JSON.stringify(n.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(s=>s!=="object")&&await this.updatePrompt(e,{description:t==null?void 0:t.description,readme:t==null?void 0:t.readme,tags:t==null?void 0:t.tags,isPublic:t==null?void 0:t.isPublic}):await this.createPrompt(e,{description:t==null?void 0:t.description,readme:t==null?void 0:t.readme,tags:t==null?void 0:t.tags,isPublic:t==null?void 0:t.isPublic}),t!=null&&t.object?await this.createCommit(e,t==null?void 0:t.object,{parentCommitHash:t==null?void 0:t.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){const{sourceApiUrl:n=this.apiUrl,datasetName:s}=t,[a,i]=this.parseTokenOrUrl(e,n),o=new $s({apiUrl:a,apiKey:"placeholder"}),c=await o.readSharedDataset(i),l=s||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}const u=await o.listSharedExamples(i),d=await this.createDataset(l,{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:u.map(h=>h.inputs),outputs:u.flatMap(h=>h.outputs?[h.outputs]:[]),datasetId:d.id})}catch(h){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),h}}parseTokenOrUrl(e,t,n=2,s="dataset"){try{return le(e),[t,e]}catch{}try{const i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=n){const o=i[i.length-n];return[t,o]}else throw new Error(`Invalid public ${s} URL: ${e}`)}catch{throw new Error(`Invalid public ${s} URL or token: ${e}`)}}async awaitPendingTraceBatches(){var e,t;if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:n})=>n),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await((t=(e=Sv())==null?void 0:e.DEFAULT_LANGSMITH_SPAN_PROCESSOR)==null?void 0:t.forceFlush())}}function tf(r){return"dataset_id"in r||"dataset_name"in r}const I0=r=>!!["TRACING_V2","TRACING"].find(t=>ct(t)==="true"),Nc=Symbol.for("lc:context_variables");function R0(r){return r.replace(/[-:.]/g,"")}function xm(r,e,t=1){const n=t.toFixed(0).slice(0,3).padStart(3,"0"),s=`${new Date(r).toISOString().slice(0,-1)}${n}Z`;return{dottedOrder:R0(s)+e,microsecondPrecisionDatestring:s}}class hi{constructor(e,t,n,s){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=n,this.replicas=s}static fromHeader(e){const t=e.split(",");let n={},s=[],a,i;for(const o of t){const[c,l]=o.split("="),u=decodeURIComponent(l);c==="langsmith-metadata"?n=JSON.parse(u):c==="langsmith-tags"?s=u.split(","):c==="langsmith-project"?a=u:c==="langsmith-replicas"&&(i=JSON.parse(u))}return new hi(n,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 it{constructor(e){var o;if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),O0(e)){Object.assign(this,{...e});return}const t=it.getDefaultConfig(),{metadata:n,...s}=e,a=s.client??it.getSharedClient(),i={...n,...(o=s==null?void 0:s.extra)==null?void 0:o.metadata};if(s.extra={...s.extra,metadata:i},Object.assign(this,{...t,...s,client:a}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=N0(this.replicas),this.execution_order??(this.execution_order=1),this.child_execution_order??(this.child_execution_order=1),!this.dotted_order){const{dottedOrder:c,microsecondPrecisionDatestring:l}=xm(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+c:this.dotted_order=c,this._serialized_start_time=l}}set metadata(e){var t;this.extra={...this.extra,metadata:{...(t=this.extra)==null?void 0:t.metadata,...e}}}get metadata(){var e;return(e=this.extra)==null?void 0:e.metadata}static getDefaultConfig(){return{id:pn(),run_type:"chain",project_name:um(),child_runs:[],api_url:ir("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:ir("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return it.sharedClient||(it.sharedClient=new $s),it.sharedClient}createChild(e){var c,l,u,d,h,f;const t=this.child_execution_order+1,n=new it({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});Nc in this&&(n[Nc]=this[Nc]);const s=Symbol.for("lc:child_config"),a=((c=e.extra)==null?void 0:c[s])??this.extra[s];if(C0(a)){const p={...a},g=$0(p.callbacks)?(u=(l=p.callbacks).copy)==null?void 0:u.call(l):void 0;g&&(Object.assign(g,{_parentRunId:n.id}),(f=(h=(d=g.handlers)==null?void 0:d.find(Am))==null?void 0:h.updateFromRunTree)==null||f.call(h,n),p.callbacks=g),n.extra[s]=p}const i=new Set;let o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,t),o=o.parent_run;return this.child_runs.push(n),n}async end(e,t,n=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??n,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,t,n=!0){var o,c;const s=e.extra??{};if(((o=s==null?void 0:s.runtime)==null?void 0:o.library)===void 0&&(s.runtime||(s.runtime={}),t))for(const[l,u]of Object.entries(t))s.runtime[l]||(s.runtime[l]=u);let a,i;return n?(i=((c=e.parent_run)==null?void 0:c.id)??e.parent_run_id,a=[]):(a=e.child_runs.map(l=>this._convertToCreate(l,t,n)),i=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:s,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_remapForProject(e,t,n=!0){const s=this._convertToCreate(this,t,n);if(e===this.project_name)return s;const a=d=>Ud(`${d}:${e}`,Ud.DNS),i=a(s.id),o=s.trace_id?a(s.trace_id):void 0,c=s.parent_run_id?a(s.parent_run_id):void 0;let l;if(s.dotted_order){const d=k0(s.dotted_order),h=[];for(let p=0;p<d.length-1;p++){const[g,_]=d[p],b=a(_);h.push(g.toISOString().replace(/[-:]/g,"").replace(".","")+b)}const[f]=d[d.length-1];h.push(f.toISOString().replace(/[-:]/g,"").replace(".","")+i),l=h.join(".")}else l=void 0;return{...s,id:i,trace_id:o,parent_run_id:c,dotted_order:l,session_name:e}}async postRun(e=!0){try{const t=pm();if(this.replicas&&this.replicas.length>0)for(const{projectName:n,apiKey:s,apiUrl:a,workspaceId:i}of this.replicas){const o=this._remapForProject(n??this.project_name,t,!0);await this.client.createRun(o,{apiKey:s,apiUrl:a,workspaceId:i})}else{const n=this._convertToCreate(this,t,e);await this.client.createRun(n)}if(!e){ym("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const n of this.child_runs)await n.postRun(!1)}}catch(t){console.error(`Error in postRun for run ${this.id}:`,t)}}async patchRun(e){var t;if(this.replicas&&this.replicas.length>0)for(const{projectName:n,apiKey:s,apiUrl:a,workspaceId:i,updates:o}of this.replicas){const c=this._remapForProject(n??this.project_name),l={id:c.id,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,...o};e!=null&&e.excludeInputs||(l.inputs=c.inputs),await this.client.updateRun(c.id,l,{apiKey:s,apiUrl:a,workspaceId:i})}else try{const n={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:((t=this.parent_run)==null?void 0:t.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!=null&&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)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,t){var l,u,d,h;const n=e==null?void 0:e.callbacks;let s,a,i,o=I0();if(n){const f=((l=n==null?void 0:n.getParentRunId)==null?void 0:l.call(n))??"",p=(u=n==null?void 0:n.handlers)==null?void 0:u.find(g=>(g==null?void 0:g.name)=="langchain_tracer");s=(d=p==null?void 0:p.getRun)==null?void 0:d.call(p,f),a=p==null?void 0:p.projectName,i=p==null?void 0:p.client,o=o||!!p}return s?new it({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==null?void 0:s.tags)??[]).concat((e==null?void 0:e.tags)??[]))],extra:{metadata:{...(h=s==null?void 0:s.extra)==null?void 0:h.metadata,...e==null?void 0:e.metadata}}}).createChild(t):new it({...t,client:i,tracingEnabled:o,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){var l;const n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=n["langsmith-trace"];if(!s||typeof s!="string")return;const a=s.trim(),i=a.split(".").map(u=>{const[d,h]=u.split("Z");return{strTime:d,time:Date.parse(d+"Z"),uuid:h}}),o=i[0].uuid,c={...t,name:(t==null?void 0:t.name)??"parent",run_type:(t==null?void 0:t.run_type)??"chain",start_time:(t==null?void 0:t.start_time)??Date.now(),id:(l=i.at(-1))==null?void 0:l.uuid,trace_id:o,dotted_order:a};if(n.baggage&&typeof n.baggage=="string"){const u=hi.fromHeader(n.baggage);c.metadata=u.metadata,c.tags=u.tags,c.project_name=u.project_name,c.replicas=u.replicas}return new it(c)}toHeaders(e){var n;const t={"langsmith-trace":this.dotted_order,baggage:new hi((n=this.extra)==null?void 0:n.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[s,a]of Object.entries(t))e.set(s,a);return t}}Object.defineProperty(it,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function O0(r){return r!=null&&typeof r.createChild=="function"&&typeof r.postRun=="function"}function Am(r){return typeof r=="object"&&r!=null&&typeof r.name=="string"&&r.name==="langchain_tracer"}function rf(r){return Array.isArray(r)&&r.some(e=>Am(e))}function $0(r){return typeof r=="object"&&r!=null&&Array.isArray(r.handlers)}function C0(r){var e;return r!=null&&typeof r.callbacks=="object"&&(rf((e=r.callbacks)==null?void 0:e.handlers)||rf(r.callbacks))}function k0(r){return r.split(".").map(t=>{const n=t.slice(0,-36),s=t.slice(-36),a=parseInt(n.slice(0,4)),i=parseInt(n.slice(4,6))-1,o=parseInt(n.slice(6,8)),c=parseInt(n.slice(9,11)),l=parseInt(n.slice(11,13)),u=parseInt(n.slice(13,15)),d=parseInt(n.slice(15,21));return[new Date(a,i,o,c,l,u,d/1e3),s]})}function P0(){const r=ir("LANGSMITH_RUNS_ENDPOINTS");if(!r)return[];try{const e=JSON.parse(r);if(Array.isArray(e)){const t=[];for(const n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}t.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return t}else if(typeof e=="object"&&e!==null){L0(e);const t=[];for(const[n,s]of Object.entries(e)){const a=n.replace(/\/$/,"");if(typeof s=="string")t.push({apiUrl:a,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof s}`);continue}}return t}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(f0(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function N0(r){return r?r.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):P0()}function L0(r){if(Object.keys(r).length>0&&ct("ENDPOINT"))throw new h0}var M0={};pe(M0,{BaseTracer:()=>Pn,isBaseTracer:()=>mn});const j0=r=>{if(r)return r.events=r.events??[],r.child_runs=r.child_runs??[],r};function wl(r,e){if(r)return new it({...r,start_time:r._serialized_start_time??r.start_time,parent_run:wl(e),child_runs:r.child_runs.map(t=>wl(t)).filter(t=>t!==void 0),extra:{...r.extra,runtime:im()},tracingEnabled:!1})}function Lc(r,e){return r&&!Array.isArray(r)&&typeof r=="object"?r:{[e]:r}}function mn(r){return typeof r._addRunToRunMap=="function"}var Pn=class extends Hs{constructor(e){super(...arguments);w(this,"runMap",new Map);w(this,"runTreeMap",new Map);w(this,"usesRunTreeMap",!1)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?j0(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e!=null&&e.stack?`
49
+
50
+ ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:n}=xm(new Date(e.start_time).getTime(),e.id,e.execution_order),s={...e},a=this.getRunById(s.parent_run_id);if(s.parent_run_id!==void 0?a&&(this._addChildRun(a,s),a.child_execution_order=Math.max(a.child_execution_order,s.child_execution_order),s.trace_id=a.trace_id,a.dotted_order!==void 0&&(s.dotted_order=[a.dotted_order,t].join("."),s._serialized_start_time=n)):(s.trace_id=s.id,s.dotted_order=t,s._serialized_start_time=n),this.usesRunTreeMap){const i=wl(s,a);i!==void 0&&this.runTreeMap.set(s.id,i)}else this.runMap.set(s.id,s);return s}async _endTrace(e){var n;const t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await((n=this.onRunUpdate)==null?void 0:n.call(this,e)),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,s,a,i,o,c){const l=this._getExecutionOrder(s),u=Date.now(),d=o?{...a,metadata:o}:a,h={id:n,name:c??e.id[e.id.length-1],parent_run_id:s,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(h)}async handleLLMStart(e,t,n,s,a,i,o,c){var u,d;const l=this.getRunById(n)??this._createRunForLLMStart(e,t,n,s,a,i,o,c);return await((u=this.onRunCreate)==null?void 0:u.call(this,l)),await((d=this.onLLMStart)==null?void 0:d.call(this,l)),l}_createRunForChatModelStart(e,t,n,s,a,i,o,c){const l=this._getExecutionOrder(s),u=Date.now(),d=o?{...a,metadata:o}:a,h={id:n,name:c??e.id[e.id.length-1],parent_run_id:s,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(h)}async handleChatModelStart(e,t,n,s,a,i,o,c){var u,d;const l=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,s,a,i,o,c);return await((u=this.onRunCreate)==null?void 0:u.call(this,l)),await((d=this.onLLMStart)==null?void 0:d.call(this,l)),l}async handleLLMEnd(e,t,n,s,a){var o;const i=this.getRunById(t);if(!i||(i==null?void 0:i.run_type)!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await((o=this.onLLMEnd)==null?void 0:o.call(this,i)),await this._endTrace(i),i}async handleLLMError(e,t,n,s,a){var o;const i=this.getRunById(t);if(!i||(i==null?void 0:i.run_type)!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await((o=this.onLLMError)==null?void 0:o.call(this,i)),await this._endTrace(i),i}_createRunForChainStart(e,t,n,s,a,i,o,c){const l=this._getExecutionOrder(s),u=Date.now(),d={id:n,name:c??e.id[e.id.length-1],parent_run_id:s,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:t,execution_order:l,child_execution_order:l,run_type:o??"chain",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,n,s,a,i,o,c){var u,d;const l=this.getRunById(n)??this._createRunForChainStart(e,t,n,s,a,i,o,c);return await((u=this.onRunCreate)==null?void 0:u.call(this,l)),await((d=this.onChainStart)==null?void 0:d.call(this,l)),l}async handleChainEnd(e,t,n,s,a){var o;const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=Lc(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),(a==null?void 0:a.inputs)!==void 0&&(i.inputs=Lc(a.inputs,"input")),await((o=this.onChainEnd)==null?void 0:o.call(this,i)),await this._endTrace(i),i}async handleChainError(e,t,n,s,a){var o;const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),(a==null?void 0:a.inputs)!==void 0&&(i.inputs=Lc(a.inputs,"input")),await((o=this.onChainError)==null?void 0:o.call(this,i)),await this._endTrace(i),i}_createRunForToolStart(e,t,n,s,a,i,o){const c=this._getExecutionOrder(s),l=Date.now(),u={id:n,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:t},execution_order:c,child_execution_order:c,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleToolStart(e,t,n,s,a,i,o){var l,u;const c=this.getRunById(n)??this._createRunForToolStart(e,t,n,s,a,i,o);return await((l=this.onRunCreate)==null?void 0:l.call(this,c)),await((u=this.onToolStart)==null?void 0:u.call(this,c)),c}async handleToolEnd(e,t){var s;const n=this.getRunById(t);if(!n||(n==null?void 0:n.run_type)!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await((s=this.onToolEnd)==null?void 0:s.call(this,n)),await this._endTrace(n),n}async handleToolError(e,t){var s;const n=this.getRunById(t);if(!n||(n==null?void 0:n.run_type)!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await((s=this.onToolError)==null?void 0:s.call(this,n)),await this._endTrace(n),n}async handleAgentAction(e,t){var a;const n=this.getRunById(t);if(!n||(n==null?void 0:n.run_type)!=="chain")return;const s=n;s.actions=s.actions||[],s.actions.push(e),s.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await((a=this.onAgentAction)==null?void 0:a.call(this,n))}async handleAgentEnd(e,t){var s;const n=this.getRunById(t);!n||(n==null?void 0:n.run_type)!=="chain"||(n.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await((s=this.onAgentEnd)==null?void 0:s.call(this,n)))}_createRunForRetrieverStart(e,t,n,s,a,i,o){const c=this._getExecutionOrder(s),l=Date.now(),u={id:n,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:t},execution_order:c,child_execution_order:c,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,t,n,s,a,i,o){var l,u;const c=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,s,a,i,o);return await((l=this.onRunCreate)==null?void 0:l.call(this,c)),await((u=this.onRetrieverStart)==null?void 0:u.call(this,c)),c}async handleRetrieverEnd(e,t){var s;const n=this.getRunById(t);if(!n||(n==null?void 0:n.run_type)!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await((s=this.onRetrieverEnd)==null?void 0:s.call(this,n)),await this._endTrace(n),n}async handleRetrieverError(e,t){var s;const n=this.getRunById(t);if(!n||(n==null?void 0:n.run_type)!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await((s=this.onRetrieverError)==null?void 0:s.call(this,n)),await this._endTrace(n),n}async handleText(e,t){var s;const n=this.getRunById(t);!n||(n==null?void 0:n.run_type)!=="chain"||(n.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await((s=this.onText)==null?void 0:s.call(this,n)))}async handleLLMNewToken(e,t,n,s,a,i){var c;const o=this.getRunById(n);if(!o||(o==null?void 0:o.run_type)!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:i==null?void 0:i.chunk}}),await((c=this.onLLMNewToken)==null?void 0:c.call(this,o,e,{chunk:i==null?void 0:i.chunk})),o}},Va={exports:{}};Va.exports;var nf;function D0(){return nf||(nf=1,(function(r){const t=(a=0)=>i=>`\x1B[${38+a};5;${i}m`,n=(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[l,u]of Object.entries(c))i[l]={open:`\x1B[${u[0]}m`,close:`\x1B[${u[1]}m`},c[l]=i[l],a.set(u[0],u[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=t(),i.color.ansi16m=n(),i.bgColor.ansi256=t(10),i.bgColor.ansi16m=n(10),Object.defineProperties(i,{rgbToAnsi256:{value:(o,c,l)=>o===c&&c===l?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(l/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:l}=c.groups;l.length===3&&(l=l.split("").map(d=>d+d).join(""));const u=Number.parseInt(l,16);return[u>>16&255,u>>8&255,u&255]},enumerable:!1},hexToAnsi256:{value:o=>i.rgbToAnsi256(...i.hexToRgb(o)),enumerable:!1}}),i}Object.defineProperty(r,"exports",{enumerable:!0,get:s})})(Va)),Va.exports}var U0=D0();const Im=Ds(U0);var F0={};pe(F0,{ConsoleCallbackHandler:()=>bl});function Ye(r,e){return`${r.open}${e}${r.close}`}function It(r,e){try{return JSON.stringify(r,null,2)}catch{return e}}function sf(r){return typeof r=="string"?r.trim():r==null?r:It(r,r.toString())}function Tr(r){if(!r.end_time)return"";const e=r.end_time-r.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:st}=Im;var bl=class extends Pn{constructor(){super(...arguments);w(this,"name","console_callback_handler")}persistRun(e){return Promise.resolve()}getParents(e){const t=[];let n=e;for(;n.parent_run_id;){const s=this.runMap.get(n.parent_run_id);if(s)t.push(s),n=s;else break}return t}getBreadcrumbs(e){const n=[...this.getParents(e).reverse(),e].map((s,a,i)=>{const o=`${s.execution_order}:${s.run_type}:${s.name}`;return a===i.length-1?Ye(Im.bold,o):o}).join(" > ");return Ye(st.grey,n)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${Ye(st.green,"[chain/start]")} [${t}] Entering Chain run with input: ${It(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ye(st.cyan,"[chain/end]")} [${t}] [${Tr(e)}] Exiting Chain run with output: ${It(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${Ye(st.red,"[chain/error]")} [${t}] [${Tr(e)}] Chain run errored with error: ${It(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),n="prompts"in e.inputs?{prompts:e.inputs.prompts.map(s=>s.trim())}:e.inputs;console.log(`${Ye(st.green,"[llm/start]")} [${t}] Entering LLM run with input: ${It(n,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ye(st.cyan,"[llm/end]")} [${t}] [${Tr(e)}] Exiting LLM run with output: ${It(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${Ye(st.red,"[llm/error]")} [${t}] [${Tr(e)}] LLM run errored with error: ${It(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${Ye(st.green,"[tool/start]")} [${t}] Entering Tool run with input: "${sf(e.inputs.input)}"`)}onToolEnd(e){var n;const t=this.getBreadcrumbs(e);console.log(`${Ye(st.cyan,"[tool/end]")} [${t}] [${Tr(e)}] Exiting Tool run with output: "${sf((n=e.outputs)==null?void 0:n.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${Ye(st.red,"[tool/error]")} [${t}] [${Tr(e)}] Tool run errored with error: ${It(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${Ye(st.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${It(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ye(st.cyan,"[retriever/end]")} [${t}] [${Tr(e)}] Exiting Retriever run with output: ${It(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${Ye(st.red,"[retriever/error]")} [${t}] [${Tr(e)}] Retriever run errored with error: ${It(e.error,"[error]")}`)}onAgentAction(e){const t=e,n=this.getBreadcrumbs(e);console.log(`${Ye(st.blue,"[agent/action]")} [${n}] Agent selected action: ${It(t.actions[t.actions.length-1],"[action]")}`)}};let Mc;const Rm=()=>{if(Mc===void 0){const r=qt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Mc=new $s(r)}return Mc};let B0=class{getStore(){}run(e,t){return t()}};const jc=Symbol.for("ls:tracing_async_local_storage"),q0=new B0;let z0=class{getInstance(){return globalThis[jc]??q0}initializeGlobalInstance(e){globalThis[jc]===void 0&&(globalThis[jc]=e)}};const H0=new z0;function W0(r=!1){const e=H0.getInstance().getStore();if(!r&&e===void 0)throw new Error(`Could not get the current run tree.
51
+
52
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function $u(r){return typeof r=="function"&&"langsmith:traceable"in r}var G0={};pe(G0,{LangChainTracer:()=>Ka});var Ka=class Om extends Pn{constructor(t={}){super(t);w(this,"name","langchain_tracer");w(this,"projectName");w(this,"exampleId");w(this,"client");w(this,"replicas");w(this,"usesRunTreeMap",!0);const{exampleId:n,projectName:s,client:a,replicas:i}=t;this.projectName=s??um(),this.replicas=i,this.exampleId=n,this.client=a??Rm();const o=Om.getTraceableRunTree();o&&this.updateFromRunTree(o)}async persistRun(t){}async onRunCreate(t){const n=this.getRunTreeWithTracingConfig(t.id);await(n==null?void 0:n.postRun())}async onRunUpdate(t){const n=this.getRunTreeWithTracingConfig(t.id);await(n==null?void 0:n.patchRun())}getRun(t){return this.runTreeMap.get(t)}updateFromRunTree(t){this.runTreeMap.set(t.id,t);let n=t;const s=new Set;for(;n.parent_run&&!(s.has(n.id)||(s.add(n.id),!n.parent_run));)n=n.parent_run;s.clear();const a=[n];for(;a.length>0;){const i=a.shift();!i||s.has(i.id)||(s.add(i.id),this.runTreeMap.set(i.id,i),i.child_runs&&a.push(...i.child_runs))}this.client=t.client??this.client,this.replicas=t.replicas??this.replicas,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(t){const n=this.runTreeMap.get(t);if(n)return new it({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return W0(!0)}catch{return}}};let Gr;function J0(){const r="default"in mr?mr.default:mr;return new r({autoStart:!0,concurrency:1})}function V0(){return typeof Gr>"u"&&(Gr=J0()),Gr}async function Le(r,e){if(e===!0){const t=Os();t!==void 0?await t.run(void 0,async()=>r()):await r()}else Gr=V0(),Gr.add(async()=>{const t=Os();t!==void 0?await t.run(void 0,async()=>r()):await r()})}async function K0(){const r=Rm();await Promise.allSettled([typeof Gr<"u"?Gr.onIdle():Promise.resolve(),r.awaitPendingTraceBatches()])}var Z0={};pe(Z0,{awaitAllCallbacks:()=>K0,consumeCallback:()=>Le});const X0=r=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(t=>qt(t)==="true");function $m(r){var n;const e=Os();if(e===void 0)return;const t=e.getStore();return(n=t==null?void 0:t[vs])==null?void 0:n[r]}const Y0=Symbol("lc:configure_hooks"),Q0=()=>$m(Y0)||[];var eS={};pe(eS,{BaseCallbackManager:()=>Cm,BaseRunManager:()=>Gs,CallbackManager:()=>dt,CallbackManagerForChainRun:()=>Pm,CallbackManagerForLLMRun:()=>vl,CallbackManagerForRetrieverRun:()=>km,CallbackManagerForToolRun:()=>Nm,ensureHandler:()=>Cs,parseCallbackConfigArg:()=>Ki});function Ki(r){return r?Array.isArray(r)||"name"in r?{callbacks:r}:r:{}}var Cm=class{setHandler(r){return this.setHandlers([r])}},Gs=class{constructor(r,e,t,n,s,a,i,o){this.runId=r,this.handlers=e,this.inheritableHandlers=t,this.tags=n,this.inheritableTags=s,this.metadata=a,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(r){await Promise.all(this.handlers.map(e=>Le(async()=>{var t;try{await((t=e.handleText)==null?void 0:t.call(e,r,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(r,e,t,n,s){await Promise.all(this.handlers.map(a=>Le(async()=>{var i;try{await((i=a.handleCustomEvent)==null?void 0:i.call(a,r,e,this.runId,this.tags,this.metadata))}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}},km=class extends Gs{getChild(r){const e=new dt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),r&&e.addTags([r],!1),e}async handleRetrieverEnd(r){await Promise.all(this.handlers.map(e=>Le(async()=>{var t;if(!e.ignoreRetriever)try{await((t=e.handleRetrieverEnd)==null?void 0:t.call(e,r,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(r){await Promise.all(this.handlers.map(e=>Le(async()=>{var t;if(!e.ignoreRetriever)try{await((t=e.handleRetrieverError)==null?void 0:t.call(e,r,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 r}},e.awaitHandlers)))}},vl=class extends Gs{async handleLLMNewToken(r,e,t,n,s,a){await Promise.all(this.handlers.map(i=>Le(async()=>{var o;if(!i.ignoreLLM)try{await((o=i.handleLLMNewToken)==null?void 0:o.call(i,r,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a))}catch(c){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${c}`),i.raiseError)throw c}},i.awaitHandlers)))}async handleLLMError(r,e,t,n,s){await Promise.all(this.handlers.map(a=>Le(async()=>{var i;if(!a.ignoreLLM)try{await((i=a.handleLLMError)==null?void 0:i.call(a,r,this.runId,this._parentRunId,this.tags,s))}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMError: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleLLMEnd(r,e,t,n,s){await Promise.all(this.handlers.map(a=>Le(async()=>{var i;if(!a.ignoreLLM)try{await((i=a.handleLLMEnd)==null?void 0:i.call(a,r,this.runId,this._parentRunId,this.tags,s))}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMEnd: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}},Pm=class extends Gs{getChild(r){const e=new dt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),r&&e.addTags([r],!1),e}async handleChainError(r,e,t,n,s){await Promise.all(this.handlers.map(a=>Le(async()=>{var i;if(!a.ignoreChain)try{await((i=a.handleChainError)==null?void 0:i.call(a,r,this.runId,this._parentRunId,this.tags,s))}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainError: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleChainEnd(r,e,t,n,s){await Promise.all(this.handlers.map(a=>Le(async()=>{var i;if(!a.ignoreChain)try{await((i=a.handleChainEnd)==null?void 0:i.call(a,r,this.runId,this._parentRunId,this.tags,s))}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainEnd: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleAgentAction(r){await Promise.all(this.handlers.map(e=>Le(async()=>{var t;if(!e.ignoreAgent)try{await((t=e.handleAgentAction)==null?void 0:t.call(e,r,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(r){await Promise.all(this.handlers.map(e=>Le(async()=>{var t;if(!e.ignoreAgent)try{await((t=e.handleAgentEnd)==null?void 0:t.call(e,r,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)))}},Nm=class extends Gs{getChild(r){const e=new dt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),r&&e.addTags([r],!1),e}async handleToolError(r){await Promise.all(this.handlers.map(e=>Le(async()=>{var t;if(!e.ignoreAgent)try{await((t=e.handleToolError)==null?void 0:t.call(e,r,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(r){await Promise.all(this.handlers.map(e=>Le(async()=>{var t;if(!e.ignoreAgent)try{await((t=e.handleToolEnd)==null?void 0:t.call(e,r,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 ns extends Cm{constructor(t,n){super();w(this,"handlers",[]);w(this,"inheritableHandlers",[]);w(this,"tags",[]);w(this,"inheritableTags",[]);w(this,"metadata",{});w(this,"inheritableMetadata",{});w(this,"name","callback_manager");w(this,"_parentRunId");this.handlers=(n==null?void 0:n.handlers)??this.handlers,this.inheritableHandlers=(n==null?void 0:n.inheritableHandlers)??this.inheritableHandlers,this.tags=(n==null?void 0:n.tags)??this.tags,this.inheritableTags=(n==null?void 0:n.inheritableTags)??this.inheritableTags,this.metadata=(n==null?void 0:n.metadata)??this.metadata,this.inheritableMetadata=(n==null?void 0:n.inheritableMetadata)??this.inheritableMetadata,this._parentRunId=t}getParentRunId(){return this._parentRunId}async handleLLMStart(t,n,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0,l=void 0){return Promise.all(n.map(async(u,d)=>{const h=d===0&&s?s:dr();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return mn(f)&&f._createRunForLLMStart(t,[u],h,this._parentRunId,i,this.tags,this.metadata,l),Le(async()=>{var p;try{await((p=f.handleLLMStart)==null?void 0:p.call(f,t,[u],h,this._parentRunId,i,this.tags,this.metadata,l))}catch(g){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${g}`),f.raiseError)throw g}},f.awaitHandlers)})),new vl(h,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,n,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0,l=void 0){return Promise.all(n.map(async(u,d)=>{const h=d===0&&s?s:dr();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return mn(f)&&f._createRunForChatModelStart(t,[u],h,this._parentRunId,i,this.tags,this.metadata,l),Le(async()=>{var p,g;try{if(f.handleChatModelStart)await((p=f.handleChatModelStart)==null?void 0:p.call(f,t,[u],h,this._parentRunId,i,this.tags,this.metadata,l));else if(f.handleLLMStart){const _=bu(u);await((g=f.handleLLMStart)==null?void 0:g.call(f,t,[_],h,this._parentRunId,i,this.tags,this.metadata,l))}}catch(_){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${_}`),f.raiseError)throw _}},f.awaitHandlers)})),new vl(h,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,n,s=dr(),a=void 0,i=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreChain)return mn(l)&&l._createRunForChainStart(t,n,s,this._parentRunId,this.tags,this.metadata,a,c),Le(async()=>{var u;try{await((u=l.handleChainStart)==null?void 0:u.call(l,t,n,s,this._parentRunId,this.tags,this.metadata,a,c))}catch(d){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleChainStart: ${d}`),l.raiseError)throw d}},l.awaitHandlers)})),new Pm(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,n,s=dr(),a=void 0,i=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreAgent)return mn(l)&&l._createRunForToolStart(t,n,s,this._parentRunId,this.tags,this.metadata,c),Le(async()=>{var u;try{await((u=l.handleToolStart)==null?void 0:u.call(l,t,n,s,this._parentRunId,this.tags,this.metadata,c))}catch(d){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleToolStart: ${d}`),l.raiseError)throw d}},l.awaitHandlers)})),new Nm(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,n,s=dr(),a=void 0,i=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreRetriever)return mn(l)&&l._createRunForRetrieverStart(t,n,s,this._parentRunId,this.tags,this.metadata,c),Le(async()=>{var u;try{await((u=l.handleRetrieverStart)==null?void 0:u.call(l,t,n,s,this._parentRunId,this.tags,this.metadata,c))}catch(d){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleRetrieverStart: ${d}`),l.raiseError)throw d}},l.awaitHandlers)})),new km(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,n,s,a,i){await Promise.all(this.handlers.map(o=>Le(async()=>{var c;if(!o.ignoreCustomEvent)try{await((c=o.handleCustomEvent)==null?void 0:c.call(o,t,n,s,this.tags,this.metadata))}catch(l){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleCustomEvent: ${l}`),o.raiseError)throw l}},o.awaitHandlers)))}addHandler(t,n=!0){this.handlers.push(t),n&&this.inheritableHandlers.push(t)}removeHandler(t){this.handlers=this.handlers.filter(n=>n!==t),this.inheritableHandlers=this.inheritableHandlers.filter(n=>n!==t)}setHandlers(t,n=!0){this.handlers=[],this.inheritableHandlers=[];for(const s of t)this.addHandler(s,n)}addTags(t,n=!0){this.removeTags(t),this.tags.push(...t),n&&this.inheritableTags.push(...t)}removeTags(t){this.tags=this.tags.filter(n=>!t.includes(n)),this.inheritableTags=this.inheritableTags.filter(n=>!t.includes(n))}addMetadata(t,n=!0){this.metadata={...this.metadata,...t},n&&(this.inheritableMetadata={...this.inheritableMetadata,...t})}removeMetadata(t){for(const n of Object.keys(t))delete this.metadata[n],delete this.inheritableMetadata[n]}copy(t=[],n=!0){const s=new ns(this._parentRunId);for(const a of this.handlers){const i=this.inheritableHandlers.includes(a);s.addHandler(a,i)}for(const a of this.tags){const i=this.inheritableTags.includes(a);s.addTags([a],i)}for(const a of Object.keys(this.metadata)){const i=Object.keys(this.inheritableMetadata).includes(a);s.addMetadata({[a]:this.metadata[a]},i)}for(const a of t)s.handlers.filter(i=>i.name==="console_callback_handler").some(i=>i.name===a.name)||s.addHandler(a,n);return s}static fromHandlers(t){class n extends Hs{constructor(){super();w(this,"name",dr());Object.assign(this,t)}}const s=new this;return s.addHandler(new n),s}static configure(t,n,s,a,i,o,c){return this._configureSync(t,n,s,a,i,o,c)}static _configureSync(t,n,s,a,i,o,c){var f;let l;(t||n)&&(Array.isArray(t)||!t?(l=new ns,l.setHandlers((t==null?void 0:t.map(Cs))??[],!0)):l=t,l=l.copy(Array.isArray(n)?n.map(Cs):n==null?void 0:n.handlers,!1));const u=qt("LANGCHAIN_VERBOSE")==="true"||(c==null?void 0:c.verbose),d=((f=Ka.getTraceableRunTree())==null?void 0:f.tracingEnabled)||X0(),h=d||(qt("LANGCHAIN_TRACING")??!1);if(u||h){if(l||(l=new ns),u&&!l.handlers.some(p=>p.name===bl.prototype.name)){const p=new bl;l.addHandler(p,!0)}if(h&&!l.handlers.some(p=>p.name==="langchain_tracer")&&d){const p=new Ka;l.addHandler(p,!0)}if(d){const p=Ka.getTraceableRunTree();if(p&&l._parentRunId===void 0){l._parentRunId=p.id;const g=l.handlers.find(_=>_.name==="langchain_tracer");g==null||g.updateFromRunTree(p)}}}for(const{contextVar:p,inheritable:g=!0,handlerClass:_,envVar:b}of Q0()){const m=b&&qt(b)==="true"&&_;let y;const T=p!==void 0?$m(p):void 0;T&&om(T)?y=T:m&&(y=new _({})),y!==void 0&&(l||(l=new ns),l.handlers.some(x=>x.name===y.name)||l.addHandler(y,g))}return(s||a)&&l&&(l.addTags(s??[]),l.addTags(a??[],!1)),(i||o)&&l&&(l.addMetadata(i??{}),l.addMetadata(o??{},!1)),l}};function Cs(r){return"name"in r?r:Hs.fromMethods(r)}var Lm=class{getStore(){}run(r,e){return e()}enterWith(r){}};const tS=new Lm,af=Symbol.for("lc:child_config");var rS=class{getInstance(){return Os()??tS}getRunnableConfig(){var e,t;return(t=(e=this.getInstance().getStore())==null?void 0:e.extra)==null?void 0:t[af]}runWithConfig(r,e,t){var l;const n=dt._configureSync(r==null?void 0:r.callbacks,void 0,r==null?void 0:r.tags,void 0,r==null?void 0:r.metadata),s=this.getInstance(),a=s.getStore(),i=n==null?void 0:n.getParentRunId(),o=(l=n==null?void 0:n.handlers)==null?void 0:l.find(u=>(u==null?void 0:u.name)==="langchain_tracer");let c;return o&&i?c=o.getRunTreeWithTracingConfig(i):t||(c=new it({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[af]:r}),a!==void 0&&a[vs]!==void 0&&(c===void 0&&(c={}),c[vs]=a[vs]),s.run(c,e)}initializeGlobalInstance(r){Os()===void 0&&db(r)}};const Jt=new rS;var nS={};pe(nS,{AsyncLocalStorageProviderSingleton:()=>Jt,MockAsyncLocalStorage:()=>Lm,_CONTEXT_VARIABLES_KEY:()=>vs});const Dc=25;async function vt(r){return dt._configureSync(r==null?void 0:r.callbacks,void 0,r==null?void 0:r.tags,void 0,r==null?void 0:r.metadata)}function fi(...r){const e={};for(const t of r.filter(n=>!!n))for(const n of Object.keys(t))if(n==="metadata")e[n]={...e[n],...t[n]};else if(n==="tags"){const s=e[n]??[];e[n]=[...new Set(s.concat(t[n]??[]))]}else if(n==="configurable")e[n]={...e[n],...t[n]};else if(n==="timeout")e.timeout===void 0?e.timeout=t.timeout:t.timeout!==void 0&&(e.timeout=Math.min(e.timeout,t.timeout));else if(n==="signal")e.signal===void 0?e.signal=t.signal:t.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,t.signal]):e.signal=t.signal);else if(n==="callbacks"){const s=e.callbacks,a=t.callbacks;if(Array.isArray(a))if(!s)e.callbacks=a;else if(Array.isArray(s))e.callbacks=s.concat(a);else{const i=s.copy();for(const o of a)i.addHandler(Cs(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(Cs(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=n;e[s]=t[s]??e[s]}return e}const sS=new Set(["string","number","boolean"]);function ge(r){var n;const e=Jt.getRunnableConfig();let t={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:s,runName:a,...i}=e;t=Object.entries(i).reduce((o,[c,l])=>(l!==void 0&&(o[c]=l),o),t)}if(r&&(t=Object.entries(r).reduce((s,[a,i])=>(i!==void 0&&(s[a]=i),s),t)),t!=null&&t.configurable)for(const s of Object.keys(t.configurable))sS.has(typeof t.configurable[s])&&!((n=t.metadata)!=null&&n[s])&&(t.metadata||(t.metadata={}),t.metadata[s]=t.configurable[s]);if(t.timeout!==void 0){if(t.timeout<=0)throw new Error("Timeout must be a positive number");const s=AbortSignal.timeout(t.timeout);t.signal!==void 0?"any"in AbortSignal&&(t.signal=AbortSignal.any([t.signal,s])):t.signal=s,delete t.timeout}return t}function Te(r={},{callbacks:e,maxConcurrency:t,recursionLimit:n,runName:s,configurable:a,runId:i}={}){const o=ge(r);return e!==void 0&&(delete o.runName,o.callbacks=e),n!==void 0&&(o.recursionLimit=n),t!==void 0&&(o.maxConcurrency=t),s!==void 0&&(o.runName=s),a!==void 0&&(o.configurable={...o.configurable,...a}),i!==void 0&&delete o.runId,o}function yr(r){return r?{configurable:r.configurable,recursionLimit:r.recursionLimit,callbacks:r.callbacks,tags:r.tags,metadata:r.metadata,maxConcurrency:r.maxConcurrency,timeout:r.timeout,signal:r.signal}:void 0}async function Nr(r,e){if(e===void 0)return r;let t;return Promise.race([r.catch(n=>{if(!(e!=null&&e.aborted))throw n}),new Promise((n,s)=>{t=()=>{s(ks(e))},e.addEventListener("abort",t),e.aborted&&s(ks(e))})]).finally(()=>e.removeEventListener("abort",t))}function ks(r){return(r==null?void 0:r.reason)instanceof Error?r.reason:typeof(r==null?void 0:r.reason)=="string"?new Error(r.reason):new Error("Aborted")}var aS={};pe(aS,{AsyncGeneratorWithSetup:()=>rn,IterableReadableStream:()=>Vt,atee:()=>Cu,concat:()=>Lr,pipeGeneratorWithSetup:()=>Mm});var Vt=class Sl extends ReadableStream{constructor(){super(...arguments);w(this,"reader")}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){const n=this.reader.cancel();this.reader.releaseLock(),await n}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){const n=t.getReader();return new Sl({start(s){return a();function a(){return n.read().then(({done:i,value:o})=>{if(i){s.close();return}return s.enqueue(o),a()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new Sl({async pull(n){const{value:s,done:a}=await t.next();a&&n.close(),n.enqueue(s)},async cancel(n){await t.return(n)}})}};function Cu(r,e=2){const t=Array.from({length:e},()=>[]);return t.map(async function*(s){for(;;)if(s.length===0){const a=await r.next();for(const i of t)i.push(a)}else{if(s[0].done)return;yield s.shift().value}})}function Lr(r,e){if(Array.isArray(r)&&Array.isArray(e))return r.concat(e);if(typeof r=="string"&&typeof e=="string")return r+e;if(typeof r=="number"&&typeof e=="number")return r+e;if("concat"in r&&typeof r.concat=="function")return r.concat(e);if(typeof r=="object"&&typeof e=="object"){const t={...r};for(const[n,s]of Object.entries(e))n in t&&!Array.isArray(t[n])?t[n]=Lr(t[n],s):t[n]=s;return t}else throw new Error(`Cannot concat ${typeof r} and ${typeof e}`)}var rn=class{constructor(r){w(this,"generator");w(this,"setup");w(this,"config");w(this,"signal");w(this,"firstResult");w(this,"firstResultUsed",!1);var e;this.generator=r.generator,this.config=r.config,this.signal=r.signal??((e=this.config)==null?void 0:e.signal),this.setup=new Promise((t,n)=>{Jt.runWithConfig(yr(r.config),async()=>{this.firstResult=r.generator.next(),r.startSetup?this.firstResult.then(r.startSetup).then(t,n):this.firstResult.then(s=>t(void 0),n)},!0)})}async next(...r){var e;return(e=this.signal)==null||e.throwIfAborted(),this.firstResultUsed?Jt.runWithConfig(yr(this.config),this.signal?async()=>Nr(this.generator.next(...r),this.signal):async()=>this.generator.next(...r),!0):(this.firstResultUsed=!0,this.firstResult)}async return(r){return this.generator.return(r)}async throw(r){return this.generator.throw(r)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function Mm(r,e,t,n,...s){const a=new rn({generator:e,startSetup:t,signal:n}),i=await a.setup;return{output:r(a,i,...s),setup:i}}/*!
53
+ * https://github.com/Starcounter-Jack/JSON-Patch
54
+ * (c) 2017-2022 Joachim Wester
55
+ * MIT licensed
56
+ */const iS=Object.prototype.hasOwnProperty;function El(r,e){return iS.call(r,e)}function Tl(r){if(Array.isArray(r)){const t=new Array(r.length);for(let n=0;n<t.length;n++)t[n]=""+n;return t}if(Object.keys)return Object.keys(r);let e=[];for(let t in r)El(r,t)&&e.push(t);return e}function Ut(r){switch(typeof r){case"object":return JSON.parse(JSON.stringify(r));case"undefined":return null;default:return r}}function xl(r){let e=0;const t=r.length;let n;for(;e<t;){if(n=r.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function sn(r){return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}function oS(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}function Al(r){if(r===void 0)return!0;if(r){if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(Al(r[t]))return!0}else if(typeof r=="object"){const t=Tl(r),n=t.length;for(var e=0;e<n;e++)if(Al(r[t[e]]))return!0}}return!1}function of(r,e){const t=[r];for(const n in e){const s=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof s<"u"&&t.push(`${n}: ${s}`)}return t.join(`
57
+ `)}var cS=class extends Error{constructor(r,e,t,n,s){super(of(r,{name:e,index:t,operation:n,tree:s})),this.name=e,this.index=t,this.operation=n,this.tree=s,Object.setPrototypeOf(this,new.target.prototype),this.message=of(r,{name:e,index:t,operation:n,tree:s})}},jm={};pe(jm,{JsonPatchError:()=>Oe,_areEquals:()=>Ps,applyOperation:()=>Jr,applyPatch:()=>On,applyReducer:()=>dS,deepClone:()=>lS,getValueByPointer:()=>pi,validate:()=>Dm,validator:()=>mi});const Oe=cS,lS=Ut,En={add:function(r,e,t){return r[e]=this.value,{newDocument:t}},remove:function(r,e,t){var n=r[e];return delete r[e],{newDocument:t,removed:n}},replace:function(r,e,t){var n=r[e];return r[e]=this.value,{newDocument:t,removed:n}},move:function(r,e,t){let n=pi(t,this.path);n&&(n=Ut(n));const s=Jr(t,{op:"remove",path:this.from}).removed;return Jr(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:n}},copy:function(r,e,t){const n=pi(t,this.from);return Jr(t,{op:"add",path:this.path,value:Ut(n)}),{newDocument:t}},test:function(r,e,t){return{newDocument:t,test:Ps(r[e],this.value)}},_get:function(r,e,t){return this.value=r[e],{newDocument:t}}};var uS={add:function(r,e,t){return xl(e)?r.splice(e,0,this.value):r[e]=this.value,{newDocument:t,index:e}},remove:function(r,e,t){var n=r.splice(e,1);return{newDocument:t,removed:n[0]}},replace:function(r,e,t){var n=r[e];return r[e]=this.value,{newDocument:t,removed:n}},move:En.move,copy:En.copy,test:En.test,_get:En._get};function pi(r,e){if(e=="")return r;var t={op:"_get",path:e};return Jr(r,t),t.value}function Jr(r,e,t=!1,n=!0,s=!0,a=0){if(t&&(typeof t=="function"?t(e,0,r,e.path):mi(e,0)),e.path===""){let i={newDocument:r};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=r,i;if(e.op==="move"||e.op==="copy")return i.newDocument=pi(r,e.from),e.op==="move"&&(i.removed=r),i;if(e.op==="test"){if(i.test=Ps(r,e.value),i.test===!1)throw new Oe("Test operation failed","TEST_OPERATION_FAILED",a,e,r);return i.newDocument=r,i}else{if(e.op==="remove")return i.removed=r,i.newDocument=null,i;if(e.op==="_get")return e.value=r,i;if(t)throw new Oe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,e,r);return i}}else{n||(r=Ut(r));const o=(e.path||"").split("/");let c=r,l=1,u=o.length,d,h,f;for(typeof t=="function"?f=t:f=mi;;){if(h=o[l],h&&h.indexOf("~")!=-1&&(h=oS(h)),s&&(h=="__proto__"||h=="prototype"&&l>0&&o[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(c[h]===void 0?d=o.slice(0,l).join("/"):l==u-1&&(d=e.path),d!==void 0&&f(e,0,r,d)),l++,Array.isArray(c)){if(h==="-")h=c.length;else{if(t&&!xl(h))throw new Oe("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,r);xl(h)&&(h=~~h)}if(l>=u){if(t&&e.op==="add"&&h>c.length)throw new Oe("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,e,r);const p=uS[e.op].call(e,c,h,r);if(p.test===!1)throw new Oe("Test operation failed","TEST_OPERATION_FAILED",a,e,r);return p}}else if(l>=u){const p=En[e.op].call(e,c,h,r);if(p.test===!1)throw new Oe("Test operation failed","TEST_OPERATION_FAILED",a,e,r);return p}if(c=c[h],t&&l<u&&(!c||typeof c!="object"))throw new Oe("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,e,r)}}}function On(r,e,t,n=!0,s=!0){if(t&&!Array.isArray(e))throw new Oe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(r=Ut(r));const a=new Array(e.length);for(let i=0,o=e.length;i<o;i++)a[i]=Jr(r,e[i],t,!0,s,i),r=a[i].newDocument;return a.newDocument=r,a}function dS(r,e,t){const n=Jr(r,e);if(n.test===!1)throw new Oe("Test operation failed","TEST_OPERATION_FAILED",t,e,r);return n.newDocument}function mi(r,e,t,n){if(typeof r!="object"||r===null||Array.isArray(r))throw new Oe("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,r,t);if(En[r.op]){if(typeof r.path!="string")throw new Oe("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,r,t);if(r.path.indexOf("/")!==0&&r.path.length>0)throw new Oe('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,r,t);if((r.op==="move"||r.op==="copy")&&typeof r.from!="string")throw new Oe("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,r,t);if((r.op==="add"||r.op==="replace"||r.op==="test")&&r.value===void 0)throw new Oe("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,r,t);if((r.op==="add"||r.op==="replace"||r.op==="test")&&Al(r.value))throw new Oe("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,r,t);if(t){if(r.op=="add"){var s=r.path.split("/").length,a=n.split("/").length;if(s!==a+1&&s!==a)throw new Oe("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,r,t)}else if(r.op==="replace"||r.op==="remove"||r.op==="_get"){if(r.path!==n)throw new Oe("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,r,t)}else if(r.op==="move"||r.op==="copy"){var i={op:"_get",path:r.from,value:void 0},o=Dm([i],t);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new Oe("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,r,t)}}}else throw new Oe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,r,t)}function Dm(r,e,t){try{if(!Array.isArray(r))throw new Oe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)On(Ut(e),Ut(r),t||!0);else{t=t||mi;for(var n=0;n<r.length;n++)t(r[n],n,e,void 0)}}catch(s){if(s instanceof Oe)return s;throw s}}function Ps(r,e){if(r===e)return!0;if(r&&e&&typeof r=="object"&&typeof e=="object"){var t=Array.isArray(r),n=Array.isArray(e),s,a,i;if(t&&n){if(a=r.length,a!=e.length)return!1;for(s=a;s--!==0;)if(!Ps(r[s],e[s]))return!1;return!0}if(t!=n)return!1;var o=Object.keys(r);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],!Ps(r[i],e[i]))return!1;return!0}return r!==r&&e!==e}function Um(r,e,t,n,s){if(e!==r){typeof e.toJSON=="function"&&(e=e.toJSON());for(var a=Tl(e),i=Tl(r),o=!1,c=i.length-1;c>=0;c--){var l=i[c],u=r[l];if(El(e,l)&&!(e[l]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof u=="object"&&u!=null&&typeof d=="object"&&d!=null&&Array.isArray(u)===Array.isArray(d)?Um(u,d,t,n+"/"+sn(l),s):u!==d&&(s&&t.push({op:"test",path:n+"/"+sn(l),value:Ut(u)}),t.push({op:"replace",path:n+"/"+sn(l),value:Ut(d)}))}else Array.isArray(r)===Array.isArray(e)?(s&&t.push({op:"test",path:n+"/"+sn(l),value:Ut(u)}),t.push({op:"remove",path:n+"/"+sn(l)}),o=!0):(s&&t.push({op:"test",path:n,value:r}),t.push({op:"replace",path:n,value:e}))}if(!(!o&&a.length==i.length))for(var c=0;c<a.length;c++){var l=a[c];!El(r,l)&&e[l]!==void 0&&t.push({op:"add",path:n+"/"+sn(l),value:Ut(e[l])})}}}function ku(r,e,t=!1){var n=[];return Um(r,e,n,"",t),n}({...jm});var hS={};pe(hS,{LogStreamCallbackHandler:()=>Rl,RunLog:()=>Pu,RunLogPatch:()=>hr,isLogStreamHandler:()=>Fm});var hr=class{constructor(r){w(this,"ops");this.ops=r.ops??[]}concat(r){const e=this.ops.concat(r.ops),t=On({},e);return new Pu({ops:e,state:t[t.length-1].newDocument})}},Pu=class Il extends hr{constructor(t){super(t);w(this,"state");this.state=t.state}concat(t){const n=this.ops.concat(t.ops),s=On(this.state,t.ops);return new Il({ops:n,state:s[s.length-1].newDocument})}static fromRunLogPatch(t){const n=On({},t.ops);return new Il({ops:t.ops,state:n[n.length-1].newDocument})}};const Fm=r=>r.name==="log_stream_tracer";async function cf(r,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:t}=r;if(["retriever","llm","prompt"].includes(r.run_type))return t;if(!(Object.keys(t).length===1&&(t==null?void 0:t.input)===""))return t.input}async function lf(r,e){const{outputs:t}=r;return e==="original"||["retriever","llm","prompt"].includes(r.run_type)?t:t!==void 0&&Object.keys(t).length===1&&(t==null?void 0:t.output)!==void 0?t.output:t}function fS(r){return r!==void 0&&r.message!==void 0}var Rl=class extends Pn{constructor(e){super({_awaitHandler:!0,...e});w(this,"autoClose",!0);w(this,"includeNames");w(this,"includeTypes");w(this,"includeTags");w(this,"excludeNames");w(this,"excludeTypes");w(this,"excludeTags");w(this,"_schemaFormat","original");w(this,"rootId");w(this,"keyMapByRunId",{});w(this,"counterMapByRunName",{});w(this,"transformStream");w(this,"writer");w(this,"receiveStream");w(this,"name","log_stream_tracer");w(this,"lc_prefer_streaming",!0);this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this._schemaFormat=(e==null?void 0:e._schemaFormat)??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Vt.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n=n||t.find(s=>{var a;return(a=this.includeTags)==null?void 0:a.includes(s)})!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n=n&&t.every(s=>{var a;return!((a=this.excludeTags)!=null&&a.includes(s))})),n}async*tapOutputIterable(e,t){for await(const n of t){if(e!==this.rootId){const s=this.keyMapByRunId[e];s&&await this.writer.write(new hr({ops:[{op:"add",path:`/logs/${s}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){var s;if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new hr({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;const n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(n.inputs=await cf(e,this._schemaFormat)),await this.writer.write(new hr({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(t===void 0)return;const n=[];this._schemaFormat==="streaming_events"&&n.push({op:"replace",path:`/logs/${t}/inputs`,value:await cf(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await lf(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const s=new hr({ops:n});await this.writer.write(s)}finally{if(e.id===this.rootId){const t=new hr({ops:[{op:"replace",path:"/final_output",value:await lf(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){const s=this.keyMapByRunId[e.id];if(s===void 0)return;const a=e.inputs.messages!==void 0;let i;a?fS(n==null?void 0:n.chunk)?i=n==null?void 0:n.chunk:i=new ke({id:`run-${e.id}`,content:t}):i=t;const o=new hr({ops:[{op:"add",path:`/logs/${s}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${s}/streamed_output/-`,value:i}]});await this.writer.write(o)}},pS={};pe(pS,{ChatGenerationChunk:()=>Xr,GenerationChunk:()=>$n,RUN_KEY:()=>Ns});const Ns="__run";var $n=class Bm{constructor(e){w(this,"text");w(this,"generationInfo");this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new Bm({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},Xr=class qm extends $n{constructor(t){super(t);w(this,"message");this.message=t.message}concat(t){return new qm({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function _a({name:r,serialized:e}){return r!==void 0?r:(e==null?void 0:e.name)!==void 0?e.name:(e==null?void 0:e.id)!==void 0&&Array.isArray(e==null?void 0:e.id)?e.id[e.id.length-1]:"Unnamed"}const mS=r=>r.name==="event_stream_tracer";var gS=class extends Pn{constructor(e){super({_awaitHandler:!0,...e});w(this,"autoClose",!0);w(this,"includeNames");w(this,"includeTypes");w(this,"includeTags");w(this,"excludeNames");w(this,"excludeTypes");w(this,"excludeTags");w(this,"runInfoMap",new Map);w(this,"tappedPromises",new Map);w(this,"transformStream");w(this,"writer");w(this,"receiveStream");w(this,"name","event_stream_tracer");w(this,"lc_prefer_streaming",!0);this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Vt.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.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(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n=n||t.find(s=>{var a;return(a=this.includeTags)==null?void 0:a.includes(s)})!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n=n&&t.every(s=>{var a;return!((a=this.excludeTags)!=null&&a.includes(s))})),n}async*tapOutputIterable(e,t){const n=await t.next();if(n.done)return;const s=this.runInfoMap.get(e);if(s===void 0){yield n.value;return}function a(o,c){return o==="llm"&&typeof c=="string"?new $n({text:c}):c}let i=this.tappedPromises.get(e);if(i===void 0){let o;i=new Promise(c=>{o=c}),this.tappedPromises.set(e,i);try{const c={event:`on_${s.runType}_stream`,run_id:e,name:s.name,tags:s.tags,metadata:s.metadata,data:{}};await this.send({...c,data:{chunk:a(s.runType,n.value)}},s),yield n.value;for await(const l of t)s.runType!=="tool"&&s.runType!=="retriever"&&await this.send({...c,data:{chunk:a(s.runType,l)}},s),yield l}finally{o==null||o()}}else{yield n.value;for await(const o of t)yield o}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const n=this.tappedPromises.get(e.run_id);n!==void 0?n.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){var i,o;const t=_a(e),n=e.inputs.messages!==void 0?"chat_model":"llm",s={tags:e.tags??[],metadata:((i=e.extra)==null?void 0:i.metadata)??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,s);const a=`on_${n}_start`;await this.send({event:a,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},s)}async onLLMNewToken(e,t,n){const s=this.runInfoMap.get(e.id);let a,i;if(s===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(s.runType==="chat_model")i="on_chat_model_stream",(n==null?void 0:n.chunk)===void 0?a=new ke({content:t,id:`run-${e.id}`}):a=n.chunk.message;else if(s.runType==="llm")i="on_llm_stream",(n==null?void 0:n.chunk)===void 0?a=new $n({text:t}):a=n.chunk;else throw new Error(`Unexpected run type ${s.runType}`);await this.send({event:i,data:{chunk:a},run_id:e.id,name:s.name,tags:s.tags,metadata:s.metadata},s)}}async onLLMEnd(e){var i,o,c;const t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const s=(i=e.outputs)==null?void 0:i.generations;let a;if(t.runType==="chat_model"){for(const l of s??[]){if(a!==void 0)break;a=(o=l[0])==null?void 0:o.message}n="on_chat_model_end"}else if(t.runType==="llm")a={generations:s==null?void 0:s.map(l=>l.map(u=>({text:u.text,generationInfo:u.generationInfo}))),llmOutput:((c=e.outputs)==null?void 0:c.llmOutput)??{}},n="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:a,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){var i,o;const t=_a(e),n=e.run_type??"chain",s={tags:e.tags??[],metadata:((i=e.extra)==null?void 0:i.metadata)??{},name:t,runType:e.run_type};let a={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(a={},s.inputs={}):e.inputs.input!==void 0?(a.input=e.inputs.input,s.inputs=e.inputs.input):(a.input=e.inputs,s.inputs=e.inputs),this.runInfoMap.set(e.id,s),await this.send({event:`on_${n}_start`,data:a,name:t,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},s)}async onChainEnd(e){var o;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const n=`on_${e.run_type}_end`,s=e.inputs??t.inputs??{},i={output:((o=e.outputs)==null?void 0:o.output)??e.outputs,input:s};s.input&&Object.keys(s).length===1&&(i.input=s.input,t.inputs=s.input),await this.sendEndEvent({event:n,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){var s,a;const t=_a(e),n={tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{}},n)}async onToolEnd(e){var s;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const n=((s=e.outputs)==null?void 0:s.output)===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){var a,i;const t=_a(e),s={tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,s),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:((i=e.extra)==null?void 0:i.metadata)??{}},s)}async onRetrieverEnd(e){var n;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:((n=e.outputs)==null?void 0:n.documents)??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){const s=this.runInfoMap.get(n);if(s===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:e,tags:s.tags,metadata:s.metadata,data:t},s)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},_S={};pe(_S,{AsyncCaller:()=>Js});const yS=[400,401,402,403,404,405,406,407,409],wS=r=>{var t,n;if(r.message.startsWith("Cancel")||r.message.startsWith("AbortError")||r.name==="AbortError"||(r==null?void 0:r.code)==="ECONNABORTED")throw r;const e=((t=r==null?void 0:r.response)==null?void 0:t.status)??(r==null?void 0:r.status);if(e&&yS.includes(+e))throw r;if(((n=r==null?void 0:r.error)==null?void 0:n.code)==="insufficient_quota"){const s=new Error(r==null?void 0:r.message);throw s.name="InsufficientQuotaError",s}};var Js=class{constructor(r){w(this,"maxConcurrency");w(this,"maxRetries");w(this,"onFailedAttempt");w(this,"queue");this.maxConcurrency=r.maxConcurrency??1/0,this.maxRetries=r.maxRetries??6,this.onFailedAttempt=r.onFailedAttempt??wS;const e="default"in mr?mr.default:mr;this.queue=new e({concurrency:this.maxConcurrency})}call(r,...e){return this.queue.add(()=>ui(()=>r(...e).catch(t=>{throw t instanceof Error?t:new Error(t)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(r,e,...t){return r.signal?Promise.race([this.call(e,...t),new Promise((n,s)=>{var a;(a=r.signal)==null||a.addEventListener("abort",()=>{s(ks(r.signal))})})]):this.call(e,...t)}fetch(...r){return this.call(()=>fetch(...r).then(e=>e.ok?e:Promise.reject(e)))}},zm=class extends Pn{constructor({config:e,onStart:t,onEnd:n,onError:s}){super({_awaitHandler:!0});w(this,"name","RootListenersTracer");w(this,"rootId");w(this,"config");w(this,"argOnStart");w(this,"argOnEnd");w(this,"argOnError");this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=s}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function Nu(r){return r?r.lc_runnable:!1}var bS=class{constructor(r){w(this,"includeNames");w(this,"includeTypes");w(this,"includeTags");w(this,"excludeNames");w(this,"excludeTypes");w(this,"excludeTags");this.includeNames=r.includeNames,this.includeTypes=r.includeTypes,this.includeTags=r.includeTags,this.excludeNames=r.excludeNames,this.excludeTypes=r.excludeTypes,this.excludeTags=r.excludeTags}includeEvent(r,e){let t=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const n=r.tags??[];return this.includeNames!==void 0&&(t=t||this.includeNames.includes(r.name)),this.includeTypes!==void 0&&(t=t||this.includeTypes.includes(e)),this.includeTags!==void 0&&(t=t||n.some(s=>{var a;return(a=this.includeTags)==null?void 0:a.includes(s)})),this.excludeNames!==void 0&&(t=t&&!this.excludeNames.includes(r.name)),this.excludeTypes!==void 0&&(t=t&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(t=t&&n.every(s=>{var a;return!((a=this.excludeTags)!=null&&a.includes(s))})),t}};function Nn(r,e,t){function n(o,c){var l;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(l=o._zod).traits??(l.traits=new Set),o._zod.traits.add(r),e(o,c);for(const u in i.prototype)u in o||Object.defineProperty(o,u,{value:i.prototype[u].bind(o)});o._zod.constr=i,o._zod.def=c}const s=(t==null?void 0:t.Parent)??Object;class a extends s{}Object.defineProperty(a,"name",{value:r});function i(o){var c;const l=t!=null&&t.Parent?new a:this;n(l,o),(c=l._zod).deferred??(c.deferred=[]);for(const u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>{var c,l;return t!=null&&t.Parent&&o instanceof t.Parent?!0:(l=(c=o==null?void 0:o._zod)==null?void 0:c.traits)==null?void 0:l.has(r)}}),Object.defineProperty(i,"name",{value:r}),i}class gi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const vS={};function Zi(r){return vS}function SS(r){const e=Object.values(r).filter(n=>typeof n=="number");return Object.entries(r).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function ES(r,e){return typeof e=="bigint"?e.toString():e}function TS(r){const e=r.startsWith("^")?1:0,t=r.endsWith("$")?r.length-1:r.length;return r.slice(e,t)}function uf(r,e,t){Object.defineProperty(r,e,{get(){{const n=t();return r[e]=n,n}},set(n){Object.defineProperty(r,e,{value:n})},configurable:!0})}function xS(r,e,t){Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}const Hm=Error.captureStackTrace?Error.captureStackTrace:(...r)=>{};function df(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function AS(r){if(df(r)===!1)return!1;const e=r.constructor;if(e===void 0)return!0;const t=e.prototype;return!(df(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function wr(r,e,t){const n=new r._zod.constr(e??r._zod.def);return(!e||t!=null&&t.parent)&&(n._zod.parent=r),n}function IS(r){return{}}function RS(r,e){if(!AS(e))throw new Error("Invalid input to extend: expected a plain object");const t={...r._zod.def,get shape(){const n={...r._zod.def.shape,...e};return xS(this,"shape",n),n},checks:[]};return wr(r,t)}function OS(r,e,t){const n=e._zod.def.shape,s={...n};for(const a in n)s[a]=r?new r({type:"optional",innerType:n[a]}):n[a];return wr(e,{...e._zod.def,shape:s,checks:[]})}function Uc(r,e=0){var t;for(let n=e;n<r.issues.length;n++)if(((t=r.issues[n])==null?void 0:t.continue)!==!0)return!0;return!1}function ya(r){return typeof r=="string"?r:r==null?void 0:r.message}function Xi(r,e,t){var s,a,i,o,c,l;const n={...r,path:r.path??[]};if(!r.message){const u=ya((i=(a=(s=r.inst)==null?void 0:s._zod.def)==null?void 0:a.error)==null?void 0:i.call(a,r))??ya((o=e==null?void 0:e.error)==null?void 0:o.call(e,r))??ya((c=t.customError)==null?void 0:c.call(t,r))??ya((l=t.localeError)==null?void 0:l.call(t,r))??"Invalid input";n.message=u}return delete n.inst,delete n.continue,e!=null&&e.reportInput||delete n.input,n}const Wm=(r,e)=>{r.name="$ZodError",Object.defineProperty(r,"_zod",{value:r._zod,enumerable:!1}),Object.defineProperty(r,"issues",{value:e,enumerable:!1}),Object.defineProperty(r,"message",{get(){return JSON.stringify(e,ES,2)},enumerable:!0}),Object.defineProperty(r,"toString",{value:()=>r.message,enumerable:!1})},$S=Nn("$ZodError",Wm),Yi=Nn("$ZodError",Wm,{Parent:Error});function CS(r){const e=[];for(const t of r)typeof t=="number"?e.push(`[${t}]`):typeof t=="symbol"?e.push(`[${JSON.stringify(String(t))}]`):/[^\w$]/.test(t)?e.push(`[${JSON.stringify(t)}]`):(e.length&&e.push("."),e.push(t));return e.join("")}function kS(r){var n;const e=[],t=[...r.issues].sort((s,a)=>s.path.length-a.path.length);for(const s of t)e.push(`✖ ${s.message}`),(n=s.path)!=null&&n.length&&e.push(` → at ${CS(s.path)}`);return e.join(`
58
+ `)}const PS=r=>(e,t,n,s)=>{const a=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise)throw new gi;if(i.issues.length){const o=new((s==null?void 0:s.Err)??r)(i.issues.map(c=>Xi(c,a,Zi())));throw Hm(o,s==null?void 0:s.callee),o}return i.value},Qi=PS(Yi),NS=r=>async(e,t,n,s)=>{const a=n?Object.assign(n,{async:!0}):{async:!0};let i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const o=new((s==null?void 0:s.Err)??r)(i.issues.map(c=>Xi(c,a,Zi())));throw Hm(o,s==null?void 0:s.callee),o}return i.value},Gm=NS(Yi),LS=r=>(e,t,n)=>{const s=n?{...n,async:!1}:{async:!1},a=e._zod.run({value:t,issues:[]},s);if(a instanceof Promise)throw new gi;return a.issues.length?{success:!1,error:new(r??$S)(a.issues.map(i=>Xi(i,s,Zi())))}:{success:!0,data:a.value}},MS=LS(Yi),jS=r=>async(e,t,n)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let a=e._zod.run({value:t,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new r(a.issues.map(i=>Xi(i,s,Zi())))}:{success:!0,data:a.value}},DS=jS(Yi),US={major:4,minor:0,patch:0},Lu=Nn("$ZodType",(r,e)=>{var s;var t;r??(r={}),r._zod.def=e,r._zod.bag=r._zod.bag||{},r._zod.version=US;const n=[...r._zod.def.checks??[]];r._zod.traits.has("$ZodCheck")&&n.unshift(r);for(const a of n)for(const i of a._zod.onattach)i(r);if(n.length===0)(t=r._zod).deferred??(t.deferred=[]),(s=r._zod.deferred)==null||s.push(()=>{r._zod.run=r._zod.parse});else{const a=(i,o,c)=>{let l=Uc(i),u;for(const d of o){if(d._zod.def.when){if(!d._zod.def.when(i))continue}else if(l)continue;const h=i.issues.length,f=d._zod.check(i);if(f instanceof Promise&&(c==null?void 0:c.async)===!1)throw new gi;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,i.issues.length!==h&&(l||(l=Uc(i,h)))});else{if(i.issues.length===h)continue;l||(l=Uc(i,h))}}return u?u.then(()=>i):i};r._zod.run=(i,o)=>{const c=r._zod.parse(i,o);if(c instanceof Promise){if(o.async===!1)throw new gi;return c.then(l=>a(l,n,o))}return a(c,n,o)}}r["~standard"]={validate:a=>{var i;try{const o=MS(r,a);return o.success?{value:o.data}:{issues:(i=o.error)==null?void 0:i.issues}}catch{return DS(r,a).then(c=>{var l;return c.success?{value:c.data}:{issues:(l=c.error)==null?void 0:l.issues}})}},vendor:"zod",version:1}}),FS=Nn("$ZodUnknown",(r,e)=>{Lu.init(r,e),r._zod.parse=t=>t}),BS=Nn("$ZodNever",(r,e)=>{Lu.init(r,e),r._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:r}),t)}),Jm=Nn("$ZodOptional",(r,e)=>{Lu.init(r,e),r._zod.optin="optional",r._zod.optout="optional",uf(r._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),uf(r._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${TS(t.source)})?$`):void 0}),r._zod.parse=(t,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(t,n):t.value===void 0?t:e.innerType._zod.run(t,n)});class Vm{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const n=t[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function qS(){return new Vm}const lt=qS();function zS(r){return new r({type:"unknown"})}function HS(r,e){return new r({type:"never",...IS()})}class hf{constructor(e){this.counter=0,this.metadataRegistry=(e==null?void 0:e.metadata)??lt,this.target=(e==null?void 0:e.target)??"draft-2020-12",this.unrepresentable=(e==null?void 0:e.unrepresentable)??"throw",this.override=(e==null?void 0:e.override)??(()=>{}),this.io=(e==null?void 0:e.io)??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var d,h,f;var n;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,t.schemaPath.includes(e)&&(i.cycle=t.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,o);const c=(h=(d=e._zod).toJSONSchema)==null?void 0:h.call(d);if(c)o.schema=c;else{const p={...t,schemaPath:[...t.schemaPath,e],path:t.path},g=e._zod.parent;if(g)o.ref=g,this.process(g,p),this.seen.get(g).isParent=!0;else{const _=o.schema;switch(s.type){case"string":{const b=_;b.type="string";const{minimum:m,maximum:y,format:T,patterns:x,contentEncoding:R}=e._zod.bag;if(typeof m=="number"&&(b.minLength=m),typeof y=="number"&&(b.maxLength=y),T&&(b.format=a[T]??T,b.format===""&&delete b.format),R&&(b.contentEncoding=R),x&&x.size>0){const $=[...x];$.length===1?b.pattern=$[0].source:$.length>1&&(o.schema.allOf=[...$.map(E=>({...this.target==="draft-7"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{const b=_,{minimum:m,maximum:y,format:T,multipleOf:x,exclusiveMaximum:R,exclusiveMinimum:$}=e._zod.bag;typeof T=="string"&&T.includes("int")?b.type="integer":b.type="number",typeof $=="number"&&(b.exclusiveMinimum=$),typeof m=="number"&&(b.minimum=m,typeof $=="number"&&($>=m?delete b.minimum:delete b.exclusiveMinimum)),typeof R=="number"&&(b.exclusiveMaximum=R),typeof y=="number"&&(b.maximum=y,typeof R=="number"&&(R<=y?delete b.maximum:delete b.exclusiveMaximum)),typeof x=="number"&&(b.multipleOf=x);break}case"boolean":{const b=_;b.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":{_.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":{_.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const b=_,{minimum:m,maximum:y}=e._zod.bag;typeof m=="number"&&(b.minItems=m),typeof y=="number"&&(b.maxItems=y),b.type="array",b.items=this.process(s.element,{...p,path:[...p.path,"items"]});break}case"object":{const b=_;b.type="object",b.properties={};const m=s.shape;for(const x in m)b.properties[x]=this.process(m[x],{...p,path:[...p.path,"properties",x]});const y=new Set(Object.keys(m)),T=new Set([...y].filter(x=>{const R=s.shape[x]._zod;return this.io==="input"?R.optin===void 0:R.optout===void 0}));T.size>0&&(b.required=Array.from(T)),((f=s.catchall)==null?void 0:f._zod.def.type)==="never"?b.additionalProperties=!1:s.catchall?s.catchall&&(b.additionalProperties=this.process(s.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(b.additionalProperties=!1);break}case"union":{const b=_;b.anyOf=s.options.map((m,y)=>this.process(m,{...p,path:[...p.path,"anyOf",y]}));break}case"intersection":{const b=_,m=this.process(s.left,{...p,path:[...p.path,"allOf",0]}),y=this.process(s.right,{...p,path:[...p.path,"allOf",1]}),T=R=>"allOf"in R&&Object.keys(R).length===1,x=[...T(m)?m.allOf:[m],...T(y)?y.allOf:[y]];b.allOf=x;break}case"tuple":{const b=_;b.type="array";const m=s.items.map((x,R)=>this.process(x,{...p,path:[...p.path,"prefixItems",R]}));if(this.target==="draft-2020-12"?b.prefixItems=m:b.items=m,s.rest){const x=this.process(s.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?b.items=x:b.additionalItems=x}s.rest&&(b.items=this.process(s.rest,{...p,path:[...p.path,"items"]}));const{minimum:y,maximum:T}=e._zod.bag;typeof y=="number"&&(b.minItems=y),typeof T=="number"&&(b.maxItems=T);break}case"record":{const b=_;b.type="object",b.propertyNames=this.process(s.keyType,{...p,path:[...p.path,"propertyNames"]}),b.additionalProperties=this.process(s.valueType,{...p,path:[...p.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 b=_,m=SS(s.entries);m.every(y=>typeof y=="number")&&(b.type="number"),m.every(y=>typeof y=="string")&&(b.type="string"),b.enum=m;break}case"literal":{const b=_,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];b.type=y===null?"null":typeof y,b.const=y}else m.every(y=>typeof y=="number")&&(b.type="number"),m.every(y=>typeof y=="string")&&(b.type="string"),m.every(y=>typeof y=="boolean")&&(b.type="string"),m.every(y=>y===null)&&(b.type="null"),b.enum=m;break}case"file":{const b=_,m={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:T,mime:x}=e._zod.bag;y!==void 0&&(m.minLength=y),T!==void 0&&(m.maxLength=T),x?x.length===1?(m.contentMediaType=x[0],Object.assign(b,m)):b.anyOf=x.map(R=>({...m,contentMediaType:R})):Object.assign(b,m);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const b=this.process(s.innerType,p);_.anyOf=[b,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,p),o.ref=s.innerType;break}case"success":{const b=_;b.type="boolean";break}case"default":{this.process(s.innerType,p),o.ref=s.innerType,_.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,p),o.ref=s.innerType,this.io==="input"&&(_._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,p),o.ref=s.innerType;let b;try{b=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}_.default=b;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const b=_,m=e._zod.pattern;if(!m)throw new Error("Pattern not found in template literal");b.type="string",b.pattern=m.source;break}case"pipe":{const b=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(b,p),o.ref=b;break}case"readonly":{this.process(s.innerType,p),o.ref=s.innerType,_.readOnly=!0;break}case"promise":{this.process(s.innerType,p),o.ref=s.innerType;break}case"optional":{this.process(s.innerType,p),o.ref=s.innerType;break}case"lazy":{const b=e._zod.innerType;this.process(b,p),o.ref=b;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const l=this.metadataRegistry.get(e);return l&&Object.assign(o.schema,l),this.io==="input"&&Fe(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,t){var u,d,h,f,p,g;const n={cycles:(t==null?void 0:t.cycles)??"ref",reused:(t==null?void 0:t.reused)??"inline",external:(t==null?void 0:t.external)??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=_=>{var x;const b=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const R=(x=n.external.registry.get(_[0]))==null?void 0:x.id,$=n.external.uri??(J=>J);if(R)return{ref:$(R)};const E=_[1].defId??_[1].schema.id??`schema${this.counter++}`;return _[1].defId=E,{defId:E,ref:`${$("__shared")}#/${b}/${E}`}}if(_[1]===s)return{ref:"#"};const y=`#/${b}/`,T=_[1].schema.id??`__schema${this.counter++}`;return{defId:T,ref:y+T}},i=_=>{if(_[1].schema.$ref)return;const b=_[1],{ref:m,defId:y}=a(_);b.def={...b.schema},y&&(b.defId=y);const T=b.schema;for(const x in T)delete T[x];T.$ref=m};if(n.cycles==="throw")for(const _ of this.seen.entries()){const b=_[1];if(b.cycle)throw new Error(`Cycle detected: #/${(u=b.cycle)==null?void 0:u.join("/")}/<root>
59
+
60
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const _ of this.seen.entries()){const b=_[1];if(e===_[0]){i(_);continue}if(n.external){const y=(d=n.external.registry.get(_[0]))==null?void 0:d.id;if(e!==_[0]&&y){i(_);continue}}if((h=this.metadataRegistry.get(_[0]))==null?void 0:h.id){i(_);continue}if(b.cycle){i(_);continue}if(b.count>1&&n.reused==="ref"){i(_);continue}}const o=(_,b)=>{const m=this.seen.get(_),y=m.def??m.schema,T={...y};if(m.ref===null)return;const x=m.ref;if(m.ref=null,x){o(x,b);const R=this.seen.get(x).schema;R.$ref&&b.target==="draft-7"?(y.allOf=y.allOf??[],y.allOf.push(R)):(Object.assign(y,R),Object.assign(y,T))}m.isParent||this.override({zodSchema:_,jsonSchema:y,path:m.path??[]})};for(const _ of[...this.seen.entries()].reverse())o(_[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}`),(f=n.external)!=null&&f.uri){const _=(p=n.external.registry.get(e))==null?void 0:p.id;if(!_)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(_)}Object.assign(c,s.def);const l=((g=n.external)==null?void 0:g.defs)??{};for(const _ of this.seen.entries()){const b=_[1];b.def&&b.defId&&(l[b.defId]=b.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}function Ol(r,e){if(r instanceof Vm){const n=new hf(e),s={};for(const o of r._idmap.entries()){const[c,l]=o;n.process(l)}const a={},i={registry:r,uri:e==null?void 0:e.uri,defs:s};for(const o of r._idmap.entries()){const[c,l]=o;a[c]=n.emit(l,{...e,external:i})}if(Object.keys(s).length>0){const o=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[o]:s}}return{schemas:a}}const t=new hf(e);return t.process(r),t.emit(r,e)}function Fe(r,e){const t=e??{seen:new Set};if(t.seen.has(r))return!1;t.seen.add(r);const s=r._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 Fe(s.element,t);case"object":{for(const a in s.shape)if(Fe(s.shape[a],t))return!0;return!1}case"union":{for(const a of s.options)if(Fe(a,t))return!0;return!1}case"intersection":return Fe(s.left,t)||Fe(s.right,t);case"tuple":{for(const a of s.items)if(Fe(a,t))return!0;return!!(s.rest&&Fe(s.rest,t))}case"record":return Fe(s.keyType,t)||Fe(s.valueType,t);case"map":return Fe(s.keyType,t)||Fe(s.valueType,t);case"set":return Fe(s.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Fe(s.innerType,t);case"lazy":return Fe(s.getter(),t);case"default":return Fe(s.innerType,t);case"prefault":return Fe(s.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return Fe(s.in,t)||Fe(s.out,t);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}function $e(r){if(typeof r!="object"||r===null)return!1;const e=r;if(!("_zod"in e))return!1;const t=e._zod;return typeof t=="object"&&t!==null&&"def"in t}function je(r){if(typeof r!="object"||r===null)return!1;const e=r;if(!("_def"in e)||"_zod"in e)return!1;const t=e._def;return typeof t=="object"&&t!=null&&"typeName"in t}function WS(r){return $e(r)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),je(r)}function Rt(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!($e(r)||je(r))}function Km(r){return typeof r=="object"&&r!==null&&"_def"in r&&typeof r._def=="object"&&r._def!==null&&"typeName"in r._def&&r._def.typeName==="ZodLiteral"}function Zm(r){return $e(r)?typeof r=="object"&&r!==null&&"_zod"in r&&typeof r._zod=="object"&&r._zod!==null&&"def"in r._zod&&typeof r._zod.def=="object"&&r._zod.def!==null&&"type"in r._zod.def&&r._zod.def.type==="literal":!1}function GS(r){return!!(Km(r)||Zm(r))}async function Mu(r,e){if($e(r))try{return{success:!0,data:await Gm(r,e)}}catch(t){return{success:!1,error:t}}if(je(r))return await r.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function eo(r,e){if($e(r))return await Gm(r,e);if(je(r))return await r.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function JS(r,e){if($e(r))try{return{success:!0,data:Qi(r,e)}}catch(t){return{success:!1,error:t}}if(je(r))return r.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function VS(r,e){if($e(r))return Qi(r,e);if(je(r))return r.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function to(r){var e;if($e(r))return(e=lt.get(r))==null?void 0:e.description;if(je(r)||"description"in r&&typeof r.description=="string")return r.description}function KS(r){if(!Rt(r))return!1;if(je(r)){const e=r._def;if(e.typeName==="ZodObject"){const t=r;return!t.shape||Object.keys(t.shape).length===0}if(e.typeName==="ZodRecord")return!0}if($e(r)){const e=r._zod.def;if(e.type==="object"){const t=r;return!t.shape||Object.keys(t.shape).length===0}if(e.type==="record")return!0}return typeof r=="object"&&r!==null&&!("shape"in r)}function ju(r){return Rt(r)?je(r)?r._def.typeName==="ZodString":$e(r)?r._zod.def.type==="string":!1:!1}function Du(r){return typeof r=="object"&&r!==null&&"_def"in r&&typeof r._def=="object"&&r._def!==null&&"typeName"in r._def&&r._def.typeName==="ZodObject"}function ar(r){return $e(r)?typeof r=="object"&&r!==null&&"_zod"in r&&typeof r._zod=="object"&&r._zod!==null&&"def"in r._zod&&typeof r._zod.def=="object"&&r._zod.def!==null&&"type"in r._zod.def&&r._zod.def.type==="object":!1}function ro(r){return $e(r)?typeof r=="object"&&r!==null&&"_zod"in r&&typeof r._zod=="object"&&r._zod!==null&&"def"in r._zod&&typeof r._zod.def=="object"&&r._zod.def!==null&&"type"in r._zod.def&&r._zod.def.type==="array":!1}function ZS(r){return!!(Du(r)||ar(r))}function $l(r){if(je(r))return r.shape;if($e(r))return r._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function XS(r,e){if(je(r))return r.extend(e);if($e(r))return RS(r,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function YS(r){if(je(r))return r.partial();if($e(r))return OS(Jm,r);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function _i(r,e=!1){if(je(r))return r.strict();if(ar(r)){const t=r._zod.def.shape;if(e)for(const[a,i]of Object.entries(r._zod.def.shape)){if(ar(i)){const c=_i(i,e);t[a]=c}else if(ro(i)){let c=i._zod.def.element;ar(c)&&(c=_i(c,e)),t[a]=wr(i,{...i._zod.def,element:c})}else t[a]=i;const o=lt.get(i);o&&lt.add(t[a],o)}const n=wr(r,{...r._zod.def,shape:t,catchall:HS(BS)}),s=lt.get(r);return s&&lt.add(n,s),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Cl(r,e=!1){if(Du(r))return r.passthrough();if(ar(r)){const t=r._zod.def.shape;if(e)for(const[a,i]of Object.entries(r._zod.def.shape)){if(ar(i)){const c=Cl(i,e);t[a]=c}else if(ro(i)){let c=i._zod.def.element;ar(c)&&(c=Cl(c,e)),t[a]=wr(i,{...i._zod.def,element:c})}else t[a]=i;const o=lt.get(i);o&&lt.add(t[a],o)}const n=wr(r,{...r._zod.def,shape:t,catchall:zS(FS)}),s=lt.get(r);return s&&lt.add(n,s),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function QS(r){if(je(r))try{const e=r.parse(void 0);return()=>e}catch{return}if($e(r))try{const e=Qi(r,void 0);return()=>e}catch{return}}function eE(r){return je(r)&&"typeName"in r._def&&r._def.typeName==="ZodEffects"}function tE(r){return $e(r)&&r._zod.def.type==="pipe"}function Tn(r,e=!1){if(je(r))return eE(r)?Tn(r._def.schema,e):r;if($e(r)){let t=r;if(tE(r)&&(t=Tn(r._zod.def.in,e)),e){if(ar(t)){const s=t._zod.def.shape;for(const[a,i]of Object.entries(t._zod.def.shape))s[a]=Tn(i,e);t=wr(t,{...t._zod.def,shape:s})}else if(ro(t)){const s=Tn(t._zod.def.element,e);t=wr(t,{...t._zod.def,element:s})}}const n=lt.get(r);return n&&lt.add(t,n),t}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function rE(r,e){if(je(r)){const t=$l(r),n={};for(const[s,a]of Object.entries(t))e(s,a)?n[s]=a.optional():n[s]=a;return r.extend(n)}if($e(r)){const t=$l(r),n={...r._zod.def.shape};for(const[i,o]of Object.entries(t))e(i,o)&&(n[i]=new Jm({type:"optional",innerType:o}));const s=wr(r,{...r._zod.def,shape:n}),a=lt.get(r);return a&&lt.add(s,a),s}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Fc(r){return r.replace(/[^a-zA-Z-_0-9]/g,"_")}const nE=["*","_","`"];function sE(r){let e="";for(const[t,n]of Object.entries(r))e+=` classDef ${t} ${n};
61
+ `;return e}function aE(r,e,t){const{firstNode:n,lastNode:s,nodeColors:a,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=t??{};let l=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
62
+ graph TD;
63
+ `:`graph TD;
64
+ `;if(i){const f="default",p={[f]:"{0}({1})"};n!==void 0&&(p[n]="{0}([{1}]):::first"),s!==void 0&&(p[s]="{0}([{1}]):::last");for(const[g,_]of Object.entries(r)){const b=_.name.split(":").pop()??"";let y=nE.some(x=>b.startsWith(x)&&b.endsWith(x))?`<p>${b}</p>`:b;Object.keys(_.metadata??{}).length&&(y+=`<hr/><small><em>${Object.entries(_.metadata??{}).map(([x,R])=>`${x} = ${R}`).join(`
65
+ `)}</em></small>`);const T=(p[g]??p[f]).replace("{0}",Fc(g)).replace("{1}",y);l+=` ${T}
66
+ `}}const u={};for(const f of e){const p=f.source.split(":"),g=f.target.split(":"),_=p.filter((b,m)=>b===g[m]).join(":");u[_]||(u[_]=[]),u[_].push(f)}const d=new Set;function h(f,p){const g=f.length===1&&f[0].source===f[0].target;if(p&&!g){const _=p.split(":").pop();if(d.has(_))throw new Error(`Found duplicate subgraph '${_}' -- 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(_),l+=` subgraph ${_}
67
+ `}for(const _ of f){const{source:b,target:m,data:y,conditional:T}=_;let x="";if(y!==void 0){let R=y;const $=R.split(" ");$.length>c&&(R=Array.from({length:Math.ceil($.length/c)},(E,J)=>$.slice(J*c,(J+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),x=T?` -. &nbsp;${R}&nbsp; .-> `:` -- &nbsp;${R}&nbsp; --> `}else x=T?" -.-> ":" --> ";l+=` ${Fc(b)}${x}${Fc(m)};
68
+ `}for(const _ in u)_.startsWith(`${p}:`)&&_!==p&&h(u[_],_);p&&!g&&(l+=` end
69
+ `)}h(u[""]??[],"");for(const f in u)!f.includes(":")&&f!==""&&h(u[f],f);return i&&(l+=sE(a??{})),l}async function iE(r,e){let t=(e==null?void 0:e.backgroundColor)??"white";const n=(e==null?void 0:e.imageType)??"png",s=btoa(r);t!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(t)||(t=`!${t}`));const a=`https://mermaid.ink/img/${s}?bgColor=${t}&type=${n}`,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(`
70
+ `));return await i.blob()}const oE=Symbol("Let zodToJsonSchema decide on which parser to use"),cE={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"},lE=r=>({...cE,...r}),uE=r=>{const e=lE(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},Xm=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};function Et(r){if(r.target!=="openAi")return{};const e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?Xm(e,r.currentPath):e.join("/")}}function Ym(r,e,t,n){n!=null&&n.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function be(r,e,t,n,s){r[e]=t,Ym(r,e,n,s)}function dE(r,e){var n,s,a;const t={type:"array"};return(n=r.type)!=null&&n._def&&((a=(s=r.type)==null?void 0:s._def)==null?void 0:a.typeName)!==L.ZodAny&&(t.items=we(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&be(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&be(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(be(t,"minItems",r.exactLength.value,r.exactLength.message,e),be(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function hE(r,e){const t={type:"integer",format:"int64"};if(!r.checks)return t;for(const n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?be(t,"minimum",n.value,n.message,e):be(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),be(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?be(t,"maximum",n.value,n.message,e):be(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),be(t,"maximum",n.value,n.message,e));break;case"multipleOf":be(t,"multipleOf",n.value,n.message,e);break}return t}function fE(){return{type:"boolean"}}function Qm(r,e){return we(r.type._def,e)}const pE=(r,e)=>we(r.innerType._def,e);function eg(r,e,t){const n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(s=>eg(r,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return mE(r,e)}}const mE=(r,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const n of r.checks)switch(n.kind){case"min":be(t,"minimum",n.value,n.message,e);break;case"max":be(t,"maximum",n.value,n.message,e);break}return t};function gE(r,e){return{...we(r.innerType._def,e),default:r.defaultValue()}}function _E(r,e){return e.effectStrategy==="input"?we(r.schema._def,e):Et(e)}function yE(r){return{type:"string",enum:Array.from(r.values)}}const wE=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function bE(r,e){const t=[we(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),we(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return t.forEach(a=>{if(wE(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}function vE(r,e){const t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}let Bc;const $t={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:()=>(Bc===void 0&&(Bc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Bc),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 tg(r,e){const t={type:"string"};if(r.checks)for(const n of r.checks)switch(n.kind){case"min":be(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":be(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ct(t,"email",n.message,e);break;case"format:idn-email":Ct(t,"idn-email",n.message,e);break;case"pattern:zod":Qe(t,$t.email,n.message,e);break}break;case"url":Ct(t,"uri",n.message,e);break;case"uuid":Ct(t,"uuid",n.message,e);break;case"regex":Qe(t,n.regex,n.message,e);break;case"cuid":Qe(t,$t.cuid,n.message,e);break;case"cuid2":Qe(t,$t.cuid2,n.message,e);break;case"startsWith":Qe(t,RegExp(`^${qc(n.value,e)}`),n.message,e);break;case"endsWith":Qe(t,RegExp(`${qc(n.value,e)}$`),n.message,e);break;case"datetime":Ct(t,"date-time",n.message,e);break;case"date":Ct(t,"date",n.message,e);break;case"time":Ct(t,"time",n.message,e);break;case"duration":Ct(t,"duration",n.message,e);break;case"length":be(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),be(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":Qe(t,RegExp(qc(n.value,e)),n.message,e);break;case"ip":n.version!=="v6"&&Ct(t,"ipv4",n.message,e),n.version!=="v4"&&Ct(t,"ipv6",n.message,e);break;case"base64url":Qe(t,$t.base64url,n.message,e);break;case"jwt":Qe(t,$t.jwt,n.message,e);break;case"cidr":n.version!=="v6"&&Qe(t,$t.ipv4Cidr,n.message,e),n.version!=="v4"&&Qe(t,$t.ipv6Cidr,n.message,e);break;case"emoji":Qe(t,$t.emoji(),n.message,e);break;case"ulid":Qe(t,$t.ulid,n.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":Ct(t,"binary",n.message,e);break;case"contentEncoding:base64":be(t,"contentEncoding","base64",n.message,e);break;case"pattern:zod":Qe(t,$t.base64,n.message,e);break}break;case"nanoid":Qe(t,$t.nanoid,n.message,e);break}return t}function qc(r,e){return e.patternStrategy==="escape"?EE(r):r}const SE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function EE(r){let e="";for(let t=0;t<r.length;t++)SE.has(r[t])||(e+="\\"),e+=r[t];return e}function Ct(r,e,t,n){var s;r.format||(s=r.anyOf)!=null&&s.some(a=>a.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):be(r,"format",e,t,n)}function Qe(r,e,t,n){var s;r.pattern||(s=r.allOf)!=null&&s.some(a=>a.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:ff(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):be(r,"pattern",ff(e,n),t,n)}function ff(r,e){var c;if(!e.applyRegexFlags||!r.flags)return r.source;const t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source;let s="",a=!1,i=!1,o=!1;for(let l=0;l<n.length;l++){if(a){s+=n[l],a=!1;continue}if(t.i){if(i){if(n[l].match(/[a-z]/)){o?(s+=n[l],s+=`${n[l-2]}-${n[l]}`.toUpperCase(),o=!1):n[l+1]==="-"&&((c=n[l+2])!=null&&c.match(/[a-z]/))?(s+=n[l],o=!0):s+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){s+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(t.m){if(n[l]==="^"){s+=`(^|(?<=[\r
71
+ ]))`;continue}else if(n[l]==="$"){s+=`($|(?=[\r
72
+ ]))`;continue}}if(t.s&&n[l]==="."){s+=i?`${n[l]}\r
73
+ `:`[${n[l]}\r
74
+ ]`;continue}s+=n[l],n[l]==="\\"?a=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(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`),r.source}return s}function rg(r,e){var n,s,a,i,o,c;if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&((n=r.keyType)==null?void 0:n._def.typeName)===L.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((l,u)=>({...l,[u]:we(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",u]})??Et(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const t={type:"object",additionalProperties:we(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(((s=r.keyType)==null?void 0:s._def.typeName)===L.ZodString&&((a=r.keyType._def.checks)!=null&&a.length)){const{type:l,...u}=tg(r.keyType._def,e);return{...t,propertyNames:u}}else{if(((i=r.keyType)==null?void 0:i._def.typeName)===L.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(((o=r.keyType)==null?void 0:o._def.typeName)===L.ZodBranded&&r.keyType._def.type._def.typeName===L.ZodString&&((c=r.keyType._def.type._def.checks)!=null&&c.length)){const{type:l,...u}=Qm(r.keyType._def,e);return{...t,propertyNames:u}}}return t}function TE(r,e){if(e.mapStrategy==="record")return rg(r,e);const t=we(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Et(e),n=we(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Et(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function xE(r){const e=r.values,n=Object.keys(r.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(n.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function AE(r){return r.target==="openAi"?void 0:{not:Et({...r,currentPath:[...r.currentPath,"not"]})}}function IE(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const yi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function RE(r,e){if(e.target==="openApi3")return pf(r,e);const t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in yi&&(!n._def.checks||!n._def.checks.length))){const n=t.reduce((s,a)=>{const i=yi[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=t.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":return a._def.value===null?[...s,"null"]:s;case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===t.length){const s=n.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:t.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,s)=>[...n,...s._def.values.filter(a=>!n.includes(a))],[])};return pf(r,e)}const pf=(r,e)=>{const t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,s)=>we(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function OE(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:yi[r.innerType._def.typeName],nullable:!0}:{type:[yi[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=we(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const t=we(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function $E(r,e){const t={type:"number"};if(!r.checks)return t;for(const n of r.checks)switch(n.kind){case"int":t.type="integer",Ym(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?be(t,"minimum",n.value,n.message,e):be(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),be(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?be(t,"maximum",n.value,n.message,e):be(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),be(t,"maximum",n.value,n.message,e));break;case"multipleOf":be(t,"multipleOf",n.value,n.message,e);break}return t}function CE(r,e){const t=e.target==="openAi",n={type:"object",properties:{}},s=[],a=r.shape();for(const o in a){let c=a[o];if(c===void 0||c._def===void 0)continue;let l=PE(c);l&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=we(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});u!==void 0&&(n.properties[o]=u,l||s.push(o))}s.length&&(n.required=s);const i=kE(r,e);return i!==void 0&&(n.additionalProperties=i),n}function kE(r,e){if(r.catchall._def.typeName!=="ZodNever")return we(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function PE(r){try{return r.isOptional()}catch{return!0}}const NE=(r,e)=>{var n;if(e.currentPath.toString()===((n=e.propertyPath)==null?void 0:n.toString()))return we(r.innerType._def,e);const t=we(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:Et(e)},t]}:Et(e)},LE=(r,e)=>{if(e.pipeStrategy==="input")return we(r.in._def,e);if(e.pipeStrategy==="output")return we(r.out._def,e);const t=we(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=we(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(s=>s!==void 0)}};function ME(r,e){return we(r.type._def,e)}function jE(r,e){const n={type:"array",uniqueItems:!0,items:we(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&be(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&be(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function DE(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>we(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:we(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>we(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function UE(r){return{not:Et(r)}}function FE(r){return Et(r)}const BE=(r,e)=>we(r.innerType._def,e),qE=(r,e,t)=>{switch(e){case L.ZodString:return tg(r,t);case L.ZodNumber:return $E(r,t);case L.ZodObject:return CE(r,t);case L.ZodBigInt:return hE(r,t);case L.ZodBoolean:return fE();case L.ZodDate:return eg(r,t);case L.ZodUndefined:return UE(t);case L.ZodNull:return IE(t);case L.ZodArray:return dE(r,t);case L.ZodUnion:case L.ZodDiscriminatedUnion:return RE(r,t);case L.ZodIntersection:return bE(r,t);case L.ZodTuple:return DE(r,t);case L.ZodRecord:return rg(r,t);case L.ZodLiteral:return vE(r,t);case L.ZodEnum:return yE(r);case L.ZodNativeEnum:return xE(r);case L.ZodNullable:return OE(r,t);case L.ZodOptional:return NE(r,t);case L.ZodMap:return TE(r,t);case L.ZodSet:return jE(r,t);case L.ZodLazy:return()=>r.getter()._def;case L.ZodPromise:return ME(r,t);case L.ZodNaN:case L.ZodNever:return AE(t);case L.ZodEffects:return _E(r,t);case L.ZodAny:return Et(t);case L.ZodUnknown:return FE(t);case L.ZodDefault:return gE(r,t);case L.ZodBranded:return Qm(r,t);case L.ZodReadonly:return BE(r,t);case L.ZodCatch:return pE(r,t);case L.ZodPipeline:return LE(r,t);case L.ZodFunction:case L.ZodVoid:case L.ZodSymbol:return;default:return(n=>{})()}};function we(r,e,t=!1){var o;const n=e.seen.get(r);if(e.override){const c=(o=e.override)==null?void 0:o.call(e,r,e,n,t);if(c!==oE)return c}if(n&&!t){const c=zE(n,e);if(c!==void 0)return c}const s={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,s);const a=qE(r,r.typeName,e),i=typeof a=="function"?we(a(),e):a;if(i&&HE(r,e,i),e.postProcess){const c=e.postProcess(i,r,e);return s.jsonSchema=i,c}return s.jsonSchema=i,i}const zE=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:Xm(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Et(e)):e.$refStrategy==="seen"?Et(e):void 0}},HE=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t),WE=(r,e)=>{const t=uE(e);let n;const s=we(r._def,t,!1)??Et(t);t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));const a=n?{...s,[t.definitionPath]:n}:s;return t.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),t.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 Vr(r,e){const t=typeof r;if(t!==typeof e)return!1;if(Array.isArray(r)){if(!Array.isArray(e))return!1;const n=r.length;if(n!==e.length)return!1;for(let s=0;s<n;s++)if(!Vr(r[s],e[s]))return!1;return!0}if(t==="object"){if(!r||!e)return r===e;const n=Object.keys(r),s=Object.keys(e);if(n.length!==s.length)return!1;for(const i of n)if(!Vr(r[i],e[i]))return!1;return!0}return r===e}function Lt(r){return encodeURI(GE(r))}function GE(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}const JE={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},VE={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},KE={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 ZE=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 Cr(r,e=Object.create(null),t=ZE,n=""){if(r&&typeof r=="object"&&!Array.isArray(r)){const a=r.$id||r.id;if(a){const i=new URL(a,t.href);i.hash.length>1?e[i.href]=r:(i.hash="",n===""?t=i:Cr(r,e,t))}}else if(r!==!0&&r!==!1)return e;const s=t.href+(n?"#"+n:"");if(e[s]!==void 0)throw new Error(`Duplicate schema URI "${s}".`);if(e[s]=r,r===!0||r===!1)return e;if(r.__absolute_uri__===void 0&&Object.defineProperty(r,"__absolute_uri__",{enumerable:!1,value:s}),r.$ref&&r.__absolute_ref__===void 0){const a=new URL(r.$ref,t.href);a.hash=a.hash,Object.defineProperty(r,"__absolute_ref__",{enumerable:!1,value:a.href})}if(r.$recursiveRef&&r.__absolute_recursive_ref__===void 0){const a=new URL(r.$recursiveRef,t.href);a.hash=a.hash,Object.defineProperty(r,"__absolute_recursive_ref__",{enumerable:!1,value:a.href})}if(r.$anchor){const a=new URL("#"+r.$anchor,t.href);e[a.href]=r}for(let a in r){if(KE[a])continue;const i=`${n}/${Lt(a)}`,o=r[a];if(Array.isArray(o)){if(JE[a]){const c=o.length;for(let l=0;l<c;l++)Cr(o[l],e,t,`${i}/${l}`)}}else if(VE[a])for(let c in o)Cr(o[c],e,t,`${i}/${Lt(c)}`);else Cr(o,e,t,i)}return e}const XE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,YE=[0,31,28,31,30,31,30,31,31,30,31,30,31],QE=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,eT=/^(?=.{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,tT=/^(?:[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,rT=/^(?:(?:[^\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,nT=/^(?:(?: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,sT=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,aT=/^(?:\/(?:[^~/]|~0|~1)*)*$/,iT=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,oT=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,cT=r=>{if(r[0]==='"')return!1;const[e,t,...n]=r.split("@");return!e||!t||n.length!==0||e.length>64||t.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(t)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:t.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},lT=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,uT=/^((([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,dT=r=>r.length>1&&r.length<80&&(/^P\d+([.,]\d+)?W$/.test(r)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(r)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(r));function Qt(r){return r.test.bind(r)}const mf={date:ng,time:sg.bind(void 0,!1),"date-time":pT,duration:dT,uri:_T,"uri-reference":Qt(tT),"uri-template":Qt(rT),url:Qt(nT),email:cT,hostname:Qt(eT),ipv4:Qt(lT),ipv6:Qt(uT),regex:wT,uuid:Qt(sT),"json-pointer":Qt(aT),"json-pointer-uri-fragment":Qt(iT),"relative-json-pointer":Qt(oT)};function hT(r){return r%4===0&&(r%100!==0||r%400===0)}function ng(r){const e=r.match(XE);if(!e)return!1;const t=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&hT(t)?29:YE[n])}function sg(r,e){const t=e.match(QE);if(!t)return!1;const n=+t[1],s=+t[2],a=+t[3],i=!!t[5];return(n<=23&&s<=59&&a<=59||n==23&&s==59&&a==60)&&(!r||i)}const fT=/t|\s/i;function pT(r){const e=r.split(fT);return e.length==2&&ng(e[0])&&sg(!0,e[1])}const mT=/\/|:/,gT=/^(?:[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 _T(r){return mT.test(r)&&gT.test(r)}const yT=/[^\\]\\Z/;function wT(r){if(yT.test(r))return!1;try{return new RegExp(r,"u"),!0}catch{return!1}}function bT(r){let e=0,t=r.length,n=0,s;for(;n<t;)e++,s=r.charCodeAt(n++),s>=55296&&s<=56319&&n<t&&(s=r.charCodeAt(n),(s&64512)==56320&&n++);return e}function Ie(r,e,t="2019-09",n=Cr(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 l=typeof r;let u;switch(l){case"boolean":case"number":case"string":u=l;break;case"object":r===null?u="null":Array.isArray(r)?u="array":u="object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}const{$ref:d,$recursiveRef:h,$recursiveAnchor:f,type:p,const:g,enum:_,required:b,not:m,anyOf:y,allOf:T,oneOf:x,if:R,then:$,else:E,format:J,properties:se,patternProperties:H,additionalProperties:Ae,unevaluatedProperties:ft,minProperties:M,maxProperties:P,propertyNames:N,dependentRequired:W,dependentSchemas:V,dependencies:z,prefixItems:ee,items:de,additionalItems:oe,unevaluatedItems:ye,contains:Ce,minContains:me,maxContains:S,minItems:v,maxItems:C,uniqueItems:A,minimum:fe,maximum:Se,exclusiveMinimum:Ee,exclusiveMaximum:Ne,multipleOf:We,minLength:Ot,maxLength:Re,pattern:Tt,__absolute_ref__:nn,__absolute_recursive_ref__:ia}=e,D=[];if(f===!0&&a===null&&(a=e),h==="#"){const re=a===null?n[ia]:a,X=`${o}/$recursiveRef`,ie=Ie(r,a===null?e:a,t,n,s,re,i,X,c);ie.valid||D.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:X,error:"A subschema had errors."},...ie.errors)}if(d!==void 0){const X=n[nn||d];if(X===void 0){let j=`Unresolved $ref "${d}".`;throw nn&&nn!==d&&(j+=` Absolute URI "${nn}".`),j+=`
75
+ Known schemas:
76
+ - ${Object.keys(n).join(`
77
+ - `)}`,new Error(j)}const ie=`${o}/$ref`,B=Ie(r,X,t,n,s,a,i,ie,c);if(B.valid||D.push({instanceLocation:i,keyword:"$ref",keywordLocation:ie,error:"A subschema had errors."},...B.errors),t==="4"||t==="7")return{valid:D.length===0,errors:D}}if(Array.isArray(p)){let re=p.length,X=!1;for(let ie=0;ie<re;ie++)if(u===p[ie]||p[ie]==="integer"&&u==="number"&&r%1===0&&r===r){X=!0;break}X||D.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${u}" is invalid. Expected "${p.join('", "')}".`})}else p==="integer"?(u!=="number"||r%1||r!==r)&&D.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${u}" is invalid. Expected "${p}".`}):p!==void 0&&u!==p&&D.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${u}" is invalid. Expected "${p}".`});if(g!==void 0&&(u==="object"||u==="array"?Vr(r,g)||D.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(g)}.`}):r!==g&&D.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(g)}.`})),_!==void 0&&(u==="object"||u==="array"?_.some(re=>Vr(r,re))||D.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`}):_.some(re=>r===re)||D.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`})),m!==void 0){const re=`${o}/not`;Ie(r,m,t,n,s,a,i,re).valid&&D.push({instanceLocation:i,keyword:"not",keywordLocation:re,error:'Instance matched "not" schema.'})}let jr=[];if(y!==void 0){const re=`${o}/anyOf`,X=D.length;let ie=!1;for(let B=0;B<y.length;B++){const j=y[B],ae=Object.create(c),ne=Ie(r,j,t,n,s,f===!0?a:null,i,`${re}/${B}`,ae);D.push(...ne.errors),ie=ie||ne.valid,ne.valid&&jr.push(ae)}ie?D.length=X:D.splice(X,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:re,error:"Instance does not match any subschemas."})}if(T!==void 0){const re=`${o}/allOf`,X=D.length;let ie=!0;for(let B=0;B<T.length;B++){const j=T[B],ae=Object.create(c),ne=Ie(r,j,t,n,s,f===!0?a:null,i,`${re}/${B}`,ae);D.push(...ne.errors),ie=ie&&ne.valid,ne.valid&&jr.push(ae)}ie?D.length=X:D.splice(X,0,{instanceLocation:i,keyword:"allOf",keywordLocation:re,error:"Instance does not match every subschema."})}if(x!==void 0){const re=`${o}/oneOf`,X=D.length,ie=x.filter((B,j)=>{const ae=Object.create(c),ne=Ie(r,B,t,n,s,f===!0?a:null,i,`${re}/${j}`,ae);return D.push(...ne.errors),ne.valid&&jr.push(ae),ne.valid}).length;ie===1?D.length=X:D.splice(X,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:re,error:`Instance does not match exactly one subschema (${ie} matches).`})}if((u==="object"||u==="array")&&Object.assign(c,...jr),R!==void 0){const re=`${o}/if`;if(Ie(r,R,t,n,s,a,i,re,c).valid){if($!==void 0){const ie=Ie(r,$,t,n,s,a,i,`${o}/then`,c);ie.valid||D.push({instanceLocation:i,keyword:"if",keywordLocation:re,error:'Instance does not match "then" schema.'},...ie.errors)}}else if(E!==void 0){const ie=Ie(r,E,t,n,s,a,i,`${o}/else`,c);ie.valid||D.push({instanceLocation:i,keyword:"if",keywordLocation:re,error:'Instance does not match "else" schema.'},...ie.errors)}}if(u==="object"){if(b!==void 0)for(const B of b)B in r||D.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${B}".`});const re=Object.keys(r);if(M!==void 0&&re.length<M&&D.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${M} properties.`}),P!==void 0&&re.length>P&&D.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${P} properties.`}),N!==void 0){const B=`${o}/propertyNames`;for(const j in r){const ae=`${i}/${Lt(j)}`,ne=Ie(j,N,t,n,s,a,ae,B);ne.valid||D.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:B,error:`Property name "${j}" does not match schema.`},...ne.errors)}}if(W!==void 0){const B=`${o}/dependantRequired`;for(const j in W)if(j in r){const ae=W[j];for(const ne of ae)ne in r||D.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:B,error:`Instance has "${j}" but does not have "${ne}".`})}}if(V!==void 0)for(const B in V){const j=`${o}/dependentSchemas`;if(B in r){const ae=Ie(r,V[B],t,n,s,a,i,`${j}/${Lt(B)}`,c);ae.valid||D.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:j,error:`Instance has "${B}" but does not match dependant schema.`},...ae.errors)}}if(z!==void 0){const B=`${o}/dependencies`;for(const j in z)if(j in r){const ae=z[j];if(Array.isArray(ae))for(const ne of ae)ne in r||D.push({instanceLocation:i,keyword:"dependencies",keywordLocation:B,error:`Instance has "${j}" but does not have "${ne}".`});else{const ne=Ie(r,ae,t,n,s,a,i,`${B}/${Lt(j)}`);ne.valid||D.push({instanceLocation:i,keyword:"dependencies",keywordLocation:B,error:`Instance has "${j}" but does not match dependant schema.`},...ne.errors)}}}const X=Object.create(null);let ie=!1;if(se!==void 0){const B=`${o}/properties`;for(const j in se){if(!(j in r))continue;const ae=`${i}/${Lt(j)}`,ne=Ie(r[j],se[j],t,n,s,a,ae,`${B}/${Lt(j)}`);if(ne.valid)c[j]=X[j]=!0;else if(ie=s,D.push({instanceLocation:i,keyword:"properties",keywordLocation:B,error:`Property "${j}" does not match schema.`},...ne.errors),ie)break}}if(!ie&&H!==void 0){const B=`${o}/patternProperties`;for(const j in H){const ae=new RegExp(j,"u"),ne=H[j];for(const nt in r){if(!ae.test(nt))continue;const xd=`${i}/${Lt(nt)}`,Ad=Ie(r[nt],ne,t,n,s,a,xd,`${B}/${Lt(j)}`);Ad.valid?c[nt]=X[nt]=!0:(ie=s,D.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:B,error:`Property "${nt}" matches pattern "${j}" but does not match associated schema.`},...Ad.errors))}}}if(!ie&&Ae!==void 0){const B=`${o}/additionalProperties`;for(const j in r){if(X[j])continue;const ae=`${i}/${Lt(j)}`,ne=Ie(r[j],Ae,t,n,s,a,ae,B);ne.valid?c[j]=!0:(ie=s,D.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:B,error:`Property "${j}" does not match additional properties schema.`},...ne.errors))}}else if(!ie&&ft!==void 0){const B=`${o}/unevaluatedProperties`;for(const j in r)if(!c[j]){const ae=`${i}/${Lt(j)}`,ne=Ie(r[j],ft,t,n,s,a,ae,B);ne.valid?c[j]=!0:D.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:B,error:`Property "${j}" does not match unevaluated properties schema.`},...ne.errors)}}}else if(u==="array"){C!==void 0&&r.length>C&&D.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${r.length} > ${C}).`}),v!==void 0&&r.length<v&&D.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${r.length} < ${v}).`});const re=r.length;let X=0,ie=!1;if(ee!==void 0){const B=`${o}/prefixItems`,j=Math.min(ee.length,re);for(;X<j;X++){const ae=Ie(r[X],ee[X],t,n,s,a,`${i}/${X}`,`${B}/${X}`);if(c[X]=!0,!ae.valid&&(ie=s,D.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:B,error:"Items did not match schema."},...ae.errors),ie))break}}if(de!==void 0){const B=`${o}/items`;if(Array.isArray(de)){const j=Math.min(de.length,re);for(;X<j;X++){const ae=Ie(r[X],de[X],t,n,s,a,`${i}/${X}`,`${B}/${X}`);if(c[X]=!0,!ae.valid&&(ie=s,D.push({instanceLocation:i,keyword:"items",keywordLocation:B,error:"Items did not match schema."},...ae.errors),ie))break}}else for(;X<re;X++){const j=Ie(r[X],de,t,n,s,a,`${i}/${X}`,B);if(c[X]=!0,!j.valid&&(ie=s,D.push({instanceLocation:i,keyword:"items",keywordLocation:B,error:"Items did not match schema."},...j.errors),ie))break}if(!ie&&oe!==void 0){const j=`${o}/additionalItems`;for(;X<re;X++){const ae=Ie(r[X],oe,t,n,s,a,`${i}/${X}`,j);c[X]=!0,ae.valid||(ie=s,D.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:j,error:"Items did not match additional items schema."},...ae.errors))}}}if(Ce!==void 0)if(re===0&&me===void 0)D.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(me!==void 0&&re<me)D.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${re}) than minContains (${me}).`});else{const B=`${o}/contains`,j=D.length;let ae=0;for(let ne=0;ne<re;ne++){const nt=Ie(r[ne],Ce,t,n,s,a,`${i}/${ne}`,B);nt.valid?(c[ne]=!0,ae++):D.push(...nt.errors)}ae>=(me||0)&&(D.length=j),me===void 0&&S===void 0&&ae===0?D.splice(j,0,{instanceLocation:i,keyword:"contains",keywordLocation:B,error:"Array does not contain item matching schema."}):me!==void 0&&ae<me?D.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${me} items matching schema. Only ${ae} items were found.`}):S!==void 0&&ae>S&&D.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${S} items matching schema. ${ae} items were found.`})}if(!ie&&ye!==void 0){const B=`${o}/unevaluatedItems`;for(X;X<re;X++){if(c[X])continue;const j=Ie(r[X],ye,t,n,s,a,`${i}/${X}`,B);c[X]=!0,j.valid||D.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:B,error:"Items did not match unevaluated items schema."},...j.errors)}}if(A)for(let B=0;B<re;B++){const j=r[B],ae=typeof j=="object"&&j!==null;for(let ne=0;ne<re;ne++){if(B===ne)continue;const nt=r[ne];(j===nt||ae&&(typeof nt=="object"&&nt!==null)&&Vr(j,nt))&&(D.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${B} and ${ne}.`}),B=Number.MAX_SAFE_INTEGER,ne=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(t==="4"?(fe!==void 0&&(Ee===!0&&r<=fe||r<fe)&&D.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${r} is less than ${Ee?"or equal to ":""} ${fe}.`}),Se!==void 0&&(Ne===!0&&r>=Se||r>Se)&&D.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${r} is greater than ${Ne?"or equal to ":""} ${Se}.`})):(fe!==void 0&&r<fe&&D.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${r} is less than ${fe}.`}),Se!==void 0&&r>Se&&D.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${r} is greater than ${Se}.`}),Ee!==void 0&&r<=Ee&&D.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${r} is less than ${Ee}.`}),Ne!==void 0&&r>=Ne&&D.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${r} is greater than or equal to ${Ne}.`})),We!==void 0){const re=r%We;Math.abs(0-re)>=11920929e-14&&Math.abs(We-re)>=11920929e-14&&D.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${r} is not a multiple of ${We}.`})}}else if(u==="string"){const re=Ot===void 0&&Re===void 0?0:bT(r);Ot!==void 0&&re<Ot&&D.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${re} < ${Ot}).`}),Re!==void 0&&re>Re&&D.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${re} > ${Re}).`}),Tt!==void 0&&!new RegExp(Tt,"u").test(r)&&D.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),J!==void 0&&mf[J]&&!mf[J](r)&&D.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${J}".`})}return{valid:D.length===0,errors:D}}class vT{constructor(e,t="2019-09",n=!0){w(this,"schema");w(this,"draft");w(this,"shortCircuit");w(this,"lookup");this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Cr(e)}validate(e){return Ie(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Cr(e,this.lookup)}}var ST={};pe(ST,{Validator:()=>vT,deepCompareStrict:()=>Vr,toJsonSchema:()=>ut,validatesOnlyStrings:()=>Es});function ut(r){if($e(r)){const e=Tn(r,!0);if(ar(e)){const t=_i(e,!0);return Ol(t)}else return Ol(r)}return je(r)?WE(r):r}function Es(r){if(!r||typeof r!="object"||Object.keys(r).length===0||Array.isArray(r))return!1;if("type"in r)return typeof r.type=="string"?r.type==="string":Array.isArray(r.type)?r.type.every(e=>e==="string"):!1;if("enum"in r)return Array.isArray(r.enum)&&r.enum.length>0&&r.enum.every(e=>typeof e=="string");if("const"in r)return typeof r.const=="string";if("allOf"in r&&Array.isArray(r.allOf))return r.allOf.some(e=>Es(e));if("anyOf"in r&&Array.isArray(r.anyOf)||"oneOf"in r&&Array.isArray(r.oneOf)){const e="anyOf"in r?r.anyOf:r.oneOf;return e.length>0&&e.every(t=>Es(t))}if("not"in r)return!1;if("$ref"in r&&typeof r.$ref=="string"){const e=r.$ref,t=Cr(r);return t[e]?Es(t[e]):!1}return!1}var ET={};pe(ET,{Graph:()=>Uu});function TT(r,e){if(r!==void 0&&!Ja(r))return r;if(Nu(e))try{let t=e.getName();return t=t.startsWith("Runnable")?t.slice(8):t,t}catch{return e.getName()}else return e.name??"UnknownSchema"}function xT(r){return Nu(r.data)?{type:"runnable",data:{id:r.data.lc_id,name:r.data.getName()}}:{type:"schema",data:{...ut(r.data.schema),title:r.data.name}}}var Uu=class ag{constructor(e){w(this,"nodes",{});w(this,"edges",[]);this.nodes=(e==null?void 0:e.nodes)??this.nodes,this.edges=(e==null?void 0:e.edges)??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((t,n)=>{e[t.id]=Ja(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...xT(t)})),edges:this.edges.map(t=>{const n={source:e[t.source],target:e[t.target]};return typeof t.data<"u"&&(n.data=t.data),typeof t.conditional<"u"&&(n.conditional=t.conditional),n})}}addNode(e,t,n){if(t!==void 0&&this.nodes[t]!==void 0)throw new Error(`Node with id ${t} already exists`);const s=t??dr(),a={id:s,data:e,name:TT(t,e),metadata:n};return this.nodes[s]=a,a}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,n,s){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw new Error(`Target node ${t.id} not in graph`);const a={source:e.id,target:t.id,data:n,conditional:s};return this.edges.push(a),a}firstNode(){return gf(this)}lastNode(){return _f(this)}extend(e,t=""){let n=t;Object.values(e.nodes).map(l=>l.id).every(Ja)&&(n="");const a=l=>n?`${n}:${l}`:l;Object.entries(e.nodes).forEach(([l,u])=>{this.nodes[a(l)]={...u,id:a(l)}});const i=e.edges.map(l=>({...l,source:a(l.source),target:a(l.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&&gf(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&_f(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(s=>[s.id,s.name])),t=new Map;Object.values(e).forEach(s=>{t.set(s,(t.get(s)||0)+1)});const n=s=>{const a=e[s];return Ja(s)&&t.get(a)===1?a:s};return new ag({nodes:Object.fromEntries(Object.entries(this.nodes).map(([s,a])=>[n(s),{...a,id:n(s)}])),edges:this.edges.map(s=>({...s,source:n(s.source),target:n(s.target)}))})}drawMermaid(e){const{withStyles:t,curveStyle:n,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 aE(i.nodes,i.edges,{firstNode:o==null?void 0:o.id,lastNode:c==null?void 0:c.id,withStyles:t,curveStyle:n,nodeColors:s,wrapLabelNWords:a})}async drawMermaidPng(e){const t=this.drawMermaid(e);return iE(t,{backgroundColor:e==null?void 0:e.backgroundColor})}};function gf(r,e=[]){const t=new Set(r.edges.filter(s=>!e.includes(s.source)).map(s=>s.target)),n=[];for(const s of Object.values(r.nodes))!e.includes(s.id)&&!t.has(s.id)&&n.push(s);return n.length===1?n[0]:void 0}function _f(r,e=[]){const t=new Set(r.edges.filter(s=>!e.includes(s.target)).map(s=>s.source)),n=[];for(const s of Object.values(r.nodes))!e.includes(s.id)&&!t.has(s.id)&&n.push(s);return n.length===1?n[0]:void 0}function AT(r){const e=new TextEncoder,t=new ReadableStream({async start(n){for await(const s of r)n.enqueue(e.encode(`event: data
78
+ data: ${JSON.stringify(s)}
79
+
80
+ `));n.enqueue(e.encode(`event: end
81
+
82
+ `)),n.close()}});return Vt.fromReadableStream(t)}function yf(r){return typeof r=="object"&&r!==null&&typeof r[Symbol.iterator]=="function"&&typeof r.next=="function"}const IT=r=>r!=null&&typeof r=="object"&&"next"in r&&typeof r.next=="function";function kl(r){return typeof r=="object"&&r!==null&&typeof r[Symbol.asyncIterator]=="function"}function*wf(r,e){for(;;){const{value:t,done:n}=Jt.runWithConfig(yr(r),e.next.bind(e),!0);if(n)break;yield t}}async function*Pl(r,e){const t=e[Symbol.asyncIterator]();for(;;){const{value:n,done:s}=await Jt.runWithConfig(yr(r),t.next.bind(e),!0);if(s)break;yield n}}function qe(r,e){return r&&!Array.isArray(r)&&!(r instanceof Date)&&typeof r=="object"?r:{[e]:r}}var Pe=class extends Rn{constructor(){super(...arguments);w(this,"lc_runnable",!0);w(this,"name")}getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new Fu({bound:this,kwargs:{},config:{},maxAttemptNumber:e==null?void 0:e.stopAfterAttempt,...e})}withConfig(e){return new Cn({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new dg({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(ge);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const n=Object.fromEntries(Object.entries(e).filter(([s])=>s!=="runId"));return Array.from({length:t},(s,a)=>ge(a===0?e:n))}return Array.from({length:t},()=>ge(e))}async batch(e,t,n){var c;const s=this._getOptionsList(t??{},e.length),a=((c=s[0])==null?void 0:c.maxConcurrency)??(n==null?void 0:n.maxConcurrency),i=new Js({maxConcurrency:a,onFailedAttempt:l=>{throw l}}),o=e.map((l,u)=>i.call(async()=>{try{return await this.invoke(l,s[u])}catch(d){if(n!=null&&n.returnExceptions)return d;throw d}}));return Promise.all(o)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const n=ge(t),s=new rn({generator:this._streamIterator(e,n),config:n});return await s.setup,Vt.fromAsyncGenerator(s)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=ge(e):t=ge({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const n={...e};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,[t,n]}async _callWithConfig(e,t,n){const s=ge(n),a=await vt(s),i=await(a==null?void 0:a.handleChainStart(this.toJSON(),qe(t,"input"),s.runId,s==null?void 0:s.runType,void 0,void 0,(s==null?void 0:s.runName)??this.getName()));delete s.runId;let o;try{const c=e.call(this,t,s,i);o=await Nr(c,n==null?void 0:n.signal)}catch(c){throw await(i==null?void 0:i.handleChainError(c)),c}return await(i==null?void 0:i.handleChainEnd(qe(o,"output"))),o}async _batchWithConfig(e,t,n,s){var l;const a=this._getOptionsList(n??{},t.length),i=await Promise.all(a.map(vt)),o=await Promise.all(i.map(async(u,d)=>{const h=await(u==null?void 0:u.handleChainStart(this.toJSON(),qe(t[d],"input"),a[d].runId,a[d].runType,void 0,void 0,a[d].runName??this.getName()));return delete a[d].runId,h}));let c;try{const u=e.call(this,t,a,o,s);c=await Nr(u,(l=a==null?void 0:a[0])==null?void 0:l.signal)}catch(u){throw await Promise.all(o.map(d=>d==null?void 0:d.handleChainError(u))),u}return await Promise.all(o.map(u=>u==null?void 0:u.handleChainEnd(qe(c,"output")))),c}_concatOutputChunks(e,t){return Lr(e,t)}async*_transformStreamWithConfig(e,t,n){let s,a=!0,i,o=!0;const c=ge(n),l=await vt(c),u=this;async function*d(){for await(const f of e){if(a)if(s===void 0)s=f;else try{s=u._concatOutputChunks(s,f)}catch{s=void 0,a=!1}yield f}}let h;try{const f=await Mm(t.bind(this),d(),async()=>l==null?void 0:l.handleChainStart(this.toJSON(),{input:""},c.runId,c.runType,void 0,void 0,c.runName??this.getName()),n==null?void 0:n.signal,c);delete c.runId,h=f.setup;const p=h==null?void 0:h.handlers.find(mS);let g=f.output;p!==void 0&&h!==void 0&&(g=p.tapOutputIterable(h.runId,g));const _=h==null?void 0:h.handlers.find(Fm);_!==void 0&&h!==void 0&&(g=_.tapOutputIterable(h.runId,g));for await(const b of g)if(yield b,o)if(i===void 0)i=b;else try{i=this._concatOutputChunks(i,b)}catch{i=void 0,o=!1}}catch(f){throw await(h==null?void 0:h.handleChainError(f,void 0,void 0,void 0,{inputs:qe(s,"input")})),f}await(h==null?void 0:h.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:qe(s,"input")}))}getGraph(e){const t=new Uu,n=t.addNode({name:`${this.getName()}Input`,schema:vn()}),s=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:vn()});return t.addEdge(n,s),t.addEdge(s,a),t}pipe(e){return new Ln({first:this,last:Ft(e)})}pick(e){return this.pipe(new hg(e))}assign(e){return this.pipe(new Bu(new Mn({steps:e})))}async*transform(e,t){let n;for await(const s of e)n===void 0?n=s:n=this._concatOutputChunks(n,s);yield*this._streamIterator(n,ge(t))}async*streamLog(e,t,n){const s=new Rl({...n,autoClose:!1,_schemaFormat:"original"}),a=ge(t);yield*this._streamLog(e,s,a)}async*_streamLog(e,t,n){const{callbacks:s}=n;if(s===void 0)n.callbacks=[t];else if(Array.isArray(s))n.callbacks=s.concat([t]);else{const c=s.copy();c.addHandler(t,!0),n.callbacks=c}const a=this.stream(e,n);async function i(){try{const c=await a;for await(const l of c){const u=new hr({ops:[{op:"add",path:"/streamed_output/-",value:l}]});await t.writer.write(u)}}finally{await t.writer.close()}}const o=i();try{for await(const c of t)yield c}finally{await o}}streamEvents(e,t,n){let s;if(t.version==="v1")s=this._streamEventsV1(e,t,n);else if(t.version==="v2")s=this._streamEventsV2(e,t,n);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?AT(s):Vt.fromAsyncGenerator(s)}async*_streamEventsV2(e,t,n){var p;const s=new gS({...n,autoClose:!1}),a=ge(t),i=a.runId??dr();a.runId=i;const o=a.callbacks;if(o===void 0)a.callbacks=[s];else if(Array.isArray(o))a.callbacks=o.concat(s);else{const g=o.copy();g.addHandler(s,!0),a.callbacks=g}const c=new AbortController,l=this;async function u(){let g,_=null;try{t!=null&&t.signal?"any"in AbortSignal?g=AbortSignal.any([c.signal,t.signal]):(g=t.signal,_=()=>{c.abort()},t.signal.addEventListener("abort",_,{once:!0})):g=c.signal;const b=await l.stream(e,{...a,signal:g}),m=s.tapOutputIterable(i,b);for await(const y of m)if(c.signal.aborted)break}finally{await s.finish(),g&&_&&g.removeEventListener("abort",_)}}const d=u();let h=!1,f;try{for await(const g of s){if(!h){g.data.input=e,h=!0,f=g.run_id,yield g;continue}g.run_id===f&&g.event.endsWith("_end")&&(p=g.data)!=null&&p.input&&delete g.data.input,yield g}}finally{c.abort(),await d}}async*_streamEventsV1(e,t,n){let s,a=!1;const i=ge(t),o=i.tags??[],c=i.metadata??{},l=i.runName??this.getName(),u=new Rl({...n,autoClose:!1,_schemaFormat:"streaming_events"}),d=new bS({...n}),h=this._streamLog(e,u,i);for await(const p of h){if(s?s=s.concat(p):s=Pu.fromRunLogPatch(p),s.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;const m={...s.state},y={run_id:m.id,event:`on_${m.type}_start`,name:l,tags:o,metadata:c,data:{input:e}};d.includeEvent(y,m.type)&&(yield y)}const g=p.ops.filter(m=>m.path.startsWith("/logs/")).map(m=>m.path.split("/")[2]),_=[...new Set(g)];for(const m of _){let y,T={};const x=s.state.logs[m];if(x.end_time===void 0?x.streamed_output.length>0?y="stream":y="start":y="end",y==="start")x.inputs!==void 0&&(T.input=x.inputs);else if(y==="end")x.inputs!==void 0&&(T.input=x.inputs),T.output=x.final_output;else if(y==="stream"){const R=x.streamed_output.length;if(R!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${R} instead. Encountered in: "${x.name}"`);T={chunk:x.streamed_output[0]},x.streamed_output=[]}yield{event:`on_${x.type}_${y}`,name:x.name,run_id:x.id,tags:x.tags,metadata:x.metadata,data:T}}const{state:b}=s;if(b.streamed_output.length>0){const m=b.streamed_output.length;if(m!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${m} instead. Encountered in: "${b.name}"`);const y={chunk:b.streamed_output[0]};b.streamed_output=[];const T={event:`on_${b.type}_stream`,run_id:b.id,tags:o,metadata:c,name:l,data:y};d.includeEvent(T,b.type)&&(yield T)}}const f=s==null?void 0:s.state;if(f!==void 0){const p={event:`on_${f.type}_end`,name:l,run_id:f.id,tags:o,metadata:c,data:{output:f.final_output}};d.includeEvent(p,f.type)&&(yield p)}}static isRunnable(e){return Nu(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new Cn({bound:this,config:{},configFactories:[s=>({callbacks:[new zm({config:s,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return kT(this,e)}},Cn=class ig extends Pe{constructor(t){super(t);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"lc_serializable",!0);w(this,"bound");w(this,"config");w(this,"kwargs");w(this,"configFactories");this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}static lc_name(){return"RunnableBinding"}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){const n=fi(this.config,...t);return fi(n,...this.configFactories?await Promise.all(this.configFactories.map(async s=>await s(n))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new Fu({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t==null?void 0:t.stopAfterAttempt,...t})}async invoke(t,n){return this.bound.invoke(t,await this._mergeConfig(n,this.kwargs))}async batch(t,n,s){const a=Array.isArray(n)?await Promise.all(n.map(async i=>this._mergeConfig(ge(i),this.kwargs))):await this._mergeConfig(ge(n),this.kwargs);return this.bound.batch(t,a,s)}_concatOutputChunks(t,n){return this.bound._concatOutputChunks(t,n)}async*_streamIterator(t,n){yield*this.bound._streamIterator(t,await this._mergeConfig(ge(n),this.kwargs))}async stream(t,n){return this.bound.stream(t,await this._mergeConfig(ge(n),this.kwargs))}async*transform(t,n){yield*this.bound.transform(t,await this._mergeConfig(ge(n),this.kwargs))}streamEvents(t,n,s){const a=this,i=async function*(){yield*a.bound.streamEvents(t,{...await a._mergeConfig(ge(n),a.kwargs),version:n.version},s)};return Vt.fromAsyncGenerator(i())}static isRunnableBinding(t){return t.bound&&Pe.isRunnable(t.bound)}withListeners({onStart:t,onEnd:n,onError:s}){return new ig({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new zm({config:a,onStart:t,onEnd:n,onError:s})]})]})}},RT=class og extends Pe{constructor(t){super(t);w(this,"lc_serializable",!0);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"bound");this.bound=t.bound}static lc_name(){return"RunnableEach"}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async _invoke(t,n,s){return this.bound.batch(t,Te(n,{callbacks:s==null?void 0:s.getChild()}))}withListeners({onStart:t,onEnd:n,onError:s}){return new og({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:s})})}},Fu=class extends Cn{constructor(e){super(e);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"maxAttemptNumber",3);w(this,"onFailedAttempt",()=>{});this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}static lc_name(){return"RunnableRetry"}_patchConfigForRetry(e,t,n){const s=e>1?`retry:attempt:${e}`:void 0;return Te(t,{callbacks:n==null?void 0:n.getChild(s)})}async _invoke(e,t,n){return ui(s=>super.invoke(e,this._patchConfigForRetry(s,t,n)),{onFailedAttempt:s=>this.onFailedAttempt(s,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,s){const a={};try{await ui(async i=>{const o=e.map((h,f)=>f).filter(h=>a[h.toString()]===void 0||a[h.toString()]instanceof Error),c=o.map(h=>e[h]),l=o.map(h=>this._patchConfigForRetry(i,t==null?void 0:t[h],n==null?void 0:n[h])),u=await super.batch(c,l,{...s,returnExceptions:!0});let d;for(let h=0;h<u.length;h+=1){const f=u[h],p=o[h];f instanceof Error&&d===void 0&&(d=f,d.input=c[h]),a[p.toString()]=f}if(d)throw d;return u},{onFailedAttempt:i=>this.onFailedAttempt(i,i.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(i){if((s==null?void 0:s.returnExceptions)!==!0)throw i}return Object.keys(a).sort((i,o)=>parseInt(i,10)-parseInt(o,10)).map(i=>a[parseInt(i,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},Ln=class ss extends Pe{constructor(t){super(t);w(this,"first");w(this,"middle",[]);w(this,"last");w(this,"omitSequenceTags",!1);w(this,"lc_serializable",!0);w(this,"lc_namespace",["langchain_core","runnables"]);this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}static lc_name(){return"RunnableSequence"}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,n){var l;const s=ge(n),a=await vt(s),i=await(a==null?void 0:a.handleChainStart(this.toJSON(),qe(t,"input"),s.runId,void 0,void 0,void 0,s==null?void 0:s.runName));delete s.runId;let o=t,c;try{const u=[this.first,...this.middle];for(let d=0;d<u.length;d+=1){const f=u[d].invoke(o,Te(s,{callbacks:i==null?void 0:i.getChild(this.omitSequenceTags?void 0:`seq:step:${d+1}`)}));o=await Nr(f,n==null?void 0:n.signal)}if((l=n==null?void 0:n.signal)!=null&&l.aborted)throw ks(n.signal);c=await this.last.invoke(o,Te(s,{callbacks:i==null?void 0:i.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(u){throw await(i==null?void 0:i.handleChainError(u)),u}return await(i==null?void 0:i.handleChainEnd(qe(c,"output"))),c}async batch(t,n,s){var l;const a=this._getOptionsList(n??{},t.length),i=await Promise.all(a.map(vt)),o=await Promise.all(i.map(async(u,d)=>{const h=await(u==null?void 0:u.handleChainStart(this.toJSON(),qe(t[d],"input"),a[d].runId,void 0,void 0,void 0,a[d].runName));return delete a[d].runId,h}));let c=t;try{for(let u=0;u<this.steps.length;u+=1){const h=this.steps[u].batch(c,o.map((f,p)=>{const g=f==null?void 0:f.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`);return Te(a[p],{callbacks:g})}),s);c=await Nr(h,(l=a[0])==null?void 0:l.signal)}}catch(u){throw await Promise.all(o.map(d=>d==null?void 0:d.handleChainError(u))),u}return await Promise.all(o.map(u=>u==null?void 0:u.handleChainEnd(qe(c,"output")))),c}_concatOutputChunks(t,n){return this.last._concatOutputChunks(t,n)}async*_streamIterator(t,n){var h;const s=await vt(n),{runId:a,...i}=n??{},o=await(s==null?void 0:s.handleChainStart(this.toJSON(),qe(t,"input"),a,void 0,void 0,void 0,i==null?void 0:i.runName)),c=[this.first,...this.middle,this.last];let l=!0,u;async function*d(){yield t}try{let f=c[0].transform(d(),Te(i,{callbacks:o==null?void 0:o.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let p=1;p<c.length;p+=1)f=await c[p].transform(f,Te(i,{callbacks:o==null?void 0:o.getChild(this.omitSequenceTags?void 0:`seq:step:${p+1}`)}));for await(const p of f)if((h=n==null?void 0:n.signal)==null||h.throwIfAborted(),yield p,l)if(u===void 0)u=p;else try{u=this._concatOutputChunks(u,p)}catch{u=void 0,l=!1}}catch(f){throw await(o==null?void 0:o.handleChainError(f)),f}await(o==null?void 0:o.handleChainEnd(qe(u,"output")))}getGraph(t){const n=new Uu;let s=null;return this.steps.forEach((a,i)=>{const o=a.getGraph(t);i!==0&&o.trimFirstNode(),i!==this.steps.length-1&&o.trimLastNode(),n.extend(o);const c=o.firstNode();if(!c)throw new Error(`Runnable ${a} has no first node`);s&&n.addEdge(s,c),s=o.lastNode()}),n}pipe(t){return ss.isRunnableSequence(t)?new ss({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new ss({first:this.first,middle:[...this.middle,this.last],last:Ft(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&Pe.isRunnable(t)}static from([t,...n],s){let a={};return typeof s=="string"?a.name=s:s!==void 0&&(a=s),new ss({...a,first:Ft(t),middle:n.slice(0,-1).map(Ft),last:Ft(n[n.length-1])})}},Mn=class cg extends Pe{constructor(t){super(t);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"lc_serializable",!0);w(this,"steps");this.steps={};for(const[n,s]of Object.entries(t.steps))this.steps[n]=Ft(s)}static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}static from(t){return new cg({steps:t})}async invoke(t,n){const s=ge(n),a=await vt(s),i=await(a==null?void 0:a.handleChainStart(this.toJSON(),{input:t},s.runId,void 0,void 0,void 0,s==null?void 0:s.runName));delete s.runId;const o={};try{const c=Object.entries(this.steps).map(async([l,u])=>{o[l]=await u.invoke(t,Te(s,{callbacks:i==null?void 0:i.getChild(`map:key:${l}`)}))});await Nr(Promise.all(c),n==null?void 0:n.signal)}catch(c){throw await(i==null?void 0:i.handleChainError(c)),c}return await(i==null?void 0:i.handleChainEnd(o)),o}async*_transform(t,n,s){const a={...this.steps},i=Cu(t,Object.keys(a).length),o=new Map(Object.entries(a).map(([c,l],u)=>{const d=l.transform(i[u],Te(s,{callbacks:n==null?void 0:n.getChild(`map:key:${c}`)}));return[c,d.next().then(h=>({key:c,gen:d,result:h}))]}));for(;o.size;){const c=Promise.race(o.values()),{key:l,result:u,gen:d}=await Nr(c,s==null?void 0:s.signal);o.delete(l),u.done||(yield{[l]:u.value},o.set(l,d.next().then(h=>({key:l,gen:d,result:h}))))}}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*s(){yield t}const a=ge(n),i=new rn({generator:this.transform(s(),a),config:a});return await i.setup,Vt.fromAsyncGenerator(i)}},OT=class lg extends Pe{constructor(t){super(t);w(this,"lc_serializable",!1);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"func");if(!$u(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,n){const[s]=this._getOptionsList(n??{},1),a=await vt(s),i=this.func(Te(s,{callbacks:a}),t);return Nr(i,s==null?void 0:s.signal)}async*_streamIterator(t,n){var i,o;const[s]=this._getOptionsList(n??{},1),a=await this.invoke(t,n);if(kl(a)){for await(const c of a)(i=s==null?void 0:s.signal)==null||i.throwIfAborted(),yield c;return}if(IT(a)){for(;;){(o=s==null?void 0:s.signal)==null||o.throwIfAborted();const c=a.next();if(c.done)break;yield c.value}return}yield a}static from(t){return new lg({func:t})}};function $T(r){if($u(r))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var vr=class ug extends Pe{constructor(t){if($u(t.func))return OT.from(t.func);super(t);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"func");$T(t.func),this.func=t.func}static lc_name(){return"RunnableLambda"}static from(t){return new ug({func:t})}async _invoke(t,n,s){return new Promise((a,i)=>{const o=Te(n,{callbacks:s==null?void 0:s.getChild(),recursionLimit:((n==null?void 0:n.recursionLimit)??Dc)-1});Jt.runWithConfig(yr(o),async()=>{var c,l;try{let u=await this.func(t,{...o});if(u&&Pe.isRunnable(u)){if((n==null?void 0:n.recursionLimit)===0)throw new Error("Recursion limit reached.");u=await u.invoke(t,{...o,recursionLimit:(o.recursionLimit??Dc)-1})}else if(kl(u)){let d;for await(const h of Pl(o,u))if((c=n==null?void 0:n.signal)==null||c.throwIfAborted(),d===void 0)d=h;else try{d=this._concatOutputChunks(d,h)}catch{d=h}u=d}else if(yf(u)){let d;for(const h of wf(o,u))if((l=n==null?void 0:n.signal)==null||l.throwIfAborted(),d===void 0)d=h;else try{d=this._concatOutputChunks(d,h)}catch{d=h}u=d}a(u)}catch(u){i(u)}})})}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async*_transform(t,n,s){var c,l;let a;for await(const u of t)if(a===void 0)a=u;else try{a=this._concatOutputChunks(a,u)}catch{a=u}const i=Te(s,{callbacks:n==null?void 0:n.getChild(),recursionLimit:((s==null?void 0:s.recursionLimit)??Dc)-1}),o=await new Promise((u,d)=>{Jt.runWithConfig(yr(i),async()=>{try{const h=await this.func(a,{...i,config:i});u(h)}catch(h){d(h)}})});if(o&&Pe.isRunnable(o)){if((s==null?void 0:s.recursionLimit)===0)throw new Error("Recursion limit reached.");const u=await o.stream(a,i);for await(const d of u)yield d}else if(kl(o))for await(const u of Pl(i,o))(c=s==null?void 0:s.signal)==null||c.throwIfAborted(),yield u;else if(yf(o))for(const u of wf(i,o))(l=s==null?void 0:s.signal)==null||l.throwIfAborted(),yield u;else yield o}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*s(){yield t}const a=ge(n),i=new rn({generator:this.transform(s(),a),config:a});return await i.setup,Vt.fromAsyncGenerator(i)}},CT=class extends Mn{},dg=class extends Pe{constructor(e){super(e);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"lc_serializable",!0);w(this,"runnable");w(this,"fallbacks");this.runnable=e.runnable,this.fallbacks=e.fallbacks}static lc_name(){return"RunnableWithFallbacks"}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const n=ge(t),s=await vt(n),{runId:a,...i}=n,o=await(s==null?void 0:s.handleChainStart(this.toJSON(),qe(e,"input"),a,void 0,void 0,void 0,i==null?void 0:i.runName)),c=Te(i,{callbacks:o==null?void 0:o.getChild()});return await Jt.runWithConfig(c,async()=>{var d;let u;for(const h of this.runnables()){(d=n==null?void 0:n.signal)==null||d.throwIfAborted();try{const f=await h.invoke(e,c);return await(o==null?void 0:o.handleChainEnd(qe(f,"output"))),f}catch(f){u===void 0&&(u=f)}}throw u===void 0?new Error("No error stored at end of fallback."):(await(o==null?void 0:o.handleChainError(u)),u)})}async*_streamIterator(e,t){var d;const n=ge(t),s=await vt(n),{runId:a,...i}=n,o=await(s==null?void 0:s.handleChainStart(this.toJSON(),qe(e,"input"),a,void 0,void 0,void 0,i==null?void 0:i.runName));let c,l;for(const h of this.runnables()){(d=n==null?void 0:n.signal)==null||d.throwIfAborted();const f=Te(i,{callbacks:o==null?void 0:o.getChild()});try{const p=await h.stream(e,f);l=Pl(f,p);break}catch(p){c===void 0&&(c=p)}}if(l===void 0){const h=c??new Error("No error stored at end of fallback.");throw await(o==null?void 0:o.handleChainError(h)),h}let u;try{for await(const h of l){yield h;try{u=u===void 0?u:this._concatOutputChunks(u,h)}catch{u=void 0}}}catch(h){throw await(o==null?void 0:o.handleChainError(h)),h}await(o==null?void 0:o.handleChainEnd(qe(u,"output")))}async batch(e,t,n){var c;if(n!=null&&n.returnExceptions)throw new Error("Not implemented.");const s=this._getOptionsList(t??{},e.length),a=await Promise.all(s.map(l=>vt(l))),i=await Promise.all(a.map(async(l,u)=>{const d=await(l==null?void 0:l.handleChainStart(this.toJSON(),qe(e[u],"input"),s[u].runId,void 0,void 0,void 0,s[u].runName));return delete s[u].runId,d}));let o;for(const l of this.runnables()){(c=s[0].signal)==null||c.throwIfAborted();try{const u=await l.batch(e,i.map((d,h)=>Te(s[h],{callbacks:d==null?void 0:d.getChild()})),n);return await Promise.all(i.map((d,h)=>d==null?void 0:d.handleChainEnd(qe(u[h],"output")))),u}catch(u){o===void 0&&(o=u)}}throw o?(await Promise.all(i.map(l=>l==null?void 0:l.handleChainError(o))),o):new Error("No error stored at end of fallbacks.")}};function Ft(r){if(typeof r=="function")return new vr({func:r});if(Pe.isRunnable(r))return r;if(!Array.isArray(r)&&typeof r=="object"){const e={};for(const[t,n]of Object.entries(r))e[t]=Ft(n);return new Mn({steps:e})}else throw new Error(`Expected a Runnable, function or object.
83
+ Instead got an unsupported type.`)}var Bu=class extends Pe{constructor(e){e instanceof Mn&&(e={mapper:e});super(e);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"lc_serializable",!0);w(this,"mapper");this.mapper=e.mapper}static lc_name(){return"RunnableAssign"}async invoke(e,t){const n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){const s=this.mapper.getStepsKeys(),[a,i]=Cu(e),o=this.mapper.transform(i,Te(n,{callbacks:t==null?void 0:t.getChild()})),c=o.next();for await(const l of a){if(typeof l!="object"||Array.isArray(l))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof l}`);const u=Object.fromEntries(Object.entries(l).filter(([d])=>!s.includes(d)));Object.keys(u).length>0&&(yield u)}yield(await c).value;for await(const l of o)yield l}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const s=ge(t),a=new rn({generator:this.transform(n(),s),config:s});return await a.setup,Vt.fromAsyncGenerator(a)}},hg=class extends Pe{constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e});super(e);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"lc_serializable",!0);w(this,"keys");this.keys=e.keys}static lc_name(){return"RunnablePick"}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const t=this.keys.map(n=>[n,e[n]]).filter(n=>n[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const n=await this._pick(t);n!==void 0&&(yield n)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const s=ge(t),a=new rn({generator:this.transform(n(),s),config:s});return await a.setup,Vt.fromAsyncGenerator(a)}},Nl=class extends Cn{constructor(e){const t=Ln.from([vr.from(async n=>{let s;if(ws(n))try{s=await eo(this.schema,n.args)}catch{throw new ci("Received tool input did not match expected schema",JSON.stringify(n.args))}else s=n;return s}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}});w(this,"name");w(this,"description");w(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function kT(r,e){const t=e.name??r.getName(),n=e.description??to(e.schema);return ju(e.schema)?new Nl({name:t,description:n,schema:$r({input:In()}).transform(s=>s.input),bound:r}):new Nl({name:t,description:n,schema:e.schema,bound:r})}const wi=(r,e)=>{const t=[...new Set(e==null?void 0: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()}))],n=r.getType();return t.some(s=>s===n)};function PT(r,e){return Array.isArray(r)?bf(r,e):vr.from(t=>bf(t,r))}function bf(r,e={}){const{includeNames:t,excludeNames:n,includeTypes:s,excludeTypes:a,includeIds:i,excludeIds:o}=e,c=[];for(const l of r)if(!(n&&l.name&&n.includes(l.name))){{if(a&&wi(l,a))continue;if(o&&l.id&&o.includes(l.id))continue}s||i||t?(t&&l.name&&t.some(u=>u===l.name)||s&&wi(l,s)||i&&l.id&&i.some(u=>u===l.id))&&c.push(l):c.push(l)}return c}function NT(r){return Array.isArray(r)?vf(r):vr.from(vf)}function vf(r){if(!r.length)return[];const e=[];for(const t of r){const n=t,s=e.pop();if(!s)e.push(n);else if(n.getType()==="tool"||n.getType()!==s.getType())e.push(s,n);else{const a=li(s),i=li(n),o=a.concat(i);typeof a.content=="string"&&typeof i.content=="string"&&(o.content=`${a.content}
84
+ ${i.content}`),e.push(jT(o))}}return e}function LT(r,e){if(Array.isArray(r)){const t=r;if(!e)throw new Error("Options parameter is required when providing messages.");return Sf(t,e)}else{const t=r;return vr.from(n=>Sf(n,t)).withConfig({runName:"trim_messages"})}}async function Sf(r,e){const{maxTokens:t,tokenCounter:n,strategy:s="last",allowPartial:a=!1,endOn:i,startOn:o,includeSystem:c=!1,textSplitter:l}=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 u;"getNumTokens"in n?u=async h=>(await Promise.all(h.map(p=>n.getNumTokens(p.content)))).reduce((p,g)=>p+g,0):u=async h=>n(h);let d=pg;if(l&&("splitText"in l?d=l.splitText:d=async h=>l(h)),s==="first")return fg(r,{maxTokens:t,tokenCounter:u,textSplitter:d,partialStrategy:a?"first":void 0,endOn:i});if(s==="last")return MT(r,{maxTokens:t,tokenCounter:u,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 fg(r,e){const{maxTokens:t,tokenCounter:n,textSplitter:s,partialStrategy:a,endOn:i}=e;let o=[...r],c=0;for(let l=0;l<o.length;l+=1){const u=l>0?o.slice(0,-l):o;if(await n(u)<=t){c=o.length-l;break}}if(c<o.length&&a){let l=!1;if(Array.isArray(o[c].content)){const u=o[c];if(typeof u.content=="string")throw new Error("Expected content to be an array.");const d=u.content.length,h=a==="last"?[...u.content].reverse():u.content;for(let f=1;f<=d;f+=1){const p=a==="first"?h.slice(0,f):h.slice(-f),g=Object.fromEntries(Object.entries(u).filter(([m])=>m!=="type"&&!m.startsWith("lc_"))),_=qu(u.getType(),{...g,content:p}),b=[...o.slice(0,c),_];if(await n(b)<=t)o=b,c+=1,l=!0;else break}l&&a==="last"&&(u.content=[...h].reverse())}if(!l){const u=o[c];let d;if(Array.isArray(u.content)&&u.content.some(h=>typeof h=="string"||h.type==="text")){const h=u.content.find(f=>f.type==="text"&&f.text);d=h==null?void 0:h.text}else typeof u.content=="string"&&(d=u.content);if(d){const h=await s(d),f=h.length;a==="last"&&h.reverse();for(let p=0;p<f-1;p+=1)if(h.pop(),u.content=h.join(""),await n([...o.slice(0,c),u])<=t){a==="last"&&(u.content=[...h].reverse().join("")),o=[...o.slice(0,c),u],c+=1;break}}}}if(i){const l=Array.isArray(i)?i:[i];for(;c>0&&!wi(o[c-1],l);)c-=1}return o.slice(0,c)}async function MT(r,e){var u;const{allowPartial:t=!1,includeSystem:n=!1,endOn:s,startOn:a,...i}=e;let o=r.map(d=>{const h=Object.fromEntries(Object.entries(d).filter(([f])=>f!=="type"&&!f.startsWith("lc_")));return qu(d.getType(),h,gu(d))});if(s){const d=Array.isArray(s)?s:[s];for(;o.length>0&&!wi(o[o.length-1],d);)o=o.slice(0,-1)}const c=n&&((u=o[0])==null?void 0:u.getType())==="system";let l=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return l=await fg(l,{...i,partialStrategy:t?"last":void 0,endOn:a}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}const Ef={human:{message:Gt,messageChunk:zs},ai:{message:St,messageChunk:ke},system:{message:kr,messageChunk:Pr},developer:{message:kr,messageChunk:Pr},tool:{message:gr,messageChunk:Fs},function:{message:qi,messageChunk:qs},generic:{message:tn,messageChunk:Bs},remove:{message:oi,messageChunk:oi}};function qu(r,e,t){var a;let n,s;switch(r){case"human":t?n=new zs(e):s=new Gt(e);break;case"ai":if(t){let i={...e};"tool_calls"in i&&(i={...i,tool_call_chunks:(a=i.tool_calls)==null?void 0:a.map(o=>({...o,type:"tool_call_chunk",index:void 0,args:JSON.stringify(o.args)}))}),n=new ke(i)}else s=new St(e);break;case"system":t?n=new Pr(e):s=new kr(e);break;case"developer":t?n=new Pr({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):s=new kr({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)t?n=new Fs(e):s=new gr(e);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(t)n=new qs(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");s=new qi(e)}break;case"generic":if("role"in e)t?n=new Bs(e):s=new tn(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 ${r}`)}if(t&&n)return n;if(s)return s;throw new Error(`Unrecognized message type ${r}`)}function jT(r){const e=r.getType();let t;const n=Object.fromEntries(Object.entries(r).filter(([s])=>!["type","tool_call_chunks"].includes(s)&&!s.startsWith("lc_")));if(e in Ef&&(t=qu(e,n)),!t)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys(Ef)}`);return t}function pg(r){const e=r.split(`
85
+ `);return Promise.resolve([...e.slice(0,-1).map(t=>`${t}
86
+ `),e[e.length-1]])}const DT=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],UT=["image","video","audio","text-plain","file"],FT=["text","reasoning",...DT,...UT];var BT={};pe(BT,{AIMessage:()=>St,AIMessageChunk:()=>ke,BaseMessage:()=>br,BaseMessageChunk:()=>en,ChatMessage:()=>tn,ChatMessageChunk:()=>Bs,FunctionMessage:()=>qi,FunctionMessageChunk:()=>qs,HumanMessage:()=>Gt,HumanMessageChunk:()=>zs,KNOWN_BLOCK_TYPES:()=>FT,RemoveMessage:()=>oi,SystemMessage:()=>kr,SystemMessageChunk:()=>Pr,ToolMessage:()=>gr,ToolMessageChunk:()=>Fs,_isMessageFieldWithRole:()=>Wp,_mergeDicts:()=>Ze,_mergeLists:()=>Us,_mergeObj:()=>Hp,_mergeStatus:()=>zp,coerceMessageLikeToMessage:()=>bs,convertToChunk:()=>li,convertToOpenAIImageBlock:()=>Dp,convertToProviderContentBlock:()=>Fi,defaultTextSplitter:()=>pg,defaultToolCallParser:()=>yu,filterMessages:()=>PT,getBufferString:()=>bu,iife:()=>ab,isAIMessage:()=>_r,isAIMessageChunk:()=>_l,isBase64ContentBlock:()=>hu,isBaseMessage:()=>pr,isBaseMessageChunk:()=>gu,isChatMessage:()=>Zw,isChatMessageChunk:()=>Xw,isDataContentBlock:()=>Wt,isDirectToolOutput:()=>_u,isFunctionMessage:()=>Yw,isFunctionMessageChunk:()=>Qw,isHumanMessage:()=>eb,isHumanMessageChunk:()=>tb,isIDContentBlock:()=>jp,isMessage:()=>Up,isOpenAIToolCallArray:()=>Fw,isPlainTextContentBlock:()=>_w,isSystemMessage:()=>rb,isSystemMessageChunk:()=>nb,isToolMessage:()=>Kp,isToolMessageChunk:()=>Zp,isURLContentBlock:()=>du,mapChatMessagesToStoredMessages:()=>ub,mapStoredMessageToChatMessage:()=>vu,mapStoredMessagesToChatMessages:()=>lb,mergeContent:()=>Qr,mergeMessageRuns:()=>NT,mergeResponseMetadata:()=>Gp,mergeUsageMetadata:()=>Vp,parseBase64DataUrl:()=>Zr,parseMimeType:()=>ml,trimMessages:()=>LT});const Kr=r=>r();function Vs(r){return r?!!(/^o\d/.test(r??"")||r.startsWith("gpt-5")&&!r.startsWith("gpt-5-chat")):!1}function qT(r){return r.role!=="system"&&r.role!=="developer"&&r.role!=="assistant"&&r.role!=="user"&&r.role!=="function"&&r.role!=="tool"&&console.warn(`Unknown message role: ${r.role}`),r.role}function Ks(r){const e=r._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!tn.isInstance(r))throw new Error("Invalid generic chat message");return qT(r);default:throw new Error(`Unknown message type: ${e}`)}}function zT(r){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:t,azureOpenAIApiKey:n,azureOpenAIBasePath:s,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=r;if((n||i)&&s&&e)return`${s}/${e}`;if((n||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(n||i){if(!t)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${t}.openai.azure.com/openai/deployments/${e}`}return a}var HT={};pe(HT,{extendInteropZodObject:()=>XS,getInteropZodDefaultGetter:()=>QS,getInteropZodObjectShape:()=>$l,getSchemaDescription:()=>to,interopParse:()=>VS,interopParseAsync:()=>eo,interopSafeParse:()=>JS,interopSafeParseAsync:()=>Mu,interopZodObjectMakeFieldsOptional:()=>rE,interopZodObjectPartial:()=>YS,interopZodObjectPassthrough:()=>Cl,interopZodObjectStrict:()=>_i,interopZodTransformInputSchema:()=>Tn,isInteropZodLiteral:()=>GS,isInteropZodObject:()=>ZS,isInteropZodSchema:()=>Rt,isShapelessZodSchema:()=>KS,isSimpleStringZodSchema:()=>ju,isZodArrayV4:()=>ro,isZodLiteralV3:()=>Km,isZodLiteralV4:()=>Zm,isZodObjectV3:()=>Du,isZodObjectV4:()=>ar,isZodSchema:()=>WS,isZodSchemaV3:()=>je,isZodSchemaV4:()=>$e});function zu(r){return r!==void 0&&Array.isArray(r.lc_namespace)}function Hu(r){return r!==void 0&&Pe.isRunnable(r)&&"lc_name"in r.constructor&&typeof r.constructor.lc_name=="function"&&r.constructor.lc_name()==="RunnableToolLike"}function Wu(r){return!!r&&typeof r=="object"&&"name"in r&&"schema"in r&&(Rt(r.schema)||r.schema!=null&&typeof r.schema=="object"&&"type"in r.schema&&typeof r.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(r.schema.type))}function Zs(r){return Wu(r)||Hu(r)||zu(r)}var WT={};pe(WT,{convertToOpenAIFunction:()=>mg,convertToOpenAITool:()=>gg,isLangChainTool:()=>Zs,isRunnableToolLike:()=>Hu,isStructuredTool:()=>zu,isStructuredToolParams:()=>Wu});function mg(r,e){const t=typeof e=="number"?void 0:e;return{name:r.name,description:r.description,parameters:ut(r.schema),...(t==null?void 0:t.strict)!==void 0?{strict:t.strict}:{}}}function gg(r,e){const t=typeof e=="number"?void 0:e;let n;return Zs(r)?n={type:"function",function:mg(r)}:n=r,(t==null?void 0:t.strict)!==void 0&&(n.function.strict=t.strict),n}function GT(r,e){let t;return Zs(r)?t=gg(r):t=r,(e==null?void 0:e.strict)!==void 0&&(t.function.strict=e.strict),t}function JT(r){return r.anyOf!==void 0&&Array.isArray(r.anyOf)}function VT(r){const e=["namespace functions {",""];for(const t of r)t.description&&e.push(`// ${t.description}`),Object.keys(t.parameters.properties??{}).length>0?(e.push(`type ${t.name} = (_: {`),e.push(_g(t.parameters,0)),e.push("}) => any;")):e.push(`type ${t.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
87
+ `)}function _g(r,e){var n;const t=[];for(const[s,a]of Object.entries(r.properties??{}))a.description&&e<2&&t.push(`// ${a.description}`),(n=r.required)!=null&&n.includes(s)?t.push(`${s}: ${bi(a,e)},`):t.push(`${s}?: ${bi(a,e)},`);return t.map(s=>" ".repeat(e)+s).join(`
88
+ `)}function bi(r,e){if(JT(r))return r.anyOf.map(t=>bi(t,e)).join(" | ");switch(r.type){case"string":return r.enum?r.enum.map(t=>`"${t}"`).join(" | "):"string";case"number":return r.enum?r.enum.map(t=>`${t}`).join(" | "):"number";case"integer":return r.enum?r.enum.map(t=>`${t}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",_g(r,e+2),"}"].join(`
89
+ `);case"array":return r.items?`${bi(r.items,e)}[]`:"any[]";default:return""}}function yg(r){if(r)return r==="any"||r==="required"?"required":r==="auto"?"auto":r==="none"?"none":typeof r=="string"?{type:"function",function:{name:r}}:r}function Gu(r){return"type"in r&&r.type!=="function"}function KT(r){return r!=null&&typeof r=="object"&&"type"in r&&r.type!=="function"}function vi(r){return typeof r=="object"&&r!==null&&"metadata"in r&&typeof r.metadata=="object"&&r.metadata!==null&&"customTool"in r.metadata&&typeof r.metadata.customTool=="object"&&r.metadata.customTool!==null}function wg(r){return"type"in r&&r.type==="custom"&&"custom"in r&&typeof r.custom=="object"&&r.custom!==null}function ZT(r){if(r.type==="custom_tool_call")return{...r,type:"tool_call",call_id:r.id,id:r.call_id,name:r.name,isCustomTool:!0,args:{input:r.input}}}function XT(r){return r.type==="tool_call"&&"isCustomTool"in r&&r.isCustomTool===!0}function YT(r){const e=()=>{if(r.custom.format){if(r.custom.format.type==="grammar")return{type:"grammar",definition:r.custom.format.grammar.definition,syntax:r.custom.format.grammar.syntax};if(r.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:r.custom.name,description:r.custom.description,format:e()}}function QT(r){const e=()=>{if(r.format){if(r.format.type==="grammar")return{type:"grammar",grammar:{definition:r.format.definition,syntax:r.format.syntax}};if(r.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:r.name,description:r.description,format:e()}}}function Ll(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}const Ml=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){const e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};class Y extends Error{}let ht=class jl extends Y{constructor(e,t,n,s){super(`${jl.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("x-request-id"),this.error=t;const a=t;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(e,t,n){const s=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new no({message:n,cause:Ml(t)});const a=t==null?void 0:t.error;return e===400?new bg(e,a,n,s):e===401?new vg(e,a,n,s):e===403?new Sg(e,a,n,s):e===404?new Eg(e,a,n,s):e===409?new Tg(e,a,n,s):e===422?new xg(e,a,n,s):e===429?new Ag(e,a,n,s):e>=500?new Ig(e,a,n,s):new jl(e,a,n,s)}},bt=class extends ht{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},no=class extends ht{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},so=class extends no{constructor({message:e}={}){super({message:e??"Request timed out."})}},bg=class extends ht{},vg=class extends ht{},Sg=class extends ht{},Eg=class extends ht{},Tg=class extends ht{},xg=class extends ht{},Ag=class extends ht{},Ig=class extends ht{};class Rg extends Y{constructor(){super("Could not parse response content as the length limit was reached")}}class Og extends Y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class as extends Error{constructor(e){super(e)}}function Si(r){return r!==void 0&&"function"in r&&r.function!==void 0}function ex(r,e){const t={...r};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function Ju(r){return(r==null?void 0:r.$brand)==="auto-parseable-response-format"}function Xs(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function tx(r,e){return!e||!$g(e)?{...r,choices:r.choices.map(t=>(Cg(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Vu(r,e)}function Vu(r,e){const t=r.choices.map(n=>{var s;if(n.finish_reason==="length")throw new Rg;if(n.finish_reason==="content_filter")throw new Og;return Cg(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((s=n.message.tool_calls)==null?void 0:s.map(a=>nx(e,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?rx(e,n.message.content):null}}});return{...r,choices:t}}function rx(r,e){var t,n;return((t=r.response_format)==null?void 0:t.type)!=="json_schema"?null:((n=r.response_format)==null?void 0:n.type)==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}function nx(r,e){var n;const t=(n=r.tools)==null?void 0:n.find(s=>{var a;return Si(s)&&((a=s.function)==null?void 0:a.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Xs(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function sx(r,e){var n;if(!r||!("tools"in r)||!r.tools)return!1;const t=(n=r.tools)==null?void 0:n.find(s=>{var a;return Si(s)&&((a=s.function)==null?void 0:a.name)===e.function.name});return Si(t)&&(Xs(t)||(t==null?void 0:t.function.strict)||!1)}function $g(r){var e;return Ju(r.response_format)?!0:((e=r.tools)==null?void 0:e.some(t=>Xs(t)||t.type==="function"&&t.function.strict===!0))??!1}function Cg(r){for(const e of r||[])if(e.type!=="function")throw new Y(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function ax(r){for(const e of r??[]){if(e.type!=="function")throw new Y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new Y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const ix=Symbol("Let zodToJsonSchema decide on which parser to use"),Tf={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},ox=r=>typeof r=="string"?{...Tf,basePath:["#"],definitions:{},name:r}:{...Tf,basePath:["#"],definitions:{},...r},Dl=r=>"_def"in r?r._def:r;function cx(r){if(!r)return!0;for(const e in r)return!1;return!0}const lx=r=>{const e=ox(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[Dl(s),{def:Dl(s),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function kg(r,e,t,n){n!=null&&n.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function ve(r,e,t,n,s){r[e]=t,kg(r,e,n,s)}function ux(){return{}}function dx(r,e){var n,s;const t={type:"array"};return((s=(n=r.type)==null?void 0:n._def)==null?void 0:s.typeName)!==L.ZodAny&&(t.items=_e(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&ve(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&ve(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(ve(t,"minItems",r.exactLength.value,r.exactLength.message,e),ve(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function hx(r,e){const t={type:"integer",format:"int64"};if(!r.checks)return t;for(const n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ve(t,"minimum",n.value,n.message,e):ve(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ve(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ve(t,"maximum",n.value,n.message,e):ve(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ve(t,"maximum",n.value,n.message,e));break;case"multipleOf":ve(t,"multipleOf",n.value,n.message,e);break}return t}function fx(){return{type:"boolean"}}function px(r,e){return _e(r.type._def,e)}const mx=(r,e)=>_e(r.innerType._def,e);function Pg(r,e,t){const n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,a)=>Pg(r,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return gx(r,e)}}const gx=(r,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const n of r.checks)switch(n.kind){case"min":ve(t,"minimum",n.value,n.message,e);break;case"max":ve(t,"maximum",n.value,n.message,e);break}return t};function _x(r,e){return{..._e(r.innerType._def,e),default:r.defaultValue()}}function yx(r,e,t){return e.effectStrategy==="input"?_e(r.schema._def,e,t):{}}function wx(r){return{type:"string",enum:[...r.values]}}const bx=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function vx(r,e){const t=[_e(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),_e(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return t.forEach(a=>{if(bx(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}function Sx(r,e){const t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}let zc;const Dr={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:()=>(zc===void 0&&(zc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),zc),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function Ng(r,e){const t={type:"string"};function n(s){return e.patternStrategy==="escape"?Ex(s):s}if(r.checks)for(const s of r.checks)switch(s.kind){case"min":ve(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,s.value):s.value,s.message,e);break;case"max":ve(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,s.value):s.value,s.message,e);break;case"email":switch(e.emailStrategy){case"format:email":kt(t,"email",s.message,e);break;case"format:idn-email":kt(t,"idn-email",s.message,e);break;case"pattern:zod":Pt(t,Dr.email,s.message,e);break}break;case"url":kt(t,"uri",s.message,e);break;case"uuid":kt(t,"uuid",s.message,e);break;case"regex":Pt(t,s.regex,s.message,e);break;case"cuid":Pt(t,Dr.cuid,s.message,e);break;case"cuid2":Pt(t,Dr.cuid2,s.message,e);break;case"startsWith":Pt(t,RegExp(`^${n(s.value)}`),s.message,e);break;case"endsWith":Pt(t,RegExp(`${n(s.value)}$`),s.message,e);break;case"datetime":kt(t,"date-time",s.message,e);break;case"date":kt(t,"date",s.message,e);break;case"time":kt(t,"time",s.message,e);break;case"duration":kt(t,"duration",s.message,e);break;case"length":ve(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,s.value):s.value,s.message,e),ve(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,s.value):s.value,s.message,e);break;case"includes":{Pt(t,RegExp(n(s.value)),s.message,e);break}case"ip":{s.version!=="v6"&&kt(t,"ipv4",s.message,e),s.version!=="v4"&&kt(t,"ipv6",s.message,e);break}case"emoji":Pt(t,Dr.emoji,s.message,e);break;case"ulid":{Pt(t,Dr.ulid,s.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{kt(t,"binary",s.message,e);break}case"contentEncoding:base64":{ve(t,"contentEncoding","base64",s.message,e);break}case"pattern:zod":{Pt(t,Dr.base64,s.message,e);break}}break}case"nanoid":Pt(t,Dr.nanoid,s.message,e)}return t}const Ex=r=>Array.from(r).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),kt=(r,e,t,n)=>{var s;r.format||(s=r.anyOf)!=null&&s.some(a=>a.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):ve(r,"format",e,t,n)},Pt=(r,e,t,n)=>{var s;r.pattern||(s=r.allOf)!=null&&s.some(a=>a.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:xf(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):ve(r,"pattern",xf(e,n),t,n)},xf=(r,e)=>{var l;const t=typeof r=="function"?r():r;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")},s=n.i?t.source.toLowerCase():t.source;let a="",i=!1,o=!1,c=!1;for(let u=0;u<s.length;u++){if(i){a+=s[u],i=!1;continue}if(n.i){if(o){if(s[u].match(/[a-z]/)){c?(a+=s[u],a+=`${s[u-2]}-${s[u]}`.toUpperCase(),c=!1):s[u+1]==="-"&&((l=s[u+2])!=null&&l.match(/[a-z]/))?(a+=s[u],c=!0):a+=`${s[u]}${s[u].toUpperCase()}`;continue}}else if(s[u].match(/[a-z]/)){a+=`[${s[u]}${s[u].toUpperCase()}]`;continue}}if(n.m){if(s[u]==="^"){a+=`(^|(?<=[\r
90
+ ]))`;continue}else if(s[u]==="$"){a+=`($|(?=[\r
91
+ ]))`;continue}}if(n.s&&s[u]==="."){a+=o?`${s[u]}\r
92
+ `:`[${s[u]}\r
93
+ ]`;continue}a+=s[u],s[u]==="\\"?i=!0:o&&s[u]==="]"?o=!1:!o&&s[u]==="["&&(o=!0)}try{const u=new RegExp(a)}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 a};function Lg(r,e){var n,s,a,i;if(e.target==="openApi3"&&((n=r.keyType)==null?void 0:n._def.typeName)===L.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((o,c)=>({...o,[c]:_e(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",c]})??{}}),{}),additionalProperties:!1};const t={type:"object",additionalProperties:_e(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(((s=r.keyType)==null?void 0:s._def.typeName)===L.ZodString&&((a=r.keyType._def.checks)!=null&&a.length)){const o=Object.entries(Ng(r.keyType._def,e)).reduce((c,[l,u])=>l==="type"?c:{...c,[l]:u},{});return{...t,propertyNames:o}}else if(((i=r.keyType)==null?void 0:i._def.typeName)===L.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};return t}function Tx(r,e){if(e.mapStrategy==="record")return Lg(r,e);const t=_e(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=_e(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function xx(r){const e=r.values,n=Object.keys(r.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(n.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function Ax(){return{not:{}}}function Ix(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ei={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Rx(r,e){if(e.target==="openApi3")return Af(r,e);const t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in Ei&&(!n._def.checks||!n._def.checks.length))){const n=t.reduce((s,a)=>{const i=Ei[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=t.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===t.length){const s=n.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:t.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,s)=>[...n,...s._def.values.filter(a=>!n.includes(a))],[])};return Af(r,e)}const Af=(r,e)=>{const t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,s)=>_e(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function Ox(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Ei[r.innerType._def.typeName],nullable:!0}:{type:[Ei[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=_e(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const t=_e(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function $x(r,e){const t={type:"number"};if(!r.checks)return t;for(const n of r.checks)switch(n.kind){case"int":t.type="integer",kg(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ve(t,"minimum",n.value,n.message,e):ve(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ve(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ve(t,"maximum",n.value,n.message,e):ve(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ve(t,"maximum",n.value,n.message,e));break;case"multipleOf":ve(t,"multipleOf",n.value,n.message,e);break}return t}function Cx(r,e){return e.removeAdditionalStrategy==="strict"?r.catchall._def.typeName==="ZodNever"?r.unknownKeys!=="strict":_e(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:r.catchall._def.typeName==="ZodNever"?r.unknownKeys==="passthrough":_e(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function kx(r,e){const t={type:"object",...Object.entries(r.shape()).reduce((n,[s,a])=>{var c;if(a===void 0||a._def===void 0)return n;const i=[...e.currentPath,"properties",s],o=_e(a._def,{...e,currentPath:i,propertyPath:i});if(o===void 0)return n;if(e.openaiStrictMode&&a.isOptional()&&!a.isNullable()&&typeof((c=a._def)==null?void 0:c.defaultValue)>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[s]:o},required:a.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,s]}},{properties:{},required:[]}),additionalProperties:Cx(r,e)};return t.required.length||delete t.required,t}const Px=(r,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return _e(r.innerType._def,{...e,currentPath:e.currentPath});const t=_e(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}},Nx=(r,e)=>{if(e.pipeStrategy==="input")return _e(r.in._def,e);if(e.pipeStrategy==="output")return _e(r.out._def,e);const t=_e(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=_e(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(s=>s!==void 0)}};function Lx(r,e){return _e(r.type._def,e)}function Mx(r,e){const n={type:"array",uniqueItems:!0,items:_e(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&ve(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&ve(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function jx(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>_e(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:_e(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>_e(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function Dx(){return{not:{}}}function Ux(){return{}}const Fx=(r,e)=>_e(r.innerType._def,e);function _e(r,e,t=!1){var i;const n=e.seen.get(r);if(e.override){const o=(i=e.override)==null?void 0:i.call(e,r,e,n,t);if(o!==ix)return o}if(n&&!t){const o=Bx(n,e);if(o!==void 0)return"$ref"in o&&e.seenRefs.add(o.$ref),o}const s={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,s);const a=zx(r,r.typeName,e,t);return a&&Hx(r,e,a),s.jsonSchema=a,a}const Bx=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"extract-to-root":const t=r.path.slice(e.basePath.length+1).join("_");return t!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[t]=r.def),{$ref:[...e.basePath,e.definitionPath,t].join("/")};case"relative":return{$ref:qx(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((n,s)=>e.currentPath[s]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},qx=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")},zx=(r,e,t,n)=>{switch(e){case L.ZodString:return Ng(r,t);case L.ZodNumber:return $x(r,t);case L.ZodObject:return kx(r,t);case L.ZodBigInt:return hx(r,t);case L.ZodBoolean:return fx();case L.ZodDate:return Pg(r,t);case L.ZodUndefined:return Dx();case L.ZodNull:return Ix(t);case L.ZodArray:return dx(r,t);case L.ZodUnion:case L.ZodDiscriminatedUnion:return Rx(r,t);case L.ZodIntersection:return vx(r,t);case L.ZodTuple:return jx(r,t);case L.ZodRecord:return Lg(r,t);case L.ZodLiteral:return Sx(r,t);case L.ZodEnum:return wx(r);case L.ZodNativeEnum:return xx(r);case L.ZodNullable:return Ox(r,t);case L.ZodOptional:return Px(r,t);case L.ZodMap:return Tx(r,t);case L.ZodSet:return Mx(r,t);case L.ZodLazy:return _e(r.getter()._def,t);case L.ZodPromise:return Lx(r,t);case L.ZodNaN:case L.ZodNever:return Ax();case L.ZodEffects:return yx(r,t,n);case L.ZodAny:return ux();case L.ZodUnknown:return Ux();case L.ZodDefault:return _x(r,t);case L.ZodBranded:return px(r,t);case L.ZodReadonly:return Fx(r,t);case L.ZodCatch:return mx(r,t);case L.ZodPipeline:return Nx(r,t);case L.ZodFunction:case L.ZodVoid:case L.ZodSymbol:return;default:return(s=>{})()}},Hx=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t),Wx=(r,e)=>{const t=lx(e),n=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,s=_e(r._def,n===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,n]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(s.title=a);const i=(()=>{if(cx(t.definitions))return;const c={},l=new Set;for(let u=0;u<500;u++){const d=Object.entries(t.definitions).filter(([h])=>!l.has(h));if(d.length===0)break;for(const[h,f]of d)c[h]=_e(Dl(f),{...t,currentPath:[...t.basePath,t.definitionPath,h]},!0)??{},l.add(h)}return c})(),o=n===void 0?i?{...s,[t.definitionPath]:i}:s:t.nameStrategy==="duplicate-ref"?{...s,...i||t.seenRefs.size?{[t.definitionPath]:{...i,...t.seenRefs.size?{[n]:s}:void 0}}:void 0}:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,n].join("/"),[t.definitionPath]:{...i,[n]:s}};return t.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function Gx(r,e){return!e||!Vx(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:Mg(r,e)}function Mg(r,e){const t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Xx(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:Jx(e,i.text)}:i);return{...s,content:a}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||Ul(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const s of n.output)if(s.type==="message"){for(const a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function Jx(r,e){var t,n,s,a;return((n=(t=r.text)==null?void 0:t.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((s=r.text)==null?void 0:s.format)?((a=r.text)==null?void 0:a.format).$parseRaw(e):JSON.parse(e)}function Vx(r){var e;return!!Ju((e=r.text)==null?void 0:e.format)}function Kx(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function Zx(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function Xx(r,e){const t=Zx(r.tools??[],e.name);return{...e,...e,parsed_arguments:Kx(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function Ul(r){const e=[];for(const t of r.output)if(t.type==="message")for(const n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}function Yx(r,e){return Wx(r,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Qx(r,e,t){return ex({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:Yx(r,{name:e})}},n=>r.parse(JSON.parse(n)))}const If=["jsonSchema","functionCalling","jsonMode"];function eA(r,e){if(typeof e<"u"&&!If.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${If.join(", ")}`);const t=!r.startsWith("gpt-3")&&!r.startsWith("gpt-4-")&&r!=="gpt-4";if(t&&!e)return"jsonSchema";if(!t&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${r}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function tA(r,e){const t={...r};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function rA(r,e,t){if(je(r))return Qx(r,e,t);if($e(r))return tA({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:Ol(r,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Qi(r,JSON.parse(n)));throw new Error("Unsupported schema response format")}function nA(r,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){const t=e.images.filter(n=>{var s;return typeof((s=n==null?void 0:n.image_url)==null?void 0:s.url)=="string"}).map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:r},...t]}return r}function Rf(r){var n,s,a,i;const e={...((n=r==null?void 0:r.input_tokens_details)==null?void 0:n.cached_tokens)!=null&&{cache_read:(s=r==null?void 0:r.input_tokens_details)==null?void 0:s.cached_tokens}},t={...((a=r==null?void 0:r.output_tokens_details)==null?void 0:a.reasoning_tokens)!=null&&{reasoning:(i=r==null?void 0:r.output_tokens_details)==null?void 0:i.reasoning_tokens}};return{input_tokens:(r==null?void 0:r.input_tokens)??0,output_tokens:(r==null?void 0:r.output_tokens)??0,total_tokens:(r==null?void 0:r.total_tokens)??0,input_token_details:e,output_token_details:t}}function te(r,e,t,n,s){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}function I(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}let jg=function(){const{crypto:r}=globalThis;if(r!=null&&r.randomUUID)return jg=r.randomUUID.bind(r),r.randomUUID();const e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};const sA=/^[a-z][a-z0-9+.-]*:/i,aA=r=>sA.test(r);let ot=r=>(ot=Array.isArray,ot(r)),Of=ot;function Dg(r){return typeof r!="object"?{}:r??{}}function iA(r){if(!r)return!0;for(const e in r)return!1;return!0}function oA(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Hc(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}const cA=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Y(`${r} must be an integer`);if(e<0)throw new Y(`${r} must be a positive integer`);return e},lA=r=>{try{return JSON.parse(r)}catch{return}},Ys=r=>new Promise(e=>setTimeout(e,r)),gn="6.6.0",uA=()=>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=()=>{var t;const r=dA();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gn,"X-Stainless-OS":Cf(Deno.build.os),"X-Stainless-Arch":$f(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((t=Deno.version)==null?void 0:t.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gn,"X-Stainless-OS":Cf(globalThis.process.platform??"unknown"),"X-Stainless-Arch":$f(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":gn,"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":gn,"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 r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of r){const n=t.exec(navigator.userAgent);if(n){const s=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}const $f=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Cf=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown");let kf;const pA=()=>kf??(kf=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 Ug(...r){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(...r)}function Fg(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return Ug({start(){},async pull(t){const{done:n,value:s}=await e.next();n?t.close():t.enqueue(s)},async cancel(){var t;await((t=e.return)==null?void 0:t.call(e))}})}function Bg(r){if(r[Symbol.asyncIterator])return r;const e=r.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function gA(r){var n,s;if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await((s=(n=r[Symbol.asyncIterator]()).return)==null?void 0:s.call(n));return}const e=r.getReader(),t=e.cancel();e.releaseLock(),await t}const _A=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),qg="RFC3986",zg=r=>String(r),Pf={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:zg},yA="RFC1738";let Fl=(r,e)=>(Fl=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Fl(r,e));const er=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),Wc=1024,wA=(r,e,t,n,s)=>{if(r.length===0)return r;let a=r;if(typeof r=="symbol"?a=Symbol.prototype.toString.call(r):typeof r!="string"&&(a=String(r)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=Wc){const c=a.length>=Wc?a.slice(o,o+Wc):a,l=[];for(let u=0;u<c.length;++u){let d=c.charCodeAt(u);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)){l[l.length]=c.charAt(u);continue}if(d<128){l[l.length]=er[d];continue}if(d<2048){l[l.length]=er[192|d>>6]+er[128|d&63];continue}if(d<55296||d>=57344){l[l.length]=er[224|d>>12]+er[128|d>>6&63]+er[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=er[240|d>>18]+er[128|d>>12&63]+er[128|d>>6&63]+er[128|d&63]}i+=l.join("")}return i};function bA(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Nf(r,e){if(ot(r)){const t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}const Hg={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},Wg=function(r,e){Array.prototype.push.apply(r,ot(e)?e:[e])};let Lf;const Be={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:wA,encodeValuesOnly:!1,format:qg,formatter:zg,indices:!1,serializeDate(r){return(Lf??(Lf=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function vA(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const Gc={};function Gg(r,e,t,n,s,a,i,o,c,l,u,d,h,f,p,g,_,b){let m=r,y=b,T=0,x=!1;for(;(y=y.get(Gc))!==void 0&&!x;){const se=y.get(r);if(T+=1,typeof se<"u"){if(se===T)throw new RangeError("Cyclic object value");x=!0}typeof y.get(Gc)>"u"&&(T=0)}if(typeof l=="function"?m=l(e,m):m instanceof Date?m=h==null?void 0:h(m):t==="comma"&&ot(m)&&(m=Nf(m,function(se){return se instanceof Date?h==null?void 0:h(se):se})),m===null){if(a)return c&&!g?c(e,Be.encoder,_,"key",f):e;m=""}if(vA(m)||bA(m)){if(c){const se=g?e:c(e,Be.encoder,_,"key",f);return[(p==null?void 0:p(se))+"="+(p==null?void 0:p(c(m,Be.encoder,_,"value",f)))]}return[(p==null?void 0:p(e))+"="+(p==null?void 0:p(String(m)))]}const R=[];if(typeof m>"u")return R;let $;if(t==="comma"&&ot(m))g&&c&&(m=Nf(m,c)),$=[{value:m.length>0?m.join(",")||null:void 0}];else if(ot(l))$=l;else{const se=Object.keys(m);$=u?se.sort(u):se}const E=o?String(e).replace(/\./g,"%2E"):String(e),J=n&&ot(m)&&m.length===1?E+"[]":E;if(s&&ot(m)&&m.length===0)return J+"[]";for(let se=0;se<$.length;++se){const H=$[se],Ae=typeof H=="object"&&typeof H.value<"u"?H.value:m[H];if(i&&Ae===null)continue;const ft=d&&o?H.replace(/\./g,"%2E"):H,M=ot(m)?typeof t=="function"?t(J,ft):J:J+(d?"."+ft:"["+ft+"]");b.set(r,T);const P=new WeakMap;P.set(Gc,b),Wg(R,Gg(Ae,M,t,n,s,a,i,o,t==="comma"&&g&&ot(m)?null:c,l,u,d,h,f,p,g,_,P))}return R}function SA(r=Be){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=r.charset||Be.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=qg;if(typeof r.format<"u"){if(!Fl(Pf,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const n=Pf[t];let s=Be.filter;(typeof r.filter=="function"||ot(r.filter))&&(s=r.filter);let a;if(r.arrayFormat&&r.arrayFormat in Hg?a=r.arrayFormat:"indices"in r?a=r.indices?"indices":"repeat":a=Be.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:Be.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:Be.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:Be.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:Be.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?Be.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:Be.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:Be.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:Be.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:Be.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:Be.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:Be.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:Be.strictNullHandling}}function EA(r,e={}){let t=r;const n=SA(e);let s,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):ot(n.filter)&&(a=n.filter,s=a);const i=[];if(typeof t!="object"||t===null)return"";const o=Hg[n.arrayFormat],c=o==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);const l=new WeakMap;for(let h=0;h<s.length;++h){const f=s[h];n.skipNulls&&t[f]===null||Wg(i,Gg(t[f],f,o,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}const u=i.join(n.delimiter);let d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}function TA(r){let e=0;for(const s of r)e+=s.length;const t=new Uint8Array(e);let n=0;for(const s of r)t.set(s,n),n+=s.length;return t}let Mf;function Ku(r){let e;return(Mf??(e=new globalThis.TextEncoder,Mf=e.encode.bind(e)))(r)}let jf;function Df(r){let e;return(jf??(e=new globalThis.TextDecoder,jf=e.decode.bind(e)))(r)}var mt,gt;let ao=class{constructor(){mt.set(this,void 0),gt.set(this,void 0),te(this,mt,new Uint8Array),te(this,gt,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Ku(e):e;te(this,mt,TA([I(this,mt,"f"),t]));const n=[];let s;for(;(s=xA(I(this,mt,"f"),I(this,gt,"f")))!=null;){if(s.carriage&&I(this,gt,"f")==null){te(this,gt,s.index);continue}if(I(this,gt,"f")!=null&&(s.index!==I(this,gt,"f")+1||s.carriage)){n.push(Df(I(this,mt,"f").subarray(0,I(this,gt,"f")-1))),te(this,mt,I(this,mt,"f").subarray(I(this,gt,"f"))),te(this,gt,null);continue}const a=I(this,gt,"f")!==null?s.preceding-1:s.preceding,i=Df(I(this,mt,"f").subarray(0,a));n.push(i),te(this,mt,I(this,mt,"f").subarray(s.index)),te(this,gt,null)}return n}flush(){return I(this,mt,"f").length?this.decode(`
94
+ `):[]}};mt=new WeakMap,gt=new WeakMap;ao.NEWLINE_CHARS=new Set([`
95
+ `,"\r"]);ao.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function xA(r,e){for(let s=e??0;s<r.length;s++){if(r[s]===10)return{preceding:s,index:s+1,carriage:!1};if(r[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function AA(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}const Ti={off:0,error:200,warn:300,info:400,debug:500},Uf=(r,e,t)=>{if(r){if(oA(Ti,r))return r;Ve(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Ti))}`)}};function is(){}function wa(r,e,t){return!e||Ti[r]>Ti[t]?is:e[r].bind(e)}const IA={error:is,warn:is,info:is,debug:is};let Ff=new WeakMap;function Ve(r){const e=r.logger,t=r.logLevel??"off";if(!e)return IA;const n=Ff.get(e);if(n&&n[0]===t)return n[1];const s={error:wa("error",e,t),warn:wa("warn",e,t),info:wa("info",e,t),debug:wa("debug",e,t)};return Ff.set(e,[t,s]),s}const Fr=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var Bn;let Ls=class os{constructor(e,t,n){this.iterator=e,Bn.set(this,void 0),this.controller=t,te(this,Bn,n)}static fromSSEResponse(e,t,n){let s=!1;const a=n?Ve(n):console;async function*i(){if(s)throw new Y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const c of RA(e,t))if(!o){if(c.data.startsWith("[DONE]")){o=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let l;try{l=JSON.parse(c.data)}catch(u){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),u}if(l&&l.error)throw new ht(void 0,l.error,void 0,e.headers);yield l}else{let l;try{l=JSON.parse(c.data)}catch(u){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),u}if(c.event=="error")throw new ht(void 0,l.error,l.message,void 0);yield{event:c.event,data:l}}}o=!0}catch(c){if(Ll(c))return;throw c}finally{o||t.abort()}}return new os(i,t,n)}static fromReadableStream(e,t,n){let s=!1;async function*a(){const o=new ao,c=Bg(e);for await(const l of c)for(const u of o.decode(l))yield u;for(const l of o.flush())yield l}async function*i(){if(s)throw new Y("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(Ll(c))return;throw c}finally{o||t.abort()}}return new os(i,t,n)}[(Bn=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=a=>({next:()=>{if(a.length===0){const i=n.next();e.push(i),t.push(i)}return a.shift()}});return[new os(()=>s(e),this.controller,I(this,Bn,"f")),new os(()=>s(t),this.controller,I(this,Bn,"f"))]}toReadableStream(){const e=this;let t;return Ug({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{const{value:s,done:a}=await t.next();if(a)return n.close();const i=Ku(JSON.stringify(s)+`
96
+ `);n.enqueue(i)}catch(s){n.error(s)}},async cancel(){var n;await((n=t.return)==null?void 0:n.call(t))}})}};async function*RA(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Y("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 Y("Attempted to iterate over a response with no body");const t=new $A,n=new ao,s=Bg(r.body);for await(const a of OA(s))for(const i of n.decode(a)){const o=t.decode(i);o&&(yield o)}for(const a of n.flush()){const i=t.decode(a);i&&(yield i)}}async function*OA(r){let e=new Uint8Array;for await(const t of r){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Ku(t):t;let s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let a;for(;(a=AA(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}let $A=class{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(`
97
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=CA(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function CA(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function Jg(r,e){const{response:t,requestLogID:n,retryOfRequestLogID:s,startTime:a}=e,i=await(async()=>{var d;if(e.options.stream)return Ve(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r):Ls.fromSSEResponse(t,e.controller,r);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const o=t.headers.get("content-type"),c=(d=o==null?void 0:o.split(";")[0])==null?void 0:d.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){const h=await t.json();return Vg(h,t)}return await t.text()})();return Ve(r).debug(`[${n}] response parsed`,Fr({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function Vg(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var cs;let Kg=class Zg extends Promise{constructor(e,t,n=Jg){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=n,cs.set(this,void 0),te(this,cs,e)}_thenUnwrap(e){return new Zg(I(this,cs,"f"),this.responsePromise,async(t,n)=>Vg(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(I(this,cs,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};cs=new WeakMap;var ba;let Zu=class{constructor(e,t,n,s){ba.set(this,void 0),te(this,ba,e),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await I(this,ba,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ba=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}},kA=class extends Kg{constructor(e,t,n){super(e,t,async(s,a)=>new n(s,a.response,await Jg(s,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}},io=class extends Zu{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}};class Me extends Zu{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var n;const e=this.getPaginatedItems(),t=(n=e[e.length-1])==null?void 0:n.id;return t?{...this.options,query:{...Dg(this.options.query),after:t}}:null}}class xi extends Zu{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.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:{...Dg(this.options.query),after:e}}:null}}const Xg=()=>{var r;if(typeof File>"u"){const{process:e}=globalThis,t=typeof((r=e==null?void 0:e.versions)==null?void 0:r.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ts(r,e,t){return Xg(),new File(r,e??"unknown_file",t)}function Za(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}const Xu=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Bf=async(r,e)=>Bl(r.body)?{...r,body:await Yg(r.body,e)}:r,Yr=async(r,e)=>({...r,body:await Yg(r.body,e)}),qf=new WeakMap;function PA(r){const e=typeof r=="function"?r:r.fetch,t=qf.get(e);if(t)return t;const n=(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 qf.set(e,n),n}const Yg=async(r,e)=>{if(!await PA(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(r||{}).map(([n,s])=>ql(t,n,s))),t},Qg=r=>r instanceof Blob&&"name"in r,NA=r=>typeof r=="object"&&r!==null&&(r instanceof Response||Xu(r)||Qg(r)),Bl=r=>{if(NA(r))return!0;if(Array.isArray(r))return r.some(Bl);if(r&&typeof r=="object"){for(const e in r)if(Bl(r[e]))return!0}return!1},ql=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response)r.append(e,Ts([await t.blob()],Za(t)));else if(Xu(t))r.append(e,Ts([await new Response(Fg(t)).blob()],Za(t)));else if(Qg(t))r.append(e,t,Za(t));else if(Array.isArray(t))await Promise.all(t.map(n=>ql(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>ql(r,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},e_=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",LA=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&e_(r),MA=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function jA(r,e,t){if(Xg(),r=await r,LA(r))return r instanceof File?r:Ts([await r.arrayBuffer()],r.name);if(MA(r)){const s=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),Ts(await zl(s),e,t)}const n=await zl(r);if(e||(e=Za(r)),!(t!=null&&t.type)){const s=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof s=="string"&&(t={...t,type:s})}return Ts(n,e,t)}async function zl(r){var t;let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(e_(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(Xu(r))for await(const n of r)e.push(...await zl(n));else{const n=(t=r==null?void 0:r.constructor)==null?void 0:t.name;throw new Error(`Unexpected data type: ${typeof r}${n?`; constructor: ${n}`:""}${DA(r)}`)}return e}function DA(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}let K=class{constructor(e){this._client=e}};function t_(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const zf=Object.freeze(Object.create(null)),UA=(r=t_)=>function(t,...n){if(t.length===1)return t[0];let s=!1;const a=[],i=t.reduce((u,d,h)=>{var g;/[?#]/.test(d)&&(s=!0);const f=n[h];let p=(s?encodeURIComponent:r)(""+f);return h!==n.length&&(f==null||typeof f=="object"&&f.toString===((g=Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??zf)??zf))==null?void 0:g.toString))&&(p=f+"",a.push({start:u.length+d.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),u+d+(h===n.length?"":p)},""),o=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let l;for(;(l=c.exec(o))!==null;)a.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(a.sort((u,d)=>u.start-d.start),a.length>0){let u=0;const d=a.reduce((h,f)=>{const p=" ".repeat(f.start-u),g="^".repeat(f.length);return u=f.start+f.length,h+p+g},"");throw new Y(`Path parameters result in path with invalid segments:
98
+ ${a.map(h=>h.error).join(`
99
+ `)}
100
+ ${i}
101
+ ${d}`)}return i},k=UA(t_);let r_=class extends K{list(e,t={},n){return this._client.getAPIList(k`/chat/completions/${e}/messages`,Me,{query:t,...n})}};const Ai=r=>(r==null?void 0:r.role)==="assistant",n_=r=>(r==null?void 0:r.role)==="tool";var Hl,Xa,Ya,ls,us,Qa,ds,ur,hs,Ii,Ri,_n,s_;class Yu{constructor(){Hl.add(this),this.controller=new AbortController,Xa.set(this,void 0),Ya.set(this,()=>{}),ls.set(this,()=>{}),us.set(this,void 0),Qa.set(this,()=>{}),ds.set(this,()=>{}),ur.set(this,{}),hs.set(this,!1),Ii.set(this,!1),Ri.set(this,!1),_n.set(this,!1),te(this,Xa,new Promise((e,t)=>{te(this,Ya,e,"f"),te(this,ls,t,"f")})),te(this,us,new Promise((e,t)=>{te(this,Qa,e,"f"),te(this,ds,t,"f")})),I(this,Xa,"f").catch(()=>{}),I(this,us,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},I(this,Hl,"m",s_).bind(this))},0)}_connected(){this.ended||(I(this,Ya,"f").call(this),this._emit("connect"))}get ended(){return I(this,hs,"f")}get errored(){return I(this,Ii,"f")}get aborted(){return I(this,Ri,"f")}abort(){this.controller.abort()}on(e,t){return(I(this,ur,"f")[e]||(I(this,ur,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=I(this,ur,"f")[e];if(!n)return this;const s=n.findIndex(a=>a.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(I(this,ur,"f")[e]||(I(this,ur,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{te(this,_n,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){te(this,_n,!0),await I(this,us,"f")}_emit(e,...t){if(I(this,hs,"f"))return;e==="end"&&(te(this,hs,!0),I(this,Qa,"f").call(this));const n=I(this,ur,"f")[e];if(n&&(I(this,ur,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!I(this,_n,"f")&&!(n!=null&&n.length)&&Promise.reject(s),I(this,ls,"f").call(this,s),I(this,ds,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!I(this,_n,"f")&&!(n!=null&&n.length)&&Promise.reject(s),I(this,ls,"f").call(this,s),I(this,ds,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Xa=new WeakMap,Ya=new WeakMap,ls=new WeakMap,us=new WeakMap,Qa=new WeakMap,ds=new WeakMap,ur=new WeakMap,hs=new WeakMap,Ii=new WeakMap,Ri=new WeakMap,_n=new WeakMap,Hl=new WeakSet,s_=function(e){if(te(this,Ii,!0),e instanceof Error&&e.name==="AbortError"&&(e=new bt),e instanceof bt)return te(this,Ri,!0),this._emit("abort",e);if(e instanceof Y)return this._emit("error",e);if(e instanceof Error){const t=new Y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Y(String(e)))};function FA(r){return typeof r.parse=="function"}var et,Wl,Oi,Gl,Jl,Vl,a_,i_;const BA=10;class o_ extends Yu{constructor(){super(...arguments),et.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var n;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(n=e.choices[0])==null?void 0:n.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),n_(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Ai(e)&&e.tool_calls)for(const n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),I(this,et,"m",Wl).call(this)}async finalMessage(){return await this.done(),I(this,et,"m",Oi).call(this)}async finalFunctionToolCall(){return await this.done(),I(this,et,"m",Gl).call(this)}async finalFunctionToolCallResult(){return await this.done(),I(this,et,"m",Jl).call(this)}async totalUsage(){return await this.done(),I(this,et,"m",Vl).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=I(this,et,"m",Oi).call(this);t&&this._emit("finalMessage",t);const n=I(this,et,"m",Wl).call(this);n&&this._emit("finalContent",n);const s=I(this,et,"m",Gl).call(this);s&&this._emit("finalFunctionToolCall",s);const a=I(this,et,"m",Jl).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",I(this,et,"m",Vl).call(this))}async _createChatCompletion(e,t,n){const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),I(this,et,"m",a_).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Vu(a,t))}async _runChatCompletion(e,t,n){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){var f,p,g;const s="tool",{tool_choice:a="auto",stream:i,...o}=t,c=typeof a!="string"&&a.type==="function"&&((f=a==null?void 0:a.function)==null?void 0:f.name),{maxChatCompletions:l=BA}=n||{},u=t.tools.map(_=>{if(Xs(_)){if(!_.$callback)throw new Y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:_.$callback,name:_.function.name,description:_.function.description||"",parameters:_.function.parameters,parse:_.$parseRaw,strict:!0}}}return _}),d={};for(const _ of u)_.type==="function"&&(d[_.function.name||_.function.function.name]=_.function);const h="tools"in t?u.map(_=>_.type==="function"?{type:"function",function:{name:_.function.name||_.function.function.name,parameters:_.function.parameters,description:_.function.description,strict:_.function.strict}}:_):void 0;for(const _ of t.messages)this._addMessage(_,!1);for(let _=0;_<l;++_){const m=(p=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:h,messages:[...this.messages]},n)).choices[0])==null?void 0:p.message;if(!m)throw new Y("missing message in ChatCompletion response");if(!((g=m.tool_calls)!=null&&g.length))return;for(const y of m.tool_calls){if(y.type!=="function")continue;const T=y.id,{name:x,arguments:R}=y.function,$=d[x];if($){if(c&&c!==x){const H=`Invalid tool_call: ${JSON.stringify(x)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:T,content:H});continue}}else{const H=`Invalid tool_call: ${JSON.stringify(x)}. Available options are: ${Object.keys(d).map(Ae=>JSON.stringify(Ae)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:T,content:H});continue}let E;try{E=FA($)?await $.parse(R):R}catch(H){const Ae=H instanceof Error?H.message:String(H);this._addMessage({role:s,tool_call_id:T,content:Ae});continue}const J=await $.function(E,this),se=I(this,et,"m",i_).call(this,J);if(this._addMessage({role:s,tool_call_id:T,content:se}),c)return}}}}et=new WeakSet,Wl=function(){return I(this,et,"m",Oi).call(this).content??null},Oi=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Ai(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new Y("stream ended without producing a ChatCompletionMessage with role=assistant")},Gl=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const s=this.messages[n];if(Ai(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.filter(a=>a.type==="function").at(-1))==null?void 0:t.function}},Jl=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(n_(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>{var s;return n.role==="assistant"&&((s=n.tool_calls)==null?void 0:s.some(a=>a.type==="function"&&a.id===t.tool_call_id))}))return t.content}},Vl=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},a_=function(e){if(e.n!=null&&e.n>1)throw new Y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},i_=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Qu extends o_{static runTools(e,t,n){const s=new Qu,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}_addMessage(e,t=!0){super._addMessage(e,t),Ai(e)&&e.content&&this._emit("content",e.content)}}const c_=1,l_=2,u_=4,d_=8,h_=16,f_=32,p_=64,m_=128,g_=256,__=m_|g_,y_=h_|f_|__|p_,w_=c_|l_|y_,b_=u_|d_,qA=w_|b_,He={STR:c_,NUM:l_,ARR:u_,OBJ:d_,NULL:h_,BOOL:f_,NAN:p_,INFINITY:m_,MINUS_INFINITY:g_,INF:__,SPECIAL:y_,ATOM:w_,COLLECTION:b_,ALL:qA};class zA extends Error{}class HA extends Error{}function WA(r,e=He.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return GA(r.trim(),e)}const GA=(r,e)=>{const t=r.length;let n=0;const s=h=>{throw new zA(`${h} at position ${n}`)},a=h=>{throw new HA(`${h} at position ${n}`)},i=()=>(d(),n>=t&&s("Unexpected end of input"),r[n]==='"'?o():r[n]==="{"?c():r[n]==="["?l():r.substring(n,n+4)==="null"||He.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||He.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||He.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||He.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||He.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||He.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):u()),o=()=>{const h=n;let f=!1;for(n++;n<t&&(r[n]!=='"'||f&&r[n-1]==="\\");)f=r[n]==="\\"?!f:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(h,++n-Number(f)))}catch(p){a(String(p))}else if(He.STR&e)try{return JSON.parse(r.substring(h,n-Number(f))+'"')}catch{return JSON.parse(r.substring(h,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{n++,d();const h={};try{for(;r[n]!=="}";){if(d(),n>=t&&He.OBJ&e)return h;const f=o();d(),n++;try{const p=i();Object.defineProperty(h,f,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if(He.OBJ&e)return h;throw p}d(),r[n]===","&&n++}}catch{if(He.OBJ&e)return h;s("Expected '}' at end of object")}return n++,h},l=()=>{n++;const h=[];try{for(;r[n]!=="]";)h.push(i()),d(),r[n]===","&&n++}catch{if(He.ARR&e)return h;s("Expected ']' at end of array")}return n++,h},u=()=>{if(n===0){r==="-"&&He.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(f){if(He.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}a(String(f))}}const h=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(He.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(h,n))}catch{r.substring(h,n)==="-"&&He.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(h,r.lastIndexOf("e")))}catch(p){a(String(p))}}},d=()=>{for(;n<t&&`
102
+ \r `.includes(r[n]);)n++};return i()},Hf=r=>WA(r,He.ALL^He.NUM);var Ue,or,an,xr,Jc,va,Vc,Kc,Zc,Sa,Xc,Wf;class Ms extends o_{constructor(e){super(),Ue.add(this),or.set(this,void 0),an.set(this,void 0),xr.set(this,void 0),te(this,or,e),te(this,an,[])}get currentChatCompletionSnapshot(){return I(this,xr,"f")}static fromReadableStream(e){const t=new Ms(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new Ms(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){var i;super._createChatCompletion;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),I(this,Ue,"m",Jc).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const o of a)I(this,Ue,"m",Vc).call(this,o);if((i=a.controller.signal)!=null&&i.aborted)throw new bt;return this._addChatCompletion(I(this,Ue,"m",Sa).call(this))}async _fromReadableStream(e,t){var i;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),I(this,Ue,"m",Jc).call(this),this._connected();const s=Ls.fromReadableStream(e,this.controller);let a;for await(const o of s)a&&a!==o.id&&this._addChatCompletion(I(this,Ue,"m",Sa).call(this)),I(this,Ue,"m",Vc).call(this,o),a=o.id;if((i=s.controller.signal)!=null&&i.aborted)throw new bt;return this._addChatCompletion(I(this,Ue,"m",Sa).call(this))}[(or=new WeakMap,an=new WeakMap,xr=new WeakMap,Ue=new WeakSet,Jc=function(){this.ended||te(this,xr,void 0)},va=function(t){let n=I(this,an,"f")[t.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},I(this,an,"f")[t.index]=n,n)},Vc=function(t){var s,a,i,o,c,l,u,d,h,f,p,g,_,b,m;if(this.ended)return;const n=I(this,Ue,"m",Wf).call(this,t);this._emit("chunk",t,n);for(const y of t.choices){const T=n.choices[y.index];y.delta.content!=null&&((s=T.message)==null?void 0:s.role)==="assistant"&&((a=T.message)!=null&&a.content)&&(this._emit("content",y.delta.content,T.message.content),this._emit("content.delta",{delta:y.delta.content,snapshot:T.message.content,parsed:T.message.parsed})),y.delta.refusal!=null&&((i=T.message)==null?void 0:i.role)==="assistant"&&((o=T.message)!=null&&o.refusal)&&this._emit("refusal.delta",{delta:y.delta.refusal,snapshot:T.message.refusal}),((c=y.logprobs)==null?void 0:c.content)!=null&&((l=T.message)==null?void 0:l.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(u=y.logprobs)==null?void 0:u.content,snapshot:((d=T.logprobs)==null?void 0:d.content)??[]}),((h=y.logprobs)==null?void 0:h.refusal)!=null&&((f=T.message)==null?void 0:f.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(p=y.logprobs)==null?void 0:p.refusal,snapshot:((g=T.logprobs)==null?void 0:g.refusal)??[]});const x=I(this,Ue,"m",va).call(this,T);T.finish_reason&&(I(this,Ue,"m",Zc).call(this,T),x.current_tool_call_index!=null&&I(this,Ue,"m",Kc).call(this,T,x.current_tool_call_index));for(const R of y.delta.tool_calls??[])x.current_tool_call_index!==R.index&&(I(this,Ue,"m",Zc).call(this,T),x.current_tool_call_index!=null&&I(this,Ue,"m",Kc).call(this,T,x.current_tool_call_index)),x.current_tool_call_index=R.index;for(const R of y.delta.tool_calls??[]){const $=(_=T.message.tool_calls)==null?void 0:_[R.index];$!=null&&$.type&&(($==null?void 0:$.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(b=$.function)==null?void 0:b.name,index:R.index,arguments:$.function.arguments,parsed_arguments:$.function.parsed_arguments,arguments_delta:((m=R.function)==null?void 0:m.arguments)??""}):($==null||$.type,void 0))}}},Kc=function(t,n){var i,o,c;if(I(this,Ue,"m",va).call(this,t).done_tool_calls.has(n))return;const a=(i=t.message.tool_calls)==null?void 0:i[n];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 l=(c=(o=I(this,or,"f"))==null?void 0:o.tools)==null?void 0:c.find(u=>Si(u)&&u.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:Xs(l)?l.$parseRaw(a.function.arguments):l!=null&&l.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Zc=function(t){var s,a;const n=I(this,Ue,"m",va).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=I(this,Ue,"m",Xc).call(this);this._emit("content.done",{content:t.message.content,parsed:i?i.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),(s=t.logprobs)!=null&&s.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),(a=t.logprobs)!=null&&a.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Sa=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");const t=I(this,xr,"f");if(!t)throw new Y("request ended without sending any chunks");return te(this,xr,void 0),te(this,an,[]),JA(t,I(this,or,"f"))},Xc=function(){var n;const t=(n=I(this,or,"f"))==null?void 0:n.response_format;return Ju(t)?t:null},Wf=function(t){var n,s,a,i;let o=I(this,xr,"f");const{choices:c,...l}=t;o?Object.assign(o,l):o=te(this,xr,{...l,choices:[]});for(const{delta:u,finish_reason:d,index:h,logprobs:f=null,...p}of t.choices){let g=o.choices[h];if(g||(g=o.choices[h]={finish_reason:d,index:h,message:{},logprobs:f,...p}),f)if(!g.logprobs)g.logprobs=Object.assign({},f);else{const{content:R,refusal:$,...E}=f;Object.assign(g.logprobs,E),R&&((n=g.logprobs).content??(n.content=[]),g.logprobs.content.push(...R)),$&&((s=g.logprobs).refusal??(s.refusal=[]),g.logprobs.refusal.push(...$))}if(d&&(g.finish_reason=d,I(this,or,"f")&&$g(I(this,or,"f")))){if(d==="length")throw new Rg;if(d==="content_filter")throw new Og}if(Object.assign(g,p),!u)continue;const{content:_,refusal:b,function_call:m,role:y,tool_calls:T,...x}=u;if(Object.assign(g.message,x),b&&(g.message.refusal=(g.message.refusal||"")+b),y&&(g.message.role=y),m&&(g.message.function_call?(m.name&&(g.message.function_call.name=m.name),m.arguments&&((a=g.message.function_call).arguments??(a.arguments=""),g.message.function_call.arguments+=m.arguments)):g.message.function_call=m),_&&(g.message.content=(g.message.content||"")+_,!g.message.refusal&&I(this,Ue,"m",Xc).call(this)&&(g.message.parsed=Hf(g.message.content))),T){g.message.tool_calls||(g.message.tool_calls=[]);for(const{index:R,id:$,type:E,function:J,...se}of T){const H=(i=g.message.tool_calls)[R]??(i[R]={});Object.assign(H,se),$&&(H.id=$),E&&(H.type=E),J&&(H.function??(H.function={name:J.name??"",arguments:""})),J!=null&&J.name&&(H.function.name=J.name),J!=null&&J.arguments&&(H.function.arguments+=J.arguments,sx(I(this,or,"f"),H)&&(H.function.parsed_arguments=Hf(H.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ls(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function JA(r,e){const{id:t,choices:n,created:s,model:a,system_fingerprint:i,...o}=r,c={...o,id:t,choices:n.map(({message:l,finish_reason:u,index:d,logprobs:h,...f})=>{if(!u)throw new Y(`missing finish_reason for choice ${d}`);const{content:p=null,function_call:g,tool_calls:_,...b}=l,m=l.role;if(!m)throw new Y(`missing role for choice ${d}`);if(g){const{arguments:y,name:T}=g;if(y==null)throw new Y(`missing function_call.arguments for choice ${d}`);if(!T)throw new Y(`missing function_call.name for choice ${d}`);return{...f,message:{content:p,function_call:{arguments:y,name:T},role:m,refusal:l.refusal??null},finish_reason:u,index:d,logprobs:h}}return _?{...f,index:d,finish_reason:u,logprobs:h,message:{...b,role:m,content:p,refusal:l.refusal??null,tool_calls:_.map((y,T)=>{const{function:x,type:R,id:$,...E}=y,{arguments:J,name:se,...H}=x||{};if($==null)throw new Y(`missing choices[${d}].tool_calls[${T}].id
103
+ ${Ea(r)}`);if(R==null)throw new Y(`missing choices[${d}].tool_calls[${T}].type
104
+ ${Ea(r)}`);if(se==null)throw new Y(`missing choices[${d}].tool_calls[${T}].function.name
105
+ ${Ea(r)}`);if(J==null)throw new Y(`missing choices[${d}].tool_calls[${T}].function.arguments
106
+ ${Ea(r)}`);return{...E,id:$,type:R,function:{...H,name:se,arguments:J}}})}}:{...f,message:{...b,content:p,role:m,refusal:l.refusal??null},finish_reason:u,index:d,logprobs:h}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return tx(c,e)}function Ea(r){return JSON.stringify(r)}class $i extends Ms{static fromReadableStream(e){const t=new $i(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){const s=new $i(t),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}}let ed=class extends K{constructor(){super(...arguments),this.messages=new r_(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(k`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(k`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",Me,{query:e,...t})}delete(e,t){return this._client.delete(k`/chat/completions/${e}`,t)}parse(e,t){return ax(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t==null?void 0:t.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Vu(n,e))}runTools(e,t){return e.stream?$i.runTools(this._client,e,t):Qu.runTools(this._client,e,t)}stream(e,t){return Ms.createChatCompletion(this._client,e,t)}};ed.Messages=r_;class td extends K{constructor(){super(...arguments),this.completions=new ed(this._client)}}td.Completions=ed;const v_=Symbol("brand.privateNullableHeaders");function*VA(r){if(!r)return;if(v_ in r){const{values:n,nulls:s}=r;yield*n.entries();for(const a of s)yield[a,null];return}let e=!1,t;r instanceof Headers?t=r.entries():Of(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){const s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const a=Of(n[1])?n[1]:[n[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,o])}}const F=r=>{const e=new Headers,t=new Set;for(const n of r){const s=new Set;for(const[a,i]of VA(n)){const o=a.toLowerCase();s.has(o)||(e.delete(a),s.add(o)),i===null?(e.delete(a),t.add(o)):(e.append(a,i),t.delete(o))}}return{[v_]:!0,values:e,nulls:t}};class S_ extends K{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:F([{Accept:"application/octet-stream"},t==null?void 0:t.headers]),__binaryResponse:!0})}}class E_ extends K{create(e,t){return this._client.post("/audio/transcriptions",Yr({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class T_ extends K{create(e,t){return this._client.post("/audio/translations",Yr({body:e,...t,__metadata:{model:e.model}},this._client))}}class Qs extends K{constructor(){super(...arguments),this.transcriptions=new E_(this._client),this.translations=new T_(this._client),this.speech=new S_(this._client)}}Qs.Transcriptions=E_;Qs.Translations=T_;Qs.Speech=S_;let x_=class extends K{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(k`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",Me,{query:e,...t})}cancel(e,t){return this._client.post(k`/batches/${e}/cancel`,t)}};class A_ extends K{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(k`/assistants/${e}`,{...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,n){return this._client.post(k`/assistants/${e}`,{body:t,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e={},t){return this._client.getAPIList("/assistants",Me,{query:e,...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}delete(e,t){return this._client.delete(k`/assistants/${e}`,{...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}}let I_=class extends K{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}};class R_ extends K{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}}let oo=class extends K{constructor(){super(...arguments),this.sessions=new I_(this._client),this.transcriptionSessions=new R_(this._client)}};oo.Sessions=I_;oo.TranscriptionSessions=R_;class O_ extends K{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:F([{"OpenAI-Beta":"chatkit_beta=v1"},t==null?void 0:t.headers])})}cancel(e,t){return this._client.post(k`/chatkit/sessions/${e}/cancel`,{...t,headers:F([{"OpenAI-Beta":"chatkit_beta=v1"},t==null?void 0:t.headers])})}}let $_=class extends K{retrieve(e,t){return this._client.get(k`/chatkit/threads/${e}`,{...t,headers:F([{"OpenAI-Beta":"chatkit_beta=v1"},t==null?void 0:t.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",xi,{query:e,...t,headers:F([{"OpenAI-Beta":"chatkit_beta=v1"},t==null?void 0:t.headers])})}delete(e,t){return this._client.delete(k`/chatkit/threads/${e}`,{...t,headers:F([{"OpenAI-Beta":"chatkit_beta=v1"},t==null?void 0:t.headers])})}listItems(e,t={},n){return this._client.getAPIList(k`/chatkit/threads/${e}/items`,xi,{query:t,...n,headers:F([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers])})}};class co extends K{constructor(){super(...arguments),this.sessions=new O_(this._client),this.threads=new $_(this._client)}}co.Sessions=O_;co.Threads=$_;let C_=class extends K{create(e,t,n){return this._client.post(k`/threads/${e}/messages`,{body:t,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,t,n){const{thread_id:s}=t;return this._client.get(k`/threads/${s}/messages/${e}`,{...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,t,n){const{thread_id:s,...a}=t;return this._client.post(k`/threads/${s}/messages/${e}`,{body:a,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t={},n){return this._client.getAPIList(k`/threads/${e}/messages`,Me,{query:t,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,t,n){const{thread_id:s}=t;return this._client.delete(k`/threads/${s}/messages/${e}`,{...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}};class k_ extends K{retrieve(e,t,n){const{thread_id:s,run_id:a,...i}=t;return this._client.get(k`/threads/${s}/runs/${a}/steps/${e}`,{query:i,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t,n){const{thread_id:s,...a}=t;return this._client.getAPIList(k`/threads/${s}/runs/${e}/steps`,Me,{query:a,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}const KA=r=>{if(typeof Buffer<"u"){const e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};var Yc={};const on=r=>{var e,t,n,s;if(typeof globalThis.process<"u")return((e=Yc==null?void 0:Yc[r])==null?void 0:e.trim())??void 0;if(typeof globalThis.Deno<"u")return(s=(n=(t=globalThis.Deno.env)==null?void 0:t.get)==null?void 0:n.call(t,r))==null?void 0:s.trim()};var Ke,Hr,Kl,rr,ei,jt,Wr,xn,zr,Ci,wt,ti,ri,xs,fs,ps,Gf,Jf,Vf,Kf,Zf,Xf,Yf;class As extends Yu{constructor(){super(...arguments),Ke.add(this),Kl.set(this,[]),rr.set(this,{}),ei.set(this,{}),jt.set(this,void 0),Wr.set(this,void 0),xn.set(this,void 0),zr.set(this,void 0),Ci.set(this,void 0),wt.set(this,void 0),ti.set(this,void 0),ri.set(this,void 0),xs.set(this,void 0)}[(Kl=new WeakMap,rr=new WeakMap,ei=new WeakMap,jt=new WeakMap,Wr=new WeakMap,xn=new WeakMap,zr=new WeakMap,Ci=new WeakMap,wt=new WeakMap,ti=new WeakMap,ri=new WeakMap,xs=new WeakMap,Ke=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Hr;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var a;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=Ls.fromReadableStream(e,this.controller);for await(const i of s)I(this,Ke,"m",fs).call(this,i);if((a=s.controller.signal)!=null&&a.aborted)throw new bt;return this._addRun(I(this,Ke,"m",ps).call(this))}toReadableStream(){return new Ls(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s){const a=new Hr;return a._run(()=>a._runToolAssistantStream(e,t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,s){var c;const a=s==null?void 0:s.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},o=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(const l of o)I(this,Ke,"m",fs).call(this,l);if((c=o.controller.signal)!=null&&c.aborted)throw new bt;return this._addRun(I(this,Ke,"m",ps).call(this))}static createThreadAssistantStream(e,t,n){const s=new Hr;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){const a=new Hr;return a._run(()=>a._runAssistantStream(e,t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return I(this,ti,"f")}currentRun(){return I(this,ri,"f")}currentMessageSnapshot(){return I(this,jt,"f")}currentRunStepSnapshot(){return I(this,xs,"f")}async finalRunSteps(){return await this.done(),Object.values(I(this,rr,"f"))}async finalMessages(){return await this.done(),Object.values(I(this,ei,"f"))}async finalRun(){if(await this.done(),!I(this,Wr,"f"))throw Error("Final run was not received.");return I(this,Wr,"f")}async _createThreadAssistantStream(e,t,n){var o;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const a={...t,stream:!0},i=await e.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(const c of i)I(this,Ke,"m",fs).call(this,c);if((o=i.controller.signal)!=null&&o.aborted)throw new bt;return this._addRun(I(this,Ke,"m",ps).call(this))}async _createAssistantStream(e,t,n,s){var c;const a=s==null?void 0:s.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},o=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(const l of o)I(this,Ke,"m",fs).call(this,l);if((c=o.controller.signal)!=null&&c.aborted)throw new bt;return this._addRun(I(this,Ke,"m",ps).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let a=e[n];if(a==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof a=="string"&&typeof s=="string")a+=s;else if(typeof a=="number"&&typeof s=="number")a+=s;else if(Hc(a)&&Hc(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(!Hc(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: ${n}, deltaValue: ${s}, accValue: ${a}`);e[n]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s){return await this._createToolAssistantStream(t,e,n,s)}}Hr=As,fs=function(e){if(!this.ended)switch(te(this,ti,e),I(this,Ke,"m",Vf).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":I(this,Ke,"m",Yf).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":I(this,Ke,"m",Jf).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":I(this,Ke,"m",Gf).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},ps=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");if(!I(this,Wr,"f"))throw Error("Final run has not been received");return I(this,Wr,"f")},Gf=function(e){const[t,n]=I(this,Ke,"m",Zf).call(this,e,I(this,jt,"f"));te(this,jt,t),I(this,ei,"f")[t.id]=t;for(const s of n){const a=t.content[s.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let a=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=I(this,xn,"f")){if(I(this,zr,"f"))switch(I(this,zr,"f").type){case"text":this._emit("textDone",I(this,zr,"f").text,I(this,jt,"f"));break;case"image_file":this._emit("imageFileDone",I(this,zr,"f").image_file,I(this,jt,"f"));break}te(this,xn,s.index)}te(this,zr,t.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(I(this,xn,"f")!==void 0){const s=e.data.content[I(this,xn,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,I(this,jt,"f"));break;case"text":this._emit("textDone",s.text,I(this,jt,"f"));break}}I(this,jt,"f")&&this._emit("messageDone",e.data),te(this,jt,void 0)}},Jf=function(e){const t=I(this,Ke,"m",Kf).call(this,e);switch(te(this,xs,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const a of n.step_details.tool_calls)a.index==I(this,Ci,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(I(this,wt,"f")&&this._emit("toolCallDone",I(this,wt,"f")),te(this,Ci,a.index),te(this,wt,t.step_details.tool_calls[a.index]),I(this,wt,"f")&&this._emit("toolCallCreated",I(this,wt,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":te(this,xs,void 0),e.data.step_details.type=="tool_calls"&&I(this,wt,"f")&&(this._emit("toolCallDone",I(this,wt,"f")),te(this,wt,void 0)),this._emit("runStepDone",e.data,t);break}},Vf=function(e){I(this,Kl,"f").push(e),this._emit("event",e)},Kf=function(e){switch(e.event){case"thread.run.step.created":return I(this,rr,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=I(this,rr,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const s=Hr.accumulateDelta(t,n.delta);I(this,rr,"f")[e.data.id]=s}return I(this,rr,"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":I(this,rr,"f")[e.data.id]=e.data;break}if(I(this,rr,"f")[e.data.id])return I(this,rr,"f")[e.data.id];throw new Error("No snapshot available")},Zf=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const a of s.delta.content)if(a.index in t.content){let i=t.content[a.index];t.content[a.index]=I(this,Ke,"m",Xf).call(this,a,i)}else t.content[a.index]=a,n.push(a);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Xf=function(e,t){return Hr.accumulateDelta(t,e)},Yf=function(e){switch(te(this,ri,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":te(this,Wr,e.data),I(this,wt,"f")&&(this._emit("toolCallDone",I(this,wt,"f")),te(this,wt,void 0));break}};let rd=class extends K{constructor(){super(...arguments),this.steps=new k_(this._client)}create(e,t,n){const{include:s,...a}=t;return this._client.post(k`/threads/${e}/runs`,{query:{include:s},body:a,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:t.stream??!1})}retrieve(e,t,n){const{thread_id:s}=t;return this._client.get(k`/threads/${s}/runs/${e}`,{...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,t,n){const{thread_id:s,...a}=t;return this._client.post(k`/threads/${s}/runs/${e}`,{body:a,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t={},n){return this._client.getAPIList(k`/threads/${e}/runs`,Me,{query:t,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(e,t,n){const{thread_id:s}=t;return this._client.post(k`/threads/${s}/runs/${e}/cancel`,{...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,t,n){return As.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){var a;const s=F([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:o}=await this.retrieve(e,t,{...n,headers:{...n==null?void 0:n.headers,...s}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const l=o.headers.get("openai-poll-after-ms");if(l){const u=parseInt(l);isNaN(u)||(c=u)}}await Ys(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,n){return As.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){const{thread_id:s,...a}=t;return this._client.post(k`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:a,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){const s=await this.submitToolOutputs(e,t,n);return await this.poll(s.id,t,n)}submitToolOutputsStream(e,t,n){return As.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};rd.Steps=k_;class lo extends K{constructor(){super(...arguments),this.runs=new rd(this._client),this.messages=new C_(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(k`/threads/${e}`,{...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,n){return this._client.post(k`/threads/${e}`,{body:t,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,t){return this._client.delete(k`/threads/${e}`,{...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return As.createThreadAssistantStream(e,this._client.beta.threads,t)}}lo.Runs=rd;lo.Messages=C_;let jn=class extends K{constructor(){super(...arguments),this.realtime=new oo(this._client),this.chatkit=new co(this._client),this.assistants=new A_(this._client),this.threads=new lo(this._client)}};jn.Realtime=oo;jn.ChatKit=co;jn.Assistants=A_;jn.Threads=lo;let P_=class extends K{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};class N_ extends K{retrieve(e,t,n){const{container_id:s}=t;return this._client.get(k`/containers/${s}/files/${e}/content`,{...n,headers:F([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}}let nd=class extends K{constructor(){super(...arguments),this.content=new N_(this._client)}create(e,t,n){return this._client.post(k`/containers/${e}/files`,Yr({body:t,...n},this._client))}retrieve(e,t,n){const{container_id:s}=t;return this._client.get(k`/containers/${s}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(k`/containers/${e}/files`,Me,{query:t,...n})}delete(e,t,n){const{container_id:s}=t;return this._client.delete(k`/containers/${s}/files/${e}`,{...n,headers:F([{Accept:"*/*"},n==null?void 0:n.headers])})}};nd.Content=N_;class sd extends K{constructor(){super(...arguments),this.files=new nd(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(k`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",Me,{query:e,...t})}delete(e,t){return this._client.delete(k`/containers/${e}`,{...t,headers:F([{Accept:"*/*"},t==null?void 0:t.headers])})}}sd.Files=nd;class L_ extends K{create(e,t,n){const{include:s,...a}=t;return this._client.post(k`/conversations/${e}/items`,{query:{include:s},body:a,...n})}retrieve(e,t,n){const{conversation_id:s,...a}=t;return this._client.get(k`/conversations/${s}/items/${e}`,{query:a,...n})}list(e,t={},n){return this._client.getAPIList(k`/conversations/${e}/items`,xi,{query:t,...n})}delete(e,t,n){const{conversation_id:s}=t;return this._client.delete(k`/conversations/${s}/items/${e}`,n)}}class ad extends K{constructor(){super(...arguments),this.items=new L_(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(k`/conversations/${e}`,t)}update(e,t,n){return this._client.post(k`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(k`/conversations/${e}`,t)}}ad.Items=L_;let M_=class extends K{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&Ve(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?a:(Ve(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{const c=o.embedding;o.embedding=KA(c)}),i)))}};class j_ extends K{retrieve(e,t,n){const{eval_id:s,run_id:a}=t;return this._client.get(k`/evals/${s}/runs/${a}/output_items/${e}`,n)}list(e,t,n){const{eval_id:s,...a}=t;return this._client.getAPIList(k`/evals/${s}/runs/${e}/output_items`,Me,{query:a,...n})}}class id extends K{constructor(){super(...arguments),this.outputItems=new j_(this._client)}create(e,t,n){return this._client.post(k`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){const{eval_id:s}=t;return this._client.get(k`/evals/${s}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(k`/evals/${e}/runs`,Me,{query:t,...n})}delete(e,t,n){const{eval_id:s}=t;return this._client.delete(k`/evals/${s}/runs/${e}`,n)}cancel(e,t,n){const{eval_id:s}=t;return this._client.post(k`/evals/${s}/runs/${e}`,n)}}id.OutputItems=j_;class od extends K{constructor(){super(...arguments),this.runs=new id(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(k`/evals/${e}`,t)}update(e,t,n){return this._client.post(k`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",Me,{query:e,...t})}delete(e,t){return this._client.delete(k`/evals/${e}`,t)}}od.Runs=id;let D_=class extends K{create(e,t){return this._client.post("/files",Yr({body:e,...t},this._client))}retrieve(e,t){return this._client.get(k`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",Me,{query:e,...t})}delete(e,t){return this._client.delete(k`/files/${e}`,t)}content(e,t){return this._client.get(k`/files/${e}/content`,{...t,headers:F([{Accept:"application/binary"},t==null?void 0:t.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=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 Ys(t),i=await this.retrieve(e),Date.now()-a>n)throw new so({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class U_ extends K{}let F_=class extends K{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class cd extends K{constructor(){super(...arguments),this.graders=new F_(this._client)}}cd.Graders=F_;class B_ extends K{create(e,t,n){return this._client.getAPIList(k`/fine_tuning/checkpoints/${e}/permissions`,io,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(k`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){const{fine_tuned_model_checkpoint:s}=t;return this._client.delete(k`/fine_tuning/checkpoints/${s}/permissions/${e}`,n)}}let ld=class extends K{constructor(){super(...arguments),this.permissions=new B_(this._client)}};ld.Permissions=B_;class q_ extends K{list(e,t={},n){return this._client.getAPIList(k`/fine_tuning/jobs/${e}/checkpoints`,Me,{query:t,...n})}}class ud extends K{constructor(){super(...arguments),this.checkpoints=new q_(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(k`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",Me,{query:e,...t})}cancel(e,t){return this._client.post(k`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(k`/fine_tuning/jobs/${e}/events`,Me,{query:t,...n})}pause(e,t){return this._client.post(k`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(k`/fine_tuning/jobs/${e}/resume`,t)}}ud.Checkpoints=q_;class Dn extends K{constructor(){super(...arguments),this.methods=new U_(this._client),this.jobs=new ud(this._client),this.checkpoints=new ld(this._client),this.alpha=new cd(this._client)}}Dn.Methods=U_;Dn.Jobs=ud;Dn.Checkpoints=ld;Dn.Alpha=cd;class z_ extends K{}class dd extends K{constructor(){super(...arguments),this.graderModels=new z_(this._client)}}dd.GraderModels=z_;class H_ extends K{createVariation(e,t){return this._client.post("/images/variations",Yr({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",Yr({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}let W_=class extends K{retrieve(e,t){return this._client.get(k`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",io,e)}delete(e,t){return this._client.delete(k`/models/${e}`,t)}};class G_ extends K{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class J_ extends K{accept(e,t,n){return this._client.post(k`/realtime/calls/${e}/accept`,{body:t,...n,headers:F([{Accept:"*/*"},n==null?void 0:n.headers])})}hangup(e,t){return this._client.post(k`/realtime/calls/${e}/hangup`,{...t,headers:F([{Accept:"*/*"},t==null?void 0:t.headers])})}refer(e,t,n){return this._client.post(k`/realtime/calls/${e}/refer`,{body:t,...n,headers:F([{Accept:"*/*"},n==null?void 0:n.headers])})}reject(e,t={},n){return this._client.post(k`/realtime/calls/${e}/reject`,{body:t,...n,headers:F([{Accept:"*/*"},n==null?void 0:n.headers])})}}class V_ extends K{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class uo extends K{constructor(){super(...arguments),this.clientSecrets=new V_(this._client),this.calls=new J_(this._client)}}uo.ClientSecrets=V_;uo.Calls=J_;var cn,Ta,Ar,xa,Qf,ep,tp,rp;class hd extends Yu{constructor(e){super(),cn.add(this),Ta.set(this,void 0),Ar.set(this,void 0),xa.set(this,void 0),te(this,Ta,e)}static createResponse(e,t,n){const s=new hd(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,n){var o;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),I(this,cn,"m",Qf).call(this);let a,i=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const c of a)I(this,cn,"m",ep).call(this,c,i);if((o=a.controller.signal)!=null&&o.aborted)throw new bt;return I(this,cn,"m",tp).call(this)}[(Ta=new WeakMap,Ar=new WeakMap,xa=new WeakMap,cn=new WeakSet,Qf=function(){this.ended||te(this,Ar,void 0)},ep=function(t,n){if(this.ended)return;const s=(i,o)=>{(n==null||o.sequence_number>n)&&this._emit(i,o)},a=I(this,cn,"m",rp).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const i=a.output[t.output_index];if(!i)throw new Y(`missing output at index ${t.output_index}`);if(i.type==="message"){const o=i.content[t.content_index];if(!o)throw new Y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new Y(`expected content to be 'output_text', got ${o.type}`);s("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const i=a.output[t.output_index];if(!i)throw new Y(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},tp=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");const t=I(this,Ar,"f");if(!t)throw new Y("request ended without sending any events");te(this,Ar,void 0);const n=ZA(t,I(this,Ta,"f"));return te(this,xa,n),n},rp=function(t){var s;let n=I(this,Ar,"f");if(!n){if(t.type!=="response.created")throw new Y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=te(this,Ar,t.response),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{const a=n.output[t.output_index];if(!a)throw new Y(`missing output at index ${t.output_index}`);const i=a.type,o=t.part;i==="message"&&o.type!=="reasoning_text"?a.content.push(o):i==="reasoning"&&o.type==="reasoning_text"&&(a.content||(a.content=[]),a.content.push(o));break}case"response.output_text.delta":{const a=n.output[t.output_index];if(!a)throw new Y(`missing output at index ${t.output_index}`);if(a.type==="message"){const i=a.content[t.content_index];if(!i)throw new Y(`missing content at index ${t.content_index}`);if(i.type!=="output_text")throw new Y(`expected content to be 'output_text', got ${i.type}`);i.text+=t.delta}break}case"response.function_call_arguments.delta":{const a=n.output[t.output_index];if(!a)throw new Y(`missing output at index ${t.output_index}`);a.type==="function_call"&&(a.arguments+=t.delta);break}case"response.reasoning_text.delta":{const a=n.output[t.output_index];if(!a)throw new Y(`missing output at index ${t.output_index}`);if(a.type==="reasoning"){const i=(s=a.content)==null?void 0:s[t.content_index];if(!i)throw new Y(`missing content at index ${t.content_index}`);if(i.type!=="reasoning_text")throw new Y(`expected content to be 'reasoning_text', got ${i.type}`);i.text+=t.delta}break}case"response.completed":{te(this,Ar,t.response);break}}return n},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=I(this,xa,"f");if(!e)throw new Y("stream ended without producing a ChatCompletion");return e}}function ZA(r,e){return Gx(r,e)}class K_ extends K{list(e,t={},n){return this._client.getAPIList(k`/responses/${e}/input_items`,Me,{query:t,...n})}}class Z_ extends K{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class ho extends K{constructor(){super(...arguments),this.inputItems=new K_(this._client),this.inputTokens=new Z_(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Ul(n),n))}retrieve(e,t={},n){return this._client.get(k`/responses/${e}`,{query:t,...n,stream:(t==null?void 0:t.stream)??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Ul(s),s))}delete(e,t){return this._client.delete(k`/responses/${e}`,{...t,headers:F([{Accept:"*/*"},t==null?void 0:t.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>Mg(n,e))}stream(e,t){return hd.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(k`/responses/${e}/cancel`,t)}}ho.InputItems=K_;ho.InputTokens=Z_;class X_ extends K{create(e,t,n){return this._client.post(k`/uploads/${e}/parts`,Yr({body:t,...n},this._client))}}class fd extends K{constructor(){super(...arguments),this.parts=new X_(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(k`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(k`/uploads/${e}/complete`,{body:t,...n})}}fd.Parts=X_;const XA=async r=>{const e=await Promise.allSettled(r),t=e.filter(s=>s.status==="rejected");if(t.length){for(const s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const n=[];for(const s of e)s.status==="fulfilled"&&n.push(s.value);return n};class Y_ extends K{create(e,t,n){return this._client.post(k`/vector_stores/${e}/file_batches`,{body:t,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,t,n){const{vector_store_id:s}=t;return this._client.get(k`/vector_stores/${s}/file_batches/${e}`,{...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(e,t,n){const{vector_store_id:s}=t;return this._client.post(k`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n){const{vector_store_id:s,...a}=t;return this._client.getAPIList(k`/vector_stores/${s}/file_batches/${e}/files`,Me,{query:a,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async poll(e,t,n){var a;const s=F([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:o}=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse();switch(i.status){case"in_progress":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const l=o.headers.get("openai-poll-after-ms");if(l){const u=parseInt(l);isNaN(u)||(c=u)}}await Ys(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=(s==null?void 0:s.maxConcurrency)??5,i=Math.min(a,t.length),o=this._client,c=t.values(),l=[...n];async function u(h){for(let f of h){const p=await o.files.create({file:f,purpose:"assistants"},s);l.push(p.id)}}const d=Array(i).fill(c).map(u);return await XA(d),await this.createAndPoll(e,{file_ids:l})}}let Q_=class extends K{create(e,t,n){return this._client.post(k`/vector_stores/${e}/files`,{body:t,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,t,n){const{vector_store_id:s}=t;return this._client.get(k`/vector_stores/${s}/files/${e}`,{...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,t,n){const{vector_store_id:s,...a}=t;return this._client.post(k`/vector_stores/${s}/files/${e}`,{body:a,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t={},n){return this._client.getAPIList(k`/vector_stores/${e}/files`,Me,{query:t,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,t,n){const{vector_store_id:s}=t;return this._client.delete(k`/vector_stores/${s}/files/${e}`,{...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){var a;const s=F([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const i=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse(),o=i.data;switch(o.status){case"in_progress":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const l=i.response.headers.get("openai-poll-after-ms");if(l){const u=parseInt(l);isNaN(u)||(c=u)}}await Ys(c);break;case"failed":case"completed":return o}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){const{vector_store_id:s}=t;return this._client.getAPIList(k`/vector_stores/${s}/files/${e}/content`,io,{...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}};class fo extends K{constructor(){super(...arguments),this.files=new Q_(this._client),this.fileBatches=new Y_(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(k`/vector_stores/${e}`,{...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,n){return this._client.post(k`/vector_stores/${e}`,{body:t,...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",Me,{query:e,...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}delete(e,t){return this._client.delete(k`/vector_stores/${e}`,{...t,headers:F([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}search(e,t,n){return this._client.getAPIList(k`/vector_stores/${e}/search`,io,{body:t,method:"post",...n,headers:F([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}fo.Files=Q_;fo.FileBatches=Y_;class ey extends K{create(e,t){return this._client.post("/videos",Bf({body:e,...t},this._client))}retrieve(e,t){return this._client.get(k`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",xi,{query:e,...t})}delete(e,t){return this._client.delete(k`/videos/${e}`,t)}downloadContent(e,t={},n){return this._client.get(k`/videos/${e}/content`,{query:t,...n,headers:F([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}remix(e,t,n){return this._client.post(k`/videos/${e}/remix`,Bf({body:t,...n},this._client))}}var yn,ty,ni;class ry extends K{constructor(){super(...arguments),yn.add(this)}async unwrap(e,t,n=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,n,s),JSON.parse(e)}async verifySignature(e,t,n=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");I(this,yn,"m",ty).call(this,n);const a=F([t]).values,i=I(this,yn,"m",ni).call(this,a,"webhook-signature"),o=I(this,yn,"m",ni).call(this,a,"webhook-timestamp"),c=I(this,yn,"m",ni).call(this,a,"webhook-id"),l=parseInt(o,10);if(isNaN(l))throw new as("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-l>s)throw new as("Webhook timestamp is too old");if(l>u+s)throw new as("Webhook timestamp is too new");const d=i.split(" ").map(g=>g.startsWith("v1,")?g.substring(3):g),h=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),f=c?`${c}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey("raw",h,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const g of d)try{const _=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",p,_,new TextEncoder().encode(f)))return}catch{continue}throw new as("The given webhook signature does not match the expected signature")}}yn=new WeakSet,ty=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")},ni=function(e,t){if(!e)throw new Error("Headers are required");const n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};var Zl,pd,si,ny;class he{constructor({baseURL:e=on("OPENAI_BASE_URL"),apiKey:t=on("OPENAI_API_KEY"),organization:n=on("OPENAI_ORG_ID")??null,project:s=on("OPENAI_PROJECT_ID")??null,webhookSecret:a=on("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Zl.add(this),si.set(this,void 0),this.completions=new P_(this),this.chat=new td(this),this.embeddings=new M_(this),this.files=new D_(this),this.images=new H_(this),this.audio=new Qs(this),this.moderations=new G_(this),this.models=new W_(this),this.fineTuning=new Dn(this),this.graders=new dd(this),this.vectorStores=new fo(this),this.webhooks=new ry(this),this.beta=new jn(this),this.batches=new x_(this),this.uploads=new fd(this),this.responses=new ho(this),this.realtime=new uo(this),this.conversations=new ad(this),this.evals=new od(this),this.containers=new sd(this),this.videos=new ey(this),t===void 0)throw new Y("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const o={apiKey:t,organization:n,project:s,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&uA())throw new Y(`It looks like you're running in a browser-like environment.
107
+
108
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
109
+ If you understand the risks and have appropriate mitigations in place,
110
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
111
+
112
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
113
+
114
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
115
+ `);this.baseURL=o.baseURL,this.timeout=o.timeout??pd.DEFAULT_TIMEOUT,this.logger=o.logger??console;const c="warn";this.logLevel=c,this.logLevel=Uf(o.logLevel,"ClientOptions.logLevel",this)??Uf(on("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??mA(),te(this,si,_A),this._options=o,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=n,this.project=s,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return F([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return EA(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${gn}`}defaultIdempotencyKey(){return`stainless-node-retry-${jg()}`}makeStatusError(e,t,n,s){return ht.generate(e,t,n,s)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(n){throw n instanceof Y?n:new Y(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof t!="string"||!t)throw new Y(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){const s=!I(this,Zl,"m",ny).call(this)&&n||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)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new Kg(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){var b,m;const s=await e,a=s.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(s);const{req:i,url:o,timeout:c}=await this.buildRequest(s,{retryCount:a-t});await this.prepareRequest(i,{url:o,options:s});const l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Ve(this).debug(`[${l}] sending request`,Fr({retryOfRequestLogID:n,method:s.method,url:o,options:s,headers:i.headers})),(b=s.signal)!=null&&b.aborted)throw new bt;const h=new AbortController,f=await this.fetchWithTimeout(o,i,c,h).catch(Ml),p=Date.now();if(f instanceof globalThis.Error){const y=`retrying, ${t} attempts remaining`;if((m=s.signal)!=null&&m.aborted)throw new bt;const T=Ll(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return Ve(this).info(`[${l}] connection ${T?"timed out":"failed"} - ${y}`),Ve(this).debug(`[${l}] connection ${T?"timed out":"failed"} (${y})`,Fr({retryOfRequestLogID:n,url:o,durationMs:p-d,message:f.message})),this.retryRequest(s,t,n??l);throw Ve(this).info(`[${l}] connection ${T?"timed out":"failed"} - error; no more retries left`),Ve(this).debug(`[${l}] connection ${T?"timed out":"failed"} (error; no more retries left)`,Fr({retryOfRequestLogID:n,url:o,durationMs:p-d,message:f.message})),T?new so:new no({cause:f})}const g=[...f.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,T])=>", "+y+": "+JSON.stringify(T)).join(""),_=`[${l}${u}${g}] ${i.method} ${o} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${p-d}ms`;if(!f.ok){const y=await this.shouldRetry(f);if(t&&y){const J=`retrying, ${t} attempts remaining`;return await gA(f.body),Ve(this).info(`${_} - ${J}`),Ve(this).debug(`[${l}] response error (${J})`,Fr({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-d})),this.retryRequest(s,t,n??l,f.headers)}const T=y?"error; no more retries left":"error; not retryable";Ve(this).info(`${_} - ${T}`);const x=await f.text().catch(J=>Ml(J).message),R=lA(x),$=R?void 0:x;throw Ve(this).debug(`[${l}] response error (${T})`,Fr({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:$,durationMs:Date.now()-d})),this.makeStatusError(f.status,R,$,f.headers)}return Ve(this).info(_),Ve(this).debug(`[${l}] response start`,Fr({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-d})),{response:f,options:s,controller:h,requestLogID:l,retryOfRequestLogID:n,startTime:d}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new kA(this,n,e)}async fetchWithTimeout(e,t,n,s){const{signal:a,method:i,...o}=t||{};a&&a.addEventListener("abort",()=>s.abort());const c=setTimeout(()=>s.abort(),n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...o};i&&(u.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,s){let a;const i=s==null?void 0:s.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const o=s==null?void 0: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(t,c)}return await Ys(a),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}async buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:s,path:a,query:i,defaultBaseURL:o}=n,c=this.buildURL(a,i,o);"timeout"in n&&cA("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:l,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:s,bodyHeaders:l,retryCount:t});return{req:{method:s,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:s}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=F([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,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=F([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.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:Fg(e)}:I(this,si,"f").call(this,{body:e,headers:n})}}pd=he,si=new WeakMap,Zl=new WeakSet,ny=function(){return this.baseURL!=="https://api.openai.com/v1"};he.OpenAI=pd;he.DEFAULT_TIMEOUT=6e5;he.OpenAIError=Y;he.APIError=ht;he.APIConnectionError=no;he.APIConnectionTimeoutError=so;he.APIUserAbortError=bt;he.NotFoundError=Eg;he.ConflictError=Tg;he.RateLimitError=Ag;he.BadRequestError=bg;he.AuthenticationError=vg;he.InternalServerError=Ig;he.PermissionDeniedError=Sg;he.UnprocessableEntityError=xg;he.InvalidWebhookSignatureError=as;he.toFile=jA;he.Completions=P_;he.Chat=td;he.Embeddings=M_;he.Files=D_;he.Images=H_;he.Audio=Qs;he.Moderations=G_;he.Models=W_;he.FineTuning=Dn;he.Graders=dd;he.VectorStores=fo;he.Webhooks=ry;he.Beta=jn;he.Batches=x_;he.Uploads=fd;he.Responses=ho;he.Realtime=uo;he.Conversations=ad;he.Evals=od;he.Containers=sd;he.Videos=ey;var YA={};pe(YA,{BasePromptValue:()=>po,ChatPromptValue:()=>ay,ImagePromptValue:()=>QA,StringPromptValue:()=>sy});var po=class extends Rn{},sy=class extends po{constructor(e){super({value:e});w(this,"lc_namespace",["langchain_core","prompt_values"]);w(this,"lc_serializable",!0);w(this,"value");this.value=e}static lc_name(){return"StringPromptValue"}toString(){return this.value}toChatMessages(){return[new Gt(this.value)]}},ay=class extends po{constructor(e){Array.isArray(e)&&(e={messages:e});super(e);w(this,"lc_namespace",["langchain_core","prompt_values"]);w(this,"lc_serializable",!0);w(this,"messages");this.messages=e.messages}static lc_name(){return"ChatPromptValue"}toString(){return bu(this.messages)}toChatMessages(){return this.messages}},QA=class extends po{constructor(e){"imageUrl"in e||(e={imageUrl:e});super(e);w(this,"lc_namespace",["langchain_core","prompt_values"]);w(this,"lc_serializable",!0);w(this,"imageUrl");w(this,"value");this.imageUrl=e.imageUrl}static lc_name(){return"ImagePromptValue"}toString(){return this.imageUrl.url}toChatMessages(){return[new Gt({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},q="0123456789abcdef".split(""),eI=[-2147483648,8388608,32768,128],Nt=[24,16,8,0],Aa=[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],ze=[];function Kt(r,e){e?(ze[0]=ze[16]=ze[1]=ze[2]=ze[3]=ze[4]=ze[5]=ze[6]=ze[7]=ze[8]=ze[9]=ze[10]=ze[11]=ze[12]=ze[13]=ze[14]=ze[15]=0,this.blocks=ze):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],r?(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=r}Kt.prototype.update=function(r){if(!this.finalized){var e,t=typeof r;if(t!=="string"){if(t==="object"){if(r===null)throw new Error(ERROR);if(ARRAY_BUFFER&&r.constructor===ArrayBuffer)r=new Uint8Array(r);else if(!Array.isArray(r)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(r)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var n,s=0,a,i=r.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]|=r[s]<<Nt[a++&3];else for(a=this.start;s<i&&a<64;++s)n=r.charCodeAt(s),n<128?o[a>>>2]|=n<<Nt[a++&3]:n<2048?(o[a>>>2]|=(192|n>>>6)<<Nt[a++&3],o[a>>>2]|=(128|n&63)<<Nt[a++&3]):n<55296||n>=57344?(o[a>>>2]|=(224|n>>>12)<<Nt[a++&3],o[a>>>2]|=(128|n>>>6&63)<<Nt[a++&3],o[a>>>2]|=(128|n&63)<<Nt[a++&3]):(n=65536+((n&1023)<<10|r.charCodeAt(++s)&1023),o[a>>>2]|=(240|n>>>18)<<Nt[a++&3],o[a>>>2]|=(128|n>>>12&63)<<Nt[a++&3],o[a>>>2]|=(128|n>>>6&63)<<Nt[a++&3],o[a>>>2]|=(128|n&63)<<Nt[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}};Kt.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var r=this.blocks,e=this.lastByteIndex;r[16]=this.block,r[e>>>2]|=eI[e&3],this.block=r[16],e>=56&&(this.hashed||this.hash(),r[0]=this.block,r[16]=r[1]=r[2]=r[3]=r[4]=r[5]=r[6]=r[7]=r[8]=r[9]=r[10]=r[11]=r[12]=r[13]=r[14]=r[15]=0),r[14]=this.hBytes<<3|this.bytes>>>29,r[15]=this.bytes<<3,this.hash()}};Kt.prototype.hash=function(){var r=this.h0,e=this.h1,t=this.h2,n=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=this.blocks,l,u,d,h,f,p,g,_,b,m,y;for(l=16;l<64;++l)f=c[l-15],u=(f>>>7|f<<25)^(f>>>18|f<<14)^f>>>3,f=c[l-2],d=(f>>>17|f<<15)^(f>>>19|f<<13)^f>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=e&t,l=0;l<64;l+=4)this.first?(this.is224?(_=300032,f=c[0]-1413257819,o=f-150054599<<0,n=f+24177077<<0):(_=704751109,f=c[0]-210244248,o=f-1521486534<<0,n=f+143694565<<0),this.first=!1):(u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,h=_^r&t^y,g=s&a^~s&i,f=o+d+g+Aa[l]+c[l],p=u+h,o=n+f<<0,n=f+p<<0),u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),b=n&r,h=b^n&e^_,g=i&o^~i&s,f=a+d+g+Aa[l+1]+c[l+1],p=u+h,i=t+f<<0,t=f+p<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),m=t&n,h=m^t&r^b,g=a&i^~a&o,f=s+d+g+Aa[l+2]+c[l+2],p=u+h,a=e+f<<0,e=f+p<<0,u=(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),y=e&t,h=y^e&n^m,g=a&i^~a&o,f=s+d+g+Aa[l+3]+c[l+3],p=u+h,s=r+f<<0,r=f+p<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+r<<0,this.h1=this.h1+e<<0,this.h2=this.h2+t<<0,this.h3=this.h3+n<<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};Kt.prototype.hex=function(){this.finalize();var r=this.h0,e=this.h1,t=this.h2,n=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=q[r>>>28&15]+q[r>>>24&15]+q[r>>>20&15]+q[r>>>16&15]+q[r>>>12&15]+q[r>>>8&15]+q[r>>>4&15]+q[r&15]+q[e>>>28&15]+q[e>>>24&15]+q[e>>>20&15]+q[e>>>16&15]+q[e>>>12&15]+q[e>>>8&15]+q[e>>>4&15]+q[e&15]+q[t>>>28&15]+q[t>>>24&15]+q[t>>>20&15]+q[t>>>16&15]+q[t>>>12&15]+q[t>>>8&15]+q[t>>>4&15]+q[t&15]+q[n>>>28&15]+q[n>>>24&15]+q[n>>>20&15]+q[n>>>16&15]+q[n>>>12&15]+q[n>>>8&15]+q[n>>>4&15]+q[n&15]+q[s>>>28&15]+q[s>>>24&15]+q[s>>>20&15]+q[s>>>16&15]+q[s>>>12&15]+q[s>>>8&15]+q[s>>>4&15]+q[s&15]+q[a>>>28&15]+q[a>>>24&15]+q[a>>>20&15]+q[a>>>16&15]+q[a>>>12&15]+q[a>>>8&15]+q[a>>>4&15]+q[a&15]+q[i>>>28&15]+q[i>>>24&15]+q[i>>>20&15]+q[i>>>16&15]+q[i>>>12&15]+q[i>>>8&15]+q[i>>>4&15]+q[i&15];return this.is224||(c+=q[o>>>28&15]+q[o>>>24&15]+q[o>>>20&15]+q[o>>>16&15]+q[o>>>12&15]+q[o>>>8&15]+q[o>>>4&15]+q[o&15]),c};Kt.prototype.toString=Kt.prototype.hex;Kt.prototype.digest=function(){this.finalize();var r=this.h0,e=this.h1,t=this.h2,n=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=[r>>>24&255,r>>>16&255,r>>>8&255,r&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&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};Kt.prototype.array=Kt.prototype.digest;Kt.prototype.arrayBuffer=function(){this.finalize();var r=new ArrayBuffer(this.is224?28:32),e=new DataView(r);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),r};const iy=(...r)=>new Kt(!1,!0).update(r.join("")).hex();var tI={};pe(tI,{sha256:()=>iy});var rI={};pe(rI,{BaseCache:()=>cy,InMemoryCache:()=>ly,defaultHashKeyEncoder:()=>oy,deserializeStoredGeneration:()=>nI,serializeGeneration:()=>sI});const oy=(...r)=>iy(r.join("_"));function nI(r){return r.message!==void 0?{text:r.text,message:vu(r.message)}:{text:r.text}}function sI(r){const e={text:r.text};return r.message!==void 0&&(e.message=r.message.toDict()),e}var cy=class{constructor(){w(this,"keyEncoder",oy)}makeDefaultKeyEncoder(r){this.keyEncoder=r}};const aI=new Map;var ly=class uy extends cy{constructor(t){super();w(this,"cache");this.cache=t??new Map}lookup(t,n){return Promise.resolve(this.cache.get(this.keyEncoder(t,n))??null)}async update(t,n,s){this.cache.set(this.keyEncoder(t,n),s)}static global(){return new uy(aI)}},qn={},np;function iI(){if(np)return qn;np=1,qn.byteLength=o,qn.toByteArray=l,qn.fromByteArray=h;for(var r=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,a=n.length;s<a;++s)r[s]=n[s],e[n.charCodeAt(s)]=s;e[45]=62,e[95]=63;function i(f){var p=f.length;if(p%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var g=f.indexOf("=");g===-1&&(g=p);var _=g===p?0:4-g%4;return[g,_]}function o(f){var p=i(f),g=p[0],_=p[1];return(g+_)*3/4-_}function c(f,p,g){return(p+g)*3/4-g}function l(f){var p,g=i(f),_=g[0],b=g[1],m=new t(c(f,_,b)),y=0,T=b>0?_-4:_,x;for(x=0;x<T;x+=4)p=e[f.charCodeAt(x)]<<18|e[f.charCodeAt(x+1)]<<12|e[f.charCodeAt(x+2)]<<6|e[f.charCodeAt(x+3)],m[y++]=p>>16&255,m[y++]=p>>8&255,m[y++]=p&255;return b===2&&(p=e[f.charCodeAt(x)]<<2|e[f.charCodeAt(x+1)]>>4,m[y++]=p&255),b===1&&(p=e[f.charCodeAt(x)]<<10|e[f.charCodeAt(x+1)]<<4|e[f.charCodeAt(x+2)]>>2,m[y++]=p>>8&255,m[y++]=p&255),m}function u(f){return r[f>>18&63]+r[f>>12&63]+r[f>>6&63]+r[f&63]}function d(f,p,g){for(var _,b=[],m=p;m<g;m+=3)_=(f[m]<<16&16711680)+(f[m+1]<<8&65280)+(f[m+2]&255),b.push(u(_));return b.join("")}function h(f){for(var p,g=f.length,_=g%3,b=[],m=16383,y=0,T=g-_;y<T;y+=m)b.push(d(f,y,y+m>T?T:y+m));return _===1?(p=f[g-1],b.push(r[p>>2]+r[p<<4&63]+"==")):_===2&&(p=(f[g-2]<<8)+f[g-1],b.push(r[p>>10]+r[p>>4&63]+r[p<<2&63]+"=")),b.join("")}return qn}var oI=iI();const cI=Ds(oI);var lI=Object.defineProperty,uI=(r,e,t)=>e in r?lI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,dI=(r,e,t)=>(uI(r,e+"",t),t);function hI(r,e){let t=Array.from({length:r.length},(n,s)=>({start:s,end:s+1}));for(;t.length>1;){let n=null;for(let s=0;s<t.length-1;s++){const a=r.slice(t[s].start,t[s+1].end),i=e.get(a.join(","));i!=null&&(n==null||i<n[0])&&(n=[i,s])}if(n!=null){const s=n[1];t[s]={start:t[s].start,end:t[s+1].end},t.splice(s+1,1)}else break}return t}function fI(r,e){return r.length===1?[e.get(r.join(","))]:hI(r,e).map(t=>e.get(r.slice(t.start,t.end).join(","))).filter(t=>t!=null)}function pI(r){return r.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var Xl=class{constructor(r,e){w(this,"specialTokens");w(this,"inverseSpecialTokens");w(this,"patStr");w(this,"textEncoder",new TextEncoder);w(this,"textDecoder",new TextDecoder("utf-8"));w(this,"rankMap",new Map);w(this,"textMap",new Map);this.patStr=r.pat_str;const t=r.bpe_ranks.split(`
116
+ `).filter(Boolean).reduce((n,s)=>{const[a,i,...o]=s.split(" "),c=Number.parseInt(i,10);return o.forEach((l,u)=>n[l]=c+u),n},{});for(const[n,s]of Object.entries(t)){const a=cI.toByteArray(n);this.rankMap.set(a.join(","),s),this.textMap.set(s,a)}this.specialTokens={...r.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[s,a])=>(n[a]=this.textEncoder.encode(s),n),{})}encode(r,e=[],t="all"){const n=new RegExp(this.patStr,"ug"),s=Xl.specialTokenRegex(Object.keys(this.specialTokens)),a=[],i=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(t==="all"?Object.keys(this.specialTokens).filter(l=>!i.has(l)):t);if(o.size>0){const l=Xl.specialTokenRegex([...o]),u=r.match(l);if(u!=null)throw new Error(`The text contains a special token that is not allowed: ${u[0]}`)}let c=0;for(;;){let l=null,u=c;for(;s.lastIndex=u,l=s.exec(r),!(l==null||i.has(l[0]));)u=l.index+1;const d=(l==null?void 0:l.index)??r.length;for(const f of r.substring(c,d).matchAll(n)){const p=this.textEncoder.encode(f[0]),g=this.rankMap.get(p.join(","));if(g!=null){a.push(g);continue}a.push(...fI(p,this.rankMap))}if(l==null)break;let h=this.specialTokens[l[0]];a.push(h),c=l.index+l[0].length}return a}decode(r){const e=[];let t=0;for(let a=0;a<r.length;++a){const i=r[a],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(e.push(o),t+=o.length)}const n=new Uint8Array(t);let s=0;for(const a of e)n.set(a,s),s+=a.length;return this.textDecoder.decode(n)}},dy=Xl;dI(dy,"specialTokenRegex",r=>new RegExp(r.map(e=>pI(e)).join("|"),"g"));function mI(r){switch(r){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 gI={};pe(gI,{encodingForModel:()=>md,getEncoding:()=>hy});const Ia={},_I=new Js({});async function hy(r){return r in Ia||(Ia[r]=_I.fetch(`https://tiktoken.pages.dev/js/${r}.json`).then(e=>e.json()).then(e=>new dy(e)).catch(e=>{throw delete Ia[r],e})),await Ia[r]}async function md(r){return hy(mI(r))}var yI={};pe(yI,{BaseLangChain:()=>gd,BaseLanguageModel:()=>_d,calculateMaxTokens:()=>bI,getEmbeddingContextSize:()=>wI,getModelContextSize:()=>fy,getModelNameForTiktoken:()=>mo,isOpenAITool:()=>go});const mo=r=>r.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":r.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":r.startsWith("gpt-4-32k")?"gpt-4-32k":r.startsWith("gpt-4-")?"gpt-4":r.startsWith("gpt-4o")?"gpt-4o":r,wI=r=>{switch(r){case"text-embedding-ada-002":return 8191;default:return 2046}},fy=r=>{switch(mo(r)){case"gpt-3.5-turbo-16k":return 16384;case"gpt-3.5-turbo":return 4096;case"gpt-4-32k":return 32768;case"gpt-4":return 8192;case"text-davinci-003":return 4097;case"text-curie-001":return 2048;case"text-babbage-001":return 2048;case"text-ada-001":return 2048;case"code-davinci-002":return 8e3;case"code-cushman-001":return 2048;default:return 4097}};function go(r){return typeof r!="object"||!r?!1:!!("type"in r&&r.type==="function"&&"function"in r&&typeof r.function=="object"&&r.function&&"name"in r.function&&"parameters"in r.function)}const bI=async({prompt:r,modelName:e})=>{let t;try{t=(await md(mo(e))).encode(r).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),t=Math.ceil(r.length/4)}return fy(e)-t},vI=()=>!1;var gd=class extends Pe{constructor(e){super(e);w(this,"verbose");w(this,"callbacks");w(this,"tags");w(this,"metadata");this.verbose=e.verbose??vI(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}},_d=class extends gd{constructor({callbacks:e,callbackManager:t,...n}){const{cache:s,...a}=n;super({callbacks:e??t,...a});w(this,"caller");w(this,"cache");w(this,"_encoding");typeof s=="object"?this.cache=s:s?this.cache=ly.global():this.cache=void 0,this.caller=new Js(n??{})}get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join("");let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await md("modelName"in this?mo(this.modelName):"gpt2")}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}if(this._encoding)try{n=this._encoding.encode(t).length}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}return n}static _convertInputToPromptValue(e){return typeof e=="string"?new sy(e):Array.isArray(e)?new ay(e.map(bs)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([i,o])=>o!==void 0).map(([i,o])=>`${i}:${JSON.stringify(o)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}},Mr=class extends Pe{constructor(e){super(e);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"lc_serializable",!0);w(this,"func");e&&(this.func=e.func)}static lc_name(){return"RunnablePassthrough"}async invoke(e,t){const n=ge(t);return this.func&&await this.func(e,n),this._callWithConfig(s=>Promise.resolve(s),e,n)}async*transform(e,t){const n=ge(t);let s,a=!0;for await(const i of this._transformStreamWithConfig(e,o=>o,n))if(yield i,a)if(s===void 0)s=i;else try{s=Lr(s,i)}catch{s=void 0,a=!1}this.func&&s!==void 0&&await this.func(s,n)}static assign(e){return new Bu(new Mn({steps:e}))}};const SI=r=>r();function Qc(r){const e=r.constructor;return new e({...r,content:r.contentBlocks,response_metadata:{...r.response_metadata,output_version:"v1"}})}var EI={};pe(EI,{BaseChatModel:()=>_o,SimpleChatModel:()=>TI});function el(r){const e=[];for(const t of r){let n=t;if(Array.isArray(t.content))for(let s=0;s<t.content.length;s++){const a=t.content[s];(du(a)||hu(a))&&n===t&&(n=new t.constructor({...n,content:[...t.content.slice(0,s),Dp(a),...t.content.slice(s+1)]}))}e.push(n)}return e}var _o=class Br extends _d{constructor(t){super(t);w(this,"lc_namespace",["langchain","chat_models",this._llmType()]);w(this,"disableStreaming",!1);w(this,"outputVersion");this.outputVersion=SI(()=>{const n=t.outputVersion??qt("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}get callKeys(){return[...super.callKeys,"outputVersion"]}_separateRunnableConfigFromCallOptionsCompat(t){const[n,s]=super._separateRunnableConfigFromCallOptions(t);return s.signal=n.signal,[n,s]}async invoke(t,n){const s=Br._convertInputToPromptValue(t);return(await this.generatePrompt([s],n,n==null?void 0:n.callbacks)).generations[0][0].message}async*_streamResponseChunks(t,n,s){throw new Error("Not implemented.")}async*_streamIterator(t,n){var s;if(this._streamResponseChunks===Br.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,n);else{const i=Br._convertInputToPromptValue(t).toChatMessages(),[o,c]=this._separateRunnableConfigFromCallOptionsCompat(n),l={...o.metadata,...this.getLsParams(c)},u=await dt.configure(o.callbacks,this.callbacks,o.tags,this.tags,l,this.metadata,{verbose:this.verbose}),d={options:c,invocation_params:this==null?void 0:this.invocationParams(c),batch_size:1},h=c.outputVersion??this.outputVersion,f=await(u==null?void 0:u.handleChatModelStart(this.toJSON(),[el(i)],o.runId,void 0,d,void 0,void 0,o.runName));let p,g;try{for await(const _ of this._streamResponseChunks(i,c,f==null?void 0:f[0])){if(_.message.id==null){const b=(s=f==null?void 0:f.at(0))==null?void 0:s.runId;b!=null&&_.message._updateId(`run-${b}`)}_.message.response_metadata={..._.generationInfo,..._.message.response_metadata},h==="v1"?yield Qc(_.message):yield _.message,p?p=p.concat(_):p=_,_l(_.message)&&_.message.usage_metadata!==void 0&&(g={tokenUsage:{promptTokens:_.message.usage_metadata.input_tokens,completionTokens:_.message.usage_metadata.output_tokens,totalTokens:_.message.usage_metadata.total_tokens}})}}catch(_){throw await Promise.all((f??[]).map(b=>b==null?void 0:b.handleLLMError(_))),_}await Promise.all((f??[]).map(_=>_==null?void 0:_.handleLLMEnd({generations:[[p]],llmOutput:g})))}}getLsParams(t){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:t.stop,ls_provider:n}}async _generateUncached(t,n,s,a){var f,p;const i=t.map(g=>g.map(bs));let o;if(a!==void 0&&a.length===i.length)o=a;else{const g={...s.metadata,...this.getLsParams(n)},_=await dt.configure(s.callbacks,this.callbacks,s.tags,this.tags,g,this.metadata,{verbose:this.verbose}),b={options:n,invocation_params:this==null?void 0:this.invocationParams(n),batch_size:1};o=await(_==null?void 0:_.handleChatModelStart(this.toJSON(),i.map(el),s.runId,void 0,b,void 0,void 0,s.runName))}const c=n.outputVersion??this.outputVersion,l=[],u=[];if(!!(o!=null&&o[0].handlers.find(Su))&&!this.disableStreaming&&i.length===1&&this._streamResponseChunks!==Br.prototype._streamResponseChunks)try{const g=await this._streamResponseChunks(i[0],n,o==null?void 0:o[0]);let _,b;for await(const m of g){if(m.message.id==null){const y=(f=o==null?void 0:o.at(0))==null?void 0:f.runId;y!=null&&m.message._updateId(`run-${y}`)}_===void 0?_=m:_=Lr(_,m),_l(m.message)&&m.message.usage_metadata!==void 0&&(b={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}})}if(_===void 0)throw new Error("Received empty response from chat model call.");l.push([_]),await(o==null?void 0:o[0].handleLLMEnd({generations:l,llmOutput:b}))}catch(g){throw await(o==null?void 0:o[0].handleLLMError(g)),g}else{const g=await Promise.allSettled(i.map(async(_,b)=>{const m=await this._generate(_,{...n,promptIndex:b},o==null?void 0:o[b]);if(c==="v1")for(const y of m.generations)y.message=Qc(y.message);return m}));await Promise.all(g.map(async(_,b)=>{var m,y,T;if(_.status==="fulfilled"){const x=_.value;for(const R of x.generations){if(R.message.id==null){const $=(m=o==null?void 0:o.at(0))==null?void 0:m.runId;$!=null&&R.message._updateId(`run-${$}`)}R.message.response_metadata={...R.generationInfo,...R.message.response_metadata}}return x.generations.length===1&&(x.generations[0].message.response_metadata={...x.llmOutput,...x.generations[0].message.response_metadata}),l[b]=x.generations,u[b]=x.llmOutput,(y=o==null?void 0:o[b])==null?void 0:y.handleLLMEnd({generations:[x.generations],llmOutput:x.llmOutput})}else return await((T=o==null?void 0:o[b])==null?void 0:T.handleLLMError(_.reason)),Promise.reject(_.reason)}))}const h={generations:l,llmOutput:u.length?(p=this._combineLLMOutput)==null?void 0:p.call(this,...u):void 0};return Object.defineProperty(h,Ns,{value:o?{runIds:o==null?void 0:o.map(g=>g.runId)}:void 0,configurable:!0}),h}async _generateCached({messages:t,cache:n,llmStringKey:s,parsedOptions:a,handledOptions:i}){const o=t.map(m=>m.map(bs)),c={...i.metadata,...this.getLsParams(a)},l=await dt.configure(i.callbacks,this.callbacks,i.tags,this.tags,c,this.metadata,{verbose:this.verbose}),u={options:a,invocation_params:this==null?void 0:this.invocationParams(a),batch_size:1},d=await(l==null?void 0:l.handleChatModelStart(this.toJSON(),o.map(el),i.runId,void 0,u,void 0,void 0,i.runName)),h=[],p=(await Promise.allSettled(o.map(async(m,y)=>{const T=Br._convertInputToPromptValue(m).toString(),x=await n.lookup(T,s);return x==null&&h.push(y),x}))).map((m,y)=>({result:m,runManager:d==null?void 0:d[y]})).filter(({result:m})=>m.status==="fulfilled"&&m.value!=null||m.status==="rejected"),g=a.outputVersion??this.outputVersion,_=[];await Promise.all(p.map(async({result:m,runManager:y},T)=>{if(m.status==="fulfilled"){const x=m.value;return _[T]=x.map(R=>("message"in R&&pr(R.message)&&_r(R.message)&&(R.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},g==="v1"&&(R.message=Qc(R.message))),R.generationInfo={...R.generationInfo,tokenUsage:{}},R)),x.length&&await(y==null?void 0:y.handleLLMNewToken(x[0].text)),y==null?void 0:y.handleLLMEnd({generations:[x]},void 0,void 0,void 0,{cached:!0})}else return await(y==null?void 0:y.handleLLMError(m.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(m.reason)}));const b={generations:_,missingPromptIndices:h,startedRunManagers:d};return Object.defineProperty(b,Ns,{value:d?{runIds:d==null?void 0:d.map(m=>m.runId)}:void 0,configurable:!0}),b}async generate(t,n,s){let a;Array.isArray(n)?a={stop:n}:a=n;const i=t.map(g=>g.map(bs)),[o,c]=this._separateRunnableConfigFromCallOptionsCompat(a);if(o.callbacks=o.callbacks??s,!this.cache)return this._generateUncached(i,c,o);const{cache:l}=this,u=this._getSerializedCacheKeyParametersForCall(c),{generations:d,missingPromptIndices:h,startedRunManagers:f}=await this._generateCached({messages:i,cache:l,llmStringKey:u,parsedOptions:c,handledOptions:o});let p={};if(h.length>0){const g=await this._generateUncached(h.map(_=>i[_]),c,o,f!==void 0?h.map(_=>f==null?void 0:f[_]):void 0);await Promise.all(g.generations.map(async(_,b)=>{const m=h[b];d[m]=_;const y=Br._convertInputToPromptValue(i[m]).toString();return l.update(y,u,_)})),p=g.llmOutput??{}}return{generations:d,llmOutput:p}}invocationParams(t){return{}}_modelType(){return"base_chat_model"}async generatePrompt(t,n,s){const a=t.map(i=>i.toChatMessages());return this.generate(a,n,s)}withStructuredOutput(t,n){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(n!=null&&n.strict)throw new Error('"strict" mode is not supported for this model by default.');const s=t,a=n==null?void 0:n.name,i=to(s)??"A function available to call.",o=n==null?void 0:n.method,c=n==null?void 0:n.includeRaw;if(o==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let l=a??"extract",u;Rt(s)?u=[{type:"function",function:{name:l,description:i,parameters:ut(s)}}]:("name"in s&&(l=s.name),u=[{type:"function",function:{name:l,description:i,parameters:s}}]);const d=this.bindTools(u),h=vr.from(_=>{if(!ke.isInstance(_))throw new Error("Input is not an AIMessageChunk.");if(!_.tool_calls||_.tool_calls.length===0)throw new Error("No tool calls found in the response.");const b=_.tool_calls.find(m=>m.name===l);if(!b)throw new Error(`No tool call found with name ${l}.`);return b.args});if(!c)return d.pipe(h).withConfig({runName:"StructuredOutput"});const f=Mr.assign({parsed:(_,b)=>h.invoke(_.raw,b)}),p=Mr.assign({parsed:()=>null}),g=f.withFallbacks({fallbacks:[p]});return Ln.from([{raw:d},g]).withConfig({runName:"StructuredOutputRunnable"})}},TI=class extends _o{async _generate(r,e,t){const n=await this._call(r,e,t),s=new St(n);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}]}}},xI=class extends Pe{constructor(e){super(e);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"lc_serializable",!0);w(this,"runnables");this.runnables=e.runnables}static lc_name(){return"RouterRunnable"}async invoke(e,t){const{key:n,input:s}=e,a=this.runnables[n];if(a===void 0)throw new Error(`No runnable associated with key "${n}".`);return a.invoke(s,ge(t))}async batch(e,t,n){var h;const s=e.map(f=>f.key),a=e.map(f=>f.input);if(s.find(f=>this.runnables[f]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const o=s.map(f=>this.runnables[f]),c=this._getOptionsList(t??{},e.length),l=((h=c[0])==null?void 0:h.maxConcurrency)??(n==null?void 0:n.maxConcurrency),u=l&&l>0?l:e.length,d=[];for(let f=0;f<a.length;f+=u){const p=a.slice(f,f+u).map((_,b)=>o[b].invoke(_,c[b])),g=await Promise.all(p);d.push(g)}return d.flat()}async stream(e,t){const{key:n,input:s}=e,a=this.runnables[n];if(a===void 0)throw new Error(`No runnable associated with key "${n}".`);return a.stream(s,t)}},AI=class extends Pe{constructor(e){super(e);w(this,"lc_namespace",["langchain_core","runnables"]);w(this,"lc_serializable",!0);w(this,"default");w(this,"branches");this.branches=e.branches,this.default=e.default}static lc_name(){return"RunnableBranch"}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const n=e.slice(0,-1).map(([a,i])=>[Ft(a),Ft(i)]),s=Ft(e[e.length-1]);return new this({branches:n,default:s})}async _invoke(e,t,n){let s;for(let a=0;a<this.branches.length;a+=1){const[i,o]=this.branches[a];if(await i.invoke(e,Te(t,{callbacks:n==null?void 0:n.getChild(`condition:${a+1}`)}))){s=await o.invoke(e,Te(t,{callbacks:n==null?void 0:n.getChild(`branch:${a+1}`)}));break}}return s||(s=await this.default.invoke(e,Te(t,{callbacks:n==null?void 0:n.getChild("branch:default")}))),s}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){const n=await vt(t),s=await(n==null?void 0:n.handleChainStart(this.toJSON(),qe(e,"input"),t==null?void 0:t.runId,void 0,void 0,void 0,t==null?void 0:t.runName));let a,i=!0,o;try{for(let c=0;c<this.branches.length;c+=1){const[l,u]=this.branches[c];if(await l.invoke(e,Te(t,{callbacks:s==null?void 0:s.getChild(`condition:${c+1}`)}))){o=await u.stream(e,Te(t,{callbacks:s==null?void 0:s.getChild(`branch:${c+1}`)}));for await(const h of o)if(yield h,i)if(a===void 0)a=h;else try{a=Lr(a,h)}catch{a=void 0,i=!1}break}}if(o===void 0){o=await this.default.stream(e,Te(t,{callbacks:s==null?void 0:s.getChild("branch:default")}));for await(const c of o)if(yield c,i)if(a===void 0)a=c;else try{a=Lr(a,c)}catch{a=void 0,i=!1}}}catch(c){throw await(s==null?void 0:s.handleChainError(c)),c}await(s==null?void 0:s.handleChainEnd(a??{}))}},II=class extends Cn{constructor(e){let t=vr.from((i,o)=>this._enterHistory(i,o??{})).withConfig({runName:"loadHistory"});const n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=Mr.assign({[n]:t}).withConfig({runName:"insertHistory"}));const s=t.pipe(e.runnable.withListeners({onEnd:(i,o)=>this._exitHistory(i,o??{})})).withConfig({runName:"RunnableWithMessageHistory"}),a=e.config??{};super({...e,config:a,bound:s});w(this,"runnable");w(this,"inputMessagesKey");w(this,"outputMessagesKey");w(this,"historyMessagesKey");w(this,"getMessageHistory");this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e=="object"&&!Array.isArray(e)&&!pr(e)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="input",Array.isArray(e[n])&&Array.isArray(e[n][0])?t=e[n][0]:t=e[n]}else t=e;if(typeof t=="string")return[new Gt(t)];if(Array.isArray(t))return t;if(pr(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
117
+ Got ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!pr(e)&&typeof e!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="output",e.generations!==void 0?t=e.generations[0][0].message:t=e[n]}else t=e;if(typeof t=="string")return[new St(t)];if(Array.isArray(t))return t;if(pr(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){var a;const s=await((a=t==null?void 0:t.configurable)==null?void 0:a.messageHistory).getMessages();return this.historyMessagesKey===void 0?s.concat(this._getInputMessages(e)):s}async _exitHistory(e,t){var c;const n=(c=t.configurable)==null?void 0:c.messageHistory;let s;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?s=e.inputs[0]:s=e.inputs;let a=this._getInputMessages(s);if(this.historyMessagesKey===void 0){const l=await n.getMessages();a=a.slice(l.length)}const i=e.outputs;if(!i)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const o=this._getOutputMessages(i);await n.addMessages([...a,...o])}async _mergeConfig(...e){const t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){const s={[this.inputMessagesKey??"input"]:"foo"},a={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
118
+ eg. chain.invoke(${JSON.stringify(s)}, ${JSON.stringify(a)})`)}const{sessionId:n}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(n),t}},RI={};pe(RI,{RouterRunnable:()=>xI,Runnable:()=>Pe,RunnableAssign:()=>Bu,RunnableBinding:()=>Cn,RunnableBranch:()=>AI,RunnableEach:()=>RT,RunnableLambda:()=>vr,RunnableMap:()=>Mn,RunnableParallel:()=>CT,RunnablePassthrough:()=>Mr,RunnablePick:()=>hg,RunnableRetry:()=>Fu,RunnableSequence:()=>Ln,RunnableToolLike:()=>Nl,RunnableWithFallbacks:()=>dg,RunnableWithMessageHistory:()=>II,_coerceToRunnable:()=>Ft,ensureConfig:()=>ge,getCallbackManagerForConfig:()=>vt,mergeConfigs:()=>fi,patchConfig:()=>Te,pickRunnableConfigKeys:()=>yr});var yd=class extends Pe{parseResultWithPrompt(r,e,t){return this.parseResult(r,t)}_baseMessageToString(r){return typeof r.content=="string"?r.content:this._baseMessageContentToString(r.content)}_baseMessageContentToString(r){return JSON.stringify(r)}async invoke(r,e){return typeof r=="string"?this._callWithConfig(async(t,n)=>this.parseResult([{text:t}],n==null?void 0:n.callbacks),r,{...e,runType:"parser"}):this._callWithConfig(async(t,n)=>this.parseResult([{message:t,text:this._baseMessageToString(t)}],n==null?void 0:n.callbacks),r,{...e,runType:"parser"})}},yo=class extends yd{parseResult(r,e){return this.parse(r[0].text,e)}async parseWithPrompt(r,e,t){return this.parse(r,t)}_type(){throw new Error("_type not implemented")}},zt=class extends Error{constructor(e,t,n,s=!1){super(e);w(this,"llmOutput");w(this,"observation");w(this,"sendToLLM");if(this.llmOutput=t,this.observation=n,this.sendToLLM=s,s&&(n===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");Qp(this,"OUTPUT_PARSING_FAILURE")}},ea=class extends yo{async*_transform(r){for await(const e of r)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(r,e){yield*this._transformStreamWithConfig(r,this._transform.bind(this),{...e,runType:"parser"})}},wo=class extends ea{constructor(e){super(e);w(this,"diff",!1);this.diff=(e==null?void 0:e.diff)??this.diff}async*_transform(e){let t,n;for await(const s of e){if(typeof s!="string"&&typeof s.content!="string")throw new Error("Cannot handle non-string output.");let a;if(gu(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");a=new Xr({message:s,text:s.content})}else if(pr(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");a=new Xr({message:li(s),text:s.content})}else a=new $n({text:s});n===void 0?n=a:n=n.concat(a);const i=await this.parsePartialResult([n]);i!=null&&!Vr(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return""}},OI=class extends ea{constructor(){super(...arguments);w(this,"lc_namespace",["langchain_core","output_parsers","bytes"]);w(this,"lc_serializable",!0);w(this,"textEncoder",new TextEncoder)}static lc_name(){return"BytesOutputParser"}parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},ta=class extends ea{constructor(){super(...arguments);w(this,"re")}async*_transform(e){let t="";for await(const n of e)if(typeof n=="string"?t+=n:t+=n.content,this.re){const s=[...t.matchAll(this.re)];if(s.length>1){let a=0;for(const i of s.slice(0,-1))yield[i[1]],a+=(i.index??0)+i[0].length;t=t.slice(a)}}else{const s=await this.parse(t);if(s.length>1){for(const a of s.slice(0,-1))yield[a];t=s[s.length-1]}}for(const n of await this.parse(t))yield[n]}},$I=class extends ta{constructor(){super(...arguments);w(this,"lc_namespace",["langchain_core","output_parsers","list"]);w(this,"lc_serializable",!0)}static lc_name(){return"CommaSeparatedListOutputParser"}async parse(e){try{return e.trim().split(",").map(t=>t.trim())}catch{throw new zt(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},CI=class extends ta{constructor({length:e,separator:t}){super(...arguments);w(this,"lc_namespace",["langchain_core","output_parsers","list"]);w(this,"length");w(this,"separator");this.length=e,this.separator=t||","}async parse(e){try{const t=e.trim().split(this.separator).map(n=>n.trim());if(this.length!==void 0&&t.length!==this.length)throw new zt(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===zt.prototype?t:new zt(`Could not parse output: ${e}`)}}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\`)`}},kI=class extends ta{constructor(){super(...arguments);w(this,"lc_namespace",["langchain_core","output_parsers","list"]);w(this,"lc_serializable",!0);w(this,"re",/\d+\.\s([^\n]+)/g)}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
119
+
120
+ 1. foo
121
+
122
+ 2. bar
123
+
124
+ 3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},PI=class extends ta{constructor(){super(...arguments);w(this,"lc_namespace",["langchain_core","output_parsers","list"]);w(this,"lc_serializable",!0);w(this,"re",/^\s*[-*]\s([^\n]+)$/gm)}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
125
+
126
+ 1. foo
127
+
128
+ 2. bar
129
+
130
+ 3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},NI=class extends ea{constructor(){super(...arguments);w(this,"lc_namespace",["langchain_core","output_parsers","string"]);w(this,"lc_serializable",!0)}static lc_name(){return"StrOutputParser"}parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((t,n)=>t+this._messageContentToString(n),"")}},ki=class extends yo{constructor(e){super(e);w(this,"lc_namespace",["langchain","output_parsers","structured"]);this.schema=e}static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=$r(Object.fromEntries(Object.entries(e).map(([n,s])=>[n,In().describe(s)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
131
+
132
+ "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
133
+
134
+ For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
135
+ would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
136
+ Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
137
+
138
+ Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
139
+
140
+ Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
141
+ \`\`\`json
142
+ ${JSON.stringify(ut(this.schema))}
143
+ \`\`\`
144
+ `}async parse(e){var t,n;try{const s=e.trim(),i=(((t=s.match(/^```(?:json)?\s*([\s\S]*?)```/))==null?void 0:t[1])||((n=s.match(/```json\s*([\s\S]*?)```/))==null?void 0:n[1])||s).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(o,c)=>`"${c.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await eo(this.schema,JSON.parse(i))}catch(s){throw new zt(`Failed to parse. Text: "${e}". Error: ${s}`,e)}}},py=class extends ki{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(r){const e=(r==null?void 0:r.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:
145
+ \`\`\`json
146
+ ${this._schemaToInstruction(ut(this.schema)).replaceAll("{","{".repeat(e)).replaceAll("}","}".repeat(e))}
147
+ \`\`\``}_schemaToInstruction(r,e=2){const t=r;if("type"in t){let n=!1,s;if(Array.isArray(t.type)){const o=t.type.findIndex(c=>c==="null");o!==-1&&(n=!0,t.type.splice(o,1)),s=t.type.join(" | ")}else s=t.type;if(t.type==="object"&&t.properties){const o=t.description?` // ${t.description}`:"";return`{
148
+ ${Object.entries(t.properties).map(([l,u])=>{var h;const d=(h=t.required)!=null&&h.includes(l)?"":" (optional)";return`${" ".repeat(e)}"${l}": ${this._schemaToInstruction(u,e+2)}${d}`}).join(`
149
+ `)}
150
+ ${" ".repeat(e-2)}}${o}`}if(t.type==="array"&&t.items){const o=t.description?` // ${t.description}`:"";return`array[
151
+ ${" ".repeat(e)}${this._schemaToInstruction(t.items,e+2)}
152
+ ${" ".repeat(e-2)}] ${o}`}const a=n?" (nullable)":"",i=t.description?` // ${t.description}`:"";return`${s}${i}${a}`}if("anyOf"in t)return t.anyOf.map(n=>this._schemaToInstruction(n,e)).join(`
153
+ ${" ".repeat(e-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(r){return new this(r)}static fromNamesAndDescriptions(r){const e=$r(Object.fromEntries(Object.entries(r).map(([t,n])=>[t,In().describe(n)])));return new this(e)}},LI=class extends yo{constructor({inputSchema:e}){super(...arguments);w(this,"structuredInputParser");this.structuredInputParser=new py(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(n){throw new zt(`Failed to parse. Text: "${e}". Error: ${n}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},MI={};pe(MI,{applyPatch:()=>On,compare:()=>ku});var Yl=class extends wo{constructor(){super(...arguments);w(this,"lc_namespace",["langchain_core","output_parsers"]);w(this,"lc_serializable",!0)}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?ku(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return gl(e[0].text)}async parse(e){return gl(e,JSON.parse)}getFormatInstructions(){return""}};const jI=function(){const r={};r.parser=function(S,v){return new t(S,v)},r.SAXParser=t,r.SAXStream=l,r.createStream=c,r.MAX_BUFFER_LENGTH=64*1024;const e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];r.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function t(S,v){if(!(this instanceof t))return new t(S,v);var C=this;s(C),C.q=C.c="",C.bufferCheckPosition=r.MAX_BUFFER_LENGTH,C.opt=v||{},C.opt.lowercase=C.opt.lowercase||C.opt.lowercasetags,C.looseCase=C.opt.lowercase?"toLowerCase":"toUpperCase",C.tags=[],C.closed=C.closedRoot=C.sawRoot=!1,C.tag=C.error=null,C.strict=!!S,C.noscript=!!(S||C.opt.noscript),C.state=E.BEGIN,C.strictEntities=C.opt.strictEntities,C.ENTITIES=C.strictEntities?Object.create(r.XML_ENTITIES):Object.create(r.ENTITIES),C.attribList=[],C.opt.xmlns&&(C.ns=Object.create(p)),C.trackPosition=C.opt.position!==!1,C.trackPosition&&(C.position=C.line=C.column=0),se(C,"onready")}Object.create||(Object.create=function(S){function v(){}v.prototype=S;var C=new v;return C}),Object.keys||(Object.keys=function(S){var v=[];for(var C in S)S.hasOwnProperty(C)&&v.push(C);return v});function n(S){for(var v=Math.max(r.MAX_BUFFER_LENGTH,10),C=0,A=0,fe=e.length;A<fe;A++){var Se=S[e[A]].length;if(Se>v)switch(e[A]){case"textNode":Ae(S);break;case"cdata":H(S,"oncdata",S.cdata),S.cdata="";break;case"script":H(S,"onscript",S.script),S.script="";break;default:M(S,"Max buffer length exceeded: "+e[A])}C=Math.max(C,Se)}var Ee=r.MAX_BUFFER_LENGTH-C;S.bufferCheckPosition=Ee+S.position}function s(S){for(var v=0,C=e.length;v<C;v++)S[e[v]]=""}function a(S){Ae(S),S.cdata!==""&&(H(S,"oncdata",S.cdata),S.cdata=""),S.script!==""&&(H(S,"onscript",S.script),S.script="")}t.prototype={end:function(){P(this)},write:me,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=r.EVENTS.filter(function(S){return S!=="error"&&S!=="end"});function c(S,v){return new l(S,v)}function l(S,v){if(!(this instanceof l))return new l(S,v);i.apply(this),this._parser=new t(S,v),this.writable=!0,this.readable=!0;var C=this;this._parser.onend=function(){C.emit("end")},this._parser.onerror=function(A){C.emit("error",A),C._parser.error=null},this._decoder=null,o.forEach(function(A){Object.defineProperty(C,"on"+A,{get:function(){return C._parser["on"+A]},set:function(fe){if(!fe)return C.removeAllListeners(A),C._parser["on"+A]=fe,fe;C.on(A,fe)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(i.prototype,{constructor:{value:l}}),l.prototype.write=function(S){return this._parser.write(S.toString()),this.emit("data",S),!0},l.prototype.end=function(S){return S&&S.length&&this.write(S),this._parser.end(),!0},l.prototype.on=function(S,v){var C=this;return!C._parser["on"+S]&&o.indexOf(S)!==-1&&(C._parser["on"+S]=function(){var A=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);A.splice(0,0,S),C.emit.apply(C,A)}),i.prototype.on.call(C,S,v)};var u="[CDATA[",d="DOCTYPE",h="http://www.w3.org/XML/1998/namespace",f="http://www.w3.org/2000/xmlns/",p={xml:h,xmlns:f},g=/[:_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]/,_=/[:_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-]/,b=/[#:_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]/,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\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function y(S){return S===" "||S===`
154
+ `||S==="\r"||S===" "}function T(S){return S==='"'||S==="'"}function x(S){return S===">"||y(S)}function R(S,v){return S.test(v)}function $(S,v){return!R(S,v)}var E=0;r.STATE={BEGIN:E++,BEGIN_WHITESPACE:E++,TEXT:E++,TEXT_ENTITY:E++,OPEN_WAKA:E++,SGML_DECL:E++,SGML_DECL_QUOTED:E++,DOCTYPE:E++,DOCTYPE_QUOTED:E++,DOCTYPE_DTD:E++,DOCTYPE_DTD_QUOTED:E++,COMMENT_STARTING:E++,COMMENT:E++,COMMENT_ENDING:E++,COMMENT_ENDED:E++,CDATA:E++,CDATA_ENDING:E++,CDATA_ENDING_2:E++,PROC_INST:E++,PROC_INST_BODY:E++,PROC_INST_ENDING:E++,OPEN_TAG:E++,OPEN_TAG_SLASH:E++,ATTRIB:E++,ATTRIB_NAME:E++,ATTRIB_NAME_SAW_WHITE:E++,ATTRIB_VALUE:E++,ATTRIB_VALUE_QUOTED:E++,ATTRIB_VALUE_CLOSED:E++,ATTRIB_VALUE_UNQUOTED:E++,ATTRIB_VALUE_ENTITY_Q:E++,ATTRIB_VALUE_ENTITY_U:E++,CLOSE_TAG:E++,CLOSE_TAG_SAW_WHITE:E++,SCRIPT:E++,SCRIPT_ENDING:E++},r.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},r.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(r.ENTITIES).forEach(function(S){var v=r.ENTITIES[S],C=typeof v=="number"?String.fromCharCode(v):v;r.ENTITIES[S]=C});for(var J in r.STATE)r.STATE[r.STATE[J]]=J;E=r.STATE;function se(S,v,C){S[v]&&S[v](C)}function H(S,v,C){S.textNode&&Ae(S),se(S,v,C)}function Ae(S){S.textNode=ft(S.opt,S.textNode),S.textNode&&se(S,"ontext",S.textNode),S.textNode=""}function ft(S,v){return S.trim&&(v=v.trim()),S.normalize&&(v=v.replace(/\s+/g," ")),v}function M(S,v){return Ae(S),S.trackPosition&&(v+=`
155
+ Line: `+S.line+`
156
+ Column: `+S.column+`
157
+ Char: `+S.c),v=new Error(v),S.error=v,se(S,"onerror",v),S}function P(S){return S.sawRoot&&!S.closedRoot&&N(S,"Unclosed root tag"),S.state!==E.BEGIN&&S.state!==E.BEGIN_WHITESPACE&&S.state!==E.TEXT&&M(S,"Unexpected end"),Ae(S),S.c="",S.closed=!0,se(S,"onend"),t.call(S,S.strict,S.opt),S}function N(S,v){if(typeof S!="object"||!(S instanceof t))throw new Error("bad call to strictFail");S.strict&&M(S,v)}function W(S){S.strict||(S.tagName=S.tagName[S.looseCase]());var v=S.tags[S.tags.length-1]||S,C=S.tag={name:S.tagName,attributes:{}};S.opt.xmlns&&(C.ns=v.ns),S.attribList.length=0,H(S,"onopentagstart",C)}function V(S,v){var C=S.indexOf(":"),A=C<0?["",S]:S.split(":"),fe=A[0],Se=A[1];return v&&S==="xmlns"&&(fe="xmlns",Se=""),{prefix:fe,local:Se}}function z(S){if(S.strict||(S.attribName=S.attribName[S.looseCase]()),S.attribList.indexOf(S.attribName)!==-1||S.tag.attributes.hasOwnProperty(S.attribName)){S.attribName=S.attribValue="";return}if(S.opt.xmlns){var v=V(S.attribName,!0),C=v.prefix,A=v.local;if(C==="xmlns")if(A==="xml"&&S.attribValue!==h)N(S,"xml: prefix must be bound to "+h+`
158
+ Actual: `+S.attribValue);else if(A==="xmlns"&&S.attribValue!==f)N(S,"xmlns: prefix must be bound to "+f+`
159
+ Actual: `+S.attribValue);else{var fe=S.tag,Se=S.tags[S.tags.length-1]||S;fe.ns===Se.ns&&(fe.ns=Object.create(Se.ns)),fe.ns[A]=S.attribValue}S.attribList.push([S.attribName,S.attribValue])}else S.tag.attributes[S.attribName]=S.attribValue,H(S,"onattribute",{name:S.attribName,value:S.attribValue});S.attribName=S.attribValue=""}function ee(S,v){if(S.opt.xmlns){var C=S.tag,A=V(S.tagName);C.prefix=A.prefix,C.local=A.local,C.uri=C.ns[A.prefix]||"",C.prefix&&!C.uri&&(N(S,"Unbound namespace prefix: "+JSON.stringify(S.tagName)),C.uri=A.prefix);var fe=S.tags[S.tags.length-1]||S;C.ns&&fe.ns!==C.ns&&Object.keys(C.ns).forEach(function(jr){H(S,"onopennamespace",{prefix:jr,uri:C.ns[jr]})});for(var Se=0,Ee=S.attribList.length;Se<Ee;Se++){var Ne=S.attribList[Se],We=Ne[0],Ot=Ne[1],Re=V(We,!0),Tt=Re.prefix,nn=Re.local,ia=Tt===""?"":C.ns[Tt]||"",D={name:We,value:Ot,prefix:Tt,local:nn,uri:ia};Tt&&Tt!=="xmlns"&&!ia&&(N(S,"Unbound namespace prefix: "+JSON.stringify(Tt)),D.uri=Tt),S.tag.attributes[We]=D,H(S,"onattribute",D)}S.attribList.length=0}S.tag.isSelfClosing=!!v,S.sawRoot=!0,S.tags.push(S.tag),H(S,"onopentag",S.tag),v||(!S.noscript&&S.tagName.toLowerCase()==="script"?S.state=E.SCRIPT:S.state=E.TEXT,S.tag=null,S.tagName=""),S.attribName=S.attribValue="",S.attribList.length=0}function de(S){if(!S.tagName){N(S,"Weird empty close tag."),S.textNode+="</>",S.state=E.TEXT;return}if(S.script){if(S.tagName!=="script"){S.script+="</"+S.tagName+">",S.tagName="",S.state=E.SCRIPT;return}H(S,"onscript",S.script),S.script=""}var v=S.tags.length,C=S.tagName;S.strict||(C=C[S.looseCase]());for(var A=C;v--;){var fe=S.tags[v];if(fe.name!==A)N(S,"Unexpected close tag");else break}if(v<0){N(S,"Unmatched closing tag: "+S.tagName),S.textNode+="</"+S.tagName+">",S.state=E.TEXT;return}S.tagName=C;for(var Se=S.tags.length;Se-- >v;){var Ee=S.tag=S.tags.pop();S.tagName=S.tag.name,H(S,"onclosetag",S.tagName);var Ne={};for(var We in Ee.ns)Ne[We]=Ee.ns[We];var Ot=S.tags[S.tags.length-1]||S;S.opt.xmlns&&Ee.ns!==Ot.ns&&Object.keys(Ee.ns).forEach(function(Re){var Tt=Ee.ns[Re];H(S,"onclosenamespace",{prefix:Re,uri:Tt})})}v===0&&(S.closedRoot=!0),S.tagName=S.attribValue=S.attribName="",S.attribList.length=0,S.state=E.TEXT}function oe(S){var v=S.entity,C=v.toLowerCase(),A,fe="";return S.ENTITIES[v]?S.ENTITIES[v]:S.ENTITIES[C]?S.ENTITIES[C]:(v=C,v.charAt(0)==="#"&&(v.charAt(1)==="x"?(v=v.slice(2),A=parseInt(v,16),fe=A.toString(16)):(v=v.slice(1),A=parseInt(v,10),fe=A.toString(10))),v=v.replace(/^0+/,""),isNaN(A)||fe.toLowerCase()!==v?(N(S,"Invalid character entity"),"&"+S.entity+";"):String.fromCodePoint(A))}function ye(S,v){v==="<"?(S.state=E.OPEN_WAKA,S.startTagPosition=S.position):y(v)||(N(S,"Non-whitespace before first tag."),S.textNode=v,S.state=E.TEXT)}function Ce(S,v){var C="";return v<S.length&&(C=S.charAt(v)),C}function me(S){var v=this;if(this.error)throw this.error;if(v.closed)return M(v,"Cannot write after close. Assign an onready handler.");if(S===null)return P(v);typeof S=="object"&&(S=S.toString());for(var C=0,A="";A=Ce(S,C++),v.c=A,!!A;)switch(v.trackPosition&&(v.position++,A===`
160
+ `?(v.line++,v.column=0):v.column++),v.state){case E.BEGIN:if(v.state=E.BEGIN_WHITESPACE,A==="\uFEFF")continue;ye(v,A);continue;case E.BEGIN_WHITESPACE:ye(v,A);continue;case E.TEXT:if(v.sawRoot&&!v.closedRoot){for(var fe=C-1;A&&A!=="<"&&A!=="&";)A=Ce(S,C++),A&&v.trackPosition&&(v.position++,A===`
161
+ `?(v.line++,v.column=0):v.column++);v.textNode+=S.substring(fe,C-1)}A==="<"&&!(v.sawRoot&&v.closedRoot&&!v.strict)?(v.state=E.OPEN_WAKA,v.startTagPosition=v.position):(!y(A)&&(!v.sawRoot||v.closedRoot)&&N(v,"Text data outside of root node."),A==="&"?v.state=E.TEXT_ENTITY:v.textNode+=A);continue;case E.SCRIPT:A==="<"?v.state=E.SCRIPT_ENDING:v.script+=A;continue;case E.SCRIPT_ENDING:A==="/"?v.state=E.CLOSE_TAG:(v.script+="<"+A,v.state=E.SCRIPT);continue;case E.OPEN_WAKA:if(A==="!")v.state=E.SGML_DECL,v.sgmlDecl="";else if(!y(A))if(R(g,A))v.state=E.OPEN_TAG,v.tagName=A;else if(A==="/")v.state=E.CLOSE_TAG,v.tagName="";else if(A==="?")v.state=E.PROC_INST,v.procInstName=v.procInstBody="";else{if(N(v,"Unencoded <"),v.startTagPosition+1<v.position){var Se=v.position-v.startTagPosition;A=new Array(Se).join(" ")+A}v.textNode+="<"+A,v.state=E.TEXT}continue;case E.SGML_DECL:(v.sgmlDecl+A).toUpperCase()===u?(H(v,"onopencdata"),v.state=E.CDATA,v.sgmlDecl="",v.cdata=""):v.sgmlDecl+A==="--"?(v.state=E.COMMENT,v.comment="",v.sgmlDecl=""):(v.sgmlDecl+A).toUpperCase()===d?(v.state=E.DOCTYPE,(v.doctype||v.sawRoot)&&N(v,"Inappropriately located doctype declaration"),v.doctype="",v.sgmlDecl=""):A===">"?(H(v,"onsgmldeclaration",v.sgmlDecl),v.sgmlDecl="",v.state=E.TEXT):(T(A)&&(v.state=E.SGML_DECL_QUOTED),v.sgmlDecl+=A);continue;case E.SGML_DECL_QUOTED:A===v.q&&(v.state=E.SGML_DECL,v.q=""),v.sgmlDecl+=A;continue;case E.DOCTYPE:A===">"?(v.state=E.TEXT,H(v,"ondoctype",v.doctype),v.doctype=!0):(v.doctype+=A,A==="["?v.state=E.DOCTYPE_DTD:T(A)&&(v.state=E.DOCTYPE_QUOTED,v.q=A));continue;case E.DOCTYPE_QUOTED:v.doctype+=A,A===v.q&&(v.q="",v.state=E.DOCTYPE);continue;case E.DOCTYPE_DTD:v.doctype+=A,A==="]"?v.state=E.DOCTYPE:T(A)&&(v.state=E.DOCTYPE_DTD_QUOTED,v.q=A);continue;case E.DOCTYPE_DTD_QUOTED:v.doctype+=A,A===v.q&&(v.state=E.DOCTYPE_DTD,v.q="");continue;case E.COMMENT:A==="-"?v.state=E.COMMENT_ENDING:v.comment+=A;continue;case E.COMMENT_ENDING:A==="-"?(v.state=E.COMMENT_ENDED,v.comment=ft(v.opt,v.comment),v.comment&&H(v,"oncomment",v.comment),v.comment=""):(v.comment+="-"+A,v.state=E.COMMENT);continue;case E.COMMENT_ENDED:A!==">"?(N(v,"Malformed comment"),v.comment+="--"+A,v.state=E.COMMENT):v.state=E.TEXT;continue;case E.CDATA:A==="]"?v.state=E.CDATA_ENDING:v.cdata+=A;continue;case E.CDATA_ENDING:A==="]"?v.state=E.CDATA_ENDING_2:(v.cdata+="]"+A,v.state=E.CDATA);continue;case E.CDATA_ENDING_2:A===">"?(v.cdata&&H(v,"oncdata",v.cdata),H(v,"onclosecdata"),v.cdata="",v.state=E.TEXT):A==="]"?v.cdata+="]":(v.cdata+="]]"+A,v.state=E.CDATA);continue;case E.PROC_INST:A==="?"?v.state=E.PROC_INST_ENDING:y(A)?v.state=E.PROC_INST_BODY:v.procInstName+=A;continue;case E.PROC_INST_BODY:if(!v.procInstBody&&y(A))continue;A==="?"?v.state=E.PROC_INST_ENDING:v.procInstBody+=A;continue;case E.PROC_INST_ENDING:A===">"?(H(v,"onprocessinginstruction",{name:v.procInstName,body:v.procInstBody}),v.procInstName=v.procInstBody="",v.state=E.TEXT):(v.procInstBody+="?"+A,v.state=E.PROC_INST_BODY);continue;case E.OPEN_TAG:R(_,A)?v.tagName+=A:(W(v),A===">"?ee(v):A==="/"?v.state=E.OPEN_TAG_SLASH:(y(A)||N(v,"Invalid character in tag name"),v.state=E.ATTRIB));continue;case E.OPEN_TAG_SLASH:A===">"?(ee(v,!0),de(v)):(N(v,"Forward-slash in opening tag not followed by >"),v.state=E.ATTRIB);continue;case E.ATTRIB:if(y(A))continue;A===">"?ee(v):A==="/"?v.state=E.OPEN_TAG_SLASH:R(g,A)?(v.attribName=A,v.attribValue="",v.state=E.ATTRIB_NAME):N(v,"Invalid attribute name");continue;case E.ATTRIB_NAME:A==="="?v.state=E.ATTRIB_VALUE:A===">"?(N(v,"Attribute without value"),v.attribValue=v.attribName,z(v),ee(v)):y(A)?v.state=E.ATTRIB_NAME_SAW_WHITE:R(_,A)?v.attribName+=A:N(v,"Invalid attribute name");continue;case E.ATTRIB_NAME_SAW_WHITE:if(A==="=")v.state=E.ATTRIB_VALUE;else{if(y(A))continue;N(v,"Attribute without value"),v.tag.attributes[v.attribName]="",v.attribValue="",H(v,"onattribute",{name:v.attribName,value:""}),v.attribName="",A===">"?ee(v):R(g,A)?(v.attribName=A,v.state=E.ATTRIB_NAME):(N(v,"Invalid attribute name"),v.state=E.ATTRIB)}continue;case E.ATTRIB_VALUE:if(y(A))continue;T(A)?(v.q=A,v.state=E.ATTRIB_VALUE_QUOTED):(N(v,"Unquoted attribute value"),v.state=E.ATTRIB_VALUE_UNQUOTED,v.attribValue=A);continue;case E.ATTRIB_VALUE_QUOTED:if(A!==v.q){A==="&"?v.state=E.ATTRIB_VALUE_ENTITY_Q:v.attribValue+=A;continue}z(v),v.q="",v.state=E.ATTRIB_VALUE_CLOSED;continue;case E.ATTRIB_VALUE_CLOSED:y(A)?v.state=E.ATTRIB:A===">"?ee(v):A==="/"?v.state=E.OPEN_TAG_SLASH:R(g,A)?(N(v,"No whitespace between attributes"),v.attribName=A,v.attribValue="",v.state=E.ATTRIB_NAME):N(v,"Invalid attribute name");continue;case E.ATTRIB_VALUE_UNQUOTED:if(!x(A)){A==="&"?v.state=E.ATTRIB_VALUE_ENTITY_U:v.attribValue+=A;continue}z(v),A===">"?ee(v):v.state=E.ATTRIB;continue;case E.CLOSE_TAG:if(v.tagName)A===">"?de(v):R(_,A)?v.tagName+=A:v.script?(v.script+="</"+v.tagName,v.tagName="",v.state=E.SCRIPT):(y(A)||N(v,"Invalid tagname in closing tag"),v.state=E.CLOSE_TAG_SAW_WHITE);else{if(y(A))continue;$(g,A)?v.script?(v.script+="</"+A,v.state=E.SCRIPT):N(v,"Invalid tagname in closing tag."):v.tagName=A}continue;case E.CLOSE_TAG_SAW_WHITE:if(y(A))continue;A===">"?de(v):N(v,"Invalid characters in closing tag");continue;case E.TEXT_ENTITY:case E.ATTRIB_VALUE_ENTITY_Q:case E.ATTRIB_VALUE_ENTITY_U:var Ee,Ne;switch(v.state){case E.TEXT_ENTITY:Ee=E.TEXT,Ne="textNode";break;case E.ATTRIB_VALUE_ENTITY_Q:Ee=E.ATTRIB_VALUE_QUOTED,Ne="attribValue";break;case E.ATTRIB_VALUE_ENTITY_U:Ee=E.ATTRIB_VALUE_UNQUOTED,Ne="attribValue";break}if(A===";")if(v.opt.unparsedEntities){var We=oe(v);v.entity="",v.state=Ee,v.write(We)}else v[Ne]+=oe(v),v.entity="",v.state=Ee;else R(v.entity.length?m:b,A)?v.entity+=A:(N(v,"Invalid character in entity name"),v[Ne]+="&"+v.entity+A,v.entity="",v.state=Ee);continue;default:throw new Error(v,"Unknown state: "+v.state)}return v.position>=v.bufferCheckPosition&&n(v),v}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */return String.fromCodePoint||(function(){var S=String.fromCharCode,v=Math.floor,C=function(){var A=16384,fe=[],Se,Ee,Ne=-1,We=arguments.length;if(!We)return"";for(var Ot="";++Ne<We;){var Re=Number(arguments[Ne]);if(!isFinite(Re)||Re<0||Re>1114111||v(Re)!==Re)throw RangeError("Invalid code point: "+Re);Re<=65535?fe.push(Re):(Re-=65536,Se=(Re>>10)+55296,Ee=Re%1024+56320,fe.push(Se,Ee)),(Ne+1===We||fe.length>A)&&(Ot+=S.apply(null,fe),fe.length=0)}return Ot};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:C,configurable:!0,writable:!0}):String.fromCodePoint=C})(),r},DI=jI(),Ql=`The output should be formatted as a XML file.
162
+ 1. Output should conform to the tags below.
163
+ 2. If tags are not given, make them on your own.
164
+ 3. Remember to always open and close all the tags.
165
+
166
+ As an example, for the tags ["foo", "bar", "baz"]:
167
+ 1. String "<foo>
168
+ <bar>
169
+ <baz></baz>
170
+ </bar>
171
+ </foo>" is a well-formatted instance of the schema.
172
+ 2. String "<foo>
173
+ <bar>
174
+ </foo>" is a badly-formatted instance.
175
+ 3. String "<foo>
176
+ <tag>
177
+ </tag>
178
+ </foo>" is a badly-formatted instance.
179
+
180
+ Here are the output tags:
181
+ \`\`\`
182
+ {tags}
183
+ \`\`\``;var UI=class extends wo{constructor(e){super(e);w(this,"tags");w(this,"lc_namespace",["langchain_core","output_parsers"]);w(this,"lc_serializable",!0);this.tags=e==null?void 0:e.tags}static lc_name(){return"XMLOutputParser"}_diff(e,t){if(t)return e?ku(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return eu(e[0].text)}async parse(e){return eu(e)}getFormatInstructions(){var t;return!!(this.tags&&this.tags.length>0)?Ql.replace("{tags}",((t=this.tags)==null?void 0:t.join(", "))??""):Ql}};const FI=r=>r.split(`
184
+ `).map(e=>e.replace(/^\s+/,"")).join(`
185
+ `).trim(),my=r=>{if(Object.keys(r).length===0)return{};const e={};return r.children.length>0?(e[r.name]=r.children.map(my),e):(e[r.name]=r.text??void 0,e)};function eu(r){const e=FI(r),t=DI.parser(!0);let n={};const s=[];t.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):n=c,o.isSelfClosing||s.push(c)},t.onclosetag=()=>{if(s.length>0){const o=s.pop();s.length===0&&o&&(n=o)}},t.ontext=o=>{if(s.length>0){const c=s[s.length-1];c.text+=o}},t.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 t.write(i).close(),n&&n.name==="?xml"&&(n=n.children[0]),my(n)}var BI={};pe(BI,{AsymmetricStructuredOutputParser:()=>LI,BaseCumulativeTransformOutputParser:()=>wo,BaseLLMOutputParser:()=>yd,BaseOutputParser:()=>yo,BaseTransformOutputParser:()=>ea,BytesOutputParser:()=>OI,CommaSeparatedListOutputParser:()=>$I,CustomListOutputParser:()=>CI,JsonMarkdownStructuredOutputParser:()=>py,JsonOutputParser:()=>Yl,ListOutputParser:()=>ta,MarkdownListOutputParser:()=>PI,NumberedListOutputParser:()=>kI,OutputParserException:()=>zt,StringOutputParser:()=>NI,StructuredOutputParser:()=>ki,XMLOutputParser:()=>UI,XML_FORMAT_INSTRUCTIONS:()=>Ql,parseJsonMarkdown:()=>gl,parsePartialJson:()=>Bi,parseXMLMarkdown:()=>eu});function bo(r,e){if(r.function===void 0)return;let t;if(e!=null&&e.partial)try{t=Bi(r.function.arguments??"{}")}catch{return}else try{t=JSON.parse(r.function.arguments)}catch(s){throw new zt([`Function "${r.function.name}" arguments:`,"",r.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`
186
+ `))}const n={name:r.function.name,args:t,type:"tool_call"};return e!=null&&e.returnId&&(n.id=r.id),n}function gy(r){if(r.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:r.id,type:"function",function:{name:r.name,arguments:JSON.stringify(r.args)}}}function Pi(r,e){var t,n;return{name:(t=r.function)==null?void 0:t.name,args:(n=r.function)==null?void 0:n.arguments,id:r.id,error:e,type:"invalid_tool_call"}}var _y=class extends wo{constructor(e){super(e);w(this,"returnId",!1);w(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);w(this,"lc_serializable",!0);this.returnId=(e==null?void 0:e.returnId)??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){var i;const n=e[0].message;let s;if(_r(n)&&((i=n.tool_calls)!=null&&i.length)?s=n.tool_calls.map(o=>{const{id:c,...l}=o;return this.returnId?{id:c,...l}:l}):n.additional_kwargs.tool_calls!==void 0&&(s=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(c=>bo(c,{returnId:this.returnId,partial:t}))),!s)return[];const a=[];for(const o of s)if(o!==void 0){const c={type:o.name,args:o.args,id:o.id};a.push(c)}return a}},tu=class extends _y{constructor(e){super(e);w(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);w(this,"lc_serializable",!0);w(this,"returnId",!1);w(this,"keyName");w(this,"returnSingle",!1);w(this,"zodSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){var n;if(this.zodSchema===void 0)return e;const t=await Mu(this.zodSchema,e);if(t.success)return t.data;throw new zt(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify((n=t.error)==null?void 0:n.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const n=(await super.parsePartialResult(e)).filter(a=>a.type===this.keyName);let s=n;if(n.length)return this.returnId||(s=n.map(a=>a.args)),this.returnSingle?s[0]:s}async parseResult(e){const n=(await super.parsePartialResult(e,!1)).filter(i=>i.type===this.keyName);let s=n;return n.length?(this.returnId||(s=n.map(i=>i.args)),this.returnSingle?this._validateResult(s[0]):await Promise.all(s.map(i=>this._validateResult(i)))):void 0}},qI={};pe(qI,{JsonOutputKeyToolsParser:()=>tu,JsonOutputToolsParser:()=>_y,convertLangChainToolCallToOpenAI:()=>gy,makeInvalidToolCall:()=>Pi,parseToolCall:()=>bo});var wd=class extends _o{constructor(e){var n,s,a;super(e??{});w(this,"temperature");w(this,"topP");w(this,"frequencyPenalty");w(this,"presencePenalty");w(this,"n");w(this,"logitBias");w(this,"model","gpt-3.5-turbo");w(this,"modelKwargs");w(this,"stop");w(this,"stopSequences");w(this,"user");w(this,"timeout");w(this,"streaming",!1);w(this,"streamUsage",!0);w(this,"maxTokens");w(this,"logprobs");w(this,"topLogprobs");w(this,"apiKey");w(this,"organization");w(this,"__includeRawResponse");w(this,"client");w(this,"clientConfig");w(this,"supportsStrictToolCalling");w(this,"audio");w(this,"modalities");w(this,"reasoning");w(this,"zdrEnabled");w(this,"service_tier");w(this,"promptCacheKey");w(this,"verbosity");w(this,"defaultOptions");w(this,"lc_serializable",!0);const t=typeof((n=e==null?void 0:e.configuration)==null?void 0:n.apiKey)=="string"?(s=e==null?void 0:e.configuration)==null?void 0:s.apiKey:void 0;this.apiKey=(e==null?void 0:e.apiKey)??t??qt("OPENAI_API_KEY"),this.organization=((a=e==null?void 0:e.configuration)==null?void 0:a.organization)??qt("OPENAI_ORGANIZATION"),this.model=(e==null?void 0:e.model)??(e==null?void 0:e.modelName)??this.model,this.modelKwargs=(e==null?void 0:e.modelKwargs)??{},this.timeout=e==null?void 0:e.timeout,this.temperature=(e==null?void 0:e.temperature)??this.temperature,this.topP=(e==null?void 0:e.topP)??this.topP,this.frequencyPenalty=(e==null?void 0:e.frequencyPenalty)??this.frequencyPenalty,this.presencePenalty=(e==null?void 0:e.presencePenalty)??this.presencePenalty,this.logprobs=e==null?void 0:e.logprobs,this.topLogprobs=e==null?void 0:e.topLogprobs,this.n=(e==null?void 0:e.n)??this.n,this.logitBias=e==null?void 0:e.logitBias,this.stop=(e==null?void 0:e.stopSequences)??(e==null?void 0:e.stop),this.stopSequences=this.stop,this.user=e==null?void 0:e.user,this.__includeRawResponse=e==null?void 0:e.__includeRawResponse,this.audio=e==null?void 0:e.audio,this.modalities=e==null?void 0:e.modalities,this.reasoning=e==null?void 0:e.reasoning,this.maxTokens=(e==null?void 0:e.maxCompletionTokens)??(e==null?void 0:e.maxTokens),this.promptCacheKey=(e==null?void 0:e.promptCacheKey)??this.promptCacheKey,this.verbosity=(e==null?void 0:e.verbosity)??this.verbosity,this.disableStreaming=(e==null?void 0:e.disableStreaming)===!0,this.streaming=(e==null?void 0:e.streaming)===!0,this.disableStreaming&&(this.streaming=!1),(e==null?void 0:e.streaming)===!1&&(this.disableStreaming=!0),this.streamUsage=(e==null?void 0:e.streamUsage)??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e==null?void 0:e.configuration},(e==null?void 0:e.supportsStrictToolCalling)!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),(e==null?void 0:e.service_tier)!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=(e==null?void 0:e.zdrEnabled)??!1}_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","service_tier"]}get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","verbosity"]}getLsParams(e){const t=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}_getReasoningParams(e){if(!Vs(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),(e==null?void 0:e.reasoning)!==void 0&&(t={...t,...e.reasoning}),t}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&Rt(e.json_schema.schema)?rA(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){const n={baseURL:this.clientConfig.baseURL},s=zT(n),a={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};a.baseURL||delete a.baseURL,this.client=new he(a)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return vi(e)?QT(e.metadata.customTool):go(e)?(t==null?void 0:t.strict)!==void 0?{...e,function:{...e.function,strict:t.strict}}:e:GT(e,t)}bindTools(e,t){let n;return(t==null?void 0:t.strict)!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling),this.withConfig({tools:e.map(s=>Gu(s)||vi(s)?s:this._convertChatOpenAIToolToCompletionsTool(s,{strict:n})),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((t,n)=>(n&&n.tokenUsage&&(t.tokenUsage.completionTokens+=n.tokenUsage.completionTokens??0,t.tokenUsage.promptTokens+=n.tokenUsage.promptTokens??0,t.tokenUsage.totalTokens+=n.tokenUsage.totalTokens??0),t),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,n=0,s=0;this.model==="gpt-3.5-turbo-0301"?(n=4,s=-1):(n=3,s=1);const a=await Promise.all(e.map(async i=>{var h,f,p,g,_,b;const o=await this.getNumTokens(i.content),c=await this.getNumTokens(Ks(i)),l=i.name!==void 0?s+await this.getNumTokens(i.name):0;let u=o+n+c+l;const d=i;if(d._getType()==="function"&&(u-=2),(h=d.additional_kwargs)!=null&&h.function_call&&(u+=3),(f=d==null?void 0:d.additional_kwargs.function_call)!=null&&f.name&&(u+=await this.getNumTokens((p=d.additional_kwargs.function_call)==null?void 0:p.name)),(g=d.additional_kwargs.function_call)!=null&&g.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse((_=d.additional_kwargs.function_call)==null?void 0:_.arguments)))}catch(m){console.error("Error parsing function arguments",m,JSON.stringify(d.additional_kwargs.function_call)),u+=await this.getNumTokens((b=d.additional_kwargs.function_call)==null?void 0:b.arguments)}return t+=u,u}));return t+=3,{totalCount:t,countPerMessage:a}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async n=>{var s;return(s=n.message.additional_kwargs)!=null&&s.function_call?(await this.getNumTokensFromMessages([n.message])).countPerMessage[0]:await this.getNumTokens(n.message.content)}))).reduce((n,s)=>n+s,0)}async _getEstimatedTokenCountFromPrompt(e,t,n){let s=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&n!=="auto"){const a=VT(t);s+=await this.getNumTokens(a),s+=9}return t&&e.find(a=>a._getType()==="system")&&(s-=4),n==="none"?s+=1:typeof n=="object"&&(s+=await this.getNumTokens(n.name)+4),s}_getStructuredOutputMethod(e){const t={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if((t==null?void 0:t.method)===void 0)return"jsonSchema"}else t.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let n,s;const{schema:a,name:i,includeRaw:o}={...t,schema:e};if((t==null?void 0:t.strict)!==void 0&&t.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");const c=eA(this.model,t==null?void 0:t.method);if(c==="jsonMode"){Rt(a)?s=ki.fromZodSchema(a):s=new Yl;const h=ut(a);n=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:i??"extract",...h}}})}else if(c==="jsonSchema"){const h={name:i??"extract",description:to(a),schema:a,strict:t==null?void 0:t.strict},f=ut(h.schema);if(n=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:h},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:h.name,description:h.description,...f}}}),Rt(a)){const p=ki.fromZodSchema(a);s=vr.from(g=>"parsed"in g.additional_kwargs?g.additional_kwargs.parsed:p)}else s=new Yl}else{let h=i??"extract";if(Rt(a)){const f=ut(a);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:h,description:f.description,parameters:f}}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...f}},...(t==null?void 0:t.strict)!==void 0?{strict:t.strict}:{}}),s=new tu({returnSingle:!0,keyName:h,zodSchema:a})}else{let f;typeof a.name=="string"&&typeof a.parameters=="object"&&a.parameters!=null?(f=a,h=a.name):(h=a.title??h,f={name:h,description:a.description??"",parameters:a});const p=ut(a);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...p}},...(t==null?void 0:t.strict)!==void 0?{strict:t.strict}:{}}),s=new tu({returnSingle:!0,keyName:h})}}if(!o)return n.pipe(s);const l=Mr.assign({parsed:(h,f)=>s.invoke(h.raw,f)}),u=Mr.assign({parsed:()=>null}),d=l.withFallbacks({fallbacks:[u]});return Ln.from([{raw:n},d])}};function Ra(r,e){return r.lc_error_code=e,r.message=`${r.message}
187
+
188
+ Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
189
+ `,r}function yy(r){if(!r||typeof r!="object")return r;let e;return r.constructor.name===so.name&&"message"in r&&typeof r.message=="string"?(e=new Error(r.message),e.name="TimeoutError"):r.constructor.name===bt.name&&"message"in r&&typeof r.message=="string"?(e=new Error(r.message),e.name="AbortError"):"status"in r&&r.status===400&&"message"in r&&typeof r.message=="string"&&r.message.includes("tool_calls")?e=Ra(r,"INVALID_TOOL_RESULTS"):"status"in r&&r.status===401?e=Ra(r,"MODEL_AUTHENTICATION"):"status"in r&&r.status===429?e=Ra(r,"MODEL_RATE_LIMIT"):"status"in r&&r.status===404?e=Ra(r,"MODEL_NOT_FOUND"):e=r,e}function zI(r){if(r.type==="image"){if(r.url)return{type:"image_url",image_url:{url:r.url}};if(r.data)return{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.data}`}}}if(r.type==="audio"&&r.data){const e=Kr(()=>{const[,t]=r.mimeType.split("/");return t==="wav"||t==="mp3"?t:"wav"});return{type:"input_audio",input_audio:{data:r.data.toString(),format:e}}}if(r.type==="file"){if(r.data)return{type:"file",file:{file_data:r.data.toString()}};if(r.fileId)return{type:"file",file:{file_id:r.fileId}}}}function HI(r,e){let t=Ks(r);if(t==="system"&&Vs(e)&&(t="developer"),t==="developer")return{role:"developer",content:r.contentBlocks.filter(s=>s.type==="text")};if(t==="system")return{role:"system",content:r.contentBlocks.filter(s=>s.type==="text")};if(t==="assistant")return{role:"assistant",content:r.contentBlocks.filter(s=>s.type==="text")};if(t==="tool"&&gr.isInstance(r))return{role:"tool",tool_call_id:r.tool_call_id,content:r.contentBlocks.filter(s=>s.type==="text")};if(t==="function")return{role:"function",name:r.name??"",content:r.contentBlocks.filter(s=>s.type==="text").join("")};function*n(s){for(const a of s){a.type==="text"&&(yield{type:"text",text:a.text});const i=zI(a);i&&(yield i)}}return{role:"user",content:Array.from(n(r.contentBlocks))}}function WI(r){var n;const e=_r(r)&&((n=r.response_metadata)==null?void 0:n.model_provider)==="openai";function*t(){const s=Kr(()=>{try{const m=Ks(r);return m==="system"||m==="developer"||m==="assistant"||m==="user"?m:"assistant"}catch{return"assistant"}});let a;const i=new Set,o=new Set,c=new Map,l=new Map;function*u(){if(!a)return;const m=a.content;(typeof m=="string"&&m.length>0||Array.isArray(m)&&m.length>0)&&(yield a),a=void 0}const d=m=>{a||(a={type:"message",role:s,content:[]}),typeof a.content=="string"?a.content=a.content.length>0?[{type:"input_text",text:a.content},...m]:[...m]:a.content.push(...m)},h=m=>{if(typeof m=="string")return m;try{return JSON.stringify(m??{})}catch{return"{}"}},f=m=>{const y=Kr(()=>{var x;const T=(x=m.metadata)==null?void 0:x.detail;return T==="low"||T==="high"||T==="auto"?T:"auto"});if(m.fileId)return{type:"input_image",detail:y,file_id:m.fileId};if(m.url)return{type:"input_image",detail:y,image_url:m.url};if(m.data){const T=typeof m.data=="string"?m.data:Buffer.from(m.data).toString("base64"),x=m.mimeType??"image/png";return{type:"input_image",detail:y,image_url:`data:${x};base64,${T}`}}},p=m=>{var T,x,R;const y=((T=m.metadata)==null?void 0:T.filename)??((x=m.metadata)==null?void 0:x.name)??((R=m.metadata)==null?void 0:R.title);if(m.fileId&&typeof y=="string")return{type:"input_file",file_id:m.fileId,...y?{filename:y}:{}};if(m.url&&typeof y=="string")return{type:"input_file",file_url:m.url,...y?{filename:y}:{}};if(m.data&&typeof y=="string"){const $=typeof m.data=="string"?m.data:Buffer.from(m.data).toString("base64");return{type:"input_file",file_data:`data:${m.mimeType??"application/octet-stream"};base64,${$}`,...y?{filename:y}:{}}}},g=m=>{const y=Kr(()=>{if(Array.isArray(m.summary)){const R=m.summary,$=(R==null?void 0:R.map(E=>E==null?void 0:E.text).filter(E=>typeof E=="string"))??[];if($.length>0)return $}return m.reasoning?[m.reasoning]:[]}),T=y.length>0?y.map(R=>({type:"summary_text",text:R})):[{type:"summary_text",text:""}],x={type:"reasoning",id:m.id??"",summary:T};return m.reasoning&&(x.content=[{type:"reasoning_text",text:m.reasoning}]),x},_=m=>({type:"function_call",name:m.name??"",call_id:m.id??"",arguments:h(m.args)}),b=m=>{const y=h(m.output),T=m.status==="success"?"completed":m.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:m.toolCallId??"",output:y,...T?{status:T}:{}}};for(const m of r.contentBlocks)if(m.type==="text")d([{type:"input_text",text:m.text}]);else if(m.type!=="invalid_tool_call"){if(m.type==="reasoning")yield*u(),yield g(m);else if(m.type==="tool_call"){yield*u();const y=m.id??"";y&&(i.add(y),c.delete(y)),yield _(m)}else if(m.type==="tool_call_chunk"){if(m.id){const y=c.get(m.id)??{name:m.name,args:[]};m.name&&(y.name=m.name),m.args&&y.args.push(m.args),c.set(m.id,y)}}else if(m.type==="server_tool_call"){yield*u();const y=m.id??"";y&&(o.add(y),l.delete(y)),yield _(m)}else if(m.type==="server_tool_call_chunk"){if(m.id){const y=l.get(m.id)??{name:m.name,args:[]};m.name&&(y.name=m.name),m.args&&y.args.push(m.args),l.set(m.id,y)}}else if(m.type==="server_tool_call_result")yield*u(),yield b(m);else if(m.type!=="audio")if(m.type==="file"){const y=p(m);y&&d([y])}else if(m.type==="image"){const y=f(m);y&&d([y])}else if(m.type==="video"){const y=p(m);y&&d([y])}else m.type==="text-plain"?m.text&&d([{type:"input_text",text:m.text}]):m.type==="non_standard"&&e&&(yield*u(),yield m.value)}yield*u();for(const[m,y]of c){if(!m||i.has(m))continue;const T=y.args.join("");!y.name&&!T||(yield{type:"function_call",call_id:m,name:y.name??"",arguments:T})}for(const[m,y]of l){if(!m||o.has(m))continue;const T=y.args.join("");!y.name&&!T||(yield{type:"function_call",call_id:m,name:y.name??"",arguments:T})}}return Array.from(t())}const wy={providerName:"ChatOpenAI",fromStandardTextBlock(r){return{type:"text",text:r.text}},fromStandardImageBlock(r){var e,t;if(r.source_type==="url")return{type:"image_url",image_url:{url:r.url,...(e=r.metadata)!=null&&e.detail?{detail:r.metadata.detail}:{}}};if(r.source_type==="base64")return{type:"image_url",image_url:{url:`data:${r.mime_type??""};base64,${r.data}`,...(t=r.metadata)!=null&&t.detail?{detail:r.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${r.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(r){if(r.source_type==="url"){const e=Zr({dataUrl:r.url});if(!e)throw new Error(`URL audio blocks with source_type ${r.source_type} must be formatted as a data URL for ChatOpenAI`);const t=e.mime_type||r.mime_type||"";let n;try{n=ml(t)}catch{throw new Error(`Audio blocks with source_type ${r.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${r.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:e.data}}}if(r.source_type==="base64"){let e;try{e=ml(r.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${r.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${r.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:r.data}}}throw new Error(`Audio content blocks with source_type ${r.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(r){var e,t,n,s,a,i,o,c,l,u;if(r.source_type==="url"){if(!Zr({dataUrl:r.url}))throw new Error(`URL file blocks with source_type ${r.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:r.url,...(e=r.metadata)!=null&&e.filename||(t=r.metadata)!=null&&t.name?{filename:((n=r.metadata)==null?void 0:n.filename)||((s=r.metadata)==null?void 0:s.name)}:{}}}}if(r.source_type==="base64")return{type:"file",file:{file_data:`data:${r.mime_type??""};base64,${r.data}`,...(a=r.metadata)!=null&&a.filename||(i=r.metadata)!=null&&i.name||(o=r.metadata)!=null&&o.title?{filename:((c=r.metadata)==null?void 0:c.filename)||((l=r.metadata)==null?void 0:l.name)||((u=r.metadata)==null?void 0:u.title)}:{}}};if(r.source_type==="id")return{type:"file",file:{file_id:r.id}};throw new Error(`File content blocks with source_type ${r.source_type} are not supported for ChatOpenAI`)}};function sp(r,e){return r.flatMap(t=>{var i,o;if("output_version"in t.response_metadata&&((i=t.response_metadata)==null?void 0:i.output_version)==="v1")return HI(t);let n=Ks(t);n==="system"&&Vs(e)&&(n="developer");const s=typeof t.content=="string"?t.content:t.content.map(c=>Wt(c)?Fi(c,wy):c),a={role:n,content:s};if(t.name!=null&&(a.name=t.name),t.additional_kwargs.function_call!=null&&(a.function_call=t.additional_kwargs.function_call,a.content=""),_r(t)&&((o=t.tool_calls)!=null&&o.length)?(a.tool_calls=t.tool_calls.map(gy),a.content=""):(t.additional_kwargs.tool_calls!=null&&(a.tool_calls=t.additional_kwargs.tool_calls),t.tool_call_id!=null&&(a.tool_call_id=t.tool_call_id)),t.additional_kwargs.audio&&typeof t.additional_kwargs.audio=="object"&&"id"in t.additional_kwargs.audio){const c={role:"assistant",audio:{id:t.additional_kwargs.audio.id}};return[a,c]}return a})}const ln="__openai_function_call_ids__";var GI=class extends wd{invocationParams(r){var s;let e;(r==null?void 0:r.strict)!==void 0?e=r.strict:this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);const t={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:r==null?void 0:r.previous_response_id,truncation:r==null?void 0:r.truncation,include:r==null?void 0:r.include,tools:(s=r==null?void 0:r.tools)!=null&&s.length?this._reduceChatOpenAITools(r.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:KT(r==null?void 0:r.tool_choice)?r==null?void 0:r.tool_choice:(()=>{const a=yg(r==null?void 0:r.tool_choice);if(typeof a=="object"&&"type"in a){if(a.type==="function")return{type:"function",name:a.function.name};if(a.type==="allowed_tools")return{type:"allowed_tools",mode:a.allowed_tools.mode,tools:a.allowed_tools.tools};if(a.type==="custom")return{type:"custom",name:a.custom.name}}})(),text:(()=>{if(r!=null&&r.text)return r.text;const a=this._getResponseFormat(r==null?void 0:r.response_format);return(a==null?void 0:a.type)==="json_schema"?a.json_schema.schema!=null?{format:{type:"json_schema",schema:a.json_schema.schema,description:a.json_schema.description,name:a.json_schema.name,strict:a.json_schema.strict},verbosity:r==null?void 0:r.verbosity}:void 0:{format:a,verbosity:r==null?void 0:r.verbosity}})(),parallel_tool_calls:r==null?void 0:r.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:(r==null?void 0:r.promptCacheKey)??this.promptCacheKey,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(r);return n!==void 0&&(t.reasoning=n),t}async _generate(r,e){var n;const t=this.invocationParams(e);if(t.stream){const s=this._streamResponseChunks(r,e);let a;for await(const i of s)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},a=(a==null?void 0:a.concat(i))??i;return{generations:a?[a]:[],llmOutput:{estimatedTokenUsage:(n=a==null?void 0:a.message)==null?void 0:n.usage_metadata}}}else{const s=this._convertMessagesToResponsesParams(r),a=await this.completionWithRetry({input:s,...t,stream:!1},{signal:e==null?void 0:e.signal,...e==null?void 0:e.options});return{generations:[{text:a.output_text,message:this._convertResponsesMessageToBaseMessage(a)}],llmOutput:{id:a.id,estimatedTokenUsage:a.usage?{promptTokens:a.usage.input_tokens,completionTokens:a.usage.output_tokens,totalTokens:a.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(r,e,t){const n=await this.completionWithRetry({...this.invocationParams(e),input:this._convertMessagesToResponsesParams(r),stream:!0},e);for await(const s of n){const a=this._convertResponsesDeltaToBaseMessageChunk(s);a!=null&&(yield a,await(t==null?void 0:t.handleLLMNewToken(a.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:a})))}}async completionWithRetry(r,e){return this.caller.call(async()=>{var n,s;const t=this._getClientOptions(e);try{return((s=(n=r.text)==null?void 0:n.format)==null?void 0:s.type)==="json_schema"&&!r.stream?await this.client.responses.parse(r,t):await this.client.responses.create(r,t)}catch(a){throw yy(a)}})}_convertResponsesMessageToBaseMessage(r){if(r.error){const o=new Error(r.error.message);throw o.name=r.error.code,o}let e;const t=[],n=[],s=[],a={model_provider:"openai",model:r.model,created_at:r.created_at,id:r.id,incomplete_details:r.incomplete_details,metadata:r.metadata,object:r.object,status:r.status,user:r.user,service_tier:r.service_tier,model_name:r.model},i={};for(const o of r.output)if(o.type==="message")e=o.id,t.push(...o.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(i.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations}):c.type==="refusal"?(i.refusal=c.refusal,[]):c));else if(o.type==="function_call"){const c={function:{name:o.name,arguments:o.arguments},id:o.call_id};try{n.push(bo(c,{returnId:!0}))}catch(l){let u;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(u=l.message),s.push(Pi(c,u))}i[ln]??(i[ln]={}),o.id&&(i[ln][o.call_id]=o.id)}else if(o.type==="reasoning")i.reasoning=o;else if(o.type==="custom_tool_call"){const c=ZT(o);c?n.push(c):s.push(Pi(o,"Malformed custom tool call"))}else i.tool_outputs??(i.tool_outputs=[]),i.tool_outputs.push(o);return new St({id:e,content:t,tool_calls:n,invalid_tool_calls:s,usage_metadata:Rf(r.usage),additional_kwargs:i,response_metadata:a})}_convertResponsesDeltaToBaseMessageChunk(r){var c,l;const e=[];let t={},n;const s=[],a={model_provider:"openai"},i={};let o;if(r.type==="response.output_text.delta")e.push({type:"text",text:r.delta,index:r.content_index});else if(r.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[r.annotation],index:r.content_index});else if(r.type==="response.output_item.added"&&r.item.type==="message")o=r.item.id;else if(r.type==="response.output_item.added"&&r.item.type==="function_call")s.push({type:"tool_call_chunk",name:r.item.name,args:r.item.arguments,id:r.item.call_id,index:r.output_index}),i[ln]={[r.item.call_id]:r.item.id};else if(r.type==="response.output_item.done"&&["web_search_call","file_search_call","computer_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","image_generation_call","custom_tool_call"].includes(r.item.type))i.tool_outputs=[r.item];else if(r.type==="response.created")a.id=r.response.id,a.model_name=r.response.model,a.model=r.response.model;else if(r.type==="response.completed"){const u=this._convertResponsesMessageToBaseMessage(r.response);n=Rf(r.response.usage),((l=(c=r.response.text)==null?void 0:c.format)==null?void 0:l.type)==="json_schema"&&(i.parsed??(i.parsed=JSON.parse(u.text)));for(const[d,h]of Object.entries(r.response))d!=="id"&&(a[d]=h)}else if(r.type==="response.function_call_arguments.delta"||r.type==="response.custom_tool_call_input.delta")s.push({type:"tool_call_chunk",args:r.delta,index:r.output_index});else if(r.type==="response.web_search_call.completed"||r.type==="response.file_search_call.completed")t={tool_outputs:{id:r.item_id,type:r.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(r.type==="response.refusal.done")i.refusal=r.refusal;else if(r.type==="response.output_item.added"&&"item"in r&&r.item.type==="reasoning"){const u=r.item.summary?r.item.summary.map((d,h)=>({...d,index:h})):void 0;i.reasoning={id:r.item.id,type:r.item.type,...u?{summary:u}:{}}}else if(r.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...r.part,index:r.summary_index}]};else if(r.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:r.delta,type:"summary_text",index:r.summary_index}]};else return r.type==="response.image_generation_call.partial_image",null;return new Xr({text:e.map(u=>u.text).join(""),message:new ke({id:o,content:e,tool_call_chunks:s,usage_metadata:n,additional_kwargs:i,response_metadata:a}),generationInfo:t})}_convertMessagesToResponsesParams(r){return r.flatMap(e=>{var a,i,o,c;const t=e.response_metadata;if((t==null?void 0:t.output_version)==="v1")return WI(e);const n=e.additional_kwargs;let s=Ks(e);if(s==="system"&&Vs(this.model)&&(s="developer"),s==="function")throw new Error("Function messages are not supported in Responses API");if(s==="tool"){const l=e;return(n==null?void 0:n.type)==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof l.content=="string")return{type:"computer_screenshot",image_url:l.content};if(Array.isArray(l.content)){const d=l.content.find(f=>f.type==="computer_screenshot");if(d)return d;const h=l.content.find(f=>f.type==="image_url");if(h)return{type:"computer_screenshot",image_url:typeof h.image_url=="string"?h.image_url:h.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:l.tool_call_id}:(a=l.additional_kwargs)!=null&&a.customTool?{type:"custom_tool_call_output",call_id:l.tool_call_id,output:l.content}:{type:"function_call_output",call_id:l.tool_call_id,id:(i=l.id)!=null&&i.startsWith("fc_")?l.id:void 0,output:typeof l.content!="string"?JSON.stringify(l.content):l.content}}if(s==="assistant"){if(!this.zdrEnabled&&(t==null?void 0:t.output)!=null&&Array.isArray(t==null?void 0:t.output)&&(t==null?void 0:t.output.length)>0&&(t!=null&&t.output.every(p=>"type"in p)))return t==null?void 0:t.output;const l=[];if(n!=null&&n.reasoning&&!this.zdrEnabled){const p=this._convertReasoningSummary(n.reasoning);l.push(p)}let{content:u}=e;n!=null&&n.refusal&&(typeof u=="string"&&(u=[{type:"output_text",text:u,annotations:[]}]),u=[...u,{type:"refusal",refusal:n.refusal}]),(typeof u=="string"||u.length>0)&&l.push({type:"message",role:"assistant",...e.id&&!this.zdrEnabled&&e.id.startsWith("msg_")?{id:e.id}:{},content:Kr(()=>typeof u=="string"?u:u.flatMap(p=>p.type==="text"?{type:"output_text",text:p.text,annotations:p.annotations??[]}:p.type==="output_text"||p.type==="refusal"?p:[]))});const d=n==null?void 0:n[ln];_r(e)&&((o=e.tool_calls)!=null&&o.length)?l.push(...e.tool_calls.map(p=>XT(p)?{type:"custom_tool_call",id:p.call_id,call_id:p.id??"",input:p.args.input,name:p.name}:{type:"function_call",name:p.name,arguments:JSON.stringify(p.args),call_id:p.id,...this.zdrEnabled?{id:d==null?void 0:d[p.id]}:{}})):n!=null&&n.tool_calls&&l.push(...n.tool_calls.map(p=>({type:"function_call",name:p.function.name,call_id:p.id,arguments:p.function.arguments,...this.zdrEnabled?{id:d==null?void 0:d[p.id]}:{}})));const h=(c=t==null?void 0:t.output)!=null&&c.length?t==null?void 0:t.output:n.tool_outputs,f=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(h!=null){const p=h,g=p==null?void 0:p.filter(_=>f.includes(_.type));g.length>0&&l.push(...g)}return l}if(s==="user"||s==="system"||s==="developer"){if(typeof e.content=="string")return{type:"message",role:s,content:e.content};const l=[],u=e.content.flatMap(d=>{if(d.type==="mcp_approval_response"&&l.push({type:"mcp_approval_response",approval_request_id:d.approval_request_id,approve:d.approve}),Wt(d))return Fi(d,wy);if(d.type==="text")return{type:"input_text",text:d.text};if(d.type==="image_url"){const h=Kr(()=>{if(typeof d.image_url=="string")return d.image_url;if(typeof d.image_url=="object"&&d.image_url!==null&&"url"in d.image_url)return d.image_url.url}),f=Kr(()=>{if(typeof d.image_url=="string")return"auto";if(typeof d.image_url=="object"&&d.image_url!==null&&"detail"in d.image_url)return d.image_url.detail});return{type:"input_image",image_url:h,detail:f}}return d.type==="input_text"||d.type==="input_image"||d.type==="input_file"?d:[]});return u.length>0&&l.push({type:"message",role:s,content:u}),l}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${s}`),[]})}_convertReasoningSummary(r){const e=(r.summary.length>1?r.summary.reduce((t,n)=>{const s=t[t.length-1];return s.index===n.index?s.text+=n.text:t.push(n),t},[{...r.summary[0]}]):r.summary).map(t=>Object.fromEntries(Object.entries(t).filter(([n])=>n!=="index")));return{...r,summary:e}}_reduceChatOpenAITools(r,e){const t=[];for(const n of r)if(Gu(n))n.type==="image_generation"&&(e!=null&&e.stream)&&(n.partial_images=1),t.push(n);else if(vi(n)){const s=n.metadata.customTool;t.push({type:"custom",name:s.name,description:s.description,format:s.format})}else go(n)?t.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:(e==null?void 0:e.strict)??null}):wg(n)&&t.push(YT(n));return t}},JI=class extends wd{invocationParams(r,e){var i;let t;(r==null?void 0:r.strict)!==void 0?t=r.strict:this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let n={};(r==null?void 0:r.stream_options)!==void 0?n={stream_options:r.stream_options}:this.streamUsage&&(this.streaming||e!=null&&e.streaming)&&(n={stream_options:{include_usage:!0}});const s={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:(r==null?void 0:r.stop)??this.stopSequences,user:this.user,stream:this.streaming,functions:r==null?void 0:r.functions,function_call:r==null?void 0:r.function_call,tools:(i=r==null?void 0:r.tools)!=null&&i.length?r.tools.map(o=>this._convertChatOpenAIToolToCompletionsTool(o,{strict:t})):void 0,tool_choice:yg(r==null?void 0:r.tool_choice),response_format:this._getResponseFormat(r==null?void 0:r.response_format),seed:r==null?void 0:r.seed,...n,parallel_tool_calls:r==null?void 0:r.parallel_tool_calls,...this.audio||r!=null&&r.audio?{audio:this.audio||(r==null?void 0:r.audio)}:{},...this.modalities||r!=null&&r.modalities?{modalities:this.modalities||(r==null?void 0:r.modalities)}:{},...this.modelKwargs,prompt_cache_key:(r==null?void 0:r.promptCacheKey)??this.promptCacheKey,verbosity:(r==null?void 0:r.verbosity)??this.verbosity};(r==null?void 0:r.prediction)!==void 0&&(s.prediction=r.prediction),this.service_tier!==void 0&&(s.service_tier=this.service_tier),(r==null?void 0:r.service_tier)!==void 0&&(s.service_tier=r.service_tier);const a=this._getReasoningParams(r);return a!==void 0&&a.effort!==void 0&&(s.reasoning_effort=a.effort),Vs(s.model)?s.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:s.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,s}async _generate(r,e,t){var i,o;const n={},s=this.invocationParams(e),a=sp(r,this.model);if(s.stream){const c=this._streamResponseChunks(r,e,t),l={};for await(const g of c){g.message.response_metadata={...g.generationInfo,...g.message.response_metadata};const _=((i=g.generationInfo)==null?void 0:i.completion)??0;l[_]===void 0?l[_]=g:l[_]=l[_].concat(g)}const u=Object.entries(l).sort(([g],[_])=>parseInt(g,10)-parseInt(_,10)).map(([g,_])=>_),{functions:d,function_call:h}=this.invocationParams(e),f=await this._getEstimatedTokenCountFromPrompt(r,d,h),p=await this._getNumTokensFromGenerations(u);return n.input_tokens=f,n.output_tokens=p,n.total_tokens=f+p,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{const c=await this.completionWithRetry({...s,stream:!1,messages:a},{signal:e==null?void 0:e.signal,...e==null?void 0:e.options}),{completion_tokens:l,prompt_tokens:u,total_tokens:d,prompt_tokens_details:h,completion_tokens_details:f}=(c==null?void 0:c.usage)??{};l&&(n.output_tokens=(n.output_tokens??0)+l),u&&(n.input_tokens=(n.input_tokens??0)+u),d&&(n.total_tokens=(n.total_tokens??0)+d),((h==null?void 0:h.audio_tokens)!==null||(h==null?void 0:h.cached_tokens)!==null)&&(n.input_token_details={...(h==null?void 0:h.audio_tokens)!==null&&{audio:h==null?void 0:h.audio_tokens},...(h==null?void 0:h.cached_tokens)!==null&&{cache_read:h==null?void 0:h.cached_tokens}}),((f==null?void 0:f.audio_tokens)!==null||(f==null?void 0:f.reasoning_tokens)!==null)&&(n.output_token_details={...(f==null?void 0:f.audio_tokens)!==null&&{audio:f==null?void 0:f.audio_tokens},...(f==null?void 0:f.reasoning_tokens)!==null&&{reasoning:f==null?void 0:f.reasoning_tokens}});const p=[];for(const g of(c==null?void 0:c.choices)??[]){const b={text:((o=g.message)==null?void 0:o.content)??"",message:this._convertCompletionsMessageToBaseMessage(g.message??{role:"assistant"},c)};b.generationInfo={...g.finish_reason?{finish_reason:g.finish_reason}:{},...g.logprobs?{logprobs:g.logprobs}:{}},_r(b.message)&&(b.message.usage_metadata=n),b.message=new St(Object.fromEntries(Object.entries(b.message).filter(([m])=>!m.startsWith("lc_")))),p.push(b)}return{generations:p,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamResponseChunks(r,e,t){var c,l,u,d,h,f,p,g,_,b;const n=sp(r,this.model),s={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0};let a;const i=await this.completionWithRetry(s,e);let o;for await(const m of i){const y=(c=m==null?void 0:m.choices)==null?void 0:c[0];if(m.usage&&(o=m.usage),!y)continue;const{delta:T}=y;if(!T)continue;const x=this._convertCompletionsDeltaToBaseMessageChunk(T,m,a);a=T.role??a;const R={prompt:e.promptIndex??0,completion:y.index??0};if(typeof x.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const $={...R};y.finish_reason!=null&&($.finish_reason=y.finish_reason,$.system_fingerprint=m.system_fingerprint,$.model_name=m.model,$.service_tier=m.service_tier),this.logprobs&&($.logprobs=y.logprobs);const E=new Xr({message:x,text:x.content,generationInfo:$});yield E,await(t==null?void 0:t.handleLLMNewToken(E.text??"",R,void 0,void 0,void 0,{chunk:E}))}if(o){const m={...((l=o.prompt_tokens_details)==null?void 0:l.audio_tokens)!==null&&{audio:(u=o.prompt_tokens_details)==null?void 0:u.audio_tokens},...((d=o.prompt_tokens_details)==null?void 0:d.cached_tokens)!==null&&{cache_read:(h=o.prompt_tokens_details)==null?void 0:h.cached_tokens}},y={...((f=o.completion_tokens_details)==null?void 0:f.audio_tokens)!==null&&{audio:(p=o.completion_tokens_details)==null?void 0:p.audio_tokens},...((g=o.completion_tokens_details)==null?void 0:g.reasoning_tokens)!==null&&{reasoning:(_=o.completion_tokens_details)==null?void 0:_.reasoning_tokens}};yield new Xr({message:new ke({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(m).length>0&&{input_token_details:m},...Object.keys(y).length>0&&{output_token_details:y}}}),text:""})}if((b=e.signal)!=null&&b.aborted)throw new Error("AbortError")}async completionWithRetry(r,e){const t=this._getClientOptions(e),n=r.response_format&&r.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!r.stream?await this.client.chat.completions.parse(r,t):await this.client.chat.completions.create(r,t)}catch(s){throw yy(s)}})}_convertCompletionsMessageToBaseMessage(r,e){var n,s;const t=r.tool_calls;switch(r.role){case"assistant":{const a=[],i=[];for(const u of t??[])try{a.push(bo(u,{returnId:!0}))}catch(d){i.push(Pi(u,d.message))}const o={function_call:r.function_call,tool_calls:t};this.__includeRawResponse!==void 0&&(o.__raw_response=e);const c={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};r.audio&&(o.audio=r.audio);const l=nA(r.content||"",(s=(n=e.choices)==null?void 0:n[0])==null?void 0:s.message);return new St({content:l,tool_calls:a,invalid_tool_calls:i,additional_kwargs:o,response_metadata:c,id:e.id})}default:return new tn(r.content||"",r.role??"unknown")}}_convertCompletionsDeltaToBaseMessageChunk(r,e,t){var o,c;const n=r.role??t,s=r.content??"";let a;r.function_call?a={function_call:r.function_call}:r.tool_calls?a={tool_calls:r.tool_calls}:a={},this.__includeRawResponse&&(a.__raw_response=e),r.audio&&(a.audio={...r.audio,index:e.choices[0].index});const i={model_provider:"openai",usage:{...e.usage}};if(n==="user")return new zs({content:s,response_metadata:i});if(n==="assistant"){const l=[];if(Array.isArray(r.tool_calls))for(const u of r.tool_calls)l.push({name:(o=u.function)==null?void 0:o.name,args:(c=u.function)==null?void 0:c.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new ke({content:s,tool_call_chunks:l,additional_kwargs:a,id:e.id,response_metadata:i})}else return n==="system"?new Pr({content:s,response_metadata:i}):n==="developer"?new Pr({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new qs({content:s,additional_kwargs:a,name:r.name,response_metadata:i}):n==="tool"?new Fs({content:s,additional_kwargs:a,tool_call_id:r.tool_call_id,response_metadata:i}):new Bs({content:s,role:n,response_metadata:i})}},VI=class by extends wd{constructor(t){super(t);w(this,"useResponsesApi",!1);w(this,"responses");w(this,"completions");this.fields=t,this.useResponsesApi=(t==null?void 0:t.useResponsesApi)??!1,this.responses=(t==null?void 0:t.responses)??new GI(t),this.completions=(t==null?void 0:t.completions)??new JI(t)}get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}_useResponsesApi(t){var i,o,c,l,u;const n=(i=t==null?void 0:t.tools)==null?void 0:i.some(Gu),s=(t==null?void 0:t.previous_response_id)!=null||(t==null?void 0:t.text)!=null||(t==null?void 0:t.truncation)!=null||(t==null?void 0:t.include)!=null||((o=t==null?void 0:t.reasoning)==null?void 0:o.summary)!=null||((c=this.reasoning)==null?void 0:c.summary)!=null,a=((l=t==null?void 0:t.tools)==null?void 0:l.some(wg))||((u=t==null?void 0:t.tools)==null?void 0:u.some(vi));return this.useResponsesApi||n||s||a}getLsParams(t){const n=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.getLsParams(n):this.completions.getLsParams(n)}invocationParams(t){const n=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.invocationParams(n):this.completions.invocationParams(n)}async _generate(t,n,s){return this._useResponsesApi(n)?this.responses._generate(t,n):this.completions._generate(t,n,s)}async*_streamResponseChunks(t,n,s){if(this._useResponsesApi(n)){yield*this.responses._streamResponseChunks(t,this._combineCallOptions(n),s);return}yield*this.completions._streamResponseChunks(t,this._combineCallOptions(n),s)}withConfig(t){const n=new by(this.fields);return n.defaultOptions={...this.defaultOptions,...t},n}},KI={};pe(KI,{BaseLLM:()=>vy,LLM:()=>ZI});var vy=class ms extends _d{constructor(){super(...arguments);w(this,"lc_namespace",["langchain","llms",this._llmType()])}async invoke(t,n){const s=ms._convertInputToPromptValue(t);return(await this.generatePrompt([s],n,n==null?void 0:n.callbacks)).generations[0][0].text}async*_streamResponseChunks(t,n,s){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(t){const[n,s]=super._separateRunnableConfigFromCallOptions(t);return s.signal=n.signal,[n,s]}async*_streamIterator(t,n){if(this._streamResponseChunks===ms.prototype._streamResponseChunks)yield this.invoke(t,n);else{const s=ms._convertInputToPromptValue(t),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(n),o=await dt.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),c={options:i,invocation_params:this==null?void 0:this.invocationParams(i),batch_size:1},l=await(o==null?void 0:o.handleLLMStart(this.toJSON(),[s.toString()],a.runId,void 0,c,void 0,void 0,a.runName));let u=new $n({text:""});try{for await(const d of this._streamResponseChunks(s.toString(),i,l==null?void 0:l[0]))u?u=u.concat(d):u=d,typeof d.text=="string"&&(yield d.text)}catch(d){throw await Promise.all((l??[]).map(h=>h==null?void 0:h.handleLLMError(d))),d}await Promise.all((l??[]).map(d=>d==null?void 0:d.handleLLMEnd({generations:[[u]]})))}}async generatePrompt(t,n,s){const a=t.map(i=>i.toString());return this.generate(a,n,s)}invocationParams(t){return{}}_flattenLLMResult(t){const n=[];for(let s=0;s<t.generations.length;s+=1){const a=t.generations[s];if(s===0)n.push({generations:[a],llmOutput:t.llmOutput});else{const i=t.llmOutput?{...t.llmOutput,tokenUsage:{}}:void 0;n.push({generations:[a],llmOutput:i})}}return n}async _generateUncached(t,n,s,a){let i;if(a!==void 0&&a.length===t.length)i=a;else{const u=await dt.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),d={options:n,invocation_params:this==null?void 0:this.invocationParams(n),batch_size:t.length};i=await(u==null?void 0:u.handleLLMStart(this.toJSON(),t,s.runId,void 0,d,void 0,void 0,s==null?void 0:s.runName))}const o=!!(i!=null&&i[0].handlers.find(Su));let c;if(o&&t.length===1&&this._streamResponseChunks!==ms.prototype._streamResponseChunks)try{const u=await this._streamResponseChunks(t[0],n,i==null?void 0:i[0]);let d;for await(const h of u)d===void 0?d=h:d=Lr(d,h);if(d===void 0)throw new Error("Received empty response from chat model call.");c={generations:[[d]],llmOutput:{}},await(i==null?void 0:i[0].handleLLMEnd(c))}catch(u){throw await(i==null?void 0:i[0].handleLLMError(u)),u}else{try{c=await this._generate(t,n,i==null?void 0:i[0])}catch(d){throw await Promise.all((i??[]).map(h=>h==null?void 0:h.handleLLMError(d))),d}const u=this._flattenLLMResult(c);await Promise.all((i??[]).map((d,h)=>d==null?void 0:d.handleLLMEnd(u[h])))}const l=(i==null?void 0:i.map(u=>u.runId))||void 0;return Object.defineProperty(c,Ns,{value:l?{runIds:l}:void 0,configurable:!0}),c}async _generateCached({prompts:t,cache:n,llmStringKey:s,parsedOptions:a,handledOptions:i,runId:o}){const c=await dt.configure(i.callbacks,this.callbacks,i.tags,this.tags,i.metadata,this.metadata,{verbose:this.verbose}),l={options:a,invocation_params:this==null?void 0:this.invocationParams(a),batch_size:t.length},u=await(c==null?void 0:c.handleLLMStart(this.toJSON(),t,o,void 0,l,void 0,void 0,i==null?void 0:i.runName)),d=[],f=(await Promise.allSettled(t.map(async(_,b)=>{const m=await n.lookup(_,s);return m==null&&d.push(b),m}))).map((_,b)=>({result:_,runManager:u==null?void 0:u[b]})).filter(({result:_})=>_.status==="fulfilled"&&_.value!=null||_.status==="rejected"),p=[];await Promise.all(f.map(async({result:_,runManager:b},m)=>{if(_.status==="fulfilled"){const y=_.value;return p[m]=y.map(T=>(T.generationInfo={...T.generationInfo,tokenUsage:{}},T)),y.length&&await(b==null?void 0:b.handleLLMNewToken(y[0].text)),b==null?void 0:b.handleLLMEnd({generations:[y]},void 0,void 0,void 0,{cached:!0})}else return await(b==null?void 0:b.handleLLMError(_.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(_.reason)}));const g={generations:p,missingPromptIndices:d,startedRunManagers:u};return Object.defineProperty(g,Ns,{value:u?{runIds:u==null?void 0:u.map(_=>_.runId)}:void 0,configurable:!0}),g}async generate(t,n,s){if(!Array.isArray(t))throw new Error("Argument 'prompts' is expected to be a string[]");let a;Array.isArray(n)?a={stop:n}:a=n;const[i,o]=this._separateRunnableConfigFromCallOptionsCompat(a);if(i.callbacks=i.callbacks??s,!this.cache)return this._generateUncached(t,o,i);const{cache:c}=this,l=this._getSerializedCacheKeyParametersForCall(o),{generations:u,missingPromptIndices:d,startedRunManagers:h}=await this._generateCached({prompts:t,cache:c,llmStringKey:l,parsedOptions:o,handledOptions:i,runId:i.runId});let f={};if(d.length>0){const p=await this._generateUncached(d.map(g=>t[g]),o,i,h!==void 0?d.map(g=>h==null?void 0:h[g]):void 0);await Promise.all(p.generations.map(async(g,_)=>{const b=d[_];return u[b]=g,c.update(t[b],l,g)})),f=p.llmOutput??{}}return{generations:u,llmOutput:f}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},ZI=class extends vy{async _generate(r,e,t){return{generations:await Promise.all(r.map((s,a)=>this._call(s,{...e,promptIndex:a},t).then(i=>[{text:i}])))}}},XI={};pe(XI,{chunkArray:()=>YI});const YI=(r,e)=>r.reduce((t,n,s)=>{const a=Math.floor(s/e),i=t[a]||[];return t[a]=i.concat([n]),t},[]);var QI={};pe(QI,{Embeddings:()=>eR});var eR=class{constructor(r){w(this,"caller");this.caller=new Js(r??{})}},tR={};pe(tR,{BaseToolkit:()=>rR,DynamicStructuredTool:()=>Ty,DynamicTool:()=>Ey,StructuredTool:()=>bd,Tool:()=>Sy,ToolInputParsingException:()=>ci,isLangChainTool:()=>Zs,isRunnableToolLike:()=>Hu,isStructuredTool:()=>zu,isStructuredToolParams:()=>Wu,tool:()=>nR});var bd=class extends gd{constructor(e){super(e??{});w(this,"returnDirect",!1);w(this,"verboseParsingErrors",!1);w(this,"responseFormat","content");w(this,"defaultConfig");this.verboseParsingErrors=(e==null?void 0:e.verboseParsingErrors)??this.verboseParsingErrors,this.responseFormat=(e==null?void 0:e.responseFormat)??this.responseFormat,this.defaultConfig=(e==null?void 0:e.defaultConfig)??this.defaultConfig,this.metadata=(e==null?void 0:e.metadata)??this.metadata}get lc_namespace(){return["langchain","tools"]}async invoke(e,t){let n,s=ge(fi(this.defaultConfig,t));return ws(e)?(n=e.args,s={...s,toolCall:e}):n=e,this.call(n,s)}async call(e,t,n){const s=ws(e)?e.args:e;let a;if(Rt(this.schema))try{a=await eo(this.schema,s)}catch(p){let g="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(g=`${g}
190
+ Details: ${p.message}`),p instanceof Error&&p.constructor.name==="ZodError"&&(g=`${g}
191
+
192
+ ${kS(p)}`),new ci(g,JSON.stringify(e))}else{const p=Ie(s,this.schema);if(!p.valid){let g="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(g=`${g}
193
+ Details: ${p.errors.map(_=>`${_.keywordLocation}: ${_.error}`).join(`
194
+ `)}`),new ci(g,JSON.stringify(e))}a=s}const i=Ki(t),o=dt.configure(i.callbacks,this.callbacks,i.tags||n,this.tags,i.metadata,this.metadata,{verbose:this.verbose}),c=await(o==null?void 0:o.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),i.runId,void 0,void 0,void 0,i.runName));delete i.runId;let l;try{l=await this._call(a,c,i)}catch(p){throw await(c==null?void 0:c.handleToolError(p)),p}let u,d;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[u,d]=l;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
195
+ Result: ${JSON.stringify(l)}`);else u=l;let h;ws(e)&&(h=e.id),!h&&sb(i)&&(h=i.toolCall.id);const f=sR({content:u,artifact:d,toolCallId:h,name:this.name,metadata:this.metadata});return await(c==null?void 0:c.handleToolEnd(f)),f}},Sy=class extends bd{constructor(e){super(e);w(this,"schema",$r({input:In().optional()}).transform(e=>e.input))}call(e,t){const n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,t)}},Ey=class extends Sy{constructor(e){super(e);w(this,"name");w(this,"description");w(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,t){const n=Ki(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}async _call(e,t,n){return this.func(e,t,n)}},Ty=class extends bd{constructor(e){super(e);w(this,"name");w(this,"description");w(this,"func");w(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,t,n){const s=Ki(t);return s.runName===void 0&&(s.runName=this.name),super.call(e,s,n)}_call(e,t,n){return this.func(e,t,n)}},rR=class{getTools(){return this.tools}};function nR(r,e){var i;const t=ju(e.schema),n=Es(e.schema);if(!e.schema||t||n)return new Ey({...e,description:e.description??((i=e.schema)==null?void 0:i.description)??`${e.name} tool`,func:async(o,c,l)=>new Promise((u,d)=>{const h=Te(l,{callbacks:c==null?void 0:c.getChild()});Jt.runWithConfig(yr(h),async()=>{try{u(r(o,h))}catch(f){d(f)}})})});const s=e.schema,a=e.description??e.schema.description??`${e.name} tool`;return new Ty({...e,description:a,schema:s,func:async(o,c,l)=>new Promise((u,d)=>{l!=null&&l.signal&&l.signal.addEventListener("abort",()=>d(ks(l.signal)));const h=Te(l,{callbacks:c==null?void 0:c.getChild()});Jt.runWithConfig(yr(h),async()=>{var f;try{const p=await r(o,h);if((f=l==null?void 0:l.signal)!=null&&f.aborted)return;u(p)}catch(p){d(p)}})})})}function sR(r){const{content:e,artifact:t,toolCallId:n,metadata:s}=r;return n&&!_u(e)?typeof e=="string"||Array.isArray(e)&&e.every(a=>typeof a=="object")?new gr({status:"success",content:e,artifact:t,tool_call_id:n,name:r.name,metadata:s}):new gr({status:"success",content:aR(e),artifact:t,tool_call_id:n,name:r.name,metadata:s}):e}function aR(r){try{return JSON.stringify(r,null,2)??""}catch{return`${r}`}}const Di=class Di{constructor(e){w(this,"llm");w(this,"modelName");const{apiKey:t,model:n=Di.DEFAULT_MODEL,temperature:s=0}=e;if(!t||t.trim()==="")throw new Error("OpenAI API key is required");this.modelName=n,this.llm=new VI({apiKey:t,model:n,temperature:s})}async parseStructuredData(e,t){try{return await this.llm.withStructuredOutput(t).invoke(e)}catch(n){throw console.error("[OpenAIModel] Parsing failed:",n),n}}};w(Di,"DEFAULT_MODEL","gpt-4o-mini");let ru=Di;var ap=class extends yd{constructor(e){super(e);w(this,"lc_namespace",["langchain","anthropic","output_parsers"]);w(this,"returnId",!1);w(this,"keyName");w(this,"returnSingle",!1);w(this,"zodSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}static lc_name(){return"AnthropicToolsOutputParser"}async _validateResult(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(s){throw new zt(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(s.message)}`,e)}else t=e;if(this.zodSchema===void 0)return t;const n=await Mu(this.zodSchema,t);if(n.success)return n.data;throw new zt(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(e){const t=e.flatMap(a=>{const{message:i}=a;return Array.isArray(i.content)?xy(i.content)[0]:[]});if(t[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=t;return await this._validateResult(n.args)}};function xy(r){const e=[];for(const t of r)t.type==="tool_use"&&e.push({name:t.name,args:t.input,id:t.id,type:"tool_call"});return e}function iR(r){if(r)return r==="any"?{type:"any"}:r==="auto"?{type:"auto"}:r==="none"?{type:"none"}:typeof r=="string"?{type:"tool",name:r}:r}function oR(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="thinking"}function cR(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="redacted_thinking"}function lR(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="search_result"}function uR(r){return typeof r!="object"||r==null||!("type"in r)||r.type!=="image"||!("source"in r)||typeof r.source!="object"||r.source==null||!("type"in r.source)?!1:r.source.type==="base64"?!(!("media_type"in r.source)||typeof r.source.media_type!="string"||!("data"in r.source)||typeof r.source.data!="string"):r.source.type==="url"?!(!("url"in r.source)||typeof r.source.url!="string"):!1}const dR={providerName:"anthropic",fromStandardTextBlock(r){return{type:"text",text:r.text,..."citations"in(r.metadata??{})?{citations:r.metadata.citations}:{},..."cache_control"in(r.metadata??{})?{cache_control:r.metadata.cache_control}:{}}},fromStandardImageBlock(r){if(r.source_type==="url"){const e=Zr({dataUrl:r.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(r.metadata??{})?{cache_control:r.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:r.url},..."cache_control"in(r.metadata??{})?{cache_control:r.metadata.cache_control}:{}}}else{if(r.source_type==="base64")return{type:"image",source:{type:"base64",data:r.data,media_type:r.mime_type??""},..."cache_control"in(r.metadata??{})?{cache_control:r.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${r.source_type}`)}},fromStandardFileBlock(r){const e=(r.mime_type??"").split(";")[0];if(r.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:r.url},..."cache_control"in(r.metadata??{})?{cache_control:r.metadata.cache_control}:{},..."citations"in(r.metadata??{})?{citations:r.metadata.citations}:{},..."context"in(r.metadata??{})?{context:r.metadata.context}:{},..."title"in(r.metadata??{})?{title:r.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${r.mime_type}`)}else if(r.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:r.text,media_type:r.mime_type??""},..."cache_control"in(r.metadata??{})?{cache_control:r.metadata.cache_control}:{},..."citations"in(r.metadata??{})?{citations:r.metadata.citations}:{},..."context"in(r.metadata??{})?{context:r.metadata.context}:{},..."title"in(r.metadata??{})?{title:r.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${r.mime_type}`)}else if(r.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:r.data,media_type:"application/pdf"},..."cache_control"in(r.metadata??{})?{cache_control:r.metadata.cache_control}:{},..."citations"in(r.metadata??{})?{citations:r.metadata.citations}:{},..."context"in(r.metadata??{})?{context:r.metadata.context}:{},..."title"in(r.metadata??{})?{title:r.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:r.data,media_type:e}}]},..."cache_control"in(r.metadata??{})?{cache_control:r.metadata.cache_control}:{},..."citations"in(r.metadata??{})?{citations:r.metadata.citations}:{},..."context"in(r.metadata??{})?{context:r.metadata.context}:{},..."title"in(r.metadata??{})?{title:r.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${r.mime_type}`)}else throw new Error(`Unsupported file source type: ${r.source_type}`)}},hR=r=>r();function fR(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="citation"}function pR(r){function*e(){for(const t of r)fR(t)&&(t.source==="char"?yield{type:"char_location",file_id:t.url??"",start_char_index:t.startIndex??0,end_char_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??""}:t.source==="page"?yield{type:"page_location",file_id:t.url??"",start_page_number:t.startIndex??0,end_page_number:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??""}:t.source==="block"?yield{type:"content_block_location",file_id:t.url??"",start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??""}:t.source==="url"?yield{type:"web_search_result_location",url:t.url??"",title:t.title??null,encrypted_index:String(t.startIndex??0),cited_text:t.citedText??""}:t.source==="search"&&(yield{type:"search_result_location",title:t.title??null,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,search_result_index:0,source:t.source??"",cited_text:t.citedText??""}))}return Array.from(e())}function zn(r){return typeof r=="string"?r:mR(r)}function mR(r){const e=[];for(let t=0,{length:n}=r;t<n;t++)e.push(String.fromCharCode(r[t]));return btoa(e.join(""))}function tl(r){return(r??"").split(";")[0].toLowerCase()}function gs(r,e){if(r!=null&&typeof r=="object"&&e in r)return r[e]}function un(r,e){const t=gs(e,"cache_control");t!==void 0&&(r.cache_control=t);const n=gs(e,"citations");n!==void 0&&(r.citations=n);const s=gs(e,"context");s!==void 0&&(r.context=s);const a=gs(e,"title");return a!==void 0&&(r.title=a),r}function rl(r,e){const t=gs(e,"cache_control");return t!==void 0&&(r.cache_control=t),r}function ip(r){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(r)}function gR(r){const e=[],t=r.response_metadata,n="model_provider"in t&&(t==null?void 0:t.model_provider)==="anthropic";for(const s of r.contentBlocks)if(s.type==="text")s.annotations?e.push({type:"text",text:s.text,citations:pR(s.annotations)}):e.push({type:"text",text:s.text});else if(s.type==="tool_call")e.push({type:"tool_use",id:s.id??"",name:s.name,input:s.args});else if(s.type==="tool_call_chunk"){const a=hR(()=>{if(typeof s.args!="string")return s.args;try{return JSON.parse(s.args)}catch{return{}}});e.push({type:"tool_use",id:s.id??"",name:s.name??"",input:a})}else if(s.type==="reasoning"&&n)e.push({type:"thinking",thinking:s.reasoning,signature:String(s.signature)});else if(s.type==="server_tool_call"&&n)s.name==="web_search"?e.push({type:"server_tool_use",name:s.name,id:s.id??"",input:s.args}):s.name==="code_execution"&&e.push({type:"server_tool_use",name:s.name,id:s.id??"",input:s.args});else if(s.type==="server_tool_call_result"&&n)if(s.name==="web_search"&&Array.isArray(s.output.urls)){const a=s.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:s.toolCallId??"",content:a})}else s.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId??"",content:s.output}):s.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:s.toolCallId??"",content:s.output});else{if(s.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(s.type==="file"){const a=s.metadata;if(s.fileId){e.push(un({type:"document",source:{type:"file",file_id:s.fileId}},a));continue}if(s.url){const i=tl(s.mimeType);if(i==="application/pdf"||i===""){e.push(un({type:"document",source:{type:"url",url:s.url}},a));continue}}if(s.data){const i=tl(s.mimeType);if(i===""||i==="application/pdf")e.push(un({type:"document",source:{type:"base64",data:zn(s.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(un({type:"document",source:{type:"text",data:zn(s.data),media_type:"text/plain"}},a));else if(ip(i))e.push(un({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:zn(s.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(s.type==="image"){const a=s.metadata;if(s.fileId){e.push(rl({type:"image",source:{type:"file",file_id:s.fileId}},a));continue}if(s.url){e.push(rl({type:"image",source:{type:"url",url:s.url}},a));continue}if(s.data){const i=tl(s.mimeType)||"image/png";ip(i)&&e.push(rl({type:"image",source:{type:"base64",data:zn(s.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else s.type==="video"||(s.type==="text-plain"?s.data&&e.push(un({type:"document",source:{type:"text",data:zn(s.data),media_type:"text/plain"}},s.metadata)):s.type==="non_standard"&&n&&e.push(s.value))}return e}function op(r){const e=Zr({dataUrl:r});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let t;try{t=new URL(r)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(r)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
196
+
197
+ `))}if(t.protocol==="http:"||t.protocol==="https:")return{type:"url",url:r};throw new Error([`Invalid image URL protocol: ${JSON.stringify(t.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
198
+
199
+ `))}function _R(r){const e=[];for(const t of r)if(t._getType()==="tool")if(typeof t.content=="string"){const n=e[e.length-1];(n==null?void 0:n._getType())==="human"&&Array.isArray(n.content)&&"type"in n.content[0]&&n.content[0].type==="tool_result"?n.content.push({type:"tool_result",content:t.content,tool_use_id:t.tool_call_id}):e.push(new Gt({content:[{type:"tool_result",content:t.content,tool_use_id:t.tool_call_id}]}))}else e.push(new Gt({content:[{type:"tool_result",...t.content!=null?{content:nu(t)}:{},tool_use_id:t.tool_call_id}]}));else e.push(t);return e}function cp(r){if(r.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:r.id,name:r.name,input:r.args}}function*yR(r){const e=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],t=["text","text_delta"];for(const n of r){Wt(n)&&(yield Fi(n,dR));const s="cache_control"in n?n.cache_control:void 0;if(n.type==="image_url"){let a;typeof n.image_url=="string"?a=op(n.image_url):typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(a=op(n.image_url.url)),a&&(yield{type:"image",source:a,...s?{cache_control:s}:{}})}else{if(uR(n))return n;if(n.type==="document")yield{...n,...s?{cache_control:s}:{}};else if(oR(n))yield{type:"thinking",thinking:n.thinking,signature:n.signature,...s?{cache_control:s}:{}};else if(cR(n))yield{type:"redacted_thinking",data:n.data,...s?{cache_control:s}:{}};else if(lR(n))yield{type:"search_result",title:n.title,source:n.source,..."cache_control"in n&&n.cache_control?{cache_control:n.cache_control}:{},..."citations"in n&&n.citations?{citations:n.citations}:{},content:n.content};else if(t.find(a=>a===n.type)&&"text"in n)yield{type:"text",text:n.text,...s?{cache_control:s}:{},..."citations"in n&&n.citations?{citations:n.citations}:{}};else if(e.find(a=>a===n.type)){const a={...n};if("index"in a&&delete a.index,a.type==="input_json_delta"&&(a.type="tool_use"),"input"in a&&typeof a.input=="string")try{a.input=JSON.parse(a.input)}catch{a.input={}}yield{...a,...s?{cache_control:s}:{}}}else n.type==="container_upload"&&(yield{...n,...s?{cache_control:s}:{}})}}}function nu(r){const{content:e}=r;return typeof e=="string"?e:Array.from(yR(e))}function lp(r){const e=_R(r);let t;e.length>0&&e[0]._getType()==="system"&&(t=r[0].content);const s=(t!==void 0?e.slice(1):e).map(a=>{var o,c;let i;if(a._getType()==="human")i="user";else if(a._getType()==="ai")i="assistant";else if(a._getType()==="tool")i="user";else throw a._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${a.type}" is not supported.`);if(_r(a)&&((o=a.response_metadata)==null?void 0:o.output_version)==="v1")return{role:i,content:gR(a)};if(_r(a)&&((c=a.tool_calls)!=null&&c.length)){if(typeof a.content=="string")return a.content===""?{role:i,content:a.tool_calls.map(cp)}:{role:i,content:[{type:"text",text:a.content},...a.tool_calls.map(cp)]};{const{content:l}=a;return!a.tool_calls.every(d=>l.find(h=>(h.type==="tool_use"||h.type==="input_json_delta"||h.type==="server_tool_use")&&h.id===d.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:i,content:nu(a)}}}else return{role:i,content:nu(a)}});return{messages:wR(s),system:t}}function wR(r){if(!r||r.length<=1)return r;const e=[];let t=r[0];const n=a=>typeof a=="string"?[{type:"text",text:a}]:a,s=a=>a.role!=="user"||typeof a.content=="string"?!1:Array.isArray(a.content)&&a.content.every(i=>i.type==="tool_result");for(let a=1;a<r.length;a+=1){const i=r[a];s(t)&&s(i)?t={...t,content:[...n(t.content),...n(i.content)]}:(e.push(t),t=i)}return e.push(t),e}function bR(r,e){var n;const t={model_provider:"anthropic"};if(r.type==="message_start"){const{content:s,usage:a,...i}=r.message,o={};for(const[h,f]of Object.entries(i))f!=null&&(o[h]=f);const{input_tokens:c,output_tokens:l,...u}=a??{},d={input_tokens:c,output_tokens:l,total_tokens:c+l,input_token_details:{cache_creation:u.cache_creation_input_tokens,cache_read:u.cache_read_input_tokens}};return{chunk:new ke({content:e.coerceContentToString?"":[],additional_kwargs:o,usage_metadata:e.streamUsage?d:void 0,response_metadata:{...t,usage:{...u}},id:r.message.id})}}else if(r.type==="message_delta"){const s={input_tokens:0,output_tokens:r.usage.output_tokens,total_tokens:r.usage.output_tokens,input_token_details:{cache_creation:r.usage.cache_creation_input_tokens,cache_read:r.usage.cache_read_input_tokens}},a="context_management"in r.delta?{context_management:r.delta.context_management}:void 0;return{chunk:new ke({content:e.coerceContentToString?"":[],response_metadata:a,additional_kwargs:{...r.delta},usage_metadata:e.streamUsage?s:void 0})}}else if(r.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(r.content_block.type)){const s=r.content_block;let a;return s.type==="tool_use"?a=[{id:s.id,index:r.index,name:s.name,args:""}]:a=[],{chunk:new ke({content:e.coerceContentToString?"":[{index:r.index,...r.content_block,input:s.type==="server_tool_use"||s.type==="tool_use"?"":void 0}],response_metadata:t,additional_kwargs:{},tool_call_chunks:a})}}else if(r.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(r.delta.type)){if(e.coerceContentToString&&"text"in r.delta)return{chunk:new ke({content:r.delta.text})};{const s=r.delta;return"citation"in s&&(s.citations=[s.citation],delete s.citation),s.type==="thinking_delta"||s.type==="signature_delta"?{chunk:new ke({content:[{index:r.index,...s,type:"thinking"}],response_metadata:t})}:{chunk:new ke({content:[{index:r.index,...s,type:"text"}],response_metadata:t})}}}else{if(r.type==="content_block_delta"&&r.delta.type==="input_json_delta")return{chunk:new ke({content:e.coerceContentToString?"":[{index:r.index,input:r.delta.partial_json,type:r.delta.type}],response_metadata:t,additional_kwargs:{},tool_call_chunks:[{index:r.index,args:r.delta.partial_json}]})};if(r.type==="content_block_start"&&r.content_block.type==="text"){const s=(n=r.content_block)==null?void 0:n.text;if(s!==void 0)return{chunk:new ke({content:e.coerceContentToString?s:[{index:r.index,...r.content_block}],response_metadata:t,additional_kwargs:{}})}}else{if(r.type==="content_block_start"&&r.content_block.type==="redacted_thinking")return{chunk:new ke({content:e.coerceContentToString?"":[{index:r.index,...r.content_block}],response_metadata:t})};if(r.type==="content_block_start"&&r.content_block.type==="thinking"){const s=r.content_block.thinking;return{chunk:new ke({content:e.coerceContentToString?s:[{index:r.index,...r.content_block}],response_metadata:t})}}}}return null}function vR(r,e){const t={...e,model_provider:"anthropic"},n=e.usage,s=n!=null?{input_tokens:n.input_tokens??0,output_tokens:n.output_tokens??0,total_tokens:(n.input_tokens??0)+(n.output_tokens??0),input_token_details:{cache_creation:n.cache_creation_input_tokens,cache_read:n.cache_read_input_tokens}}:void 0;if(r.length===1&&r[0].type==="text")return[{text:r[0].text,message:new St({content:r[0].text,additional_kwargs:e,usage_metadata:s,response_metadata:t,id:e.id})}];{const a=xy(r);return[{text:"",message:new St({content:r,additional_kwargs:e,tool_calls:a,usage_metadata:s,response_metadata:t,id:e.id})}]}}function Oa(r,e){return r.lc_error_code=e,r.message=`${r.message}
200
+
201
+ Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
202
+ `,r}function up(r){let e;return r.status===400&&r.message.includes("tool")?e=Oa(r,"INVALID_TOOL_RESULTS"):r.status===401?e=Oa(r,"MODEL_AUTHENTICATION"):r.status===404?e=Oa(r,"MODEL_NOT_FOUND"):r.status===429?e=Oa(r,"MODEL_RATE_LIMIT"):e=r,e}function G(r,e,t,n,s){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}function O(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}let Ay=function(){const{crypto:r}=globalThis;if(r!=null&&r.randomUUID)return Ay=r.randomUUID.bind(r),r.randomUUID();const e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function js(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}const su=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){const e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};class ue extends Error{}class Xe extends ue{constructor(e,t,n,s){super(`${Xe.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("request-id"),this.error=t}static makeMessage(e,t,n){const s=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new vo({message:n,cause:su(t)});const a=t;return e===400?new Ry(e,a,n,s):e===401?new Oy(e,a,n,s):e===403?new $y(e,a,n,s):e===404?new Cy(e,a,n,s):e===409?new ky(e,a,n,s):e===422?new Py(e,a,n,s):e===429?new Ny(e,a,n,s):e>=500?new Ly(e,a,n,s):new Xe(e,a,n,s)}}class Bt extends Xe{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class vo extends Xe{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Iy extends vo{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ry extends Xe{}class Oy extends Xe{}class $y extends Xe{}class Cy extends Xe{}class ky extends Xe{}class Py extends Xe{}class Ny extends Xe{}class Ly extends Xe{}const SR=/^[a-z][a-z0-9+.-]*:/i,ER=r=>SR.test(r);let au=r=>(au=Array.isArray,au(r)),dp=au;function hp(r){return typeof r!="object"?{}:r??{}}function TR(r){if(!r)return!0;for(const e in r)return!1;return!0}function xR(r,e){return Object.prototype.hasOwnProperty.call(r,e)}const AR=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ue(`${r} must be an integer`);if(e<0)throw new ue(`${r} must be a positive integer`);return e},My=r=>{try{return JSON.parse(r)}catch{return}},IR=r=>new Promise(e=>setTimeout(e,r)),wn="0.65.0",RR=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function OR(){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 $R=()=>{var t;const r=OR();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":wn,"X-Stainless-OS":pp(Deno.build.os),"X-Stainless-Arch":fp(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((t=Deno.version)==null?void 0:t.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":wn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":wn,"X-Stainless-OS":pp(globalThis.process.platform??"unknown"),"X-Stainless-Arch":fp(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=CR();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":wn,"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":wn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function CR(){if(typeof navigator>"u"||!navigator)return null;const r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of r){const n=t.exec(navigator.userAgent);if(n){const s=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}const fp=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",pp=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown");let mp;const kR=()=>mp??(mp=$R());function PR(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function jy(...r){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(...r)}function Dy(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return jy({start(){},async pull(t){const{done:n,value:s}=await e.next();n?t.close():t.enqueue(s)},async cancel(){var t;await((t=e.return)==null?void 0:t.call(e))}})}function vd(r){if(r[Symbol.asyncIterator])return r;const e=r.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function NR(r){var n,s;if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await((s=(n=r[Symbol.asyncIterator]()).return)==null?void 0:s.call(n));return}const e=r.getReader(),t=e.cancel();e.releaseLock(),await t}const LR=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function MR(r){let e=0;for(const s of r)e+=s.length;const t=new Uint8Array(e);let n=0;for(const s of r)t.set(s,n),n+=s.length;return t}let gp;function Sd(r){let e;return(gp??(e=new globalThis.TextEncoder,gp=e.encode.bind(e)))(r)}let _p;function yp(r){let e;return(_p??(e=new globalThis.TextDecoder,_p=e.decode.bind(e)))(r)}var _t,yt;class ra{constructor(){_t.set(this,void 0),yt.set(this,void 0),G(this,_t,new Uint8Array),G(this,yt,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Sd(e):e;G(this,_t,MR([O(this,_t,"f"),t]));const n=[];let s;for(;(s=jR(O(this,_t,"f"),O(this,yt,"f")))!=null;){if(s.carriage&&O(this,yt,"f")==null){G(this,yt,s.index);continue}if(O(this,yt,"f")!=null&&(s.index!==O(this,yt,"f")+1||s.carriage)){n.push(yp(O(this,_t,"f").subarray(0,O(this,yt,"f")-1))),G(this,_t,O(this,_t,"f").subarray(O(this,yt,"f"))),G(this,yt,null);continue}const a=O(this,yt,"f")!==null?s.preceding-1:s.preceding,i=yp(O(this,_t,"f").subarray(0,a));n.push(i),G(this,_t,O(this,_t,"f").subarray(s.index)),G(this,yt,null)}return n}flush(){return O(this,_t,"f").length?this.decode(`
203
+ `):[]}}_t=new WeakMap,yt=new WeakMap;ra.NEWLINE_CHARS=new Set([`
204
+ `,"\r"]);ra.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function jR(r,e){for(let s=e??0;s<r.length;s++){if(r[s]===10)return{preceding:s,index:s+1,carriage:!1};if(r[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function DR(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}const Ni={off:0,error:200,warn:300,info:400,debug:500},wp=(r,e,t)=>{if(r){if(xR(Ni,r))return r;tt(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Ni))}`)}};function _s(){}function $a(r,e,t){return!e||Ni[r]>Ni[t]?_s:e[r].bind(e)}const UR={error:_s,warn:_s,info:_s,debug:_s};let bp=new WeakMap;function tt(r){const e=r.logger,t=r.logLevel??"off";if(!e)return UR;const n=bp.get(e);if(n&&n[0]===t)return n[1];const s={error:$a("error",e,t),warn:$a("warn",e,t),info:$a("info",e,t),debug:$a("debug",e,t)};return bp.set(e,[t,s]),s}const qr=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var Hn;class nr{constructor(e,t,n){this.iterator=e,Hn.set(this,void 0),this.controller=t,G(this,Hn,n)}static fromSSEResponse(e,t,n){let s=!1;const a=n?tt(n):console;async function*i(){if(s)throw new ue("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const c of FR(e,t)){if(c.event==="completion")try{yield 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(c.event==="message_start"||c.event==="message_delta"||c.event==="message_stop"||c.event==="content_block_start"||c.event==="content_block_delta"||c.event==="content_block_stop")try{yield 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(c.event!=="ping"&&c.event==="error")throw new Xe(void 0,My(c.data)??c.data,void 0,e.headers)}o=!0}catch(c){if(js(c))return;throw c}finally{o||t.abort()}}return new nr(i,t,n)}static fromReadableStream(e,t,n){let s=!1;async function*a(){const o=new ra,c=vd(e);for await(const l of c)for(const u of o.decode(l))yield u;for(const l of o.flush())yield l}async function*i(){if(s)throw new ue("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(js(c))return;throw c}finally{o||t.abort()}}return new nr(i,t,n)}[(Hn=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=a=>({next:()=>{if(a.length===0){const i=n.next();e.push(i),t.push(i)}return a.shift()}});return[new nr(()=>s(e),this.controller,O(this,Hn,"f")),new nr(()=>s(t),this.controller,O(this,Hn,"f"))]}toReadableStream(){const e=this;let t;return jy({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{const{value:s,done:a}=await t.next();if(a)return n.close();const i=Sd(JSON.stringify(s)+`
205
+ `);n.enqueue(i)}catch(s){n.error(s)}},async cancel(){var n;await((n=t.return)==null?void 0:n.call(t))}})}}async function*FR(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ue("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 ue("Attempted to iterate over a response with no body");const t=new qR,n=new ra,s=vd(r.body);for await(const a of BR(s))for(const i of n.decode(a)){const o=t.decode(i);o&&(yield o)}for(const a of n.flush()){const i=t.decode(a);i&&(yield i)}}async function*BR(r){let e=new Uint8Array;for await(const t of r){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Sd(t):t;let s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let a;for(;(a=DR(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class qR{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(`
206
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=zR(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function zR(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function Uy(r,e){const{response:t,requestLogID:n,retryOfRequestLogID:s,startTime:a}=e,i=await(async()=>{var d;if(e.options.stream)return tt(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):nr.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const o=t.headers.get("content-type"),c=(d=o==null?void 0:o.split(";")[0])==null?void 0:d.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){const h=await t.json();return Fy(h,t)}return await t.text()})();return tt(r).debug(`[${n}] response parsed`,qr({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function Fy(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var ys;class So extends Promise{constructor(e,t,n=Uy){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=n,ys.set(this,void 0),G(this,ys,e)}_thenUnwrap(e){return new So(O(this,ys,"f"),this.responsePromise,async(t,n)=>Fy(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(O(this,ys,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}ys=new WeakMap;var Ca;class HR{constructor(e,t,n,s){Ca.set(this,void 0),G(this,Ca,e),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new ue("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await O(this,Ca,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ca=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class WR extends So{constructor(e,t,n){super(e,t,async(s,a)=>new n(s,a.response,await Uy(s,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class na extends HR{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var t;if((t=this.options.query)!=null&&t.before_id){const n=this.first_id;return n?{...this.options,query:{...hp(this.options.query),before_id:n}}:null}const e=this.last_id;return e?{...this.options,query:{...hp(this.options.query),after_id:e}}:null}}const By=()=>{var r;if(typeof File>"u"){const{process:e}=globalThis,t=typeof((r=e==null?void 0:e.versions)==null?void 0:r.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function An(r,e,t){return By(),new File(r,e??"unknown_file",t)}function ai(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}const qy=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",GR=async(r,e)=>({...r,body:await VR(r.body,e)}),vp=new WeakMap;function JR(r){const e=typeof r=="function"?r:r.fetch,t=vp.get(e);if(t)return t;const n=(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 vp.set(e,n),n}const VR=async(r,e)=>{if(!await JR(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(r||{}).map(([n,s])=>iu(t,n,s))),t},KR=r=>r instanceof Blob&&"name"in r,iu=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response){let n={};const s=t.headers.get("Content-Type");s&&(n={type:s}),r.append(e,An([await t.blob()],ai(t),n))}else if(qy(t))r.append(e,An([await new Response(Dy(t)).blob()],ai(t)));else if(KR(t))r.append(e,An([t],ai(t),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(n=>iu(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>iu(r,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},zy=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",ZR=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&zy(r),XR=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function YR(r,e,t){if(By(),r=await r,e||(e=ai(r)),ZR(r))return r instanceof File&&e==null&&t==null?r:An([await r.arrayBuffer()],e??r.name,{type:r.type,lastModified:r.lastModified,...t});if(XR(r)){const s=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),An(await ou(s),e,t)}const n=await ou(r);if(!(t!=null&&t.type)){const s=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof s=="string"&&(t={...t,type:s})}return An(n,e,t)}async function ou(r){var t;let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(zy(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(qy(r))for await(const n of r)e.push(...await ou(n));else{const n=(t=r==null?void 0:r.constructor)==null?void 0:t.name;throw new Error(`Unexpected data type: ${typeof r}${n?`; constructor: ${n}`:""}${QR(r)}`)}return e}function QR(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}class Sr{constructor(e){this._client=e}}const Hy=Symbol.for("brand.privateNullableHeaders");function*eO(r){if(!r)return;if(Hy in r){const{values:n,nulls:s}=r;yield*n.entries();for(const a of s)yield[a,null];return}let e=!1,t;r instanceof Headers?t=r.entries():dp(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){const s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const a=dp(n[1])?n[1]:[n[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,o])}}const xe=r=>{const e=new Headers,t=new Set;for(const n of r){const s=new Set;for(const[a,i]of eO(n)){const o=a.toLowerCase();s.has(o)||(e.delete(a),s.add(o)),i===null?(e.delete(a),t.add(o)):(e.append(a,i),t.delete(o))}}return{[Hy]:!0,values:e,nulls:t}};function Wy(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Sp=Object.freeze(Object.create(null)),tO=(r=Wy)=>function(t,...n){if(t.length===1)return t[0];let s=!1;const a=[],i=t.reduce((u,d,h)=>{var g;/[?#]/.test(d)&&(s=!0);const f=n[h];let p=(s?encodeURIComponent:r)(""+f);return h!==n.length&&(f==null||typeof f=="object"&&f.toString===((g=Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Sp)??Sp))==null?void 0:g.toString))&&(p=f+"",a.push({start:u.length+d.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),u+d+(h===n.length?"":p)},""),o=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let l;for(;(l=c.exec(o))!==null;)a.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(a.sort((u,d)=>u.start-d.start),a.length>0){let u=0;const d=a.reduce((h,f)=>{const p=" ".repeat(f.start-u),g="^".repeat(f.length);return u=f.start+f.length,h+p+g},"");throw new ue(`Path parameters result in path with invalid segments:
207
+ ${a.map(h=>h.error).join(`
208
+ `)}
209
+ ${i}
210
+ ${d}`)}return i},Ht=tO(Wy);class Gy extends Sr{list(e={},t){const{betas:n,...s}=e??{};return this._client.getAPIList("/v1/files",na,{query:s,...t,headers:xe([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t==null?void 0:t.headers])})}delete(e,t={},n){const{betas:s}=t??{};return this._client.delete(Ht`/v1/files/${e}`,{...n,headers:xe([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},n==null?void 0:n.headers])})}download(e,t={},n){const{betas:s}=t??{};return this._client.get(Ht`/v1/files/${e}/content`,{...n,headers:xe([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){const{betas:s}=t??{};return this._client.get(Ht`/v1/files/${e}`,{...n,headers:xe([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},n==null?void 0:n.headers])})}upload(e,t){const{betas:n,...s}=e;return this._client.post("/v1/files",GR({body:s,...t,headers:xe([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t==null?void 0:t.headers])},this._client))}}let Jy=class extends Sr{retrieve(e,t={},n){const{betas:s}=t??{};return this._client.get(Ht`/v1/models/${e}?beta=true`,{...n,headers:xe([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},n==null?void 0:n.headers])})}list(e={},t){const{betas:n,...s}=e??{};return this._client.getAPIList("/v1/models?beta=true",na,{query:s,...t,headers:xe([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},t==null?void 0:t.headers])})}};class Eo{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new ra;for await(const t of this.iterator)for(const n of e.decode(t))yield JSON.parse(n);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ue("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 ue("Attempted to iterate over a response with no body");return new Eo(vd(e.body),t)}}let Vy=class extends Sr{create(e,t){const{betas:n,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...t,headers:xe([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t==null?void 0:t.headers])})}retrieve(e,t={},n){const{betas:s}=t??{};return this._client.get(Ht`/v1/messages/batches/${e}?beta=true`,{...n,headers:xe([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}list(e={},t){const{betas:n,...s}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",na,{query:s,...t,headers:xe([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t==null?void 0:t.headers])})}delete(e,t={},n){const{betas:s}=t??{};return this._client.delete(Ht`/v1/messages/batches/${e}?beta=true`,{...n,headers:xe([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}cancel(e,t={},n){const{betas:s}=t??{};return this._client.post(Ht`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:xe([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}async results(e,t={},n){const s=await this.retrieve(e);if(!s.results_url)throw new ue(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);const{betas:a}=t??{};return this._client.get(s.results_url,{...n,headers:xe([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n==null?void 0:n.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((i,o)=>Eo.fromResponse(o.response,o.controller))}};const rO=r=>{let e=0,t=[];for(;e<r.length;){let n=r[e];if(n==="\\"){e++;continue}if(n==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(n==="["){t.push({type:"paren",value:"["}),e++;continue}if(n==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(n===":"){t.push({type:"separator",value:":"}),e++;continue}if(n===","){t.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let o="",c=!1;for(n=r[++e];n!=='"';){if(e===r.length){c=!0;break}if(n==="\\"){if(e++,e===r.length){c=!0;break}o+=n+r[e],n=r[++e]}else o+=n,n=r[++e]}n=r[++e],c||t.push({type:"string",value:o});continue}if(n&&/\s/.test(n)){e++;continue}let a=/[0-9]/;if(n&&a.test(n)||n==="-"||n==="."){let o="";for(n==="-"&&(o+=n,n=r[++e]);n&&a.test(n)||n===".";)o+=n,n=r[++e];t.push({type:"number",value:o});continue}let i=/[a-z]/i;if(n&&i.test(n)){let o="";for(;n&&i.test(n)&&e!==r.length;)o+=n,n=r[++e];if(o=="true"||o=="false"||o==="null")t.push({type:"name",value:o});else{e++;continue}continue}e++}return t},bn=r=>{if(r.length===0)return r;let e=r[r.length-1];switch(e.type){case"separator":return r=r.slice(0,r.length-1),bn(r);case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),bn(r);case"string":let n=r[r.length-2];if((n==null?void 0:n.type)==="delimiter")return r=r.slice(0,r.length-1),bn(r);if((n==null?void 0:n.type)==="brace"&&n.value==="{")return r=r.slice(0,r.length-1),bn(r);break;case"delimiter":return r=r.slice(0,r.length-1),bn(r)}return r},nO=r=>{let e=[];return r.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?r.push({type:"brace",value:"}"}):t==="]"&&r.push({type:"paren",value:"]"})}),r},sO=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Ky=r=>JSON.parse(sO(nO(bn(rO(r)))));var xt,Ir,Wn,ka,Gn,Jn,Pa,Vn,cr,Kn,Na,La,dn,Ma,ja,nl,Ep,Da,sl,al,il,Tp;const xp="__json_buf";function Ap(r){return r.type==="tool_use"||r.type==="server_tool_use"||r.type==="mcp_tool_use"}class Li{constructor(){xt.add(this),this.messages=[],this.receivedMessages=[],Ir.set(this,void 0),this.controller=new AbortController,Wn.set(this,void 0),ka.set(this,()=>{}),Gn.set(this,()=>{}),Jn.set(this,void 0),Pa.set(this,()=>{}),Vn.set(this,()=>{}),cr.set(this,{}),Kn.set(this,!1),Na.set(this,!1),La.set(this,!1),dn.set(this,!1),Ma.set(this,void 0),ja.set(this,void 0),Da.set(this,e=>{if(G(this,Na,!0),js(e)&&(e=new Bt),e instanceof Bt)return G(this,La,!0),this._emit("abort",e);if(e instanceof ue)return this._emit("error",e);if(e instanceof Error){const t=new ue(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new ue(String(e)))}),G(this,Wn,new Promise((e,t)=>{G(this,ka,e,"f"),G(this,Gn,t,"f")})),G(this,Jn,new Promise((e,t)=>{G(this,Pa,e,"f"),G(this,Vn,t,"f")})),O(this,Wn,"f").catch(()=>{}),O(this,Jn,"f").catch(()=>{})}get response(){return O(this,Ma,"f")}get request_id(){return O(this,ja,"f")}async withResponse(){const e=await O(this,Wn,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Li;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const s=new Li;for(const a of t.messages)s._addMessageParam(a);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},O(this,Da,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){var i;const s=n==null?void 0:n.signal;let a;s&&(s.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),s.addEventListener("abort",a));try{O(this,xt,"m",sl).call(this);const{response:o,data:c}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of c)O(this,xt,"m",al).call(this,l);if((i=c.controller.signal)!=null&&i.aborted)throw new Bt;O(this,xt,"m",il).call(this)}finally{s&&a&&s.removeEventListener("abort",a)}}_connected(e){this.ended||(G(this,Ma,e),G(this,ja,e==null?void 0:e.headers.get("request-id")),O(this,ka,"f").call(this,e),this._emit("connect"))}get ended(){return O(this,Kn,"f")}get errored(){return O(this,Na,"f")}get aborted(){return O(this,La,"f")}abort(){this.controller.abort()}on(e,t){return(O(this,cr,"f")[e]||(O(this,cr,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=O(this,cr,"f")[e];if(!n)return this;const s=n.findIndex(a=>a.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(O(this,cr,"f")[e]||(O(this,cr,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{G(this,dn,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){G(this,dn,!0),await O(this,Jn,"f")}get currentMessage(){return O(this,Ir,"f")}async finalMessage(){return await this.done(),O(this,xt,"m",nl).call(this)}async finalText(){return await this.done(),O(this,xt,"m",Ep).call(this)}_emit(e,...t){if(O(this,Kn,"f"))return;e==="end"&&(G(this,Kn,!0),O(this,Pa,"f").call(this));const n=O(this,cr,"f")[e];if(n&&(O(this,cr,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!O(this,dn,"f")&&!(n!=null&&n.length)&&Promise.reject(s),O(this,Gn,"f").call(this,s),O(this,Vn,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!O(this,dn,"f")&&!(n!=null&&n.length)&&Promise.reject(s),O(this,Gn,"f").call(this,s),O(this,Vn,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",O(this,xt,"m",nl).call(this))}async _fromReadableStream(e,t){var a;const n=t==null?void 0:t.signal;let s;n&&(n.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),n.addEventListener("abort",s));try{O(this,xt,"m",sl).call(this),this._connected(null);const i=nr.fromReadableStream(e,this.controller);for await(const o of i)O(this,xt,"m",al).call(this,o);if((a=i.controller.signal)!=null&&a.aborted)throw new Bt;O(this,xt,"m",il).call(this)}finally{n&&s&&n.removeEventListener("abort",s)}}[(Ir=new WeakMap,Wn=new WeakMap,ka=new WeakMap,Gn=new WeakMap,Jn=new WeakMap,Pa=new WeakMap,Vn=new WeakMap,cr=new WeakMap,Kn=new WeakMap,Na=new WeakMap,La=new WeakMap,dn=new WeakMap,Ma=new WeakMap,ja=new WeakMap,Da=new WeakMap,xt=new WeakSet,nl=function(){if(this.receivedMessages.length===0)throw new ue("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ep=function(){if(this.receivedMessages.length===0)throw new ue("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new ue("stream ended without producing a content block with type=text");return t.join(" ")},sl=function(){this.ended||G(this,Ir,void 0)},al=function(t){if(this.ended)return;const n=O(this,xt,"m",Tp).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{Ap(s)&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{G(this,Ir,n);break}}},il=function(){if(this.ended)throw new ue("stream has ended, this shouldn't happen");const t=O(this,Ir,"f");if(!t)throw new ue("request ended without sending any chunks");return G(this,Ir,void 0),t},Tp=function(t){let n=O(this,Ir,"f");if(t.type==="message_start"){if(n)throw new ue(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new ue(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.container=t.delta.container,n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n.context_management=t.context_management,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{const s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{(s==null?void 0:s.type)==="text"&&(n.content[t.index]={...s,text:(s.text||"")+t.delta.text});break}case"citations_delta":{(s==null?void 0:s.type)==="text"&&(n.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]});break}case"input_json_delta":{if(s&&Ap(s)){let a=s[xp]||"";a+=t.delta.partial_json;const i={...s};if(Object.defineProperty(i,xp,{value:a,enumerable:!1,writable:!0}),a)try{i.input=Ky(a)}catch(o){const c=new ue(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${o}. JSON: ${a}`);O(this,Da,"f").call(this,c)}n.content[t.index]=i}break}case"thinking_delta":{(s==null?void 0:s.type)==="thinking"&&(n.content[t.index]={...s,thinking:s.thinking+t.delta.thinking});break}case"signature_delta":{(s==null?void 0:s.type)==="thinking"&&(n.content[t.index]={...s,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new nr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}const Zy={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};var Ua,hn,Ur,at,Zn,tr,fr,Rr,Xn,cu;function Ip(){let r,e;return{promise:new Promise((n,s)=>{r=n,e=s}),resolve:r,reject:e}}class Xy{constructor(e,t,n){Ua.add(this),this.client=e,hn.set(this,!1),Ur.set(this,!1),at.set(this,void 0),Zn.set(this,void 0),tr.set(this,void 0),fr.set(this,void 0),Rr.set(this,void 0),Xn.set(this,0),G(this,at,{params:{...t,messages:structuredClone(t.messages)}}),G(this,Zn,{...n,headers:xe([{"x-stainless-helper":"BetaToolRunner"},n==null?void 0:n.headers])}),G(this,Rr,Ip())}async*[(hn=new WeakMap,Ur=new WeakMap,at=new WeakMap,Zn=new WeakMap,tr=new WeakMap,fr=new WeakMap,Rr=new WeakMap,Xn=new WeakMap,Ua=new WeakSet,Symbol.asyncIterator)](){var e;if(O(this,hn,"f"))throw new ue("Cannot iterate over a consumed stream");G(this,hn,!0),G(this,Ur,!0),G(this,fr,void 0);try{for(;;){let t;try{if(O(this,at,"f").params.max_iterations&&O(this,Xn,"f")>=O(this,at,"f").params.max_iterations)break;G(this,Ur,!1,"f"),G(this,tr,void 0,"f"),G(this,fr,void 0,"f"),G(this,Xn,(e=O(this,Xn,"f"),e++,e),"f");const{max_iterations:n,...s}=O(this,at,"f").params;if(s.stream?(t=this.client.beta.messages.stream({...s},O(this,Zn,"f")),G(this,tr,t.finalMessage(),"f"),yield t):(G(this,tr,this.client.beta.messages.create({...s,stream:!1},O(this,Zn,"f")),"f"),yield O(this,tr,"f")),!O(this,Ur,"f")){const{role:i,content:o}=await O(this,tr,"f");O(this,at,"f").params.messages.push({role:i,content:o})}const a=await O(this,Ua,"m",cu).call(this,O(this,at,"f").params.messages.at(-1));if(a&&O(this,at,"f").params.messages.push(a),!a&&!O(this,Ur,"f"))break}finally{t&&t.abort()}}if(!O(this,tr,"f"))throw new ue("ToolRunner concluded without a message from the server");O(this,Rr,"f").resolve(await O(this,tr,"f"))}catch(t){throw G(this,hn,!1),O(this,Rr,"f").promise.catch(()=>{}),O(this,Rr,"f").reject(t),G(this,Rr,Ip()),t}}setMessagesParams(e){typeof e=="function"?O(this,at,"f").params=e(O(this,at,"f").params):O(this,at,"f").params=e,G(this,Ur,!0),G(this,fr,void 0)}async generateToolResponse(){const e=await O(this,tr,"f")??this.params.messages.at(-1);return e?O(this,Ua,"m",cu).call(this,e):null}done(){return O(this,Rr,"f").promise}async runUntilDone(){if(!O(this,hn,"f"))for await(const e of this);return this.done()}get params(){return O(this,at,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}}cu=async function(e){return O(this,fr,"f")!==void 0?O(this,fr,"f"):(G(this,fr,aO(O(this,at,"f").params,e)),O(this,fr,"f"))};async function aO(r,e=r.messages.at(-1)){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;const t=e.content.filter(s=>s.type==="tool_use");return t.length===0?null:{role:"user",content:await Promise.all(t.map(async s=>{const a=r.tools.find(i=>i.name===s.name);if(!a||!("run"in a))return{type:"tool_result",tool_use_id:s.id,content:`Error: Tool '${s.name}' not found`,is_error:!0};try{let i=s.input;"parse"in a&&a.parse&&(i=a.parse(i));const o=await a.run(i);return{type:"tool_result",tool_use_id:s.id,content:o}}catch(i){return{type:"tool_result",tool_use_id:s.id,content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}))}}const Rp={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};let To=class extends Sr{constructor(){super(...arguments),this.batches=new Vy(this._client)}create(e,t){const{betas:n,...s}=e;s.model in Rp&&console.warn(`The model '${s.model}' is deprecated and will reach end-of-life on ${Rp[s.model]}
211
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let a=this._client._options.timeout;if(!s.stream&&a==null){const i=Zy[s.model]??void 0;a=this._client.calculateNonstreamingTimeout(s.max_tokens,i)}return this._client.post("/v1/messages?beta=true",{body:s,timeout:a??6e5,...t,headers:xe([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},t==null?void 0:t.headers]),stream:e.stream??!1})}stream(e,t){return Li.createMessage(this,e,t)}countTokens(e,t){const{betas:n,...s}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:s,...t,headers:xe([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},t==null?void 0:t.headers])})}toolRunner(e,t){return new Xy(this._client,e,t)}};To.Batches=Vy;To.BetaToolRunner=Xy;class sa extends Sr{constructor(){super(...arguments),this.models=new Jy(this._client),this.messages=new To(this._client),this.files=new Gy(this._client)}}sa.Models=Jy;sa.Messages=To;sa.Files=Gy;class Yy extends Sr{create(e,t){const{betas:n,...s}=e;return this._client.post("/v1/complete",{body:s,timeout:this._client._options.timeout??6e5,...t,headers:xe([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},t==null?void 0:t.headers]),stream:e.stream??!1})}}var At,Or,Yn,Fa,Qn,es,Ba,ts,lr,rs,qa,za,fn,Ha,Wa,ol,Op,cl,ll,ul,dl,$p;const Cp="__json_buf";function kp(r){return r.type==="tool_use"||r.type==="server_tool_use"}class Mi{constructor(){At.add(this),this.messages=[],this.receivedMessages=[],Or.set(this,void 0),this.controller=new AbortController,Yn.set(this,void 0),Fa.set(this,()=>{}),Qn.set(this,()=>{}),es.set(this,void 0),Ba.set(this,()=>{}),ts.set(this,()=>{}),lr.set(this,{}),rs.set(this,!1),qa.set(this,!1),za.set(this,!1),fn.set(this,!1),Ha.set(this,void 0),Wa.set(this,void 0),cl.set(this,e=>{if(G(this,qa,!0),js(e)&&(e=new Bt),e instanceof Bt)return G(this,za,!0),this._emit("abort",e);if(e instanceof ue)return this._emit("error",e);if(e instanceof Error){const t=new ue(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new ue(String(e)))}),G(this,Yn,new Promise((e,t)=>{G(this,Fa,e,"f"),G(this,Qn,t,"f")})),G(this,es,new Promise((e,t)=>{G(this,Ba,e,"f"),G(this,ts,t,"f")})),O(this,Yn,"f").catch(()=>{}),O(this,es,"f").catch(()=>{})}get response(){return O(this,Ha,"f")}get request_id(){return O(this,Wa,"f")}async withResponse(){const e=await O(this,Yn,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Mi;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const s=new Mi;for(const a of t.messages)s._addMessageParam(a);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},O(this,cl,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){var i;const s=n==null?void 0:n.signal;let a;s&&(s.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),s.addEventListener("abort",a));try{O(this,At,"m",ll).call(this);const{response:o,data:c}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of c)O(this,At,"m",ul).call(this,l);if((i=c.controller.signal)!=null&&i.aborted)throw new Bt;O(this,At,"m",dl).call(this)}finally{s&&a&&s.removeEventListener("abort",a)}}_connected(e){this.ended||(G(this,Ha,e),G(this,Wa,e==null?void 0:e.headers.get("request-id")),O(this,Fa,"f").call(this,e),this._emit("connect"))}get ended(){return O(this,rs,"f")}get errored(){return O(this,qa,"f")}get aborted(){return O(this,za,"f")}abort(){this.controller.abort()}on(e,t){return(O(this,lr,"f")[e]||(O(this,lr,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=O(this,lr,"f")[e];if(!n)return this;const s=n.findIndex(a=>a.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(O(this,lr,"f")[e]||(O(this,lr,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{G(this,fn,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){G(this,fn,!0),await O(this,es,"f")}get currentMessage(){return O(this,Or,"f")}async finalMessage(){return await this.done(),O(this,At,"m",ol).call(this)}async finalText(){return await this.done(),O(this,At,"m",Op).call(this)}_emit(e,...t){if(O(this,rs,"f"))return;e==="end"&&(G(this,rs,!0),O(this,Ba,"f").call(this));const n=O(this,lr,"f")[e];if(n&&(O(this,lr,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!O(this,fn,"f")&&!(n!=null&&n.length)&&Promise.reject(s),O(this,Qn,"f").call(this,s),O(this,ts,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!O(this,fn,"f")&&!(n!=null&&n.length)&&Promise.reject(s),O(this,Qn,"f").call(this,s),O(this,ts,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",O(this,At,"m",ol).call(this))}async _fromReadableStream(e,t){var a;const n=t==null?void 0:t.signal;let s;n&&(n.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),n.addEventListener("abort",s));try{O(this,At,"m",ll).call(this),this._connected(null);const i=nr.fromReadableStream(e,this.controller);for await(const o of i)O(this,At,"m",ul).call(this,o);if((a=i.controller.signal)!=null&&a.aborted)throw new Bt;O(this,At,"m",dl).call(this)}finally{n&&s&&n.removeEventListener("abort",s)}}[(Or=new WeakMap,Yn=new WeakMap,Fa=new WeakMap,Qn=new WeakMap,es=new WeakMap,Ba=new WeakMap,ts=new WeakMap,lr=new WeakMap,rs=new WeakMap,qa=new WeakMap,za=new WeakMap,fn=new WeakMap,Ha=new WeakMap,Wa=new WeakMap,cl=new WeakMap,At=new WeakSet,ol=function(){if(this.receivedMessages.length===0)throw new ue("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Op=function(){if(this.receivedMessages.length===0)throw new ue("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new ue("stream ended without producing a content block with type=text");return t.join(" ")},ll=function(){this.ended||G(this,Or,void 0)},ul=function(t){if(this.ended)return;const n=O(this,At,"m",$p).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{kp(s)&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{G(this,Or,n);break}}},dl=function(){if(this.ended)throw new ue("stream has ended, this shouldn't happen");const t=O(this,Or,"f");if(!t)throw new ue("request ended without sending any chunks");return G(this,Or,void 0),t},$p=function(t){let n=O(this,Or,"f");if(t.type==="message_start"){if(n)throw new ue(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new ue(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),n;case"content_block_start":return n.content.push({...t.content_block}),n;case"content_block_delta":{const s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{(s==null?void 0:s.type)==="text"&&(n.content[t.index]={...s,text:(s.text||"")+t.delta.text});break}case"citations_delta":{(s==null?void 0:s.type)==="text"&&(n.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]});break}case"input_json_delta":{if(s&&kp(s)){let a=s[Cp]||"";a+=t.delta.partial_json;const i={...s};Object.defineProperty(i,Cp,{value:a,enumerable:!1,writable:!0}),a&&(i.input=Ky(a)),n.content[t.index]=i}break}case"thinking_delta":{(s==null?void 0:s.type)==="thinking"&&(n.content[t.index]={...s,thinking:s.thinking+t.delta.thinking});break}case"signature_delta":{(s==null?void 0:s.type)==="thinking"&&(n.content[t.index]={...s,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new nr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class Qy extends Sr{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Ht`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",na,{query:e,...t})}delete(e,t){return this._client.delete(Ht`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(Ht`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const n=await this.retrieve(e);if(!n.results_url)throw new ue(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:xe([{Accept:"application/binary"},t==null?void 0:t.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,a)=>Eo.fromResponse(a.response,a.controller))}}class Ed extends Sr{constructor(){super(...arguments),this.batches=new Qy(this._client)}create(e,t){e.model in Pp&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Pp[e.model]}
212
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){const s=Zy[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,s)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...t,stream:e.stream??!1})}stream(e,t){return Mi.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const Pp={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};Ed.Batches=Qy;class ew extends Sr{retrieve(e,t={},n){const{betas:s}=t??{};return this._client.get(Ht`/v1/models/${e}`,{...n,headers:xe([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},n==null?void 0:n.headers])})}list(e={},t){const{betas:n,...s}=e??{};return this._client.getAPIList("/v1/models",na,{query:s,...t,headers:xe([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},t==null?void 0:t.headers])})}}var hl={};const Ga=r=>{var e,t,n,s;if(typeof globalThis.process<"u")return((e=hl==null?void 0:hl[r])==null?void 0:e.trim())??void 0;if(typeof globalThis.Deno<"u")return(s=(n=(t=globalThis.Deno.env)==null?void 0:t.get)==null?void 0:n.call(t,r))==null?void 0:s.trim()};var lu,Td,ii,tw;const iO="\\n\\nHuman:",oO="\\n\\nAssistant:";class De{constructor({baseURL:e=Ga("ANTHROPIC_BASE_URL"),apiKey:t=Ga("ANTHROPIC_API_KEY")??null,authToken:n=Ga("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){lu.add(this),ii.set(this,void 0);const a={apiKey:t,authToken:n,...s,baseURL:e||"https://api.anthropic.com"};if(!a.dangerouslyAllowBrowser&&RR())throw new ue(`It looks like you're running in a browser-like environment.
213
+
214
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
215
+ If you understand the risks and have appropriate mitigations in place,
216
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
217
+
218
+ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
219
+ `);this.baseURL=a.baseURL,this.timeout=a.timeout??Td.DEFAULT_TIMEOUT,this.logger=a.logger??console;const i="warn";this.logLevel=i,this.logLevel=wp(a.logLevel,"ClientOptions.logLevel",this)??wp(Ga("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??i,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??PR(),G(this,ii,LR),this._options=a,this.apiKey=t,this.authToken=n}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,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return xe([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return xe([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return xe([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new ue(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${wn}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ay()}`}makeStatusError(e,t,n,s){return Xe.generate(e,t,n,s)}buildURL(e,t,n){const s=!O(this,lu,"m",tw).call(this)&&n||this.baseURL,a=ER(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return TR(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new ue("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new So(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){var b,m;const s=await e,a=s.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(s);const{req:i,url:o,timeout:c}=await this.buildRequest(s,{retryCount:a-t});await this.prepareRequest(i,{url:o,options:s});const l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(tt(this).debug(`[${l}] sending request`,qr({retryOfRequestLogID:n,method:s.method,url:o,options:s,headers:i.headers})),(b=s.signal)!=null&&b.aborted)throw new Bt;const h=new AbortController,f=await this.fetchWithTimeout(o,i,c,h).catch(su),p=Date.now();if(f instanceof globalThis.Error){const y=`retrying, ${t} attempts remaining`;if((m=s.signal)!=null&&m.aborted)throw new Bt;const T=js(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return tt(this).info(`[${l}] connection ${T?"timed out":"failed"} - ${y}`),tt(this).debug(`[${l}] connection ${T?"timed out":"failed"} (${y})`,qr({retryOfRequestLogID:n,url:o,durationMs:p-d,message:f.message})),this.retryRequest(s,t,n??l);throw tt(this).info(`[${l}] connection ${T?"timed out":"failed"} - error; no more retries left`),tt(this).debug(`[${l}] connection ${T?"timed out":"failed"} (error; no more retries left)`,qr({retryOfRequestLogID:n,url:o,durationMs:p-d,message:f.message})),T?new Iy:new vo({cause:f})}const g=[...f.headers.entries()].filter(([y])=>y==="request-id").map(([y,T])=>", "+y+": "+JSON.stringify(T)).join(""),_=`[${l}${u}${g}] ${i.method} ${o} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${p-d}ms`;if(!f.ok){const y=await this.shouldRetry(f);if(t&&y){const J=`retrying, ${t} attempts remaining`;return await NR(f.body),tt(this).info(`${_} - ${J}`),tt(this).debug(`[${l}] response error (${J})`,qr({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-d})),this.retryRequest(s,t,n??l,f.headers)}const T=y?"error; no more retries left":"error; not retryable";tt(this).info(`${_} - ${T}`);const x=await f.text().catch(J=>su(J).message),R=My(x),$=R?void 0:x;throw tt(this).debug(`[${l}] response error (${T})`,qr({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:$,durationMs:Date.now()-d})),this.makeStatusError(f.status,R,$,f.headers)}return tt(this).info(_),tt(this).debug(`[${l}] response start`,qr({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-d})),{response:f,options:s,controller:h,requestLogID:l,retryOfRequestLogID:n,startTime:d}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new WR(this,n,e)}async fetchWithTimeout(e,t,n,s){const{signal:a,method:i,...o}=t||{};a&&a.addEventListener("abort",()=>s.abort());const c=setTimeout(()=>s.abort(),n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...o};i&&(u.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,s){let a;const i=s==null?void 0:s.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const o=s==null?void 0: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(t,c)}return await IR(a),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new ue("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:s,path:a,query:i,defaultBaseURL:o}=n,c=this.buildURL(a,i,o);"timeout"in n&&AR("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:l,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:s,bodyHeaders:l,retryCount:t});return{req:{method:s,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:s}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=xe([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))}:{},...kR(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=xe([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.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:Dy(e)}:O(this,ii,"f").call(this,{body:e,headers:n})}}Td=De,ii=new WeakMap,lu=new WeakSet,tw=function(){return this.baseURL!=="https://api.anthropic.com"};De.Anthropic=Td;De.HUMAN_PROMPT=iO;De.AI_PROMPT=oO;De.DEFAULT_TIMEOUT=6e5;De.AnthropicError=ue;De.APIError=Xe;De.APIConnectionError=vo;De.APIConnectionTimeoutError=Iy;De.APIUserAbortError=Bt;De.NotFoundError=Cy;De.ConflictError=ky;De.RateLimitError=Ny;De.BadRequestError=Ry;De.AuthenticationError=Oy;De.InternalServerError=Ly;De.PermissionDeniedError=$y;De.UnprocessableEntityError=Py;De.toFile=YR;class aa extends De{constructor(){super(...arguments),this.completions=new Yy(this),this.messages=new Ed(this),this.models=new ew(this),this.beta=new sa(this)}}aa.Completions=Yy;aa.Messages=Ed;aa.Models=ew;aa.Beta=sa;const cO={"claude-opus-4-1":8192,"claude-opus-4":8192,"claude-sonnet-4":8192,"claude-sonnet-3-7-sonnet":8192,"claude-3-5-sonnet":4096,"claude-3-5-haiku":4096,"claude-3-haiku":2048},Np=2048;function lO(r){var t;return r?((t=Object.entries(cO).find(([n])=>r.startsWith(n)))==null?void 0:t[1])??Np:Np}function uO(r){return!!(r.tools&&r.tools.length>0)}function dO(r){var e;for(const t of r.messages??[])if(typeof t.content!="string"){for(const n of t.content??[])if(typeof n=="object"&&n!=null&&n.type==="document"&&typeof n.citations=="object"&&((e=n.citations)!=null&&e.enabled))return!0}return!1}function hO(r){return!!(r.thinking&&r.thinking.type==="enabled")}function fO(r){return"input_schema"in r}function pO(r){const e=["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_"];return typeof r=="object"&&r!==null&&"type"in r&&"name"in r&&typeof r.type=="string"&&e.some(t=>typeof r.type=="string"&&r.type.startsWith(t))}function mO(r){if(typeof r.content=="string")return r.content;if(Array.isArray(r.content)&&r.content.length>=1&&"input"in r.content[0])return typeof r.content[0].input=="string"?r.content[0].input:JSON.stringify(r.content[0].input);if(Array.isArray(r.content)&&r.content.length>=1&&"text"in r.content[0]&&typeof r.content[0].text=="string")return r.content[0].text}var gO=class extends _o{constructor(e){super(e??{});w(this,"lc_serializable",!0);w(this,"anthropicApiKey");w(this,"apiKey");w(this,"apiUrl");w(this,"temperature");w(this,"topK");w(this,"topP");w(this,"maxTokens");w(this,"modelName","claude-3-5-sonnet-latest");w(this,"model","claude-3-5-sonnet-latest");w(this,"invocationKwargs");w(this,"stopSequences");w(this,"streaming",!1);w(this,"clientOptions");w(this,"thinking",{type:"disabled"});w(this,"contextManagement");w(this,"batchClient");w(this,"streamingClient");w(this,"streamUsage",!0);w(this,"createClient");if(this.anthropicApiKey=(e==null?void 0:e.apiKey)??(e==null?void 0:e.anthropicApiKey)??qt("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!(e!=null&&e.createClient))throw new Error("Anthropic API key not found");this.clientOptions=(e==null?void 0:e.clientOptions)??{},this.apiKey=this.anthropicApiKey,this.apiUrl=e==null?void 0:e.anthropicApiUrl,this.modelName=(e==null?void 0:e.model)??(e==null?void 0:e.modelName)??this.model,this.model=this.modelName,this.invocationKwargs=(e==null?void 0:e.invocationKwargs)??{},this.topP=(e==null?void 0:e.topP)??this.topP,this.temperature=(e==null?void 0:e.temperature)??this.temperature,this.topK=(e==null?void 0:e.topK)??this.topK,this.maxTokens=(e==null?void 0:e.maxTokens)??lO(this.model),this.stopSequences=(e==null?void 0:e.stopSequences)??this.stopSequences,this.streaming=(e==null?void 0:e.streaming)??!1,this.streamUsage=(e==null?void 0:e.streamUsage)??this.streamUsage,this.thinking=(e==null?void 0:e.thinking)??this.thinking,this.contextManagement=(e==null?void 0:e.contextManagement)??this.contextManagement,this.createClient=(e==null?void 0:e.createClient)??(t=>new aa(t))}static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}getLsParams(e){const t=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(!(!e||!e.length))return e.map(t=>{if(pO(t)||fO(t))return t;if(go(t))return{name:t.function.name,description:t.function.description,input_schema:t.function.parameters};if(Zs(t))return{name:t.name,description:t.description,input_schema:Rt(t.schema)?ut(t.schema):t.schema};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(t,null,2)}`)})}bindTools(e,t){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e),...t})}invocationParams(e){const t=iR(e==null?void 0:e.tool_choice);if(this.thinking.type==="enabled"){if(this.topP!==void 0&&this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.temperature!==void 0&&this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:(e==null?void 0:e.stop)??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e==null?void 0:e.tools),tool_choice:t,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:e==null?void 0:e.container}}return{model:this.model,temperature:this.temperature,top_k:this.topK,top_p:this.topP,stop_sequences:(e==null?void 0:e.stop)??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e==null?void 0:e.tools),tool_choice:t,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:e==null?void 0:e.container}}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,t,n){var l;const s=this.invocationParams(t),a=lp(e),i={...s,...a,stream:!0},o=!uO(i)&&!dO(i)&&!hO(i),c=await this.createStreamWithRetry(i,{headers:t.headers});for await(const u of c){if((l=t.signal)!=null&&l.aborted)throw c.controller.abort(),new Error("AbortError: User aborted the request.");const d=this.streamUsage??t.streamUsage,h=bR(u,{streamUsage:d,coerceContentToString:o});if(!h)continue;const{chunk:f}=h,p=mO(f),g=new Xr({message:new ke({content:f.content,additional_kwargs:f.additional_kwargs,tool_call_chunks:f.tool_call_chunks,usage_metadata:d?f.usage_metadata:void 0,response_metadata:f.response_metadata,id:f.id}),text:p??""});yield g,await(n==null?void 0:n.handleLLMNewToken(p??"",void 0,void 0,void 0,void 0,{chunk:g}))}}async _generateNonStreaming(e,t,n){const s=await this.completionWithRetry({...t,stream:!1,...lp(e)},n),{content:a,...i}=s,o=vR(a,i),{role:c,type:l,...u}=i;return{generations:o,llmOutput:u}}async _generate(e,t,n){if(this.stopSequences&&t.stop)throw new Error('"stopSequence" parameter found in input and default params');const s=this.invocationParams(t);if(s.stream){let a;const i=this._streamResponseChunks(e,t,n);for await(const o of i)a===void 0?a=o:a=a.concat(o);if(a===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:a.text,message:a.message}]}}else return this._generateNonStreaming(e,s,{signal:t.signal,headers:t.headers})}async createStreamWithRetry(e,t){if(!this.streamingClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.streamingClient.messages.create({...e,...this.invocationKwargs,stream:!0},t)}catch(s){throw up(s)}};return this.caller.call(n)}async completionWithRetry(e,t){if(!this.batchClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.batchClient.messages.create({...e,...this.invocationKwargs},t)}catch(s){throw up(s)}};return this.caller.callWithOptions({signal:t.signal??void 0},n)}_llmType(){return"anthropic"}withStructuredOutput(e,t){var p;const n=e,s=t==null?void 0:t.name,a=t==null?void 0:t.method,i=t==null?void 0:t.includeRaw;if(a==="jsonMode")throw new Error('Anthropic only supports "functionCalling" as a method.');let o=s??"extract",c,l;if(Rt(n)){const g=ut(n);l=[{name:o,description:g.description??"A function available to call.",input_schema:g}],c=new ap({returnSingle:!0,keyName:o,zodSchema:n})}else{let g;typeof n.name=="string"&&typeof n.description=="string"&&typeof n.input_schema=="object"&&n.input_schema!=null?(g=n,o=n.name):g={name:o,description:n.description??"",input_schema:n},l=[g],c=new ap({returnSingle:!0,keyName:o})}let u;if(((p=this.thinking)==null?void 0:p.type)==="enabled"){const g="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(g),u=this.withConfig({outputVersion:"v0",tools:l,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ut(n)}});const _=b=>{if(!b.tool_calls||b.tool_calls.length===0)throw new Error(g);return b};u=u.pipe(_)}else u=this.withConfig({outputVersion:"v0",tools:l,tool_choice:{type:"tool",name:o},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ut(n)}});if(!i)return u.pipe(c).withConfig({runName:"ChatAnthropicStructuredOutput"});const d=Mr.assign({parsed:(g,_)=>c.invoke(g.raw,_)}),h=Mr.assign({parsed:()=>null}),f=d.withFallbacks({fallbacks:[h]});return Ln.from([{raw:u},f]).withConfig({runName:"StructuredOutputRunnable"})}},_O=class extends gO{};const Ui=class Ui{constructor(e){w(this,"llm");w(this,"modelName");const{apiKey:t,model:n=Ui.DEFAULT_MODEL,temperature:s=0}=e;if(!t||t.trim()==="")throw new Error("Anthropic API key is required");this.modelName=n,this.llm=new _O({apiKey:t,model:n,temperature:s})}async parseStructuredData(e,t){try{return await this.llm.withStructuredOutput(t).invoke(e)}catch(n){throw console.error("[AnthropicModel] Parsing failed:",n),n}}};w(Ui,"DEFAULT_MODEL","claude-haiku-4-5");let uu=Ui;class yO{static createModel(e){const{provider:t,apiKey:n,model:s,temperature:a=0}=e;switch(t){case"openai":return new ru({apiKey:n,model:s,temperature:a});case"anthropic":return new uu({apiKey:n,model:s,temperature:a});default:throw new Error(`Unsupported AI provider: ${t}`)}}}class wO{constructor(){}async handleParseData(e,t){try{console.log("[AiParsingService] Handle parse data request");const n=await this.parseData(e);n.success?t({success:!0,data:n.data}):t({$isError:!0,message:n.error||"AI parsing failed",data:null})}catch(n){console.error("[AiParsingService] Parse data error:",n),t({$isError:!0,message:n instanceof Error?n.message:"Unknown error in AI parsing",data:null})}}async parseData(e){try{const{sourceData:t,schemaDefinition:n,prompt:s,model:a,apiKey:i,provider:o}=e;if(!i||i.trim()==="")return{success:!1,error:"AI API key is required. Please provide it in the ai-parse-data block."};const c=n.type==="array",l=this.reconstructZodSchema(n),u=yO.createModel({provider:o,apiKey:i,model:a,temperature:0}),d=this.buildPrompt(t,n,s),h=await u.parseStructuredData(d,l);return{success:!0,data:c&&h&&typeof h=="object"&&"items"in h?h.items:h}}catch(t){return console.error("[AI Parsing Service] Parsing failed:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error during AI parsing"}}}reconstructZodSchema(e){if(e.type==="array"&&e.items){const t=this.buildZodType(e.items);return $r({items:Id(t)})}if(e.type==="object"&&e.shape){const t={};for(const[n,s]of Object.entries(e.shape))t[n]=this.buildZodType(s);return $r(t)}return vn()}buildZodType(e){let t;switch(e.type){case"string":e.enum&&Array.isArray(e.enum)&&e.enum.length>0?t=oa(e.enum):t=In();break;case"number":if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0){const n=e.enum.map(s=>fw(s));t=pw(n)}else t=Rd();break;case"boolean":t=hw();break;case"array":t=Id(e.items?this.buildZodType(e.items):vn());break;case"object":if(e.shape){const n={};for(const[s,a]of Object.entries(e.shape))n[s]=this.buildZodType(a);t=$r(n)}else t=vn();break;case"currency":t=$r({code:oa(xo.code.enum),symbol:oa(xo.symbol.enum),format:oa(xo.format.enum),amount:Rd(),text:In()});break;default:t=vn()}return e.optional&&(t=t.nullable()),t}buildPrompt(e,t,n){const s=typeof e=="string"?e:JSON.stringify(e,null,2),a=this.describeSchema(t),i=t.type==="array";return`You are a data parsing assistant. Your task is to extract and structure data according to the provided schema.
220
+
221
+ Source Data:
222
+ \`\`\`
223
+ ${s}
224
+ \`\`\`
225
+
226
+ Expected Output Schema:
227
+ ${a}
228
+
229
+ ${n?`
230
+ Additional Instructions:
231
+ ${n}
232
+ `:""}
233
+
234
+ Please parse the source data and return it in the exact format specified by the schema. Extract all relevant information and ensure the data types match the schema.${i?`
235
+
236
+ IMPORTANT: Return the array in an object with "items" field: { items: [...your array here...] }`:""}`}describeSchema(e,t=0){const n=" ".repeat(t);if(e.type==="array"&&e.items)return`Array<${this.describeSchema(e.items,0)}>`;if(e.type==="object"&&e.shape){let s=`${n}{
237
+ `;for(const[a,i]of Object.entries(e.shape)){const o=i.optional?" (nullable)":"",c=i.description?` // ${i.description}`:"";s+=`${n} ${a}: ${this.describeSchema(i,t+1)}${o}${c}
238
+ `}return s+=`${n}}`,s}return e.type==="currency"?"{ code: string, symbol: string, format: string, amount: number, text: string }":e.enum&&Array.isArray(e.enum)?e.enum.map(a=>JSON.stringify(a)).join(" | "):e.type||"any"}}class bO{async handleClick(e,t){try{console.log("[CdpService] Handle click request:",e);const{tabId:n,x:s,y:a}=e;await this.click(n,s,a),t({success:!0,data:{clicked:!0}})}catch(n){console.error("[CdpService] Click error:",n),t({$isError:!0,message:n instanceof Error?n.message:"CDP click failed",data:null})}}async handleKeypress(e,t){try{console.log("[CdpService] Handle keypress request:",e);const{tabId:n,key:s,code:a,keyCode:i,modifiers:o}=e;await this.keypress(n,s,a,i,o),t({success:!0,data:{pressed:!0}})}catch(n){console.error("[CdpService] Keypress error:",n),t({$isError:!0,message:n instanceof Error?n.message:"CDP keypress failed",data:null})}}async click(e,t,n){console.log("[CdpService] Click request - tabId:",e,"x:",t,"y:",n),await chrome.debugger.attach({tabId:e},"1.3"),console.log("[CdpService] Debugger attached to tab:",e);try{await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mouseMoved",x:t,y:n,button:"none",clickCount:0}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mousePressed",x:t,y:n,button:"left",clickCount:1}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mouseReleased",x:t,y:n,button:"left",clickCount:1}),console.log("[CdpService] Click completed successfully")}finally{await chrome.debugger.detach({tabId:e}),console.log("[CdpService] Debugger detached from tab:",e)}}async keypress(e,t,n,s,a=[]){console.log("[CdpService] Keypress request - tabId:",e,"key:",t),await chrome.debugger.attach({tabId:e},"1.3"),console.log("[CdpService] Debugger attached to tab:",e);try{const i=this.convertModifiersToCdp(a);await chrome.debugger.sendCommand({tabId:e},"Input.dispatchKeyEvent",{type:"keyDown",key:t,code:n,windowsVirtualKeyCode:s,nativeVirtualKeyCode:s,modifiers:i}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchKeyEvent",{type:"keyUp",key:t,code:n,windowsVirtualKeyCode:s,nativeVirtualKeyCode:s,modifiers:i}),console.log("[CdpService] Keypress completed successfully")}finally{await chrome.debugger.detach({tabId:e}),console.log("[CdpService] Debugger detached from tab:",e)}}convertModifiersToCdp(e){let t=0;return e.includes("Alt")&&(t|=1),e.includes("Control")&&(t|=2),e.includes("Meta")&&(t|=4),e.includes("Shift")&&(t|=8),t}}const vO=()=>({steps:{}}),SO=(r,e,t)=>({steps:{...r.steps,[e]:t}}),EO=r=>r.startsWith("steps."),TO=(r,e)=>{if(!e.startsWith("steps."))return;const t=e.slice(6);if(t)return t.split(".").reduce((n,s)=>n==null?void 0:n[s],r.steps)},xO=()=>({vars:{}}),AO=(r,e)=>({vars:{...r.vars,...e}}),IO=r=>r.startsWith("vars."),RO=(r,e)=>{if(!e.startsWith("vars."))return;const t=e.slice(5);if(t)return t.split(".").reduce((n,s)=>n==null?void 0:n[s],r.vars)},OO=()=>({}),$O=(r,e,t,n)=>({...r,forEach:{item:e,index:t,total:n}}),CO=(r,e,t)=>({...r,loop:{index:e,count:t}}),kO=r=>{const{forEach:e,loop:t,...n}=r;return n},PO=r=>r.startsWith("forEach.")||r.startsWith("loop."),NO=(r,e)=>{if(!(!e.startsWith("forEach.")&&!e.startsWith("loop.")))return e.split(".").reduce((t,n)=>t==null?void 0:t[n],r)},LO=()=>({stepContext:vO(),varContext:xO(),loopContext:OO()}),MO=(r,e,t)=>({...r,stepContext:SO(r.stepContext,e,t)}),jO=(r,e)=>({...r,varContext:AO(r.varContext,e)}),DO=(r,e,t,n)=>({...r,loopContext:$O(r.loopContext,e,t,n)}),UO=(r,e,t)=>({...r,loopContext:CO(r.loopContext,e,t)}),fl=r=>({...r,loopContext:kO(r.loopContext)}),Dt=(r,e)=>{if(EO(e))return TO(r.stepContext,e);if(IO(e))return RO(r.varContext,e);if(PO(e))return NO(r.loopContext,e)},rw=(r,e)=>{const t=/^\$\{([^}]+)\}$/.exec(r);return t?Dt(e,t[1].trim()):r.startsWith("$.")?Dt(e,r.substring(2)):r.replace(/\$\{([^}]+)\}/g,(n,s)=>{const a=Dt(e,s.trim());return a==null?"":typeof a=="object"?JSON.stringify(a):String(a)})},FO=(r,e)=>{const{valueFrom:t,template:n,default:s}=r;try{if(t!=null){const a=Dt(e,t);return a===void 0?s:a}if(n!=null){const a=rw(n,e);return a==null||a===""?s:a}}catch{return s}return s},ji=(r,e)=>{if(r==null)return r;if(typeof r=="string")return rw(r,e);if(Array.isArray(r))return r.map(t=>ji(t,e));if(typeof r=="object"){if("valueFrom"in r||"template"in r)return FO(r,e);const t={};for(const n of Object.keys(r))t[n]=ji(r[n],e);return t}return r},Is=(r,e)=>{if("exists"in r)return Dt(e,r.exists)!==void 0;if("equals"in r)return Dt(e,r.equals.left)===r.equals.right;if("notEquals"in r)return Dt(e,r.notEquals.left)!==r.notEquals.right;if("contains"in r){const t=Dt(e,r.contains.value),n=String(r.contains.search);return Array.isArray(t)?t.some(s=>String(s).includes(n)):String(t).includes(n)}if("regex"in r){const t=String(Dt(e,r.regex.value));return new RegExp(r.regex.pattern,r.regex.flags||"").test(t)}return"and"in r?r.and.every(t=>Is(t,e)):"or"in r?r.or.some(t=>Is(t,e)):"not"in r?!Is(r.not,e):!1},BO=(r,e)=>{try{const t=e.varContext.vars,n=e.stepContext.steps,s=e.loopContext.forEach,a=e.loopContext.loop;return!!new Function("vars","steps","forEach","loop",`return (${r});`)(t,n,s,a)}catch{return!1}},qO=r=>typeof r=="object"&&r!==null&&("exists"in r||"equals"in r||"notEquals"in r||"contains"in r||"regex"in r||"and"in r||"or"in r||"not"in r),nw=(r,e)=>{if(!r)return!0;if(qO(r))return Is(r,e);const t=r;return t.json?Is(t.json,e):t.expr?BO(t.expr,e):!0},zO=async(r,e)=>!e||e<=0?r():new Promise((t,n)=>{const s=setTimeout(()=>n(new Error("Step timeout")),e);r().then(a=>{clearTimeout(s),t(a)}).catch(a=>{clearTimeout(s),n(a)})}),sw=async(r,e,t,n,s={})=>{const a=Math.max(1,s.maxAttempts??1),i=s.baseDelay??0,o=s.backoff??1;let c=0,l=null,u=!1,d="";for(;c<a;){c++;try{const h=ji(r,e);if(l=await zO(()=>t(h,n),s.timeoutMs),u=!(l!=null&&l.hasError),d=(l==null?void 0:l.message)||"",u)break}catch(h){u=!1,d=(h==null?void 0:h.message)||"Workflow step error",l={hasError:!0,message:d}}if(c<a){const h=i*Math.pow(o,c-1);h>0&&await new Promise(f=>setTimeout(f,h))}}return{result:l,success:u,message:d,attempts:c}},HO=(r,e)=>{if(r.forEach){const t=Dt(e,r.forEach);return Array.isArray(t)?{items:t,isForEach:!0}:t!=null?{items:[t],isForEach:!0}:{items:[],isForEach:!0}}if(r.count!=null){let t;return typeof r.count=="string"?t=Dt(e,r.count)??0:t=r.count,{items:Array.from({length:Math.max(0,t)},(s,a)=>a),isForEach:!1}}throw new Error("repeat requires either forEach or count")},WO=async(r,e,t,n,s,a={})=>{const i=[],o=[];let c=t;try{const{items:l,isForEach:u}=HO(e,t);for(let d=0;d<l.length;d++){const h=l[d];u?c=DO(c,h,d,l.length):c=UO(c,d,l.length);try{const f=await sw(r,c,n,s,a);if(f.success)i.push(f.result);else if(o.push({index:d,item:h,error:f.result}),e.continueOnError)i.push(null);else return c=fl(c),{result:{hasError:!0,message:`Repeat failed at index ${d}: ${f.message}`,data:{results:i,errors:o,stoppedAt:d}},context:c}}catch(f){if(o.push({index:d,item:h,error:f.message}),e.continueOnError)i.push(null);else return c=fl(c),{result:{hasError:!0,message:`Repeat failed at index ${d}: ${f.message}`,data:{results:i,errors:o,stoppedAt:d}},context:c}}e.delayBetween&&d<l.length-1&&await new Promise(f=>setTimeout(f,e.delayBetween))}return c=fl(c),{result:{hasError:o.length>0&&!e.continueOnError,message:o.length>0?`Completed with ${o.length} error(s) out of ${l.length}`:`Completed ${l.length} iteration(s)`,data:i},context:c}}catch(l){return{result:{hasError:!0,message:l.message||"repeat requires either forEach or count",data:null},context:c}}},GO=async(r,e,t,n)=>{var f,p,g,_,b,m,y,T;const s=new Date().toISOString();let a=!1,i=!0,o="",c=null,l=0,u=e;if(!nw(r.when,e))a=!0;else if(r.block)if(r.repeat){const x=await WO(r.block,r.repeat,e,t,n,{maxAttempts:(f=r.retry)==null?void 0:f.attempts,baseDelay:(p=r.retry)==null?void 0:p.delayMs,backoff:(g=r.retry)==null?void 0:g.backoffFactor,timeoutMs:r.timeoutMs});c=x.result,i=!((_=x.result)!=null&&_.hasError),o=((b=x.result)==null?void 0:b.message)||"",u=x.context}else{const x=await sw(r.block,e,t,n,{maxAttempts:(m=r.retry)==null?void 0:m.attempts,baseDelay:(y=r.retry)==null?void 0:y.delayMs,backoff:(T=r.retry)==null?void 0:T.backoffFactor,timeoutMs:r.timeoutMs});c=x.result,i=x.success,o=x.message,l=x.attempts}else a=!0;const h=new Date().toISOString();return u=MO(u,r.id,{result:c,success:i,skipped:a}),{stepId:r.id,skipped:a,success:i,message:o,result:c,startedAt:s,finishedAt:h,attempts:l,context:u}},JO=(r,e,t)=>{if(r.switch&&r.switch.length>0){const n=r.switch.find(s=>nw(s.when,t));if(n)return n.next}if(e&&r.onSuccess)return r.onSuccess;if(!e&&r.onFailure)return r.onFailure;if(r.next)return r.next},VO=async r=>{typeof r.delayAfterMs=="number"&&r.delayAfterMs>0&&await new Promise(e=>setTimeout(e,r.delayAfterMs))};class KO{constructor(e,t,n){this.executeBlock=e,this.createTab=t,this.statusController=n}async run(e,t,n=!1){var o,c;let s=LO();e.vars&&(s=jO(s,e.vars)),console.log("context",e.vars),console.log("targetUrl",t),console.log(s);const a=typeof t=="string"?ji(t,s):t;console.log("resolvedTargetUrl",a);const i=await this.createTab(a,n);try{await((o=this.statusController)==null?void 0:o.show(i,"워크플로우 실행 중"));const l=new Map(e.steps.map(h=>[h.id,h]));let u=e.start;const d=[];for(;u;){const h=l.get(u);if(!h)break;const f=await GO(h,s,this.executeBlock,i);d.push(f),s=f.context;const p=JO(h,f.success,s);p&&!f.skipped&&await VO(h),u=p}return{steps:d,tabId:i,context:s}}finally{await((c=this.statusController)==null?void 0:c.hide(i))}}}class ZO{constructor(e){w(this,"workflowRunner");this.tabManager=e;const t=(a,i)=>this.tabManager.executeBlock(a,i),n=async(a,i)=>{const o=await this.tabManager.createTab(a,i);if(o.id===void 0)throw new Error("Failed to create tab or tab ID is missing");return o.id},s={show:(a,i)=>this.tabManager.showExecutionStatus(a,i),hide:a=>this.tabManager.hideExecutionStatus(a)};this.workflowRunner=new KO(t,n,s)}async handleCollectWorkflow(e,t){const n=this.validateRequest(e);if(!n.success){t({$isError:!0,message:n.error,data:{}});return}let s;try{console.log("[WorkflowService] Running workflow for:",e.targetUrl);const a=await this.workflowRunner.run(e.workflow,e.targetUrl,e.activateTab===!0);s=a.tabId;const i={steps:a.context.stepContext.steps,vars:a.context.varContext.vars,forEach:a.context.loopContext.forEach,loop:a.context.loopContext.loop};t({success:!0,targetUrl:e.targetUrl,tabId:a.tabId,result:{steps:a.steps,context:i},timestamp:new Date().toISOString(),closeTabAfterCollection:e.closeTabAfterCollection!==!1})}catch(a){console.error("[WorkflowService] Workflow execution error:",a),t({$isError:!0,message:a instanceof Error?a.message:"Workflow execution failed",data:{}})}finally{s!==void 0&&e.closeTabAfterCollection!==!1&&await this.cleanup(s)}}validateRequest(e){return e.targetUrl?e.workflow?{success:!0}:{success:!1,error:"Workflow is required"}:{success:!1,error:"Target URL is required for workflow"}}async cleanup(e){console.log("[WorkflowService] Cleanup - closing tab:",e),await new Promise(t=>setTimeout(t,1e3)),await this.tabManager.closeTab(e)}}class XO{async handleRequest(e,t){try{console.log("[ApiService] Handle API request:",e.url);const n=await this.fetchData(e);t({success:!0,data:n})}catch(n){console.error("[ApiService] API request error:",n),t({$isError:!0,message:n instanceof Error?n.message:"Unknown error in API request",data:null})}}async fetchData(e){const{url:t,method:n,headers:s,body:a,timeout:i,parseJson:o,returnHeaders:c}=e;console.log(`[ApiService] Fetching ${n} ${t}`);const l=new AbortController,u=setTimeout(()=>l.abort(),i);try{const d={method:n,headers:s,signal:l.signal};a&&!["GET","HEAD"].includes(n)&&(typeof a=="string"?d.body=a:(d.body=JSON.stringify(a),!s["Content-Type"]&&!s["content-type"]&&(d.headers={...s,"Content-Type":"application/json"})));const h=await fetch(t,d);clearTimeout(u);let f;const p=h.headers.get("content-type")||"";if(o&&p.includes("application/json"))try{f=await h.json()}catch{f=await h.text()}else f=await h.text();let g;c&&(g={},h.headers.forEach((b,m)=>{g[m]=b}));const _={status:h.status,statusText:h.statusText,data:f,headers:g};return console.log(`[ApiService] Response status: ${h.status}`),_}catch(d){throw clearTimeout(u),d instanceof Error&&d.name==="AbortError"?new Error(`Request timeout after ${i}ms`):d}}}function YO(r){return JSON.stringify(r,null,2)}function QO(r,e){const t=(e==null?void 0:e.delimiter)||",",n=(e==null?void 0:e.includeHeaders)!==!1,s=Array.isArray(r)?r:[r];if(s.length===0)return"";const a=new Set;s.forEach(c=>{typeof c=="object"&&c!==null&&Object.keys(c).forEach(l=>a.add(l))});const i=Array.from(a),o=[];return n&&i.length>0&&o.push(i.map(c=>pl(c,t)).join(t)),s.forEach(c=>{if(typeof c=="object"&&c!==null){const l=i.map(u=>{const d=c[u];return pl(d,t)});o.push(l.join(t))}else o.push(pl(c,t))}),o.join(`
239
+ `)}function pl(r,e){if(r==null)return"";let t=String(r);return(t.includes(e)||t.includes('"')||t.includes(`
240
+ `)||t.includes("\r"))&&(t='"'+t.replace(/"/g,'""')+'"'),t}function e$(r){const e=Array.isArray(r)?r:[r];if(e.length===0)return Lp([]);const t=new Set;e.forEach(a=>{typeof a=="object"&&a!==null&&Object.keys(a).forEach(i=>t.add(i))});const n=Array.from(t),s=[];return n.length>0&&s.push(n),e.forEach(a=>{if(typeof a=="object"&&a!==null){const i=n.map(o=>a[o]);s.push(i)}else s.push([a])}),Lp(s)}function Lp(r){return`<?xml version="1.0"?>
241
+ <?mso-application progid="Excel.Sheet"?>
242
+ <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
243
+ xmlns:o="urn:schemas-microsoft-com:office:office"
244
+ xmlns:x="urn:schemas-microsoft-com:office:excel"
245
+ xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
246
+ xmlns:html="http://www.w3.org/TR/REC-html40">
247
+ <Worksheet ss:Name="Sheet1">
248
+ <Table>
249
+ ${r.map(t=>` <Row>
250
+ ${t.map(s=>{const a=s==null?"":String(s);return` <Cell><Data ss:Type="String">${t$(a)}</Data></Cell>`}).join(`
251
+ `)}
252
+ </Row>`).join(`
253
+ `)}
254
+ </Table>
255
+ </Worksheet>
256
+ </Workbook>`}function t$(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}class r${static async exportData(e){const{data:t,format:n,filename:s="export-data",csvOptions:a}=e;if(t==null)throw new Error("No data provided for export");let i,o,c;switch(n){case"json":i=YO(t),o=s.endsWith(".json")?s:`${s}.json`,c="application/json";break;case"csv":i=QO(t,a),o=s.endsWith(".csv")?s:`${s}.csv`,c="text/csv;charset=utf-8;";break;case"xlsx":i=e$(t),o=s.endsWith(".xlsx")?s:`${s}.xlsx`,c="application/vnd.ms-excel";break;default:throw new Error(`Unsupported format: ${n}`)}const l=new Blob([i],{type:c}),u=await this.blobToDataUrl(l),d=await new Promise((h,f)=>{chrome.downloads.download({url:u,filename:o,saveAs:!1},p=>{chrome.runtime.lastError?f(new Error(chrome.runtime.lastError.message)):h(p)})});return{filename:o,downloadId:d}}static blobToDataUrl(e){return new Promise((t,n)=>{const s=new FileReader;s.onloadend=()=>t(s.result),s.onerror=n,s.readAsDataURL(e)})}}class n${constructor(){w(this,"aiParsingService");w(this,"cdpService");w(this,"workflowService");w(this,"apiService");this.aiParsingService=new wO,this.cdpService=new bO,this.workflowService=new ZO(new mw),this.apiService=new XO}initHandler(){chrome.runtime.onMessage.addListener((e,t,n)=>{var s,a;if(e.type==="COLLECT_WORKFLOW_NEW_TAB")return this.handleAsyncCollectWorkflow(e.data,n),!0;if(e.type==="CDP_CLICK"&&cw(e)){const i=(s=t.tab)==null?void 0:s.id;return i?(this.handleAsyncCdpClick({...e.data,tabId:i},n),!0):(n({$isError:!0,message:"Tab ID not found in sender",data:null}),!1)}if(e.type==="CDP_KEYPRESS"&&lw(e)){const i=(a=t.tab)==null?void 0:a.id;return i?(this.handleAsyncCdpKeypress({...e.data,tabId:i},n),!0):(n({$isError:!0,message:"Tab ID not found in sender",data:null}),!1)}return e.type==="AI_PARSE_DATA"?(this.handleAsyncAiParseData(e.data,n),!0):e.type==="FETCH_API"&&uw(e)?(this.handleAsyncFetchApi(e.data,n),!0):e.type==="EXPORT_DATA"&&dw(e)?(this.handleAsyncExportData(e.data,n),!0):(n({$isError:!0,message:"Invalid message type",data:{}}),!1)})}async handleAsyncCollectWorkflow(e,t){await this.workflowService.handleCollectWorkflow(e,t)}async handleAsyncCdpClick(e,t){await this.cdpService.handleClick(e,t)}async handleAsyncCdpKeypress(e,t){await this.cdpService.handleKeypress(e,t)}async handleAsyncAiParseData(e,t){await this.aiParsingService.handleParseData(e,t)}async handleAsyncFetchApi(e,t){await this.apiService.handleRequest(e,t)}async handleAsyncExportData(e,t){try{const n=await r$.exportData(e);t({data:n})}catch(n){console.error("[BackgroundManager] Export data error:",n),t({$isError:!0,message:n instanceof Error?n.message:"Unknown error in export data",data:null})}}}console.log("[8G Extension] Background script starting...");const s$=new n$;s$.initHandler();