@mcp-use/inspector 0.4.10 → 0.4.11-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/cli.js +3 -3
  2. package/dist/client/assets/chunk-VL2OQCWN-BE4txAap.js +8 -0
  3. package/dist/client/assets/{embeddings-BvWgxmh-.js → embeddings-D0mnwVrX.js} +1 -1
  4. package/dist/client/assets/{index-F8MAAt6D.js → index-B0MYHYe6.js} +1 -1
  5. package/dist/client/assets/{index-CWYxvW-c.js → index-BEMSyME5.js} +2 -2
  6. package/dist/client/assets/{index-DHsHh1_g.js → index-BgupETL3.js} +1 -1
  7. package/dist/client/assets/{index-Dnm19mgK.js → index-CQ9XIRcv.js} +2 -2
  8. package/dist/client/assets/index-DrYUC3_O.js +1775 -0
  9. package/dist/client/assets/index-mBO7pd_t.js +1 -0
  10. package/dist/client/assets/index-wkxN17B9.js +4 -0
  11. package/dist/client/assets/langfuse-MO3AMDBE-DYoZ4Kwk.js +570 -0
  12. package/dist/client/index.html +2 -2
  13. package/dist/server/{chunk-UAGOQUEV.js → chunk-5JZ2RXUR.js} +3 -3
  14. package/dist/server/{chunk-GZSRGACL.js → chunk-AFTM3F6I.js} +1 -1
  15. package/dist/server/{chunk-G2KU64MV.js → chunk-JTBAUVJ3.js} +1 -1
  16. package/dist/server/{chunk-HPZTE753.js → chunk-RK4WSNY7.js} +3 -3
  17. package/dist/server/{chunk-BE2QCYB4.js → chunk-VMVT3HVZ.js} +3 -3
  18. package/dist/server/cli.js +4 -4
  19. package/dist/server/index.js +5 -5
  20. package/dist/server/middleware.js +5 -5
  21. package/dist/server/server.js +5 -5
  22. package/dist/server/shared-routes.js +2 -2
  23. package/dist/server/shared-static.js +2 -2
  24. package/dist/server/shared-utils-browser.js +1 -1
  25. package/dist/server/shared-utils.js +1 -1
  26. package/package.json +2 -2
  27. package/dist/client/assets/browser-BkJdGGVq.js +0 -611
  28. package/dist/client/assets/chunk-VL2OQCWN-Dm4XquLI.js +0 -8
  29. package/dist/client/assets/index-BxUJEXs5.js +0 -1734
  30. package/dist/client/assets/index-CEkgKN2t.js +0 -1
  31. package/dist/client/assets/index-WLUXcbDv.js +0 -4
  32. package/dist/client/assets/langfuse-6AJGHMAV-QljN0jPu.js +0 -1
  33. package/dist/client/assets/v4-BKrj-4V8.js +0 -1
@@ -1,4 +1,4 @@
1
- import{s as Oi,v as se,P as Pe,p as Ht,a as Ga,b as Nr,g as he,c as kr,d as Ke,_ as Ci,$ as xi,e as Ni,f as ki,h as Ri,i as Rr,j as ca,k as Pi,t as Va,l as Pr,V as Mi,m as Li,n as Ut,o as $i,T as ji}from"./chunk-VL2OQCWN-Dm4XquLI.js";import{Z as P,a as Za,o as la,s as ua}from"./index-BxUJEXs5.js";var Di=Object.defineProperty,F=(e,t)=>{for(var n in t)Di(e,n,{get:t[n],enumerable:!0})};function Ue(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function da(e){return Ue(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ha(e){return Ue(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Fi(e){return Ue(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function Mr(e){return Ue(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function Lr(e){if(Ue(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Ui(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),a=t[1].trim();if(n===""||a==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const r={};for(const s of e.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);r[o]=c}return{type:n,subtype:a,parameters:r}}function $n({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let a;if(n){a=n[1].toLowerCase();const r=t?Uint8Array.from(atob(n[2]),s=>s.charCodeAt(0)):n[2];return{mime_type:a,data:r}}}function Bi(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function $r(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function zi(e,t){return t?.[e]||Oi(e)}function Hi(e,t,n){const a={};for(const r in e)Object.hasOwn(e,r)&&(a[t(r,n)]=e[r]);return a}var Gi={};F(Gi,{Serializable:()=>lt,get_lc_unique_name:()=>pa});function qa(e){return Array.isArray(e)?[...e]:{...e}}function Vi(e,t){const n=qa(e);for(const[a,r]of Object.entries(t)){const[s,...i]=a.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=qa(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[r]})}return n}function pa(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var lt=class jr{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pa(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([a])=>this.lc_serializable_keys?.includes(a))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof jr||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},a=Object.keys(this.lc_kwargs).reduce((r,s)=>(r[s]=s in this?this[s]:this.lc_kwargs[s],r),{});for(let r=Object.getPrototypeOf(this);r;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r,"lc_aliases",this)),Object.assign(n,Reflect.get(r,"lc_secrets",this)),Object.assign(a,Reflect.get(r,"lc_attributes",this));return Object.keys(n).forEach(r=>{let s=this,i=a;const[o,...c]=r.split(".").reverse();for(const l of c.reverse()){if(!(l in s)||s[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof s[l]=="object"&&s[l]!=null?i[l]={}:Array.isArray(s[l])&&(i[l]=[])),s=s[l],i=i[l]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Hi(Object.keys(n).length?Vi(a,n):a,zi,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function C(e,t){return k(e)&&e.type===t}function k(e){return typeof e=="object"&&e!==null}function Ie(e){return Array.isArray(e)}function S(e){return typeof e=="string"}function we(e){return typeof e=="number"}function fa(e){return e instanceof Uint8Array}function Ja(e){try{return JSON.parse(e)}catch{return}}const vt=e=>e();function Zi(e){if(e.type==="char_location"&&S(e.document_title)&&we(e.start_char_index)&&we(e.end_char_index)&&S(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="page_location"&&S(e.document_title)&&we(e.start_page_number)&&we(e.end_page_number)&&S(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="content_block_location"&&S(e.document_title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="web_search_result_location"&&S(e.url)&&S(e.title)&&S(e.encrypted_index)&&S(e.cited_text)){const{url:t,title:n,encrypted_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"url",url:t,title:n,startIndex:Number(a),endIndex:Number(a),citedText:r}}if(e.type==="search_result_location"&&S(e.source)&&S(e.title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{source:t,title:n,start_block_index:a,end_block_index:r,cited_text:s,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:a,endIndex:r,citedText:s}}}function Dr(e){if(C(e,"document")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&S(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(C(e,"image")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function qi(e){function*t(){for(const n of e){const a=Dr(n);a?yield a:yield n}}return Array.from(t())}function Wa(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"text")&&S(a.text)){const{text:r,citations:s,...i}=a;if(Ie(s)&&s.length){const o=s.reduce((c,l)=>{const d=Zi(l);return d?[...c,d]:c},[]);yield{...i,type:"text",text:r,annotations:o};continue}else{yield{...i,type:"text",text:r};continue}}else if(C(a,"thinking")&&S(a.thinking)){const{thinking:r,signature:s,...i}=a;yield{...i,type:"reasoning",reasoning:r,signature:s};continue}else if(C(a,"redacted_thinking")){yield{type:"non_standard",value:a};continue}else if(C(a,"tool_use")&&S(a.name)&&S(a.id)){yield{type:"tool_call",id:a.id,name:a.name,args:a.input};continue}else if(C(a,"input_json_delta")){if(Wi(e)&&e.tool_call_chunks?.length){const r=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args,index:r.index};continue}}else if(C(a,"server_tool_use")&&S(a.name)&&S(a.id)){const{name:r,id:s}=a;if(r==="web_search"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.query))return a.input.query;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(a.name==="code_execution"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.code))return a.input.code;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(C(a,"web_search_tool_result")&&S(a.tool_use_id)&&Ie(a.content)){const{content:r,tool_use_id:s}=a,i=r.reduce((o,c)=>C(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(C(a,"code_execution_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"mcp_tool_use")){yield{id:a.id,type:"server_tool_call",name:"mcp_tool_use",args:a.input};continue}else if(C(a,"mcp_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:a.input};continue}else if(C(a,"search_result")){yield{id:a.id,type:"non_standard",value:a};continue}else if(C(a,"tool_result")){yield{id:a.id,type:"non_standard",value:a};continue}else{const r=Dr(a);if(r){yield r;continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ji={translateContent:Wa,translateContentChunk:Wa};function Wi(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function Ki(e){return da(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ha(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Mr(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Yi(e){return e.map(Ki)}function Qi(e){return!!(C(e,"image_url")&&k(e.image_url)||C(e,"input_audio")&&k(e.input_audio)||C(e,"file")&&k(e.file))}function Xi(e){if(C(e,"image_url")&&k(e.image_url)&&S(e.image_url.url)){const t=$n({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(C(e,"input_audio")&&k(e.input_audio)&&S(e.input_audio.data)&&S(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(C(e,"file")&&k(e.file)&&S(e.file.data)){const t=$n({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(S(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function eo(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function to(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function ma(e){const t=[];for(const n of e)Qi(n)?t.push(Xi(n)):t.push(n);return t}function no(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:a,end_index:r}=e;return{type:"citation",url:t,title:n,startIndex:a,endIndex:r}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:a}=e;return{type:"citation",title:n,startIndex:a,endIndex:a,fileId:t}}return e}function Fr(e){function*t(){k(e.additional_kwargs?.reasoning)&&Ie(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((r,s)=>k(s)&&S(s.text)?`${r}${s.text}`:r,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n)if(C(a,"text")){const{text:r,annotations:s,...i}=a;Array.isArray(s)?yield{...i,type:"text",text:String(r),annotations:s.map(no)}:yield{...i,type:"text",text:String(r)}}for(const a of e.tool_calls??[])yield{type:"tool_call",id:a.id,name:a.name,args:a.args};if(k(e.additional_kwargs)&&Ie(e.additional_kwargs.tool_outputs))for(const a of e.additional_kwargs.tool_outputs){if(C(a,"web_search_call")){yield{id:a.id,type:"server_tool_call",name:"web_search",args:{query:a.query}};continue}else if(C(a,"file_search_call")){yield{id:a.id,type:"server_tool_call",name:"file_search",args:{query:a.query}};continue}else if(C(a,"computer_call")){yield{type:"non_standard",value:a};continue}else if(C(a,"code_interpreter_call")){if(S(a.code)&&(yield{id:a.id,type:"server_tool_call",name:"code_interpreter",args:{code:a.code}}),Ie(a.outputs)){const r=vt(()=>{if(a.status!=="in_progress"){if(a.status==="completed")return 0;if(a.status==="incomplete")return 127;if(a.status!=="interpreting"&&a.status==="failed")return 1}});for(const s of a.outputs)if(C(s,"logs")){yield{type:"server_tool_call_result",toolCallId:a.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:r??0,stderr:[0,void 0].includes(r)?void 0:String(s.logs),stdout:[0,void 0].includes(r)?String(s.logs):void 0}};continue}}continue}else if(C(a,"mcp_call")){yield{id:a.id,type:"server_tool_call",name:"mcp_call",args:a.input};continue}else if(C(a,"mcp_list_tools")){yield{id:a.id,type:"server_tool_call",name:"mcp_list_tools",args:a.input};continue}else if(C(a,"mcp_approval_request")){yield{type:"non_standard",value:a};continue}else if(C(a,"image_generation_call")){yield{type:"non_standard",value:a};continue}k(a)&&(yield{type:"non_standard",value:a})}}return Array.from(t())}function ao(e){function*t(){yield*Fr(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const ro={translateContent:e=>typeof e.content=="string"?eo(e):Fr(e),translateContentChunk:e=>typeof e.content=="string"?to(e):ao(e)};function so(e,t="pretty"){return t==="pretty"?io(e):JSON.stringify(e)}function io(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-n.length)/2),r="=".repeat(a),s=n.length%2===0?r:`${r}=`;if(t.push(`${r}${n}${s}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
1
+ import{s as Oi,v as se,P as Pe,p as Ht,a as Ga,b as Nr,g as he,c as kr,d as Ke,_ as Ci,$ as xi,e as Ni,f as ki,h as Rr,i as ca,j as Ri,k as Pi,t as Va,l as Pr,V as Mi,m as Li,n as Ut,o as $i,T as ji}from"./chunk-VL2OQCWN-BE4txAap.js";import{Z as P,a as Za,o as la,s as ua}from"./index-DrYUC3_O.js";var Di=Object.defineProperty,F=(e,t)=>{for(var n in t)Di(e,n,{get:t[n],enumerable:!0})};function Ue(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function da(e){return Ue(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ha(e){return Ue(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Fi(e){return Ue(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function Mr(e){return Ue(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function Lr(e){if(Ue(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Ui(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),a=t[1].trim();if(n===""||a==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const r={};for(const s of e.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);r[o]=c}return{type:n,subtype:a,parameters:r}}function $n({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let a;if(n){a=n[1].toLowerCase();const r=t?Uint8Array.from(atob(n[2]),s=>s.charCodeAt(0)):n[2];return{mime_type:a,data:r}}}function Bi(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function $r(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function zi(e,t){return t?.[e]||Oi(e)}function Hi(e,t,n){const a={};for(const r in e)Object.hasOwn(e,r)&&(a[t(r,n)]=e[r]);return a}var Gi={};F(Gi,{Serializable:()=>lt,get_lc_unique_name:()=>pa});function qa(e){return Array.isArray(e)?[...e]:{...e}}function Vi(e,t){const n=qa(e);for(const[a,r]of Object.entries(t)){const[s,...i]=a.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=qa(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[r]})}return n}function pa(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var lt=class jr{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pa(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([a])=>this.lc_serializable_keys?.includes(a))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof jr||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},a=Object.keys(this.lc_kwargs).reduce((r,s)=>(r[s]=s in this?this[s]:this.lc_kwargs[s],r),{});for(let r=Object.getPrototypeOf(this);r;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r,"lc_aliases",this)),Object.assign(n,Reflect.get(r,"lc_secrets",this)),Object.assign(a,Reflect.get(r,"lc_attributes",this));return Object.keys(n).forEach(r=>{let s=this,i=a;const[o,...c]=r.split(".").reverse();for(const l of c.reverse()){if(!(l in s)||s[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof s[l]=="object"&&s[l]!=null?i[l]={}:Array.isArray(s[l])&&(i[l]=[])),s=s[l],i=i[l]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Hi(Object.keys(n).length?Vi(a,n):a,zi,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function C(e,t){return k(e)&&e.type===t}function k(e){return typeof e=="object"&&e!==null}function Ie(e){return Array.isArray(e)}function S(e){return typeof e=="string"}function we(e){return typeof e=="number"}function fa(e){return e instanceof Uint8Array}function Ja(e){try{return JSON.parse(e)}catch{return}}const vt=e=>e();function Zi(e){if(e.type==="char_location"&&S(e.document_title)&&we(e.start_char_index)&&we(e.end_char_index)&&S(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="page_location"&&S(e.document_title)&&we(e.start_page_number)&&we(e.end_page_number)&&S(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="content_block_location"&&S(e.document_title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="web_search_result_location"&&S(e.url)&&S(e.title)&&S(e.encrypted_index)&&S(e.cited_text)){const{url:t,title:n,encrypted_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"url",url:t,title:n,startIndex:Number(a),endIndex:Number(a),citedText:r}}if(e.type==="search_result_location"&&S(e.source)&&S(e.title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{source:t,title:n,start_block_index:a,end_block_index:r,cited_text:s,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:a,endIndex:r,citedText:s}}}function Dr(e){if(C(e,"document")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&S(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(C(e,"image")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function qi(e){function*t(){for(const n of e){const a=Dr(n);a?yield a:yield n}}return Array.from(t())}function Wa(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"text")&&S(a.text)){const{text:r,citations:s,...i}=a;if(Ie(s)&&s.length){const o=s.reduce((c,l)=>{const d=Zi(l);return d?[...c,d]:c},[]);yield{...i,type:"text",text:r,annotations:o};continue}else{yield{...i,type:"text",text:r};continue}}else if(C(a,"thinking")&&S(a.thinking)){const{thinking:r,signature:s,...i}=a;yield{...i,type:"reasoning",reasoning:r,signature:s};continue}else if(C(a,"redacted_thinking")){yield{type:"non_standard",value:a};continue}else if(C(a,"tool_use")&&S(a.name)&&S(a.id)){yield{type:"tool_call",id:a.id,name:a.name,args:a.input};continue}else if(C(a,"input_json_delta")){if(Wi(e)&&e.tool_call_chunks?.length){const r=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args,index:r.index};continue}}else if(C(a,"server_tool_use")&&S(a.name)&&S(a.id)){const{name:r,id:s}=a;if(r==="web_search"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.query))return a.input.query;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(a.name==="code_execution"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.code))return a.input.code;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(C(a,"web_search_tool_result")&&S(a.tool_use_id)&&Ie(a.content)){const{content:r,tool_use_id:s}=a,i=r.reduce((o,c)=>C(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(C(a,"code_execution_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"mcp_tool_use")){yield{id:a.id,type:"server_tool_call",name:"mcp_tool_use",args:a.input};continue}else if(C(a,"mcp_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:a.input};continue}else if(C(a,"search_result")){yield{id:a.id,type:"non_standard",value:a};continue}else if(C(a,"tool_result")){yield{id:a.id,type:"non_standard",value:a};continue}else{const r=Dr(a);if(r){yield r;continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ji={translateContent:Wa,translateContentChunk:Wa};function Wi(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function Ki(e){return da(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ha(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Mr(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Yi(e){return e.map(Ki)}function Qi(e){return!!(C(e,"image_url")&&k(e.image_url)||C(e,"input_audio")&&k(e.input_audio)||C(e,"file")&&k(e.file))}function Xi(e){if(C(e,"image_url")&&k(e.image_url)&&S(e.image_url.url)){const t=$n({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(C(e,"input_audio")&&k(e.input_audio)&&S(e.input_audio.data)&&S(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(C(e,"file")&&k(e.file)&&S(e.file.data)){const t=$n({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(S(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function eo(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function to(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function ma(e){const t=[];for(const n of e)Qi(n)?t.push(Xi(n)):t.push(n);return t}function no(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:a,end_index:r}=e;return{type:"citation",url:t,title:n,startIndex:a,endIndex:r}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:a}=e;return{type:"citation",title:n,startIndex:a,endIndex:a,fileId:t}}return e}function Fr(e){function*t(){k(e.additional_kwargs?.reasoning)&&Ie(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((r,s)=>k(s)&&S(s.text)?`${r}${s.text}`:r,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n)if(C(a,"text")){const{text:r,annotations:s,...i}=a;Array.isArray(s)?yield{...i,type:"text",text:String(r),annotations:s.map(no)}:yield{...i,type:"text",text:String(r)}}for(const a of e.tool_calls??[])yield{type:"tool_call",id:a.id,name:a.name,args:a.args};if(k(e.additional_kwargs)&&Ie(e.additional_kwargs.tool_outputs))for(const a of e.additional_kwargs.tool_outputs){if(C(a,"web_search_call")){yield{id:a.id,type:"server_tool_call",name:"web_search",args:{query:a.query}};continue}else if(C(a,"file_search_call")){yield{id:a.id,type:"server_tool_call",name:"file_search",args:{query:a.query}};continue}else if(C(a,"computer_call")){yield{type:"non_standard",value:a};continue}else if(C(a,"code_interpreter_call")){if(S(a.code)&&(yield{id:a.id,type:"server_tool_call",name:"code_interpreter",args:{code:a.code}}),Ie(a.outputs)){const r=vt(()=>{if(a.status!=="in_progress"){if(a.status==="completed")return 0;if(a.status==="incomplete")return 127;if(a.status!=="interpreting"&&a.status==="failed")return 1}});for(const s of a.outputs)if(C(s,"logs")){yield{type:"server_tool_call_result",toolCallId:a.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:r??0,stderr:[0,void 0].includes(r)?void 0:String(s.logs),stdout:[0,void 0].includes(r)?String(s.logs):void 0}};continue}}continue}else if(C(a,"mcp_call")){yield{id:a.id,type:"server_tool_call",name:"mcp_call",args:a.input};continue}else if(C(a,"mcp_list_tools")){yield{id:a.id,type:"server_tool_call",name:"mcp_list_tools",args:a.input};continue}else if(C(a,"mcp_approval_request")){yield{type:"non_standard",value:a};continue}else if(C(a,"image_generation_call")){yield{type:"non_standard",value:a};continue}k(a)&&(yield{type:"non_standard",value:a})}}return Array.from(t())}function ao(e){function*t(){yield*Fr(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const ro={translateContent:e=>typeof e.content=="string"?eo(e):Fr(e),translateContentChunk:e=>typeof e.content=="string"?to(e):ao(e)};function so(e,t="pretty"){return t==="pretty"?io(e):JSON.stringify(e)}function io(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-n.length)/2),r="=".repeat(a),s=n.length%2===0?r:`${r}=`;if(t.push(`${r}${n}${s}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
2
2
  `)}const yn=Symbol.for("langchain.message");function Xe(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.some(n=>Ue(n))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?Ot(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(n=>Ue(n))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function Ur(e,t){return e==="error"||t==="error"?"error":"success"}function oo(e,t){function n(a,r){if(typeof a!="object"||a===null||a===void 0)return a;if(r>=t)return Array.isArray(a)?"[Array]":"[Object]";if(Array.isArray(a))return a.map(i=>n(i,r+1));const s={};for(const i of Object.keys(a))s[i]=n(a[i],r+1);return s}return JSON.stringify(n(e,0),null,2)}var Le=class extends lt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[yn]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}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),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 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[Yi,ma,qi].reduce((a,r)=>r(a),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&&yn in e&&e[yn]===!0&&$r(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=oo(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return so(this,e)}};function co(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}function ee(e={},t={}){const n={...e};for(const[a,r]of Object.entries(t))if(n[a]==null)n[a]=r;else{if(r==null)continue;if(typeof n[a]!=typeof r||Array.isArray(n[a])!==Array.isArray(r))throw new Error(`field[${a}] already exists in the message chunk, but with a different type.`);if(typeof n[a]=="string"){if(a==="type")continue;["id","name","output_version","model_provider"].includes(a)?n[a]=r:n[a]+=r}else if(typeof n[a]=="object"&&!Array.isArray(n[a]))n[a]=ee(n[a],r);else if(Array.isArray(n[a]))n[a]=Ot(n[a],r);else{if(n[a]===r)continue;console.warn(`field[${a}] already exists in this message chunk and value has unsupported type.`)}}return n}function Ot(e,t){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)return e||t;{const n=[...e];for(const a of t)if(typeof a=="object"&&a!==null&&"index"in a&&typeof a.index=="number"){const r=n.findIndex(s=>{const i=typeof s=="object",o="index"in s&&s.index===a.index,c="id"in s&&"id"in a&&s?.id===a?.id,l=!("id"in s)||!s?.id||!("id"in a)||!a?.id;return i&&o&&(c||l)});r!==-1&&typeof n[r]=="object"&&n[r]!==null?n[r]=ee(n[r],a):n.push(a)}else{if(typeof a=="object"&&a!==null&&"text"in a&&a.text==="")continue;n.push(a)}return n}}}function Br(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(!e||!t)return e||t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
3
3
  Left ${typeof e}
4
4
  Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return Ot(e,t);if(typeof e=="object"&&typeof t=="object")return ee(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.
@@ -55,7 +55,7 @@ Please make sure you are calling this method within a traceable function and tha
55
55
  * (c) 2017-2022 Joachim Wester
56
56
  * MIT licensed
57
57
  */const xl=Object.prototype.hasOwnProperty;function qn(e,t){return xl.call(e,t)}function Jn(e){if(Array.isArray(e)){const n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=""+a;return n}if(Object.keys)return Object.keys(e);let t=[];for(let n in e)qn(e,n)&&t.push(n);return t}function be(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function Wn(e){let t=0;const n=e.length;let a;for(;t<n;){if(a=e.charCodeAt(t),a>=48&&a<=57){t++;continue}return!1}return!0}function rt(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Nl(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Kn(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let n=0,a=e.length;n<a;n++)if(Kn(e[n]))return!0}else if(typeof e=="object"){const n=Jn(e),a=n.length;for(var t=0;t<a;t++)if(Kn(e[n[t]]))return!0}}return!1}function _r(e,t){const n=[e];for(const a in t){const r=typeof t[a]=="object"?JSON.stringify(t[a],null,2):t[a];typeof r<"u"&&n.push(`${a}: ${r}`)}return n.join(`
58
- `)}var kl=class extends Error{constructor(e,t,n,a,r){super(_r(e,{name:t,index:n,operation:a,tree:r})),this.name=t,this.index=n,this.operation=a,this.tree=r,Object.setPrototypeOf(this,new.target.prototype),this.message=_r(e,{name:t,index:n,operation:a,tree:r})}},ks={};F(ks,{JsonPatchError:()=>G,_areEquals:()=>At,applyOperation:()=>Je,applyPatch:()=>dt,applyReducer:()=>Ml,deepClone:()=>Rl,getValueByPointer:()=>Wt,validate:()=>Rs,validator:()=>Kt});const G=kl,Rl=be,ot={add:function(e,t,n){return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){var a=e[t];return delete e[t],{newDocument:n,removed:a}},replace:function(e,t,n){var a=e[t];return e[t]=this.value,{newDocument:n,removed:a}},move:function(e,t,n){let a=Wt(n,this.path);a&&(a=be(a));const r=Je(n,{op:"remove",path:this.from}).removed;return Je(n,{op:"add",path:this.path,value:r}),{newDocument:n,removed:a}},copy:function(e,t,n){const a=Wt(n,this.from);return Je(n,{op:"add",path:this.path,value:be(a)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:At(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}};var Pl={add:function(e,t,n){return Wn(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){var a=e.splice(t,1);return{newDocument:n,removed:a[0]}},replace:function(e,t,n){var a=e[t];return e[t]=this.value,{newDocument:n,removed:a}},move:ot.move,copy:ot.copy,test:ot.test,_get:ot._get};function Wt(e,t){if(t=="")return e;var n={op:"_get",path:t};return Je(e,n),n.value}function Je(e,t,n=!1,a=!0,r=!0,s=0){if(n&&(typeof n=="function"?n(t,0,e,t.path):Kt(t,0)),t.path===""){let i={newDocument:e};if(t.op==="add")return i.newDocument=t.value,i;if(t.op==="replace")return i.newDocument=t.value,i.removed=e,i;if(t.op==="move"||t.op==="copy")return i.newDocument=Wt(e,t.from),t.op==="move"&&(i.removed=e),i;if(t.op==="test"){if(i.test=At(e,t.value),i.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return i.newDocument=e,i}else{if(t.op==="remove")return i.removed=e,i.newDocument=null,i;if(t.op==="_get")return t.value=e,i;if(n)throw new G("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,t,e);return i}}else{a||(e=be(e));const o=(t.path||"").split("/");let c=e,l=1,d=o.length,p,f,m;for(typeof n=="function"?m=n:m=Kt;;){if(f=o[l],f&&f.indexOf("~")!=-1&&(f=Nl(f)),r&&(f=="__proto__"||f=="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(n&&p===void 0&&(c[f]===void 0?p=o.slice(0,l).join("/"):l==d-1&&(p=t.path),p!==void 0&&m(t,0,e,p)),l++,Array.isArray(c)){if(f==="-")f=c.length;else{if(n&&!Wn(f))throw new G("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",s,t,e);Wn(f)&&(f=~~f)}if(l>=d){if(n&&t.op==="add"&&f>c.length)throw new G("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);const y=Pl[t.op].call(t,c,f,e);if(y.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return y}}else if(l>=d){const y=ot[t.op].call(t,c,f,e);if(y.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return y}if(c=c[f],n&&l<d&&(!c||typeof c!="object"))throw new G("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,t,e)}}}function dt(e,t,n,a=!0,r=!0){if(n&&!Array.isArray(t))throw new G("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");a||(e=be(e));const s=new Array(t.length);for(let i=0,o=t.length;i<o;i++)s[i]=Je(e,t[i],n,!0,r,i),e=s[i].newDocument;return s.newDocument=e,s}function Ml(e,t,n){const a=Je(e,t);if(a.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a.newDocument}function Kt(e,t,n,a){if(typeof e!="object"||e===null||Array.isArray(e))throw new G("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,n);if(ot[e.op]){if(typeof e.path!="string")throw new G("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,n);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new G('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,n);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new G("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new G("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&Kn(e.value))throw new G("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,n);if(n){if(e.op=="add"){var r=e.path.split("/").length,s=a.split("/").length;if(r!==s+1&&r!==s)throw new G("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,n)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==a)throw new G("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,n)}else if(e.op==="move"||e.op==="copy"){var i={op:"_get",path:e.from,value:void 0},o=Rs([i],n);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new G("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new G("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function Rs(e,t,n){try{if(!Array.isArray(e))throw new G("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)dt(be(t),be(e),n||!0);else{n=n||Kt;for(var a=0;a<e.length;a++)n(e[a],a,t,void 0)}}catch(r){if(r instanceof G)return r;throw r}}function At(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var n=Array.isArray(e),a=Array.isArray(t),r,s,i;if(n&&a){if(s=e.length,s!=t.length)return!1;for(r=s;r--!==0;)if(!At(e[r],t[r]))return!1;return!0}if(n!=a)return!1;var o=Object.keys(e);if(s=o.length,s!==Object.keys(t).length)return!1;for(r=s;r--!==0;)if(!t.hasOwnProperty(o[r]))return!1;for(r=s;r--!==0;)if(i=o[r],!At(e[i],t[i]))return!1;return!0}return e!==e&&t!==t}function Ps(e,t,n,a,r){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=Jn(t),i=Jn(e),o=!1,c=i.length-1;c>=0;c--){var l=i[c],d=e[l];if(qn(t,l)&&!(t[l]===void 0&&d!==void 0&&Array.isArray(t)===!1)){var p=t[l];typeof d=="object"&&d!=null&&typeof p=="object"&&p!=null&&Array.isArray(d)===Array.isArray(p)?Ps(d,p,n,a+"/"+rt(l),r):d!==p&&(r&&n.push({op:"test",path:a+"/"+rt(l),value:be(d)}),n.push({op:"replace",path:a+"/"+rt(l),value:be(p)}))}else Array.isArray(e)===Array.isArray(t)?(r&&n.push({op:"test",path:a+"/"+rt(l),value:be(d)}),n.push({op:"remove",path:a+"/"+rt(l)}),o=!0):(r&&n.push({op:"test",path:a,value:e}),n.push({op:"replace",path:a,value:t}))}if(!(!o&&s.length==i.length))for(var c=0;c<s.length;c++){var l=s[c];!qn(e,l)&&t[l]!==void 0&&n.push({op:"add",path:a+"/"+rt(l),value:be(t[l])})}}}function Aa(e,t,n=!1){var a=[];return Ps(e,t,a,"",n),a}({...ks});var Ll={};F(Ll,{LogStreamCallbackHandler:()=>Qn,RunLog:()=>Ia,RunLogPatch:()=>ke,isLogStreamHandler:()=>Ms});var ke=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),n=dt({},t);return new Ia({ops:t,state:n[n.length-1].newDocument})}},Ia=class Yn extends ke{state;constructor(t){super(t),this.state=t.state}concat(t){const n=this.ops.concat(t.ops),a=dt(this.state,t.ops);return new Yn({ops:n,state:a[a.length-1].newDocument})}static fromRunLogPatch(t){const n=dt({},t.ops);return new Yn({ops:t.ops,state:n[n.length-1].newDocument})}};const Ms=e=>e.name==="log_stream_tracer";async function yr(e,t){if(t==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:n}=e;if(["retriever","llm","prompt"].includes(e.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===""))return n.input}async function wr(e,t){const{outputs:n}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function $l(e){return e!==void 0&&e.message!==void 0}var Qn=class extends ft{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Te.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(a=>this.includeTags?.includes(a))!==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(a=>!this.excludeTags?.includes(a))),n}async*tapOutputIterable(e,t){for await(const n of t){if(e!==this.rootId){const a=this.keyMapByRunId[e];a&&await this.writer.write(new ke({ops:[{op:"add",path:`/logs/${a}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new ke({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:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(n.inputs=await yr(e,this._schemaFormat)),await this.writer.write(new ke({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 yr(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await wr(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 a=new ke({ops:n});await this.writer.write(a)}finally{if(e.id===this.rootId){const t=new ke({ops:[{op:"replace",path:"/final_output",value:await wr(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){const a=this.keyMapByRunId[e.id];if(a===void 0)return;const r=e.inputs.messages!==void 0;let s;r?$l(n?.chunk)?s=n?.chunk:s=new tt({id:`run-${e.id}`,content:t}):s=t;const i=new ke({ops:[{op:"add",path:`/logs/${a}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${a}/streamed_output/-`,value:s}]});await this.writer.write(i)}},jl={};F(jl,{ChatGenerationChunk:()=>ea,GenerationChunk:()=>It,RUN_KEY:()=>Xn});const Xn="__run";var It=class Ls{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new Ls({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},ea=class $s extends It{message;constructor(t){super(t),this.message=t.message}concat(t){return new $s({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function jt({name:e,serialized:t}){return e!==void 0?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const Dl=e=>e.name==="event_stream_tracer";var Fl=class extends ft{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Te.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(a=>this.includeTags?.includes(a))!==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(a=>!this.excludeTags?.includes(a))),n}async*tapOutputIterable(e,t){const n=await t.next();if(n.done)return;const a=this.runInfoMap.get(e);if(a===void 0){yield n.value;return}function r(i,o){return i==="llm"&&typeof o=="string"?new It({text:o}):o}let s=this.tappedPromises.get(e);if(s===void 0){let i;s=new Promise(o=>{i=o}),this.tappedPromises.set(e,s);try{const o={event:`on_${a.runType}_stream`,run_id:e,name:a.name,tags:a.tags,metadata:a.metadata,data:{}};await this.send({...o,data:{chunk:r(a.runType,n.value)}},a),yield n.value;for await(const c of t)a.runType!=="tool"&&a.runType!=="retriever"&&await this.send({...o,data:{chunk:r(a.runType,c)}},a),yield c}finally{i?.()}}else{yield n.value;for await(const i of t)yield i}}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){const t=jt(e),n=e.inputs.messages!==void 0?"chat_model":"llm",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,a);const r=`on_${n}_start`;await this.send({event:r,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onLLMNewToken(e,t,n){const a=this.runInfoMap.get(e.id);let r,s;if(a===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(a.runType==="chat_model")s="on_chat_model_stream",n?.chunk===void 0?r=new tt({content:t,id:`run-${e.id}`}):r=n.chunk.message;else if(a.runType==="llm")s="on_llm_stream",n?.chunk===void 0?r=new It({text:t}):r=n.chunk;else throw new Error(`Unexpected run type ${a.runType}`);await this.send({event:s,data:{chunk:r},run_id:e.id,name:a.name,tags:a.tags,metadata:a.metadata},a)}}async onLLMEnd(e){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 a=e.outputs?.generations;let r;if(t.runType==="chat_model"){for(const s of a??[]){if(r!==void 0)break;r=s[0]?.message}n="on_chat_model_end"}else if(t.runType==="llm")r={generations:a?.map(s=>s.map(i=>({text:i.text,generationInfo:i.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=jt(e),n=e.run_type??"chain",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let r={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(r={},a.inputs={}):e.inputs.input!==void 0?(r.input=e.inputs.input,a.inputs=e.inputs.input):(r.input=e.inputs,a.inputs=e.inputs),this.runInfoMap.set(e.id,a),await this.send({event:`on_${n}_start`,data:r,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const n=`on_${e.run_type}_end`,a=e.inputs??t.inputs??{},s={output:e.outputs?.output??e.outputs,input:a};a.input&&Object.keys(a).length===1&&(s.input=a.input,t.inputs=a.input),await this.sendEndEvent({event:n,data:s,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=jt(e),n={tags:e.tags??[],metadata:e.extra?.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:e.extra?.metadata??{}},n)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const n=e.outputs?.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){const t=jt(e),a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,a),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){const a=this.runInfoMap.get(n);if(a===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:a.tags,metadata:a.metadata,data:t},a)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},Ul={};F(Ul,{AsyncCaller:()=>cn});const Bl=[400,401,402,403,404,405,406,407,409],zl=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e?.code==="ECONNABORTED")throw e;const t=e?.response?.status??e?.status;if(t&&Bl.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){const n=new Error(e?.message);throw n.name="InsufficientQuotaError",n}};var cn=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??zl;const t="default"in Pe?Pe.default:Pe;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>Ht(()=>e(...t).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((a,r)=>{e.signal?.addEventListener("abort",()=>{r(Jt(e.signal))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}},js=class extends ft{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:n,onError:a}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=a}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function Oa(e){return e?e.lc_runnable:!1}var Hl=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const a=e.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t)),this.includeTags!==void 0&&(n=n||a.some(r=>this.includeTags?.includes(r))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n=n&&a.every(r=>!this.excludeTags?.includes(r))),n}};function Z(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_zod"in t))return!1;const n=t._zod;return typeof n=="object"&&n!==null&&"def"in n}function Y(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_def"in t)||"_zod"in t)return!1;const n=t._def;return typeof n=="object"&&n!=null&&"typeName"in n}function Gl(e){return Z(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Y(e)}function kt(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(Z(e)||Y(e))}function Ds(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function Fs(e){return Z(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function Vl(e){return!!(Ds(e)||Fs(e))}async function Zl(e,t){if(Z(e))try{return{success:!0,data:await kr(e,t)}}catch(n){return{success:!1,error:n}}if(Y(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Ca(e,t){if(Z(e))return await kr(e,t);if(Y(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function ql(e,t){if(Z(e))try{return{success:!0,data:ca(e,t)}}catch(n){return{success:!1,error:n}}if(Y(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Jl(e,t){if(Z(e))return ca(e,t);if(Y(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function xa(e){if(Z(e))return he.get(e)?.description;if(Y(e)||"description"in e&&typeof e.description=="string")return e.description}function Wl(e){if(!kt(e))return!1;if(Y(e)){const t=e._def;if(t.typeName==="ZodObject"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(Z(e)){const t=e._zod.def;if(t.type==="object"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function Us(e){return kt(e)?Y(e)?e._def.typeName==="ZodString":Z(e)?e._zod.def.type==="string":!1:!1}function Na(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function Ce(e){return Z(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function ln(e){return Z(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function Kl(e){return!!(Na(e)||Ce(e))}function ta(e){if(Y(e))return e.shape;if(Z(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Yl(e,t){if(Y(e))return e.extend(t);if(Z(e))return Pi(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ql(e){if(Y(e))return e.partial();if(Z(e))return Ri(Rr,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Yt(e,t=!1){if(Y(e))return e.strict();if(Ce(e)){const n=e._zod.def.shape;if(t)for(const[s,i]of Object.entries(e._zod.def.shape)){if(Ce(i)){const c=Yt(i,t);n[s]=c}else if(ln(i)){let c=i._zod.def.element;Ce(c)&&(c=Yt(c,t)),n[s]=Ke(i,{...i._zod.def,element:c})}else n[s]=i;const o=he.get(i);o&&he.add(n[s],o)}const a=Ke(e,{...e._zod.def,shape:n,catchall:Ci(xi)}),r=he.get(e);return r&&he.add(a,r),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function na(e,t=!1){if(Na(e))return e.passthrough();if(Ce(e)){const n=e._zod.def.shape;if(t)for(const[s,i]of Object.entries(e._zod.def.shape)){if(Ce(i)){const c=na(i,t);n[s]=c}else if(ln(i)){let c=i._zod.def.element;Ce(c)&&(c=na(c,t)),n[s]=Ke(i,{...i._zod.def,element:c})}else n[s]=i;const o=he.get(i);o&&he.add(n[s],o)}const a=Ke(e,{...e._zod.def,shape:n,catchall:Ni(ki)}),r=he.get(e);return r&&he.add(a,r),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Xl(e){if(Y(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(Z(e))try{const t=ca(e,void 0);return()=>t}catch{return}}function eu(e){return Y(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function tu(e){return Z(e)&&e._zod.def.type==="pipe"}function ct(e,t=!1){if(Y(e))return eu(e)?ct(e._def.schema,t):e;if(Z(e)){let n=e;if(tu(e)&&(n=ct(e._zod.def.in,t)),t){if(Ce(n)){const r=n._zod.def.shape;for(const[s,i]of Object.entries(n._zod.def.shape))r[s]=ct(i,t);n=Ke(n,{...n._zod.def,shape:r})}else if(ln(n)){const r=ct(n._zod.def.element,t);n=Ke(n,{...n._zod.def,element:r})}}const a=he.get(e);return a&&he.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function nu(e,t){if(Y(e)){const n=ta(e),a={};for(const[r,s]of Object.entries(n))t(r,s)?a[r]=s.optional():a[r]=s;return e.extend(a)}if(Z(e)){const n=ta(e),a={...e._zod.def.shape};for(const[i,o]of Object.entries(n))t(i,o)&&(a[i]=new Rr({type:"optional",innerType:o}));const r=Ke(e,{...e._zod.def,shape:a}),s=he.get(e);return s&&he.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function kn(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const au=["*","_","`"];function ru(e){let t="";for(const[n,a]of Object.entries(e))t+=` classDef ${n} ${a};
58
+ `)}var kl=class extends Error{constructor(e,t,n,a,r){super(_r(e,{name:t,index:n,operation:a,tree:r})),this.name=t,this.index=n,this.operation=a,this.tree=r,Object.setPrototypeOf(this,new.target.prototype),this.message=_r(e,{name:t,index:n,operation:a,tree:r})}},ks={};F(ks,{JsonPatchError:()=>G,_areEquals:()=>At,applyOperation:()=>Je,applyPatch:()=>dt,applyReducer:()=>Ml,deepClone:()=>Rl,getValueByPointer:()=>Wt,validate:()=>Rs,validator:()=>Kt});const G=kl,Rl=be,ot={add:function(e,t,n){return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){var a=e[t];return delete e[t],{newDocument:n,removed:a}},replace:function(e,t,n){var a=e[t];return e[t]=this.value,{newDocument:n,removed:a}},move:function(e,t,n){let a=Wt(n,this.path);a&&(a=be(a));const r=Je(n,{op:"remove",path:this.from}).removed;return Je(n,{op:"add",path:this.path,value:r}),{newDocument:n,removed:a}},copy:function(e,t,n){const a=Wt(n,this.from);return Je(n,{op:"add",path:this.path,value:be(a)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:At(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}};var Pl={add:function(e,t,n){return Wn(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){var a=e.splice(t,1);return{newDocument:n,removed:a[0]}},replace:function(e,t,n){var a=e[t];return e[t]=this.value,{newDocument:n,removed:a}},move:ot.move,copy:ot.copy,test:ot.test,_get:ot._get};function Wt(e,t){if(t=="")return e;var n={op:"_get",path:t};return Je(e,n),n.value}function Je(e,t,n=!1,a=!0,r=!0,s=0){if(n&&(typeof n=="function"?n(t,0,e,t.path):Kt(t,0)),t.path===""){let i={newDocument:e};if(t.op==="add")return i.newDocument=t.value,i;if(t.op==="replace")return i.newDocument=t.value,i.removed=e,i;if(t.op==="move"||t.op==="copy")return i.newDocument=Wt(e,t.from),t.op==="move"&&(i.removed=e),i;if(t.op==="test"){if(i.test=At(e,t.value),i.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return i.newDocument=e,i}else{if(t.op==="remove")return i.removed=e,i.newDocument=null,i;if(t.op==="_get")return t.value=e,i;if(n)throw new G("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,t,e);return i}}else{a||(e=be(e));const o=(t.path||"").split("/");let c=e,l=1,d=o.length,p,f,m;for(typeof n=="function"?m=n:m=Kt;;){if(f=o[l],f&&f.indexOf("~")!=-1&&(f=Nl(f)),r&&(f=="__proto__"||f=="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(n&&p===void 0&&(c[f]===void 0?p=o.slice(0,l).join("/"):l==d-1&&(p=t.path),p!==void 0&&m(t,0,e,p)),l++,Array.isArray(c)){if(f==="-")f=c.length;else{if(n&&!Wn(f))throw new G("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",s,t,e);Wn(f)&&(f=~~f)}if(l>=d){if(n&&t.op==="add"&&f>c.length)throw new G("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);const y=Pl[t.op].call(t,c,f,e);if(y.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return y}}else if(l>=d){const y=ot[t.op].call(t,c,f,e);if(y.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return y}if(c=c[f],n&&l<d&&(!c||typeof c!="object"))throw new G("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,t,e)}}}function dt(e,t,n,a=!0,r=!0){if(n&&!Array.isArray(t))throw new G("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");a||(e=be(e));const s=new Array(t.length);for(let i=0,o=t.length;i<o;i++)s[i]=Je(e,t[i],n,!0,r,i),e=s[i].newDocument;return s.newDocument=e,s}function Ml(e,t,n){const a=Je(e,t);if(a.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a.newDocument}function Kt(e,t,n,a){if(typeof e!="object"||e===null||Array.isArray(e))throw new G("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,n);if(ot[e.op]){if(typeof e.path!="string")throw new G("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,n);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new G('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,n);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new G("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new G("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&Kn(e.value))throw new G("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,n);if(n){if(e.op=="add"){var r=e.path.split("/").length,s=a.split("/").length;if(r!==s+1&&r!==s)throw new G("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,n)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==a)throw new G("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,n)}else if(e.op==="move"||e.op==="copy"){var i={op:"_get",path:e.from,value:void 0},o=Rs([i],n);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new G("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new G("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function Rs(e,t,n){try{if(!Array.isArray(e))throw new G("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)dt(be(t),be(e),n||!0);else{n=n||Kt;for(var a=0;a<e.length;a++)n(e[a],a,t,void 0)}}catch(r){if(r instanceof G)return r;throw r}}function At(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var n=Array.isArray(e),a=Array.isArray(t),r,s,i;if(n&&a){if(s=e.length,s!=t.length)return!1;for(r=s;r--!==0;)if(!At(e[r],t[r]))return!1;return!0}if(n!=a)return!1;var o=Object.keys(e);if(s=o.length,s!==Object.keys(t).length)return!1;for(r=s;r--!==0;)if(!t.hasOwnProperty(o[r]))return!1;for(r=s;r--!==0;)if(i=o[r],!At(e[i],t[i]))return!1;return!0}return e!==e&&t!==t}function Ps(e,t,n,a,r){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=Jn(t),i=Jn(e),o=!1,c=i.length-1;c>=0;c--){var l=i[c],d=e[l];if(qn(t,l)&&!(t[l]===void 0&&d!==void 0&&Array.isArray(t)===!1)){var p=t[l];typeof d=="object"&&d!=null&&typeof p=="object"&&p!=null&&Array.isArray(d)===Array.isArray(p)?Ps(d,p,n,a+"/"+rt(l),r):d!==p&&(r&&n.push({op:"test",path:a+"/"+rt(l),value:be(d)}),n.push({op:"replace",path:a+"/"+rt(l),value:be(p)}))}else Array.isArray(e)===Array.isArray(t)?(r&&n.push({op:"test",path:a+"/"+rt(l),value:be(d)}),n.push({op:"remove",path:a+"/"+rt(l)}),o=!0):(r&&n.push({op:"test",path:a,value:e}),n.push({op:"replace",path:a,value:t}))}if(!(!o&&s.length==i.length))for(var c=0;c<s.length;c++){var l=s[c];!qn(e,l)&&t[l]!==void 0&&n.push({op:"add",path:a+"/"+rt(l),value:be(t[l])})}}}function Aa(e,t,n=!1){var a=[];return Ps(e,t,a,"",n),a}({...ks});var Ll={};F(Ll,{LogStreamCallbackHandler:()=>Qn,RunLog:()=>Ia,RunLogPatch:()=>ke,isLogStreamHandler:()=>Ms});var ke=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),n=dt({},t);return new Ia({ops:t,state:n[n.length-1].newDocument})}},Ia=class Yn extends ke{state;constructor(t){super(t),this.state=t.state}concat(t){const n=this.ops.concat(t.ops),a=dt(this.state,t.ops);return new Yn({ops:n,state:a[a.length-1].newDocument})}static fromRunLogPatch(t){const n=dt({},t.ops);return new Yn({ops:t.ops,state:n[n.length-1].newDocument})}};const Ms=e=>e.name==="log_stream_tracer";async function yr(e,t){if(t==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:n}=e;if(["retriever","llm","prompt"].includes(e.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===""))return n.input}async function wr(e,t){const{outputs:n}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function $l(e){return e!==void 0&&e.message!==void 0}var Qn=class extends ft{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Te.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(a=>this.includeTags?.includes(a))!==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(a=>!this.excludeTags?.includes(a))),n}async*tapOutputIterable(e,t){for await(const n of t){if(e!==this.rootId){const a=this.keyMapByRunId[e];a&&await this.writer.write(new ke({ops:[{op:"add",path:`/logs/${a}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new ke({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:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(n.inputs=await yr(e,this._schemaFormat)),await this.writer.write(new ke({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 yr(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await wr(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 a=new ke({ops:n});await this.writer.write(a)}finally{if(e.id===this.rootId){const t=new ke({ops:[{op:"replace",path:"/final_output",value:await wr(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){const a=this.keyMapByRunId[e.id];if(a===void 0)return;const r=e.inputs.messages!==void 0;let s;r?$l(n?.chunk)?s=n?.chunk:s=new tt({id:`run-${e.id}`,content:t}):s=t;const i=new ke({ops:[{op:"add",path:`/logs/${a}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${a}/streamed_output/-`,value:s}]});await this.writer.write(i)}},jl={};F(jl,{ChatGenerationChunk:()=>ea,GenerationChunk:()=>It,RUN_KEY:()=>Xn});const Xn="__run";var It=class Ls{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new Ls({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},ea=class $s extends It{message;constructor(t){super(t),this.message=t.message}concat(t){return new $s({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function jt({name:e,serialized:t}){return e!==void 0?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const Dl=e=>e.name==="event_stream_tracer";var Fl=class extends ft{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Te.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(a=>this.includeTags?.includes(a))!==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(a=>!this.excludeTags?.includes(a))),n}async*tapOutputIterable(e,t){const n=await t.next();if(n.done)return;const a=this.runInfoMap.get(e);if(a===void 0){yield n.value;return}function r(i,o){return i==="llm"&&typeof o=="string"?new It({text:o}):o}let s=this.tappedPromises.get(e);if(s===void 0){let i;s=new Promise(o=>{i=o}),this.tappedPromises.set(e,s);try{const o={event:`on_${a.runType}_stream`,run_id:e,name:a.name,tags:a.tags,metadata:a.metadata,data:{}};await this.send({...o,data:{chunk:r(a.runType,n.value)}},a),yield n.value;for await(const c of t)a.runType!=="tool"&&a.runType!=="retriever"&&await this.send({...o,data:{chunk:r(a.runType,c)}},a),yield c}finally{i?.()}}else{yield n.value;for await(const i of t)yield i}}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){const t=jt(e),n=e.inputs.messages!==void 0?"chat_model":"llm",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,a);const r=`on_${n}_start`;await this.send({event:r,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onLLMNewToken(e,t,n){const a=this.runInfoMap.get(e.id);let r,s;if(a===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(a.runType==="chat_model")s="on_chat_model_stream",n?.chunk===void 0?r=new tt({content:t,id:`run-${e.id}`}):r=n.chunk.message;else if(a.runType==="llm")s="on_llm_stream",n?.chunk===void 0?r=new It({text:t}):r=n.chunk;else throw new Error(`Unexpected run type ${a.runType}`);await this.send({event:s,data:{chunk:r},run_id:e.id,name:a.name,tags:a.tags,metadata:a.metadata},a)}}async onLLMEnd(e){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 a=e.outputs?.generations;let r;if(t.runType==="chat_model"){for(const s of a??[]){if(r!==void 0)break;r=s[0]?.message}n="on_chat_model_end"}else if(t.runType==="llm")r={generations:a?.map(s=>s.map(i=>({text:i.text,generationInfo:i.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=jt(e),n=e.run_type??"chain",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let r={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(r={},a.inputs={}):e.inputs.input!==void 0?(r.input=e.inputs.input,a.inputs=e.inputs.input):(r.input=e.inputs,a.inputs=e.inputs),this.runInfoMap.set(e.id,a),await this.send({event:`on_${n}_start`,data:r,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const n=`on_${e.run_type}_end`,a=e.inputs??t.inputs??{},s={output:e.outputs?.output??e.outputs,input:a};a.input&&Object.keys(a).length===1&&(s.input=a.input,t.inputs=a.input),await this.sendEndEvent({event:n,data:s,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=jt(e),n={tags:e.tags??[],metadata:e.extra?.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:e.extra?.metadata??{}},n)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const n=e.outputs?.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){const t=jt(e),a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,a),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){const a=this.runInfoMap.get(n);if(a===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:a.tags,metadata:a.metadata,data:t},a)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},Ul={};F(Ul,{AsyncCaller:()=>cn});const Bl=[400,401,402,403,404,405,406,407,409],zl=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e?.code==="ECONNABORTED")throw e;const t=e?.response?.status??e?.status;if(t&&Bl.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){const n=new Error(e?.message);throw n.name="InsufficientQuotaError",n}};var cn=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??zl;const t="default"in Pe?Pe.default:Pe;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>Ht(()=>e(...t).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((a,r)=>{e.signal?.addEventListener("abort",()=>{r(Jt(e.signal))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}},js=class extends ft{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:n,onError:a}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=a}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function Oa(e){return e?e.lc_runnable:!1}var Hl=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const a=e.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t)),this.includeTags!==void 0&&(n=n||a.some(r=>this.includeTags?.includes(r))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n=n&&a.every(r=>!this.excludeTags?.includes(r))),n}};function Z(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_zod"in t))return!1;const n=t._zod;return typeof n=="object"&&n!==null&&"def"in n}function Y(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_def"in t)||"_zod"in t)return!1;const n=t._def;return typeof n=="object"&&n!=null&&"typeName"in n}function Gl(e){return Z(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Y(e)}function kt(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(Z(e)||Y(e))}function Ds(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function Fs(e){return Z(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function Vl(e){return!!(Ds(e)||Fs(e))}async function Zl(e,t){if(Z(e))try{return{success:!0,data:await kr(e,t)}}catch(n){return{success:!1,error:n}}if(Y(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Ca(e,t){if(Z(e))return await kr(e,t);if(Y(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function ql(e,t){if(Z(e))try{return{success:!0,data:ca(e,t)}}catch(n){return{success:!1,error:n}}if(Y(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Jl(e,t){if(Z(e))return ca(e,t);if(Y(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function xa(e){if(Z(e))return he.get(e)?.description;if(Y(e)||"description"in e&&typeof e.description=="string")return e.description}function Wl(e){if(!kt(e))return!1;if(Y(e)){const t=e._def;if(t.typeName==="ZodObject"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(Z(e)){const t=e._zod.def;if(t.type==="object"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function Us(e){return kt(e)?Y(e)?e._def.typeName==="ZodString":Z(e)?e._zod.def.type==="string":!1:!1}function Na(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function Ce(e){return Z(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function ln(e){return Z(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function Kl(e){return!!(Na(e)||Ce(e))}function ta(e){if(Y(e))return e.shape;if(Z(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Yl(e,t){if(Y(e))return e.extend(t);if(Z(e))return Ri(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ql(e){if(Y(e))return e.partial();if(Z(e))return ki(Rr,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Yt(e,t=!1){if(Y(e))return e.strict();if(Ce(e)){const n=e._zod.def.shape;if(t)for(const[s,i]of Object.entries(e._zod.def.shape)){if(Ce(i)){const c=Yt(i,t);n[s]=c}else if(ln(i)){let c=i._zod.def.element;Ce(c)&&(c=Yt(c,t)),n[s]=Ke(i,{...i._zod.def,element:c})}else n[s]=i;const o=he.get(i);o&&he.add(n[s],o)}const a=Ke(e,{...e._zod.def,shape:n,catchall:Ci(xi)}),r=he.get(e);return r&&he.add(a,r),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function na(e,t=!1){if(Na(e))return e.passthrough();if(Ce(e)){const n=e._zod.def.shape;if(t)for(const[s,i]of Object.entries(e._zod.def.shape)){if(Ce(i)){const c=na(i,t);n[s]=c}else if(ln(i)){let c=i._zod.def.element;Ce(c)&&(c=na(c,t)),n[s]=Ke(i,{...i._zod.def,element:c})}else n[s]=i;const o=he.get(i);o&&he.add(n[s],o)}const a=Ke(e,{...e._zod.def,shape:n,catchall:Ni(Pi)}),r=he.get(e);return r&&he.add(a,r),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Xl(e){if(Y(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(Z(e))try{const t=ca(e,void 0);return()=>t}catch{return}}function eu(e){return Y(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function tu(e){return Z(e)&&e._zod.def.type==="pipe"}function ct(e,t=!1){if(Y(e))return eu(e)?ct(e._def.schema,t):e;if(Z(e)){let n=e;if(tu(e)&&(n=ct(e._zod.def.in,t)),t){if(Ce(n)){const r=n._zod.def.shape;for(const[s,i]of Object.entries(n._zod.def.shape))r[s]=ct(i,t);n=Ke(n,{...n._zod.def,shape:r})}else if(ln(n)){const r=ct(n._zod.def.element,t);n=Ke(n,{...n._zod.def,element:r})}}const a=he.get(e);return a&&he.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function nu(e,t){if(Y(e)){const n=ta(e),a={};for(const[r,s]of Object.entries(n))t(r,s)?a[r]=s.optional():a[r]=s;return e.extend(a)}if(Z(e)){const n=ta(e),a={...e._zod.def.shape};for(const[i,o]of Object.entries(n))t(i,o)&&(a[i]=new Rr({type:"optional",innerType:o}));const r=Ke(e,{...e._zod.def,shape:a}),s=he.get(e);return s&&he.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function kn(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const au=["*","_","`"];function ru(e){let t="";for(const[n,a]of Object.entries(e))t+=` classDef ${n} ${a};
59
59
  `;return t}function su(e,t,n){const{firstNode:a,lastNode:r,nodeColors:s,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=n??{};let l=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
60
60
  graph TD;
61
61
  `:`graph TD;