zen-code 4.10.2 → 5.0.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.
- package/dist/app.js +149 -239
- package/dist/{chunk-vbb3m0vz.js → chunk-069q9hkz.js} +1 -1
- package/dist/chunk-06trk066.js +1 -0
- package/dist/chunk-0kfw8bwn.js +2 -0
- package/dist/chunk-0mq8786q.js +281 -0
- package/dist/{chunk-mmx0k2yq.js → chunk-0qz8rr2k.js} +1 -1
- package/dist/chunk-1d47g6nc.js +2 -0
- package/dist/{chunk-nqh1pptf.js → chunk-1gssqf6g.js} +1 -1
- package/dist/{chunk-s5cqejr6.js → chunk-1rcc9xzn.js} +1 -1
- package/dist/{chunk-tjvhqr94.js → chunk-2bjeg40f.js} +1 -1
- package/dist/chunk-2gd8vzrf.js +2 -0
- package/dist/{chunk-spx7nn8t.js → chunk-2gprcgep.js} +2 -2
- package/dist/chunk-3k3c686f.js +1 -0
- package/dist/chunk-43h0n2td.js +1 -0
- package/dist/{chunk-8f19qk9r.js → chunk-492hjs9k.js} +1 -1
- package/dist/{chunk-pe8mzxwn.js → chunk-4eaqmt3c.js} +11 -11
- package/dist/{chunk-y8qhrx11.js → chunk-4fs853nh.js} +1 -1
- package/dist/chunk-5fe27s34.js +2 -0
- package/dist/{chunk-4wnmk2tj.js → chunk-5hqvapp1.js} +3 -3
- package/dist/chunk-6b3vfr39.js +2 -0
- package/dist/{chunk-t6440ajd.js → chunk-6j695pam.js} +2 -2
- package/dist/{chunk-pzb224c5.js → chunk-6saqxa3z.js} +2 -2
- package/dist/{chunk-tjg2e8v3.js → chunk-78ksrp8v.js} +2 -2
- package/dist/chunk-7cx9kda0.js +228 -0
- package/dist/chunk-7qba2raw.js +2 -0
- package/dist/chunk-81b2s97q.js +1 -0
- package/dist/chunk-88w3txtb.js +160 -0
- package/dist/chunk-8ygdre0g.js +1 -0
- package/dist/{chunk-fzh0v6r0.js → chunk-9011y634.js} +2 -2
- package/dist/chunk-9zcr1qh6.js +1 -0
- package/dist/chunk-a0nr8jva.js +2 -0
- package/dist/{chunk-5c3bpcpm.js → chunk-agevsn2e.js} +1 -1
- package/dist/{chunk-8tbtavry.js → chunk-akc3s5aw.js} +2 -2
- package/dist/{chunk-spa69h7p.js → chunk-b0beqmg2.js} +2 -2
- package/dist/{chunk-zg54h6gy.js → chunk-b175s7dm.js} +1 -1
- package/dist/chunk-bk32cwxa.js +5 -0
- package/dist/{chunk-vrnj0659.js → chunk-bn077sjq.js} +15 -15
- package/dist/{chunk-qxebn3jw.js → chunk-c9yrpb3g.js} +3 -3
- package/dist/{chunk-hnnwbfqk.js → chunk-cb0f54ar.js} +2 -2
- package/dist/chunk-ctqtahz4.js +1 -0
- package/dist/{chunk-gt8c6dne.js → chunk-d2sr8fnm.js} +1 -1
- package/dist/chunk-d5gzkkgg.js +1 -0
- package/dist/{chunk-bzgznka5.js → chunk-dh2f4xyb.js} +1 -1
- package/dist/chunk-dr32dt9y.js +1 -0
- package/dist/chunk-dv1vt080.js +1 -0
- package/dist/{chunk-vfxjbdz4.js → chunk-dz9sqfph.js} +1 -1
- package/dist/chunk-e7mbewmw.js +1 -0
- package/dist/chunk-em03xqy9.js +1 -0
- package/dist/chunk-fkt5b511.js +1 -0
- package/dist/{chunk-k4q8j7pg.js → chunk-gphssgy6.js} +1 -1
- package/dist/chunk-h2hk7vx4.js +1 -0
- package/dist/{chunk-c7kd2qrp.js → chunk-h7ypcqp3.js} +112 -111
- package/dist/{chunk-nsw5168d.js → chunk-j8tq0e8m.js} +2 -2
- package/dist/{chunk-40ht9pe1.js → chunk-jd1razfg.js} +2 -2
- package/dist/chunk-jhxvctg5.js +8 -0
- package/dist/chunk-kada5fyh.js +1 -0
- package/dist/chunk-kgc6ws03.js +1 -0
- package/dist/chunk-mk8ggmt8.js +17 -0
- package/dist/{chunk-e8kxa5vj.js → chunk-mv5m8bf4.js} +2 -2
- package/dist/chunk-mv8a5svx.js +1 -0
- package/dist/chunk-n61yv4t5.js +2 -0
- package/dist/chunk-nt2yp4jh.js +1 -0
- package/dist/chunk-p7ew4trx.js +1 -0
- package/dist/{chunk-s1tbdcs8.js → chunk-pgnhcznr.js} +1 -1
- package/dist/chunk-q8cfxky4.js +8 -0
- package/dist/{chunk-g2zskge5.js → chunk-q8zsxwd8.js} +2 -2
- package/dist/{chunk-nmzx5nmt.js → chunk-qfa5v4n5.js} +1 -1
- package/dist/chunk-qhzztj83.js +1 -0
- package/dist/chunk-snmkgfbe.js +15 -0
- package/dist/chunk-ss4bh5wb.js +2 -0
- package/dist/chunk-sv0k2v66.js +1 -0
- package/dist/{chunk-wmyc17aa.js → chunk-tbav8trq.js} +1 -1
- package/dist/chunk-tmyzfvsy.js +1 -0
- package/dist/chunk-ts4jreym.js +7 -0
- package/dist/chunk-tws3wcnm.js +2 -0
- package/dist/chunk-v0e9bsvt.js +89 -0
- package/dist/{chunk-n9rpnke9.js → chunk-vwj4n000.js} +1 -1
- package/dist/{chunk-gfhmzpy7.js → chunk-wd6s7gg7.js} +2 -3
- package/dist/{chunk-f0m4532p.js → chunk-y524zd2h.js} +5 -5
- package/dist/{chunk-hve2a279.js → chunk-yb71zqvt.js} +2 -2
- package/dist/{chunk-n7s6my89.js → chunk-yejgw2hm.js} +32 -32
- package/dist/{chunk-g974hxbz.js → chunk-yfjs6pf8.js} +1 -1
- package/dist/chunk-zhqdp4ak.js +2 -0
- package/dist/chunk-zkd3m39v.js +1 -0
- package/dist/cli.js +1 -1
- package/dist/nonInteractive.js +80 -80
- package/dist/zen-core.js +644 -0
- package/dist/zen-keyboard.js +1 -1
- package/package.json +5 -3
- package/dist/chunk-0ddrb30y.js +0 -1
- package/dist/chunk-215an3fz.js +0 -1
- package/dist/chunk-4z0w0ng1.js +0 -2
- package/dist/chunk-57bj89e2.js +0 -1
- package/dist/chunk-5a5mepqj.js +0 -1
- package/dist/chunk-7kw7ss8d.js +0 -1
- package/dist/chunk-86m0rmtc.js +0 -1
- package/dist/chunk-9rayxazs.js +0 -8
- package/dist/chunk-a9gpb2tx.js +0 -2
- package/dist/chunk-a9tw6d68.js +0 -1
- package/dist/chunk-anbtppz1.js +0 -294
- package/dist/chunk-bca8tkkr.js +0 -1
- package/dist/chunk-bdqds8vh.js +0 -1
- package/dist/chunk-dvbb3dd1.js +0 -233
- package/dist/chunk-ehmmd8qc.js +0 -1
- package/dist/chunk-ejfa95sm.js +0 -1
- package/dist/chunk-f7cps5x1.js +0 -1
- package/dist/chunk-fbemqjck.js +0 -2
- package/dist/chunk-feeqtzv5.js +0 -1
- package/dist/chunk-g9911ymn.js +0 -1
- package/dist/chunk-h8fdexm4.js +0 -2
- package/dist/chunk-hp2jzn9x.js +0 -166
- package/dist/chunk-js4qp900.js +0 -2
- package/dist/chunk-m21hvv91.js +0 -2
- package/dist/chunk-mnnyjmgw.js +0 -224
- package/dist/chunk-mw7x6xqp.js +0 -1
- package/dist/chunk-nk62q95g.js +0 -93
- package/dist/chunk-pg1ppq4y.js +0 -1
- package/dist/chunk-q1cxrg0x.js +0 -2
- package/dist/chunk-swc7se71.js +0 -2
- package/dist/chunk-swyc15ym.js +0 -1
- package/dist/chunk-t2s3s6af.js +0 -1
- package/dist/chunk-vdmq9d9x.js +0 -4
- package/dist/chunk-wt3p1w1g.js +0 -1
- package/dist/chunk-y5ry5c7v.js +0 -1
- package/dist/chunk-yy8p9zph.js +0 -2
- package/dist/chunk-z61m3anh.js +0 -1
- package/dist/chunk-zr90qp47.js +0 -1
- package/dist/chunk-zsa62xr0.js +0 -2
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import{Ek as g1,Fk as m1,Gk as kY,Hk as bG,Ik as Q1,Jk as $1,Kk as k1,Lk as Y1,Mk as I1,Nk as x1}from"./chunk-bk32cwxa.js";import{Pk as x,Qk as tQ}from"./chunk-qfa5v4n5.js";import{Bl as y1,Tk as vQ,Uk as aY,Vk as L$,Wk as eY,Yk as uW,Zk as cW,_k as Q8,al as KQ,bl as lW,cl as iW,dl as k8}from"./chunk-78ksrp8v.js";import{Cl as NG,Dl as m0,El as pQ,Fl as PW,Hl as FQ,Jl as Q0}from"./chunk-yb71zqvt.js";import{Wl as rQ}from"./chunk-4fs853nh.js";var r8=Object.defineProperty,M=(Q,$)=>{let Y={};for(var q in Q)r8(Y,q,{get:Q[q],enumerable:!0});if(!$)r8(Y,Symbol.toStringTag,{value:"Module"});return Y};function fQ(Q){return!!(Q&&typeof Q==="object"&&("type"in Q)&&Q.type==="tool_call")}function a8(Q){return!!(Q&&typeof Q==="object"&&("toolCall"in Q)&&Q.toolCall!=null&&typeof Q.toolCall==="object"&&("id"in Q.toolCall)&&typeof Q.toolCall.id==="string")}var U0=class extends Error{output;constructor(Q,$){super(Q);this.output=$}};var e8=rQ(g1(),1),Q6=rQ(m1(),1);function $6(Q,$){return $?.[Q]||e8.default(Q)}function rJ(Q,$){return $?.[Q]||Q6.default(Q)}function Y6(Q,$,Y){let q={};for(let W in Q)if(Object.hasOwn(Q,W))q[$(W,Y)]=Q[W];return q}function d1(Q){return"lc"in Q||Object.keys(Q).length===1&&"__lc_escaped__"in Q}function p1(Q){return{["__lc_escaped__"]:Q}}function u1(Q){return Object.keys(Q).length===1&&"__lc_escaped__"in Q}function c1(Q){return Q!==null&&typeof Q==="object"&&"lc_serializable"in Q&&typeof Q.toJSON==="function"}function l1(Q){let $;if(Q!==null&&typeof Q==="object")if("lc_id"in Q&&Array.isArray(Q.lc_id))$=Q.lc_id;else $=[Q.constructor?.name??"Object"];else $=[typeof Q];return{lc:1,type:"not_implemented",id:$}}function d0(Q,$=new WeakSet){if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q)){if($.has(Q))return l1(Q);if(c1(Q))return Q;$.add(Q);let Y=Q;if(d1(Y))return $.delete(Q),p1(Y);let q={};for(let[W,Z]of Object.entries(Y))q[W]=d0(Z,$);return $.delete(Q),q}if(Array.isArray(Q))return Q.map((Y)=>d0(Y,$));return Q}function q6(Q){if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q)){let $=Q;if(u1($))return $.__lc_escaped__;let Y={};for(let[q,W]of Object.entries($))Y[q]=q6(W);return Y}if(Array.isArray(Q))return Q.map(($)=>q6($));return Q}var q9=M({Serializable:()=>RQ,get_lc_unique_name:()=>p0});function W6(Q){return Array.isArray(Q)?[...Q]:{...Q}}function i1(Q,$){let Y=W6(Q);for(let[q,W]of Object.entries($)){let[Z,...G]=q.split(".").reverse(),J=Y;for(let z of G.reverse()){if(J[z]===void 0)break;J[z]=W6(J[z]),J=J[z]}if(J[Z]!==void 0)J[Z]={lc:1,type:"secret",id:[W]}}return Y}function p0(Q){let $=Object.getPrototypeOf(Q);if(typeof Q.lc_name==="function"&&(typeof $.lc_name!=="function"||Q.lc_name()!==$.lc_name()))return Q.lc_name();else return Q.name}var RQ=class Q{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,p0(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor($,...Y){if(this.lc_serializable_keys!==void 0)this.lc_kwargs=Object.fromEntries(Object.entries($||{}).filter(([q])=>this.lc_serializable_keys?.includes(q)));else this.lc_kwargs=$??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Q||typeof this.lc_kwargs!=="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let $={},Y={},q=Object.keys(this.lc_kwargs).reduce((J,z)=>{return J[z]=z in this?this[z]:this.lc_kwargs[z],J},{});for(let J=Object.getPrototypeOf(this);J;J=Object.getPrototypeOf(J))Object.assign($,Reflect.get(J,"lc_aliases",this)),Object.assign(Y,Reflect.get(J,"lc_secrets",this)),Object.assign(q,Reflect.get(J,"lc_attributes",this));Object.keys(Y).forEach((J)=>{let z=this,K=q,[X,...U]=J.split(".").reverse();for(let N of U.reverse()){if(!(N in z)||z[N]===void 0)return;if(!(N in K)||K[N]===void 0){if(typeof z[N]==="object"&&z[N]!=null)K[N]={};else if(Array.isArray(z[N]))K[N]=[]}z=z[N],K=K[N]}if(X in z&&z[X]!==void 0)K[X]=K[X]||z[X]});let W={},Z=new WeakSet;Z.add(this);for(let[J,z]of Object.entries(q))W[J]=d0(z,Z);let G=Y6(Object.keys(Y).length?i1(W,Y):W,$6,$);return{lc:1,type:"constructor",id:this.lc_id,kwargs:G}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function gQ(Q){return typeof Q==="object"&&Q!==null&&"type"in Q&&typeof Q.type==="string"&&"source_type"in Q&&(Q.source_type==="url"||Q.source_type==="base64"||Q.source_type==="text"||Q.source_type==="id")}function Z6(Q){return gQ(Q)&&Q.source_type==="url"&&"url"in Q&&typeof Q.url==="string"}function G6(Q){return gQ(Q)&&Q.source_type==="base64"&&"data"in Q&&typeof Q.data==="string"}function Z9(Q){return gQ(Q)&&Q.source_type==="text"&&"text"in Q&&typeof Q.text==="string"}function J6(Q){return gQ(Q)&&Q.source_type==="id"&&"id"in Q&&typeof Q.id==="string"}function G9(Q){if(gQ(Q)){if(Q.source_type==="url")return{type:"image_url",image_url:{url:Q.url}};if(Q.source_type==="base64"){if(!Q.mime_type)throw Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${Q.mime_type};base64,${Q.data}`}}}}throw Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function J9(Q){let $=Q.split(";")[0].split("/");if($.length!==2)throw Error(`Invalid mime type: "${Q}" - does not match type/subtype format.`);let Y=$[0].trim(),q=$[1].trim();if(Y===""||q==="")throw Error(`Invalid mime type: "${Q}" - type or subtype is empty.`);let W={};for(let Z of Q.split(";").slice(1)){let G=Z.split("=");if(G.length!==2)throw Error(`Invalid parameter syntax in mime type: "${Q}".`);let J=G[0].trim(),z=G[1].trim();if(J==="")throw Error(`Invalid parameter syntax in mime type: "${Q}".`);W[J]=z}return{type:Y,subtype:q,parameters:W}}function e$({dataUrl:Q,asTypedArray:$=!1}){let Y=Q.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),q;if(Y){q=Y[1].toLowerCase();let W=$?Uint8Array.from(atob(Y[2]),(Z)=>Z.charCodeAt(0)):Y[2];return{mime_type:q,data:W}}}function z9(Q,$){if(Q.type==="text"){if(!$.fromStandardTextBlock)throw Error(`Converter for ${$.providerName} does not implement \`fromStandardTextBlock\` method.`);return $.fromStandardTextBlock(Q)}if(Q.type==="image"){if(!$.fromStandardImageBlock)throw Error(`Converter for ${$.providerName} does not implement \`fromStandardImageBlock\` method.`);return $.fromStandardImageBlock(Q)}if(Q.type==="audio"){if(!$.fromStandardAudioBlock)throw Error(`Converter for ${$.providerName} does not implement \`fromStandardAudioBlock\` method.`);return $.fromStandardAudioBlock(Q)}if(Q.type==="file"){if(!$.fromStandardFileBlock)throw Error(`Converter for ${$.providerName} does not implement \`fromStandardFileBlock\` method.`);return $.fromStandardFileBlock(Q)}throw Error(`Unable to convert content block type '${Q.type}' to provider-specific format: not recognized.`)}function O(Q,$){return P(Q)&&Q.type===$}function P(Q){return typeof Q==="object"&&Q!==null}function o(Q){return Array.isArray(Q)}function V(Q){return typeof Q==="string"}function UQ(Q){return typeof Q==="number"}function u0(Q){return Q instanceof Uint8Array}function QY(Q){try{return JSON.parse(Q)}catch{return}}var NQ=(Q)=>Q();function s1(Q){if(Q.type==="char_location"&&V(Q.document_title)&&UQ(Q.start_char_index)&&UQ(Q.end_char_index)&&V(Q.cited_text)){let{document_title:$,start_char_index:Y,end_char_index:q,cited_text:W,...Z}=Q;return{...Z,type:"citation",source:"char",title:$??void 0,startIndex:Y,endIndex:q,citedText:W}}if(Q.type==="page_location"&&V(Q.document_title)&&UQ(Q.start_page_number)&&UQ(Q.end_page_number)&&V(Q.cited_text)){let{document_title:$,start_page_number:Y,end_page_number:q,cited_text:W,...Z}=Q;return{...Z,type:"citation",source:"page",title:$??void 0,startIndex:Y,endIndex:q,citedText:W}}if(Q.type==="content_block_location"&&V(Q.document_title)&&UQ(Q.start_block_index)&&UQ(Q.end_block_index)&&V(Q.cited_text)){let{document_title:$,start_block_index:Y,end_block_index:q,cited_text:W,...Z}=Q;return{...Z,type:"citation",source:"block",title:$??void 0,startIndex:Y,endIndex:q,citedText:W}}if(Q.type==="web_search_result_location"&&V(Q.url)&&V(Q.title)&&V(Q.encrypted_index)&&V(Q.cited_text)){let{url:$,title:Y,encrypted_index:q,cited_text:W,...Z}=Q;return{...Z,type:"citation",source:"url",url:$,title:Y,startIndex:Number(q),endIndex:Number(q),citedText:W}}if(Q.type==="search_result_location"&&V(Q.source)&&V(Q.title)&&UQ(Q.start_block_index)&&UQ(Q.end_block_index)&&V(Q.cited_text)){let{source:$,title:Y,start_block_index:q,end_block_index:W,cited_text:Z,...G}=Q;return{...G,type:"citation",source:"search",url:$,title:Y??void 0,startIndex:q,endIndex:W,citedText:Z}}}function K6(Q){if(O(Q,"document")&&P(Q.source)&&"type"in Q.source){if(Q.source.type==="base64"&&V(Q.source.media_type)&&V(Q.source.data))return{type:"file",mimeType:Q.source.media_type,data:Q.source.data};else if(Q.source.type==="url"&&V(Q.source.url))return{type:"file",url:Q.source.url};else if(Q.source.type==="file"&&V(Q.source.file_id))return{type:"file",fileId:Q.source.file_id};else if(Q.source.type==="text"&&V(Q.source.data))return{type:"file",mimeType:String(Q.source.media_type??"text/plain"),data:Q.source.data}}else if(O(Q,"image")&&P(Q.source)&&"type"in Q.source){if(Q.source.type==="base64"&&V(Q.source.media_type)&&V(Q.source.data))return{type:"image",mimeType:Q.source.media_type,data:Q.source.data};else if(Q.source.type==="url"&&V(Q.source.url))return{type:"image",url:Q.source.url};else if(Q.source.type==="file"&&V(Q.source.file_id))return{type:"image",fileId:Q.source.file_id}}}function X6(Q){function*$(){for(let Y of Q){let q=K6(Y);if(q)yield q;else yield Y}}return Array.from($())}function z6(Q){function*$(){let Y=typeof Q.content==="string"?[{type:"text",text:Q.content}]:Q.content;for(let q of Y){if(O(q,"text")&&V(q.text)){let{text:W,citations:Z,...G}=q;if(o(Z)&&Z.length){let J=Z.reduce((z,K)=>{let X=s1(K);if(X)return[...z,X];return z},[]);yield{...G,type:"text",text:W,annotations:J};continue}else{yield{...G,type:"text",text:W};continue}}else if(O(q,"thinking")&&V(q.thinking)){let{thinking:W,signature:Z,...G}=q;yield{...G,type:"reasoning",reasoning:W,signature:Z};continue}else if(O(q,"redacted_thinking")){yield{type:"non_standard",value:q};continue}else if(O(q,"tool_use")&&V(q.name)&&V(q.id)){yield{type:"tool_call",id:q.id,name:q.name,args:q.input};continue}else if(O(q,"input_json_delta")){if(o1(Q)&&Q.tool_call_chunks?.length){let W=Q.tool_call_chunks[0];yield{type:"tool_call_chunk",id:W.id,name:W.name,args:W.args,index:W.index};continue}}else if(O(q,"server_tool_use")&&V(q.name)&&V(q.id)){let{name:W,id:Z}=q;if(W==="web_search"){yield{id:Z,type:"server_tool_call",name:"web_search",args:{query:NQ(()=>{if(typeof q.input==="string")return q.input;else if(P(q.input)&&V(q.input.query))return q.input.query;else if(V(q.partial_json)){let G=QY(q.partial_json);if(G?.query)return G.query}return""})}};continue}else if(q.name==="code_execution"){yield{id:Z,type:"server_tool_call",name:"code_execution",args:{code:NQ(()=>{if(typeof q.input==="string")return q.input;else if(P(q.input)&&V(q.input.code))return q.input.code;else if(V(q.partial_json)){let G=QY(q.partial_json);if(G?.code)return G.code}return""})}};continue}}else if(O(q,"web_search_tool_result")&&V(q.tool_use_id)&&o(q.content)){let{content:W,tool_use_id:Z}=q;yield{type:"server_tool_call_result",name:"web_search",toolCallId:Z,status:"success",output:{urls:W.reduce((G,J)=>{if(O(J,"web_search_result"))return[...G,J.url];return G},[])}};continue}else if(O(q,"code_execution_tool_result")&&V(q.tool_use_id)&&P(q.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:q.tool_use_id,status:"success",output:q.content};continue}else if(O(q,"mcp_tool_use")){yield{id:q.id,type:"server_tool_call",name:"mcp_tool_use",args:q.input};continue}else if(O(q,"mcp_tool_result")&&V(q.tool_use_id)&&P(q.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:q.tool_use_id,status:"success",output:q.content};continue}else if(O(q,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:q.input};continue}else if(O(q,"search_result")){yield{id:q.id,type:"non_standard",value:q};continue}else if(O(q,"tool_result")){yield{id:q.id,type:"non_standard",value:q};continue}else{let W=K6(q);if(W){yield W;continue}}yield{type:"non_standard",value:q}}}return Array.from($())}var U6={translateContent:z6,translateContentChunk:z6};function o1(Q){return typeof Q?._getType==="function"&&typeof Q.concat==="function"&&Q._getType()==="ai"}function t1(Q){if(Z6(Q))return{type:Q.type,mimeType:Q.mime_type,url:Q.url,metadata:Q.metadata};if(G6(Q))return{type:Q.type,mimeType:Q.mime_type??"application/octet-stream",data:Q.data,metadata:Q.metadata};if(J6(Q))return{type:Q.type,mimeType:Q.mime_type,fileId:Q.id,metadata:Q.metadata};return Q}function N6(Q){return Q.map(t1)}function B6(Q){if(O(Q,"image_url")&&P(Q.image_url))return!0;if(O(Q,"input_audio")&&P(Q.input_audio))return!0;if(O(Q,"file")&&P(Q.file))return!0;return!1}function F6(Q){if(O(Q,"image_url")&&P(Q.image_url)&&V(Q.image_url.url)){let $=e$({dataUrl:Q.image_url.url});if($)return{type:"image",mimeType:$.mime_type,data:$.data};else return{type:"image",url:Q.image_url.url}}else if(O(Q,"input_audio")&&P(Q.input_audio)&&V(Q.input_audio.data)&&V(Q.input_audio.format))return{type:"audio",data:Q.input_audio.data,mimeType:`audio/${Q.input_audio.format}`};else if(O(Q,"file")&&P(Q.file)&&V(Q.file.data)){let $=e$({dataUrl:Q.file.data});if($)return{type:"file",data:$.data,mimeType:$.mime_type};else if(V(Q.file.file_id))return{type:"file",fileId:Q.file.file_id}}return Q}function n1(Q){let $=[];if(typeof Q.content==="string"){if(Q.content.length>0)$.push({type:"text",text:Q.content})}else $.push(...c0(Q.content));for(let Y of Q.tool_calls??[])$.push({type:"tool_call",id:Y.id,name:Y.name,args:Y.args});return $}function r1(Q){let $=[];if(typeof Q.content==="string"){if(Q.content.length>0)$.push({type:"text",text:Q.content})}else $.push(...c0(Q.content));for(let Y of Q.tool_calls??[])$.push({type:"tool_call",id:Y.id,name:Y.name,args:Y.args});return $}function c0(Q){let $=[];for(let Y of Q)if(B6(Y))$.push(F6(Y));else $.push(Y);return $}function a1(Q){if(Q.type==="url_citation"){let{url:$,title:Y,start_index:q,end_index:W}=Q;return{type:"citation",url:$,title:Y,startIndex:q,endIndex:W}}if(Q.type==="file_citation"){let{file_id:$,filename:Y,index:q}=Q;return{type:"citation",title:Y,startIndex:q,endIndex:q,fileId:$}}return Q}function V6(Q){function*$(){if(P(Q.additional_kwargs?.reasoning)&&o(Q.additional_kwargs.reasoning.summary))yield{type:"reasoning",reasoning:Q.additional_kwargs.reasoning.summary.reduce((q,W)=>{if(P(W)&&V(W.text))return`${q}${W.text}`;return q},"")};let Y=typeof Q.content==="string"?[{type:"text",text:Q.content}]:Q.content;for(let q of Y)if(O(q,"text")){let{text:W,annotations:Z,...G}=q;if(Array.isArray(Z))yield{...G,type:"text",text:String(W),annotations:Z.map(a1)};else yield{...G,type:"text",text:String(W)}}for(let q of Q.tool_calls??[])yield{type:"tool_call",id:q.id,name:q.name,args:q.args};if(P(Q.additional_kwargs)&&o(Q.additional_kwargs.tool_outputs))for(let q of Q.additional_kwargs.tool_outputs){if(O(q,"web_search_call")){let W={};if(P(q.action)&&V(q.action.query))W.query=q.action.query;if(yield{id:q.id,type:"server_tool_call",name:"web_search",args:W},q.status==="completed"||q.status==="failed"){let Z={};if(P(q.action))Z.action=q.action;yield{type:"server_tool_call_result",toolCallId:V(q.id)?q.id:"",status:q.status==="completed"?"success":"error",output:Z}}continue}else if(O(q,"file_search_call")){if(yield{id:q.id,type:"server_tool_call",name:"file_search",args:{queries:o(q.queries)?q.queries:[]}},q.status==="completed"||q.status==="failed")yield{type:"server_tool_call_result",toolCallId:V(q.id)?q.id:"",status:q.status==="completed"?"success":"error",output:o(q.results)?{results:q.results}:{}};continue}else if(O(q,"computer_call")){yield{type:"non_standard",value:q};continue}else if(O(q,"code_interpreter_call")){if(V(q.code))yield{id:q.id,type:"server_tool_call",name:"code_interpreter",args:{code:q.code}};if(o(q.outputs)){let W=NQ(()=>{if(q.status==="in_progress")return;if(q.status==="completed")return 0;if(q.status==="incomplete")return 127;if(q.status==="interpreting")return;if(q.status==="failed")return 1});for(let Z of q.outputs)if(O(Z,"logs")){yield{type:"server_tool_call_result",toolCallId:q.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:W??0,stderr:[0,void 0].includes(W)?void 0:String(Z.logs),stdout:[0,void 0].includes(W)?String(Z.logs):void 0}};continue}}continue}else if(O(q,"mcp_call")){yield{id:q.id,type:"server_tool_call",name:"mcp_call",args:q.input};continue}else if(O(q,"mcp_list_tools")){yield{id:q.id,type:"server_tool_call",name:"mcp_list_tools",args:q.input};continue}else if(O(q,"mcp_approval_request")){yield{type:"non_standard",value:q};continue}else if(O(q,"image_generation_call")){if(V(q.result))yield{type:"image",mimeType:"image/png",data:q.result,id:V(q.id)?q.id:void 0,metadata:{status:V(q.status)?q.status:void 0}};yield{type:"non_standard",value:q};continue}if(P(q))yield{type:"non_standard",value:q}}}return Array.from($())}function e1(Q){function*$(){yield*V6(Q);for(let Y of Q.tool_call_chunks??[])yield{type:"tool_call_chunk",id:Y.id,name:Y.name,args:Y.args}}return Array.from($())}var A6={translateContent:(Q)=>{if(typeof Q.content==="string")return n1(Q);return V6(Q)},translateContentChunk:(Q)=>{if(typeof Q.content==="string")return r1(Q);return e1(Q)}};function H6(Q){return typeof Q==="object"&&Q!==null&&"type"in Q&&"content"in Q&&(typeof Q.content==="string"||Array.isArray(Q.content))}function D6(Q,$="pretty"){if($==="pretty")return QZ(Q);return JSON.stringify(Q)}function QZ(Q){let $=[],Y=` ${Q.type.charAt(0).toUpperCase()+Q.type.slice(1)} Message `,q=Math.floor((80-Y.length)/2),W="=".repeat(q),Z=Y.length%2===0?W:`${W}=`;if($.push(`${W}${Y}${Z}`),Q.type==="ai"){let G=Q;if(G.tool_calls&&G.tool_calls.length>0){$.push("Tool Calls:");for(let J of G.tool_calls){$.push(` ${J.name} (${J.id})`),$.push(` Call ID: ${J.id}`),$.push(" Args:");for(let[z,K]of Object.entries(J.args))$.push(` ${z}: ${typeof K==="object"?JSON.stringify(K):K}`)}}}if(Q.type==="tool"){let G=Q;if(G.name)$.push(`Name: ${G.name}`)}if(typeof Q.content==="string"&&Q.content.trim()){if($.length>1)$.push("");$.push(Q.content)}return $.join(`
|
|
2
|
+
`)}var $Y=Symbol.for("langchain.message");function ZQ(Q,$){if(typeof Q==="string"){if(Q==="")return $;if(typeof $==="string")return Q+$;else if(Array.isArray($)&&$.length===0)return Q;else if(Array.isArray($)&&$.some((Y)=>gQ(Y)))return[{type:"text",source_type:"text",text:Q},...$];else return[{type:"text",text:Q},...$]}else if(Array.isArray($))return N0(Q,$)??[...Q,...$];else if($==="")return Q;else if(Array.isArray(Q)&&Q.some((Y)=>gQ(Y)))return[...Q,{type:"file",source_type:"text",text:$}];else return[...Q,{type:"text",text:$}]}function O6(Q,$){if(Q==="error"||$==="error")return"error";return"success"}function $Z(Q,$){function Y(q,W){if(typeof q!=="object"||q===null||q===void 0)return q;if(W>=$){if(Array.isArray(q))return"[Array]";return"[Object]"}if(Array.isArray(q))return q.map((G)=>Y(G,W+1));let Z={};for(let G of Object.keys(q))Z[G]=Y(q[G],W+1);return Z}return JSON.stringify(Y(Q,0),null,2)}var e=class extends RQ{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[$Y]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(Q){let $=typeof Q==="string"||Array.isArray(Q)?{content:Q}:Q;if(!$.additional_kwargs)$.additional_kwargs={};if(!$.response_metadata)$.response_metadata={};super($);if(this.name=$.name,$.content===void 0&&$.contentBlocks!==void 0)this.content=$.contentBlocks,this.response_metadata={output_version:"v1",...$.response_metadata};else if($.content!==void 0)this.content=$.content??[],this.response_metadata=$.response_metadata;else this.content=[],this.response_metadata=$.response_metadata;this.additional_kwargs=$.additional_kwargs,this.id=$.id}get text(){if(typeof this.content==="string")return this.content;if(!Array.isArray(this.content))return"";return this.content.map((Q)=>{if(typeof Q==="string")return Q;if(Q.type==="text")return Q.text;return""}).join("")}get contentBlocks(){let Q=typeof this.content==="string"?[{type:"text",text:this.content}]:this.content;return[N6,c0,X6].reduce(($,Y)=>Y($),Q)}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(Q){return typeof Q==="object"&&Q!==null&&$Y in Q&&Q[$Y]===!0&&H6(Q)}_updateId(Q){this.id=Q,this.lc_kwargs.id=Q}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](Q){if(Q===null)return this;let $=$Z(this._printableFields,Math.max(4,Q));return`${this.constructor.lc_name()} ${$}`}toFormattedString(Q="pretty"){return D6(this,Q)}};function _9(Q){return Array.isArray(Q)&&Q.every(($)=>typeof $.index==="number")}var YZ=["index","created","timestamp"];function p(Q,$,Y){let q=Y?.ignoreKeys??YZ;if(Q==null&&$==null)return;if(Q==null||$==null)return Q??$;let W={...Q};for(let[Z,G]of Object.entries($))if(W[Z]==null)W[Z]=G;else if(G==null)continue;else if(typeof W[Z]!==typeof G||Array.isArray(W[Z])!==Array.isArray(G))throw Error(`field[${Z}] already exists in the message chunk, but with a different type.`);else if(typeof W[Z]==="string")if(Z==="type")continue;else if(["id","name","output_version","model_provider"].includes(Z)){if(G)W[Z]=G}else if(q.includes(Z))continue;else W[Z]+=G;else if(typeof W[Z]==="number"){if(q.includes(Z))continue;W[Z]=W[Z]+G}else if(typeof W[Z]==="object"&&!Array.isArray(W[Z]))W[Z]=p(W[Z],G,Y);else if(Array.isArray(W[Z]))W[Z]=N0(W[Z],G,Y);else if(W[Z]===G)continue;else console.warn(`field[${Z}] already exists in this message chunk and value has unsupported type.`);return W}function qZ(Q){return typeof Q==="number"||typeof Q==="string"}function w6(Q){if(typeof Q!=="object"||Q===null)return!1;if(!("index"in Q))return!1;return qZ(Q.index)}function N0(Q,$,Y){if(Q==null&&$==null)return;else if(Q==null||$==null)return Q||$;else{let q=[...Q];for(let W of $)if(w6(W)){let Z=q.findIndex((G)=>{if(!w6(G))return!1;let J=G.index===W.index,z=G.id!=null&&W.id!=null&&G.id===W.id,K=G.id==null||W.id==null;return J&&(z||K)});if(Z!==-1&&typeof q[Z]==="object"&&q[Z]!==null)q[Z]=p(q[Z],W,Y);else q.push(W)}else if(typeof W==="object"&&W!==null&&"text"in W&&W.text==="")continue;else q.push(W);return q}}function E6(Q,$,Y){if(Q==null&&$==null)return;if(Q==null||$==null)return Q??$;else if(typeof Q!==typeof $)throw Error(`Cannot merge objects of different types.
|
|
3
|
+
Left ${typeof Q}
|
|
4
|
+
Right ${typeof $}`);else if(typeof Q==="string"&&typeof $==="string")return Q+$;else if(Array.isArray(Q)&&Array.isArray($))return N0(Q,$,Y);else if(typeof Q==="object"&&typeof $==="object")return p(Q,$,Y);else if(Q===$)return Q;else throw Error(`Can not merge objects of different types.
|
|
5
|
+
Left ${Q}
|
|
6
|
+
Right ${$}`)}var BQ=class Q extends e{static isInstance($){if(!super.isInstance($))return!1;let Y=Object.getPrototypeOf($);while(Y!==null){if(Y===Q.prototype)return!0;Y=Object.getPrototypeOf(Y)}return!1}};function L6(Q){return typeof Q.role==="string"}function P6(Q){return typeof Q?._getType==="function"}function I9(Q){return BQ.isInstance(Q)}var y9=M({ToolMessage:()=>aQ,ToolMessageChunk:()=>WZ,defaultToolCallParser:()=>qY,isDirectToolOutput:()=>YY,isToolMessage:()=>ZZ,isToolMessageChunk:()=>GZ});function YY(Q){return Q!=null&&typeof Q==="object"&&"lc_direct_tool_output"in Q&&Q.lc_direct_tool_output===!0}var aQ=class extends e{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(Q,$,Y){let q=typeof Q==="string"||Array.isArray(Q)?{content:Q,name:Y,tool_call_id:$}:Q;super(q);this.tool_call_id=q.tool_call_id,this.artifact=q.artifact,this.status=q.status,this.metadata=q.metadata}static isInstance(Q){return super.isInstance(Q)&&Q.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},WZ=class extends BQ{type="tool";tool_call_id;status;artifact;constructor(Q){super(Q);this.tool_call_id=Q.tool_call_id,this.artifact=Q.artifact,this.status=Q.status}static lc_name(){return"ToolMessageChunk"}concat(Q){return new this.constructor({content:ZQ(this.content,Q.content),additional_kwargs:p(this.additional_kwargs,Q.additional_kwargs),response_metadata:p(this.response_metadata,Q.response_metadata),artifact:E6(this.artifact,Q.artifact),tool_call_id:this.tool_call_id,id:this.id??Q.id,status:O6(this.status,Q.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function qY(Q){let $=[],Y=[];for(let q of Q)if(!q.function)continue;else{let W=q.function.name;try{let Z=JSON.parse(q.function.arguments);$.push({name:W||"",args:Z||{},id:q.id})}catch{Y.push({name:W,args:q.function.arguments,id:q.id,error:"Malformed args."})}}return[$,Y]}function ZZ(Q){return typeof Q==="object"&&Q!==null&&"getType"in Q&&typeof Q.getType==="function"&&Q.getType()==="tool"}function GZ(Q){return Q._getType()==="tool"}function S6(Q){let $=Symbol.for(Q);return{brand(Y,q){let W=q?Symbol.for(`${Q}.${q}`):$;class Z extends Y{[W]=!0;constructor(...G){super(...G)}static isInstance(G){return typeof G==="object"&&G!==null&&W in G&&G[W]===!0}}return Object.defineProperty(Z,"name",{value:Y.name}),Z},sub(Y){return S6(`${Q}.${Y}`)},isInstance(Y){return typeof Y==="object"&&Y!==null&&$ in Y&&Y[$]===!0}}}var T6=S6("langchain");var d9=M({ContextOverflowError:()=>zZ,LangChainError:()=>ZY,ModelAbortError:()=>JZ,addLangChainErrorFields:()=>WY,ns:()=>l0});function WY(Q,$){return Q.lc_error_code=$,Q.message=`${Q.message}
|
|
7
|
+
|
|
8
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${$}/
|
|
9
|
+
`,Q}var l0=T6.sub("error"),ZY=class extends l0.brand(Error){name="LangChainError";constructor(Q){super(Q);if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}},JZ=class extends l0.brand(ZY,"model-abort"){name="ModelAbortError";partialOutput;constructor(Q,$){super(Q);this.partialOutput=$}},zZ=class Q extends l0.brand(ZY,"context-overflow"){name="ContextOverflowError";cause;constructor($){super($??"Input exceeded the model's context window.")}static fromError($){let Y=new Q($.message);return Y.cause=$,Y}};function l9(Q,$=GY){Q=Q.trim();let Y=Q.indexOf("```");if(Y===-1)return $(Q);let q=Q.substring(Y+3);if(q.startsWith(`json
|
|
10
|
+
`))q=q.substring(5);else if(q.startsWith("json"))q=q.substring(4);else if(q.startsWith(`
|
|
11
|
+
`))q=q.substring(1);let W=q.indexOf("```"),Z=q;if(W!==-1)Z=q.substring(0,W);return $(Z.trim())}function KZ(Q){try{return JSON.parse(Q)}catch{}let $=Q.trim();if($.length===0)throw Error("Unexpected end of JSON input");let Y=0;function q(){while(Y<$.length&&/\s/.test($[Y]))Y+=1}function W(){if($[Y]!=='"')throw Error(`Expected '"' at position ${Y}, got '${$[Y]}'`);Y+=1;let X="",U=!1;while(Y<$.length){let N=$[Y];if(U){if(N==="n")X+=`
|
|
12
|
+
`;else if(N==="t")X+="\t";else if(N==="r")X+="\r";else if(N==="\\")X+="\\";else if(N==='"')X+='"';else if(N==="b")X+="\b";else if(N==="f")X+="\f";else if(N==="/")X+="/";else if(N==="u"){let B=$.substring(Y+1,Y+5);if(/^[0-9A-Fa-f]{0,4}$/.test(B)){if(B.length===4)X+=String.fromCharCode(Number.parseInt(B,16));else X+=`u${B}`;Y+=B.length}else throw Error(`Invalid unicode escape sequence '\\u${B}' at position ${Y}`)}else throw Error(`Invalid escape sequence '\\${N}' at position ${Y}`);U=!1}else if(N==="\\")U=!0;else if(N==='"')return Y+=1,X;else X+=N;Y+=1}if(U)X+="\\";return X}function Z(){let X=Y,U="";if($[Y]==="-")U+="-",Y+=1;if(Y<$.length&&$[Y]==="0"){if(U+="0",Y+=1,$[Y]>="0"&&$[Y]<="9")throw Error(`Invalid number at position ${X}`)}if(Y<$.length&&$[Y]>="1"&&$[Y]<="9")while(Y<$.length&&$[Y]>="0"&&$[Y]<="9")U+=$[Y],Y+=1;if(Y<$.length&&$[Y]==="."){U+=".",Y+=1;while(Y<$.length&&$[Y]>="0"&&$[Y]<="9")U+=$[Y],Y+=1}if(Y<$.length&&($[Y]==="e"||$[Y]==="E")){if(U+=$[Y],Y+=1,Y<$.length&&($[Y]==="+"||$[Y]==="-"))U+=$[Y],Y+=1;while(Y<$.length&&$[Y]>="0"&&$[Y]<="9")U+=$[Y],Y+=1}if(U==="-")return-0;let N=Number.parseFloat(U);if(Number.isNaN(N))throw Y=X,Error(`Invalid number '${U}' at position ${X}`);return N}function G(){if(q(),Y>=$.length)throw Error(`Unexpected end of input at position ${Y}`);let X=$[Y];if(X==="{")return z();if(X==="[")return J();if(X==='"')return W();if("null".startsWith($.substring(Y,Y+4)))return Y+=Math.min(4,$.length-Y),null;if("true".startsWith($.substring(Y,Y+4)))return Y+=Math.min(4,$.length-Y),!0;if("false".startsWith($.substring(Y,Y+5)))return Y+=Math.min(5,$.length-Y),!1;if(X==="-"||X>="0"&&X<="9")return Z();throw Error(`Unexpected character '${X}' at position ${Y}`)}function J(){if($[Y]!=="[")throw Error(`Expected '[' at position ${Y}, got '${$[Y]}'`);let X=[];if(Y+=1,q(),Y>=$.length)return X;if($[Y]==="]")return Y+=1,X;while(Y<$.length){if(q(),Y>=$.length)return X;if(X.push(G()),q(),Y>=$.length)return X;if($[Y]==="]")return Y+=1,X;else if($[Y]===","){Y+=1;continue}throw Error(`Expected ',' or ']' at position ${Y}, got '${$[Y]}'`)}return X}function z(){if($[Y]!=="{")throw Error(`Expected '{' at position ${Y}, got '${$[Y]}'`);let X={};if(Y+=1,q(),Y>=$.length)return X;if($[Y]==="}")return Y+=1,X;while(Y<$.length){if(q(),Y>=$.length)return X;let U=W();if(q(),Y>=$.length)return X;if($[Y]!==":")throw Error(`Expected ':' at position ${Y}, got '${$[Y]}'`);if(Y+=1,q(),Y>=$.length)return X;if(X[U]=G(),q(),Y>=$.length)return X;if($[Y]==="}")return Y+=1,X;else if($[Y]===","){Y+=1;continue}throw Error(`Expected ',' or '}' at position ${Y}, got '${$[Y]}'`)}return X}let K=G();if(q(),Y<$.length)throw Error(`Unexpected character '${$[Y]}' at position ${Y}`);return K}function GY(Q){try{if(typeof Q>"u")return null;return KZ(Q)}catch{return null}}function JY(Q){switch(Q){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function XZ(Q){if(P(Q.document)&&P(Q.document.source)){let $=JY(P(Q.document)&&V(Q.document.format)?Q.document.format:"");if(P(Q.document.source)){if(P(Q.document.source.s3Location)&&V(Q.document.source.s3Location.uri))return{type:"file",mimeType:$,fileId:Q.document.source.s3Location.uri};if(u0(Q.document.source.bytes))return{type:"file",mimeType:$,data:Q.document.source.bytes};if(V(Q.document.source.text))return{type:"file",mimeType:$,data:Buffer.from(Q.document.source.text).toString("base64")};if(o(Q.document.source.content))return{type:"file",mimeType:$,data:Q.document.source.content.reduce((Y,q)=>{if(P(q)&&V(q.text))return Y+q.text;return Y},"")}}}return{type:"non_standard",value:Q}}function UZ(Q){if(O(Q,"image")&&P(Q.image)){let $=JY(P(Q.image)&&V(Q.image.format)?Q.image.format:"");if(P(Q.image.source)){if(P(Q.image.source.s3Location)&&V(Q.image.source.s3Location.uri))return{type:"image",mimeType:$,fileId:Q.image.source.s3Location.uri};if(u0(Q.image.source.bytes))return{type:"image",mimeType:$,data:Q.image.source.bytes}}}return{type:"non_standard",value:Q}}function NZ(Q){if(O(Q,"video")&&P(Q.video)){let $=JY(P(Q.video)&&V(Q.video.format)?Q.video.format:"");if(P(Q.video.source)){if(P(Q.video.source.s3Location)&&V(Q.video.source.s3Location.uri))return{type:"video",mimeType:$,fileId:Q.video.source.s3Location.uri};if(u0(Q.video.source.bytes))return{type:"video",mimeType:$,data:Q.video.source.bytes}}}return{type:"non_standard",value:Q}}function R6(Q){function*$(){let Y=typeof Q.content==="string"?[{type:"text",text:Q.content}]:Q.content;for(let q of Y){if(O(q,"cache_point")){yield{type:"non_standard",value:q};continue}else if(O(q,"citations_content")&&P(q.citationsContent)){yield{type:"text",text:o(q.citationsContent.content)?q.citationsContent.content.reduce((W,Z)=>{if(P(Z)&&V(Z.text))return W+Z.text;return W},""):"",annotations:o(q.citationsContent.citations)?q.citationsContent.citations.reduce((W,Z)=>{if(P(Z)){let G=o(Z.sourceContent)?Z.sourceContent.reduce((z,K)=>{if(P(K)&&V(K.text))return z+K.text;return z},""):"",J=NQ(()=>{if(P(Z.location)){let z=Z.location.documentChar||Z.location.documentPage||Z.location.documentChunk;if(P(z))return{source:UQ(z.documentIndex)?z.documentIndex.toString():void 0,startIndex:UQ(z.start)?z.start:void 0,endIndex:UQ(z.end)?z.end:void 0}}return{}});W.push({type:"citation",citedText:G,...J})}return W},[]):[]};continue}else if(O(q,"document")&&P(q.document)){yield XZ(q);continue}else if(O(q,"guard_content")){yield{type:"non_standard",value:q};continue}else if(O(q,"image")&&P(q.image)){yield UZ(q);continue}else if(O(q,"reasoning_content")&&V(q.reasoningText)){yield{type:"reasoning",reasoning:q.reasoningText};continue}else if(O(q,"text")&&V(q.text)){yield{type:"text",text:q.text};continue}else if(O(q,"tool_result")){yield{type:"non_standard",value:q};continue}else if(O(q,"tool_call"))continue;else if(O(q,"video")&&P(q.video)){yield NZ(q);continue}yield{type:"non_standard",value:q}}}return Array.from($())}var M6={translateContent:R6,translateContentChunk:R6};function _6(Q){let $=[],Y=Q.additional_kwargs?.reasoning_content;if(V(Y)&&Y.length>0)$.push({type:"reasoning",reasoning:Y});if(typeof Q.content==="string"){if(Q.content.length>0)$.push({type:"text",text:Q.content})}else for(let q of Q.content)if(typeof q==="object"&&"type"in q&&q.type==="text"&&"text"in q&&V(q.text))$.push({type:"text",text:q.text});for(let q of Q.tool_calls??[])$.push({type:"tool_call",id:q.id,name:q.name,args:q.args});return $}var I6={translateContent:_6,translateContentChunk:_6};function x6(Q){function*$(){let Y=typeof Q.content==="string"?[{type:"text",text:Q.content}]:Q.content;for(let q of Y){if(O(q,"text")&&V(q.text)){yield{type:"text",text:q.text};continue}else if(O(q,"thinking")&&V(q.thinking)){yield{type:"reasoning",reasoning:q.thinking,...q.signature?{signature:q.signature}:{}};continue}else if(O(q,"inlineData")&&P(q.inlineData)&&V(q.inlineData.mimeType)&&V(q.inlineData.data)){yield{type:"file",mimeType:q.inlineData.mimeType,data:q.inlineData.data};continue}else if(O(q,"functionCall")&&P(q.functionCall)&&V(q.functionCall.name)&&P(q.functionCall.args)){yield{type:"tool_call",id:Q.id,name:q.functionCall.name,args:q.functionCall.args};continue}else if(O(q,"functionResponse")){yield{type:"non_standard",value:q};continue}else if(O(q,"fileData")&&P(q.fileData)&&V(q.fileData.mimeType)&&V(q.fileData.fileUri)){yield{type:"file",mimeType:q.fileData.mimeType,fileId:q.fileData.fileUri};continue}else if(O(q,"executableCode")){yield{type:"non_standard",value:q};continue}else if(O(q,"codeExecutionResult")){yield{type:"non_standard",value:q};continue}yield{type:"non_standard",value:q}}}return Array.from($())}var j6={translateContent:x6,translateContentChunk:x6};function v6(Q){function*$(){let Y=typeof Q.content==="string"?[{type:"text",text:Q.content}]:Q.content;for(let q of Y){if(O(q,"reasoning")&&V(q.reasoning)){let W=NQ(()=>{let Z=Y.indexOf(q);if(o(Q.additional_kwargs?.signatures)&&Z>=0)return Q.additional_kwargs.signatures.at(Z)});if(V(W))yield{type:"reasoning",reasoning:q.reasoning,signature:W};else yield{type:"reasoning",reasoning:q.reasoning};continue}else if(O(q,"thinking")&&V(q.thinking)){yield{type:"reasoning",reasoning:q.thinking,...q.signature?{signature:q.signature}:{}};continue}else if(O(q,"text")&&V(q.text)){yield{type:"text",text:q.text};continue}else if(O(q,"image_url")){if(V(q.image_url))if(q.image_url.startsWith("data:")){let W=q.image_url.match(/^data:([^;]+);base64,(.+)$/);if(W)yield{type:"image",data:W[2],mimeType:W[1]};else yield{type:"image",url:q.image_url}}else yield{type:"image",url:q.image_url};continue}else if(O(q,"media")&&V(q.mimeType)&&V(q.data)){yield{type:"file",mimeType:q.mimeType,data:q.data};continue}yield{type:"non_standard",value:q}}}return Array.from($())}var C6={translateContent:v6,translateContentChunk:v6};function y6(Q){let $=[],Y=Q.additional_kwargs?.reasoning;if(V(Y)&&Y.length>0)$.push({type:"reasoning",reasoning:Y});if(typeof Q.content==="string"){let q=Q.content,W=q.match(/<think>([\s\S]*?)<\/think>/);if(W){let Z=W[1].trim();if(Z.length>0)$.push({type:"reasoning",reasoning:Z});q=q.replace(/<think>[\s\S]*?<\/think>/,"").trim()}if(q.length>0)$.push({type:"text",text:q})}else for(let q of Q.content)if(typeof q==="object"&&"type"in q&&q.type==="text"&&"text"in q&&V(q.text)){let W=q.text,Z=W.match(/<think>([\s\S]*?)<\/think>/);if(Z){let G=Z[1].trim();if(G.length>0)$.push({type:"reasoning",reasoning:G});W=W.replace(/<think>[\s\S]*?<\/think>/,"").trim()}if(W.length>0)$.push({type:"text",text:W})}for(let q of Q.tool_calls??[])$.push({type:"tool_call",id:q.id,name:q.name,args:q.args});return $}var k6={translateContent:y6,translateContentChunk:y6};function b6(Q){let $=[],Y=Q.additional_kwargs?.reasoning_content;if(V(Y)&&Y.length>0)$.push({type:"reasoning",reasoning:Y});if(typeof Q.content==="string"){if(Q.content.length>0)$.push({type:"text",text:Q.content})}else for(let q of Q.content)if(typeof q==="object"&&"type"in q&&q.type==="text"&&"text"in q&&V(q.text))$.push({type:"text",text:q.text});for(let q of Q.tool_calls??[])$.push({type:"tool_call",id:q.id,name:q.name,args:q.args});return $}var h6={translateContent:b6,translateContentChunk:b6};function f6(Q){let $=[];if(P(Q.additional_kwargs?.reasoning)){let q=Q.additional_kwargs.reasoning;if(o(q.summary)){let W=q.summary.reduce((Z,G)=>{if(P(G)&&V(G.text))return`${Z}${G.text}`;return Z},"");if(W.length>0)$.push({type:"reasoning",reasoning:W})}}let Y=Q.additional_kwargs?.reasoning_content;if(V(Y)&&Y.length>0)$.push({type:"reasoning",reasoning:Y});if(typeof Q.content==="string"){if(Q.content.length>0)$.push({type:"text",text:Q.content})}else for(let q of Q.content)if(typeof q==="object"&&"type"in q&&q.type==="text"&&"text"in q&&V(q.text))$.push({type:"text",text:q.text});for(let q of Q.tool_calls??[])$.push({type:"tool_call",id:q.id,name:q.name,args:q.args});return $}var g6={translateContent:f6,translateContentChunk:f6};function m6(Q){function*$(){let Y=NQ(()=>{if(typeof Q.content==="string")if(Q.additional_kwargs.originalTextContentBlock)return[{...Q.additional_kwargs.originalTextContentBlock,type:"text"}];else return[{type:"text",text:Q.content}];else return Q.content});for(let q of Y){let W=NQ(()=>{if(O(q,"text")&&V(q.text))return{type:"text",text:q.text};else if(O(q,"inlineData")&&P(q.inlineData)&&V(q.inlineData.mimeType)&&V(q.inlineData.data))return{type:"file",mimeType:q.inlineData.mimeType,data:q.inlineData.data};else if(O(q,"functionCall")&&P(q.functionCall)&&V(q.functionCall.name)&&P(q.functionCall.args))return{type:"tool_call",id:Q.id,name:q.functionCall.name,args:q.functionCall.args};else if(O(q,"functionResponse"))return{type:"non_standard",value:q};else if(O(q,"fileData")&&P(q.fileData)&&V(q.fileData.mimeType)&&V(q.fileData.fileUri))return{type:"file",mimeType:q.fileData.mimeType,fileId:q.fileData.fileUri};else if(O(q,"executableCode"))return{type:"non_standard",value:q};else if(O(q,"codeExecutionResult"))return{type:"non_standard",value:q};return{type:"non_standard",value:q}}),Z=NQ(()=>{if("thought"in q&&q.thought)return{type:"reasoning",reasoning:W.type==="text"?W.text:"",reasoningContentBlock:W};else return W}),G={thought:q.thought,thoughtSignature:q.thoughtSignature,partMetadata:q.partMetadata,...Z};for(let J in G)if(G[J]===void 0)delete G[J];yield G}}return Array.from($())}var d6={translateContent:m6,translateContentChunk:m6};globalThis.lc_block_translators_registry??=new Map([["anthropic",U6],["bedrock-converse",M6],["deepseek",I6],["google",d6],["google-genai",j6],["google-vertexai",C6],["groq",k6],["ollama",h6],["openai",A6],["xai",g6]]);function zY(Q){return globalThis.lc_block_translators_registry.get(Q)}function p6(Q,$){return p(Q,$)??{}}function u6(Q,$){let Y={};if(Q?.audio!==void 0||$?.audio!==void 0)Y.audio=(Q?.audio??0)+($?.audio??0);if(Q?.image!==void 0||$?.image!==void 0)Y.image=(Q?.image??0)+($?.image??0);if(Q?.video!==void 0||$?.video!==void 0)Y.video=(Q?.video??0)+($?.video??0);if(Q?.document!==void 0||$?.document!==void 0)Y.document=(Q?.document??0)+($?.document??0);if(Q?.text!==void 0||$?.text!==void 0)Y.text=(Q?.text??0)+($?.text??0);return Y}function BZ(Q,$){let Y={...u6(Q,$)};if(Q?.cache_read!==void 0||$?.cache_read!==void 0)Y.cache_read=(Q?.cache_read??0)+($?.cache_read??0);if(Q?.cache_creation!==void 0||$?.cache_creation!==void 0)Y.cache_creation=(Q?.cache_creation??0)+($?.cache_creation??0);return Y}function FZ(Q,$){let Y={...u6(Q,$)};if(Q?.reasoning!==void 0||$?.reasoning!==void 0)Y.reasoning=(Q?.reasoning??0)+($?.reasoning??0);return Y}function i0(Q,$){return{input_tokens:(Q?.input_tokens??0)+($?.input_tokens??0),output_tokens:(Q?.output_tokens??0)+($?.output_tokens??0),total_tokens:(Q?.total_tokens??0)+($?.total_tokens??0),input_token_details:BZ(Q?.input_token_details,$?.input_token_details),output_token_details:FZ(Q?.output_token_details,$?.output_token_details)}}var B0=class extends e{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}constructor(Q){let $;if(typeof Q==="string"||Array.isArray(Q))$={content:Q,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{$=Q;let Y=$.additional_kwargs?.tool_calls,q=$.tool_calls;if(Y!=null&&Y.length>0&&(q===void 0||q.length===0))console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
13
|
+
|
|
14
|
+
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(Y!=null&&q===void 0){let[W,Z]=qY(Y);$.tool_calls=W??[],$.invalid_tool_calls=Z??[]}else $.tool_calls=$.tool_calls??[],$.invalid_tool_calls=$.invalid_tool_calls??[]}catch{$.tool_calls=[],$.invalid_tool_calls=[]}if($.response_metadata!==void 0&&"output_version"in $.response_metadata&&$.response_metadata.output_version==="v1")$.contentBlocks=$.content,$.content=void 0;if($.contentBlocks!==void 0){if($.tool_calls)$.contentBlocks.push(...$.tool_calls.map((Z)=>({type:"tool_call",id:Z.id,name:Z.name,args:Z.args})));let W=$.contentBlocks.filter((Z)=>Z.type==="tool_call").filter((Z)=>!$.tool_calls?.some((G)=>G.id===Z.id&&G.name===Z.name));if(W.length>0)$.tool_calls=W.map((Z)=>({type:"tool_call",id:Z.id,name:Z.name,args:Z.args}))}}super($);if(typeof $!=="string")this.tool_calls=$.tool_calls??this.tool_calls,this.invalid_tool_calls=$.invalid_tool_calls??this.invalid_tool_calls;this.usage_metadata=$.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider==="string"){let $=zY(this.response_metadata.model_provider);if($)return $.translateContent(this)}let Q=super.contentBlocks;if(this.tool_calls){let $=this.tool_calls.filter((Y)=>!Q.some((q)=>q.id===Y.id&&q.name===Y.name));Q.push(...$.map((Y)=>({type:"tool_call",id:Y.id,name:Y.name,args:Y.args})))}return Q}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(Q){return super.isInstance(Q)&&Q.type==="ai"}};function M4(Q){return Q._getType()==="ai"}function _4(Q){return Q._getType()==="ai"}var F0=class extends BQ{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(Q){let $;if(typeof Q==="string"||Array.isArray(Q))$={content:Q,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(Q.tool_call_chunks===void 0||Q.tool_call_chunks.length===0)$={...Q,tool_calls:Q.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:Q.usage_metadata!==void 0?Q.usage_metadata:void 0};else{let Y=c6(Q.tool_call_chunks??[]);$={...Q,tool_call_chunks:Y.tool_call_chunks,tool_calls:Y.tool_calls,invalid_tool_calls:Y.invalid_tool_calls,usage_metadata:Q.usage_metadata!==void 0?Q.usage_metadata:void 0}}super($);this.tool_call_chunks=$.tool_call_chunks??this.tool_call_chunks,this.tool_calls=$.tool_calls??this.tool_calls,this.invalid_tool_calls=$.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=$.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider==="string"){let $=zY(this.response_metadata.model_provider);if($)return $.translateContent(this)}let Q=super.contentBlocks;if(this.tool_calls){if(typeof this.content!=="string"){let $=this.content.filter((Y)=>Y.type==="tool_call").map((Y)=>Y.id);for(let Y of this.tool_calls)if(Y.id&&!$.includes(Y.id))Q.push({...Y,type:"tool_call",id:Y.id,name:Y.name,args:Y.args})}}return Q}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(Q){let $={content:ZQ(this.content,Q.content),additional_kwargs:p(this.additional_kwargs,Q.additional_kwargs),response_metadata:p6(this.response_metadata,Q.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??Q.id};if(this.tool_call_chunks!==void 0||Q.tool_call_chunks!==void 0){let q=N0(this.tool_call_chunks,Q.tool_call_chunks);if(q!==void 0&&q.length>0)$.tool_call_chunks=q}if(this.tool_calls!==void 0||Q.tool_calls!==void 0){let q=N0(this.tool_calls,Q.tool_calls);if(q!==void 0&&q.length>0)$.tool_calls=q}if(this.usage_metadata!==void 0||Q.usage_metadata!==void 0)$.usage_metadata=i0(this.usage_metadata,Q.usage_metadata);return new this.constructor($)}static isInstance(Q){return super.isInstance(Q)&&Q.type==="ai"}};var KY=class Q extends e{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return Q}constructor($,Y){if(typeof $==="string"||Array.isArray($))$={content:$,role:Y};super($);this.role=$.role}static isInstance($){return super.isInstance($)&&$.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},l6=class extends BQ{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(Q,$){if(typeof Q==="string"||Array.isArray(Q))Q={content:Q,role:$};super(Q);this.role=Q.role}concat(Q){return new this.constructor({content:ZQ(this.content,Q.content),additional_kwargs:p(this.additional_kwargs,Q.additional_kwargs),response_metadata:p(this.response_metadata,Q.response_metadata),role:this.role,id:this.id??Q.id})}static isInstance(Q){return super.isInstance(Q)&&Q.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function C4(Q){return Q._getType()==="generic"}function y4(Q){return Q._getType()==="generic"}var i6=class extends e{static lc_name(){return"FunctionMessage"}type="function";name;constructor(Q){super(Q);this.name=Q.name}},s6=class extends BQ{static lc_name(){return"FunctionMessageChunk"}type="function";concat(Q){return new this.constructor({content:ZQ(this.content,Q.content),additional_kwargs:p(this.additional_kwargs,Q.additional_kwargs),response_metadata:p(this.response_metadata,Q.response_metadata),name:this.name??"",id:this.id??Q.id})}};function f4(Q){return Q._getType()==="function"}function g4(Q){return Q._getType()==="function"}var eQ=class extends e{static lc_name(){return"HumanMessage"}type="human";constructor(Q){super(Q)}static isInstance(Q){return super.isInstance(Q)&&Q.type==="human"}},o6=class extends BQ{static lc_name(){return"HumanMessageChunk"}type="human";constructor(Q){super(Q)}concat(Q){return new this.constructor({content:ZQ(this.content,Q.content),additional_kwargs:p(this.additional_kwargs,Q.additional_kwargs),response_metadata:p(this.response_metadata,Q.response_metadata),id:this.id??Q.id})}static isInstance(Q){return super.isInstance(Q)&&Q.type==="human"}};function c4(Q){return Q.getType()==="human"}function l4(Q){return Q.getType()==="human"}var t6=class extends e{type="remove";id;constructor(Q){super({...Q,content:[]});this.id=Q.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(Q){return super.isInstance(Q)&&Q.type==="remove"}};var s0=class Q extends e{static lc_name(){return"SystemMessage"}type="system";constructor($){super($)}concat($){if(typeof $==="string")return new Q({...this,content:ZQ(this.content,$)});if(Q.isInstance($))return new Q({...this,additional_kwargs:{...this.additional_kwargs,...$.additional_kwargs},response_metadata:{...this.response_metadata,...$.response_metadata},content:ZQ(this.content,$.content)});throw Error("Unexpected chunk type for system message")}static isInstance($){return super.isInstance($)&&$.type==="system"}},n6=class extends BQ{static lc_name(){return"SystemMessageChunk"}type="system";constructor(Q){super(Q)}concat(Q){return new this.constructor({content:ZQ(this.content,Q.content),additional_kwargs:p(this.additional_kwargs,Q.additional_kwargs),response_metadata:p(this.response_metadata,Q.response_metadata),id:this.id??Q.id})}static isInstance(Q){return super.isInstance(Q)&&Q.type==="system"}};function e4(Q){return Q._getType()==="system"}function Qz(Q){return Q._getType()==="system"}var Fz=(Q)=>Q();function VZ(Q){if(fQ(Q))return Q;else if(typeof Q.id==="string"&&Q.type==="function"&&typeof Q.function==="object"&&Q.function!==null&&"arguments"in Q.function&&typeof Q.function.arguments==="string"&&"name"in Q.function&&typeof Q.function.name==="string")return{id:Q.id,args:JSON.parse(Q.function.arguments),name:Q.function.name,type:"tool_call"};else return Q}function AZ(Q){return typeof Q==="object"&&Q!=null&&Q.lc===1&&Array.isArray(Q.id)&&Q.kwargs!=null&&typeof Q.kwargs==="object"}function XY(Q){let $,Y;if(AZ(Q)){let q=Q.id.at(-1);if(q==="HumanMessage"||q==="HumanMessageChunk")$="user";else if(q==="AIMessage"||q==="AIMessageChunk")$="assistant";else if(q==="SystemMessage"||q==="SystemMessageChunk")$="system";else if(q==="FunctionMessage"||q==="FunctionMessageChunk")$="function";else if(q==="ToolMessage"||q==="ToolMessageChunk")$="tool";else $="unknown";Y=Q.kwargs}else{let{type:q,...W}=Q;$=q,Y=W}if($==="human"||$==="user")return new eQ(Y);else if($==="ai"||$==="assistant"){let{tool_calls:q,...W}=Y;if(!Array.isArray(q))return new B0(Y);let Z=q.map(VZ);return new B0({...W,tool_calls:Z})}else if($==="system")return new s0(Y);else if($==="developer")return new s0({...Y,additional_kwargs:{...Y.additional_kwargs,__openai_role__:"developer"}});else if($==="tool"&&"tool_call_id"in Y)return new aQ({...Y,content:Y.content,tool_call_id:Y.tool_call_id,name:Y.name});else if($==="remove"&&"id"in Y&&typeof Y.id==="string")return new t6({...Y,id:Y.id});else throw WY(Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
15
|
+
|
|
16
|
+
Received: ${JSON.stringify(Q,null,2)}`),"MESSAGE_COERCION_FAILURE")}function r6(Q){if(typeof Q==="string")return new eQ(Q);else if(P6(Q))return Q;if(Array.isArray(Q)){let[$,Y]=Q;return XY({type:$,content:Y})}else if(L6(Q)){let{role:$,...Y}=Q;return XY({...Y,type:$})}else return XY(Q)}function o0(Q,$="Human",Y="AI"){let q=[];for(let W of Q){let Z;if(W.type==="human")Z=$;else if(W.type==="ai")Z=Y;else if(W.type==="system")Z="System";else if(W.type==="tool")Z="Tool";else if(W.type==="generic")Z=W.role;else throw Error(`Got unsupported message type: ${W.type}`);let G=W.name?`${W.name}, `:"",J=W.text,z=`${Z}: ${G}${J}`;if(W.type==="ai"){let K=W;if(K.tool_calls&&K.tool_calls.length>0)z+=JSON.stringify(K.tool_calls);else if(K.additional_kwargs&&"function_call"in K.additional_kwargs)z+=JSON.stringify(K.additional_kwargs.function_call)}q.push(z)}return q.join(`
|
|
17
|
+
`)}function HZ(Q){if(Q.data!==void 0)return Q;else{let $=Q;return{type:$.type,data:{content:$.text,role:$.role,name:void 0,tool_call_id:void 0}}}}function UY(Q){let $=HZ(Q);switch($.type){case"human":return new eQ($.data);case"ai":return new B0($.data);case"system":return new s0($.data);case"function":if($.data.name===void 0)throw Error("Name must be defined for function messages");return new i6($.data);case"tool":if($.data.tool_call_id===void 0)throw Error("Tool call ID must be defined for tool messages");return new aQ($.data);case"generic":if($.data.role===void 0)throw Error("Role must be defined for chat messages");return new KY($.data);default:throw Error(`Got unexpected type: ${$.type}`)}}function Vz(Q){return Q.map(UY)}function Az(Q){return Q.map(($)=>$.toDict())}function Hz(Q){let $=Q._getType();if($==="human")return new o6({...Q});else if($==="ai"){let Y={...Q};if("tool_calls"in Y)Y={...Y,tool_call_chunks:Y.tool_calls?.map((q)=>({...q,type:"tool_call_chunk",index:void 0,args:JSON.stringify(q.args)}))};return new F0({...Y})}else if($==="system")return new n6({...Q});else if($==="function")return new s6({...Q});else if(KY.isInstance(Q))return new l6({...Q});else throw Error("Unknown message type.")}function c6(Q){let $=Q.reduce((W,Z)=>{let G=W.findIndex(([J])=>{if("id"in Z&&Z.id&&"index"in Z&&Z.index!==void 0)return Z.id===J.id&&Z.index===J.index;if("id"in Z&&Z.id)return Z.id===J.id;if("index"in Z&&Z.index!==void 0)return Z.index===J.index;return!1});if(G!==-1)W[G].push(Z);else W.push([Z]);return W},[]),Y=[],q=[];for(let W of $){let Z=null,G=W[0]?.name??"",J=W.map((X)=>X.args||"").join("").trim(),z=J.length?J:"{}",K=W[0]?.id;try{if(Z=GY(z),!K||Z===null||typeof Z!=="object"||Array.isArray(Z))throw Error("Malformed tool call chunk args.");Y.push({name:G,args:Z,id:K,type:"tool_call"})}catch{q.push({name:G,args:z,id:K,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:Q,tool_calls:Y,invalid_tool_calls:q}}var Oz=M({getEnv:()=>Yq,getEnvironmentVariable:()=>OQ,getRuntimeEnvironment:()=>BY,isBrowser:()=>a6,isDeno:()=>t0,isJsDom:()=>Qq,isNode:()=>$q,isWebWorker:()=>e6}),a6=()=>typeof window<"u"&&typeof window.document<"u",e6=()=>typeof globalThis==="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Qq=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),t0=()=>typeof Deno<"u",$q=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!t0(),Yq=()=>{let Q;if(a6())Q="browser";else if($q())Q="node";else if(e6())Q="webworker";else if(Qq())Q="jsdom";else if(t0())Q="deno";else Q="other";return Q},NY;function BY(){if(NY===void 0)NY={library:"langchain-js",runtime:Yq()};return NY}function OQ(Q){try{if(typeof process<"u")return process.env?.[Q];else if(t0())return Deno?.env.get(Q);else return}catch{return}}Q0();var Tz=M({BaseCallbackHandler:()=>$0,callbackHandlerPrefersStreaming:()=>OZ,isBaseCallbackHandler:()=>FY}),wZ=class{};function OZ(Q){return"lc_prefer_streaming"in Q&&Q.lc_prefer_streaming}var $0=class extends wZ{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,p0(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=OQ("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(Q){super();if(this.lc_kwargs=Q||{},Q)this.ignoreLLM=Q.ignoreLLM??this.ignoreLLM,this.ignoreChain=Q.ignoreChain??this.ignoreChain,this.ignoreAgent=Q.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=Q.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=Q.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=Q.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(Q._awaitHandler??this.awaitHandlers)}copy(){return new this.constructor(this)}toJSON(){return RQ.prototype.toJSON.call(this)}toJSONNotImplemented(){return RQ.prototype.toJSONNotImplemented.call(this)}static fromMethods(Q){class $ extends $0{name=FQ();constructor(){super();Object.assign(this,Q)}}return new $}},FY=(Q)=>{let $=Q;return $!==void 0&&typeof $.copy==="function"&&typeof $.name==="string"&&typeof $.awaitHandlers==="boolean"};Q0();var qq="gen_ai.operation.name",Wq="gen_ai.system",VY="gen_ai.request.model",Zq="gen_ai.response.model",AY="gen_ai.usage.input_tokens",HY="gen_ai.usage.output_tokens",DY="gen_ai.usage.total_tokens",Gq="gen_ai.request.max_tokens",Jq="gen_ai.request.temperature",zq="gen_ai.request.top_p",Kq="gen_ai.request.frequency_penalty",Xq="gen_ai.request.presence_penalty",Uq="gen_ai.response.finish_reasons",Nq="gen_ai.prompt",Bq="gen_ai.completion",Fq="gen_ai.request.extra_query",Vq="gen_ai.request.extra_body",Aq="gen_ai.serialized.name",Hq="gen_ai.serialized.signature",Dq="gen_ai.serialized.doc",wq="gen_ai.response.id",Oq="gen_ai.response.service_tier",Eq="gen_ai.response.system_fingerprint",Lq="gen_ai.usage.input_token_details",Pq="gen_ai.usage.output_token_details",Sq="langsmith.trace.session_id",Tq="langsmith.trace.session_name",Rq="langsmith.span.kind",Mq="langsmith.trace.name",_q="langsmith.metadata",wY="langsmith.span.tags";var Iq="langsmith.request.streaming",xq="langsmith.request.headers";var LZ=(...Q)=>fetch(...Q),PZ=void 0,jq=Symbol.for("ls:fetch_implementation");var vq=()=>{if(globalThis[jq]===void 0)return!0;return PZ??!1},Cq=(Q)=>{return async(...$)=>{if(Q||c("DEBUG")==="true"){let[q,W]=$;console.log(`→ ${W?.method||"GET"} ${q}`)}let Y=await(globalThis[jq]??LZ)(...$);if(Q||c("DEBUG")==="true")console.log(`← ${Y.status} ${Y.statusText} ${Y.url}`);return Y}};var T0=()=>{return c("PROJECT")??VQ("LANGCHAIN_SESSION")??"default"};Q0();var yq={};function Y0(Q){if(!yq[Q])console.warn(Q),yq[Q]=!0}var F=(Q)=>BigInt(Q),fq=F("0x9E3779B1"),gq=F("0x85EBCA77"),SZ=F("0xC2B2AE3D"),mQ=F("0x9E3779B185EBCA87"),q0=F("0xC2B2AE3D27D4EB4F"),mq=F("0x165667B19E3779F9"),PY=F("0x85EBCA77C2B2AE63"),TZ=F("0x27D4EB2F165667C5"),RZ=F("0x165667919E3779F9"),MZ=F("0x9FB21C651E98DF25");function _Z(Q){let $=new Uint8Array(Q.length/2);for(let Y=0;Y<Q.length;Y+=2)$[Y/2]=parseInt(Q.substring(Y,Y+2),16);return $}var MQ=_Z("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),A0=(F(1)<<F(128))-F(1),j=(F(1)<<F(64))-F(1),e0=(F(1)<<F(32))-F(1),kQ=64,dq=kQ/8,IZ=8,n0=4;function k(Q,$=0){return new Uint8Array(Q.buffer,Q.byteOffset+$,Q.length-$)}function h(Q,$=0){return new DataView(Q.buffer,Q.byteOffset+$).getBigUint64(0,!0)}function V0(Q,$=0){return new DataView(Q.buffer,Q.byteOffset+$).getUint32(0,!0)}function OY(Q,$=0){return Q[$]}var xZ=(Q)=>{return(Q&F(255))<<F(56)|(Q&F(65280))<<F(40)|(Q&F(16711680))<<F(24)|(Q&F(4278190080))<<F(8)|(Q&F(1095216660480))>>F(8)|(Q&F(280375465082880))>>F(24)|(Q&F(71776119061217280))>>F(40)|(Q&F(18374686479671624000))>>F(56)},jZ=(Q)=>{return Q=(Q&F(65535))<<F(16)|(Q&F(4294901760))>>F(16),Q=(Q&F(16711935))<<F(8)|(Q&F(4278255360))>>F(8),Q},vZ=(Q,$)=>(Q&e0)*($&e0)&j,H0=(Q)=>{if(!Q)throw Error("Assert failed")};function CZ(Q,$){return(Q<<$|Q>>F(32)-$)&e0}function pq(Q,$,Y){for(let q=0;q<dq;q++){let W=h($,q*8),Z=W^h(Y,q*8);Q[q^1]+=W,Q[q]+=vZ(Z,Z>>F(32))}return Q}function kq(Q,$,Y,q){for(let W=0;W<q;W++)pq(Q,k($,W*kQ),k(Y,W*8));return Q}function yZ(Q,$){for(let Y=0;Y<dq;Y++){let q=h($,Y*8),W=Q[Y];W=EY(W,F(47)),W^=q,W*=fq,Q[Y]=W&j}return Q}function r0(Q,$){return uq(Q[0]^h($,0),Q[1]^h($,IZ))}function bq(Q,$,Y){let q=Y;return q+=r0(Q.slice(0),k($,0*n0)),q+=r0(Q.slice(2),k($,4*n0)),q+=r0(Q.slice(4),k($,8*n0)),q+=r0(Q.slice(6),k($,12*n0)),_Q(q&j)}function kZ(Q,$,Y,q,W){let Z=Math.floor((Y.byteLength-kQ)/8),G=kQ*Z,J=Math.floor(($.byteLength-1)/G);for(let z=0;z<J;z++)Q=kq(Q,k($,z*G),Y,Z),Q=W(Q,k(Y,Y.byteLength-kQ));{let z=Math.floor(($.byteLength-1-G*J)/kQ);Q=kq(Q,k($,J*G),Y,z),Q=q(Q,k($,$.byteLength-kQ),k(Y,Y.byteLength-kQ-7))}return Q}function bZ(Q,$,Y){let q=new BigUint64Array([SZ,mQ,q0,mq,PY,gq,TZ,fq]);H0(Q.length>128),q=kZ(q,Q,$,pq,yZ),H0(q.length*8==64);{let W=bq(q,k($,11),F(Q.byteLength)*mQ&j);return bq(q,k($,$.byteLength-kQ-11),~(F(Q.byteLength)*q0)&j)<<F(64)|W}}function uq(Q,$){let Y=Q*$&A0;return Y&j^Y>>F(64)}function hq(Q,$,Y){return uq((h(Q,0)^h($,0)+Y)&j,(h(Q,8)^h($,8)-Y)&j)}function a0(Q,$,Y,q,W){let Z=Q&j,G=Q>>F(64)&j;return Z+=hq($,q,W),Z^=h(Y,0)+h(Y,8),Z&=j,G+=hq(Y,k(q,16),W),G^=h($,0)+h($,8),G&=j,G<<F(64)|Z}function _Q(Q){return Q^=Q>>F(37),Q*=RZ,Q&=j,Q^=Q>>F(32),Q}function Q$(Q){return Q^=Q>>F(33),Q*=q0,Q&=j,Q^=Q>>F(29),Q*=mq,Q&=j,Q^=Q>>F(32),Q}function hZ(Q,$,Y){let q=Q.byteLength;H0(q>0&&q<=3);let W=F(OY(Q,q-1))|F(q<<8)|F(OY(Q,0)<<16)|F(OY(Q,q>>1)<<24),Z=(F(V0($,0))^F(V0($,4)))+Y,G=(W^Z)&j,J=(F(V0($,8))^F(V0($,12)))-Y,z=(CZ(jZ(W),F(13))^J)&j;return(Q$(z)&j)<<F(64)|Q$(G)}function EY(Q,$){return Q^Q>>$}function fZ(Q,$,Y){let q=Q.byteLength;H0(q>=4&&q<=8);{let W=V0(Q,0),Z=V0(Q,q-4),G=F(W)|F(Z)<<F(32),J=(h($,16)^h($,24))+Y&j,K=(G^J)*(mQ+(F(q)<<F(2)))&A0;return K+=(K&j)<<F(65),K&=A0,K^=K>>F(67),EY(EY(K&j,F(35))*MZ&j,F(28))|_Q(K>>F(64))<<F(64)}}function gZ(Q,$,Y){let q=Q.byteLength;H0(q>=9&&q<=16);{let W=(h($,32)^h($,40))+Y&j,Z=(h($,48)^h($,56))-Y&j,G=h(Q),J=h(Q,q-8),z=(G^J^W)*mQ,K=(z&j)+(F(q-1)<<F(54));z=z&(A0^j)|K,J^=Z,z+=J+(J&e0)*(gq-F(1))<<F(64),z&=A0,z^=xZ(z>>F(64));let X=(z&j)*q0;return X+=(z>>F(64))*q0<<F(64),X&=A0,_Q(X&j)|_Q(X>>F(64))<<F(64)}}function mZ(Q,$){let Y=Q.byteLength;if(H0(Y<=16),Y>8)return gZ(Q,MQ,$);if(Y>=4)return fZ(Q,MQ,$);if(Y>0)return hZ(Q,MQ,$);return Q$($^h(MQ,64)^h(MQ,72))|Q$($^h(MQ,80)^h(MQ,88))<<F(64)}function LY(Q){return~Q+F(1)&j}function dZ(Q,$,Y){let q=F(Q.byteLength)*mQ&j,W=F(Q.byteLength-1)/F(32);while(W>=0){let J=Number(W);q=a0(q,k(Q,16*J),k(Q,Q.byteLength-16*(J+1)),k($,32*J),Y),W--}let Z=q+(q>>F(64))&j;Z=_Q(Z);let G=(q&j)*mQ+(q>>F(64))*PY+(F(Q.byteLength)-Y&j)*q0;return G&=j,G=LY(_Q(G)),Z|G<<F(64)}function pZ(Q,$,Y){let q=F(Q.byteLength)*mQ&j;for(let G=32;G<160;G+=32)q=a0(q,k(Q,G-32),k(Q,G-16),k($,G-32),Y);q=_Q(q&j)|_Q(q>>F(64))<<F(64);for(let G=160;G<=Q.byteLength;G+=32)q=a0(q,k(Q,G-32),k(Q,G-16),k($,3+G-160),Y);q=a0(q,k(Q,Q.byteLength-16),k(Q,Q.byteLength-32),k($,103),LY(Y));let W=q+(q>>F(64))&j;W=_Q(W);let Z=(q&j)*mQ+(q>>F(64))*PY+(F(Q.byteLength)-Y&j)*q0;return Z&=j,Z=LY(_Q(Z)),W|Z<<F(64)}function cq(Q,$=F(0)){let Y=Q.byteLength;if(Y<=16)return mZ(Q,$);if(Y<=128)return dZ(Q,MQ,$);if(Y<=240)return pZ(Q,MQ,$);return bZ(Q,MQ,$)}function lq(Q){let $=new Uint8Array(16),Y=new DataView($.buffer),q=Q&j,W=Q>>F(64);return Y.setBigUint64(0,W,!1),Y.setBigUint64(8,q,!1),$}var iq=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function I(Q,$){if(!iq.test(Q)){let Y=$!==void 0?`Invalid UUID for ${$}: ${Q}`:`Invalid UUID: ${Q}`;throw Error(Y)}return Q}function $$(Q){let $=typeof Q==="string"?Date.parse(Q):Q;return FQ({msecs:$,seq:0})}function uZ(Q){if(!iq.test(Q))return null;let $=Q[14];return parseInt($,16)}function cZ(Q){let $=Q.replace(/-/g,""),Y=new Uint8Array(16);for(let q=0;q<16;q++)Y[q]=parseInt($.slice(q*2,q*2+2),16);return Y}function lZ(Q){let $=Array.from(Q).map((Y)=>Y.toString(16).padStart(2,"0")).join("");return`${$.slice(0,8)}-${$.slice(8,12)}-${$.slice(12,16)}-${$.slice(16,20)}-${$.slice(20)}`}var iZ=new TextEncoder;function sZ(Q){let $=iZ.encode(Q),Y=cq($);return lq(Y)}function R0(Q,$){let Y=`${Q}:${$}`,q=sZ(Y),W=new Uint8Array(16);if(uZ(Q)===7){let G=cZ(Q);W.set(G.slice(0,6),0)}else{let G=Date.now();W[0]=G/1099511627776&255,W[1]=G/4294967296&255,W[2]=G/16777216&255,W[3]=G/65536&255,W[4]=G/256&255,W[5]=G&255}return W[6]=112|q[0]&15,W[7]=q[1],W[8]=128|q[2]&63,W.set(q.slice(3,10),9),lZ(W)}import*as GQ from"node:fs";import*as sq from"node:path";function oq(Q,$){let Y=sq.dirname(Q);if(!GQ.existsSync(Y))GQ.mkdirSync(Y,{recursive:!0});let q={entries:$},W=`${Q}.tmp`;try{GQ.writeFileSync(W,JSON.stringify(q,null,2)),GQ.renameSync(W,Q)}catch(Z){if(GQ.existsSync(W))GQ.unlinkSync(W);throw Z}}function tq(Q){if(!GQ.existsSync(Q))return null;try{let $=GQ.readFileSync(Q,"utf-8");return JSON.parse($).entries??null}catch{return null}}function oZ(Q,$){if($===null)return!1;return Date.now()-Q.createdAt>$*1000}class SY{constructor(Q={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(Q)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let Q=this.totalRequests;return Q>0?this._metrics.hits/Q:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(Q,$){if(this.maxSize===0)return;let Y=this.cache.get(Q);if(!Y){this._metrics.misses+=1;return}return this.cache.delete(Q),this.cache.set(Q,{...Y,refreshFunc:$}),this._metrics.hits+=1,Y.value}set(Q,$,Y){if(this.maxSize===0)return;if(this.refreshTimer===void 0)this.startRefreshLoop();if(!this.cache.has(Q)&&this.cache.size>=this.maxSize){let W=this.cache.keys().next().value;if(W!==void 0)this.cache.delete(W)}let q={value:$,createdAt:Date.now(),refreshFunc:Y};this.cache.delete(Q),this.cache.set(Q,q)}invalidate(Q){this.cache.delete(Q)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){if(this.refreshTimer)clearInterval(this.refreshTimer),this.refreshTimer=void 0}dump(Q){let $={};for(let[Y,q]of this.cache.entries())$[Y]=q.value;oq(Q,$)}load(Q){let $=tq(Q);if(!$)return 0;let Y=0,q=Date.now();for(let[W,Z]of Object.entries($)){if(this.cache.size>=this.maxSize)break;let G={value:Z,createdAt:q};this.cache.set(W,G),Y+=1}return Y}startRefreshLoop(){if(this.stop(),this.ttlSeconds!==null){if(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch((Q)=>{console.warn("Unexpected error in cache refresh loop:",Q)})},this.refreshIntervalSeconds*1000),this.refreshTimer.unref)this.refreshTimer.unref()}}getStaleEntries(){let Q=[];for(let[$,Y]of this.cache.entries())if(oZ(Y,this.ttlSeconds))Q.push([$,Y]);return Q}async refreshStaleEntries(){let Q=this.getStaleEntries();if(Q.length===0)return;for(let[$,Y]of Q)if(Y.refreshFunc!==void 0)try{let q=await Y.refreshFunc();this.set($,q,Y.refreshFunc),this._metrics.refreshes+=1}catch(q){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${$}:`,q)}}configure(Q){this.stop(),this.refreshIntervalSeconds=Q.refreshIntervalSeconds??60,this.maxSize=Q.maxSize??100,this.ttlSeconds=Q.ttlSeconds??300}}var Y$=new SY;var q$="0.5.4";var IQ,tZ=()=>typeof window<"u"&&typeof window.document<"u",nZ=()=>typeof globalThis==="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",rZ=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),nq=()=>typeof Deno<"u",aZ=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!nq(),MY=()=>{if(IQ)return IQ;if(typeof Bun<"u")IQ="bun";else if(tZ())IQ="browser";else if(aZ())IQ="node";else if(nZ())IQ="webworker";else if(rZ())IQ="jsdom";else if(nq())IQ="deno";else IQ="other";return IQ},TY;function W$(){if(TY===void 0){let Q=MY(),$=QG();TY={library:"langsmith",runtime:Q,sdk:"langsmith-js",sdk_version:q$,...$}}return TY}function _Y(){let Q=eZ(),$={},Y=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[q,W]of Object.entries(Q))if(typeof W==="string"&&!Y.includes(q)&&!q.toLowerCase().includes("key")&&!q.toLowerCase().includes("secret")&&!q.toLowerCase().includes("token"))if(q==="LANGCHAIN_REVISION_ID")$.revision_id=W;else $[q]=W;return $}function eZ(){let Q={};try{if(typeof process<"u"&&process.env){for(let[$,Y]of Object.entries(process.env))if(($.startsWith("LANGCHAIN_")||$.startsWith("LANGSMITH_"))&&Y!=null)if(($.toLowerCase().includes("key")||$.toLowerCase().includes("secret")||$.toLowerCase().includes("token"))&&typeof Y==="string")Q[$]=Y.slice(0,2)+"*".repeat(Y.length-4)+Y.slice(-2);else Q[$]=Y}}catch($){}return Q}function VQ(Q){try{return typeof process<"u"?process.env?.[Q]:void 0}catch($){return}}function c(Q){return VQ(`LANGSMITH_${Q}`)||VQ(`LANGCHAIN_${Q}`)}var RY;function QG(){if(RY!==void 0)return RY;let Q=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],$={};for(let Y of Q){let q=VQ(Y);if(q!==void 0)$[Y]=q}return RY=$,$}function Z$(){return VQ("OTEL_ENABLED")==="true"||c("OTEL_ENABLED")==="true"}class aq{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(Q,...$){if(!this.hasWarned&&Z$())console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0;let Y;if($.length===1&&typeof $[0]==="function")Y=$[0];else if($.length===2&&typeof $[1]==="function")Y=$[1];else if($.length===3&&typeof $[2]==="function")Y=$[2];if(typeof Y==="function")return Y();return}}class eq{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new aq})}getTracer(Q,$){return this.mockTracer}getActiveSpan(){return}setSpan(Q,$){return Q}getSpan(Q){return}setSpanContext(Q,$){return Q}getTracerProvider(){return}setGlobalTracerProvider(Q){return!1}}class QW{active(){return{}}with(Q,$){return $()}}var IY=Symbol.for("ls:otel_trace"),xY=Symbol.for("ls:otel_context"),rq=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),$G=new eq,YG=new QW;class $W{getTraceInstance(){return globalThis[IY]??$G}getContextInstance(){return globalThis[xY]??YG}initializeGlobalInstances(Q){if(globalThis[IY]===void 0)globalThis[IY]=Q.trace;if(globalThis[xY]===void 0)globalThis[xY]=Q.context}setDefaultOTLPTracerComponents(Q){globalThis[rq]=Q}getDefaultOTLPTracerComponents(){return globalThis[rq]??void 0}}var jY=new $W;function G$(){return jY.getTraceInstance()}function YW(){return jY.getContextInstance()}function qW(){return jY.getDefaultOTLPTracerComponents()}var qG={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function WG(Q){return qG[Q]||Q}class vY{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(Q,$){for(let Y of Q)try{if(!Y.run)continue;if(Y.operation==="post"){let q=this.createSpanForRun(Y,Y.run,$.get(Y.id));if(q&&!Y.run.end_time)this.spans.set(Y.id,q)}else this.updateSpanForRun(Y,Y.run)}catch(q){console.error(`Error processing operation ${Y.id}:`,q)}}createSpanForRun(Q,$,Y){let q=Y&&G$().getSpan(Y);if(!q)return;try{return this.finishSpanSetup(q,$,Q)}catch(W){console.error(`Failed to create span for run ${Q.id}:`,W);return}}finishSpanSetup(Q,$,Y){if(this.setSpanAttributes(Q,$,Y),$.error)Q.setStatus({code:2}),Q.recordException(Error($.error));else Q.setStatus({code:1});if($.end_time)Q.end(new Date($.end_time));return Q}updateSpanForRun(Q,$){try{let Y=this.spans.get(Q.id);if(!Y){console.debug(`No span found for run ${Q.id} during update`);return}if(this.setSpanAttributes(Y,$,Q),$.error)Y.setStatus({code:2}),Y.recordException(Error($.error));else Y.setStatus({code:1});let q=$.end_time;if(q)Y.end(new Date(q)),this.spans.delete(Q.id)}catch(Y){console.error(`Failed to update span for run ${Q.id}:`,Y)}}extractModelName(Q){if(Q.extra?.metadata){let $=Q.extra.metadata;if($.ls_model_name)return $.ls_model_name;if($.invocation_params){let Y=$.invocation_params;if(Y.model)return Y.model;else if(Y.model_name)return Y.model_name}}return}setSpanAttributes(Q,$,Y){if("run_type"in $&&$.run_type){Q.setAttribute(Rq,$.run_type);let G=WG($.run_type||"chain");Q.setAttribute(qq,G)}if("name"in $&&$.name)Q.setAttribute(Mq,$.name);if("session_id"in $&&$.session_id)Q.setAttribute(Sq,$.session_id);if("session_name"in $&&$.session_name)Q.setAttribute(Tq,$.session_name);this.setGenAiSystem(Q,$);let q=this.extractModelName($);if(q)Q.setAttribute(VY,q);if("prompt_tokens"in $&&typeof $.prompt_tokens==="number")Q.setAttribute(AY,$.prompt_tokens);if("completion_tokens"in $&&typeof $.completion_tokens==="number")Q.setAttribute(HY,$.completion_tokens);if("total_tokens"in $&&typeof $.total_tokens==="number")Q.setAttribute(DY,$.total_tokens);this.setInvocationParameters(Q,$);let W=$.extra?.metadata||{};for(let[G,J]of Object.entries(W))if(J!==null&&J!==void 0)Q.setAttribute(`${_q}.${G}`,String(J));let Z=$.tags;if(Z&&Array.isArray(Z))Q.setAttribute(wY,Z.join(", "));else if(Z)Q.setAttribute(wY,String(Z));if("serialized"in $&&typeof $.serialized==="object"){let G=$.serialized;if(G.name)Q.setAttribute(Aq,String(G.name));if(G.signature)Q.setAttribute(Hq,String(G.signature));if(G.doc)Q.setAttribute(Dq,String(G.doc))}this.setIOAttributes(Q,Y)}setGenAiSystem(Q,$){let Y="langchain",q=this.extractModelName($);if(q){let W=q.toLowerCase();if(W.includes("anthropic")||W.startsWith("claude"))Y="anthropic";else if(W.includes("bedrock"))Y="aws.bedrock";else if(W.includes("azure")&&W.includes("openai"))Y="az.ai.openai";else if(W.includes("azure")&&W.includes("inference"))Y="az.ai.inference";else if(W.includes("cohere"))Y="cohere";else if(W.includes("deepseek"))Y="deepseek";else if(W.includes("gemini"))Y="gemini";else if(W.includes("groq"))Y="groq";else if(W.includes("watson")||W.includes("ibm"))Y="ibm.watsonx.ai";else if(W.includes("mistral"))Y="mistral_ai";else if(W.includes("gpt")||W.includes("openai"))Y="openai";else if(W.includes("perplexity")||W.includes("sonar"))Y="perplexity";else if(W.includes("vertex"))Y="vertex_ai";else if(W.includes("xai")||W.includes("grok"))Y="xai"}Q.setAttribute(Wq,Y)}setInvocationParameters(Q,$){if(!$.extra?.metadata?.invocation_params)return;let Y=$.extra.metadata.invocation_params;if(Y.max_tokens!==void 0)Q.setAttribute(Gq,Y.max_tokens);if(Y.temperature!==void 0)Q.setAttribute(Jq,Y.temperature);if(Y.top_p!==void 0)Q.setAttribute(zq,Y.top_p);if(Y.frequency_penalty!==void 0)Q.setAttribute(Kq,Y.frequency_penalty);if(Y.presence_penalty!==void 0)Q.setAttribute(Xq,Y.presence_penalty)}setIOAttributes(Q,$){if($.run.inputs)try{let Y=$.run.inputs;if(typeof Y==="object"&&Y!==null){if(Y.model&&Array.isArray(Y.messages))Q.setAttribute(VY,Y.model);if(Y.stream!==void 0)Q.setAttribute(Iq,Y.stream);if(Y.extra_headers)Q.setAttribute(xq,JSON.stringify(Y.extra_headers));if(Y.extra_query)Q.setAttribute(Fq,JSON.stringify(Y.extra_query));if(Y.extra_body)Q.setAttribute(Vq,JSON.stringify(Y.extra_body))}Q.setAttribute(Nq,JSON.stringify(Y))}catch(Y){console.debug(`Failed to process inputs for run ${$.id}`,Y)}if($.run.outputs)try{let Y=$.run.outputs,q=this.getUnifiedRunTokens(Y);if(q)Q.setAttribute(AY,q[0]),Q.setAttribute(HY,q[1]),Q.setAttribute(DY,q[0]+q[1]);if(Y&&typeof Y==="object"){if(Y.model)Q.setAttribute(Zq,String(Y.model));if(Y.id)Q.setAttribute(wq,Y.id);if(Y.choices&&Array.isArray(Y.choices)){let W=Y.choices.map((Z)=>Z.finish_reason).filter((Z)=>Z).map(String);if(W.length>0)Q.setAttribute(Uq,W.join(", "))}if(Y.service_tier)Q.setAttribute(Oq,Y.service_tier);if(Y.system_fingerprint)Q.setAttribute(Eq,Y.system_fingerprint);if(Y.usage_metadata&&typeof Y.usage_metadata==="object"){let W=Y.usage_metadata;if(W.input_token_details)Q.setAttribute(Lq,JSON.stringify(W.input_token_details));if(W.output_token_details)Q.setAttribute(Pq,JSON.stringify(W.output_token_details))}}Q.setAttribute(Bq,JSON.stringify(Y))}catch(Y){console.debug(`Failed to process outputs for run ${$.id}`,Y)}}getUnifiedRunTokens(Q){if(!Q)return null;let $=this.extractUnifiedRunTokens(Q.usage_metadata);if($)return $;let Y=Object.keys(Q);for(let Z of Y){let G=Q[Z];if(!G||typeof G!=="object")continue;if($=this.extractUnifiedRunTokens(G.usage_metadata),$)return $;if(G.lc===1&&G.kwargs&&typeof G.kwargs==="object"){if($=this.extractUnifiedRunTokens(G.kwargs.usage_metadata),$)return $}}let q=Q.generations||[];if(!Array.isArray(q))return null;let W=Array.isArray(q[0])?q.flat():q;for(let Z of W)if(typeof Z==="object"&&Z.message&&typeof Z.message==="object"&&Z.message.kwargs&&typeof Z.message.kwargs==="object"){if($=this.extractUnifiedRunTokens(Z.message.kwargs.usage_metadata),$)return $}return null}extractUnifiedRunTokens(Q){if(!Q||typeof Q!=="object")return null;if(typeof Q.input_tokens!=="number"||typeof Q.output_tokens!=="number")return null;return[Q.input_tokens,Q.output_tokens]}}var ZG=Object.prototype.toString,GG=(Q)=>ZG.call(Q)==="[object Error]",JG=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function CY(Q){if(!(Q&&GG(Q)&&Q.name==="TypeError"&&typeof Q.message==="string"))return!1;let{message:Y,stack:q}=Q;if(Y==="Load failed")return q===void 0||"__sentry_captured__"in Q;if(Y.startsWith("error sending request for url"))return!0;return JG.has(Y)}function zG(Q){if(typeof Q==="number"){if(Q<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(Q))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(Q!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function J$(Q,$,{min:Y=0,allowInfinity:q=!1}={}){if($===void 0)return;if(typeof $!=="number"||Number.isNaN($))throw TypeError(`Expected \`${Q}\` to be a number${q?" or Infinity":""}.`);if(!q&&!Number.isFinite($))throw TypeError(`Expected \`${Q}\` to be a finite number.`);if($<Y)throw TypeError(`Expected \`${Q}\` to be ≥ ${Y}.`)}class ZW extends Error{constructor(Q){super();if(Q instanceof Error)this.originalError=Q,{message:Q}=Q;else this.originalError=Error(Q),this.originalError.stack=this.stack;this.name="AbortError",this.message=Q}}function KG(Q,$){let Y=Math.max(1,Q+1),q=$.randomize?Math.random()+1:1,W=Math.round(q*$.minTimeout*$.factor**(Y-1));return W=Math.min(W,$.maxTimeout),W}function WW(Q,$){if(!Number.isFinite($))return $;return $-(performance.now()-Q)}async function XG({error:Q,attemptNumber:$,retriesConsumed:Y,startTime:q,options:W}){let Z=Q instanceof Error?Q:TypeError(`Non-error was thrown: "${Q}". You should only throw errors.`);if(Z instanceof ZW)throw Z.originalError;let G=Number.isFinite(W.retries)?Math.max(0,W.retries-Y):W.retries,J=W.maxRetryTime??Number.POSITIVE_INFINITY,z=Object.freeze({error:Z,attemptNumber:$,retriesLeft:G,retriesConsumed:Y});if(await W.onFailedAttempt(z),WW(q,J)<=0)throw Z;let K=await W.shouldConsumeRetry(z),X=WW(q,J);if(X<=0||G<=0)throw Z;if(Z instanceof TypeError&&!CY(Z)){if(K)throw Z;return W.signal?.throwIfAborted(),!1}if(!await W.shouldRetry(z))throw Z;if(!K)return W.signal?.throwIfAborted(),!1;let U=KG(Y,W),N=Math.min(U,X);if(N>0)await new Promise((B,A)=>{let D=()=>{clearTimeout(w),W.signal?.removeEventListener("abort",D),A(W.signal.reason)},w=setTimeout(()=>{W.signal?.removeEventListener("abort",D),B()},N);if(W.unref)w.unref?.();W.signal?.addEventListener("abort",D,{once:!0})});return W.signal?.throwIfAborted(),!0}async function yY(Q,$={}){if($={...$},zG($.retries),Object.hasOwn($,"forever"))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");if($.retries??=10,$.factor??=2,$.minTimeout??=1000,$.maxTimeout??=Number.POSITIVE_INFINITY,$.maxRetryTime??=Number.POSITIVE_INFINITY,$.randomize??=!1,$.onFailedAttempt??=()=>{},$.shouldRetry??=()=>!0,$.shouldConsumeRetry??=()=>!0,J$("factor",$.factor,{min:0,allowInfinity:!1}),J$("minTimeout",$.minTimeout,{min:0,allowInfinity:!1}),J$("maxTimeout",$.maxTimeout,{min:0,allowInfinity:!0}),J$("maxRetryTime",$.maxRetryTime,{min:0,allowInfinity:!0}),!($.factor>0))$.factor=1;$.signal?.throwIfAborted();let Y=0,q=0,W=performance.now();while(Number.isFinite($.retries)?q<=$.retries:!0){Y++;try{$.signal?.throwIfAborted();let Z=await Q(Y);return $.signal?.throwIfAborted(),Z}catch(Z){if(await XG({error:Z,attemptNumber:Y,retriesConsumed:q,startTime:W,options:$}))q++}}throw Error("Retry attempts exhausted without throwing an error.")}var z$=rQ(kY(),1),GW="default"in z$.default?z$.default.default:z$.default;var UG=[408,425,429,500,502,503,504];class K${constructor(Q){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=Q.maxConcurrency??1/0,this.maxRetries=Q.maxRetries??6,this.maxQueueSizeBytes=Q.maxQueueSizeBytes,this.queue=new GW({concurrency:this.maxConcurrency}),this.onFailedResponseHook=Q?.onFailedResponseHook}call(Q,...$){return this.callWithOptions({},Q,...$)}callWithOptions(Q,$,...Y){let q=Q.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&q>0&&this.queueSizeBytes+q>this.maxQueueSizeBytes)return Promise.reject(Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${q} bytes.`));if(q>0)this.queueSizeBytes+=q;let W=this.onFailedResponseHook,Z=this.queue.add(()=>yY(()=>$(...Y).catch((G)=>{if(G instanceof Error)throw G;else throw Error(G)}),{async onFailedAttempt({error:G}){if(typeof G!=="object"||G==null)throw G;let J="message"in G&&typeof G.message==="string"?G.message:void 0;if(J?.startsWith("Cancel")||J?.startsWith("TimeoutError")||J?.startsWith("AbortError"))throw G;if("name"in G&&G.name==="TimeoutError")throw G;if("code"in G&&G.code==="ECONNABORTED")throw G;let z="response"in G?G.response:void 0;if(W){if(await W(z))return}let K=z?.status??("status"in G?G.status:void 0);if(K!=null&&(typeof K==="number"||typeof K==="string")&&!UG.includes(+K))throw G},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});if(q>0)Z=Z.finally(()=>{this.queueSizeBytes-=q});if(Q.signal)return Promise.race([Z,new Promise((G,J)=>{Q.signal?.addEventListener("abort",()=>{J(Error("AbortError"))})})]);return Z}}function bY(Q){return typeof Q?._getType==="function"}function hY(Q){let $={type:Q._getType(),data:{content:Q.content}};if(Q?.additional_kwargs&&Object.keys(Q.additional_kwargs).length>0)$.data.additional_kwargs={...Q.additional_kwargs};return $}var BG=rQ(NG(),1);function bQ(Q){if(!Q||Q.split("/").length>2||Q.startsWith("/")||Q.endsWith("/")||Q.split(":").length>2)throw Error(`Invalid identifier format: ${Q}`);let[$,Y]=Q.split(":"),q=Y||"latest";if($.includes("/")){let[W,Z]=$.split("/",2);if(!W||!Z)throw Error(`Invalid identifier format: ${Q}`);return[W,Z,q]}else{if(!$)throw Error(`Invalid identifier format: ${Q}`);return["-",$,q]}}class JW extends Error{constructor(Q){super(Q);Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}class zW extends Error{constructor(Q){super(Q);Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}}function fY(Q){return Q!=null&&typeof Q==="object"&&"name"in Q&&Q?.name==="LangSmithNotFoundError"}async function L(Q,$,Y){let q;if(Q.ok){if(Y)q=await Q.text();return}if(Q.status===403)try{if((await Q.json())?.error==="org_scoped_key_requires_workspace")q="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable."}catch(G){let J=Error(`${Q.status} ${Q.statusText}`);throw J.status=Q?.status,J}if(q===void 0)try{q=await Q.text()}catch(G){q=""}let W=`Failed to ${$}. Received status [${Q.status}]: ${Q.statusText}. Message: ${q}`;if(Q.status===404)throw new zW(W);if(Q.status===409)throw new JW(W);let Z=Error(W);throw Z.status=Q.status,Z}var KW="ERR_CONFLICTING_ENDPOINTS";class gY extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS.");Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:KW}),this.name="ConflictingEndpointsError"}}function XW(Q){return typeof Q==="object"&&Q!==null&&Q.code===KW}var UW="[...]",FG={result:"[Circular]"},U$=[],D0=[],VG=new TextEncoder;function AG(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function X$(Q){return VG.encode(Q)}function NW(Q){if(Q&&typeof Q==="object"&&Q!==null){if(Q instanceof Map)return Object.fromEntries(Q);else if(Q instanceof Set)return Array.from(Q);else if(Q instanceof Date)return Q.toISOString();else if(Q instanceof RegExp)return Q.toString();else if(Q instanceof Error)return{name:Q.name,message:Q.message}}else if(typeof Q==="bigint")return Q.toString();return Q}function HG(Q){return function($,Y){if(Q){let q=Q.call(this,$,Y);if(q!==void 0)return q}return NW(Y)}}function JQ(Q,$,Y,q,W){try{let Z=JSON.stringify(Q,HG(Y),q);return X$(Z)}catch(Z){if(!Z.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${$?`
|
|
18
|
+
Context: ${$}`:""}`),X$("[Unserializable]");if(c("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${$?`
|
|
19
|
+
Context: ${$}`:""}`),typeof W>"u")W=AG();dY(Q,"",0,[],void 0,0,W);let G;try{if(D0.length===0)G=JSON.stringify(Q,Y,q);else G=JSON.stringify(Q,DG(Y),q)}catch(J){return X$("[unable to serialize, circular reference is too complex to analyze]")}finally{while(U$.length!==0){let J=U$.pop();if(J.length===4)Object.defineProperty(J[0],J[1],J[3]);else J[0][J[1]]=J[2]}}return X$(G)}}function mY(Q,$,Y,q){var W=Object.getOwnPropertyDescriptor(q,Y);if(W.get!==void 0)if(W.configurable)Object.defineProperty(q,Y,{value:Q}),U$.push([q,Y,$,W]);else D0.push([$,Y,Q]);else q[Y]=Q,U$.push([q,Y,$])}function dY(Q,$,Y,q,W,Z,G){Z+=1;var J;if(typeof Q==="object"&&Q!==null){for(J=0;J<q.length;J++)if(q[J]===Q){mY(FG,Q,$,W);return}if(typeof G.depthLimit<"u"&&Z>G.depthLimit){mY(UW,Q,$,W);return}if(typeof G.edgesLimit<"u"&&Y+1>G.edgesLimit){mY(UW,Q,$,W);return}if(q.push(Q),Array.isArray(Q))for(J=0;J<Q.length;J++)dY(Q[J],J,J,q,Q,Z,G);else{Q=NW(Q);var z=Object.keys(Q);for(J=0;J<z.length;J++){var K=z[J];dY(Q[K],K,J,q,Q,Z,G)}}q.pop()}}function DG(Q){return Q=typeof Q<"u"?Q:function($,Y){return Y},function($,Y){if(D0.length>0)for(var q=0;q<D0.length;q++){var W=D0[q];if(W[1]===$&&W[0]===Y){Y=W[2],D0.splice(q,1);break}}return Q.call(this,$,Y)}}function BW(Q,$,Y){if(Y)return Q;let q=W$(),W=$??_Y(),Z=Q.extra??{},G=Z.metadata;return Q.extra={...Z,runtime:{...q,...Z?.runtime},metadata:{...W,...W.revision_id||"revision_id"in Q&&Q.revision_id?{revision_id:("revision_id"in Q?Q.revision_id:void 0)??W.revision_id}:{},...G}},Q}var wG=(Q)=>{let $=Q?.toString()??c("TRACING_SAMPLING_RATE");if($===void 0)return;let Y=parseFloat($);if(Y<0||Y>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${Y}`);return Y},OG=(Q)=>{let Y=Q.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return Y==="localhost"||Y==="127.0.0.1"||Y==="::1"};async function EG(Q){let $=[];for await(let Y of Q)$.push(Y);return $}function N$(Q){if(Q===void 0)return;return Q.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}var LG=async(Q)=>{if(Q?.status===429){let $=parseInt(Q.headers.get("retry-after")??"10",10)*1000;if($>0)return await new Promise((Y)=>setTimeout(Y,$)),!0}return!1};function FW(Q){if(typeof Q==="number")return Number(Q.toFixed(4));return Q}var PG=25165824,HW=1073741824,SG=1e4,TG=100,VW="https://api.smith.langchain.com";class DW{constructor(Q){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=Q??HW}peek(){return this.items[0]}push(Q){let $,Y=new Promise((W)=>{$=W}),q=JQ(Q.item,`Serializing run with id: ${Q.item.id}`).length;if(this.sizeBytes+q>this.maxSizeBytes&&this.items.length>0)return console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${Q.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${q} bytes.`),$(),Y;return this.items.push({action:Q.action,payload:Q.item,otelContext:Q.otelContext,apiKey:Q.apiKey,apiUrl:Q.apiUrl,itemPromiseResolve:$,itemPromise:Y,size:q}),this.sizeBytes+=q,Y}pop({upToSizeBytes:Q,upToSize:$}){if(Q<1)throw Error("Number of bytes to pop off may not be less than 1.");let Y=[],q=0;while(q+(this.peek()?.size??0)<Q&&this.items.length>0&&Y.length<$){let W=this.items.shift();if(W)Y.push(W),q+=W.size,this.sizeBytes-=W.size}if(Y.length===0&&this.items.length>0){let W=this.items.shift();Y.push(W),q+=W.size,this.sizeBytes-=W.size}return[Y.map((W)=>({action:W.action,item:W.payload,otelContext:W.otelContext,apiKey:W.apiKey,apiUrl:W.apiUrl,size:W.size})),()=>Y.forEach((W)=>W.itemPromiseResolve())]}}class dQ{get _fetch(){return this.fetchImplementation||Cq(this.debug)}constructor(Q={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:VQ("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:c("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:VQ("LANGSMITH_DEBUG")==="true"});let $=dQ.getDefaultClientConfig();if(this.tracingSampleRate=wG(Q.tracingSamplingRate),this.apiUrl=N$(Q.apiUrl??$.apiUrl)??"",this.apiUrl.endsWith("/"))this.apiUrl=this.apiUrl.slice(0,-1);if(this.apiKey=N$(Q.apiKey??$.apiKey),this.webUrl=N$(Q.webUrl??$.webUrl),this.webUrl?.endsWith("/"))this.webUrl=this.webUrl.slice(0,-1);if(this.workspaceId=N$(Q.workspaceId??c("WORKSPACE_ID")),this.timeout_ms=Q.timeout_ms??90000,this.caller=new K$({...Q.callerOptions??{},maxRetries:4,debug:Q.debug??this.debug}),this.traceBatchConcurrency=Q.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error("Trace batch concurrency must be positive.");this.debug=Q.debug??this.debug,this.fetchImplementation=Q.fetchImplementation;let Y=Q.maxIngestMemoryBytes??HW;if(this.batchIngestCaller=new K$({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:Y,...Q.callerOptions??{},onFailedResponseHook:LG,debug:Q.debug??this.debug}),this.hideInputs=Q.hideInputs??Q.anonymizer??$.hideInputs,this.hideOutputs=Q.hideOutputs??Q.anonymizer??$.hideOutputs,this.omitTracedRuntimeInfo=Q.omitTracedRuntimeInfo??!1,this.autoBatchTracing=Q.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new DW(Y),this.blockOnRootRunFinalization=Q.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=Q.batchSizeBytesLimit,this.batchSizeLimit=Q.batchSizeLimit,this.fetchOptions=Q.fetchOptions||{},this.manualFlushMode=Q.manualFlushMode??this.manualFlushMode,Z$())this.langSmithToOTELTranslator=new vY;if(this.cachedLSEnvVarsForMetadata=_Y(),Q.cache!==void 0&&Q.disablePromptCache)Y0("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value.");if(Q.cache!==void 0)if(Y0("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),Q.cache===!1)this._promptCache=void 0;else if(Q.cache===!0)this._promptCache=Y$;else this._promptCache=Q.cache;else if(!Q.disablePromptCache)this._promptCache=Y$}static getDefaultClientConfig(){let Q=c("API_KEY"),$=c("ENDPOINT")??VW,Y=c("HIDE_INPUTS")==="true",q=c("HIDE_OUTPUTS")==="true";return{apiUrl:$,apiKey:Q,webUrl:void 0,hideInputs:Y,hideOutputs:q}}getHostUrl(){if(this.webUrl)return this.webUrl;else if(OG(this.apiUrl))return this.webUrl="http://localhost:3000",this.webUrl;else if(this.apiUrl.endsWith("/api/v1"))return this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl;else if(this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api"))return this.webUrl=this.apiUrl.replace("/api",""),this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("dev"))return this.webUrl="https://dev.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("eu"))return this.webUrl="https://eu.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("beta"))return this.webUrl="https://beta.smith.langchain.com",this.webUrl;else return this.webUrl="https://smith.langchain.com",this.webUrl}get headers(){let Q={"User-Agent":`langsmith-js/${q$}`};if(this.apiKey)Q["x-api-key"]=`${this.apiKey}`;if(this.workspaceId)Q["x-tenant-id"]=this.workspaceId;return Q}_getPlatformEndpointPath(Q){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${Q}`:`/platform/${Q}`}async processInputs(Q){if(this.hideInputs===!1)return Q;if(this.hideInputs===!0)return{};if(typeof this.hideInputs==="function")return this.hideInputs(Q);return Q}async processOutputs(Q){if(this.hideOutputs===!1)return Q;if(this.hideOutputs===!0)return{};if(typeof this.hideOutputs==="function")return this.hideOutputs(Q);return Q}async prepareRunCreateOrUpdateInputs(Q){let $={...Q};if($.inputs!==void 0)$.inputs=await this.processInputs($.inputs);if($.outputs!==void 0)$.outputs=await this.processOutputs($.outputs);return $}async _getResponse(Q,$){let Y=$?.toString()??"",q=`${this.apiUrl}${Q}?${Y}`;return await this.caller.call(async()=>{let Z=await this._fetch(q,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(Z,`fetch ${Q}`),Z})}async _get(Q,$){return(await this._getResponse(Q,$)).json()}async*_getPaginated(Q,$=new URLSearchParams,Y){let q=Number($.get("offset"))||0,W=Number($.get("limit"))||100;while(!0){$.set("offset",String(q)),$.set("limit",String(W));let Z=`${this.apiUrl}${Q}?${$}`,G=await this.caller.call(async()=>{let z=await this._fetch(Z,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(z,`fetch ${Q}`),z}),J=Y?Y(await G.json()):await G.json();if(J.length===0)break;if(yield J,J.length<W)break;q+=J.length}}async*_getCursorPaginatedList(Q,$=null,Y="POST",q="runs"){let W=$?{...$}:{};while(!0){let Z=JSON.stringify(W),J=await(await this.caller.call(async()=>{let K=await this._fetch(`${this.apiUrl}${Q}`,{method:Y,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Z});return await L(K,`fetch ${Q}`),K})).json();if(!J)break;if(!J[q])break;yield J[q];let z=J.cursors;if(!z)break;if(!z.next)break;W.cursor=z.next}}_shouldSample(){if(this.tracingSampleRate===void 0)return!0;return Math.random()<this.tracingSampleRate}_filterForSampling(Q,$=!1){if(this.tracingSampleRate===void 0)return Q;if($){let Y=[];for(let q of Q)if(!this.filteredPostUuids.has(q.trace_id))Y.push(q);else if(q.id===q.trace_id)this.filteredPostUuids.delete(q.trace_id);return Y}else{let Y=[];for(let q of Q){let W=q.trace_id??q.id;if(this.filteredPostUuids.has(W))continue;if(q.id===W)if(this._shouldSample())Y.push(q);else this.filteredPostUuids.add(W);else Y.push(q)}return Y}}async _getBatchSizeLimitBytes(){let Q=await this._ensureServerInfo();return this.batchSizeBytesLimit??Q?.batch_ingest_config?.size_limit_bytes??PG}async _getBatchSizeLimit(){let Q=await this._ensureServerInfo();return this.batchSizeLimit??Q?.batch_ingest_config?.size_limit??TG}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:Q,batchSizeLimit:$}){let Y=[];while(this.autoBatchQueue.items.length>0){let[q,W]=this.autoBatchQueue.pop({upToSizeBytes:Q,upToSize:$});if(!q.length){W();break}let Z=q.reduce((z,K)=>{let X=K.apiUrl??this.apiUrl,U=K.apiKey??this.apiKey,B=K.apiKey===this.apiKey&&K.apiUrl===this.apiUrl?"default":`${X}|${U}`;if(!z[B])z[B]=[];return z[B].push(K),z},{}),G=[];for(let[z,K]of Object.entries(Z)){let X=this._processBatch(K,{apiUrl:z==="default"?void 0:z.split("|")[0],apiKey:z==="default"?void 0:z.split("|")[1]});G.push(X)}let J=Promise.all(G).finally(W);Y.push(J)}return Promise.all(Y)}async _processBatch(Q,$){if(!Q.length)return;let Y=Q.reduce((q,W)=>q+(W.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(Q);else{let q={runCreates:Q.filter((G)=>G.action==="create").map((G)=>G.item),runUpdates:Q.filter((G)=>G.action==="update").map((G)=>G.item)},W=await this._ensureServerInfo();if(!this._multipartDisabled&&(W?.batch_ingest_config?.use_multipart_endpoint??!0)){let G=!this._runCompressionDisabled&&W?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(q,{...$,useGzip:G,sizeBytes:Y})}catch(J){if(fY(J))this._multipartDisabled=!0,await this.batchIngestRuns(q,{...$,sizeBytes:Y});else throw J}}else await this.batchIngestRuns(q,{...$,sizeBytes:Y})}}catch(q){console.error("Error exporting batch:",q)}}_sendBatchToOTELTranslator(Q){if(this.langSmithToOTELTranslator!==void 0){let $=new Map,Y=[];for(let q of Q)if(q.item.id&&q.otelContext)if($.set(q.item.id,q.otelContext),q.action==="create")Y.push({operation:"post",id:q.item.id,trace_id:q.item.trace_id??q.item.id,run:q.item});else Y.push({operation:"patch",id:q.item.id,trace_id:q.item.trace_id??q.item.id,run:q.item});this.langSmithToOTELTranslator.exportBatch(Y,$)}}async processRunOperation(Q){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,Q.item=BW(Q.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let $=this.autoBatchQueue.push(Q);if(this.manualFlushMode)return $;let Y=await this._getBatchSizeLimitBytes(),q=await this._getBatchSizeLimit();if(this.autoBatchQueue.sizeBytes>Y||this.autoBatchQueue.items.length>q)this.drainAutoBatchQueue({batchSizeLimitBytes:Y,batchSizeLimit:q});if(this.autoBatchQueue.items.length>0)this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:Y,batchSizeLimit:q})},this.autoBatchAggregationDelayMs);return $}async _getServerInfo(){let $=await(await this.caller.call(async()=>{let Y=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(SG),...this.fetchOptions});return await L(Y,"get server info"),Y})).json();if(this.debug)console.log(`
|
|
20
|
+
=== LangSmith Server Configuration ===
|
|
21
|
+
`+JSON.stringify($,null,2)+`
|
|
22
|
+
`);return $}async _ensureServerInfo(){if(this._getServerInfoPromise===void 0)this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(Q){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${Q.status??"Unspecified status code"} ${Q.message}`)}return this._serverInfo??{}})();return this._getServerInfoPromise.then((Q)=>{if(this._serverInfo===void 0)this._getServerInfoPromise=void 0;return Q})}async _getSettings(){if(!this.settings)this.settings=this._get("/settings");return await this.settings}async flush(){let Q=await this._getBatchSizeLimitBytes(),$=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:Q,batchSizeLimit:$})}_cloneCurrentOTELContext(){let Q=G$(),$=YW();if(this.langSmithToOTELTranslator!==void 0){let Y=Q.getActiveSpan();if(Y)return Q.setSpan($.active(),Y)}return}async createRun(Q,$){if(!this._filterForSampling([Q]).length)return;let Y={...this.headers,"Content-Type":"application/json"},q=Q.project_name;delete Q.project_name;let W=await this.prepareRunCreateOrUpdateInputs({session_name:q,...Q,start_time:Q.start_time??Date.now()});if(this.autoBatchTracing&&W.trace_id!==void 0&&W.dotted_order!==void 0){let J=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:W,otelContext:J,apiKey:$?.apiKey,apiUrl:$?.apiUrl}).catch(console.error);return}let Z=BW(W,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);if($?.apiKey!==void 0)Y["x-api-key"]=$.apiKey;if($?.workspaceId!==void 0)Y["x-tenant-id"]=$.workspaceId;let G=JQ(Z,`Creating run with id: ${Z.id}`);await this.caller.call(async()=>{let J=await this._fetch(`${$?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:Y,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:G});return await L(J,"create run",!0),J})}async batchIngestRuns({runCreates:Q,runUpdates:$},Y){if(Q===void 0&&$===void 0)return;let q=await Promise.all(Q?.map((J)=>this.prepareRunCreateOrUpdateInputs(J))??[]),W=await Promise.all($?.map((J)=>this.prepareRunCreateOrUpdateInputs(J))??[]);if(q.length>0&&W.length>0){let J=q.reduce((K,X)=>{if(!X.id)return K;return K[X.id]=X,K},{}),z=[];for(let K of W)if(K.id!==void 0&&J[K.id])J[K.id]={...J[K.id],...K};else z.push(K);q=Object.values(J),W=z}let Z={post:q,patch:W};if(!Z.post.length&&!Z.patch.length)return;let G={post:[],patch:[]};for(let J of["post","patch"]){let z=J,K=Z[z].reverse(),X=K.pop();while(X!==void 0)G[z].push(X),X=K.pop()}if(G.post.length>0||G.patch.length>0){let J=G.post.map((z)=>z.id).concat(G.patch.map((z)=>z.id)).join(",");await this._postBatchIngestRuns(JQ(G,`Ingesting runs with ids: ${J}`),Y)}}async _postBatchIngestRuns(Q,$){let Y={...this.headers,"Content-Type":"application/json",Accept:"application/json"};if($?.apiKey!==void 0)Y["x-api-key"]=$.apiKey;await this.batchIngestCaller.callWithOptions({sizeBytes:$?.sizeBytes},async()=>{let q=await this._fetch(`${$?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:Y,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Q});return await L(q,"batch create run",!0),q})}async multipartIngestRuns({runCreates:Q,runUpdates:$},Y){if(Q===void 0&&$===void 0)return;let q={},W=[];for(let X of Q??[]){let U=await this.prepareRunCreateOrUpdateInputs(X);if(U.id!==void 0&&U.attachments!==void 0)q[U.id]=U.attachments;delete U.attachments,W.push(U)}let Z=[];for(let X of $??[])Z.push(await this.prepareRunCreateOrUpdateInputs(X));if(W.find((X)=>{return X.trace_id===void 0||X.dotted_order===void 0})!==void 0)throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(Z.find((X)=>{return X.trace_id===void 0||X.dotted_order===void 0})!==void 0)throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(W.length>0&&Z.length>0){let X=W.reduce((N,B)=>{if(!B.id)return N;return N[B.id]=B,N},{}),U=[];for(let N of Z)if(N.id!==void 0&&X[N.id])X[N.id]={...X[N.id],...N};else U.push(N);W=Object.values(X),Z=U}if(W.length===0&&Z.length===0)return;let z=[],K=[];for(let[X,U]of[["post",W],["patch",Z]])for(let N of U){let{inputs:B,outputs:A,events:D,extra:w,error:S,serialized:H,attachments:R,...T}=N,y={inputs:B,outputs:A,events:D,extra:w,error:S,serialized:H},b=JQ(T,`Serializing for multipart ingestion of run with id: ${T.id}`);K.push({name:`${X}.${T.id}`,payload:new Blob([b],{type:`application/json; length=${b.length}`})});for(let[g,WQ]of Object.entries(y)){if(WQ===void 0)continue;let XQ=JQ(WQ,`Serializing ${g} for multipart ingestion of run with id: ${T.id}`);K.push({name:`${X}.${T.id}.${g}`,payload:new Blob([XQ],{type:`application/json; length=${XQ.length}`})})}if(T.id!==void 0){let g=q[T.id];if(g){delete q[T.id];for(let[WQ,XQ]of Object.entries(g)){let X0,nQ;if(Array.isArray(XQ))[X0,nQ]=XQ;else X0=XQ.mimeType,nQ=XQ.data;if(WQ.includes(".")){console.warn(`Skipping attachment '${WQ}' for run ${T.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}K.push({name:`attachment.${T.id}.${WQ}`,payload:new Blob([nQ],{type:`${X0}; length=${nQ.byteLength}`})})}}}z.push(`trace=${T.trace_id},id=${T.id}`)}await this._sendMultipartRequest(K,z.join("; "),Y)}async _createNodeFetchBody(Q,$){let Y=[];for(let Z of Q)Y.push(new Blob([`--${$}\r
|
|
23
|
+
`])),Y.push(new Blob([`Content-Disposition: form-data; name="${Z.name}"\r
|
|
24
|
+
`,`Content-Type: ${Z.payload.type}\r
|
|
25
|
+
\r
|
|
26
|
+
`])),Y.push(Z.payload),Y.push(new Blob([`\r
|
|
27
|
+
`]));return Y.push(new Blob([`--${$}--\r
|
|
28
|
+
`])),await new Blob(Y).arrayBuffer()}async _createMultipartStream(Q,$){let Y=new TextEncoder;return new ReadableStream({async start(W){let Z=async(G)=>{if(typeof G==="string")W.enqueue(Y.encode(G));else W.enqueue(G)};for(let G of Q){await Z(`--${$}\r
|
|
29
|
+
`),await Z(`Content-Disposition: form-data; name="${G.name}"\r
|
|
30
|
+
`),await Z(`Content-Type: ${G.payload.type}\r
|
|
31
|
+
\r
|
|
32
|
+
`);let z=G.payload.stream().getReader();try{let K;while(!(K=await z.read()).done)W.enqueue(K.value)}finally{z.releaseLock()}await Z(`\r
|
|
33
|
+
`)}await Z(`--${$}--\r
|
|
34
|
+
`),W.close()}})}async _sendMultipartRequest(Q,$,Y){let q="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),W=()=>this._createNodeFetchBody(Q,q),Z=()=>this._createMultipartStream(Q,q),G=async(J)=>{return this.batchIngestCaller.callWithOptions({sizeBytes:Y?.sizeBytes},async()=>{let z=await J(),K={...this.headers,"Content-Type":`multipart/form-data; boundary=${q}`};if(Y?.apiKey!==void 0)K["x-api-key"]=Y.apiKey;let X=z;if(Y?.useGzip&&typeof z==="object"&&"pipeThrough"in z)X=z.pipeThrough(new CompressionStream("gzip")),K["Content-Encoding"]="gzip";let U=await this._fetch(`${Y?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:K,body:X,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(U,"Failed to send multipart request",!0),U})};try{let J,z=!1;if(vq()&&!this.multipartStreamingDisabled&&MY()!=="bun")z=!0,J=await G(Z);else J=await G(W);if((!this.multipartStreamingDisabled||z)&&J.status===422&&(Y?.apiUrl??this.apiUrl)!==VW)console.warn(`Streaming multipart upload to ${Y?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${$}".`),this.multipartStreamingDisabled=!0,J=await G(W)}catch(J){if(fY(J))throw J;console.warn(`${J.message.trim()}
|
|
35
|
+
|
|
36
|
+
Context: ${$}`)}}async updateRun(Q,$,Y){if(I(Q),$.inputs)$.inputs=await this.processInputs($.inputs);if($.outputs)$.outputs=await this.processOutputs($.outputs);let q={...$,id:Q};if(!this._filterForSampling([q],!0).length)return;if(this.autoBatchTracing&&q.trace_id!==void 0&&q.dotted_order!==void 0){let G=this._cloneCurrentOTELContext();if($.end_time!==void 0&&q.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:q,otelContext:G,apiKey:Y?.apiKey,apiUrl:Y?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:q,otelContext:G,apiKey:Y?.apiKey,apiUrl:Y?.apiUrl}).catch(console.error);return}let W={...this.headers,"Content-Type":"application/json"};if(Y?.apiKey!==void 0)W["x-api-key"]=Y.apiKey;if(Y?.workspaceId!==void 0)W["x-tenant-id"]=Y.workspaceId;let Z=JQ($,`Serializing payload to update run with id: ${Q}`);await this.caller.call(async()=>{let G=await this._fetch(`${Y?.apiUrl??this.apiUrl}/runs/${Q}`,{method:"PATCH",headers:W,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Z});return await L(G,"update run",!0),G})}async readRun(Q,{loadChildRuns:$}={loadChildRuns:!1}){I(Q);let Y=await this._get(`/runs/${Q}`);if($)Y=await this._loadChildRuns(Y);return Y}async getRunUrl({runId:Q,run:$,projectOpts:Y}){if($!==void 0){let q;if($.session_id)q=$.session_id;else if(Y?.projectName)q=(await this.readProject({projectName:Y?.projectName})).id;else if(Y?.projectId)q=Y?.projectId;else q=(await this.readProject({projectName:c("PROJECT")||"default"})).id;let W=await this._getTenantId();return`${this.getHostUrl()}/o/${W}/projects/p/${q}/r/${$.id}?poll=true`}else if(Q!==void 0){let q=await this.readRun(Q);if(!q.app_path)throw Error(`Run ${Q} has no app_path`);return`${this.getHostUrl()}${q.app_path}`}else throw Error("Must provide either runId or run")}async _loadChildRuns(Q){let $=await EG(this.listRuns({isRoot:!1,projectId:Q.session_id,traceId:Q.trace_id})),Y={},q={};$.sort((W,Z)=>(W?.dotted_order??"").localeCompare(Z?.dotted_order??""));for(let W of $){if(W.parent_run_id===null||W.parent_run_id===void 0)throw Error(`Child run ${W.id} has no parent`);if(W.dotted_order?.startsWith(Q.dotted_order??"")&&W.id!==Q.id){if(!(W.parent_run_id in Y))Y[W.parent_run_id]=[];Y[W.parent_run_id].push(W),q[W.id]=W}}Q.child_runs=Y[Q.id]||[];for(let W in Y)if(W!==Q.id)q[W].child_runs=Y[W];return Q}async*listRuns(Q){let{projectId:$,projectName:Y,parentRunId:q,traceId:W,referenceExampleId:Z,startTime:G,executionOrder:J,isRoot:z,runType:K,error:X,id:U,query:N,filter:B,traceFilter:A,treeFilter:D,limit:w,select:S,order:H}=Q,R=[];if($)R=Array.isArray($)?$:[$];if(Y){let g=Array.isArray(Y)?Y:[Y],WQ=await Promise.all(g.map((XQ)=>this.readProject({projectName:XQ}).then((X0)=>X0.id)));R.push(...WQ)}let T=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],y={session:R.length?R:null,run_type:K,reference_example:Z,query:N,filter:B,trace_filter:A,tree_filter:D,execution_order:J,parent_run:q,start_time:G?G.toISOString():null,error:X,id:U,limit:w,trace:W,select:S?S:T,is_root:z,order:H};if(y.select.includes("child_run_ids"))Y0("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let b=0;for await(let g of this._getCursorPaginatedList("/runs/query",y))if(w){if(b>=w)break;if(g.length+b>w){yield*g.slice(0,w-b);break}b+=g.length,yield*g}else yield*g}async*listGroupRuns(Q){let{projectId:$,projectName:Y,groupBy:q,filter:W,startTime:Z,endTime:G,limit:J,offset:z}=Q,X={session_id:$||(await this.readProject({projectName:Y})).id,group_by:q,filter:W,start_time:Z?Z.toISOString():null,end_time:G?G.toISOString():null,limit:Number(J)||100},U=Number(z)||0,N="/runs/group",B=`${this.apiUrl}${N}`;while(!0){let A={...X,offset:U},D=Object.fromEntries(Object.entries(A).filter(([y,b])=>b!==void 0)),w=JSON.stringify(D),H=await(await this.caller.call(async()=>{let y=await this._fetch(B,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:w});return await L(y,`Failed to fetch ${N}`),y})).json(),{groups:R,total:T}=H;if(R.length===0)break;for(let y of R)yield y;if(U+=R.length,U>=T)break}}async getRunStats({id:Q,trace:$,parentRun:Y,runType:q,projectNames:W,projectIds:Z,referenceExampleIds:G,startTime:J,endTime:z,error:K,query:X,filter:U,traceFilter:N,treeFilter:B,isRoot:A,dataSourceType:D}){let w=Z||[];if(W)w=[...Z||[],...await Promise.all(W.map((b)=>this.readProject({projectName:b}).then((g)=>g.id)))];let H=Object.fromEntries(Object.entries({id:Q,trace:$,parent_run:Y,run_type:q,session:w,reference_example:G,start_time:J,end_time:z,error:K,query:X,filter:U,trace_filter:N,tree_filter:B,is_root:A,data_source_type:D}).filter(([b,g])=>g!==void 0)),R=JSON.stringify(H);return await(await this.caller.call(async()=>{let b=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:R});return await L(b,"get run stats"),b})).json()}async shareRun(Q,{shareId:$}={}){let Y={run_id:Q,share_token:$||pQ()};I(Q);let q=JSON.stringify(Y),Z=await(await this.caller.call(async()=>{let G=await this._fetch(`${this.apiUrl}/runs/${Q}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:q});return await L(G,"share run"),G})).json();if(Z===null||!("share_token"in Z))throw Error("Invalid response from server");return`${this.getHostUrl()}/public/${Z.share_token}/r`}async unshareRun(Q){I(Q),await this.caller.call(async()=>{let $=await this._fetch(`${this.apiUrl}/runs/${Q}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L($,"unshare run",!0),$})}async readRunSharedLink(Q){I(Q);let Y=await(await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/runs/${Q}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(q,"read run shared link"),q})).json();if(Y===null||!("share_token"in Y))return;return`${this.getHostUrl()}/public/${Y.share_token}/r`}async listSharedRuns(Q,{runIds:$}={}){let Y=new URLSearchParams({share_token:Q});if($!==void 0)for(let Z of $)Y.append("id",Z);return I(Q),await(await this.caller.call(async()=>{let Z=await this._fetch(`${this.apiUrl}/public/${Q}/runs${Y}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(Z,"list shared runs"),Z})).json()}async readDatasetSharedSchema(Q,$){if(!Q&&!$)throw Error("Either datasetId or datasetName must be given");if(!Q)Q=(await this.readDataset({datasetName:$})).id;I(Q);let q=await(await this.caller.call(async()=>{let W=await this._fetch(`${this.apiUrl}/datasets/${Q}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(W,"read dataset shared schema"),W})).json();return q.url=`${this.getHostUrl()}/public/${q.share_token}/d`,q}async shareDataset(Q,$){if(!Q&&!$)throw Error("Either datasetId or datasetName must be given");if(!Q)Q=(await this.readDataset({datasetName:$})).id;let Y={dataset_id:Q};I(Q);let q=JSON.stringify(Y),Z=await(await this.caller.call(async()=>{let G=await this._fetch(`${this.apiUrl}/datasets/${Q}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:q});return await L(G,"share dataset"),G})).json();return Z.url=`${this.getHostUrl()}/public/${Z.share_token}/d`,Z}async unshareDataset(Q){I(Q),await this.caller.call(async()=>{let $=await this._fetch(`${this.apiUrl}/datasets/${Q}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L($,"unshare dataset",!0),$})}async readSharedDataset(Q){return I(Q),await(await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/public/${Q}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(q,"read shared dataset"),q})).json()}async listSharedExamples(Q,$){let Y={};if($?.exampleIds)Y.id=$.exampleIds;let q=new URLSearchParams;Object.entries(Y).forEach(([G,J])=>{if(Array.isArray(J))J.forEach((z)=>q.append(G,z));else q.append(G,J)});let W=await this.caller.call(async()=>{let G=await this._fetch(`${this.apiUrl}/public/${Q}/examples?${q.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(G,"list shared examples"),G}),Z=await W.json();if(!W.ok){if("detail"in Z)throw Error(`Failed to list shared examples.
|
|
37
|
+
Status: ${W.status}
|
|
38
|
+
Message: ${Array.isArray(Z.detail)?Z.detail.join(`
|
|
39
|
+
`):"Unspecified error"}`);throw Error(`Failed to list shared examples: ${W.status} ${W.statusText}`)}return Z.map((G)=>({...G,_hostUrl:this.getHostUrl()}))}async createProject({projectName:Q,description:$=null,metadata:Y=null,upsert:q=!1,projectExtra:W=null,referenceDatasetId:Z=null}){let G=q?"?upsert=true":"",J=`${this.apiUrl}/sessions${G}`,z=W||{};if(Y)z.metadata=Y;let K={name:Q,extra:z,description:$};if(Z!==null)K.reference_dataset_id=Z;let X=JSON.stringify(K);return await(await this.caller.call(async()=>{let B=await this._fetch(J,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:X});return await L(B,"create project"),B})).json()}async updateProject(Q,{name:$=null,description:Y=null,metadata:q=null,projectExtra:W=null,endTime:Z=null}){let G=`${this.apiUrl}/sessions/${Q}`,J=W;if(q)J={...J||{},metadata:q};let z=JSON.stringify({name:$,extra:J,description:Y,end_time:Z?new Date(Z).toISOString():null});return await(await this.caller.call(async()=>{let U=await this._fetch(G,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:z});return await L(U,"update project"),U})).json()}async hasProject({projectId:Q,projectName:$}){let Y="/sessions",q=new URLSearchParams;if(Q!==void 0&&$!==void 0)throw Error("Must provide either projectName or projectId, not both");else if(Q!==void 0)I(Q),Y+=`/${Q}`;else if($!==void 0)q.append("name",$);else throw Error("Must provide projectName or projectId");let W=await this.caller.call(async()=>{let Z=await this._fetch(`${this.apiUrl}${Y}?${q}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(Z,"has project"),Z});try{let Z=await W.json();if(!W.ok)return!1;if(Array.isArray(Z))return Z.length>0;return!0}catch(Z){return!1}}async readProject({projectId:Q,projectName:$,includeStats:Y}){let q="/sessions",W=new URLSearchParams;if(Q!==void 0&&$!==void 0)throw Error("Must provide either projectName or projectId, not both");else if(Q!==void 0)I(Q),q+=`/${Q}`;else if($!==void 0)W.append("name",$);else throw Error("Must provide projectName or projectId");if(Y!==void 0)W.append("include_stats",Y.toString());let Z=await this._get(q,W),G;if(Array.isArray(Z)){if(Z.length===0)throw Error(`Project[id=${Q}, name=${$}] not found`);G=Z[0]}else G=Z;return G}async getProjectUrl({projectId:Q,projectName:$}){if(Q===void 0&&$===void 0)throw Error("Must provide either projectName or projectId");let Y=await this.readProject({projectId:Q,projectName:$}),q=await this._getTenantId();return`${this.getHostUrl()}/o/${q}/projects/p/${Y.id}`}async getDatasetUrl({datasetId:Q,datasetName:$}){if(Q===void 0&&$===void 0)throw Error("Must provide either datasetName or datasetId");let Y=await this.readDataset({datasetId:Q,datasetName:$}),q=await this._getTenantId();return`${this.getHostUrl()}/o/${q}/datasets/${Y.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let Q=new URLSearchParams({limit:"1"});for await(let $ of this._getPaginated("/sessions",Q))return this._tenantId=$[0].tenant_id,$[0].tenant_id;throw Error("No projects found to resolve tenant.")}async*listProjects({projectIds:Q,name:$,nameContains:Y,referenceDatasetId:q,referenceDatasetName:W,includeStats:Z,datasetVersion:G,referenceFree:J,metadata:z}={}){let K=new URLSearchParams;if(Q!==void 0)for(let X of Q)K.append("id",X);if($!==void 0)K.append("name",$);if(Y!==void 0)K.append("name_contains",Y);if(q!==void 0)K.append("reference_dataset",q);else if(W!==void 0){let X=await this.readDataset({datasetName:W});K.append("reference_dataset",X.id)}if(Z!==void 0)K.append("include_stats",Z.toString());if(G!==void 0)K.append("dataset_version",G);if(J!==void 0)K.append("reference_free",J.toString());if(z!==void 0)K.append("metadata",JSON.stringify(z));for await(let X of this._getPaginated("/sessions",K))yield*X}async deleteProject({projectId:Q,projectName:$}){let Y;if(Q===void 0&&$===void 0)throw Error("Must provide projectName or projectId");else if(Q!==void 0&&$!==void 0)throw Error("Must provide either projectName or projectId, not both");else if(Q===void 0)Y=(await this.readProject({projectName:$})).id;else Y=Q;I(Y),await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/sessions/${Y}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(q,`delete session ${Y} (${$})`,!0),q})}async uploadCsv({csvFile:Q,fileName:$,inputKeys:Y,outputKeys:q,description:W,dataType:Z,name:G}){let J=`${this.apiUrl}/datasets/upload`,z=new FormData,K=new Blob([Q],{type:"text/csv"});if(z.append("file",K,$),Y.forEach((N)=>{z.append("input_keys",N)}),q.forEach((N)=>{z.append("output_keys",N)}),W)z.append("description",W);if(Z)z.append("data_type",Z);if(G)z.append("name",G);return await(await this.caller.call(async()=>{let N=await this._fetch(J,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:z});return await L(N,"upload CSV"),N})).json()}async createDataset(Q,{description:$,dataType:Y,inputsSchema:q,outputsSchema:W,metadata:Z}={}){let G={name:Q,description:$,extra:Z?{metadata:Z}:void 0};if(Y)G.data_type=Y;if(q)G.inputs_schema_definition=q;if(W)G.outputs_schema_definition=W;let J=JSON.stringify(G);return await(await this.caller.call(async()=>{let X=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:J});return await L(X,"create dataset"),X})).json()}async readDataset({datasetId:Q,datasetName:$}){let Y="/datasets",q=new URLSearchParams({limit:"1"});if(Q&&$)throw Error("Must provide either datasetName or datasetId, not both");else if(Q)I(Q),Y+=`/${Q}`;else if($)q.append("name",$);else throw Error("Must provide datasetName or datasetId");let W=await this._get(Y,q),Z;if(Array.isArray(W)){if(W.length===0)throw Error(`Dataset[id=${Q}, name=${$}] not found`);Z=W[0]}else Z=W;return Z}async hasDataset({datasetId:Q,datasetName:$}){try{return await this.readDataset({datasetId:Q,datasetName:$}),!0}catch(Y){if(Y instanceof Error&&Y.message.toLocaleLowerCase().includes("not found"))return!1;throw Y}}async diffDatasetVersions({datasetId:Q,datasetName:$,fromVersion:Y,toVersion:q}){let W=Q;if(W===void 0&&$===void 0)throw Error("Must provide either datasetName or datasetId");else if(W!==void 0&&$!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(W===void 0)W=(await this.readDataset({datasetName:$})).id;let Z=new URLSearchParams({from_version:typeof Y==="string"?Y:Y.toISOString(),to_version:typeof q==="string"?q:q.toISOString()});return await this._get(`/datasets/${W}/versions/diff`,Z)}async readDatasetOpenaiFinetuning({datasetId:Q,datasetName:$}){if(Q!==void 0);else if($!==void 0)Q=(await this.readDataset({datasetName:$})).id;else throw Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`/datasets/${Q}/openai_ft`)).text()).trim().split(`
|
|
40
|
+
`).map((G)=>JSON.parse(G))}async*listDatasets({limit:Q=100,offset:$=0,datasetIds:Y,datasetName:q,datasetNameContains:W,metadata:Z}={}){let J=new URLSearchParams({limit:Q.toString(),offset:$.toString()});if(Y!==void 0)for(let z of Y)J.append("id",z);if(q!==void 0)J.append("name",q);if(W!==void 0)J.append("name_contains",W);if(Z!==void 0)J.append("metadata",JSON.stringify(Z));for await(let z of this._getPaginated("/datasets",J))yield*z}async updateDataset(Q){let{datasetId:$,datasetName:Y,...q}=Q;if(!$&&!Y)throw Error("Must provide either datasetName or datasetId");let W=$??(await this.readDataset({datasetName:Y})).id;I(W);let Z=JSON.stringify(q);return await(await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/datasets/${W}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Z});return await L(J,"update dataset"),J})).json()}async updateDatasetTag(Q){let{datasetId:$,datasetName:Y,asOf:q,tag:W}=Q;if(!$&&!Y)throw Error("Must provide either datasetName or datasetId");let Z=$??(await this.readDataset({datasetName:Y})).id;I(Z);let G=JSON.stringify({as_of:typeof q==="string"?q:q.toISOString(),tag:W});await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/datasets/${Z}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:G});return await L(J,"update dataset tags",!0),J})}async deleteDataset({datasetId:Q,datasetName:$}){let Y="/datasets",q=Q;if(Q!==void 0&&$!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if($!==void 0)q=(await this.readDataset({datasetName:$})).id;if(q!==void 0)I(q),Y+=`/${q}`;else throw Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let W=await this._fetch(this.apiUrl+Y,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(W,`delete ${Y}`,!0),W})}async indexDataset({datasetId:Q,datasetName:$,tag:Y}){let q=Q;if(!q&&!$)throw Error("Must provide either datasetName or datasetId");else if(q&&$)throw Error("Must provide either datasetName or datasetId, not both");else if(!q)q=(await this.readDataset({datasetName:$})).id;I(q);let Z=JSON.stringify({tag:Y});await(await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/datasets/${q}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Z});return await L(J,"index dataset"),J})).json()}async similarExamples(Q,$,Y,{filter:q}={}){let W={limit:Y,inputs:Q};if(q!==void 0)W.filter=q;I($);let Z=JSON.stringify(W);return(await(await this.caller.call(async()=>{let z=await this._fetch(`${this.apiUrl}/datasets/${$}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:Z});return await L(z,"fetch similar examples"),z})).json()).examples}async createExample(Q,$,Y){if(AW(Q)){if($!==void 0||Y!==void 0)throw Error("Cannot provide outputs or options when using ExampleCreate object")}let q=$?Y?.datasetId:Q.dataset_id,W=$?Y?.datasetName:Q.dataset_name;if(q===void 0&&W===void 0)throw Error("Must provide either datasetName or datasetId");else if(q!==void 0&&W!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(q===void 0)q=(await this.readDataset({datasetName:W})).id;let Z=($?Y?.createdAt:Q.created_at)||new Date,G;if(!AW(Q))G={inputs:Q,outputs:$,created_at:Z?.toISOString(),id:Y?.exampleId,metadata:Y?.metadata,split:Y?.split,source_run_id:Y?.sourceRunId,use_source_run_io:Y?.useSourceRunIO,use_source_run_attachments:Y?.useSourceRunAttachments,attachments:Y?.attachments};else G=Q;let J=await this._uploadExamplesMultipart(q,[G]);return await this.readExample(J.example_ids?.[0]??pQ())}async createExamples(Q){if(Array.isArray(Q)){if(Q.length===0)return[];let S=Q,H=S[0].dataset_id,R=S[0].dataset_name;if(H===void 0&&R===void 0)throw Error("Must provide either datasetName or datasetId");else if(H!==void 0&&R!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(H===void 0)H=(await this.readDataset({datasetName:R})).id;let T=await this._uploadExamplesMultipart(H,S);return await Promise.all(T.example_ids.map((b)=>this.readExample(b)))}let{inputs:$,outputs:Y,metadata:q,splits:W,sourceRunIds:Z,useSourceRunIOs:G,useSourceRunAttachments:J,attachments:z,exampleIds:K,datasetId:X,datasetName:U}=Q;if($===void 0)throw Error("Must provide inputs when using legacy parameters");let N=X,B=U;if(N===void 0&&B===void 0)throw Error("Must provide either datasetName or datasetId");else if(N!==void 0&&B!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(N===void 0)N=(await this.readDataset({datasetName:B})).id;let A=$.map((S,H)=>{return{dataset_id:N,inputs:S,outputs:Y?.[H],metadata:q?.[H],split:W?.[H],id:K?.[H],attachments:z?.[H],source_run_id:Z?.[H],use_source_run_io:G?.[H],use_source_run_attachments:J?.[H]}}),D=await this._uploadExamplesMultipart(N,A);return await Promise.all(D.example_ids.map((S)=>this.readExample(S)))}async createLLMExample(Q,$,Y){return this.createExample({input:Q},{output:$},Y)}async createChatExample(Q,$,Y){let q=Q.map((Z)=>{if(bY(Z))return hY(Z);return Z}),W=bY($)?hY($):$;return this.createExample({input:q},{output:W},Y)}async readExample(Q){I(Q);let $=`/examples/${Q}`,Y=await this._get($),{attachment_urls:q,...W}=Y,Z=W;if(q)Z.attachments=Object.entries(q).reduce((G,[J,z])=>{return G[J.slice(11)]={presigned_url:z.presigned_url,mime_type:z.mime_type},G},{});return Z}async*listExamples({datasetId:Q,datasetName:$,exampleIds:Y,asOf:q,splits:W,inlineS3Urls:Z,metadata:G,limit:J,offset:z,filter:K,includeAttachments:X}={}){let U;if(Q!==void 0&&$!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(Q!==void 0)U=Q;else if($!==void 0)U=(await this.readDataset({datasetName:$})).id;else throw Error("Must provide a datasetName or datasetId");let N=new URLSearchParams({dataset:U}),B=q?typeof q==="string"?q:q?.toISOString():void 0;if(B)N.append("as_of",B);let A=Z??!0;if(N.append("inline_s3_urls",A.toString()),Y!==void 0)for(let w of Y)N.append("id",w);if(W!==void 0)for(let w of W)N.append("splits",w);if(G!==void 0){let w=JSON.stringify(G);N.append("metadata",w)}if(J!==void 0)N.append("limit",J.toString());if(z!==void 0)N.append("offset",z.toString());if(K!==void 0)N.append("filter",K);if(X===!0)["attachment_urls","outputs","metadata"].forEach((w)=>N.append("select",w));let D=0;for await(let w of this._getPaginated("/examples",N)){for(let S of w){let{attachment_urls:H,...R}=S,T=R;if(H)T.attachments=Object.entries(H).reduce((y,[b,g])=>{return y[b.slice(11)]={presigned_url:g.presigned_url,mime_type:g.mime_type||void 0},y},{});yield T,D++}if(J!==void 0&&D>=J)break}}async deleteExample(Q){I(Q);let $=`/examples/${Q}`;await this.caller.call(async()=>{let Y=await this._fetch(this.apiUrl+$,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(Y,`delete ${$}`,!0),Y})}async deleteExamples(Q,$){if(Q.forEach((Y)=>I(Y)),$?.hardDelete){let Y=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}${Y}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:Q,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(q,"hard delete examples",!0),q})}else{let Y=new URLSearchParams;Q.forEach((q)=>Y.append("example_ids",q)),await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/examples?${Y.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(q,"delete examples",!0),q})}}async updateExample(Q,$){let Y;if($)Y=Q;else Y=Q.id;I(Y);let q;if($)q={id:Y,...$};else q=Q;let W;if(q.dataset_id!==void 0)W=q.dataset_id;else W=(await this.readExample(Y)).dataset_id;return this._updateExamplesMultipart(W,[q])}async updateExamples(Q){let $;if(Q[0].dataset_id===void 0)$=(await this.readExample(Q[0].id)).dataset_id;else $=Q[0].dataset_id;return this._updateExamplesMultipart($,Q)}async readDatasetVersion({datasetId:Q,datasetName:$,asOf:Y,tag:q}){let W;if(!Q)W=(await this.readDataset({datasetName:$})).id;else W=Q;if(I(W),Y&&q||!Y&&!q)throw Error("Exactly one of asOf and tag must be specified.");let Z=new URLSearchParams;if(Y!==void 0)Z.append("as_of",typeof Y==="string"?Y:Y.toISOString());if(q!==void 0)Z.append("tag",q);return await(await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/datasets/${W}/version?${Z.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(J,"read dataset version"),J})).json()}async listDatasetSplits({datasetId:Q,datasetName:$,asOf:Y}){let q;if(Q===void 0&&$===void 0)throw Error("Must provide dataset name or ID");else if(Q!==void 0&&$!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(Q===void 0)q=(await this.readDataset({datasetName:$})).id;else q=Q;I(q);let W=new URLSearchParams,Z=Y?typeof Y==="string"?Y:Y?.toISOString():void 0;if(Z)W.append("as_of",Z);return await this._get(`/datasets/${q}/splits`,W)}async updateDatasetSplits({datasetId:Q,datasetName:$,splitName:Y,exampleIds:q,remove:W=!1}){let Z;if(Q===void 0&&$===void 0)throw Error("Must provide dataset name or ID");else if(Q!==void 0&&$!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(Q===void 0)Z=(await this.readDataset({datasetName:$})).id;else Z=Q;I(Z);let G={split_name:Y,examples:q.map((z)=>{return I(z),z}),remove:W},J=JSON.stringify(G);await this.caller.call(async()=>{let z=await this._fetch(`${this.apiUrl}/datasets/${Z}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:J});return await L(z,"update dataset splits",!0),z})}async createFeedback(Q,$,{score:Y,value:q,correction:W,comment:Z,sourceInfo:G,feedbackSourceType:J="api",sourceRunId:z,feedbackId:K,feedbackConfig:X,projectId:U,comparativeExperimentId:N,sessionId:B,startTime:A}){if(!Q&&!U)throw Error("One of runId or projectId must be provided");if(Q&&U)throw Error("Only one of runId or projectId can be provided");let D={type:J??"api",metadata:G??{}};if(z!==void 0&&D?.metadata!==void 0&&!D.metadata.__run)D.metadata.__run={run_id:z};if(D?.metadata!==void 0&&D.metadata.__run?.run_id!==void 0)I(D.metadata.__run.run_id);let w={id:K??pQ(),run_id:Q,key:$,score:FW(Y),value:q,correction:W,comment:Z,feedback_source:D,comparative_experiment_id:N,feedbackConfig:X,session_id:B??U,start_time:A},S=JSON.stringify(w),H=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let R=await this._fetch(H,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:S});return await L(R,"create feedback",!0),R}),w}async updateFeedback(Q,{score:$,value:Y,correction:q,comment:W}){let Z={};if($!==void 0&&$!==null)Z.score=FW($);if(Y!==void 0&&Y!==null)Z.value=Y;if(q!==void 0&&q!==null)Z.correction=q;if(W!==void 0&&W!==null)Z.comment=W;I(Q);let G=JSON.stringify(Z);await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/feedback/${Q}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:G});return await L(J,"update feedback",!0),J})}async readFeedback(Q){I(Q);let $=`/feedback/${Q}`;return await this._get($)}async deleteFeedback(Q){I(Q);let $=`/feedback/${Q}`;await this.caller.call(async()=>{let Y=await this._fetch(this.apiUrl+$,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(Y,`delete ${$}`,!0),Y})}async*listFeedback({runIds:Q,feedbackKeys:$,feedbackSourceTypes:Y}={}){let q=new URLSearchParams;if(Q)for(let W of Q)I(W),q.append("run",W);if($)for(let W of $)q.append("key",W);if(Y)for(let W of Y)q.append("source",W);for await(let W of this._getPaginated("/feedback",q))yield*W}async createPresignedFeedbackToken(Q,$,{expiration:Y,feedbackConfig:q}={}){let W={run_id:Q,feedback_key:$,feedback_config:q};if(Y){if(typeof Y==="string")W.expires_at=Y;else if(Y?.hours||Y?.minutes||Y?.days)W.expires_in=Y}else W.expires_in={hours:3};let Z=JSON.stringify(W);return await(await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Z});return await L(J,"create presigned feedback token"),J})).json()}async createComparativeExperiment({name:Q,experimentIds:$,referenceDatasetId:Y,createdAt:q,description:W,metadata:Z,id:G}){if($.length===0)throw Error("At least one experiment is required");if(!Y)Y=(await this.readProject({projectId:$[0]})).reference_dataset_id;if(!Y==null)throw Error("A reference dataset is required");let J={id:G,name:Q,experiment_ids:$,reference_dataset_id:Y,description:W,created_at:(q??new Date)?.toISOString(),extra:{}};if(Z)J.extra.metadata=Z;let z=JSON.stringify(J);return(await this.caller.call(async()=>{let X=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:z});return await L(X,"create comparative experiment"),X})).json()}async*listPresignedFeedbackTokens(Q){I(Q);let $=new URLSearchParams({run_id:Q});for await(let Y of this._getPaginated("/feedback/tokens",$))yield*Y}_selectEvalResults(Q){let $;if("results"in Q)$=Q.results;else if(Array.isArray(Q))$=Q;else $=[Q];return $}async _logEvaluationFeedback(Q,$,Y){let q=this._selectEvalResults(Q),W=[];for(let Z of q){let G=Y||{};if(Z.evaluatorInfo)G={...Z.evaluatorInfo,...G};let J=null;if(Z.targetRunId)J=Z.targetRunId;else if($)J=$.id;W.push(await this.createFeedback(J,Z.key,{score:Z.score,value:Z.value,comment:Z.comment,correction:Z.correction,sourceInfo:G,sourceRunId:Z.sourceRunId,feedbackConfig:Z.feedbackConfig,feedbackSourceType:"model",sessionId:$?.session_id,startTime:$?.start_time}))}return[q,W]}async logEvaluationFeedback(Q,$,Y){let[q]=await this._logEvaluationFeedback(Q,$,Y);return q}async createFeedbackConfig(Q){let{feedbackKey:$,feedbackConfig:Y,isLowerScoreBetter:q=!1}=Q,W={feedback_key:$,feedback_config:Y,is_lower_score_better:q};return(await this.caller.call(async()=>{let G=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(W)});return await L(G,"create feedback config"),G})).json()}async*listFeedbackConfigs(Q={}){let{feedbackKeys:$,nameContains:Y,limit:q}=Q,W=new URLSearchParams;if($)$.forEach((G)=>{W.append("key",G)});if(Y)W.append("name_contains",Y);W.append("limit",(q!==void 0?Math.min(q,100):100).toString());let Z=0;for await(let G of this._getPaginated("/feedback-configs",W))if(yield*G,Z+=G.length,q!==void 0&&Z>=q)break}async updateFeedbackConfig(Q,$={}){let{feedbackConfig:Y,isLowerScoreBetter:q}=$,W={feedback_key:Q};if(Y!==void 0)W.feedback_config=Y;if(q!==void 0)W.is_lower_score_better=q;return(await this.caller.call(async()=>{let G=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(W)});return await L(G,"update feedback config"),G})).json()}async deleteFeedbackConfig(Q){let $=new URLSearchParams({feedback_key:Q});await this.caller.call(async()=>{let Y=await this._fetch(`${this.apiUrl}/feedback-configs?${$}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(Y,"delete feedback config",!0),Y})}async*listAnnotationQueues(Q={}){let{queueIds:$,name:Y,nameContains:q,limit:W}=Q,Z=new URLSearchParams;if($)$.forEach((J,z)=>{I(J,`queueIds[${z}]`),Z.append("ids",J)});if(Y)Z.append("name",Y);if(q)Z.append("name_contains",q);Z.append("limit",(W!==void 0?Math.min(W,100):100).toString());let G=0;for await(let J of this._getPaginated("/annotation-queues",Z))if(yield*J,G++,W!==void 0&&G>=W)break}async createAnnotationQueue(Q){let{name:$,description:Y,queueId:q,rubricInstructions:W,rubricItems:Z}=Q,G={name:$,description:Y,id:q||pQ(),rubric_instructions:W,rubric_items:Z},J=JSON.stringify(Object.fromEntries(Object.entries(G).filter(([K,X])=>X!==void 0)));return(await this.caller.call(async()=>{let K=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:J});return await L(K,"create annotation queue"),K})).json()}async readAnnotationQueue(Q){return(await this.caller.call(async()=>{let Y=await this._fetch(`${this.apiUrl}/annotation-queues/${I(Q,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(Y,"read annotation queue"),Y})).json()}async updateAnnotationQueue(Q,$){let{name:Y,description:q,rubricInstructions:W,rubricItems:Z}=$,G={};if(Y!==void 0)G.name=Y;if(q!==void 0)G.description=q;if(W!==void 0)G.rubric_instructions=W;if(Z!==void 0)G.rubric_items=Z;let J=JSON.stringify(G);await this.caller.call(async()=>{let z=await this._fetch(`${this.apiUrl}/annotation-queues/${I(Q,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:J});return await L(z,"update annotation queue",!0),z})}async deleteAnnotationQueue(Q){await this.caller.call(async()=>{let $=await this._fetch(`${this.apiUrl}/annotation-queues/${I(Q,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L($,"delete annotation queue",!0),$})}async addRunsToAnnotationQueue(Q,$){let Y=JSON.stringify($.map((q,W)=>I(q,`runIds[${W}]`).toString()));await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/annotation-queues/${I(Q,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Y});return await L(q,"add runs to annotation queue",!0),q})}async getRunFromAnnotationQueue(Q,$){let Y=`/annotation-queues/${I(Q,"queueId")}/run`;return(await this.caller.call(async()=>{let W=await this._fetch(`${this.apiUrl}${Y}/${$}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(W,"get run from annotation queue"),W})).json()}async deleteRunFromAnnotationQueue(Q,$){await this.caller.call(async()=>{let Y=await this._fetch(`${this.apiUrl}/annotation-queues/${I(Q,"queueId")}/runs/${I($,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(Y,"delete run from annotation queue",!0),Y})}async getSizeFromAnnotationQueue(Q){return(await this.caller.call(async()=>{let Y=await this._fetch(`${this.apiUrl}/annotation-queues/${I(Q,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(Y,"get size from annotation queue"),Y})).json()}async _currentTenantIsOwner(Q){let $=await this._getSettings();return Q=="-"||$.tenant_handle===Q}async _ownerConflictError(Q,$){let Y=await this._getSettings();return Error(`Cannot ${Q} for another tenant.
|
|
41
|
+
|
|
42
|
+
Current tenant: ${Y.tenant_handle}
|
|
43
|
+
|
|
44
|
+
Requested tenant: ${$}`)}async _getLatestCommitHash(Q){let Y=await(await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/commits/${Q}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(q,"get latest commit hash"),q})).json();if(Y.commits.length===0)return;return Y.commits[0].commit_hash}async _likeOrUnlikePrompt(Q,$){let[Y,q,W]=bQ(Q),Z=JSON.stringify({like:$});return(await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/likes/${Y}/${q}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Z});return await L(J,`${$?"like":"unlike"} prompt`),J})).json()}async _getPromptUrl(Q){let[$,Y,q]=bQ(Q);if(!await this._currentTenantIsOwner($))if(q!=="latest")return`${this.getHostUrl()}/hub/${$}/${Y}/${q.substring(0,8)}`;else return`${this.getHostUrl()}/hub/${$}/${Y}`;else{let W=await this._getSettings();if(q!=="latest")return`${this.getHostUrl()}/prompts/${Y}/${q.substring(0,8)}?organizationId=${W.id}`;else return`${this.getHostUrl()}/prompts/${Y}?organizationId=${W.id}`}}async promptExists(Q){return!!await this.getPrompt(Q)}async likePrompt(Q){return this._likeOrUnlikePrompt(Q,!0)}async unlikePrompt(Q){return this._likeOrUnlikePrompt(Q,!1)}async*listCommits(Q){for await(let $ of this._getPaginated(`/commits/${Q}/`,new URLSearchParams,(Y)=>Y.commits))yield*$}async*listPrompts(Q){let $=new URLSearchParams;if($.append("sort_field",Q?.sortField??"updated_at"),$.append("sort_direction","desc"),$.append("is_archived",(!!Q?.isArchived).toString()),Q?.isPublic!==void 0)$.append("is_public",Q.isPublic.toString());if(Q?.query)$.append("query",Q.query);for await(let Y of this._getPaginated("/repos",$,(q)=>q.repos))yield*Y}async getPrompt(Q){let[$,Y,q]=bQ(Q),Z=await(await this.caller.call(async()=>{let G=await this._fetch(`${this.apiUrl}/repos/${$}/${Y}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(G?.status===404)return null;return await L(G,"get prompt"),G}))?.json();if(Z?.repo)return Z.repo;else return null}async createPrompt(Q,$){let Y=await this._getSettings();if($?.isPublic&&!Y.tenant_handle)throw Error(`Cannot create a public prompt without first
|
|
45
|
+
|
|
46
|
+
creating a LangChain Hub handle.
|
|
47
|
+
You can add a handle by creating a public prompt at:
|
|
48
|
+
|
|
49
|
+
https://smith.langchain.com/prompts`);let[q,W,Z]=bQ(Q);if(!await this._currentTenantIsOwner(q))throw await this._ownerConflictError("create a prompt",q);let G={repo_handle:W,...$?.description&&{description:$.description},...$?.readme&&{readme:$.readme},...$?.tags&&{tags:$.tags},is_public:!!$?.isPublic},J=JSON.stringify(G),z=await this.caller.call(async()=>{let X=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:J});return await L(X,"create prompt"),X}),{repo:K}=await z.json();return K}async createCommit(Q,$,Y){if(!await this.promptExists(Q))throw Error("Prompt does not exist, you must create it first.");let[q,W,Z]=bQ(Q),G=Y?.parentCommitHash==="latest"||!Y?.parentCommitHash?await this._getLatestCommitHash(`${q}/${W}`):Y?.parentCommitHash,J={manifest:JSON.parse(JSON.stringify($)),parent_commit:G},z=JSON.stringify(J),X=await(await this.caller.call(async()=>{let U=await this._fetch(`${this.apiUrl}/commits/${q}/${W}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:z});return await L(U,"create commit"),U})).json();return this._getPromptUrl(`${q}/${W}${X.commit_hash?`:${X.commit_hash}`:""}`)}async updateExamplesMultipart(Q,$=[]){return this._updateExamplesMultipart(Q,$)}async _updateExamplesMultipart(Q,$=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let Y=new FormData;for(let Z of $){let G=Z.id,J={...Z.metadata&&{metadata:Z.metadata},...Z.split&&{split:Z.split}},z=JQ(J,`Serializing body for example with id: ${G}`),K=new Blob([z],{type:"application/json"});if(Y.append(G,K),Z.inputs){let X=JQ(Z.inputs,`Serializing inputs for example with id: ${G}`),U=new Blob([X],{type:"application/json"});Y.append(`${G}.inputs`,U)}if(Z.outputs){let X=JQ(Z.outputs,`Serializing outputs whle updating example with id: ${G}`),U=new Blob([X],{type:"application/json"});Y.append(`${G}.outputs`,U)}if(Z.attachments)for(let[X,U]of Object.entries(Z.attachments)){let N,B;if(Array.isArray(U))[N,B]=U;else N=U.mimeType,B=U.data;let A=new Blob([B],{type:`${N}; length=${B.byteLength}`});Y.append(`${G}.attachment.${X}`,A)}if(Z.attachments_operations){let X=JQ(Z.attachments_operations,`Serializing attachments while updating example with id: ${G}`),U=new Blob([X],{type:"application/json"});Y.append(`${G}.attachments_operations`,U)}}let q=Q??$[0]?.dataset_id;return(await this.caller.call(async()=>{let Z=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${q}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Y});return await L(Z,"update examples"),Z})).json()}async uploadExamplesMultipart(Q,$=[]){return this._uploadExamplesMultipart(Q,$)}async _uploadExamplesMultipart(Q,$=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let Y=new FormData;for(let W of $){let Z=(W.id??pQ()).toString(),G={created_at:W.created_at,...W.metadata&&{metadata:W.metadata},...W.split&&{split:W.split},...W.source_run_id&&{source_run_id:W.source_run_id},...W.use_source_run_io&&{use_source_run_io:W.use_source_run_io},...W.use_source_run_attachments&&{use_source_run_attachments:W.use_source_run_attachments}},J=JQ(G,`Serializing body for uploaded example with id: ${Z}`),z=new Blob([J],{type:"application/json"});if(Y.append(Z,z),W.inputs){let K=JQ(W.inputs,`Serializing inputs for uploaded example with id: ${Z}`),X=new Blob([K],{type:"application/json"});Y.append(`${Z}.inputs`,X)}if(W.outputs){let K=JQ(W.outputs,`Serializing outputs for uploaded example with id: ${Z}`),X=new Blob([K],{type:"application/json"});Y.append(`${Z}.outputs`,X)}if(W.attachments)for(let[K,X]of Object.entries(W.attachments)){let U,N;if(Array.isArray(X))[U,N]=X;else U=X.mimeType,N=X.data;let B=new Blob([N],{type:`${U}; length=${N.byteLength}`});Y.append(`${Z}.attachment.${K}`,B)}}return(await this.caller.call(async()=>{let W=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${Q}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Y});return await L(W,"upload examples"),W})).json()}async updatePrompt(Q,$){if(!await this.promptExists(Q))throw Error("Prompt does not exist, you must create it first.");let[Y,q]=bQ(Q);if(!await this._currentTenantIsOwner(Y))throw await this._ownerConflictError("update a prompt",Y);let W={};if($?.description!==void 0)W.description=$.description;if($?.readme!==void 0)W.readme=$.readme;if($?.tags!==void 0)W.tags=$.tags;if($?.isPublic!==void 0)W.is_public=$.isPublic;if($?.isArchived!==void 0)W.is_archived=$.isArchived;if(Object.keys(W).length===0)throw Error("No valid update options provided");let Z=JSON.stringify(W);return(await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/repos/${Y}/${q}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Z});return await L(J,"update prompt"),J})).json()}async deletePrompt(Q){if(!await this.promptExists(Q))throw Error("Prompt does not exist, you must create it first.");let[$,Y,q]=bQ(Q);if(!await this._currentTenantIsOwner($))throw await this._ownerConflictError("delete a prompt",$);return(await this.caller.call(async()=>{let Z=await this._fetch(`${this.apiUrl}/repos/${$}/${Y}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(Z,"delete prompt"),Z})).json()}_getPromptCacheKey(Q,$){return`${Q}${$?":with_model":""}`}async _fetchPromptFromApi(Q,$){let[Y,q,W]=bQ(Q),G=await(await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/commits/${Y}/${q}/${W}${$?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(J,"pull prompt commit"),J})).json();return{owner:Y,repo:q,commit_hash:G.commit_hash,manifest:G.manifest,examples:G.examples}}async pullPromptCommit(Q,$){let Y=this._fetchPromptFromApi.bind(this,Q,$);if(!$?.skipCache&&this._promptCache){let q=this._getPromptCacheKey(Q,$?.includeModel),W=this._promptCache.get(q,Y);if(W)return W;let Z=await Y();return this._promptCache.set(q,Z,Y),Z}return this._fetchPromptFromApi(Q,$)}async _pullPrompt(Q,$){let Y=await this.pullPromptCommit(Q,{includeModel:$?.includeModel,skipCache:$?.skipCache});return JSON.stringify(Y.manifest)}async pushPrompt(Q,$){if(await this.promptExists(Q)){if($&&Object.keys($).some((q)=>q!=="object"))await this.updatePrompt(Q,{description:$?.description,readme:$?.readme,tags:$?.tags,isPublic:$?.isPublic})}else await this.createPrompt(Q,{description:$?.description,readme:$?.readme,tags:$?.tags,isPublic:$?.isPublic});if(!$?.object)return await this._getPromptUrl(Q);return await this.createCommit(Q,$?.object,{parentCommitHash:$?.parentCommitHash})}async clonePublicDataset(Q,$={}){let{sourceApiUrl:Y=this.apiUrl,datasetName:q}=$,[W,Z]=this.parseTokenOrUrl(Q,Y),G=new dQ({apiUrl:W,apiKey:"placeholder"}),J=await G.readSharedDataset(Z),z=q||J.name;try{if(await this.hasDataset({datasetId:z})){console.log(`Dataset ${z} already exists in your tenant. Skipping.`);return}}catch(U){}let K=await G.listSharedExamples(Z),X=await this.createDataset(z,{description:J.description,dataType:J.data_type||"kv",inputsSchema:J.inputs_schema_definition??void 0,outputsSchema:J.outputs_schema_definition??void 0});try{await this.createExamples({inputs:K.map((U)=>U.inputs),outputs:K.flatMap((U)=>U.outputs?[U.outputs]:[]),datasetId:X.id})}catch(U){throw console.error(`An error occurred while creating dataset ${z}. You should delete it manually.`),U}}parseTokenOrUrl(Q,$,Y=2,q="dataset"){try{return I(Q),[$,Q]}catch(W){}try{let Z=new URL(Q).pathname.split("/").filter((G)=>G!=="");if(Z.length>=Y){let G=Z[Z.length-Y];return[$,G]}else throw Error(`Invalid public ${q} URL: ${Q}`)}catch(W){throw Error(`Invalid public ${q} URL or token: ${Q}`)}}cleanup(){if(this._promptCache)this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();if(await new Promise((Q)=>setTimeout(Q,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:Q})=>Q),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0)await qW()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function AW(Q){return"dataset_id"in Q||"dataset_name"in Q}var wW=(Q)=>{if(Q!==void 0)return Q;return!!["TRACING_V2","TRACING"].find((Y)=>c(Y)==="true")};var xQ=Symbol.for("lc:context_variables");var B$=Symbol.for("langsmith:replica_trace_roots");function pY(Q,$){if(xQ in Q)return Q[xQ][$];return}function OW(Q,$,Y){let q=xQ in Q?Q[xQ]:{};q[$]=Y,Q[xQ]=q}Q0();var M0=36,RG="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function EW(Q){let Y=Object.keys(Q).sort().map((q)=>`${q}:${Q[q]??""}`).join("|");return PW(Y,RG)}function MG(Q){return Q.replace(/[-:.]/g,"")}function SW(Q,$=1){let Y=$.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(Q).toISOString().slice(0,-1)}${Y}Z`}function uY(Q,$,Y=1){let q=SW(Q,Y);return{dottedOrder:MG(q)+$,microsecondPrecisionDatestring:q}}var _G=new Set(["projectName","updates","reroot"]);function IG(Q){let $={};for(let Y of Object.keys(Q))if(_G.has(Y))$[Y]=Q[Y];return $}class F${constructor(Q,$,Y,q){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=Q,this.tags=$,this.project_name=Y,this.replicas=q}static fromHeader(Q){let $=Q.split(","),Y={},q=[],W,Z;for(let G of $){let[J,z]=G.split("="),K=decodeURIComponent(z);if(J==="langsmith-metadata")Y=JSON.parse(K);else if(J==="langsmith-tags")q=K.split(",");else if(J==="langsmith-project")W=K;else if(J==="langsmith-replicas")Z=JSON.parse(K).map((U)=>{if(Array.isArray(U))return U;return IG(U)})}return new F$(Y,q,W,Z)}toHeader(){let Q=[];if(this.metadata&&Object.keys(this.metadata).length>0)Q.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`);if(this.tags&&this.tags.length>0)Q.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`);if(this.project_name)Q.push(`langsmith-project=${encodeURIComponent(this.project_name)}`);return Q.join(",")}}class i{constructor(Q){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),TW(Q)){Object.assign(this,{...Q});return}let $=i.getDefaultConfig(),{metadata:Y,...q}=Q,W=q.client??i.getSharedClient(),Z={...Y,...q?.extra?.metadata};if(q.extra={...q.extra,metadata:Z},"id"in q&&q.id==null)delete q.id;if(Object.assign(this,{...$,...q,client:W}),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order)this._serialized_start_time=SW(this.start_time,this.execution_order);if(!this.id)this.id=$$(this._serialized_start_time??this.start_time);if(!this.trace_id)if(this.parent_run)this.trace_id=this.parent_run.trace_id??this.id;else this.trace_id=this.id;if(this.replicas=CG(this.replicas),!this.dotted_order){let{dottedOrder:G}=uY(this.start_time,this.id,this.execution_order);if(this.parent_run)this.dotted_order=this.parent_run.dotted_order+"."+G;else this.dotted_order=G}}set metadata(Q){this.extra={...this.extra,metadata:{...this.extra?.metadata,...Q}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let Q=Date.now();return{run_type:"chain",project_name:T0(),child_runs:[],api_url:VQ("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:VQ("LANGCHAIN_API_KEY"),caller_options:{},start_time:Q,serialized:{},inputs:{},extra:{}}}static getSharedClient(){if(!i.sharedClient)i.sharedClient=new dQ;return i.sharedClient}createChild(Q){let $=this.child_execution_order+1,Y=this.replicas?.map((K)=>{let{reroot:X,...U}=K;return U}),q=Q.replicas??Y,W=new i({...Q,parent_run:this,project_name:this.project_name,replicas:q,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:$,child_execution_order:$});if(xQ in this)W[xQ]=this[xQ];let Z=Symbol.for("lc:child_config"),G=Q.extra?.[Z]??this.extra[Z];if(jG(G)){let K={...G},X=xG(K.callbacks)?K.callbacks.copy?.():void 0;if(X)Object.assign(X,{_parentRunId:W.id}),X.handlers?.find(RW)?.updateFromRunTree?.(W),K.callbacks=X;W.extra[Z]=K}let J=new Set,z=this;while(z!=null&&!J.has(z.id))J.add(z.id),z.child_execution_order=Math.max(z.child_execution_order,$),z=z.parent_run;return this.child_runs.push(W),W}async end(Q,$,Y=Date.now(),q){if(this.outputs=this.outputs??Q,this.error=this.error??$,this.end_time=this.end_time??Y,q&&Object.keys(q).length>0)this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...q}}:{metadata:q}}_convertToCreate(Q,$,Y=!0){let q=Q.extra??{};if(q?.runtime?.library===void 0){if(!q.runtime)q.runtime={};if($){for(let[G,J]of Object.entries($))if(!q.runtime[G])q.runtime[G]=J}}let W,Z;if(!Y)W=Q.child_runs.map((G)=>this._convertToCreate(G,$,Y)),Z=void 0;else Z=Q.parent_run?.id??Q.parent_run_id,W=[];return{id:Q.id,name:Q.name,start_time:Q._serialized_start_time??Q.start_time,end_time:Q.end_time,run_type:Q.run_type,reference_example_id:Q.reference_example_id,extra:q,serialized:Q.serialized,error:Q.error,inputs:Q.inputs,outputs:Q.outputs,session_name:Q.project_name,child_runs:W,parent_run_id:Z,trace_id:Q.trace_id,dotted_order:Q.dotted_order,tags:Q.tags,attachments:Q.attachments,events:Q.events}}_sliceParentId(Q,$){if($.dotted_order){let Y=$.dotted_order.split("."),q=null;for(let W=0;W<Y.length;W++)if(Y[W].slice(-M0)===Q){q=W;break}if(q!==null){let W=Y.slice(q+1);if($.dotted_order=W.join("."),W.length>0)$.trace_id=W[0].slice(-M0);else $.trace_id=$.id}}if($.parent_run_id===Q)$.parent_run_id=void 0}_setReplicaTraceRoot(Q,$){let Y=pY(this,B$)??{};Y[Q]=$,OW(this,B$,Y);for(let q of this.child_runs)q._setReplicaTraceRoot(Q,$)}_remapForProject(Q){let{projectName:$,runtimeEnv:Y,excludeChildRuns:q=!0,reroot:W=!1,distributedParentId:Z,apiUrl:G,apiKey:J,workspaceId:z}=Q,K=this._convertToCreate(this,Y,q);if($===this.project_name)return{...K,session_name:$};if(W){if(Z)this._sliceParentId(Z,K);else if(K.parent_run_id=void 0,K.dotted_order){let S=K.dotted_order.split(".");if(S.length>0)K.dotted_order=S[S.length-1],K.trace_id=K.id}let w=EW({projectName:$,apiUrl:G,apiKey:J,workspaceId:z});this._setReplicaTraceRoot(w,K.id)}let X;if(!W){let w=pY(this,B$)??{},S=EW({projectName:$,apiUrl:G,apiKey:J,workspaceId:z});if(X=w[S],X){if(K.trace_id=X,K.dotted_order){let H=K.dotted_order.split("."),R=null;for(let T=0;T<H.length;T++)if(H[T].slice(-M0)===X){R=T;break}if(R!==null){let T=H.slice(R);K.dotted_order=T.join(".")}}}}let U=K.id,N=R0(U,$),B;if(K.trace_id)B=R0(K.trace_id,$);else B=N;let A;if(K.parent_run_id)A=R0(K.parent_run_id,$);let D;if(K.dotted_order)D=K.dotted_order.split(".").map((H)=>{let R=H.slice(-M0),T=R0(R,$);return H.slice(0,-M0)+T}).join(".");return{...K,id:N,trace_id:B,parent_run_id:A,dotted_order:D,session_name:$}}async postRun(Q=!0){if(this._awaitInputsOnPost)this.inputs=await this.inputs;try{let $=W$();if(this.replicas&&this.replicas.length>0)for(let{projectName:Y,apiKey:q,apiUrl:W,workspaceId:Z,reroot:G}of this.replicas){let J=this._remapForProject({projectName:Y??this.project_name,runtimeEnv:$,excludeChildRuns:!0,reroot:G,distributedParentId:this.distributedParentId,apiUrl:W,apiKey:q,workspaceId:Z});await this.client.createRun(J,{apiKey:q,apiUrl:W,workspaceId:Z})}else{let Y=this._convertToCreate(this,$,Q);await this.client.createRun(Y)}if(!Q){Y0("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let Y of this.child_runs)await Y.postRun(!1)}this.child_runs=[]}catch($){console.error(`Error in postRun for run ${this.id}:`,$)}}async patchRun(Q){if(this.replicas&&this.replicas.length>0)for(let{projectName:$,apiKey:Y,apiUrl:q,workspaceId:W,updates:Z,reroot:G}of this.replicas){let J=this._remapForProject({projectName:$??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:G,distributedParentId:this.distributedParentId,apiUrl:q,apiKey:Y,workspaceId:W}),z={id:J.id,name:J.name,run_type:J.run_type,start_time:J.start_time,outputs:J.outputs,error:J.error,parent_run_id:J.parent_run_id,session_name:J.session_name,reference_example_id:J.reference_example_id,end_time:J.end_time,dotted_order:J.dotted_order,trace_id:J.trace_id,events:J.events,tags:J.tags,extra:J.extra,attachments:this.attachments,...Z};if(!Q?.excludeInputs)z.inputs=J.inputs;await this.client.updateRun(J.id,z,{apiKey:Y,apiUrl:q,workspaceId:W})}else try{let $={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};if(!Q?.excludeInputs)$.inputs=this.inputs;await this.client.updateRun(this.id,$)}catch($){console.error(`Error in patchRun for run ${this.id}`,$)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(Q){if(!this.events)this.events=[];if(typeof Q==="string")this.events.push({name:"event",time:new Date().toISOString(),message:Q});else this.events.push({...Q,time:Q.time??new Date().toISOString()})}static fromRunnableConfig(Q,$){let Y=Q?.callbacks,q,W,Z,G=wW();if(Y){let z=Y?.getParentRunId?.()??"",K=Y?.handlers?.find((X)=>X?.name=="langchain_tracer");q=K?.getRun?.(z),W=K?.projectName,Z=K?.client,G=G||!!K}if(!q)return new i({...$,client:Z,tracingEnabled:G,project_name:W});return new i({name:q.name,id:q.id,trace_id:q.trace_id,dotted_order:q.dotted_order,client:Z,tracingEnabled:G,project_name:W,tags:[...new Set((q?.tags??[]).concat(Q?.tags??[]))],extra:{metadata:{...q?.extra?.metadata,...Q?.metadata}}}).createChild($)}static fromDottedOrder(Q){return this.fromHeaders({"langsmith-trace":Q})}static fromHeaders(Q,$){let Y="get"in Q&&typeof Q.get==="function"?{"langsmith-trace":Q.get("langsmith-trace"),baggage:Q.get("baggage")}:Q,q=Y["langsmith-trace"];if(!q||typeof q!=="string")return;let W=q.trim(),Z=W.split(".").map((K)=>{let[X,U]=K.split("Z");return{strTime:X,time:Date.parse(X+"Z"),uuid:U}}),G=Z[0].uuid,J={...$,name:$?.name??"parent",run_type:$?.run_type??"chain",start_time:$?.start_time??Date.now(),id:Z.at(-1)?.uuid,trace_id:G,dotted_order:W};if(Y.baggage&&typeof Y.baggage==="string"){let K=F$.fromHeader(Y.baggage);J.metadata=K.metadata,J.tags=K.tags,J.project_name=K.project_name,J.replicas=K.replicas}let z=new i(J);return z.distributedParentId=z.id,z}toHeaders(Q){let $={"langsmith-trace":this.dotted_order,baggage:new F$(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(Q)for(let[Y,q]of Object.entries($))Q.set(Y,q);return $}}Object.defineProperty(i,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function TW(Q){return Q!=null&&typeof Q.createChild==="function"&&typeof Q.postRun==="function"}function RW(Q){return typeof Q==="object"&&Q!=null&&typeof Q.name==="string"&&Q.name==="langchain_tracer"}function LW(Q){return Array.isArray(Q)&&Q.some(($)=>RW($))}function xG(Q){return typeof Q==="object"&&Q!=null&&Array.isArray(Q.handlers)}function jG(Q){let $=Q?.callbacks;return Q!=null&&typeof $==="object"&&(LW($?.handlers)||LW($))}function vG(){let Q=VQ("LANGSMITH_RUNS_ENDPOINTS");if(!Q)return[];try{let $=JSON.parse(Q);if(Array.isArray($)){let Y=[];for(let q of $){if(typeof q!=="object"||q===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof q}`);continue}if(typeof q.api_url!=="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof q.api_url}`);continue}if(typeof q.api_key!=="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof q.api_key}`);continue}Y.push({apiUrl:q.api_url.replace(/\/$/,""),apiKey:q.api_key})}return Y}else if(typeof $==="object"&&$!==null){yG($);let Y=[];for(let[q,W]of Object.entries($)){let Z=q.replace(/\/$/,"");if(typeof W==="string")Y.push({apiUrl:Z,apiKey:W});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${q}: expected string, got ${typeof W}`);continue}}return Y}else return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of "+`objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof $}`),[]}catch($){if(XW($))throw $;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of "+"objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function CG(Q){if(Q)return Q.map(($)=>{if(Array.isArray($))return{projectName:$[0],updates:$[1]};return $});return vG()}function yG(Q){if(Object.keys(Q).length>0&&c("ENDPOINT"))throw new gY}var YX=M({BaseTracer:()=>EQ,isBaseTracer:()=>W0}),kG=(Q)=>{if(!Q)return;return Q.events=Q.events??[],Q.child_runs=Q.child_runs??[],Q};function lY(Q,$){if(!Q)return;return new i({...Q,start_time:Q._serialized_start_time??Q.start_time,parent_run:lY($),child_runs:Q.child_runs.map((Y)=>lY(Y)).filter((Y)=>Y!==void 0),extra:{...Q.extra,runtime:BY()},tracingEnabled:!1})}function cY(Q,$){return Q&&!Array.isArray(Q)&&typeof Q==="object"?Q:{[$]:Q}}function W0(Q){return typeof Q._addRunToRunMap==="function"}var EQ=class extends $0{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(Q){super(...arguments)}copy(){return this}getRunById(Q){if(Q===void 0)return;return this.usesRunTreeMap?kG(this.runTreeMap.get(Q)):this.runMap.get(Q)}stringifyError(Q){if(Q instanceof Error)return Q.message+(Q?.stack?`
|
|
50
|
+
|
|
51
|
+
${Q.stack}`:"");if(typeof Q==="string")return Q;return`${Q}`}_addChildRun(Q,$){Q.child_runs.push($)}_addRunToRunMap(Q){let{dottedOrder:$,microsecondPrecisionDatestring:Y}=uY(new Date(Q.start_time).getTime(),Q.id,Q.execution_order),q={...Q},W=this.getRunById(q.parent_run_id);if(q.parent_run_id!==void 0)if(W){if(this._addChildRun(W,q),W.child_execution_order=Math.max(W.child_execution_order,q.child_execution_order),q.trace_id=W.trace_id,W.dotted_order!==void 0)q.dotted_order=[W.dotted_order,$].join("."),q._serialized_start_time=Y}else q.parent_run_id=void 0;else q.trace_id=q.id,q.dotted_order=$,q._serialized_start_time=Y;if(this.usesRunTreeMap){let Z=lY(q,W);if(Z!==void 0)this.runTreeMap.set(q.id,Z)}else this.runMap.set(q.id,q);return q}async _endTrace(Q){let $=Q.parent_run_id!==void 0&&this.getRunById(Q.parent_run_id);if($)$.child_execution_order=Math.max($.child_execution_order,Q.child_execution_order);else await this.persistRun(Q);if(await this.onRunUpdate?.(Q),this.usesRunTreeMap)this.runTreeMap.delete(Q.id);else this.runMap.delete(Q.id)}_getExecutionOrder(Q){let $=Q!==void 0&&this.getRunById(Q);if(!$)return 1;return $.child_execution_order+1}_createRunForLLMStart(Q,$,Y,q,W,Z,G,J){let z=this._getExecutionOrder(q),K=Date.now(),X=G?{...W,metadata:G}:W,U={id:Y,name:J??Q.id[Q.id.length-1],parent_run_id:q,start_time:K,serialized:Q,events:[{name:"start",time:new Date(K).toISOString()}],inputs:{prompts:$},execution_order:z,child_runs:[],child_execution_order:z,run_type:"llm",extra:X??{},tags:Z||[]};return this._addRunToRunMap(U)}async handleLLMStart(Q,$,Y,q,W,Z,G,J){let z=this.getRunById(Y)??this._createRunForLLMStart(Q,$,Y,q,W,Z,G,J);return await this.onRunCreate?.(z),await this.onLLMStart?.(z),z}_createRunForChatModelStart(Q,$,Y,q,W,Z,G,J){let z=this._getExecutionOrder(q),K=Date.now(),X=G?{...W,metadata:G}:W,U={id:Y,name:J??Q.id[Q.id.length-1],parent_run_id:q,start_time:K,serialized:Q,events:[{name:"start",time:new Date(K).toISOString()}],inputs:{messages:$},execution_order:z,child_runs:[],child_execution_order:z,run_type:"llm",extra:X??{},tags:Z||[]};return this._addRunToRunMap(U)}async handleChatModelStart(Q,$,Y,q,W,Z,G,J){let z=this.getRunById(Y)??this._createRunForChatModelStart(Q,$,Y,q,W,Z,G,J);return await this.onRunCreate?.(z),await this.onLLMStart?.(z),z}async handleLLMEnd(Q,$,Y,q,W){let Z=this.getRunById($);if(!Z||Z?.run_type!=="llm")throw Error("No LLM run to end.");return Z.end_time=Date.now(),Z.outputs=Q,Z.events.push({name:"end",time:new Date(Z.end_time).toISOString()}),Z.extra={...Z.extra,...W},await this.onLLMEnd?.(Z),await this._endTrace(Z),Z}async handleLLMError(Q,$,Y,q,W){let Z=this.getRunById($);if(!Z||Z?.run_type!=="llm")throw Error("No LLM run to end.");return Z.end_time=Date.now(),Z.error=this.stringifyError(Q),Z.events.push({name:"error",time:new Date(Z.end_time).toISOString()}),Z.extra={...Z.extra,...W},await this.onLLMError?.(Z),await this._endTrace(Z),Z}_createRunForChainStart(Q,$,Y,q,W,Z,G,J,z){let K=this._getExecutionOrder(q),X=Date.now(),U={id:Y,name:J??Q.id[Q.id.length-1],parent_run_id:q,start_time:X,serialized:Q,events:[{name:"start",time:new Date(X).toISOString()}],inputs:$,execution_order:K,child_execution_order:K,run_type:G??"chain",child_runs:[],extra:Z?{...z,metadata:Z}:{...z},tags:W||[]};return this._addRunToRunMap(U)}async handleChainStart(Q,$,Y,q,W,Z,G,J){let z=this.getRunById(Y)??this._createRunForChainStart(Q,$,Y,q,W,Z,G,J);return await this.onRunCreate?.(z),await this.onChainStart?.(z),z}async handleChainEnd(Q,$,Y,q,W){let Z=this.getRunById($);if(!Z)throw Error("No chain run to end.");if(Z.end_time=Date.now(),Z.outputs=cY(Q,"output"),Z.events.push({name:"end",time:new Date(Z.end_time).toISOString()}),W?.inputs!==void 0)Z.inputs=cY(W.inputs,"input");return await this.onChainEnd?.(Z),await this._endTrace(Z),Z}async handleChainError(Q,$,Y,q,W){let Z=this.getRunById($);if(!Z)throw Error("No chain run to end.");if(Z.end_time=Date.now(),Z.error=this.stringifyError(Q),Z.events.push({name:"error",time:new Date(Z.end_time).toISOString()}),W?.inputs!==void 0)Z.inputs=cY(W.inputs,"input");return await this.onChainError?.(Z),await this._endTrace(Z),Z}_createRunForToolStart(Q,$,Y,q,W,Z,G){let J=this._getExecutionOrder(q),z=Date.now(),K={id:Y,name:G??Q.id[Q.id.length-1],parent_run_id:q,start_time:z,serialized:Q,events:[{name:"start",time:new Date(z).toISOString()}],inputs:{input:$},execution_order:J,child_execution_order:J,run_type:"tool",child_runs:[],extra:Z?{metadata:Z}:{},tags:W||[]};return this._addRunToRunMap(K)}async handleToolStart(Q,$,Y,q,W,Z,G){let J=this.getRunById(Y)??this._createRunForToolStart(Q,$,Y,q,W,Z,G);return await this.onRunCreate?.(J),await this.onToolStart?.(J),J}async handleToolEnd(Q,$){let Y=this.getRunById($);if(!Y||Y?.run_type!=="tool")throw Error("No tool run to end");return Y.end_time=Date.now(),Y.outputs={output:Q},Y.events.push({name:"end",time:new Date(Y.end_time).toISOString()}),await this.onToolEnd?.(Y),await this._endTrace(Y),Y}async handleToolError(Q,$){let Y=this.getRunById($);if(!Y||Y?.run_type!=="tool")throw Error("No tool run to end");return Y.end_time=Date.now(),Y.error=this.stringifyError(Q),Y.events.push({name:"error",time:new Date(Y.end_time).toISOString()}),await this.onToolError?.(Y),await this._endTrace(Y),Y}async handleAgentAction(Q,$){let Y=this.getRunById($);if(!Y||Y?.run_type!=="chain")return;let q=Y;q.actions=q.actions||[],q.actions.push(Q),q.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:Q}}),await this.onAgentAction?.(Y)}async handleAgentEnd(Q,$){let Y=this.getRunById($);if(!Y||Y?.run_type!=="chain")return;Y.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:Q}}),await this.onAgentEnd?.(Y)}_createRunForRetrieverStart(Q,$,Y,q,W,Z,G){let J=this._getExecutionOrder(q),z=Date.now(),K={id:Y,name:G??Q.id[Q.id.length-1],parent_run_id:q,start_time:z,serialized:Q,events:[{name:"start",time:new Date(z).toISOString()}],inputs:{query:$},execution_order:J,child_execution_order:J,run_type:"retriever",child_runs:[],extra:Z?{metadata:Z}:{},tags:W||[]};return this._addRunToRunMap(K)}async handleRetrieverStart(Q,$,Y,q,W,Z,G){let J=this.getRunById(Y)??this._createRunForRetrieverStart(Q,$,Y,q,W,Z,G);return await this.onRunCreate?.(J),await this.onRetrieverStart?.(J),J}async handleRetrieverEnd(Q,$){let Y=this.getRunById($);if(!Y||Y?.run_type!=="retriever")throw Error("No retriever run to end");return Y.end_time=Date.now(),Y.outputs={documents:Q},Y.events.push({name:"end",time:new Date(Y.end_time).toISOString()}),await this.onRetrieverEnd?.(Y),await this._endTrace(Y),Y}async handleRetrieverError(Q,$){let Y=this.getRunById($);if(!Y||Y?.run_type!=="retriever")throw Error("No retriever run to end");return Y.end_time=Date.now(),Y.error=this.stringifyError(Q),Y.events.push({name:"error",time:new Date(Y.end_time).toISOString()}),await this.onRetrieverError?.(Y),await this._endTrace(Y),Y}async handleText(Q,$){let Y=this.getRunById($);if(!Y||Y?.run_type!=="chain")return;Y.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:Q}}),await this.onText?.(Y)}async handleLLMNewToken(Q,$,Y,q,W,Z){let G=this.getRunById(Y);if(!G||G?.run_type!=="llm")throw Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return G.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:Q,idx:$,chunk:Z?.chunk}}),await this.onLLMNewToken?.(G,Q,{chunk:Z?.chunk}),G}};var iY=rQ(bG(),1),JX=M({ConsoleCallbackHandler:()=>V$});function QQ(Q,$){return`${Q.open}${$}${Q.close}`}function AQ(Q,$){try{return JSON.stringify(Q,null,2)}catch{return $}}function MW(Q){if(typeof Q==="string")return Q.trim();if(Q===null||Q===void 0)return Q;return AQ(Q,Q.toString())}function uQ(Q){if(!Q.end_time)return"";let $=Q.end_time-Q.start_time;if($<1000)return`${$}ms`;return`${($/1000).toFixed(2)}s`}var{color:zQ}=iY.default,V$=class extends EQ{name="console_callback_handler";persistRun(Q){return Promise.resolve()}getParents(Q){let $=[],Y=Q;while(Y.parent_run_id){let q=this.runMap.get(Y.parent_run_id);if(q)$.push(q),Y=q;else break}return $}getBreadcrumbs(Q){let $=[...this.getParents(Q).reverse(),Q].map((Y,q,W)=>{let Z=`${Y.execution_order}:${Y.run_type}:${Y.name}`;return q===W.length-1?QQ(iY.default.bold,Z):Z}).join(" > ");return QQ(zQ.grey,$)}onChainStart(Q){let $=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.green,"[chain/start]")} [${$}] Entering Chain run with input: ${AQ(Q.inputs,"[inputs]")}`)}onChainEnd(Q){let $=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.cyan,"[chain/end]")} [${$}] [${uQ(Q)}] Exiting Chain run with output: ${AQ(Q.outputs,"[outputs]")}`)}onChainError(Q){let $=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.red,"[chain/error]")} [${$}] [${uQ(Q)}] Chain run errored with error: ${AQ(Q.error,"[error]")}`)}onLLMStart(Q){let $=this.getBreadcrumbs(Q),Y="prompts"in Q.inputs?{prompts:Q.inputs.prompts.map((q)=>q.trim())}:Q.inputs;console.log(`${QQ(zQ.green,"[llm/start]")} [${$}] Entering LLM run with input: ${AQ(Y,"[inputs]")}`)}onLLMEnd(Q){let $=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.cyan,"[llm/end]")} [${$}] [${uQ(Q)}] Exiting LLM run with output: ${AQ(Q.outputs,"[response]")}`)}onLLMError(Q){let $=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.red,"[llm/error]")} [${$}] [${uQ(Q)}] LLM run errored with error: ${AQ(Q.error,"[error]")}`)}onToolStart(Q){let $=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.green,"[tool/start]")} [${$}] Entering Tool run with input: "${MW(Q.inputs.input)}"`)}onToolEnd(Q){let $=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.cyan,"[tool/end]")} [${$}] [${uQ(Q)}] Exiting Tool run with output: "${MW(Q.outputs?.output)}"`)}onToolError(Q){let $=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.red,"[tool/error]")} [${$}] [${uQ(Q)}] Tool run errored with error: ${AQ(Q.error,"[error]")}`)}onRetrieverStart(Q){let $=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.green,"[retriever/start]")} [${$}] Entering Retriever run with input: ${AQ(Q.inputs,"[inputs]")}`)}onRetrieverEnd(Q){let $=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.cyan,"[retriever/end]")} [${$}] [${uQ(Q)}] Exiting Retriever run with output: ${AQ(Q.outputs,"[outputs]")}`)}onRetrieverError(Q){let $=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.red,"[retriever/error]")} [${$}] [${uQ(Q)}] Retriever run errored with error: ${AQ(Q.error,"[error]")}`)}onAgentAction(Q){let $=Q,Y=this.getBreadcrumbs(Q);console.log(`${QQ(zQ.blue,"[agent/action]")} [${Y}] Agent selected action: ${AQ($.actions[$.actions.length-1],"[action]")}`)}};var sY,A$=()=>{if(sY===void 0)sY=new dQ(OQ("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{});return sY};class _W{getStore(){return}run(Q,$){return $()}}var oY=Symbol.for("ls:tracing_async_local_storage"),hG=new _W;class IW{getInstance(){return globalThis[oY]??hG}initializeGlobalInstance(Q){if(globalThis[oY]===void 0)globalThis[oY]=Q}}var fG=new IW;function xW(Q=!1){let $=fG.getInstance().getStore();if(!Q&&$===void 0)throw Error(`Could not get the current run tree.
|
|
52
|
+
|
|
53
|
+
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return $}function H$(Q){return typeof Q==="function"&&"langsmith:traceable"in Q}var RX=M({LangChainTracer:()=>D$});function gG(Q){let $=void 0;for(let Y of Q)for(let q of Y)if(B0.isInstance(q.message)&&q.message.usage_metadata!==void 0)$=i0($,q.message.usage_metadata);return $}var D$=class Q extends EQ{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor($={}){super($);let{exampleId:Y,projectName:q,client:W,replicas:Z}=$;this.projectName=q??T0(),this.replicas=Z,this.exampleId=Y,this.client=W??A$();let G=Q.getTraceableRunTree();if(G)this.updateFromRunTree(G)}async persistRun($){}async onRunCreate($){if(!$.extra?.lc_defers_inputs)await this.getRunTreeWithTracingConfig($.id)?.postRun()}async onRunUpdate($){let Y=this.getRunTreeWithTracingConfig($.id);if($.extra?.lc_defers_inputs)await Y?.postRun();else await Y?.patchRun()}onLLMEnd($){let Y=$.outputs;if(Y?.generations){let q=gG(Y.generations);if(q!==void 0){$.extra=$.extra??{};let W=$.extra.metadata??{};W.usage_metadata=q,$.extra.metadata=W}}}getRun($){return this.runTreeMap.get($)}updateFromRunTree($){this.runTreeMap.set($.id,$);let Y=$,q=new Set;while(Y.parent_run){if(q.has(Y.id))break;if(q.add(Y.id),!Y.parent_run)break;Y=Y.parent_run}q.clear();let W=[Y];while(W.length>0){let Z=W.shift();if(!Z||q.has(Z.id))continue;if(q.add(Z.id),this.runTreeMap.set(Z.id,Z),Z.child_runs)W.push(...Z.child_runs)}this.client=$.client??this.client,this.replicas=$.replicas??this.replicas,this.projectName=$.project_name??this.projectName,this.exampleId=$.reference_example_id??this.exampleId}getRunTreeWithTracingConfig($){let Y=this.runTreeMap.get($);if(!Y)return;return new i({...Y,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return xW(!0)}catch{return}}};var jW=Symbol.for("ls:tracing_async_local_storage"),cQ=Symbol.for("lc:context_variables"),vW=(Q)=>{globalThis[jW]=Q},lQ=()=>{return globalThis[jW]};var w$=rQ(kY(),1),Z0;function mG(){return new("default"in w$.default?w$.default.default:w$.default)({autoStart:!0,concurrency:1})}function dG(){if(typeof Z0>"u")Z0=mG();return Z0}async function d(Q,$){if($===!0){let Y=lQ();if(Y!==void 0)await Y.run(void 0,async()=>Q());else await Q()}else Z0=dG(),Z0.add(async()=>{let Y=lQ();if(Y!==void 0)await Y.run(void 0,async()=>Q());else await Q()})}async function CW(){let Q=A$();await Promise.allSettled([typeof Z0<"u"?Z0.onIdle():Promise.resolve(),Q.awaitPendingTraceBatches()])}var yX=M({awaitAllCallbacks:()=>CW,consumeCallback:()=>d});var yW=(Q)=>{if(Q!==void 0)return Q;return!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(($)=>OQ($)==="true")};function tY(Q){let $=lQ();if($===void 0)return;return $.getStore()?.[cQ]?.[Q]}var pG=Symbol("lc:configure_hooks"),kW=()=>tY(pG)||[];Q0();var eX=M({BaseCallbackManager:()=>bW,BaseRunManager:()=>I0,CallbackManager:()=>LQ,CallbackManagerForChainRun:()=>fW,CallbackManagerForLLMRun:()=>nY,CallbackManagerForRetrieverRun:()=>hW,CallbackManagerForToolRun:()=>gW,ensureHandler:()=>w0,parseCallbackConfigArg:()=>_0});function _0(Q){if(!Q)return{};else if(Array.isArray(Q)||"name"in Q)return{callbacks:Q};else return Q}var bW=class{setHandler(Q){return this.setHandlers([Q])}},I0=class{constructor(Q,$,Y,q,W,Z,G,J){this.runId=Q,this.handlers=$,this.inheritableHandlers=Y,this.tags=q,this.inheritableTags=W,this.metadata=Z,this.inheritableMetadata=G,this._parentRunId=J}get parentRunId(){return this._parentRunId}async handleText(Q){await Promise.all(this.handlers.map(($)=>d(async()=>{try{await $.handleText?.(Q,this.runId,this._parentRunId,this.tags)}catch(Y){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleText: ${Y}`),$.raiseError)throw Y}},$.awaitHandlers)))}async handleCustomEvent(Q,$,Y,q,W){await Promise.all(this.handlers.map((Z)=>d(async()=>{try{await Z.handleCustomEvent?.(Q,$,this.runId,this.tags,this.metadata)}catch(G){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleCustomEvent: ${G}`),Z.raiseError)throw G}},Z.awaitHandlers)))}},hW=class extends I0{getChild(Q){let $=new LQ(this.runId);if($.setHandlers(this.inheritableHandlers),$.addTags(this.inheritableTags),$.addMetadata(this.inheritableMetadata),Q)$.addTags([Q],!1);return $}async handleRetrieverEnd(Q){await Promise.all(this.handlers.map(($)=>d(async()=>{if(!$.ignoreRetriever)try{await $.handleRetrieverEnd?.(Q,this.runId,this._parentRunId,this.tags)}catch(Y){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleRetriever`),$.raiseError)throw Y}},$.awaitHandlers)))}async handleRetrieverError(Q){await Promise.all(this.handlers.map(($)=>d(async()=>{if(!$.ignoreRetriever)try{await $.handleRetrieverError?.(Q,this.runId,this._parentRunId,this.tags)}catch(Y){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleRetrieverError: ${Y}`),$.raiseError)throw Q}},$.awaitHandlers)))}},nY=class extends I0{async handleLLMNewToken(Q,$,Y,q,W,Z){await Promise.all(this.handlers.map((G)=>d(async()=>{if(!G.ignoreLLM)try{await G.handleLLMNewToken?.(Q,$??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,Z)}catch(J){if((G.raiseError?console.error:console.warn)(`Error in handler ${G.constructor.name}, handleLLMNewToken: ${J}`),G.raiseError)throw J}},G.awaitHandlers)))}async handleLLMError(Q,$,Y,q,W){await Promise.all(this.handlers.map((Z)=>d(async()=>{if(!Z.ignoreLLM)try{await Z.handleLLMError?.(Q,this.runId,this._parentRunId,this.tags,W)}catch(G){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleLLMError: ${G}`),Z.raiseError)throw G}},Z.awaitHandlers)))}async handleLLMEnd(Q,$,Y,q,W){await Promise.all(this.handlers.map((Z)=>d(async()=>{if(!Z.ignoreLLM)try{await Z.handleLLMEnd?.(Q,this.runId,this._parentRunId,this.tags,W)}catch(G){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleLLMEnd: ${G}`),Z.raiseError)throw G}},Z.awaitHandlers)))}},fW=class extends I0{getChild(Q){let $=new LQ(this.runId);if($.setHandlers(this.inheritableHandlers),$.addTags(this.inheritableTags),$.addMetadata(this.inheritableMetadata),Q)$.addTags([Q],!1);return $}async handleChainError(Q,$,Y,q,W){await Promise.all(this.handlers.map((Z)=>d(async()=>{if(!Z.ignoreChain)try{await Z.handleChainError?.(Q,this.runId,this._parentRunId,this.tags,W)}catch(G){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleChainError: ${G}`),Z.raiseError)throw G}},Z.awaitHandlers)))}async handleChainEnd(Q,$,Y,q,W){await Promise.all(this.handlers.map((Z)=>d(async()=>{if(!Z.ignoreChain)try{await Z.handleChainEnd?.(Q,this.runId,this._parentRunId,this.tags,W)}catch(G){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleChainEnd: ${G}`),Z.raiseError)throw G}},Z.awaitHandlers)))}async handleAgentAction(Q){await Promise.all(this.handlers.map(($)=>d(async()=>{if(!$.ignoreAgent)try{await $.handleAgentAction?.(Q,this.runId,this._parentRunId,this.tags)}catch(Y){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleAgentAction: ${Y}`),$.raiseError)throw Y}},$.awaitHandlers)))}async handleAgentEnd(Q){await Promise.all(this.handlers.map(($)=>d(async()=>{if(!$.ignoreAgent)try{await $.handleAgentEnd?.(Q,this.runId,this._parentRunId,this.tags)}catch(Y){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleAgentEnd: ${Y}`),$.raiseError)throw Y}},$.awaitHandlers)))}},gW=class extends I0{getChild(Q){let $=new LQ(this.runId);if($.setHandlers(this.inheritableHandlers),$.addTags(this.inheritableTags),$.addMetadata(this.inheritableMetadata),Q)$.addTags([Q],!1);return $}async handleToolError(Q){await Promise.all(this.handlers.map(($)=>d(async()=>{if(!$.ignoreAgent)try{await $.handleToolError?.(Q,this.runId,this._parentRunId,this.tags)}catch(Y){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleToolError: ${Y}`),$.raiseError)throw Y}},$.awaitHandlers)))}async handleToolEvent(Q){await Promise.all(this.handlers.map(($)=>d(async()=>{if(!$.ignoreAgent)try{await $.handleToolEvent?.(Q,this.runId,this._parentRunId,this.tags)}catch(Y){if($.raiseError)throw Y}},$.awaitHandlers)))}async handleToolEnd(Q){await Promise.all(this.handlers.map(($)=>d(async()=>{if(!$.ignoreAgent)try{await $.handleToolEnd?.(Q,this.runId,this._parentRunId,this.tags)}catch(Y){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleToolEnd: ${Y}`),$.raiseError)throw Y}},$.awaitHandlers)))}},LQ=class Q extends bW{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor($,Y){super();this.handlers=Y?.handlers??this.handlers,this.inheritableHandlers=Y?.inheritableHandlers??this.inheritableHandlers,this.tags=Y?.tags??this.tags,this.inheritableTags=Y?.inheritableTags??this.inheritableTags,this.metadata=Y?.metadata??this.metadata,this.inheritableMetadata=Y?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=$}getParentRunId(){return this._parentRunId}async handleLLMStart($,Y,q=void 0,W=void 0,Z=void 0,G=void 0,J=void 0,z=void 0){return Promise.all(Y.map(async(K,X)=>{let U=X===0&&q?q:FQ();return await Promise.all(this.handlers.map((N)=>{if(N.ignoreLLM)return;if(W0(N))N._createRunForLLMStart($,[K],U,this._parentRunId,Z,this.tags,this.metadata,z);return d(async()=>{try{await N.handleLLMStart?.($,[K],U,this._parentRunId,Z,this.tags,this.metadata,z)}catch(B){if((N.raiseError?console.error:console.warn)(`Error in handler ${N.constructor.name}, handleLLMStart: ${B}`),N.raiseError)throw B}},N.awaitHandlers)})),new nY(U,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart($,Y,q=void 0,W=void 0,Z=void 0,G=void 0,J=void 0,z=void 0){return Promise.all(Y.map(async(K,X)=>{let U=X===0&&q?q:FQ();return await Promise.all(this.handlers.map((N)=>{if(N.ignoreLLM)return;if(W0(N))N._createRunForChatModelStart($,[K],U,this._parentRunId,Z,this.tags,this.metadata,z);return d(async()=>{try{if(N.handleChatModelStart)await N.handleChatModelStart?.($,[K],U,this._parentRunId,Z,this.tags,this.metadata,z);else if(N.handleLLMStart){let B=o0(K);await N.handleLLMStart?.($,[B],U,this._parentRunId,Z,this.tags,this.metadata,z)}}catch(B){if((N.raiseError?console.error:console.warn)(`Error in handler ${N.constructor.name}, handleLLMStart: ${B}`),N.raiseError)throw B}},N.awaitHandlers)})),new nY(U,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart($,Y,q=FQ(),W=void 0,Z=void 0,G=void 0,J=void 0,z=void 0,K=void 0){return await Promise.all(this.handlers.map((X)=>{if(X.ignoreChain)return;if(W0(X))X._createRunForChainStart($,Y,q,this._parentRunId,this.tags,this.metadata,W,J,K);return d(async()=>{try{await X.handleChainStart?.($,Y,q,this._parentRunId,this.tags,this.metadata,W,J,K)}catch(U){if((X.raiseError?console.error:console.warn)(`Error in handler ${X.constructor.name}, handleChainStart: ${U}`),X.raiseError)throw U}},X.awaitHandlers)})),new fW(q,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart($,Y,q=FQ(),W=void 0,Z=void 0,G=void 0,J=void 0,z=void 0){return await Promise.all(this.handlers.map((K)=>{if(K.ignoreAgent)return;if(W0(K))K._createRunForToolStart($,Y,q,this._parentRunId,this.tags,this.metadata,J);return d(async()=>{try{await K.handleToolStart?.($,Y,q,this._parentRunId,this.tags,this.metadata,J,z)}catch(X){if((K.raiseError?console.error:console.warn)(`Error in handler ${K.constructor.name}, handleToolStart: ${X}`),K.raiseError)throw X}},K.awaitHandlers)})),new gW(q,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart($,Y,q=FQ(),W=void 0,Z=void 0,G=void 0,J=void 0){return await Promise.all(this.handlers.map((z)=>{if(z.ignoreRetriever)return;if(W0(z))z._createRunForRetrieverStart($,Y,q,this._parentRunId,this.tags,this.metadata,J);return d(async()=>{try{await z.handleRetrieverStart?.($,Y,q,this._parentRunId,this.tags,this.metadata,J)}catch(K){if((z.raiseError?console.error:console.warn)(`Error in handler ${z.constructor.name}, handleRetrieverStart: ${K}`),z.raiseError)throw K}},z.awaitHandlers)})),new hW(q,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent($,Y,q,W,Z){await Promise.all(this.handlers.map((G)=>d(async()=>{if(!G.ignoreCustomEvent)try{await G.handleCustomEvent?.($,Y,q,this.tags,this.metadata)}catch(J){if((G.raiseError?console.error:console.warn)(`Error in handler ${G.constructor.name}, handleCustomEvent: ${J}`),G.raiseError)throw J}},G.awaitHandlers)))}addHandler($,Y=!0){if(this.handlers.push($),Y)this.inheritableHandlers.push($)}removeHandler($){this.handlers=this.handlers.filter((Y)=>Y!==$),this.inheritableHandlers=this.inheritableHandlers.filter((Y)=>Y!==$)}setHandlers($,Y=!0){this.handlers=[],this.inheritableHandlers=[];for(let q of $)this.addHandler(q,Y)}addTags($,Y=!0){if(this.removeTags($),this.tags.push(...$),Y)this.inheritableTags.push(...$)}removeTags($){this.tags=this.tags.filter((Y)=>!$.includes(Y)),this.inheritableTags=this.inheritableTags.filter((Y)=>!$.includes(Y))}addMetadata($,Y=!0){if(this.metadata={...this.metadata,...$},Y)this.inheritableMetadata={...this.inheritableMetadata,...$}}removeMetadata($){for(let Y of Object.keys($))delete this.metadata[Y],delete this.inheritableMetadata[Y]}copy($=[],Y=!0){let q=new Q(this._parentRunId);for(let W of this.handlers){let Z=this.inheritableHandlers.includes(W);q.addHandler(W,Z)}for(let W of this.tags){let Z=this.inheritableTags.includes(W);q.addTags([W],Z)}for(let W of Object.keys(this.metadata)){let Z=Object.keys(this.inheritableMetadata).includes(W);q.addMetadata({[W]:this.metadata[W]},Z)}for(let W of $){if(q.handlers.filter((Z)=>Z.name==="console_callback_handler").some((Z)=>Z.name===W.name))continue;q.addHandler(W,Y)}return q}static fromHandlers($){class Y extends $0{name=FQ();constructor(){super();Object.assign(this,$)}}let q=new this;return q.addHandler(new Y),q}static configure($,Y,q,W,Z,G,J){return this._configureSync($,Y,q,W,Z,G,J)}static _configureSync($,Y,q,W,Z,G,J){let z;if($||Y){if(Array.isArray($)||!$)z=new Q,z.setHandlers($?.map(w0)??[],!0);else z=$;z=z.copy(Array.isArray(Y)?Y.map(w0):Y?.handlers,!1)}let K=OQ("LANGCHAIN_VERBOSE")==="true"||J?.verbose,X=D$.getTraceableRunTree(),U=X?.tracingEnabled??yW();if(X?.tracingEnabled===!1&&z){let B=z.handlers.filter((A)=>A.name==="langchain_tracer");for(let A of B)z.removeHandler(A)}let N=U||(OQ("LANGCHAIN_TRACING")??!1);if(K||N){if(!z)z=new Q;if(K&&!z.handlers.some((B)=>B.name===V$.prototype.name)){let B=new V$;z.addHandler(B,!0)}if(N&&!z.handlers.some((B)=>B.name==="langchain_tracer")){if(U){let B=new D$;z.addHandler(B,!0)}}if(U){if(X&&z._parentRunId===void 0)z._parentRunId=X.id,z.handlers.find((B)=>B.name==="langchain_tracer")?.updateFromRunTree(X)}}for(let{contextVar:B,inheritable:A=!0,handlerClass:D,envVar:w}of kW()){let S=w&&OQ(w)==="true"&&D,H,R=B!==void 0?tY(B):void 0;if(R&&FY(R))H=R;else if(S)H=new D({});if(H!==void 0){if(!z)z=new Q;if(!z.handlers.some((T)=>T.name===H.name))z.addHandler(H,A)}}if(q||W){if(z)z.addTags(q??[]),z.addTags(W??[],!1)}if(Z||G){if(z)z.addMetadata(Z??{}),z.addMetadata(G??{},!1)}return z}};function w0(Q){if("name"in Q)return Q;return $0.fromMethods(Q)}var rY=class{getStore(){}run(Q,$){return $()}enterWith(Q){}},uG=new rY,mW=Symbol.for("lc:child_config"),cG=class{getInstance(){return lQ()??uG}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[mW]}runWithConfig(Q,$,Y){let q=LQ._configureSync(Q?.callbacks,void 0,Q?.tags,void 0,Q?.metadata),W=this.getInstance(),Z=W.getStore(),G=q?.getParentRunId(),J=q?.handlers?.find((K)=>K?.name==="langchain_tracer"),z;if(J&&G)z=J.getRunTreeWithTracingConfig(G);else if(!Y)z=new i({name:"<runnable_lambda>",tracingEnabled:!1});if(z)z.extra={...z.extra,[mW]:Q};if(Z!==void 0&&Z[cQ]!==void 0){if(z===void 0)z={};z[cQ]=Z[cQ]}return W.run(z,$)}initializeGlobalInstance(Q){if(lQ()===void 0)vW(Q)}},a=new cG;var A2=M({AsyncLocalStorageProviderSingleton:()=>a,MockAsyncLocalStorage:()=>rY,_CONTEXT_VARIABLES_KEY:()=>cQ});var O$=25;async function HQ(Q){return LQ._configureSync(Q?.callbacks,void 0,Q?.tags,void 0,Q?.metadata)}function x0(...Q){let $={};for(let Y of Q.filter((q)=>!!q))for(let q of Object.keys(Y))if(q==="metadata")$[q]={...$[q],...Y[q]};else if(q==="tags"){let W=$[q]??[];$[q]=[...new Set(W.concat(Y[q]??[]))]}else if(q==="configurable")$[q]={...$[q],...Y[q]};else if(q==="timeout"){if($.timeout===void 0)$.timeout=Y.timeout;else if(Y.timeout!==void 0)$.timeout=Math.min($.timeout,Y.timeout)}else if(q==="signal"){if($.signal===void 0)$.signal=Y.signal;else if(Y.signal!==void 0)if("any"in AbortSignal)$.signal=AbortSignal.any([$.signal,Y.signal]);else $.signal=Y.signal}else if(q==="callbacks"){let W=$.callbacks,Z=Y.callbacks;if(Array.isArray(Z))if(!W)$.callbacks=Z;else if(Array.isArray(W))$.callbacks=W.concat(Z);else{let G=W.copy();for(let J of Z)G.addHandler(w0(J),!0);$.callbacks=G}else if(Z)if(!W)$.callbacks=Z;else if(Array.isArray(W)){let G=Z.copy();for(let J of W)G.addHandler(w0(J),!0);$.callbacks=G}else $.callbacks=new LQ(Z._parentRunId,{handlers:W.handlers.concat(Z.handlers),inheritableHandlers:W.inheritableHandlers.concat(Z.inheritableHandlers),tags:Array.from(new Set(W.tags.concat(Z.tags))),inheritableTags:Array.from(new Set(W.inheritableTags.concat(Z.inheritableTags))),metadata:{...W.metadata,...Z.metadata}})}else{let W=q;$[W]=Y[W]??$[W]}return $}var lG=new Set(["string","number","boolean"]);function C(Q){let $=a.getRunnableConfig(),Y={tags:[],metadata:{},recursionLimit:25,runId:void 0};if($){let{runId:q,runName:W,...Z}=$;Y=Object.entries(Z).reduce((G,[J,z])=>{if(z!==void 0)G[J]=z;return G},Y)}if(Q)Y=Object.entries(Q).reduce((q,[W,Z])=>{if(Z!==void 0)q[W]=Z;return q},Y);if(Y?.configurable){for(let q of Object.keys(Y.configurable))if(lG.has(typeof Y.configurable[q])&&!Y.metadata?.[q]){if(!Y.metadata)Y.metadata={};Y.metadata[q]=Y.configurable[q]}}if(Y.timeout!==void 0){if(Y.timeout<=0)throw Error("Timeout must be a positive number");let q=Y.timeout,W=AbortSignal.timeout(q);if(!Y.metadata)Y.metadata={};if(Y.metadata.timeoutMs===void 0)Y.metadata.timeoutMs=q;if(Y.signal!==void 0){if("any"in AbortSignal)Y.signal=AbortSignal.any([Y.signal,W])}else Y.signal=W;delete Y.timeout}return Y}function l(Q={},{callbacks:$,maxConcurrency:Y,recursionLimit:q,runName:W,configurable:Z,runId:G}={}){let J=C(Q);if($!==void 0)delete J.runName,J.callbacks=$;if(q!==void 0)J.recursionLimit=q;if(Y!==void 0)J.maxConcurrency=Y;if(W!==void 0)J.runName=W;if(Z!==void 0)J.configurable={...J.configurable,...Z};if(G!==void 0)delete J.runId;return J}function DQ(Q){if(!Q)return;return{configurable:Q.configurable,recursionLimit:Q.recursionLimit,callbacks:Q.callbacks,tags:Q.tags,metadata:Q.metadata,maxConcurrency:Q.maxConcurrency,timeout:Q.timeout,signal:Q.signal,store:Q.store}}async function jQ(Q,$){if($===void 0)return Q;let Y;return Promise.race([Q.catch((q)=>{if(!$?.aborted)throw q;else return}),new Promise((q,W)=>{if(Y=()=>{W(iQ($))},$.addEventListener("abort",Y,{once:!0}),$.aborted)W(iQ($))})]).finally(()=>$.removeEventListener("abort",Y))}function iQ(Q){if(Q?.reason instanceof Error)return Q.reason;if(typeof Q?.reason==="string")return Error(Q.reason);return Error("Aborted")}function m(Q){if(typeof Q!=="object"||Q===null)return!1;let $=Q;if(!("_zod"in $))return!1;let Y=$._zod;return typeof Y==="object"&&Y!==null&&"def"in Y}function s(Q){if(typeof Q!=="object"||Q===null)return!1;let $=Q;if(!("_def"in $)||"_zod"in $)return!1;let Y=$._def;return typeof Y==="object"&&Y!=null&&"typeName"in Y}function S2(Q){if(m(Q))console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior.");return s(Q)}function O0(Q){if(!Q)return!1;if(typeof Q!=="object")return!1;if(Array.isArray(Q))return!1;if(m(Q)||s(Q))return!0;return!1}function iG(Q){if(typeof Q==="object"&&Q!==null&&"_def"in Q&&typeof Q._def==="object"&&Q._def!==null&&"typeName"in Q._def&&Q._def.typeName==="ZodLiteral")return!0;return!1}function sG(Q){if(!m(Q))return!1;if(typeof Q==="object"&&Q!==null&&"_zod"in Q&&typeof Q._zod==="object"&&Q._zod!==null&&"def"in Q._zod&&typeof Q._zod.def==="object"&&Q._zod.def!==null&&"type"in Q._zod.def&&Q._zod.def.type==="literal")return!0;return!1}function T2(Q){if(iG(Q))return!0;if(sG(Q))return!0;return!1}async function R2(Q,$){if(m(Q))try{return{success:!0,data:await eY(Q,$)}}catch(Y){return{success:!1,error:Y}}if(s(Q))return await Q.safeParseAsync($);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function P$(Q,$){if(m(Q))return await eY(Q,$);if(s(Q))return await Q.parseAsync($);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function M2(Q,$){if(m(Q))try{return{success:!0,data:L$(Q,$)}}catch(Y){return{success:!1,error:Y}}if(s(Q))return Q.safeParse($);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function _2(Q,$){if(m(Q))return L$(Q,$);if(s(Q))return Q.parse($);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function sW(Q){if(m(Q))return KQ.get(Q)?.description;if(s(Q))return Q.description;if("description"in Q&&typeof Q.description==="string")return Q.description}function I2(Q){if(!O0(Q))return!1;if(s(Q)){let $=Q._def;if($.typeName==="ZodObject"){let Y=Q;return!Y.shape||Object.keys(Y.shape).length===0}if($.typeName==="ZodRecord")return!0}if(m(Q)){let $=Q._zod.def;if($.type==="object"){let Y=Q;return!Y.shape||Object.keys(Y.shape).length===0}if($.type==="record")return!0}if(typeof Q==="object"&&Q!==null&&!("shape"in Q))return!0;return!1}function S$(Q){if(!O0(Q))return!1;if(s(Q))return Q._def.typeName==="ZodString";if(m(Q))return Q._zod.def.type==="string";return!1}function oW(Q){if(typeof Q==="object"&&Q!==null&&"_def"in Q&&typeof Q._def==="object"&&Q._def!==null&&"typeName"in Q._def&&Q._def.typeName==="ZodObject")return!0;return!1}function CQ(Q){if(!m(Q))return!1;if(typeof Q==="object"&&Q!==null&&"_zod"in Q&&typeof Q._zod==="object"&&Q._zod!==null&&"def"in Q._zod&&typeof Q._zod.def==="object"&&Q._zod.def!==null&&"type"in Q._zod.def&&Q._zod.def.type==="object")return!0;return!1}function $8(Q){if(!m(Q))return!1;if(typeof Q==="object"&&Q!==null&&"_zod"in Q&&typeof Q._zod==="object"&&Q._zod!==null&&"def"in Q._zod&&typeof Q._zod.def==="object"&&Q._zod.def!==null&&"type"in Q._zod.def&&Q._zod.def.type==="array")return!0;return!1}function oG(Q){if(!m(Q))return!1;if(typeof Q==="object"&&Q!==null&&"_zod"in Q&&typeof Q._zod==="object"&&Q._zod!==null&&"def"in Q._zod&&typeof Q._zod.def==="object"&&Q._zod.def!==null&&"type"in Q._zod.def&&Q._zod.def.type==="optional")return!0;return!1}function tG(Q){if(!m(Q))return!1;if(typeof Q==="object"&&Q!==null&&"_zod"in Q&&typeof Q._zod==="object"&&Q._zod!==null&&"def"in Q._zod&&typeof Q._zod.def==="object"&&Q._zod.def!==null&&"type"in Q._zod.def&&Q._zod.def.type==="nullable")return!0;return!1}function x2(Q){if(oW(Q))return!0;if(CQ(Q))return!0;return!1}function dW(Q){if(s(Q))return Q.shape;if(m(Q))return Q._zod.def.shape;throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function j2(Q,$){if(s(Q))return Q.extend($);if(m(Q))return aY.extend(Q,$);throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function v2(Q){if(s(Q))return Q.partial();if(m(Q))return aY.partial(Q8,Q,void 0);throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function E$(Q,$=!1){if(s(Q))return Q.strict();if(CQ(Q)){let Y=Q._zod.def.shape;if($)for(let[Z,G]of Object.entries(Q._zod.def.shape)){if(CQ(G))Y[Z]=E$(G,$);else if($8(G)){let z=G._zod.def.element;if(CQ(z))z=E$(z,$);Y[Z]=vQ(G,{...G._zod.def,element:z})}else Y[Z]=G;let J=KQ.get(G);if(J)KQ.add(Y[Z],J)}let q=vQ(Q,{...Q._zod.def,shape:Y,catchall:iW(cW)}),W=KQ.get(Q);if(W)KQ.add(q,W);return q}throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function pW(Q,$=!1){if(oW(Q))return Q.passthrough();if(CQ(Q)){let Y=Q._zod.def.shape;if($)for(let[Z,G]of Object.entries(Q._zod.def.shape)){if(CQ(G))Y[Z]=pW(G,$);else if($8(G)){let z=G._zod.def.element;if(CQ(z))z=pW(z,$);Y[Z]=vQ(G,{...G._zod.def,element:z})}else Y[Z]=G;let J=KQ.get(G);if(J)KQ.add(Y[Z],J)}let q=vQ(Q,{...Q._zod.def,shape:Y,catchall:lW(uW)}),W=KQ.get(Q);if(W)KQ.add(q,W);return q}throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function C2(Q){if(s(Q))try{let $=Q.parse(void 0);return()=>$}catch{return}if(m(Q))try{let $=L$(Q,void 0);return()=>$}catch{return}}function nG(Q){return s(Q)&&"typeName"in Q._def&&Q._def.typeName==="ZodEffects"}function rG(Q){return m(Q)&&Q._zod.def.type==="pipe"}function G0(Q,$,Y){let q=Y.get(Q);if(q!==void 0)return q;if(s(Q)){if(nG(Q))return G0(Q._def.schema,$,Y);return Q}if(m(Q)){let W=Q;if(rG(Q))W=G0(Q._zod.def.in,$,Y);if($){if(CQ(W)){let G={};for(let[J,z]of Object.entries(W._zod.def.shape))G[J]=G0(z,$,Y);W=vQ(W,{...W._zod.def,shape:G})}else if($8(W)){let G=G0(W._zod.def.element,$,Y);W=vQ(W,{...W._zod.def,element:G})}else if(oG(W)){let G=G0(W._zod.def.innerType,$,Y);W=vQ(W,{...W._zod.def,innerType:G})}else if(tG(W)){let G=G0(W._zod.def.innerType,$,Y);W=vQ(W,{...W._zod.def,innerType:G})}}let Z=KQ.get(Q);if(Z)KQ.add(W,Z);return Y.set(Q,W),W}throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function tW(Q,$=!1){return G0(Q,$,new WeakMap)}function y2(Q,$){if(s(Q)){let Y=dW(Q),q={};for(let[W,Z]of Object.entries(Y))if($(W,Z))q[W]=Z.optional();else q[W]=Z;return Q.extend(q)}if(m(Q)){let Y=dW(Q),q={...Q._zod.def.shape};for(let[G,J]of Object.entries(Y))if($(G,J))q[G]=new Q8({type:"optional",innerType:J});let W=vQ(Q,{...Q._zod.def,shape:q}),Z=KQ.get(Q);if(Z)KQ.add(W,Z);return W}throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function nW(Q){return Q instanceof Error&&(Q.constructor.name==="ZodError"||Q.constructor.name==="$ZodError")}var q8=Symbol("Let zodToJsonSchema decide on which parser to use"),Y8={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},W8=(Q)=>typeof Q==="string"?{...Y8,name:Q}:{...Y8,...Q};var Z8=(Q)=>{let $=W8(Q),Y=$.name!==void 0?[...$.basePath,$.definitionPath,$.name]:$.basePath;return{...$,flags:{hasReferencedOpenAiAnyType:!1},currentPath:Y,propertyPath:void 0,seen:new Map(Object.entries($.definitions).map(([q,W])=>[W._def,{def:W._def,path:[...$.basePath,$.definitionPath,q],jsonSchema:void 0}]))}};var j0=(Q,$)=>{let Y=0;for(;Y<Q.length&&Y<$.length;Y++)if(Q[Y]!==$[Y])break;return[(Q.length-Y).toString(),...$.slice(Y)].join("/")};function f(Q){if(Q.target!=="openAi")return{};let $=[...Q.basePath,Q.definitionPath,Q.openAiAnyTypeName];return Q.flags.hasReferencedOpenAiAnyType=!0,{$ref:Q.$refStrategy==="relative"?j0($,Q.currentPath):$.join("/")}}function T$(Q,$,Y,q){if(!q?.errorMessages)return;if(Y)Q.errorMessage={...Q.errorMessage,[$]:Y}}function v(Q,$,Y,q,W){Q[$]=Y,T$(Q,$,q,W)}function G8(Q,$){let Y={type:"array"};if(Q.type?._def&&Q.type?._def?.typeName!==x.ZodAny)Y.items=_(Q.type._def,{...$,currentPath:[...$.currentPath,"items"]});if(Q.minLength)v(Y,"minItems",Q.minLength.value,Q.minLength.message,$);if(Q.maxLength)v(Y,"maxItems",Q.maxLength.value,Q.maxLength.message,$);if(Q.exactLength)v(Y,"minItems",Q.exactLength.value,Q.exactLength.message,$),v(Y,"maxItems",Q.exactLength.value,Q.exactLength.message,$);return Y}function J8(Q,$){let Y={type:"integer",format:"int64"};if(!Q.checks)return Y;for(let q of Q.checks)switch(q.kind){case"min":if($.target==="jsonSchema7")if(q.inclusive)v(Y,"minimum",q.value,q.message,$);else v(Y,"exclusiveMinimum",q.value,q.message,$);else{if(!q.inclusive)Y.exclusiveMinimum=!0;v(Y,"minimum",q.value,q.message,$)}break;case"max":if($.target==="jsonSchema7")if(q.inclusive)v(Y,"maximum",q.value,q.message,$);else v(Y,"exclusiveMaximum",q.value,q.message,$);else{if(!q.inclusive)Y.exclusiveMaximum=!0;v(Y,"maximum",q.value,q.message,$)}break;case"multipleOf":v(Y,"multipleOf",q.value,q.message,$);break}return Y}function z8(){return{type:"boolean"}}function v0(Q,$){return _(Q.type._def,$)}var K8=(Q,$)=>{return _(Q.innerType._def,$)};function R$(Q,$,Y){let q=Y??$.dateStrategy;if(Array.isArray(q))return{anyOf:q.map((W)=>R$(Q,$,W))};switch(q){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return aG(Q,$)}}var aG=(Q,$)=>{let Y={type:"integer",format:"unix-time"};if($.target==="openApi3")return Y;for(let q of Q.checks)switch(q.kind){case"min":v(Y,"minimum",q.value,q.message,$);break;case"max":v(Y,"maximum",q.value,q.message,$);break}return Y};function X8(Q,$){return{..._(Q.innerType._def,$),default:Q.defaultValue()}}function U8(Q,$){return $.effectStrategy==="input"?_(Q.schema._def,$):f($)}function N8(Q){return{type:"string",enum:Array.from(Q.values)}}var eG=(Q)=>{if("type"in Q&&Q.type==="string")return!1;return"allOf"in Q};function B8(Q,$){let Y=[_(Q.left._def,{...$,currentPath:[...$.currentPath,"allOf","0"]}),_(Q.right._def,{...$,currentPath:[...$.currentPath,"allOf","1"]})].filter((Z)=>!!Z),q=$.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,W=[];return Y.forEach((Z)=>{if(eG(Z)){if(W.push(...Z.allOf),Z.unevaluatedProperties===void 0)q=void 0}else{let G=Z;if("additionalProperties"in Z&&Z.additionalProperties===!1){let{additionalProperties:J,...z}=Z;G=z}else q=void 0;W.push(G)}}),W.length?{allOf:W,...q}:void 0}function F8(Q,$){let Y=typeof Q.value;if(Y!=="bigint"&&Y!=="number"&&Y!=="boolean"&&Y!=="string")return{type:Array.isArray(Q.value)?"array":"object"};if($.target==="openApi3")return{type:Y==="bigint"?"integer":Y,enum:[Q.value]};return{type:Y==="bigint"?"integer":Y,const:Q.value}}var V8=void 0,wQ={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(V8===void 0)V8=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return V8},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function C0(Q,$){let Y={type:"string"};if(Q.checks)for(let q of Q.checks)switch(q.kind){case"min":v(Y,"minLength",typeof Y.minLength==="number"?Math.max(Y.minLength,q.value):q.value,q.message,$);break;case"max":v(Y,"maxLength",typeof Y.maxLength==="number"?Math.min(Y.maxLength,q.value):q.value,q.message,$);break;case"email":switch($.emailStrategy){case"format:email":PQ(Y,"email",q.message,$);break;case"format:idn-email":PQ(Y,"idn-email",q.message,$);break;case"pattern:zod":$Q(Y,wQ.email,q.message,$);break}break;case"url":PQ(Y,"uri",q.message,$);break;case"uuid":PQ(Y,"uuid",q.message,$);break;case"regex":$Q(Y,q.regex,q.message,$);break;case"cuid":$Q(Y,wQ.cuid,q.message,$);break;case"cuid2":$Q(Y,wQ.cuid2,q.message,$);break;case"startsWith":$Q(Y,RegExp(`^${A8(q.value,$)}`),q.message,$);break;case"endsWith":$Q(Y,RegExp(`${A8(q.value,$)}$`),q.message,$);break;case"datetime":PQ(Y,"date-time",q.message,$);break;case"date":PQ(Y,"date",q.message,$);break;case"time":PQ(Y,"time",q.message,$);break;case"duration":PQ(Y,"duration",q.message,$);break;case"length":v(Y,"minLength",typeof Y.minLength==="number"?Math.max(Y.minLength,q.value):q.value,q.message,$),v(Y,"maxLength",typeof Y.maxLength==="number"?Math.min(Y.maxLength,q.value):q.value,q.message,$);break;case"includes":$Q(Y,RegExp(A8(q.value,$)),q.message,$);break;case"ip":if(q.version!=="v6")PQ(Y,"ipv4",q.message,$);if(q.version!=="v4")PQ(Y,"ipv6",q.message,$);break;case"base64url":$Q(Y,wQ.base64url,q.message,$);break;case"jwt":$Q(Y,wQ.jwt,q.message,$);break;case"cidr":if(q.version!=="v6")$Q(Y,wQ.ipv4Cidr,q.message,$);if(q.version!=="v4")$Q(Y,wQ.ipv6Cidr,q.message,$);break;case"emoji":$Q(Y,wQ.emoji(),q.message,$);break;case"ulid":$Q(Y,wQ.ulid,q.message,$);break;case"base64":switch($.base64Strategy){case"format:binary":PQ(Y,"binary",q.message,$);break;case"contentEncoding:base64":v(Y,"contentEncoding","base64",q.message,$);break;case"pattern:zod":$Q(Y,wQ.base64,q.message,$);break}break;case"nanoid":$Q(Y,wQ.nanoid,q.message,$);break;case"toLowerCase":case"toUpperCase":case"trim":break;default:((W)=>{})(q)}return Y}function A8(Q,$){return $.patternStrategy==="escape"?$J(Q):Q}var QJ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function $J(Q){let $="";for(let Y=0;Y<Q.length;Y++){if(!QJ.has(Q[Y]))$+="\\";$+=Q[Y]}return $}function PQ(Q,$,Y,q){if(Q.format||Q.anyOf?.some((W)=>W.format)){if(!Q.anyOf)Q.anyOf=[];if(Q.format){if(Q.anyOf.push({format:Q.format,...Q.errorMessage&&q.errorMessages&&{errorMessage:{format:Q.errorMessage.format}}}),delete Q.format,Q.errorMessage){if(delete Q.errorMessage.format,Object.keys(Q.errorMessage).length===0)delete Q.errorMessage}}Q.anyOf.push({format:$,...Y&&q.errorMessages&&{errorMessage:{format:Y}}})}else v(Q,"format",$,Y,q)}function $Q(Q,$,Y,q){if(Q.pattern||Q.allOf?.some((W)=>W.pattern)){if(!Q.allOf)Q.allOf=[];if(Q.pattern){if(Q.allOf.push({pattern:Q.pattern,...Q.errorMessage&&q.errorMessages&&{errorMessage:{pattern:Q.errorMessage.pattern}}}),delete Q.pattern,Q.errorMessage){if(delete Q.errorMessage.pattern,Object.keys(Q.errorMessage).length===0)delete Q.errorMessage}}Q.allOf.push({pattern:rW($,q),...Y&&q.errorMessages&&{errorMessage:{pattern:Y}}})}else v(Q,"pattern",rW($,q),Y,q)}function rW(Q,$){if(!$.applyRegexFlags||!Q.flags)return Q.source;let Y={i:Q.flags.includes("i"),m:Q.flags.includes("m"),s:Q.flags.includes("s")},q=Y.i?Q.source.toLowerCase():Q.source,W="",Z=!1,G=!1,J=!1;for(let z=0;z<q.length;z++){if(Z){W+=q[z],Z=!1;continue}if(Y.i){if(G){if(q[z].match(/[a-z]/)){if(J)W+=q[z],W+=`${q[z-2]}-${q[z]}`.toUpperCase(),J=!1;else if(q[z+1]==="-"&&q[z+2]?.match(/[a-z]/))W+=q[z],J=!0;else W+=`${q[z]}${q[z].toUpperCase()}`;continue}}else if(q[z].match(/[a-z]/)){W+=`[${q[z]}${q[z].toUpperCase()}]`;continue}}if(Y.m){if(q[z]==="^"){W+=`(^|(?<=[\r
|
|
54
|
+
]))`;continue}else if(q[z]==="$"){W+=`($|(?=[\r
|
|
55
|
+
]))`;continue}}if(Y.s&&q[z]==="."){W+=G?`${q[z]}\r
|
|
56
|
+
`:`[${q[z]}\r
|
|
57
|
+
]`;continue}if(W+=q[z],q[z]==="\\")Z=!0;else if(G&&q[z]==="]")G=!1;else if(!G&&q[z]==="[")G=!0}try{new RegExp(W)}catch{return console.warn(`Could not convert regex pattern at ${$.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return W}function y0(Q,$){if($.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if($.target==="openApi3"&&Q.keyType?._def.typeName===x.ZodEnum)return{type:"object",required:Q.keyType._def.values,properties:Q.keyType._def.values.reduce((q,W)=>({...q,[W]:_(Q.valueType._def,{...$,currentPath:[...$.currentPath,"properties",W]})??f($)}),{}),additionalProperties:$.rejectedAdditionalProperties};let Y={type:"object",additionalProperties:_(Q.valueType._def,{...$,currentPath:[...$.currentPath,"additionalProperties"]})??$.allowedAdditionalProperties};if($.target==="openApi3")return Y;if(Q.keyType?._def.typeName===x.ZodString&&Q.keyType._def.checks?.length){let{type:q,...W}=C0(Q.keyType._def,$);return{...Y,propertyNames:W}}else if(Q.keyType?._def.typeName===x.ZodEnum)return{...Y,propertyNames:{enum:Q.keyType._def.values}};else if(Q.keyType?._def.typeName===x.ZodBranded&&Q.keyType._def.type._def.typeName===x.ZodString&&Q.keyType._def.type._def.checks?.length){let{type:q,...W}=v0(Q.keyType._def,$);return{...Y,propertyNames:W}}return Y}function H8(Q,$){if($.mapStrategy==="record")return y0(Q,$);return{type:"array",maxItems:125,items:{type:"array",items:[_(Q.keyType._def,{...$,currentPath:[...$.currentPath,"items","items","0"]})||f($),_(Q.valueType._def,{...$,currentPath:[...$.currentPath,"items","items","1"]})||f($)],minItems:2,maxItems:2}}}function D8(Q){let $=Q.values,Y=Object.keys(Q.values).filter((W)=>{return typeof $[$[W]]!=="number"}).map((W)=>$[W]),q=Array.from(new Set(Y.map((W)=>typeof W)));return{type:q.length===1?q[0]==="string"?"string":"number":["string","number"],enum:Y}}function w8(Q){return Q.target==="openAi"?void 0:{not:f({...Q,currentPath:[...Q.currentPath,"not"]})}}function O8(Q){return Q.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var E0={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function E8(Q,$){if($.target==="openApi3")return aW(Q,$);let Y=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if(Y.every((q)=>(q._def.typeName in E0)&&(!q._def.checks||!q._def.checks.length))){let q=Y.reduce((W,Z)=>{let G=E0[Z._def.typeName];return G&&!W.includes(G)?[...W,G]:W},[]);return{type:q.length>1?q:q[0]}}else if(Y.every((q)=>q._def.typeName==="ZodLiteral"&&!q.description)){let q=Y.reduce((W,Z)=>{let G=typeof Z._def.value;switch(G){case"string":case"number":case"boolean":return[...W,G];case"bigint":return[...W,"integer"];case"object":if(Z._def.value===null)return[...W,"null"];return W;default:return W}},[]);if(q.length===Y.length){let W=q.filter((Z,G,J)=>J.indexOf(Z)===G);return{type:W.length>1?W:W[0],enum:Y.reduce((Z,G)=>{return Z.includes(G._def.value)?Z:[...Z,G._def.value]},[])}}}else if(Y.every((q)=>q._def.typeName==="ZodEnum"))return{type:"string",enum:Y.reduce((q,W)=>[...q,...W._def.values.filter((Z)=>!q.includes(Z))],[])};return aW(Q,$)}var aW=(Q,$)=>{let Y=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map((q,W)=>_(q._def,{...$,currentPath:[...$.currentPath,"anyOf",`${W}`]})).filter((q)=>!!q&&(!$.strictUnions||typeof q==="object"&&Object.keys(q).length>0));return Y.length?{anyOf:Y}:void 0};function L8(Q,$){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length)){if($.target==="openApi3")return{type:E0[Q.innerType._def.typeName],nullable:!0};return{type:[E0[Q.innerType._def.typeName],"null"]}}if($.target==="openApi3"){let q=_(Q.innerType._def,{...$,currentPath:[...$.currentPath]});if(q&&"$ref"in q)return{allOf:[q],nullable:!0};return q&&{...q,nullable:!0}}let Y=_(Q.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","0"]});return Y&&{anyOf:[Y,{type:"null"}]}}function P8(Q,$){let Y={type:"number"};if(!Q.checks)return Y;for(let q of Q.checks)switch(q.kind){case"int":Y.type="integer",T$(Y,"type",q.message,$);break;case"min":if($.target==="jsonSchema7")if(q.inclusive)v(Y,"minimum",q.value,q.message,$);else v(Y,"exclusiveMinimum",q.value,q.message,$);else{if(!q.inclusive)Y.exclusiveMinimum=!0;v(Y,"minimum",q.value,q.message,$)}break;case"max":if($.target==="jsonSchema7")if(q.inclusive)v(Y,"maximum",q.value,q.message,$);else v(Y,"exclusiveMaximum",q.value,q.message,$);else{if(!q.inclusive)Y.exclusiveMaximum=!0;v(Y,"maximum",q.value,q.message,$)}break;case"multipleOf":v(Y,"multipleOf",q.value,q.message,$);break}return Y}function S8(Q,$){let Y=$.target==="openAi",q={type:"object",properties:{}},W=[],Z=Q.shape();for(let J in Z){let z=Z[J];if(z===void 0||z._def===void 0)continue;let K=qJ(z);if(K&&Y){if(z._def.typeName==="ZodOptional")z=z._def.innerType;if(!z.isNullable())z=z.nullable();K=!1}let X=_(z._def,{...$,currentPath:[...$.currentPath,"properties",J],propertyPath:[...$.currentPath,"properties",J]});if(X===void 0)continue;if(q.properties[J]=X,!K)W.push(J)}if(W.length)q.required=W;let G=YJ(Q,$);if(G!==void 0)q.additionalProperties=G;return q}function YJ(Q,$){if(Q.catchall._def.typeName!=="ZodNever")return _(Q.catchall._def,{...$,currentPath:[...$.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return $.allowedAdditionalProperties;case"strict":return $.rejectedAdditionalProperties;case"strip":return $.removeAdditionalStrategy==="strict"?$.allowedAdditionalProperties:$.rejectedAdditionalProperties}}function qJ(Q){try{return Q.isOptional()}catch{return!0}}var T8=(Q,$)=>{if($.currentPath.toString()===$.propertyPath?.toString())return _(Q.innerType._def,$);let Y=_(Q.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","1"]});return Y?{anyOf:[{not:f($)},Y]}:f($)};var R8=(Q,$)=>{if($.pipeStrategy==="input")return _(Q.in._def,$);else if($.pipeStrategy==="output")return _(Q.out._def,$);let Y=_(Q.in._def,{...$,currentPath:[...$.currentPath,"allOf","0"]});return{allOf:[Y,_(Q.out._def,{...$,currentPath:[...$.currentPath,"allOf",Y?"1":"0"]})].filter((q)=>q!==void 0)}};function M8(Q,$){return _(Q.type._def,$)}function _8(Q,$){let Y={type:"array",uniqueItems:!0,items:_(Q.valueType._def,{...$,currentPath:[...$.currentPath,"items"]})};if(Q.minSize)v(Y,"minItems",Q.minSize.value,Q.minSize.message,$);if(Q.maxSize)v(Y,"maxItems",Q.maxSize.value,Q.maxSize.message,$);return Y}function I8(Q,$){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map((Y,q)=>_(Y._def,{...$,currentPath:[...$.currentPath,"items",`${q}`]})).reduce((Y,q)=>q===void 0?Y:[...Y,q],[]),additionalItems:_(Q.rest._def,{...$,currentPath:[...$.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map((Y,q)=>_(Y._def,{...$,currentPath:[...$.currentPath,"items",`${q}`]})).reduce((Y,q)=>q===void 0?Y:[...Y,q],[])}}function x8(Q){return{not:f(Q)}}function j8(Q){return f(Q)}var v8=(Q,$)=>{return _(Q.innerType._def,$)};var C8=(Q,$,Y)=>{switch($){case x.ZodString:return C0(Q,Y);case x.ZodNumber:return P8(Q,Y);case x.ZodObject:return S8(Q,Y);case x.ZodBigInt:return J8(Q,Y);case x.ZodBoolean:return z8();case x.ZodDate:return R$(Q,Y);case x.ZodUndefined:return x8(Y);case x.ZodNull:return O8(Y);case x.ZodArray:return G8(Q,Y);case x.ZodUnion:case x.ZodDiscriminatedUnion:return E8(Q,Y);case x.ZodIntersection:return B8(Q,Y);case x.ZodTuple:return I8(Q,Y);case x.ZodRecord:return y0(Q,Y);case x.ZodLiteral:return F8(Q,Y);case x.ZodEnum:return N8(Q);case x.ZodNativeEnum:return D8(Q);case x.ZodNullable:return L8(Q,Y);case x.ZodOptional:return T8(Q,Y);case x.ZodMap:return H8(Q,Y);case x.ZodSet:return _8(Q,Y);case x.ZodLazy:return()=>Q.getter()._def;case x.ZodPromise:return M8(Q,Y);case x.ZodNaN:case x.ZodNever:return w8(Y);case x.ZodEffects:return U8(Q,Y);case x.ZodAny:return f(Y);case x.ZodUnknown:return j8(Y);case x.ZodDefault:return X8(Q,Y);case x.ZodBranded:return v0(Q,Y);case x.ZodReadonly:return v8(Q,Y);case x.ZodCatch:return K8(Q,Y);case x.ZodPipeline:return R8(Q,Y);case x.ZodFunction:case x.ZodVoid:case x.ZodSymbol:return;default:return((q)=>{return})($)}};function _(Q,$,Y=!1){let q=$.seen.get(Q);if($.override){let J=$.override?.(Q,$,q,Y);if(J!==q8)return J}if(q&&!Y){let J=WJ(q,$);if(J!==void 0)return J}let W={def:Q,path:$.currentPath,jsonSchema:void 0};$.seen.set(Q,W);let Z=C8(Q,Q.typeName,$),G=typeof Z==="function"?_(Z(),$):Z;if(G)ZJ(Q,$,G);if($.postProcess){let J=$.postProcess(G,Q,$);return W.jsonSchema=G,J}return W.jsonSchema=G,G}var WJ=(Q,$)=>{switch($.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:j0($.currentPath,Q.path)};case"none":case"seen":if(Q.path.length<$.currentPath.length&&Q.path.every((Y,q)=>$.currentPath[q]===Y))return console.warn(`Recursive reference detected at ${$.currentPath.join("/")}! Defaulting to any`),f($);return $.$refStrategy==="seen"?f($):void 0}},ZJ=(Q,$,Y)=>{if(Q.description){if(Y.description=Q.description,$.markdownDescription)Y.markdownDescription=Q.description}return Y};var y8=(Q,$)=>{let Y=Z8($),q=typeof $==="object"&&$.definitions?Object.entries($.definitions).reduce((z,[K,X])=>({...z,[K]:_(X._def,{...Y,currentPath:[...Y.basePath,Y.definitionPath,K]},!0)??f(Y)}),{}):void 0,W=typeof $==="string"?$:$?.nameStrategy==="title"?void 0:$?.name,Z=_(Q._def,W===void 0?Y:{...Y,currentPath:[...Y.basePath,Y.definitionPath,W]},!1)??f(Y),G=typeof $==="object"&&$.name!==void 0&&$.nameStrategy==="title"?$.name:void 0;if(G!==void 0)Z.title=G;if(Y.flags.hasReferencedOpenAiAnyType){if(!q)q={};if(!q[Y.openAiAnyTypeName])q[Y.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Y.$refStrategy==="relative"?"1":[...Y.basePath,Y.definitionPath,Y.openAiAnyTypeName].join("/")}}}let J=W===void 0?q?{...Z,[Y.definitionPath]:q}:Z:{$ref:[...Y.$refStrategy==="relative"?[]:Y.basePath,Y.definitionPath,W].join("/"),[Y.definitionPath]:{...q,[W]:Z}};if(Y.target==="jsonSchema7")J.$schema="http://json-schema.org/draft-07/schema#";else if(Y.target==="jsonSchema2019-09"||Y.target==="openAi")J.$schema="https://json-schema.org/draft/2019-09/schema#";if(Y.target==="openAi"&&(("anyOf"in J)||("oneOf"in J)||("allOf"in J)||("type"in J)&&Array.isArray(J.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return J};var T5=M({isSerializableSchema:()=>GJ,isStandardJsonSchema:()=>M$,isStandardSchema:()=>eW});function eW(Q){return(typeof Q==="object"||typeof Q==="function")&&Q!==null&&"~standard"in Q&&typeof Q["~standard"]==="object"&&Q["~standard"]!==null&&"validate"in Q["~standard"]}function M$(Q){return(typeof Q==="object"||typeof Q==="function")&&Q!==null&&"~standard"in Q&&typeof Q["~standard"]==="object"&&Q["~standard"]!==null&&"jsonSchema"in Q["~standard"]}function GJ(Q){return eW(Q)&&M$(Q)}var y5=M({Validator:()=>Y1,deepCompareStrict:()=>Q1,toJsonSchema:()=>b8,validatesOnlyStrings:()=>L0});function b8(Q,$){if(M$(Q)&&!m(Q))return Q["~standard"].jsonSchema.input({target:"draft-07"});if(m(Q)){let Y=tW(Q,!0);if(CQ(Y))return k8(E$(Y,!0),$);else return k8(Q,$)}if(s(Q))return y8(Q);return Q}function L0(Q){if(!Q||typeof Q!=="object"||Object.keys(Q).length===0||Array.isArray(Q))return!1;if("type"in Q){if(typeof Q.type==="string")return Q.type==="string";if(Array.isArray(Q.type))return Q.type.every(($)=>$==="string");return!1}if("enum"in Q)return Array.isArray(Q.enum)&&Q.enum.length>0&&Q.enum.every(($)=>typeof $==="string");if("const"in Q)return typeof Q.const==="string";if("allOf"in Q&&Array.isArray(Q.allOf))return Q.allOf.some(($)=>L0($));if("anyOf"in Q&&Array.isArray(Q.anyOf)||"oneOf"in Q&&Array.isArray(Q.oneOf)){let $="anyOf"in Q?Q.anyOf:Q.oneOf;return $.length>0&&$.every((Y)=>L0(Y))}if("not"in Q)return!1;if("$ref"in Q&&typeof Q.$ref==="string"){let $=Q.$ref,Y=$1(Q);if(Y[$])return L0(Y[$]);return!1}return!1}function h8(Q){return typeof Q==="object"&&Q!==null&&typeof Q[Symbol.iterator]==="function"&&typeof Q.next==="function"}var q1=(Q)=>Q!=null&&typeof Q==="object"&&("next"in Q)&&typeof Q.next==="function";function _$(Q){return typeof Q==="object"&&Q!==null&&typeof Q[Symbol.asyncIterator]==="function"}function W1(Q){return Q!=null&&typeof Q==="object"&&typeof Q.next==="function"}async function Z1(Q,$){try{let Y=await Q.next();while(!Y.done)await $?.(Y.value),Y=await Q.next();return Y.value}finally{await Q.return?.(void 0)}}function*f8(Q,$){while(!0){let{value:Y,done:q}=a.runWithConfig(DQ(Q),$.next.bind($),!0);if(q)break;else yield Y}}async function*I$(Q,$){let Y=$[Symbol.asyncIterator]();while(!0){let{value:q,done:W}=await a.runWithConfig(DQ(Q),Y.next.bind($),!0);if(W)break;else yield q}}var E="0123456789abcdef".split(""),JJ=[-2147483648,8388608,32768,128],SQ=[24,16,8,0],x$=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],t=[];function TQ(Q,$){if($)t[0]=t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0,this.blocks=t;else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];if(Q)this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428;else this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225;this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=Q}TQ.prototype.update=function(Q){if(this.finalized)return;var $,Y=typeof Q;if(Y!=="string"){if(Y==="object"){if(Q===null)throw Error(ERROR);else if(ARRAY_BUFFER&&Q.constructor===ArrayBuffer)Q=new Uint8Array(Q);else if(!Array.isArray(Q)){if(!ARRAY_BUFFER||!ArrayBuffer.isView(Q))throw Error(ERROR)}}else throw Error(ERROR);$=!0}var q,W=0,Z,G=Q.length,J=this.blocks;while(W<G){if(this.hashed)this.hashed=!1,J[0]=this.block,this.block=J[16]=J[1]=J[2]=J[3]=J[4]=J[5]=J[6]=J[7]=J[8]=J[9]=J[10]=J[11]=J[12]=J[13]=J[14]=J[15]=0;if($)for(Z=this.start;W<G&&Z<64;++W)J[Z>>>2]|=Q[W]<<SQ[Z++&3];else for(Z=this.start;W<G&&Z<64;++W)if(q=Q.charCodeAt(W),q<128)J[Z>>>2]|=q<<SQ[Z++&3];else if(q<2048)J[Z>>>2]|=(192|q>>>6)<<SQ[Z++&3],J[Z>>>2]|=(128|q&63)<<SQ[Z++&3];else if(q<55296||q>=57344)J[Z>>>2]|=(224|q>>>12)<<SQ[Z++&3],J[Z>>>2]|=(128|q>>>6&63)<<SQ[Z++&3],J[Z>>>2]|=(128|q&63)<<SQ[Z++&3];else q=65536+((q&1023)<<10|Q.charCodeAt(++W)&1023),J[Z>>>2]|=(240|q>>>18)<<SQ[Z++&3],J[Z>>>2]|=(128|q>>>12&63)<<SQ[Z++&3],J[Z>>>2]|=(128|q>>>6&63)<<SQ[Z++&3],J[Z>>>2]|=(128|q&63)<<SQ[Z++&3];if(this.lastByteIndex=Z,this.bytes+=Z-this.start,Z>=64)this.block=J[16],this.start=Z-64,this.hash(),this.hashed=!0;else this.start=Z}if(this.bytes>4294967295)this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296;return this};TQ.prototype.finalize=function(){if(this.finalized)return;this.finalized=!0;var Q=this.blocks,$=this.lastByteIndex;if(Q[16]=this.block,Q[$>>>2]|=JJ[$&3],this.block=Q[16],$>=56){if(!this.hashed)this.hash();Q[0]=this.block,Q[16]=Q[1]=Q[2]=Q[3]=Q[4]=Q[5]=Q[6]=Q[7]=Q[8]=Q[9]=Q[10]=Q[11]=Q[12]=Q[13]=Q[14]=Q[15]=0}Q[14]=this.hBytes<<3|this.bytes>>>29,Q[15]=this.bytes<<3,this.hash()};TQ.prototype.hash=function(){var Q=this.h0,$=this.h1,Y=this.h2,q=this.h3,W=this.h4,Z=this.h5,G=this.h6,J=this.h7,z=this.blocks,K,X,U,N,B,A,D,w,S,H,R;for(K=16;K<64;++K)B=z[K-15],X=(B>>>7|B<<25)^(B>>>18|B<<14)^B>>>3,B=z[K-2],U=(B>>>17|B<<15)^(B>>>19|B<<13)^B>>>10,z[K]=z[K-16]+X+z[K-7]+U<<0;R=$&Y;for(K=0;K<64;K+=4){if(this.first){if(this.is224)w=300032,B=z[0]-1413257819,J=B-150054599<<0,q=B+24177077<<0;else w=704751109,B=z[0]-210244248,J=B-1521486534<<0,q=B+143694565<<0;this.first=!1}else X=(Q>>>2|Q<<30)^(Q>>>13|Q<<19)^(Q>>>22|Q<<10),U=(W>>>6|W<<26)^(W>>>11|W<<21)^(W>>>25|W<<7),w=Q&$,N=w^Q&Y^R,D=W&Z^~W&G,B=J+U+D+x$[K]+z[K],A=X+N,J=q+B<<0,q=B+A<<0;X=(q>>>2|q<<30)^(q>>>13|q<<19)^(q>>>22|q<<10),U=(J>>>6|J<<26)^(J>>>11|J<<21)^(J>>>25|J<<7),S=q&Q,N=S^q&$^w,D=G&J^~G&W,B=Z+U+D+x$[K+1]+z[K+1],A=X+N,G=Y+B<<0,Y=B+A<<0,X=(Y>>>2|Y<<30)^(Y>>>13|Y<<19)^(Y>>>22|Y<<10),U=(G>>>6|G<<26)^(G>>>11|G<<21)^(G>>>25|G<<7),H=Y&q,N=H^Y&Q^S,D=Z&G^~Z&J,B=W+U+D+x$[K+2]+z[K+2],A=X+N,Z=$+B<<0,$=B+A<<0,X=($>>>2|$<<30)^($>>>13|$<<19)^($>>>22|$<<10),U=(Z>>>6|Z<<26)^(Z>>>11|Z<<21)^(Z>>>25|Z<<7),R=$&Y,N=R^$&q^H,D=Z&G^~Z&J,B=W+U+D+x$[K+3]+z[K+3],A=X+N,W=Q+B<<0,Q=B+A<<0,this.chromeBugWorkAround=!0}this.h0=this.h0+Q<<0,this.h1=this.h1+$<<0,this.h2=this.h2+Y<<0,this.h3=this.h3+q<<0,this.h4=this.h4+W<<0,this.h5=this.h5+Z<<0,this.h6=this.h6+G<<0,this.h7=this.h7+J<<0};TQ.prototype.hex=function(){this.finalize();var Q=this.h0,$=this.h1,Y=this.h2,q=this.h3,W=this.h4,Z=this.h5,G=this.h6,J=this.h7,z=E[Q>>>28&15]+E[Q>>>24&15]+E[Q>>>20&15]+E[Q>>>16&15]+E[Q>>>12&15]+E[Q>>>8&15]+E[Q>>>4&15]+E[Q&15]+E[$>>>28&15]+E[$>>>24&15]+E[$>>>20&15]+E[$>>>16&15]+E[$>>>12&15]+E[$>>>8&15]+E[$>>>4&15]+E[$&15]+E[Y>>>28&15]+E[Y>>>24&15]+E[Y>>>20&15]+E[Y>>>16&15]+E[Y>>>12&15]+E[Y>>>8&15]+E[Y>>>4&15]+E[Y&15]+E[q>>>28&15]+E[q>>>24&15]+E[q>>>20&15]+E[q>>>16&15]+E[q>>>12&15]+E[q>>>8&15]+E[q>>>4&15]+E[q&15]+E[W>>>28&15]+E[W>>>24&15]+E[W>>>20&15]+E[W>>>16&15]+E[W>>>12&15]+E[W>>>8&15]+E[W>>>4&15]+E[W&15]+E[Z>>>28&15]+E[Z>>>24&15]+E[Z>>>20&15]+E[Z>>>16&15]+E[Z>>>12&15]+E[Z>>>8&15]+E[Z>>>4&15]+E[Z&15]+E[G>>>28&15]+E[G>>>24&15]+E[G>>>20&15]+E[G>>>16&15]+E[G>>>12&15]+E[G>>>8&15]+E[G>>>4&15]+E[G&15];if(!this.is224)z+=E[J>>>28&15]+E[J>>>24&15]+E[J>>>20&15]+E[J>>>16&15]+E[J>>>12&15]+E[J>>>8&15]+E[J>>>4&15]+E[J&15];return z};TQ.prototype.toString=TQ.prototype.hex;TQ.prototype.digest=function(){this.finalize();var Q=this.h0,$=this.h1,Y=this.h2,q=this.h3,W=this.h4,Z=this.h5,G=this.h6,J=this.h7,z=[Q>>>24&255,Q>>>16&255,Q>>>8&255,Q&255,$>>>24&255,$>>>16&255,$>>>8&255,$&255,Y>>>24&255,Y>>>16&255,Y>>>8&255,Y&255,q>>>24&255,q>>>16&255,q>>>8&255,q&255,W>>>24&255,W>>>16&255,W>>>8&255,W&255,Z>>>24&255,Z>>>16&255,Z>>>8&255,Z&255,G>>>24&255,G>>>16&255,G>>>8&255,G&255];if(!this.is224)z.push(J>>>24&255,J>>>16&255,J>>>8&255,J&255);return z};TQ.prototype.array=TQ.prototype.digest;TQ.prototype.arrayBuffer=function(){this.finalize();var Q=new ArrayBuffer(this.is224?28:32),$=new DataView(Q);if($.setUint32(0,this.h0),$.setUint32(4,this.h1),$.setUint32(8,this.h2),$.setUint32(12,this.h3),$.setUint32(16,this.h4),$.setUint32(20,this.h5),$.setUint32(24,this.h6),!this.is224)$.setUint32(28,this.h7);return Q};var j$=(...Q)=>{return new TQ(!1,!0).update(Q.join("")).hex()};var u5=M({sha256:()=>j$});var t5=M({BaseCache:()=>J1,InMemoryCache:()=>g8,defaultHashKeyEncoder:()=>G1,deserializeStoredGeneration:()=>zJ,serializeGeneration:()=>KJ}),G1=(...Q)=>j$(Q.join("_"));function zJ(Q){if(Q.message!==void 0)return{text:Q.text,message:UY(Q.message)};else return{text:Q.text}}function KJ(Q){let $={text:Q.text};if(Q.message!==void 0)$.message=Q.message.toDict();return $}var J1=class{keyEncoder=G1;makeDefaultKeyEncoder(Q){this.keyEncoder=Q}},XJ=new Map,g8=class Q extends J1{cache;constructor($){super();this.cache=$??new Map}lookup($,Y){return Promise.resolve(this.cache.get(this.keyEncoder($,Y))??null)}async update($,Y,q){this.cache.set(this.keyEncoder($,Y),q)}static global(){return new Q(XJ)}};var UJ=Object.prototype.toString,NJ=(Q)=>UJ.call(Q)==="[object Error]",BJ=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function z1(Q){if(!(Q&&NJ(Q)&&Q.name==="TypeError"&&typeof Q.message==="string"))return!1;let{message:$,stack:Y}=Q;if($==="Load failed")return Y===void 0||"__sentry_captured__"in Q;if($.startsWith("error sending request for url"))return!0;return BJ.has($)}function FJ(Q){if(typeof Q==="number"){if(Q<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(Q))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(Q!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function v$(Q,$,{min:Y=0,allowInfinity:q=!1}={}){if($===void 0)return;if(typeof $!=="number"||Number.isNaN($))throw TypeError(`Expected \`${Q}\` to be a number${q?" or Infinity":""}.`);if(!q&&!Number.isFinite($))throw TypeError(`Expected \`${Q}\` to be a finite number.`);if($<Y)throw TypeError(`Expected \`${Q}\` to be ≥ ${Y}.`)}var VJ=class extends Error{constructor(Q){super();if(Q instanceof Error)this.originalError=Q,{message:Q}=Q;else this.originalError=Error(Q),this.originalError.stack=this.stack;this.name="AbortError",this.message=Q}};function AJ(Q,$){let Y=Math.max(1,Q+1),q=$.randomize?Math.random()+1:1,W=Math.round(q*$.minTimeout*$.factor**(Y-1));return W=Math.min(W,$.maxTimeout),W}function K1(Q,$){if(!Number.isFinite($))return $;return $-(performance.now()-Q)}async function HJ({error:Q,attemptNumber:$,retriesConsumed:Y,startTime:q,options:W}){let Z=Q instanceof Error?Q:TypeError(`Non-error was thrown: "${Q}". You should only throw errors.`);if(Z instanceof VJ)throw Z.originalError;let G=Number.isFinite(W.retries)?Math.max(0,W.retries-Y):W.retries,J=W.maxRetryTime??Number.POSITIVE_INFINITY,z=Object.freeze({error:Z,attemptNumber:$,retriesLeft:G,retriesConsumed:Y});if(await W.onFailedAttempt(z),K1(q,J)<=0)throw Z;let K=await W.shouldConsumeRetry(z),X=K1(q,J);if(X<=0||G<=0)throw Z;if(Z instanceof TypeError&&!z1(Z)){if(K)throw Z;return W.signal?.throwIfAborted(),!1}if(!await W.shouldRetry(z))throw Z;if(!K)return W.signal?.throwIfAborted(),!1;let U=AJ(Y,W),N=Math.min(U,X);if(N>0)await new Promise((B,A)=>{let D=()=>{clearTimeout(w),W.signal?.removeEventListener("abort",D),A(W.signal.reason)},w=setTimeout(()=>{W.signal?.removeEventListener("abort",D),B()},N);if(W.unref)w.unref?.();W.signal?.addEventListener("abort",D,{once:!0})});return W.signal?.throwIfAborted(),!0}async function k0(Q,$={}){if($={...$},FJ($.retries),Object.hasOwn($,"forever"))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");if($.retries??=10,$.factor??=2,$.minTimeout??=1000,$.maxTimeout??=Number.POSITIVE_INFINITY,$.maxRetryTime??=Number.POSITIVE_INFINITY,$.randomize??=!1,$.onFailedAttempt??=()=>{},$.shouldRetry??=()=>!0,$.shouldConsumeRetry??=()=>!0,v$("factor",$.factor,{min:0,allowInfinity:!1}),v$("minTimeout",$.minTimeout,{min:0,allowInfinity:!1}),v$("maxTimeout",$.maxTimeout,{min:0,allowInfinity:!0}),v$("maxRetryTime",$.maxRetryTime,{min:0,allowInfinity:!0}),!($.factor>0))$.factor=1;$.signal?.throwIfAborted();let Y=0,q=0,W=performance.now();while(Number.isFinite($.retries)?q<=$.retries:!0){Y++;try{$.signal?.throwIfAborted();let Z=await Q(Y);return $.signal?.throwIfAborted(),Z}catch(Z){if(await HJ({error:Z,attemptNumber:Y,retriesConsumed:q,startTime:W,options:$}))q++}}throw Error("Retry attempts exhausted without throwing an error.")}var C$=rQ(kY(),1),Z7=M({AsyncCaller:()=>J0}),DJ=[400,401,402,403,404,405,406,407,409],wJ=(Q)=>{if(typeof Q!=="object"||Q===null)return;if("message"in Q&&typeof Q.message==="string"&&(Q.message.startsWith("Cancel")||Q.message.startsWith("AbortError"))||"name"in Q&&typeof Q.name==="string"&&Q.name==="AbortError")throw Q;if("code"in Q&&typeof Q.code==="string"&&Q.code==="ECONNABORTED")throw Q;let $="response"in Q&&typeof Q.response==="object"&&Q.response!==null&&"status"in Q.response&&typeof Q.response.status==="number"?Q.response.status:void 0,Y="status"in Q&&typeof Q.status==="number"?Q.status:void 0,q=$??Y;if(q&&DJ.includes(+q))throw Q;if(("error"in Q&&typeof Q.error==="object"&&Q.error!==null&&"code"in Q.error&&typeof Q.error.code==="string"?Q.error.code:void 0)==="insufficient_quota"){let W=Error("message"in Q&&typeof Q.message==="string"?Q.message:"Insufficient quota");throw W.name="InsufficientQuotaError",W}},J0=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(Q){this.maxConcurrency=Q.maxConcurrency??1/0,this.maxRetries=Q.maxRetries??6,this.onFailedAttempt=Q.onFailedAttempt??wJ,this.queue=new("default"in C$.default?C$.default.default:C$.default)({concurrency:this.maxConcurrency})}async call(Q,...$){return this.queue.add(()=>k0(()=>Q(...$).catch((Y)=>{if(Y instanceof Error)throw Y;else throw Error(Y)}),{onFailedAttempt:({error:Y})=>this.onFailedAttempt?.(Y),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(Q,$,...Y){if(Q.signal){let q;return Promise.race([this.call($,...Y),new Promise((W,Z)=>{q=()=>{Z(iQ(Q.signal))},Q.signal?.addEventListener("abort",q,{once:!0})})]).finally(()=>{if(Q.signal&&q)Q.signal.removeEventListener("abort",q)})}return this.call($,...Y)}fetch(...Q){return this.call(()=>fetch(...Q).then(($)=>$.ok?$:Promise.reject($)))}};var B7=M({AsyncGeneratorWithSetup:()=>sQ,IterableReadableStream:()=>YQ,atee:()=>y$,concat:()=>k$,pipeGeneratorWithSetup:()=>m8}),YQ=class Q extends ReadableStream{reader;ensureReader(){if(!this.reader)this.reader=this.getReader()}async next(){this.ensureReader();try{let $=await this.reader.read();if($.done)return this.reader.releaseLock(),{done:!0,value:void 0};else return{done:!1,value:$.value}}catch($){throw this.reader.releaseLock(),$}}async return(){if(this.ensureReader(),this.locked){let $=this.reader.cancel();this.reader.releaseLock(),await $}return{done:!0,value:void 0}}async throw($){if(this.ensureReader(),this.locked){let Y=this.reader.cancel();this.reader.releaseLock(),await Y}throw $}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream($){let Y=$.getReader();return new Q({start(q){return W();function W(){return Y.read().then(({done:Z,value:G})=>{if(Z){q.close();return}return q.enqueue(G),W()})}},cancel(){Y.releaseLock()}})}static fromAsyncGenerator($){return new Q({async pull(Y){let{value:q,done:W}=await $.next();if(W)Y.close();Y.enqueue(q)},async cancel(Y){await $.return(Y)}})}};function y$(Q,$=2){let Y=Array.from({length:$},()=>[]);return Y.map(async function*(W){while(!0)if(W.length===0){let Z=await Q.next();for(let G of Y)G.push(Z)}else if(W[0].done)return;else yield W.shift().value})}function k$(Q,$){if(Array.isArray(Q)&&Array.isArray($))return Q.concat($);else if(typeof Q==="string"&&typeof $==="string")return Q+$;else if(typeof Q==="number"&&typeof $==="number")return Q+$;else if("concat"in Q&&typeof Q.concat==="function")return Q.concat($);else if(typeof Q==="object"&&typeof $==="object"){let Y={...Q};for(let[q,W]of Object.entries($))if(q in Y&&!Array.isArray(Y[q]))Y[q]=k$(Y[q],W);else Y[q]=W;return Y}else throw Error(`Cannot concat ${typeof Q} and ${typeof $}`)}var sQ=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(Q){this.generator=Q.generator,this.config=Q.config,this.signal=Q.signal??this.config?.signal,this.setup=new Promise(($,Y)=>{a.runWithConfig(DQ(Q.config),async()=>{if(this.firstResult=Q.generator.next(),Q.startSetup)this.firstResult.then(Q.startSetup).then($,Y);else this.firstResult.then((q)=>$(void 0),Y)},!0)})}async next(...Q){if(this.signal?.throwIfAborted(),!this.firstResultUsed)return this.firstResultUsed=!0,this.firstResult;return a.runWithConfig(DQ(this.config),this.signal?async()=>{return jQ(this.generator.next(...Q),this.signal)}:async()=>{return this.generator.next(...Q)},!0)}async return(Q){return this.generator.return(Q)}async throw(Q){return this.generator.throw(Q)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function m8(Q,$,Y,q,...W){let Z=new sQ({generator:$,startSetup:Y,signal:q}),G=await Z.setup;return{output:Q(Z,G,...W),setup:G}}/*!
|
|
58
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
59
|
+
* (c) 2017-2022 Joachim Wester
|
|
60
|
+
* MIT licensed
|
|
61
|
+
*/var OJ=Object.prototype.hasOwnProperty;function h$(Q,$){return OJ.call(Q,$)}function f$(Q){if(Array.isArray(Q)){let Y=Array(Q.length);for(let q=0;q<Y.length;q++)Y[q]=""+q;return Y}if(Object.keys)return Object.keys(Q);let $=[];for(let Y in Q)if(h$(Q,Y))$.push(Y);return $}function qQ(Q){switch(typeof Q){case"object":return JSON.parse(JSON.stringify(Q));case"undefined":return null;default:return Q}}function g$(Q){let $=0,Y=Q.length,q;while($<Y){if(q=Q.charCodeAt($),q>=48&&q<=57){$++;continue}return!1}return!0}function hQ(Q){if(Q.indexOf("/")===-1&&Q.indexOf("~")===-1)return Q;return Q.replace(/~/g,"~0").replace(/\//g,"~1")}function m$(Q){return Q.replace(/~1/g,"/").replace(/~0/g,"~")}function b$(Q){if(Q===void 0)return!0;if(Q){if(Array.isArray(Q)){for(let Y=0,q=Q.length;Y<q;Y++)if(b$(Q[Y]))return!0}else if(typeof Q==="object"){let Y=f$(Q),q=Y.length;for(var $=0;$<q;$++)if(b$(Q[Y[$]]))return!0}}return!1}function X1(Q,$){let Y=[Q];for(let q in $){let W=typeof $[q]==="object"?JSON.stringify($[q],null,2):$[q];if(typeof W<"u")Y.push(`${q}: ${W}`)}return Y.join(`
|
|
62
|
+
`)}var d$=class extends Error{constructor(Q,$,Y,q,W){super(X1(Q,{name:$,index:Y,operation:q,tree:W}));this.name=$,this.index=Y,this.operation=q,this.tree=W,Object.setPrototypeOf(this,new.target.prototype),this.message=X1(Q,{name:$,index:Y,operation:q,tree:W})}};var U1=M({JsonPatchError:()=>u,_areEquals:()=>S0,applyOperation:()=>oQ,applyPatch:()=>z0,applyReducer:()=>N1,deepClone:()=>EJ,getValueByPointer:()=>b0,validate:()=>d8,validator:()=>h0}),u=d$,EJ=qQ,P0={add:function(Q,$,Y){if($==="__proto__"||$==="constructor")throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return Q[$]=this.value,{newDocument:Y}},remove:function(Q,$,Y){if($==="__proto__"||$==="constructor")throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var q=Q[$];return delete Q[$],{newDocument:Y,removed:q}},replace:function(Q,$,Y){if($==="__proto__"||$==="constructor")throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var q=Q[$];return Q[$]=this.value,{newDocument:Y,removed:q}},move:function(Q,$,Y){let q=b0(Y,this.path);if(q)q=qQ(q);let W=oQ(Y,{op:"remove",path:this.from}).removed;return oQ(Y,{op:"add",path:this.path,value:W}),{newDocument:Y,removed:q}},copy:function(Q,$,Y){let q=b0(Y,this.from);return oQ(Y,{op:"add",path:this.path,value:qQ(q)}),{newDocument:Y}},test:function(Q,$,Y){return{newDocument:Y,test:S0(Q[$],this.value)}},_get:function(Q,$,Y){return this.value=Q[$],{newDocument:Y}}},LJ={add:function(Q,$,Y){if(g$($))Q.splice($,0,this.value);else Q[$]=this.value;return{newDocument:Y,index:$}},remove:function(Q,$,Y){return{newDocument:Y,removed:Q.splice($,1)[0]}},replace:function(Q,$,Y){var q=Q[$];return Q[$]=this.value,{newDocument:Y,removed:q}},move:P0.move,copy:P0.copy,test:P0.test,_get:P0._get};function b0(Q,$){if($=="")return Q;var Y={op:"_get",path:$};return oQ(Q,Y),Y.value}function oQ(Q,$,Y=!1,q=!0,W=!0,Z=0){if(Y)if(typeof Y=="function")Y($,0,Q,$.path);else h0($,0);if($.path===""){let G={newDocument:Q};if($.op==="add")return G.newDocument=$.value,G;else if($.op==="replace")return G.newDocument=$.value,G.removed=Q,G;else if($.op==="move"||$.op==="copy"){if(G.newDocument=b0(Q,$.from),$.op==="move")G.removed=Q;return G}else if($.op==="test"){if(G.test=S0(Q,$.value),G.test===!1)throw new u("Test operation failed","TEST_OPERATION_FAILED",Z,$,Q);return G.newDocument=Q,G}else if($.op==="remove")return G.removed=Q,G.newDocument=null,G;else if($.op==="_get")return $.value=Q,G;else if(Y)throw new u("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",Z,$,Q);else return G}else{if(!q)Q=qQ(Q);let G=($.path||"").split("/"),J=Q,z=1,K=G.length,X=void 0,U,N;if(typeof Y=="function")N=Y;else N=h0;while(!0){if(U=G[z],U&&U.indexOf("~")!=-1)U=m$(U);if(W&&(U=="__proto__"||U=="prototype"&&z>0&&G[z-1]=="constructor"))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(Y){if(X===void 0){if(J[U]===void 0)X=G.slice(0,z).join("/");else if(z==K-1)X=$.path;if(X!==void 0)N($,0,Q,X)}}if(z++,Array.isArray(J)){if(U==="-")U=J.length;else if(Y&&!g$(U))throw new u("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",Z,$,Q);else if(g$(U))U=~~U;if(z>=K){if(Y&&$.op==="add"&&U>J.length)throw new u("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",Z,$,Q);let B=LJ[$.op].call($,J,U,Q);if(B.test===!1)throw new u("Test operation failed","TEST_OPERATION_FAILED",Z,$,Q);return B}}else if(z>=K){let B=P0[$.op].call($,J,U,Q);if(B.test===!1)throw new u("Test operation failed","TEST_OPERATION_FAILED",Z,$,Q);return B}if(J=J[U],Y&&z<K&&(!J||typeof J!=="object"))throw new u("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",Z,$,Q)}}}function z0(Q,$,Y,q=!0,W=!0){if(Y){if(!Array.isArray($))throw new u("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY")}if(!q)Q=qQ(Q);let Z=Array($.length);for(let G=0,J=$.length;G<J;G++)Z[G]=oQ(Q,$[G],Y,!0,W,G),Q=Z[G].newDocument;return Z.newDocument=Q,Z}function N1(Q,$,Y){let q=oQ(Q,$);if(q.test===!1)throw new u("Test operation failed","TEST_OPERATION_FAILED",Y,$,Q);return q.newDocument}function h0(Q,$,Y,q){if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new u("Operation is not an object","OPERATION_NOT_AN_OBJECT",$,Q,Y);else if(!P0[Q.op])throw new u("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",$,Q,Y);else if(typeof Q.path!=="string")throw new u("Operation `path` property is not a string","OPERATION_PATH_INVALID",$,Q,Y);else if(Q.path.indexOf("/")!==0&&Q.path.length>0)throw new u('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",$,Q,Y);else if((Q.op==="move"||Q.op==="copy")&&typeof Q.from!=="string")throw new u("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",$,Q,Y);else if((Q.op==="add"||Q.op==="replace"||Q.op==="test")&&Q.value===void 0)throw new u("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",$,Q,Y);else if((Q.op==="add"||Q.op==="replace"||Q.op==="test")&&b$(Q.value))throw new u("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",$,Q,Y);else if(Y){if(Q.op=="add"){var W=Q.path.split("/").length,Z=q.split("/").length;if(W!==Z+1&&W!==Z)throw new u("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",$,Q,Y)}else if(Q.op==="replace"||Q.op==="remove"||Q.op==="_get"){if(Q.path!==q)throw new u("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",$,Q,Y)}else if(Q.op==="move"||Q.op==="copy"){var G=d8([{op:"_get",path:Q.from,value:void 0}],Y);if(G&&G.name==="OPERATION_PATH_UNRESOLVABLE")throw new u("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",$,Q,Y)}}}function d8(Q,$,Y){try{if(!Array.isArray(Q))throw new u("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if($)z0(qQ($),qQ(Q),Y||!0);else{Y=Y||h0;for(var q=0;q<Q.length;q++)Y(Q[q],q,$,void 0)}}catch(W){if(W instanceof u)return W;else throw W}}function S0(Q,$){if(Q===$)return!0;if(Q&&$&&typeof Q=="object"&&typeof $=="object"){var Y=Array.isArray(Q),q=Array.isArray($),W,Z,G;if(Y&&q){if(Z=Q.length,Z!=$.length)return!1;for(W=Z;W--!==0;)if(!S0(Q[W],$[W]))return!1;return!0}if(Y!=q)return!1;var J=Object.keys(Q);if(Z=J.length,Z!==Object.keys($).length)return!1;for(W=Z;W--!==0;)if(!$.hasOwnProperty(J[W]))return!1;for(W=Z;W--!==0;)if(G=J[W],!S0(Q[G],$[G]))return!1;return!0}return Q!==Q&&$!==$}/*!
|
|
63
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
64
|
+
* (c) 2013-2021 Joachim Wester
|
|
65
|
+
* MIT license
|
|
66
|
+
*/function B1(Q,$,Y,q,W){if($===Q)return;if(typeof $.toJSON==="function")$=$.toJSON();var Z=f$($),G=f$(Q),J=!1;for(var z=G.length-1;z>=0;z--){var K=G[z],X=Q[K];if(h$($,K)&&!($[K]===void 0&&X!==void 0&&Array.isArray($)===!1)){var U=$[K];if(typeof X=="object"&&X!=null&&typeof U=="object"&&U!=null&&Array.isArray(X)===Array.isArray(U))B1(X,U,Y,q+"/"+hQ(K),W);else if(X!==U){if(W)Y.push({op:"test",path:q+"/"+hQ(K),value:qQ(X)});Y.push({op:"replace",path:q+"/"+hQ(K),value:qQ(U)})}}else if(Array.isArray(Q)===Array.isArray($)){if(W)Y.push({op:"test",path:q+"/"+hQ(K),value:qQ(X)});Y.push({op:"remove",path:q+"/"+hQ(K)}),J=!0}else{if(W)Y.push({op:"test",path:q,value:Q});Y.push({op:"replace",path:q,value:$})}}if(!J&&Z.length==G.length)return;for(var z=0;z<Z.length;z++){var K=Z[z];if(!h$(Q,K)&&$[K]!==void 0)Y.push({op:"add",path:q+"/"+hQ(K),value:qQ($[K])})}}function PJ(Q,$,Y=!1){var q=[];return B1(Q,$,q,"",Y),q}var M7={...U1,JsonPatchError:d$,deepClone:qQ,escapePathComponent:hQ,unescapePathComponent:m$};var y7=M({LogStreamCallbackHandler:()=>u$,RunLog:()=>p$,RunLogPatch:()=>yQ,isLogStreamHandler:()=>p8}),yQ=class{ops;constructor(Q){this.ops=Q.ops??[]}concat(Q){let $=this.ops.concat(Q.ops),Y=z0({},$);return new p$({ops:$,state:Y[Y.length-1].newDocument})}},p$=class Q extends yQ{state;constructor($){super($);this.state=$.state}concat($){let Y=this.ops.concat($.ops),q=z0(this.state,$.ops);return new Q({ops:Y,state:q[q.length-1].newDocument})}static fromRunLogPatch($){let Y=z0({},$.ops);return new Q({ops:$.ops,state:Y[Y.length-1].newDocument})}},p8=(Q)=>Q.name==="log_stream_tracer";async function F1(Q,$){if($==="original")throw Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");let{inputs:Y}=Q;if(["retriever","llm","prompt"].includes(Q.run_type))return Y;if(Object.keys(Y).length===1&&Y?.input==="")return;return Y.input}async function V1(Q,$){let{outputs:Y}=Q;if($==="original")return Y;if(["retriever","llm","prompt"].includes(Q.run_type))return Y;if(Y!==void 0&&Object.keys(Y).length===1&&Y?.output!==void 0)return Y.output;return Y}function SJ(Q){return Q!==void 0&&Q.message!==void 0}var u$=class extends EQ{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(Q){super({_awaitHandler:!0,...Q});this.autoClose=Q?.autoClose??!0,this.includeNames=Q?.includeNames,this.includeTypes=Q?.includeTypes,this.includeTags=Q?.includeTags,this.excludeNames=Q?.excludeNames,this.excludeTypes=Q?.excludeTypes,this.excludeTags=Q?.excludeTags,this._schemaFormat=Q?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=YQ.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(Q){}_includeRun(Q){if(Q.id===this.rootId)return!1;let $=Q.tags??[],Y=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;if(this.includeNames!==void 0)Y=Y||this.includeNames.includes(Q.name);if(this.includeTypes!==void 0)Y=Y||this.includeTypes.includes(Q.run_type);if(this.includeTags!==void 0)Y=Y||$.find((q)=>this.includeTags?.includes(q))!==void 0;if(this.excludeNames!==void 0)Y=Y&&!this.excludeNames.includes(Q.name);if(this.excludeTypes!==void 0)Y=Y&&!this.excludeTypes.includes(Q.run_type);if(this.excludeTags!==void 0)Y=Y&&$.every((q)=>!this.excludeTags?.includes(q));return Y}async*tapOutputIterable(Q,$){for await(let Y of $){if(Q!==this.rootId){let q=this.keyMapByRunId[Q];if(q)await this.writer.write(new yQ({ops:[{op:"add",path:`/logs/${q}/streamed_output/-`,value:Y}]}))}yield Y}}async onRunCreate(Q){if(this.rootId===void 0)this.rootId=Q.id,await this.writer.write(new yQ({ops:[{op:"replace",path:"",value:{id:Q.id,name:Q.name,type:Q.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}));if(!this._includeRun(Q))return;if(this.counterMapByRunName[Q.name]===void 0)this.counterMapByRunName[Q.name]=0;this.counterMapByRunName[Q.name]+=1;let $=this.counterMapByRunName[Q.name];this.keyMapByRunId[Q.id]=$===1?Q.name:`${Q.name}:${$}`;let Y={id:Q.id,name:Q.name,type:Q.run_type,tags:Q.tags??[],metadata:Q.extra?.metadata??{},start_time:new Date(Q.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};if(this._schemaFormat==="streaming_events")Y.inputs=await F1(Q,this._schemaFormat);await this.writer.write(new yQ({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[Q.id]}`,value:Y}]}))}async onRunUpdate(Q){try{let $=this.keyMapByRunId[Q.id];if($===void 0)return;let Y=[];if(this._schemaFormat==="streaming_events")Y.push({op:"replace",path:`/logs/${$}/inputs`,value:await F1(Q,this._schemaFormat)});if(Y.push({op:"add",path:`/logs/${$}/final_output`,value:await V1(Q,this._schemaFormat)}),Q.end_time!==void 0)Y.push({op:"add",path:`/logs/${$}/end_time`,value:new Date(Q.end_time).toISOString()});let q=new yQ({ops:Y});await this.writer.write(q)}finally{if(Q.id===this.rootId){let $=new yQ({ops:[{op:"replace",path:"/final_output",value:await V1(Q,this._schemaFormat)}]});if(await this.writer.write($),this.autoClose)await this.writer.close()}}}async onLLMNewToken(Q,$,Y){let q=this.keyMapByRunId[Q.id];if(q===void 0)return;let W=Q.inputs.messages!==void 0,Z;if(W)if(SJ(Y?.chunk))Z=Y?.chunk;else Z=new F0({id:`run-${Q.id}`,content:$});else Z=$;let G=new yQ({ops:[{op:"add",path:`/logs/${q}/streamed_output_str/-`,value:$},{op:"add",path:`/logs/${q}/streamed_output/-`,value:Z}]});await this.writer.write(G)}};var g7=M({ChatGenerationChunk:()=>RJ,GenerationChunk:()=>f0,RUN_KEY:()=>TJ}),TJ="__run",f0=class Q{text;generationInfo;constructor($){this.text=$.text,this.generationInfo=$.generationInfo}concat($){return new Q({text:this.text+$.text,generationInfo:{...this.generationInfo,...$.generationInfo}})}},RJ=class Q extends f0{message;constructor($){super($);this.message=$.message}concat($){return new Q({text:this.text+$.text,generationInfo:{...this.generationInfo,...$.generationInfo},message:this.message.concat($.message)})}};function c$({name:Q,serialized:$}){if(Q!==void 0)return Q;if($?.name!==void 0)return $.name;else if($?.id!==void 0&&Array.isArray($?.id))return $.id[$.id.length-1];return"Unnamed"}var A1=(Q)=>Q.name==="event_stream_tracer",H1=class extends EQ{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(Q){super({_awaitHandler:!0,...Q});this.autoClose=Q?.autoClose??!0,this.includeNames=Q?.includeNames,this.includeTypes=Q?.includeTypes,this.includeTags=Q?.includeTags,this.excludeNames=Q?.excludeNames,this.excludeTypes=Q?.excludeTypes,this.excludeTags=Q?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=YQ.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(Q){}_includeRun(Q){let $=Q.tags??[],Y=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;if(this.includeNames!==void 0)Y=Y||this.includeNames.includes(Q.name);if(this.includeTypes!==void 0)Y=Y||this.includeTypes.includes(Q.runType);if(this.includeTags!==void 0)Y=Y||$.find((q)=>this.includeTags?.includes(q))!==void 0;if(this.excludeNames!==void 0)Y=Y&&!this.excludeNames.includes(Q.name);if(this.excludeTypes!==void 0)Y=Y&&!this.excludeTypes.includes(Q.runType);if(this.excludeTags!==void 0)Y=Y&&$.every((q)=>!this.excludeTags?.includes(q));return Y}async*tapOutputIterable(Q,$){let Y=await $.next();if(Y.done)return;let q=this.runInfoMap.get(Q);if(q===void 0){yield Y.value;return}function W(G,J){if(G==="llm"&&typeof J==="string")return new f0({text:J});return J}let Z=this.tappedPromises.get(Q);if(Z===void 0){let G;Z=new Promise((J)=>{G=J}),this.tappedPromises.set(Q,Z);try{let J={event:`on_${q.runType}_stream`,run_id:Q,name:q.name,tags:q.tags,metadata:q.metadata,data:{}};await this.send({...J,data:{chunk:W(q.runType,Y.value)}},q),yield Y.value;for await(let z of $){if(q.runType!=="tool"&&q.runType!=="retriever")await this.send({...J,data:{chunk:W(q.runType,z)}},q);yield z}}finally{G?.()}}else{yield Y.value;for await(let G of $)yield G}}async send(Q,$){if(this.readableStreamClosed)return;if(this._includeRun($))await this.writer.write(Q)}async sendEndEvent(Q,$){let Y=this.tappedPromises.get(Q.run_id);if(Y!==void 0)Y.then(()=>{this.send(Q,$)});else await this.send(Q,$)}async onLLMStart(Q){let $=c$(Q),Y=Q.inputs.messages!==void 0?"chat_model":"llm",q={tags:Q.tags??[],metadata:Q.extra?.metadata??{},name:$,runType:Y,inputs:Q.inputs};this.runInfoMap.set(Q.id,q);let W=`on_${Y}_start`;await this.send({event:W,data:{input:Q.inputs},name:$,tags:Q.tags??[],run_id:Q.id,metadata:Q.extra?.metadata??{}},q)}async onLLMNewToken(Q,$,Y){let q=this.runInfoMap.get(Q.id),W,Z;if(q===void 0)throw Error(`onLLMNewToken: Run ID ${Q.id} not found in run map.`);if(this.runInfoMap.size===1)return;if(q.runType==="chat_model")if(Z="on_chat_model_stream",Y?.chunk===void 0)W=new F0({content:$,id:`run-${Q.id}`});else W=Y.chunk.message;else if(q.runType==="llm")if(Z="on_llm_stream",Y?.chunk===void 0)W=new f0({text:$});else W=Y.chunk;else throw Error(`Unexpected run type ${q.runType}`);await this.send({event:Z,data:{chunk:W},run_id:Q.id,name:q.name,tags:q.tags,metadata:q.metadata},q)}async onLLMEnd(Q){let $=this.runInfoMap.get(Q.id);this.runInfoMap.delete(Q.id);let Y;if($===void 0)throw Error(`onLLMEnd: Run ID ${Q.id} not found in run map.`);let q=Q.outputs?.generations,W;if($.runType==="chat_model"){for(let Z of q??[]){if(W!==void 0)break;W=Z[0]?.message}Y="on_chat_model_end"}else if($.runType==="llm")W={generations:q?.map((Z)=>{return Z.map((G)=>{return{text:G.text,generationInfo:G.generationInfo}})}),llmOutput:Q.outputs?.llmOutput??{}},Y="on_llm_end";else throw Error(`onLLMEnd: Unexpected run type: ${$.runType}`);await this.sendEndEvent({event:Y,data:{output:W,input:$.inputs},run_id:Q.id,name:$.name,tags:$.tags,metadata:$.metadata},$)}async onChainStart(Q){let $=c$(Q),Y=Q.run_type??"chain",q={tags:Q.tags??[],metadata:Q.extra?.metadata??{},name:$,runType:Q.run_type},W={};if(Q.inputs.input===""&&Object.keys(Q.inputs).length===1)W={},q.inputs={};else if(Q.inputs.input!==void 0)W.input=Q.inputs.input,q.inputs=Q.inputs.input;else W.input=Q.inputs,q.inputs=Q.inputs;this.runInfoMap.set(Q.id,q),await this.send({event:`on_${Y}_start`,data:W,name:$,tags:Q.tags??[],run_id:Q.id,metadata:Q.extra?.metadata??{}},q)}async onChainEnd(Q){let $=this.runInfoMap.get(Q.id);if(this.runInfoMap.delete(Q.id),$===void 0)throw Error(`onChainEnd: Run ID ${Q.id} not found in run map.`);let Y=`on_${Q.run_type}_end`,q=Q.inputs??$.inputs??{},W={output:Q.outputs?.output??Q.outputs,input:q};if(q.input&&Object.keys(q).length===1)W.input=q.input,$.inputs=q.input;await this.sendEndEvent({event:Y,data:W,run_id:Q.id,name:$.name,tags:$.tags,metadata:$.metadata??{}},$)}async onToolStart(Q){let $=c$(Q),Y={tags:Q.tags??[],metadata:Q.extra?.metadata??{},name:$,runType:"tool",inputs:Q.inputs??{}};this.runInfoMap.set(Q.id,Y),await this.send({event:"on_tool_start",data:{input:Q.inputs??{}},name:$,run_id:Q.id,tags:Q.tags??[],metadata:Q.extra?.metadata??{}},Y)}async onToolEnd(Q){let $=this.runInfoMap.get(Q.id);if(this.runInfoMap.delete(Q.id),$===void 0)throw Error(`onToolEnd: Run ID ${Q.id} not found in run map.`);if($.inputs===void 0)throw Error(`onToolEnd: Run ID ${Q.id} is a tool call, and is expected to have traced inputs.`);let Y=Q.outputs?.output===void 0?Q.outputs:Q.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:Y,input:$.inputs},run_id:Q.id,name:$.name,tags:$.tags,metadata:$.metadata},$)}async onToolError(Q){let $=this.runInfoMap.get(Q.id);if(this.runInfoMap.delete(Q.id),$===void 0)throw Error(`onToolEnd: Run ID ${Q.id} not found in run map.`);if($.inputs===void 0)throw Error(`onToolEnd: Run ID ${Q.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:$.inputs,error:Q.error},run_id:Q.id,name:$.name,tags:$.tags,metadata:$.metadata},$)}async onRetrieverStart(Q){let $=c$(Q),Y={tags:Q.tags??[],metadata:Q.extra?.metadata??{},name:$,runType:"retriever",inputs:{query:Q.inputs.query}};this.runInfoMap.set(Q.id,Y),await this.send({event:"on_retriever_start",data:{input:{query:Q.inputs.query}},name:$,tags:Q.tags??[],run_id:Q.id,metadata:Q.extra?.metadata??{}},Y)}async onRetrieverEnd(Q){let $=this.runInfoMap.get(Q.id);if(this.runInfoMap.delete(Q.id),$===void 0)throw Error(`onRetrieverEnd: Run ID ${Q.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:Q.outputs?.documents??Q.outputs,input:$.inputs},run_id:Q.id,name:$.name,tags:$.tags,metadata:$.metadata},$)}async handleCustomEvent(Q,$,Y){let q=this.runInfoMap.get(Y);if(q===void 0)throw Error(`handleCustomEvent: Run ID ${Y} not found in run map.`);await this.send({event:"on_custom_event",run_id:Y,name:Q,tags:q.tags,metadata:q.metadata,data:$},q)}async finish(){let Q=[...this.tappedPromises.values()];Promise.all(Q).finally(()=>{this.writer.close()})}};var u8=class extends EQ{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:Q,onStart:$,onEnd:Y,onError:q}){super({_awaitHandler:!0});this.config=Q,this.argOnStart=$,this.argOnEnd=Y,this.argOnError=q}persistRun(Q){return Promise.resolve()}async onRunCreate(Q){if(this.rootId)return;if(this.rootId=Q.id,this.argOnStart)await this.argOnStart(Q,this.config)}async onRunUpdate(Q){if(Q.id!==this.rootId)return;if(!Q.error){if(this.argOnEnd)await this.argOnEnd(Q,this.config)}else if(this.argOnError)await this.argOnError(Q,this.config)}};function g0(Q){return Q?Q.lc_runnable:!1}var D1=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(Q){this.includeNames=Q.includeNames,this.includeTypes=Q.includeTypes,this.includeTags=Q.includeTags,this.excludeNames=Q.excludeNames,this.excludeTypes=Q.excludeTypes,this.excludeTags=Q.excludeTags}includeEvent(Q,$){let Y=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,q=Q.tags??[];if(this.includeNames!==void 0)Y=Y||this.includeNames.includes(Q.name);if(this.includeTypes!==void 0)Y=Y||this.includeTypes.includes($);if(this.includeTags!==void 0)Y=Y||q.some((W)=>this.includeTags?.includes(W));if(this.excludeNames!==void 0)Y=Y&&!this.excludeNames.includes(Q.name);if(this.excludeTypes!==void 0)Y=Y&&!this.excludeTypes.includes($);if(this.excludeTags!==void 0)Y=Y&&q.every((W)=>!this.excludeTags?.includes(W));return Y}},w1=(Q)=>{return btoa(Q).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")};function c8(Q){return Q.replace(/[^a-zA-Z-_0-9]/g,"_")}var MJ=["*","_","`"];function _J(Q){let $="";for(let[Y,q]of Object.entries(Q))$+=` classDef ${Y} ${q};
|
|
67
|
+
`;return $}function O1(Q,$,Y){let{firstNode:q,lastNode:W,nodeColors:Z,withStyles:G=!0,curveStyle:J="linear",wrapLabelNWords:z=9}=Y??{},K=G?`%%{init: {'flowchart': {'curve': '${J}'}}}%%
|
|
68
|
+
graph TD;
|
|
69
|
+
`:`graph TD;
|
|
70
|
+
`;if(G){let D={["default"]:"{0}({1})"};if(q!==void 0)D[q]="{0}([{1}]):::first";if(W!==void 0)D[W]="{0}([{1}]):::last";for(let[w,S]of Object.entries(Q)){let H=S.name.split(":").pop()??"",R=MJ.some((y)=>H.startsWith(y)&&H.endsWith(y))?`<p>${H}</p>`:H;if(Object.keys(S.metadata??{}).length)R+=`<hr/><small><em>${Object.entries(S.metadata??{}).map(([y,b])=>`${y} = ${b}`).join(`
|
|
71
|
+
`)}</em></small>`;let T=(D[w]??D.default).replace("{0}",c8(w)).replace("{1}",R);K+=` ${T}
|
|
72
|
+
`}}let X={};for(let A of $){let D=A.source.split(":"),w=A.target.split(":"),S=D.filter((H,R)=>H===w[R]).join(":");if(!X[S])X[S]=[];X[S].push(A)}let U=new Set;function N(A){return[...A].sort((D,w)=>{return D.split(":").length-w.split(":").length})}function B(A,D){let w=A.length===1&&A[0].source===A[0].target;if(D&&!w){let H=D.split(":").pop();if(U.has(D))throw Error(`Found duplicate subgraph '${H}' at '${D} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);U.add(D),K+=` subgraph ${H}
|
|
73
|
+
`}let S=N(Object.keys(X).filter((H)=>H.startsWith(`${D}:`)&&H!==D&&H.split(":").length===D.split(":").length+1));for(let H of S)B(X[H],H);for(let H of A){let{source:R,target:T,data:y,conditional:b}=H,g="";if(y!==void 0){let WQ=y,XQ=WQ.split(" ");if(XQ.length>z)WQ=Array.from({length:Math.ceil(XQ.length/z)},(X0,nQ)=>XQ.slice(nQ*z,(nQ+1)*z).join(" ")).join(" <br> ");g=b?` -. ${WQ} .-> `:` -- ${WQ} --> `}else g=b?" -.-> ":" --> ";K+=` ${c8(R)}${g}${c8(T)};
|
|
74
|
+
`}if(D&&!w)K+=` end
|
|
75
|
+
`}B(X[""]??[],"");for(let A in X)if(!A.includes(":")&&A!=="")B(X[A],A);if(G)K+=_J(Z??{});return K}async function E1(Q,$){let Y=$?.backgroundColor??"white",q=$?.imageType??"png",W=w1(Q);if(Y!==void 0){if(!/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(Y))Y=`!${Y}`}let Z=`https://mermaid.ink/img/${W}?bgColor=${Y}&type=${q}`,G=await fetch(Z);if(!G.ok)throw Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${G.status}`,`Status text: ${G.statusText}`].join(`
|
|
76
|
+
`));return await G.blob()}Q0();var ZN=M({Graph:()=>l$});function IJ(Q,$){if(Q!==void 0&&!m0(Q))return Q;else if(g0($))try{let Y=$.getName();return Y=Y.startsWith("Runnable")?Y.slice(8):Y,Y}catch{return $.getName()}else return $.name??"UnknownSchema"}function xJ(Q){if(g0(Q.data))return{type:"runnable",data:{id:Q.data.lc_id,name:Q.data.getName()}};else return{type:"schema",data:{...b8(Q.data.schema),title:Q.data.name}}}var l$=class Q{nodes={};edges=[];constructor($){this.nodes=$?.nodes??this.nodes,this.edges=$?.edges??this.edges}toJSON(){let $={};return Object.values(this.nodes).forEach((Y,q)=>{$[Y.id]=m0(Y.id)?q:Y.id}),{nodes:Object.values(this.nodes).map((Y)=>({id:$[Y.id],...xJ(Y)})),edges:this.edges.map((Y)=>{let q={source:$[Y.source],target:$[Y.target]};if(typeof Y.data<"u")q.data=Y.data;if(typeof Y.conditional<"u")q.conditional=Y.conditional;return q})}}addNode($,Y,q){if(Y!==void 0&&this.nodes[Y]!==void 0)throw Error(`Node with id ${Y} already exists`);let W=Y??pQ(),Z={id:W,data:$,name:IJ(Y,$),metadata:q};return this.nodes[W]=Z,Z}removeNode($){delete this.nodes[$.id],this.edges=this.edges.filter((Y)=>Y.source!==$.id&&Y.target!==$.id)}addEdge($,Y,q,W){if(this.nodes[$.id]===void 0)throw Error(`Source node ${$.id} not in graph`);if(this.nodes[Y.id]===void 0)throw Error(`Target node ${Y.id} not in graph`);let Z={source:$.id,target:Y.id,data:q,conditional:W};return this.edges.push(Z),Z}firstNode(){return L1(this)}lastNode(){return P1(this)}extend($,Y=""){let q=Y;if(Object.values($.nodes).map((z)=>z.id).every(m0))q="";let W=(z)=>{return q?`${q}:${z}`:z};Object.entries($.nodes).forEach(([z,K])=>{this.nodes[W(z)]={...K,id:W(z)}});let Z=$.edges.map((z)=>{return{...z,source:W(z.source),target:W(z.target)}});this.edges=[...this.edges,...Z];let G=$.firstNode(),J=$.lastNode();return[G?{id:W(G.id),data:G.data}:void 0,J?{id:W(J.id),data:J.data}:void 0]}trimFirstNode(){let $=this.firstNode();if($&&L1(this,[$.id]))this.removeNode($)}trimLastNode(){let $=this.lastNode();if($&&P1(this,[$.id]))this.removeNode($)}reid(){let $=Object.fromEntries(Object.values(this.nodes).map((W)=>[W.id,W.name])),Y=new Map;Object.values($).forEach((W)=>{Y.set(W,(Y.get(W)||0)+1)});let q=(W)=>{let Z=$[W];if(m0(W)&&Y.get(Z)===1)return Z;else return W};return new Q({nodes:Object.fromEntries(Object.entries(this.nodes).map(([W,Z])=>[q(W),{...Z,id:q(W)}])),edges:this.edges.map((W)=>({...W,source:q(W.source),target:q(W.target)}))})}drawMermaid($){let{withStyles:Y,curveStyle:q,nodeColors:W={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:Z}=$??{},G=this.reid(),J=G.firstNode(),z=G.lastNode();return O1(G.nodes,G.edges,{firstNode:J?.id,lastNode:z?.id,withStyles:Y,curveStyle:q,nodeColors:W,wrapLabelNWords:Z})}async drawMermaidPng($){return E1(this.drawMermaid($),{backgroundColor:$?.backgroundColor})}};function L1(Q,$=[]){let Y=new Set(Q.edges.filter((W)=>!$.includes(W.source)).map((W)=>W.target)),q=[];for(let W of Object.values(Q.nodes))if(!$.includes(W.id)&&!Y.has(W.id))q.push(W);return q.length===1?q[0]:void 0}function P1(Q,$=[]){let Y=new Set(Q.edges.filter((W)=>!$.includes(W.target)).map((W)=>W.source)),q=[];for(let W of Object.values(Q.nodes))if(!$.includes(W.id)&&!Y.has(W.id))q.push(W);return q.length===1?q[0]:void 0}function S1(Q){let $=new TextEncoder,Y=new ReadableStream({async start(q){for await(let W of Q)q.enqueue($.encode(`event: data
|
|
77
|
+
data: ${JSON.stringify(W)}
|
|
78
|
+
|
|
79
|
+
`));q.enqueue($.encode(`event: end
|
|
80
|
+
|
|
81
|
+
`)),q.close()}});return YQ.fromReadableStream(Y)}Q0();function n(Q,$){return Q&&!Array.isArray(Q)&&!(Q instanceof Date)&&typeof Q==="object"?Q:{[$]:Q}}var r=class extends RQ{lc_runnable=!0;name;getName(Q){let $=this.name??this.constructor.lc_name()??this.constructor.name;return Q?`${$}${Q}`:$}withRetry(Q){return new R1({bound:this,kwargs:{},config:{},maxAttemptNumber:Q?.stopAfterAttempt,...Q})}withConfig(Q){return new i$({bound:this,config:Q,kwargs:{}})}withFallbacks(Q){let $=Array.isArray(Q)?Q:Q.fallbacks;return new CJ({runnable:this,fallbacks:$})}_getOptionsList(Q,$=0){if(Array.isArray(Q)&&Q.length!==$)throw Error(`Passed "options" must be an array with the same length as the inputs, but got ${Q.length} options for ${$} inputs`);if(Array.isArray(Q))return Q.map(C);if($>1&&!Array.isArray(Q)&&Q.runId){console.warn("Provided runId will be used only for the first element of the batch.");let Y=Object.fromEntries(Object.entries(Q).filter(([q])=>q!=="runId"));return Array.from({length:$},(q,W)=>C(W===0?Q:Y))}return Array.from({length:$},()=>C(Q))}async batch(Q,$,Y){let q=this._getOptionsList($??{},Q.length),W=new J0({maxConcurrency:q[0]?.maxConcurrency??Y?.maxConcurrency,onFailedAttempt:(G)=>{throw G}}),Z=Q.map((G,J)=>W.call(async()=>{try{return await this.invoke(G,q[J])}catch(z){if(Y?.returnExceptions)return z;throw z}}));return Promise.all(Z)}async*_streamIterator(Q,$){yield this.invoke(Q,$)}async stream(Q,$){let Y=C($),q=new sQ({generator:this._streamIterator(Q,Y),config:Y});return await q.setup,YQ.fromAsyncGenerator(q)}_separateRunnableConfigFromCallOptions(Q){let $;if(Q===void 0)$=C(Q);else $=C({callbacks:Q.callbacks,tags:Q.tags,metadata:Q.metadata,runName:Q.runName,configurable:Q.configurable,recursionLimit:Q.recursionLimit,maxConcurrency:Q.maxConcurrency,runId:Q.runId,timeout:Q.timeout,signal:Q.signal});let Y={...Q};return delete Y.callbacks,delete Y.tags,delete Y.metadata,delete Y.runName,delete Y.configurable,delete Y.recursionLimit,delete Y.maxConcurrency,delete Y.runId,delete Y.timeout,delete Y.signal,[$,Y]}async _callWithConfig(Q,$,Y){let q=C(Y),W=await(await HQ(q))?.handleChainStart(this.toJSON(),n($,"input"),q.runId,q?.runType,void 0,void 0,q?.runName??this.getName());delete q.runId;let Z;try{Z=await jQ(Q.call(this,$,q,W),Y?.signal)}catch(G){throw await W?.handleChainError(G),G}return await W?.handleChainEnd(n(Z,"output")),Z}async _batchWithConfig(Q,$,Y,q){let W=this._getOptionsList(Y??{},$.length),Z=await Promise.all(W.map(HQ)),G=await Promise.all(Z.map(async(z,K)=>{let X=await z?.handleChainStart(this.toJSON(),n($[K],"input"),W[K].runId,W[K].runType,void 0,void 0,W[K].runName??this.getName());return delete W[K].runId,X})),J;try{J=await jQ(Q.call(this,$,W,G,q),W?.[0]?.signal)}catch(z){throw await Promise.all(G.map((K)=>K?.handleChainError(z))),z}return await Promise.all(G.map((z)=>z?.handleChainEnd(n(J,"output")))),J}_concatOutputChunks(Q,$){return k$(Q,$)}async*_transformStreamWithConfig(Q,$,Y){let q,W=!0,Z,G=!0,J=C(Y),z=await HQ(J),K=this;async function*X(){for await(let N of Q){if(W)if(q===void 0)q=N;else try{q=K._concatOutputChunks(q,N)}catch{q=void 0,W=!1}yield N}}let U;try{let N=await m8($.bind(this),X(),async()=>z?.handleChainStart(this.toJSON(),{input:""},J.runId,J.runType,void 0,void 0,J.runName??this.getName(),void 0,{lc_defers_inputs:!0}),Y?.signal,J);delete J.runId,U=N.setup;let B=U?.handlers.find(A1),A=N.output;if(B!==void 0&&U!==void 0)A=B.tapOutputIterable(U.runId,A);let D=U?.handlers.find(p8);if(D!==void 0&&U!==void 0)A=D.tapOutputIterable(U.runId,A);for await(let w of A)if(yield w,G)if(Z===void 0)Z=w;else try{Z=this._concatOutputChunks(Z,w)}catch{Z=void 0,G=!1}}catch(N){throw await U?.handleChainError(N,void 0,void 0,void 0,{inputs:n(q,"input")}),N}await U?.handleChainEnd(Z??{},void 0,void 0,void 0,{inputs:n(q,"input")})}getGraph(Q){let $=new l$,Y=$.addNode({name:`${this.getName()}Input`,schema:tQ.any()}),q=$.addNode(this),W=$.addNode({name:`${this.getName()}Output`,schema:tQ.any()});return $.addEdge(Y,q),$.addEdge(q,W),$}pipe(Q){return new M1({first:this,last:K0(Q)})}pick(Q){return this.pipe(new kJ(Q))}assign(Q){return this.pipe(new yJ(new s$({steps:Q})))}async*transform(Q,$){let Y;for await(let q of Q)if(Y===void 0)Y=q;else Y=this._concatOutputChunks(Y,q);yield*this._streamIterator(Y,C($))}async*streamLog(Q,$,Y){let q=new u$({...Y,autoClose:!1,_schemaFormat:"original"}),W=C($);yield*this._streamLog(Q,q,W)}async*_streamLog(Q,$,Y){let{callbacks:q}=Y;if(q===void 0)Y.callbacks=[$];else if(Array.isArray(q))Y.callbacks=q.concat([$]);else{let J=q.copy();J.addHandler($,!0),Y.callbacks=J}let W=this.stream(Q,Y);async function Z(){try{let J=await W;for await(let z of J){let K=new yQ({ops:[{op:"add",path:"/streamed_output/-",value:z}]});await $.writer.write(K)}}finally{await $.writer.close()}}let G=Z();try{for await(let J of $)yield J}finally{await G}}streamEvents(Q,$,Y){let q;if($.version==="v1")q=this._streamEventsV1(Q,$,Y);else if($.version==="v2")q=this._streamEventsV2(Q,$,Y);else throw Error('Only versions "v1" and "v2" of the schema are currently supported.');if($.encoding==="text/event-stream")return S1(q);else return YQ.fromAsyncGenerator(q)}async*_streamEventsV2(Q,$,Y){let q=new H1({...Y,autoClose:!1}),W=C($),Z=W.runId??FQ();W.runId=Z;let G=W.callbacks;if(G===void 0)W.callbacks=[q];else if(Array.isArray(G))W.callbacks=G.concat(q);else{let B=G.copy();B.addHandler(q,!0),W.callbacks=B}let J=new AbortController,z=this;async function K(){let B,A=null;try{if($?.signal)if("any"in AbortSignal)B=AbortSignal.any([J.signal,$.signal]);else B=$.signal,A=()=>{J.abort()},$.signal.addEventListener("abort",A,{once:!0});else B=J.signal;let D=await z.stream(Q,{...W,signal:B}),w=q.tapOutputIterable(Z,D);for await(let S of w)if(J.signal.aborted)break}finally{if(await q.finish(),B&&A)B.removeEventListener("abort",A)}}let X=K(),U=!1,N;try{for await(let B of q){if(!U){B.data.input=Q,U=!0,N=B.run_id,yield B;continue}if(B.run_id===N&&B.event.endsWith("_end")){if(B.data?.input)delete B.data.input}yield B}}finally{J.abort(),await X}}async*_streamEventsV1(Q,$,Y){let q,W=!1,Z=C($),G=Z.tags??[],J=Z.metadata??{},z=Z.runName??this.getName(),K=new u$({...Y,autoClose:!1,_schemaFormat:"streaming_events"}),X=new D1({...Y}),U=this._streamLog(Q,K,Z);for await(let B of U){if(!q)q=p$.fromRunLogPatch(B);else q=q.concat(B);if(q.state===void 0)throw Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!W){W=!0;let S={...q.state},H={run_id:S.id,event:`on_${S.type}_start`,name:z,tags:G,metadata:J,data:{input:Q}};if(X.includeEvent(H,S.type))yield H}let A=B.ops.filter((S)=>S.path.startsWith("/logs/")).map((S)=>S.path.split("/")[2]),D=[...new Set(A)];for(let S of D){let H,R={},T=q.state.logs[S];if(T.end_time===void 0)if(T.streamed_output.length>0)H="stream";else H="start";else H="end";if(H==="start"){if(T.inputs!==void 0)R.input=T.inputs}else if(H==="end"){if(T.inputs!==void 0)R.input=T.inputs;R.output=T.final_output}else if(H==="stream"){let y=T.streamed_output.length;if(y!==1)throw Error(`Expected exactly one chunk of streamed output, got ${y} instead. Encountered in: "${T.name}"`);R={chunk:T.streamed_output[0]},T.streamed_output=[]}yield{event:`on_${T.type}_${H}`,name:T.name,run_id:T.id,tags:T.tags,metadata:T.metadata,data:R}}let{state:w}=q;if(w.streamed_output.length>0){let S=w.streamed_output.length;if(S!==1)throw Error(`Expected exactly one chunk of streamed output, got ${S} instead. Encountered in: "${w.name}"`);let H={chunk:w.streamed_output[0]};w.streamed_output=[];let R={event:`on_${w.type}_stream`,run_id:w.id,tags:G,metadata:J,name:z,data:H};if(X.includeEvent(R,w.type))yield R}}let N=q?.state;if(N!==void 0){let B={event:`on_${N.type}_end`,name:z,run_id:N.id,tags:G,metadata:J,data:{output:N.final_output}};if(X.includeEvent(B,N.type))yield B}}static isRunnable(Q){return g0(Q)}withListeners({onStart:Q,onEnd:$,onError:Y}){return new i$({bound:this,config:{},configFactories:[(q)=>({callbacks:[new u8({config:q,onStart:Q,onEnd:$,onError:Y})]})]})}asTool(Q){return bJ(this,Q)}},i$=class Q extends r{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor($){super($);this.bound=$.bound,this.kwargs=$.kwargs,this.config=$.config,this.configFactories=$.configFactories}getName($){return this.bound.getName($)}async _mergeConfig(...$){let Y=x0(this.config,...$);return x0(Y,...this.configFactories?await Promise.all(this.configFactories.map(async(q)=>await q(Y))):[])}withConfig($){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...$}})}withRetry($){return new R1({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:$?.stopAfterAttempt,...$})}async invoke($,Y){return this.bound.invoke($,await this._mergeConfig(Y,this.kwargs))}async batch($,Y,q){let W=Array.isArray(Y)?await Promise.all(Y.map(async(Z)=>this._mergeConfig(C(Z),this.kwargs))):await this._mergeConfig(C(Y),this.kwargs);return this.bound.batch($,W,q)}_concatOutputChunks($,Y){return this.bound._concatOutputChunks($,Y)}async*_streamIterator($,Y){yield*this.bound._streamIterator($,await this._mergeConfig(C(Y),this.kwargs))}async stream($,Y){return this.bound.stream($,await this._mergeConfig(C(Y),this.kwargs))}async*transform($,Y){yield*this.bound.transform($,await this._mergeConfig(C(Y),this.kwargs))}streamEvents($,Y,q){let W=this,Z=async function*(){yield*W.bound.streamEvents($,{...await W._mergeConfig(C(Y),W.kwargs),version:Y.version},q)};return YQ.fromAsyncGenerator(Z())}static isRunnableBinding($){return $.bound&&r.isRunnable($.bound)}withListeners({onStart:$,onEnd:Y,onError:q}){return new Q({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[(W)=>({callbacks:[new u8({config:W,onStart:$,onEnd:Y,onError:q})]})]})}},IN=class Q extends r{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor($){super($);this.bound=$.bound}async invoke($,Y){return this._callWithConfig(this._invoke.bind(this),$,Y)}async _invoke($,Y,q){return this.bound.batch($,l(Y,{callbacks:q?.getChild()}))}withListeners({onStart:$,onEnd:Y,onError:q}){return new Q({bound:this.bound.withListeners({onStart:$,onEnd:Y,onError:q})})}},R1=class extends i${static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(Q){super(Q);this.maxAttemptNumber=Q.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=Q.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(Q,$,Y){let q=Q>1?`retry:attempt:${Q}`:void 0;return l($,{callbacks:Y?.getChild(q)})}async _invoke(Q,$,Y){return k0((q)=>super.invoke(Q,this._patchConfigForRetry(q,$,Y)),{onFailedAttempt:({error:q})=>this.onFailedAttempt(q,Q),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(Q,$){return this._callWithConfig(this._invoke.bind(this),Q,$)}async _batch(Q,$,Y,q){let W={};try{await k0(async(Z)=>{let G=Q.map((U,N)=>N).filter((U)=>W[U.toString()]===void 0||W[U.toString()]instanceof Error),J=G.map((U)=>Q[U]),z=G.map((U)=>this._patchConfigForRetry(Z,$?.[U],Y?.[U])),K=await super.batch(J,z,{...q,returnExceptions:!0}),X;for(let U=0;U<K.length;U+=1){let N=K[U],B=G[U];if(N instanceof Error){if(X===void 0)X=N,X.input=J[U]}W[B.toString()]=N}if(X)throw X;return K},{onFailedAttempt:({error:Z})=>this.onFailedAttempt(Z,Z.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(Z){if(q?.returnExceptions!==!0)throw Z}return Object.keys(W).sort((Z,G)=>parseInt(Z,10)-parseInt(G,10)).map((Z)=>W[parseInt(Z,10)])}async batch(Q,$,Y){return this._batchWithConfig(this._batch.bind(this),Q,$,Y)}},M1=class Q extends r{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor($){super($);this.first=$.first,this.middle=$.middle??this.middle,this.last=$.last,this.name=$.name,this.omitSequenceTags=$.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke($,Y){let q=C(Y),W=await(await HQ(q))?.handleChainStart(this.toJSON(),n($,"input"),q.runId,void 0,void 0,void 0,q?.runName);delete q.runId;let Z=$,G;try{let J=[this.first,...this.middle];for(let z=0;z<J.length;z+=1)Z=await jQ(J[z].invoke(Z,l(q,{callbacks:W?.getChild(this.omitSequenceTags?void 0:`seq:step:${z+1}`)})),Y?.signal);if(Y?.signal?.aborted)throw iQ(Y.signal);G=await this.last.invoke(Z,l(q,{callbacks:W?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(J){throw await W?.handleChainError(J),J}return await W?.handleChainEnd(n(G,"output")),G}async batch($,Y,q){let W=this._getOptionsList(Y??{},$.length),Z=await Promise.all(W.map(HQ)),G=await Promise.all(Z.map(async(z,K)=>{let X=await z?.handleChainStart(this.toJSON(),n($[K],"input"),W[K].runId,void 0,void 0,void 0,W[K].runName);return delete W[K].runId,X})),J=$;try{for(let z=0;z<this.steps.length;z+=1)J=await jQ(this.steps[z].batch(J,G.map((K,X)=>{let U=K?.getChild(this.omitSequenceTags?void 0:`seq:step:${z+1}`);return l(W[X],{callbacks:U})}),q),W[0]?.signal)}catch(z){throw await Promise.all(G.map((K)=>K?.handleChainError(z))),z}return await Promise.all(G.map((z)=>z?.handleChainEnd(n(J,"output")))),J}_concatOutputChunks($,Y){return this.last._concatOutputChunks($,Y)}async*_streamIterator($,Y){let q=await HQ(Y),{runId:W,...Z}=Y??{},G=await q?.handleChainStart(this.toJSON(),n($,"input"),W,void 0,void 0,void 0,Z?.runName),J=[this.first,...this.middle,this.last],z=!0,K;async function*X(){yield $}try{let U=J[0].transform(X(),l(Z,{callbacks:G?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let N=1;N<J.length;N+=1)U=await J[N].transform(U,l(Z,{callbacks:G?.getChild(this.omitSequenceTags?void 0:`seq:step:${N+1}`)}));for await(let N of U)if(Y?.signal?.throwIfAborted(),yield N,z)if(K===void 0)K=N;else try{K=this._concatOutputChunks(K,N)}catch{K=void 0,z=!1}}catch(U){throw await G?.handleChainError(U),U}await G?.handleChainEnd(n(K,"output"))}getGraph($){let Y=new l$,q=null;return this.steps.forEach((W,Z)=>{let G=W.getGraph($);if(Z!==0)G.trimFirstNode();if(Z!==this.steps.length-1)G.trimLastNode();Y.extend(G);let J=G.firstNode();if(!J)throw Error(`Runnable ${W} has no first node`);if(q)Y.addEdge(q,J);q=G.lastNode()}),Y}pipe($){if(Q.isRunnableSequence($))return new Q({first:this.first,middle:this.middle.concat([this.last,$.first,...$.middle]),last:$.last,name:this.name??$.name});else return new Q({first:this.first,middle:[...this.middle,this.last],last:K0($),name:this.name})}static isRunnableSequence($){return Array.isArray($.middle)&&r.isRunnable($)}static from([$,...Y],q){let W={};if(typeof q==="string")W.name=q;else if(q!==void 0)W=q;return new Q({...W,first:K0($),middle:Y.slice(0,-1).map(K0),last:K0(Y[Y.length-1])})}},s$=class Q extends r{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor($){super($);this.steps={};for(let[Y,q]of Object.entries($.steps))this.steps[Y]=K0(q)}static from($){return new Q({steps:$})}async invoke($,Y){let q=C(Y),W=await(await HQ(q))?.handleChainStart(this.toJSON(),{input:$},q.runId,void 0,void 0,void 0,q?.runName);delete q.runId;let Z={};try{let G=Object.entries(this.steps).map(async([J,z])=>{Z[J]=await z.invoke($,l(q,{callbacks:W?.getChild(`map:key:${J}`)}))});await jQ(Promise.all(G),Y?.signal)}catch(G){throw await W?.handleChainError(G),G}return await W?.handleChainEnd(Z),Z}async*_transform($,Y,q){let W={...this.steps},Z=y$($,Object.keys(W).length),G=new Map(Object.entries(W).map(([J,z],K)=>{let X=z.transform(Z[K],l(q,{callbacks:Y?.getChild(`map:key:${J}`)}));return[J,X.next().then((U)=>({key:J,gen:X,result:U}))]}));while(G.size){let{key:J,result:z,gen:K}=await jQ(Promise.race(G.values()),q?.signal);if(G.delete(J),!z.done)yield{[J]:z.value},G.set(J,K.next().then((X)=>({key:J,gen:K,result:X})))}}transform($,Y){return this._transformStreamWithConfig($,this._transform.bind(this),Y)}async stream($,Y){async function*q(){yield $}let W=C(Y),Z=new sQ({generator:this.transform(q(),W),config:W});return await Z.setup,YQ.fromAsyncGenerator(Z)}},jJ=class Q extends r{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor($){super($);if(!H$($.func))throw Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=$.func}async invoke($,Y){let[q]=this._getOptionsList(Y??{},1),W=await HQ(q);return jQ(this.func(l(q,{callbacks:W}),$),q?.signal)}async*_streamIterator($,Y){let[q]=this._getOptionsList(Y??{},1),W=await this.invoke($,Y);if(_$(W)){for await(let Z of W)q?.signal?.throwIfAborted(),yield Z;return}if(q1(W)){while(!0){q?.signal?.throwIfAborted();let Z=W.next();if(Z.done)break;yield Z.value}return}yield W}static from($){return new Q({func:$})}};function vJ(Q){if(H$(Q))throw Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var _1=class Q extends r{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor($){if(H$($.func))return jJ.from($.func);super($);vJ($.func),this.func=$.func}static from($){return new Q({func:$})}async _invoke($,Y,q){return new Promise((W,Z)=>{let G=l(Y,{callbacks:q?.getChild(),recursionLimit:(Y?.recursionLimit??O$)-1});a.runWithConfig(DQ(G),async()=>{try{let J=await this.func($,{...G});if(J&&r.isRunnable(J)){if(Y?.recursionLimit===0)throw Error("Recursion limit reached.");J=await J.invoke($,{...G,recursionLimit:(G.recursionLimit??O$)-1})}else if(_$(J)){let z;for await(let K of I$(G,J))if(Y?.signal?.throwIfAborted(),z===void 0)z=K;else try{z=this._concatOutputChunks(z,K)}catch{z=K}J=z}else if(h8(J)){let z;for(let K of f8(G,J))if(Y?.signal?.throwIfAborted(),z===void 0)z=K;else try{z=this._concatOutputChunks(z,K)}catch{z=K}J=z}W(J)}catch(J){Z(J)}})})}async invoke($,Y){return this._callWithConfig(this._invoke.bind(this),$,Y)}async*_transform($,Y,q){let W;for await(let J of $)if(W===void 0)W=J;else try{W=this._concatOutputChunks(W,J)}catch{W=J}let Z=l(q,{callbacks:Y?.getChild(),recursionLimit:(q?.recursionLimit??O$)-1}),G=await new Promise((J,z)=>{a.runWithConfig(DQ(Z),async()=>{try{J(await this.func(W,{...Z,config:Z}))}catch(K){z(K)}})});if(G&&r.isRunnable(G)){if(q?.recursionLimit===0)throw Error("Recursion limit reached.");let J=await G.stream(W,Z);for await(let z of J)yield z}else if(_$(G))for await(let J of I$(Z,G))q?.signal?.throwIfAborted(),yield J;else if(h8(G))for(let J of f8(Z,G))q?.signal?.throwIfAborted(),yield J;else yield G}transform($,Y){return this._transformStreamWithConfig($,this._transform.bind(this),Y)}async stream($,Y){async function*q(){yield $}let W=C(Y),Z=new sQ({generator:this.transform(q(),W),config:W});return await Z.setup,YQ.fromAsyncGenerator(Z)}},xN=class extends s${},CJ=class extends r{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(Q){super(Q);this.runnable=Q.runnable,this.fallbacks=Q.fallbacks}*runnables(){yield this.runnable;for(let Q of this.fallbacks)yield Q}async invoke(Q,$){let Y=C($),q=await HQ(Y),{runId:W,...Z}=Y,G=await q?.handleChainStart(this.toJSON(),n(Q,"input"),W,void 0,void 0,void 0,Z?.runName),J=l(Z,{callbacks:G?.getChild()});return await a.runWithConfig(J,async()=>{let z;for(let K of this.runnables()){Y?.signal?.throwIfAborted();try{let X=await K.invoke(Q,J);return await G?.handleChainEnd(n(X,"output")),X}catch(X){if(z===void 0)z=X}}if(z===void 0)throw Error("No error stored at end of fallback.");throw await G?.handleChainError(z),z})}async*_streamIterator(Q,$){let Y=C($),q=await HQ(Y),{runId:W,...Z}=Y,G=await q?.handleChainStart(this.toJSON(),n(Q,"input"),W,void 0,void 0,void 0,Z?.runName),J,z;for(let X of this.runnables()){Y?.signal?.throwIfAborted();let U=l(Z,{callbacks:G?.getChild()});try{z=I$(U,await X.stream(Q,U));break}catch(N){if(J===void 0)J=N}}if(z===void 0){let X=J??Error("No error stored at end of fallback.");throw await G?.handleChainError(X),X}let K;try{for await(let X of z){yield X;try{K=K===void 0?K:this._concatOutputChunks(K,X)}catch{K=void 0}}}catch(X){throw await G?.handleChainError(X),X}await G?.handleChainEnd(n(K,"output"))}async batch(Q,$,Y){if(Y?.returnExceptions)throw Error("Not implemented.");let q=this._getOptionsList($??{},Q.length),W=await Promise.all(q.map((J)=>HQ(J))),Z=await Promise.all(W.map(async(J,z)=>{let K=await J?.handleChainStart(this.toJSON(),n(Q[z],"input"),q[z].runId,void 0,void 0,void 0,q[z].runName);return delete q[z].runId,K})),G;for(let J of this.runnables()){q[0].signal?.throwIfAborted();try{let z=await J.batch(Q,Z.map((K,X)=>l(q[X],{callbacks:K?.getChild()})),Y);return await Promise.all(Z.map((K,X)=>K?.handleChainEnd(n(z[X],"output")))),z}catch(z){if(G===void 0)G=z}}if(!G)throw Error("No error stored at end of fallbacks.");throw await Promise.all(Z.map((J)=>J?.handleChainError(G))),G}};function K0(Q){if(typeof Q==="function")return new _1({func:Q});else if(r.isRunnable(Q))return Q;else if(!Array.isArray(Q)&&typeof Q==="object"){let $={};for(let[Y,q]of Object.entries(Q))$[Y]=K0(q);return new s$({steps:$})}else throw Error(`Expected a Runnable, function or object.
|
|
82
|
+
Instead got an unsupported type.`)}var yJ=class extends r{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(Q){if(Q instanceof s$)Q={mapper:Q};super(Q);this.mapper=Q.mapper}async invoke(Q,$){let Y=await this.mapper.invoke(Q,$);return{...Q,...Y}}async*_transform(Q,$,Y){let q=this.mapper.getStepsKeys(),[W,Z]=y$(Q),G=this.mapper.transform(Z,l(Y,{callbacks:$?.getChild()})),J=G.next();for await(let z of W){if(typeof z!=="object"||Array.isArray(z))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof z}`);let K=Object.fromEntries(Object.entries(z).filter(([X])=>!q.includes(X)));if(Object.keys(K).length>0)yield K}yield(await J).value;for await(let z of G)yield z}transform(Q,$){return this._transformStreamWithConfig(Q,this._transform.bind(this),$)}async stream(Q,$){async function*Y(){yield Q}let q=C($),W=new sQ({generator:this.transform(Y(),q),config:q});return await W.setup,YQ.fromAsyncGenerator(W)}},kJ=class extends r{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(Q){if(typeof Q==="string"||Array.isArray(Q))Q={keys:Q};super(Q);this.keys=Q.keys}async _pick(Q){if(typeof this.keys==="string")return Q[this.keys];else{let $=this.keys.map((Y)=>[Y,Q[Y]]).filter((Y)=>Y[1]!==void 0);return $.length===0?void 0:Object.fromEntries($)}}async invoke(Q,$){return this._callWithConfig(this._pick.bind(this),Q,$)}async*_transform(Q){for await(let $ of Q){let Y=await this._pick($);if(Y!==void 0)yield Y}}transform(Q,$){return this._transformStreamWithConfig(Q,this._transform.bind(this),$)}async stream(Q,$){async function*Y(){yield Q}let q=C($),W=new sQ({generator:this.transform(Y(),q),config:q});return await W.setup,YQ.fromAsyncGenerator(W)}},T1=class extends i${name;description;schema;constructor(Q){let $=M1.from([_1.from(async(Y)=>{let q;if(fQ(Y))try{q=await P$(this.schema,Y.args)}catch{throw new U0("Received tool input did not match expected schema",JSON.stringify(Y.args))}else q=Y;return q}).withConfig({runName:`${Q.name}:parse_input`}),Q.bound]).withConfig({runName:Q.name});super({bound:$,config:Q.config??{}});this.name=Q.name,this.description=Q.description,this.schema=Q.schema}static lc_name(){return"RunnableToolLike"}};function bJ(Q,$){let Y=$.name??Q.getName(),q=$.description??sW($.schema);if(S$($.schema))return new T1({name:Y,description:q,schema:tQ.object({input:tQ.string()}).transform((W)=>W.input),bound:Q});return new T1({name:Y,description:q,schema:$.schema,bound:Q})}var uN=M({BasePromptValue:()=>o$,ChatPromptValue:()=>i8,ImagePromptValue:()=>hJ,StringPromptValue:()=>l8}),o$=class extends RQ{},l8=class extends o${static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(Q){super({value:Q});this.value=Q}toString(){return this.value}toChatMessages(){return[new eQ(this.value)]}},i8=class extends o${lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(Q){if(Array.isArray(Q))Q={messages:Q};super(Q);this.messages=Q.messages}toString(){return o0(this.messages)}toChatMessages(){return this.messages}},hJ=class extends o${lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(Q){if(!("imageUrl"in Q))Q={imageUrl:Q};super(Q);this.imageUrl=Q.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new eQ({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}};var aN=M({encodingForModel:()=>n$,getEncoding:()=>j1}),t$={},fJ=new J0({});async function j1(Q){if(!(Q in t$))t$[Q]=fJ.fetch(`https://tiktoken.pages.dev/js/${Q}.json`).then(($)=>$.json()).then(($)=>new I1($)).catch(($)=>{throw delete t$[Q],$});return await t$[Q]}async function n$(Q){return j1(x1(Q))}var JB=M({BaseLangChain:()=>a$,BaseLanguageModel:()=>uJ,calculateMaxTokens:()=>dJ,getEmbeddingContextSize:()=>gJ,getModelContextSize:()=>v1,getModelNameForTiktoken:()=>r$,isOpenAITool:()=>mJ}),r$=(Q)=>{if(Q.startsWith("gpt-5"))return"gpt-5";if(Q.startsWith("gpt-3.5-turbo-16k"))return"gpt-3.5-turbo-16k";if(Q.startsWith("gpt-3.5-turbo-"))return"gpt-3.5-turbo";if(Q.startsWith("gpt-4-32k"))return"gpt-4-32k";if(Q.startsWith("gpt-4-"))return"gpt-4";if(Q.startsWith("gpt-4o"))return"gpt-4o";return Q},gJ=(Q)=>{switch(Q){case"text-embedding-ada-002":return 8191;default:return 2046}},v1=(Q)=>{switch(r$(Q)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 400000;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128000;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128000;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8000;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 200000;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function mJ(Q){if(typeof Q!=="object"||!Q)return!1;if("type"in Q&&Q.type==="function"&&"function"in Q&&typeof Q.function==="object"&&Q.function&&"name"in Q.function&&"parameters"in Q.function)return!0;return!1}var dJ=async({prompt:Q,modelName:$})=>{let Y;try{Y=(await n$(r$($))).encode(Q).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),Y=Math.ceil(Q.length/4)}return v1($)-Y},pJ=()=>!1,a$=class extends r{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(Q){super(Q);this.verbose=Q.verbose??pJ(),this.callbacks=Q.callbacks,this.tags=Q.tags??[],this.metadata=Q.metadata??{},this._addVersion("@langchain/core","1.1.31")}_addVersion(Q,$){let Y=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof Y==="object"&&Y!==null?Y:{},[Q]:$}}}},uJ=class extends a${get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:Q,callbackManager:$,...Y}){let{cache:q,...W}=Y;super({callbacks:Q??$,...W});if(typeof q==="object")this.cache=q;else if(q)this.cache=g8.global();else this.cache=void 0;this.caller=new J0(Y??{})}_encoding;async getNumTokens(Q){let $;if(typeof Q==="string")$=Q;else $=Q.map((q)=>{if(typeof q==="string")return q;if(q.type==="text"&&"text"in q)return q.text;return""}).join("");let Y=Math.ceil($.length/4);if(!this._encoding)try{this._encoding=await n$("modelName"in this?r$(this.modelName):"gpt2")}catch(q){console.warn("Failed to calculate number of tokens, falling back to approximate count",q)}if(this._encoding)try{Y=this._encoding.encode($).length}catch(q){console.warn("Failed to calculate number of tokens, falling back to approximate count",q)}return Y}static _convertInputToPromptValue(Q){if(typeof Q==="string")return new l8(Q);else if(Array.isArray(Q))return new i8(Q.map(r6));else return Q}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:Q,...$}){let Y={...this._identifyingParams(),...$,_type:this._llmType(),_model:this._modelType()};return Object.entries(Y).filter(([q,W])=>W!==void 0).map(([q,W])=>`${q}:${JSON.stringify(W)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(Q){throw Error("Use .toJSON() instead")}get profile(){return{}}};function s8(Q){return Q!==void 0&&Array.isArray(Q.lc_namespace)}function o8(Q){return Q!==void 0&&r.isRunnable(Q)&&"lc_name"in Q.constructor&&typeof Q.constructor.lc_name==="function"&&Q.constructor.lc_name()==="RunnableToolLike"}function t8(Q){return!!Q&&typeof Q==="object"&&"name"in Q&&"schema"in Q&&(O0(Q.schema)||Q.schema!=null&&typeof Q.schema==="object"&&("type"in Q.schema)&&typeof Q.schema.type==="string"&&["null","boolean","object","array","number","string"].includes(Q.schema.type))}function C1(Q){return t8(Q)||o8(Q)||s8(Q)}var xB=M({BaseToolkit:()=>cJ,DynamicStructuredTool:()=>f1,DynamicTool:()=>h1,StructuredTool:()=>n8,Tool:()=>b1,ToolInputParsingException:()=>U0,isLangChainTool:()=>C1,isRunnableToolLike:()=>o8,isStructuredTool:()=>s8,isStructuredToolParams:()=>t8,tool:()=>lJ}),n8=class extends a${extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(Q){super(Q??{});this.verboseParsingErrors=Q?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=Q?.responseFormat??this.responseFormat,this.defaultConfig=Q?.defaultConfig??this.defaultConfig,this.metadata=Q?.metadata??this.metadata,this.extras=Q?.extras??this.extras}async invoke(Q,$){let Y,q=C(x0(this.defaultConfig,$));if(fQ(Q))Y=Q.args,q={...q,toolCall:Q};else Y=Q;return this.call(Y,q)}async call(Q,$,Y){let q=fQ(Q)?Q.args:Q,W;if(O0(this.schema))try{W=await P$(this.schema,q)}catch(B){let A="Received tool input did not match expected schema";if(this.verboseParsingErrors)A=`${A}
|
|
83
|
+
Details: ${B.message}`;if(nW(B))A=`${A}
|
|
84
|
+
|
|
85
|
+
${y1.prettifyError(B)}`;throw new U0(A,JSON.stringify(Q))}else{let B=k1(q,this.schema);if(!B.valid){let A="Received tool input did not match expected schema";if(this.verboseParsingErrors)A=`${A}
|
|
86
|
+
Details: ${B.errors.map((D)=>`${D.keywordLocation}: ${D.error}`).join(`
|
|
87
|
+
`)}`;throw new U0(A,JSON.stringify(Q))}W=q}let Z=_0($),G=LQ.configure(Z.callbacks,this.callbacks,Z.tags||Y,this.tags,Z.metadata,this.metadata,{verbose:this.verbose}),J;if(fQ(Q))J=Q.id;if(!J&&a8(Z))J=Z.toolCall.id;let z=await G?.handleToolStart(this.toJSON(),typeof Q==="string"?Q:JSON.stringify(Q),Z.runId,void 0,void 0,void 0,Z.runName,J);delete Z.runId;let K;try{let B=await this._call(W,z,Z);K=W1(B)?await Z1(B,async(A)=>{try{await z?.handleToolEvent(A)}catch(D){await z?.handleToolError(D)}}):B}catch(B){throw await z?.handleToolError(B),B}let X,U;if(this.responseFormat==="content_and_artifact")if(Array.isArray(K)&&K.length===2)[X,U]=K;else throw Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
|
|
88
|
+
Result: ${JSON.stringify(K)}`);else X=K;let N=iJ({content:X,artifact:U,toolCallId:J,name:this.name,metadata:this.metadata});return await z?.handleToolEnd(N),N}},b1=class extends n8{schema=tQ.object({input:tQ.string().optional()}).transform((Q)=>Q.input);constructor(Q){super(Q)}call(Q,$){let Y=typeof Q==="string"||Q==null?{input:Q}:Q;return super.call(Y,$)}},h1=class extends b1{static lc_name(){return"DynamicTool"}name;description;func;constructor(Q){super(Q);this.name=Q.name,this.description=Q.description,this.func=Q.func,this.returnDirect=Q.returnDirect??this.returnDirect}async call(Q,$){let Y=_0($);if(Y.runName===void 0)Y.runName=this.name;return super.call(Q,Y)}_call(Q,$,Y){return this.func(Q,$,Y)}},f1=class extends n8{static lc_name(){return"DynamicStructuredTool"}description;func;schema;constructor(Q){super(Q);this.name=Q.name,this.description=Q.description,this.func=Q.func,this.returnDirect=Q.returnDirect??this.returnDirect,this.schema=Q.schema}async call(Q,$,Y){let q=_0($);if(q.runName===void 0)q.runName=this.name;return super.call(Q,q,Y)}_call(Q,$,Y){return this.func(Q,$,Y)}},cJ=class{getTools(){return this.tools}};function lJ(Q,$){let Y=S$($.schema),q=L0($.schema);if(!$.schema||Y||q)return new h1({...$,description:$.description??$.schema?.description??`${$.name} tool`,func:async(G,J,z)=>{return new Promise((K,X)=>{let U=l(z,{callbacks:J?.getChild()});a.runWithConfig(DQ(U),async()=>{try{K(Q(G,U))}catch(N){X(N)}})})}});let W=$.schema,Z=$.description??$.schema.description??`${$.name} tool`;return new f1({...$,description:Z,schema:W,func:async(G,J,z)=>{return new Promise((K,X)=>{let U,N=()=>{if(z?.signal&&U)z.signal.removeEventListener("abort",U)};if(z?.signal)U=()=>{N(),X(iQ(z.signal))},z.signal.addEventListener("abort",U,{once:!0});let B=l(z,{callbacks:J?.getChild()});a.runWithConfig(DQ(B),async()=>{try{let A=await Q(G,B);if(z?.signal?.aborted){N();return}N(),K(A)}catch(A){N(),X(A)}})})}})}function iJ(Q){let{content:$,artifact:Y,toolCallId:q,metadata:W}=Q;if(q&&!YY($))if(typeof $==="string"||Array.isArray($)&&$.every((Z)=>typeof Z==="object"))return new aQ({status:"success",content:$,artifact:Y,tool_call_id:q,name:Q.name,metadata:W});else return new aQ({status:"success",content:sJ($),artifact:Y,tool_call_id:q,name:Q.name,metadata:W});else return $}function sJ(Q){try{return JSON.stringify(Q)??""}catch($){return`${Q}`}}
|
|
89
|
+
export{M as dh,U0 as eh,rJ as fh,Y6 as gh,u1 as hh,q6 as ih,q9 as jh,p0 as kh,RQ as lh,gQ as mh,Z6 as nh,G6 as oh,Z9 as ph,J6 as qh,G9 as rh,J9 as sh,e$ as th,z9 as uh,H6 as vh,ZQ as wh,O6 as xh,e as yh,_9 as zh,YZ as Ah,p as Bh,N0 as Ch,E6 as Dh,BQ as Eh,L6 as Fh,P6 as Gh,I9 as Hh,y9 as Ih,YY as Jh,aQ as Kh,WZ as Lh,qY as Mh,ZZ as Nh,GZ as Oh,d9 as Ph,WY as Qh,JZ as Rh,zZ as Sh,l9 as Th,GY as Uh,p6 as Vh,i0 as Wh,B0 as Xh,M4 as Yh,_4 as Zh,F0 as _h,KY as $h,l6 as ai,C4 as bi,y4 as ci,i6 as di,s6 as ei,f4 as fi,g4 as gi,eQ as hi,o6 as ii,c4 as ji,l4 as ki,t6 as li,s0 as mi,n6 as ni,e4 as oi,Qz as pi,Fz as qi,r6 as ri,o0 as si,UY as ti,Vz as ui,Az as vi,Hz as wi,c6 as xi,Oz as yi,Yq as zi,OQ as Ai,Tz as Bi,OZ as Ci,$0 as Di,dQ as Ei,YX as Fi,EQ as Gi,JX as Hi,RX as Ii,yX as Ji,eX as Ki,_0 as Li,LQ as Mi,a as Ni,A2 as Oi,HQ as Pi,x0 as Qi,C as Ri,l as Si,DQ as Ti,jQ as Ui,m as Vi,s as Wi,S2 as Xi,O0 as Yi,iG as Zi,sG as _i,T2 as $i,R2 as aj,P$ as bj,M2 as cj,_2 as dj,sW as ej,I2 as fj,S$ as gj,oW as hj,CQ as ij,$8 as jj,oG as kj,tG as lj,x2 as mj,dW as nj,j2 as oj,v2 as pj,E$ as qj,pW as rj,C2 as sj,tW as tj,y2 as uj,nW as vj,T5 as wj,GJ as xj,y5 as yj,b8 as zj,j$ as Aj,u5 as Bj,t5 as Cj,Z7 as Dj,J0 as Ej,B7 as Fj,YQ as Gj,k$ as Hj,sQ as Ij,z0 as Jj,PJ as Kj,y7 as Lj,g7 as Mj,TJ as Nj,f0 as Oj,RJ as Pj,ZN as Qj,l$ as Rj,n as Sj,r as Tj,i$ as Uj,IN as Vj,R1 as Wj,M1 as Xj,s$ as Yj,_1 as Zj,xN as _j,CJ as $j,K0 as ak,yJ as bk,kJ as ck,T1 as dk,uN as ek,l8 as fk,i8 as gk,hJ as hk,aN as ik,JB as jk,v1 as kk,mJ as lk,uJ as mk,s8 as nk,o8 as ok,t8 as pk,C1 as qk,xB as rk,n8 as sk,f1 as tk,lJ as uk};
|