@evoscientist/webui 0.2.6 → 0.2.8
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/.next/BUILD_ID +1 -1
- package/dist/.next/build-manifest.json +3 -3
- package/dist/.next/prerender-manifest.json +5 -5
- package/dist/.next/required-server-files.json +5 -5
- package/dist/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/dist/.next/server/app/_global-error.html +1 -1
- package/dist/.next/server/app/_global-error.rsc +1 -1
- package/dist/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/dist/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/dist/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/dist/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/dist/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/_not-found.html +1 -1
- package/dist/.next/server/app/_not-found.rsc +3 -3
- package/dist/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
- package/dist/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
- package/dist/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/dist/.next/server/app/api/memory/executions/route.js.nft.json +1 -1
- package/dist/.next/server/app/api/memory/observations/route.js.nft.json +1 -1
- package/dist/.next/server/app/api/memory/route.js.nft.json +1 -1
- package/dist/.next/server/app/api/skills/catalog/route.js.nft.json +1 -1
- package/dist/.next/server/app/api/skills/detail/route.js.nft.json +1 -1
- package/dist/.next/server/app/api/skills/install/route.js.nft.json +1 -1
- package/dist/.next/server/app/api/skills/route.js.nft.json +1 -1
- package/dist/.next/server/app/index.html +1 -1
- package/dist/.next/server/app/index.rsc +4 -4
- package/dist/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/dist/.next/server/app/index.segments/_full.segment.rsc +4 -4
- package/dist/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/dist/.next/server/app/page.js.nft.json +1 -1
- package/dist/.next/server/app/page_client-reference-manifest.js +1 -1
- package/dist/.next/server/chunks/ssr/1daa_@mermaid-js_parser_dist_chunks_mermaid-parser_core_chunk-FOHPRMQF_mjs_0ybwfeq._.js +84 -0
- package/dist/.next/server/chunks/ssr/1daa_mermaid_dist_chunks_mermaid_core_mindmap-definition-YA3MSWOX_mjs_19k8byt._.js +92 -0
- package/dist/.next/server/chunks/ssr/1daa_mermaid_dist_chunks_mermaid_core_requirementDiagram-BXWQKSXE_mjs_0kwiv6n._.js +81 -0
- package/dist/.next/server/chunks/ssr/1daa_mermaid_dist_chunks_mermaid_core_timeline-definition-24CTP7MA_mjs_10dmaxt._.js +117 -0
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_gitGraphDiagram-WWUBYQGX_mjs_0g15hiw._.js +106 -0
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_ishikawaDiagram-5VMMS53U_mjs_05o2e4d._.js +66 -0
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_journeyDiagram-3NMN7TZE_mjs_16ehrbl._.js +136 -0
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_kanban-definition-UXKFOSKX_mjs_1uiqd5g._.js +81 -0
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_quadrantDiagram-AXDQQJYC_mjs_0h4a9wq._.js +3 -0
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_sequenceDiagram-WJ2MYXX4_mjs_1n01m3a._.js +155 -0
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_wardleyDiagram-VM6X3IG4_mjs_0kh3fjb._.js +79 -0
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_xychartDiagram-S5SC5T6Z_mjs_08t5e44._.js +3 -0
- package/dist/.next/server/chunks/ssr/[root-of-the-server]__0471z20._.js +1 -1
- package/dist/.next/server/chunks/ssr/[root-of-the-server]__0owaq8w._.js +3 -3
- package/dist/.next/server/chunks/ssr/[root-of-the-server]__0xpcv9w._.js +1 -1
- package/dist/.next/server/chunks/ssr/[root-of-the-server]__11a1-4t._.js +3 -0
- package/dist/.next/server/chunks/ssr/{node_modules_1-wfv6i._.js → node_modules_002u7ir._.js} +2 -2
- package/dist/.next/server/chunks/ssr/node_modules_01wbayw._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_02l4ncm._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_063ofsn._.js +64 -0
- package/dist/.next/server/chunks/ssr/node_modules_0a-3666._.js +26 -0
- package/dist/.next/server/chunks/ssr/node_modules_0dxcji9._.js +3 -0
- package/dist/.next/server/chunks/ssr/{node_modules_082g_84._.js → node_modules_0f5_pdq._.js} +12 -3
- package/dist/.next/server/chunks/ssr/node_modules_0fxlk06._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_0gs9qjb._.js +17 -0
- package/dist/.next/server/chunks/ssr/{node_modules_111pp7w._.js → node_modules_0klo3i5._.js} +2 -2
- package/dist/.next/server/chunks/ssr/node_modules_0koo_87._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_0lhl9_0._.js +17 -0
- package/dist/.next/server/chunks/ssr/node_modules_0m7-ed8._.js +43 -0
- package/dist/.next/server/chunks/ssr/node_modules_0p_8bfi._.js +3 -0
- package/dist/.next/server/chunks/ssr/{node_modules_1z_uie6._.js → node_modules_0plqukv._.js} +2 -2
- package/dist/.next/server/chunks/ssr/node_modules_0q44r64._.js +3 -0
- package/dist/.next/server/chunks/ssr/{node_modules_1nck62h._.js → node_modules_0qeu828._.js} +2 -2
- package/dist/.next/server/chunks/ssr/node_modules_0qw862r._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_0rb-_la._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_0tr3k8r._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_0urn1wt._.js +24 -0
- package/dist/.next/server/chunks/ssr/node_modules_0ybok7k._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_10v96_9._.js +3 -0
- package/dist/.next/server/chunks/ssr/{node_modules_1p9b60w._.js → node_modules_11trqmi._.js} +4 -4
- package/dist/.next/server/chunks/ssr/{node_modules_1_v-pb8._.js → node_modules_13e524_._.js} +2 -2
- package/dist/.next/server/chunks/ssr/node_modules_14gkv49._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_14xejkf._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_17rfg58._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_1_d0q_7._.js +289 -0
- package/dist/.next/server/chunks/ssr/node_modules_1a2dy76._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_1asq18n._.js +29 -0
- package/dist/.next/server/chunks/ssr/node_modules_1bo15xl._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_1c0h-_d._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_1f65-5g._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_1ki78ma._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_1mcjw-y._.js +17 -0
- package/dist/.next/server/chunks/ssr/{node_modules_0v4zc0t._.js → node_modules_1nl12mt._.js} +2 -2
- package/dist/.next/server/chunks/ssr/node_modules_1owe5xv._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_1phops3._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_1t626ye._.js +17 -0
- package/dist/.next/server/chunks/ssr/node_modules_1thrjjl._.js +3 -0
- package/dist/.next/server/chunks/ssr/{node_modules_0456qqx._.js → node_modules_1tsuh_o._.js} +3 -3
- package/dist/.next/server/chunks/ssr/node_modules_1twjy-4._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_1vbiuwu._.js +63 -0
- package/dist/.next/server/chunks/ssr/node_modules_208gr2-._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_20iziql._.js +17 -0
- package/dist/.next/server/chunks/ssr/node_modules_20oab__._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_066fcep._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_0_301m2._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_0it10w8._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_0m-ahsg._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_0n8rqkj._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_0nb4v-i._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_0tdjo9s._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_12betp4._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_1mu01rb._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_1xda76v._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_1z2f7i3._.js +3 -0
- package/dist/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_20vrei_._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_00ptcss._.js} +2 -2
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0_iovbk._.js +3 -0
- package/dist/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1quf15b._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0a2p_6-._.js} +2 -2
- package/dist/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0muxjzn._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0c6uq4c._.js} +2 -2
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0d8brvh._.js +3 -0
- package/dist/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0__ix0y._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0ha29gs._.js} +2 -2
- package/dist/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0597f-k._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0mkvkrn._.js} +2 -2
- package/dist/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1vi37xl._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0xbyurn._.js} +2 -2
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_10l-aox._.js +3 -0
- package/dist/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1fzbfn5._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_11iptmm._.js} +2 -2
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_183vuvb._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1_98arq._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1lr-xqr._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1p161c7._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1t9e3ef._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_dagre-d3-es_src_dagre_index_0g66msq.js +1 -1
- package/dist/.next/server/chunks/ssr/{node_modules_katex_dist_katex_mjs_04eh6b6._.js → node_modules_katex_dist_katex_mjs_09ex6q5._.js} +1 -1
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_0e5n4p5._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_blockDiagram-I7D4REHJ_mjs_0qg1lr5._.js +126 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_c4Diagram-7LVT6UL2_mjs_06bhe3-._.js +34 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-2E4U76K2_mjs_20f4_iz._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-4HAMMTFA_mjs_1cfif1_._.js +64 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-75Z2AOVW_mjs_051rute._.js +4 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-DU6HZSFF_mjs_20hsuk9._.js +124 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-IMKFNOWR_mjs_0vdq1-l._.js +228 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-LNGE3PJU_mjs_15ujw6f._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-OSK3NFVY_mjs_0x5leh1._.js +12 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-SHT3W25Y_mjs_00p5j42._.js +160 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-SVP7TREG_mjs_03r5m21._.js +88 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-TICWLB2K_mjs_1t97mh7._.js +203 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-Y2CYZVJY_mjs_20i4m4_._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_diagram-VX7I27RA_mjs_0dl8gzm._.js +26 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_erDiagram-RLTQ6QDP_mjs_18g60i7._.js +96 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_sankeyDiagram-P5KCCOFB_mjs_187yyta._.js +36 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_stateDiagram-D77RDMKH_mjs_1mer5fv._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_swimlanes-42K2YHIH_mjs_0scuk32._.js +3 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_vennDiagram-4TSXK5OY_mjs_0anqu7y._.js +25 -0
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_mermaid_core_mjs_1ao-jv5._.js +3 -3
- package/dist/.next/server/middleware-build-manifest.js +3 -3
- package/dist/.next/server/pages/404.html +1 -1
- package/dist/.next/server/pages/500.html +1 -1
- package/dist/.next/server/server-reference-manifest.js +1 -1
- package/dist/.next/server/server-reference-manifest.json +1 -1
- package/dist/.next/static/chunks/00h58csdfefay.js +1 -0
- package/dist/.next/static/chunks/01_remgex0cp2.js +1 -0
- package/dist/.next/static/chunks/01xjer0i_e5z5.js +15 -0
- package/dist/.next/static/chunks/025bmrgeukcb2.js +15 -0
- package/dist/.next/static/chunks/02slxciv9jt1p.js +77 -0
- package/dist/.next/static/chunks/04e-e--5lk26x.js +287 -0
- package/dist/.next/static/chunks/09nk4rn1z6j8b.js +1 -0
- package/dist/.next/static/chunks/0_l0vn2teso0z.js +1 -0
- package/dist/.next/static/chunks/0a_kuude9z_bg.js +1 -0
- package/dist/.next/static/chunks/0bz8pjqbx0nt7.js +1 -0
- package/dist/.next/static/chunks/0cnrxsj5iw5ld.js +2 -0
- package/dist/.next/static/chunks/0dcfqbly-089u.js +10 -0
- package/dist/.next/static/chunks/0dhmf6y59xjoo.js +1 -0
- package/dist/.next/static/chunks/{2-tnv5f86ywqz.js → 0kdfzi54utgbh.js} +1 -1
- package/dist/.next/static/chunks/0m-pl93u72hp9.js +1 -0
- package/dist/.next/static/chunks/0mkmxdnpoteey.js +1 -0
- package/dist/.next/static/chunks/{41ii5ld31fjk5.js → 0oyz95sujd2c7.js} +3 -3
- package/dist/.next/static/chunks/0p54qye85am3w.js +1 -0
- package/dist/.next/static/chunks/0q5tyevxl-ioe.js +1 -0
- package/dist/.next/static/chunks/0r79_ebje0i6_.js +1 -0
- package/dist/.next/static/chunks/0si45yj1su8y7.js +23 -0
- package/dist/.next/static/chunks/0u3ktztrzu1fa.js +1 -0
- package/dist/.next/static/chunks/0u9ae9k_2g7k3.js +1 -0
- package/dist/.next/static/chunks/{357a_3k2qrz6b.js → 0vhltcpdssl3-.js} +1 -1
- package/dist/.next/static/chunks/0x7n81v2cw92f.js +64 -0
- package/dist/.next/static/chunks/{1wsp3h55ims3-.js → 1-2_pusn4n8oh.js} +3 -3
- package/dist/.next/static/chunks/1-axl1a1s8xi7.js +1 -0
- package/dist/.next/static/chunks/14b2ne-5dycww.js +90 -0
- package/dist/.next/static/chunks/14osgsp3aiqpz.js +79 -0
- package/dist/.next/static/chunks/{2rob7uh46oj_f.js → 15e7e4t3feyih.js} +2 -2
- package/dist/.next/static/chunks/16mzcd_gvdgbo.js +1 -0
- package/dist/.next/static/chunks/1815xwa8351ma.js +1 -0
- package/dist/.next/static/chunks/1bzu587wut72w.js +1 -0
- package/dist/.next/static/chunks/1d9i8nlx-zy9a.js +62 -0
- package/dist/.next/static/chunks/1ebh7wwf-wzqn.js +32 -0
- package/dist/.next/static/chunks/1g6hadfcoz4ag.js +62 -0
- package/dist/.next/static/chunks/1kg8hnvdsweku.js +1 -0
- package/dist/.next/static/chunks/1kzq0rdlu1v0j.js +86 -0
- package/dist/.next/static/chunks/1qapeyh3r6cg3.js +1 -0
- package/dist/.next/static/chunks/1rh4z578p-h1a.js +104 -0
- package/dist/.next/static/chunks/1rowt7kr1tu9y.js +1 -0
- package/dist/.next/static/chunks/1u5i-jti87jbo.js +153 -0
- package/dist/.next/static/chunks/1v15lv0fcel0n.js +1 -0
- package/dist/.next/static/chunks/1wrwqqt23_cqy.js +94 -0
- package/dist/.next/static/chunks/21o6_7520je3e.js +1 -0
- package/dist/.next/static/chunks/221-n1wtpkus8.js +27 -0
- package/dist/.next/static/chunks/25pfy8u3vc_bn.js +24 -0
- package/dist/.next/static/chunks/266qo7h19xz_m.js +24 -0
- package/dist/.next/static/chunks/27ag7-c9a81uz.js +1 -0
- package/dist/.next/static/chunks/27vb_89qd7ag_.js +1 -0
- package/dist/.next/static/chunks/2b4v6n9b8htrv.js +158 -0
- package/dist/.next/static/chunks/2b57kmz64uj8h.js +1 -0
- package/dist/.next/static/chunks/2dmr54jagfdwa.css +3 -0
- package/dist/.next/static/chunks/2gocl3dq0_h1s.js +15 -0
- package/dist/.next/static/chunks/2itcfm_igcz5x.js +201 -0
- package/dist/.next/static/chunks/2l1phv_g29xz7.js +61 -0
- package/dist/.next/static/chunks/2m267diam_vib.js +22 -0
- package/dist/.next/static/chunks/2o4dndk0d68do.js +1 -0
- package/dist/.next/static/chunks/2qq7e47gpyc_e.js +82 -0
- package/dist/.next/static/chunks/2re701zfx-nrj.js +1 -0
- package/dist/.next/static/chunks/2sdwbfs1x5skp.js +1 -0
- package/dist/.next/static/chunks/2udhdtq_z8488.js +115 -0
- package/dist/.next/static/chunks/31etpuynk3lai.js +1 -0
- package/dist/.next/static/chunks/{05cl5ojgc4_ku.js → 32e7ex-ufg57f.js} +14 -14
- package/dist/.next/static/chunks/38h4_u_fq6ose.js +38 -0
- package/dist/.next/static/chunks/397b67vbg5iof.js +4 -0
- package/dist/.next/static/chunks/3her9o9_qn46y.js +226 -0
- package/dist/.next/static/chunks/3lx-n8v_8u7og.js +1 -0
- package/dist/.next/static/chunks/3mjwob-a5hhwz.js +1 -0
- package/dist/.next/static/chunks/3n80kknp-eoi9.js +1 -0
- package/dist/.next/static/chunks/3oif9bymgqjgd.js +41 -0
- package/dist/.next/static/chunks/3peltyinql2qj.js +34 -0
- package/dist/.next/static/chunks/3r7r2d2yc93-y.js +1 -0
- package/dist/.next/static/chunks/3s-zbm7kxc46y.js +93 -0
- package/dist/.next/static/chunks/3t9huugh-5_ps.js +1 -0
- package/dist/.next/static/chunks/3w5gsie2472pe.js +1 -0
- package/dist/.next/static/chunks/3zgnmu3cnahk0.js +122 -0
- package/dist/.next/static/chunks/41r6lojo50nzh.js +1 -0
- package/dist/.next/static/chunks/41uertskgrvwu.js +1 -0
- package/dist/.next/static/chunks/42kilhgqayez4.js +124 -0
- package/dist/node_modules/@img/sharp-darwin-arm64/index.cjs +1 -1
- package/dist/node_modules/@img/sharp-darwin-arm64/lib/{sharp-darwin-arm64-0.35.3.node → sharp-darwin-arm64-0.35.4.node} +0 -0
- package/dist/node_modules/@img/sharp-darwin-arm64/package.json +2 -2
- package/dist/node_modules/@img/sharp-libvips-darwin-arm64/lib/glib-2.0/include/glibconfig.h +1 -1
- package/dist/node_modules/@img/sharp-libvips-darwin-arm64/lib/{libvips-cpp.8.18.3.dylib → libvips-cpp.8.18.6.dylib} +0 -0
- package/dist/node_modules/@img/sharp-libvips-darwin-arm64/package.json +2 -2
- package/dist/node_modules/@img/sharp-libvips-darwin-arm64/versions.json +13 -13
- package/dist/node_modules/sharp/dist/composite.cjs +6 -6
- package/dist/node_modules/sharp/dist/composite.mjs +6 -6
- package/dist/node_modules/sharp/dist/constructor.cjs +1 -1
- package/dist/node_modules/sharp/dist/constructor.mjs +1 -1
- package/dist/node_modules/sharp/dist/index.d.cts +2 -2
- package/dist/node_modules/sharp/dist/index.d.mts +2 -2
- package/dist/node_modules/sharp/dist/input.cjs +20 -15
- package/dist/node_modules/sharp/dist/input.mjs +20 -15
- package/dist/node_modules/sharp/dist/operation.cjs +4 -0
- package/dist/node_modules/sharp/dist/operation.mjs +4 -0
- package/dist/node_modules/sharp/dist/output.cjs +4 -7
- package/dist/node_modules/sharp/dist/output.mjs +4 -7
- package/dist/node_modules/sharp/dist/resize.cjs +8 -8
- package/dist/node_modules/sharp/dist/resize.mjs +8 -8
- package/dist/node_modules/sharp/package.json +38 -38
- package/dist/package.json +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
- package/dist/.next/server/chunks/ssr/1daa_@mermaid-js_parser_dist_chunks_mermaid-parser_core_chunk-NNHCCRGN_mjs_03i6i8q._.js +0 -82
- package/dist/.next/server/chunks/ssr/1daa_mermaid_dist_chunks_mermaid_core_mindmap-definition-RKZ34NQL_mjs_1m8bey3._.js +0 -92
- package/dist/.next/server/chunks/ssr/1daa_mermaid_dist_chunks_mermaid_core_requirementDiagram-4Y6WPE33_mjs_0cvy8c2._.js +0 -81
- package/dist/.next/server/chunks/ssr/1daa_mermaid_dist_chunks_mermaid_core_timeline-definition-PNZ67QCA_mjs_0vzw4gu._.js +0 -117
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_gitGraphDiagram-PVQCEYII_mjs_1kl1645._.js +0 -106
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_ishikawaDiagram-YF4QCWOH_mjs_1-btteu._.js +0 -66
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_journeyDiagram-JHISSGLW_mjs_0omhwqk._.js +0 -136
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_kanban-definition-UN3LZRKU_mjs_052rc5y._.js +0 -81
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_quadrantDiagram-W4KKPZXB_mjs_0l8r0bx._.js +0 -3
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_sequenceDiagram-3UESZ5HK_mjs_0c-9sj0._.js +0 -155
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_wardleyDiagram-YWT4CUSO_mjs_0hqmyh5._.js +0 -79
- package/dist/.next/server/chunks/ssr/1q96_modules_mermaid_dist_chunks_mermaid_core_xychartDiagram-2RQKCTM6_mjs_1l5rlhy._.js +0 -3
- package/dist/.next/server/chunks/ssr/[root-of-the-server]__0nzxyl0._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_0-n78w2._.js +0 -17
- package/dist/.next/server/chunks/ssr/node_modules_00cex-8._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_07zdzg3._.js +0 -17
- package/dist/.next/server/chunks/ssr/node_modules_0_w_s0o._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_0chqc93._.js +0 -11
- package/dist/.next/server/chunks/ssr/node_modules_0i3cah4._.js +0 -17
- package/dist/.next/server/chunks/ssr/node_modules_0jx8vby._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_0kh3gaq._.js +0 -45
- package/dist/.next/server/chunks/ssr/node_modules_0oiuulr._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_0sud39z._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_0ty2qhi._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_0uvms5m._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_0xme7lg._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_0z2foqi._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_0z4gniu._.js +0 -17
- package/dist/.next/server/chunks/ssr/node_modules_15pczok._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_16l6ua_._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_16q2m8u._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_17rj81n._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_19b6jde._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_1_jf-yx._.js +0 -17
- package/dist/.next/server/chunks/ssr/node_modules_1lio4hi._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_1tj6b0h._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_1zskgct._.js +0 -26
- package/dist/.next/server/chunks/ssr/node_modules_20p8pl7._.js +0 -289
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_01lis5y._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_07fm7s3._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_0kitx9n._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_0x5ivvr._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_145f4t2._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_1_o7dux._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_1alyi8-._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_1bxlr8e._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_1grmhd9._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_01pthdh._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_03fanqm._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_16vf13h._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_blockDiagram-GPEHLZMM_mjs_0jxv2ay._.js +0 -129
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_c4Diagram-AAUBKEIU_mjs_1yyt6ej._.js +0 -7
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-3OPIFGDE_mjs_165ua5_._.js +0 -64
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-5ZQYHXKU_mjs_16ac76u._.js +0 -4
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-727SXJPM_mjs_0a9kagr._.js +0 -203
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-AQP2D5EJ_mjs_1p-51mn._.js +0 -228
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-CSCIHK7Q_mjs_0savw5-._.js +0 -121
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-KSCS5N6A_mjs_1vk17qr._.js +0 -12
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-O5CBEL6O_mjs_074844c._.js +0 -62
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_chunk-XPW4576I_mjs_0u9wa-b._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_dagre-BM42HDAG_mjs_0w_brpy._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_diagram-OG6HWLK6_mjs_0pzbdul._.js +0 -26
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_erDiagram-TEJ5UH35_mjs_1_cyy1q._.js +0 -82
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_flowDiagram-I6XJVG4X_mjs_01y3363._.js +0 -154
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_sankeyDiagram-5OEKKPKP_mjs_1nsv0tt._.js +0 -36
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_stateDiagram-AJRCARHV_mjs_0j4-fk2._.js +0 -3
- package/dist/.next/server/chunks/ssr/node_modules_mermaid_dist_chunks_mermaid_core_vennDiagram-CIIHVFJN_mjs_1jvbrvq._.js +0 -25
- package/dist/.next/static/chunks/01nhrh-3r57wh.js +0 -1
- package/dist/.next/static/chunks/03regxjjibliy.js +0 -29
- package/dist/.next/static/chunks/059oqdb-4djh4.js +0 -1
- package/dist/.next/static/chunks/0bk3aw3m9c72a.js +0 -201
- package/dist/.next/static/chunks/0bko6sy3fi25l.js +0 -1
- package/dist/.next/static/chunks/0c4y7_xzemq6-.js +0 -1
- package/dist/.next/static/chunks/0catqiaei7kwh.js +0 -62
- package/dist/.next/static/chunks/0cm59yzmvnr6a.js +0 -1
- package/dist/.next/static/chunks/0dm2etancr7wp.js +0 -2
- package/dist/.next/static/chunks/0l2v1ybx0rm07.js +0 -1
- package/dist/.next/static/chunks/0ll25xvc8tvc7.js +0 -60
- package/dist/.next/static/chunks/0o19535rrdg5j.js +0 -1
- package/dist/.next/static/chunks/0piaur2yhvb4v.js +0 -1
- package/dist/.next/static/chunks/0r-qze3me8owo.js +0 -5
- package/dist/.next/static/chunks/0s3geiy0as3cz.js +0 -104
- package/dist/.next/static/chunks/0wf_g68m1dyuq.js +0 -152
- package/dist/.next/static/chunks/0z7hf76h0cz39.js +0 -1
- package/dist/.next/static/chunks/0zao0i_njogzy.js +0 -79
- package/dist/.next/static/chunks/11jp13p4e7ycl.js +0 -1
- package/dist/.next/static/chunks/12b5tf_04ca4i.js +0 -10
- package/dist/.next/static/chunks/13j02-7zvh70e.js +0 -1
- package/dist/.next/static/chunks/15746zaz9af2k.js +0 -80
- package/dist/.next/static/chunks/15m2ikcj71414.js +0 -1
- package/dist/.next/static/chunks/17y1ca1c2d1k0.js +0 -127
- package/dist/.next/static/chunks/17zvg7jc-nx5v.js +0 -1
- package/dist/.next/static/chunks/18dnd1yq8sjcm.js +0 -80
- package/dist/.next/static/chunks/1bi4m489puezc.js +0 -64
- package/dist/.next/static/chunks/1g6nbgmclpjgd.js +0 -90
- package/dist/.next/static/chunks/1h978hs06gqwr.js +0 -1
- package/dist/.next/static/chunks/1rxbddx-dyypf.js +0 -226
- package/dist/.next/static/chunks/1s8wltynx2kei.js +0 -24
- package/dist/.next/static/chunks/1un-c368y76x-.js +0 -1
- package/dist/.next/static/chunks/1vqrf8u3eyf8l.js +0 -1
- package/dist/.next/static/chunks/1x5foe7mtvd8m.js +0 -15
- package/dist/.next/static/chunks/20uqpnur2j1hn.js +0 -1
- package/dist/.next/static/chunks/24c-6p_4lbozm.js +0 -1
- package/dist/.next/static/chunks/24l5e3uup8rxf.js +0 -153
- package/dist/.next/static/chunks/26t_0sbrej8uf.js +0 -15
- package/dist/.next/static/chunks/27n_wru0tprv5.js +0 -4
- package/dist/.next/static/chunks/29x7ecuc6vybp.js +0 -1
- package/dist/.next/static/chunks/2dqeid-8xhwun.js +0 -93
- package/dist/.next/static/chunks/2f6739bq5ewxz.js +0 -34
- package/dist/.next/static/chunks/2fuc_smcevit1.js +0 -15
- package/dist/.next/static/chunks/2h7acwi-mfsrx.js +0 -1
- package/dist/.next/static/chunks/2ia3pig2diart.js +0 -43
- package/dist/.next/static/chunks/2y3wq_x8yyu_b.js +0 -115
- package/dist/.next/static/chunks/2zrfdnujo3u51.js +0 -1
- package/dist/.next/static/chunks/3-q38f64d_smq.js +0 -77
- package/dist/.next/static/chunks/3-t8rqn47mim5.js +0 -1
- package/dist/.next/static/chunks/383s4_f7pq0oz.js +0 -1
- package/dist/.next/static/chunks/3cnkwh7z04e3e.js +0 -24
- package/dist/.next/static/chunks/3cvv663zekq_n.js +0 -119
- package/dist/.next/static/chunks/3cyn-rs5rpay6.css +0 -3
- package/dist/.next/static/chunks/3mcxvhb8ujk39.js +0 -1
- package/dist/.next/static/chunks/3s7at3o7ube_p.js +0 -9
- package/dist/.next/static/chunks/3wb9uvu5ii1sy.js +0 -287
- package/dist/.next/static/chunks/3x5hww03ialmf.js +0 -1
- package/dist/.next/static/chunks/3ypwau9uw-qzz.js +0 -23
- package/dist/.next/static/chunks/44dlrjamdw9zn.js +0 -1
- /package/dist/.next/static/{OdIi-OEl7eDEMfmeeT85N → DlVVJPKPg4elb2BXd_ZVZ}/_buildManifest.js +0 -0
- /package/dist/.next/static/{OdIi-OEl7eDEMfmeeT85N → DlVVJPKPg4elb2BXd_ZVZ}/_clientMiddlewareManifest.js +0 -0
- /package/dist/.next/static/{OdIi-OEl7eDEMfmeeT85N → DlVVJPKPg4elb2BXd_ZVZ}/_ssgManifest.js +0 -0
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,88906,364964,e=>{"use strict";var t=e.i(43073),r=e.i(827179),a=e.i(846001),i=e.i(41348),n=class{name;index;namespace;cause;graphName;toolStartedEvent;#e;#t;#r;#a;#i;#n;#s;#o=!1;#l;#u;#d;#c;constructor(e,t,r,a,i){this.name=e,this.index=t,this.namespace=r,this.cause=i?.cause,this.graphName=i?.graphName,this.toolStartedEvent=i?.toolStartedEvent,this.#e=a}get messages(){if(this.#t)return this.#t;let e=new t.MultiCursorBuffer;this.#t=e;let r=new a.StreamingMessageAssembler;return this.#h(["messages"],t=>{if("messages"!==t.method)return;let a=r.consume(t);a&&e.push(a)},()=>e.close()),e}get values(){let e,r;if(this.#r)return this.#r;let a=new t.MultiCursorBuffer,i=new Promise(e=>{r=e});this.#s=i;let n=Object.assign(a,{then:(e,t)=>i.then(e,t)});return this.#r=n,this.#h(["values"],t=>{if("values"!==t.method)return;let r=t.params.data;e=r,a.push(r)},()=>{r(e),a.close()}),n}get toolCalls(){if(this.#a)return this.#a;let e=new t.MultiCursorBuffer;this.#a=e;let a=new r.ToolCallAssembler;return this.#h(["tools"],t=>{if("tools"!==t.method)return;let i=a.consume(t);i&&e.push((0,r.toClientAssembledToolCall)(i))},()=>e.close()),e}get subgraphs(){if(this.#i)return this.#i;let e=new t.MultiCursorBuffer;return this.#i=e,(async()=>{for await(let t of new s(await this.#e.subscribe({channels:["lifecycle","tools"],namespaces:[this.namespace]}),this.#e,this.namespace))e.push(t);e.close()})(),e}get subagents(){if(this.#n)return this.#n;let r=new t.MultiCursorBuffer;return this.#n=r,(async()=>{let t=await this.#e.subscribe({channels:["tools","lifecycle"],namespaces:[this.namespace]}),{SubagentDiscoveryHandle:a}=await e.A(337539);for await(let e of new a(t,this.#e))r.push(e);r.close()})(),r}get audio(){return this.#p(),this.#l}get images(){return this.#p(),this.#u}get video(){return this.#p(),this.#d}get files(){return this.#p(),this.#c}get output(){return this.values,this.#s}#p(){if(this.#o)return;this.#o=!0;let e=new t.MultiCursorBuffer,r=new t.MultiCursorBuffer,a=new t.MultiCursorBuffer,n=new t.MultiCursorBuffer;this.#l=e,this.#u=r,this.#d=a,this.#c=n;let s=new i.MediaAssembler({onAudio:t=>e.push(t),onImage:e=>r.push(e),onVideo:e=>a.push(e),onFile:e=>n.push(e)});this.#h(["messages"],e=>{"messages"===e.method&&s.consume(e)},()=>{s.close(),e.close(),r.close(),a.close(),n.close()})}subscribe(e,t={}){return"object"==typeof e&&!Array.isArray(e)&&"channels"in e?this.#e.subscribe({...e,namespaces:e.namespaces??[this.namespace]}):this.#e.subscribe(e,{...t,namespaces:t.namespaces??[this.namespace]})}async #h(e,t,r){try{for await(let r of(await this.#e.subscribe({channels:e,namespaces:[this.namespace]})))t(r)}finally{r()}}},s=class{#f;#e;#m;#g=new Set;#y=new Map;#_=new Map;#b=[];#v=[];#w;#x=!1;constructor(e,t,r=[]){this.#f=e,this.#e=t,this.#m=r}#k(e){let t=this.#v.shift();t?t({done:!1,value:e}):this.#b.push(e)}#S(e){if("tools"!==e.method)return!1;let t=e.params.data;if("tool-started"!==t.event)return!0;let r=t.tool_call_id;if(!r)return!0;let a=this.#_.get(r);return a?(a.toolStartedEvent=e,this.#_.delete(r)):this.#y.set(r,e),!0}#E(e){let t,r,a;if(this.#S(e)||"lifecycle"!==e.method||"started"!==e.params.data.event)return;let i=e.params.namespace;if(i.length!==this.#m.length+1||!this.#m.every((e,t)=>i[t]===e))return;let s=i.join("/");if(this.#g.has(s))return;this.#g.add(s);let o=i[i.length-1]??"",l=o.lastIndexOf(":");if(l>=0){t=o.slice(0,l);let e=o.slice(l+1);r=/^\d+$/.test(e)?Number(e):0}else t=o,r=0;let u=e.params.data,d=u.cause&&"object"==typeof u.cause?u.cause:void 0;if(d?.type==="toolCall"){let e=d.tool_call_id;e&&(a=this.#y.get(e),this.#y.delete(e))}let c=new n(t,r,[...i],this.#e,{cause:d,graphName:u.graph_name,toolStartedEvent:a});if(d?.type==="toolCall"&&null==a){let e=d.tool_call_id;e&&this.#_.set(e,c)}return c}#T(){this.#w||(this.#w=(async()=>{for await(let e of this.#f){let t=this.#E(e);t&&this.#k(t)}for(this.#y.clear(),this.#_.clear(),this.#x=!0;this.#v.length>0;)this.#v.shift()?.({done:!0,value:void 0})})())}async close(){this.#x=!0,await this.#f.unsubscribe()}[Symbol.asyncIterator](){return this.#T(),{next:async()=>this.#b.length>0?{done:!1,value:this.#b.shift()}:this.#x?{done:!0,value:void 0}:await new Promise(e=>{this.#v.push(e)}),return:async()=>(await this.close(),{done:!0,value:void 0})}}};e.s(["SubgraphDiscoveryHandle",0,s],364964);var o=class{name;callId;taskInput;output;namespace;#e;#t;#a;#i;#o=!1;#l;#u;#d;#c;constructor(e,t,r,a,i,n){this.name=e,this.callId=t,this.namespace=r,this.taskInput=a,this.output=i,this.#e=n}get messages(){if(this.#t)return this.#t;let e=new t.MultiCursorBuffer;this.#t=e;let r=new a.StreamingMessageAssembler;return this.#h(["messages"],t=>{if("messages"!==t.method)return;let a=r.consume(t);a&&e.push(a)},()=>e.close()),e}get toolCalls(){if(this.#a)return this.#a;let e=new t.MultiCursorBuffer;this.#a=e;let a=new r.ToolCallAssembler;return this.#h(["tools"],t=>{if("tools"!==t.method||(0,r.shouldIgnoreScopedTaskToolEvent)(this.namespace,t))return;let i=a.consume(t);i&&e.push((0,r.toClientAssembledToolCall)(i))},()=>e.close()),e}get audio(){return this.#p(),this.#l}get images(){return this.#p(),this.#u}get video(){return this.#p(),this.#d}get files(){return this.#p(),this.#c}#p(){if(this.#o)return;this.#o=!0;let e=new t.MultiCursorBuffer,r=new t.MultiCursorBuffer,a=new t.MultiCursorBuffer,n=new t.MultiCursorBuffer;this.#l=e,this.#u=r,this.#d=a,this.#c=n;let s=new i.MediaAssembler({onAudio:t=>e.push(t),onImage:e=>r.push(e),onVideo:e=>a.push(e),onFile:e=>n.push(e)});this.#h(["messages"],e=>{"messages"===e.method&&s.consume(e)},()=>{s.close(),e.close(),r.close(),a.close(),n.close()})}get subgraphs(){if(this.#i)return this.#i;let e=new t.MultiCursorBuffer;return this.#i=e,(async()=>{for await(let t of new s(await this.#e.subscribe({channels:["lifecycle"],namespaces:[this.namespace]}),this.#e,this.namespace))e.push(t);e.close()})(),e}subscribe(e,t={}){return"object"==typeof e&&!Array.isArray(e)&&"channels"in e?this.#e.subscribe({...e,namespaces:e.namespaces??[this.namespace]}):this.#e.subscribe(e,{...t,namespaces:t.namespaces??[this.namespace]})}async #h(e,t,r){try{for await(let r of(await this.#e.subscribe({channels:e,namespaces:[this.namespace]})))t(r)}finally{r()}}},l=class{#f;#e;#b=[];#v=[];#A=new Map;#w;#x=!1;constructor(e,t){this.#f=e,this.#e=t}#E(e){if("tools"!==e.method)return;let t=e.params.data,r=t.tool_call_id;if("task"===t.tool_name&&"tool-started"===t.event){let a,i,n,s=t.input,l="string"==typeof s?JSON.parse(s):s??{},u=l.subagent_type??"unknown",d=l.description??"",c=new Promise(e=>{a=e}),h=new Promise((e,t)=>{i=e,n=t});return a(d),this.#A.set(r,{resolveOutput:i,rejectOutput:n}),new o(u,r,[...e.params.namespace],c,h,this.#e)}if(r){let e=this.#A.get(r);if(e){if("tool-finished"===t.event)e.resolveOutput(t.output),this.#A.delete(r);else if("tool-error"===t.event){let a=t.message??"unknown error";e.rejectOutput(Error(a)),this.#A.delete(r)}}}}#T(){this.#w||(this.#w=(async()=>{for await(let e of this.#f){let t=this.#E(e);if(!t)continue;let r=this.#v.shift();r?r({done:!1,value:t}):this.#b.push(t)}for(let e of(this.#x=!0,this.#A.values()))e.resolveOutput(void 0);for(this.#A.clear();this.#v.length>0;)this.#v.shift()?.({done:!0,value:void 0})})())}async close(){this.#x=!0,await this.#f.unsubscribe()}[Symbol.asyncIterator](){return this.#T(),{next:async()=>this.#b.length>0?{done:!1,value:this.#b.shift()}:this.#x?{done:!0,value:void 0}:await new Promise(e=>{this.#v.push(e)}),return:async()=>(await this.close(),{done:!0,value:void 0})}}};e.s(["SubagentDiscoveryHandle",0,l],88906)},827179,e=>{"use strict";function t(e){if("string"!=typeof e)return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function r(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return;if(t in e)return e[t];let r=e.kwargs;if(null!=r&&t in r)return r[t];let a=e.lc_kwargs;if(null!=a&&t in a)return a[t]}function a(e){return!!e&&"object"==typeof e&&("tool"===e.type||"tool"===r(e,"type")||"string"==typeof r(e,"tool_call_id")&&void 0!==r(e,"content"))}function i(e){if(null==e)return null;if("string"==typeof e)return 0===e.trim().length?null:t(e);if(Array.isArray(e)){let r=function(e){let t="";for(let r of e)r&&"object"==typeof r&&"text"===r.type&&"string"==typeof r.text&&(t+=r.text);return t}(e);return 0===r.length?null:t(r)}return"object"==typeof e?e:null}function n(e){return i(r(e,"content"))}function s(e,s){let o=t(e);if(o&&"object"==typeof o&&"Command"===o.lg_name){let e=function(e,t){let i=e.update;if(null==i||"object"!=typeof i||Array.isArray(i))return{found:!1};let s=i.messages;if(!Array.isArray(s))return{found:!1};let o=s.filter(e=>a(e));if(0===o.length)return{found:!1};if(null!=t){for(let e of o)if(r(e,"tool_call_id")===t)return{found:!0,value:n(e)};return{found:!1}}if(1===o.length)return{found:!0,value:n(o[0])};for(let e=o.length-1;e>=0;e-=1){let t=n(o[e]);if(null!=t)return{found:!0,value:t}}return{found:!0,value:null}}(o,s);return e.found?e.value:o}return a(o)?i(r(o,"content")):o??null}var o=class{active=new Map;consume(e){let t=e.params.data;return"tool-started"===t.event?this.handleStarted(e,t):"tool-finished"===t.event?this.handleFinished(t):"tool-error"===t.event?this.handleError(t):void 0}failAll(e){for(let t of this.active.values())t.rejectOutput(e),t.handle.status="error",t.handle.error=e.message;this.active.clear()}handleStarted(e,r){let a,i,n=new Promise((e,t)=>{a=e,i=t});n.catch(()=>void 0);let s=t(r.input),o=r.tool_name,l=r.tool_call_id,u={name:o,callId:l,id:l,namespace:[...e.params.namespace],input:s,args:s,output:null,status:"running",error:void 0,outputPromise:n};return this.active.set(l,{handle:u,resolveOutput:a,rejectOutput:i}),u}handleFinished(e){let t=this.active.get(e.tool_call_id);if(!t)return;this.active.delete(e.tool_call_id);let r=s(e.output,e.tool_call_id);return t.resolveOutput(r),t.handle.output=r,t.handle.status="finished",t.handle.error=void 0,t.handle}handleError(e){let t=this.active.get(e.tool_call_id);if(t)return this.active.delete(e.tool_call_id),t.rejectOutput(Error(e.message)),t.handle.output=null,t.handle.status="error",t.handle.error=e.message,t.handle}};e.s(["ToolCallAssembler",0,o,"parseToolOutput",0,s,"parseToolPayload",0,t,"shouldIgnoreScopedTaskToolEvent",0,function(e,t){let r=t.params.data;return e.length>0&&t.params.namespace.length===e.length&&t.params.namespace.every((t,r)=>t===e[r])&&"tool_name"in r&&"task"===r.tool_name},"toClientAssembledToolCall",0,function(e){return{name:e.name,callId:e.callId,id:e.id,namespace:e.namespace,input:e.input,args:e.args,output:e.outputPromise}}])},846001,44649,399855,165161,795529,265898,457933,641290,230125,833953,41348,e=>{"use strict";let t,r,a,i,n,s,o,l,u,d,c,h,p;e.s(["AIMessage",()=>e1,"AIMessageChunk",()=>e6,"isAIMessage",()=>e2,"isAIMessageChunk",()=>e4],641290),e.s(["coerceMessageLikeToMessage",()=>eG,"collapseToolCallChunks",()=>e0,"convertToChunk",()=>eX,"getBufferString",()=>eV,"iife",()=>eH,"mapChatMessagesToStoredMessages",()=>eY,"mapStoredMessageToChatMessage",()=>eK,"mapStoredMessagesToChatMessages",()=>eQ],457933);var f,m,g,y,_,b,v,w,x,k,S,E=e.i(43073);function T(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"source_type"in e&&("url"===e.source_type||"base64"===e.source_type||"text"===e.source_type||"id"===e.source_type)}function A({dataUrl:e,asTypedArray:t=!1}){let r=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);if(r)return{mime_type:r[1].toLowerCase(),data:t?Uint8Array.from(atob(r[2]),e=>e.charCodeAt(0)):r[2]}}let I=/([A-Z]+)([A-Z][a-z0-9]+)/g,O=/([a-z0-9])([A-Z])/g,C=/[-_\s]+/g;function j(e,t){return t?.[e]||e.replace(I,"$1_$2").replace(O,"$1_$2").replace(C,"_").toLowerCase()}function P(e){return Array.isArray(e)?[...e]:{...e}}function $(e){let t=Object.getPrototypeOf(e);return"function"==typeof e.lc_name&&("function"!=typeof t.lc_name||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var N=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,$(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){void 0!==this.lc_serializable_keys?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable||this.lc_kwargs instanceof e||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},r={},a=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let e=Object.getPrototypeOf(this);e;e=Object.getPrototypeOf(e))Object.assign(t,Reflect.get(e,"lc_aliases",this)),Object.assign(r,Reflect.get(e,"lc_secrets",this)),Object.assign(a,Reflect.get(e,"lc_attributes",this));Object.keys(r).forEach(e=>{let t=this,r=a,[i,...n]=e.split(".").reverse();for(let e of n.reverse()){if(!(e in t)||void 0===t[e])return;e in r&&void 0!==r[e]||("object"==typeof t[e]&&null!=t[e]?r[e]={}:Array.isArray(t[e])&&(r[e]=[])),t=t[e],r=r[e]}i in t&&void 0!==t[i]&&(r[i]=r[i]||t[i])});let i={},n=new WeakSet;for(let[e,t]of(n.add(this),Object.entries(a)))i[e]=function e(t,r=new WeakSet){if(null!==t&&"object"==typeof t&&!Array.isArray(t)){if(r.has(t))return{lc:1,type:"not_implemented",id:null!==t&&"object"==typeof t?"lc_id"in t&&Array.isArray(t.lc_id)?t.lc_id:[t.constructor?.name??"Object"]:[typeof t]};if(null!==t&&"object"==typeof t&&"lc_serializable"in t&&"function"==typeof t.toJSON)return t;if(r.add(t),"lc"in t||1===Object.keys(t).length&&"__lc_escaped__"in t)return r.delete(t),{__lc_escaped__:t};let a={};for(let[i,n]of Object.entries(t))a[i]=e(n,r);return r.delete(t),a}return Array.isArray(t)?t.map(t=>e(t,r)):t}(t,n);let s=function(e,t,r){let a={};for(let i in e)Object.hasOwn(e,i)&&(a[t(i,r)]=e[i]);return a}(Object.keys(r).length?function(e,t){let r=P(e);for(let[e,a]of Object.entries(t)){let[t,...i]=e.split(".").reverse(),n=r;for(let e of i.reverse()){if(void 0===n[e])break;n[e]=P(n[e]),n=n[e]}void 0!==n[t]&&(n[t]={lc:1,type:"secret",id:[a]})}return r}(i,r):i,j,t);return{lc:1,type:"constructor",id:this.lc_id,kwargs:s}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function R(e,t){return M(e)&&e.type===t}function M(e){return"object"==typeof e&&null!==e}function L(e){return Array.isArray(e)}function z(e){return"string"==typeof e}function U(e){return"number"==typeof e}function B(e){return e instanceof Uint8Array}function D(e){try{return JSON.parse(e)}catch{return}}let F=e=>e();function Z(e){if(R(e,"document")&&M(e.source)&&"type"in e.source){if("base64"===e.source.type&&z(e.source.media_type)&&z(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};else if("url"===e.source.type&&z(e.source.url))return{type:"file",url:e.source.url};else if("file"===e.source.type&&z(e.source.file_id))return{type:"file",fileId:e.source.file_id};else if("text"===e.source.type&&z(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(R(e,"image")&&M(e.source)&&"type"in e.source){if("base64"===e.source.type&&z(e.source.media_type)&&z(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};else if("url"===e.source.type&&z(e.source.url))return{type:"image",url:e.source.url};else if("file"===e.source.type&&z(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function H(e){return Array.from(function*(){for(let t of e){let e=Z(t);e?yield e:yield t}}())}function q(e){return Array.from(function*(){for(let r of"string"==typeof e.content?[{type:"text",text:e.content}]:e.content){if(R(r,"text")&&z(r.text)){let{text:e,citations:t,...a}=r;if(L(t)&&t.length){let r=t.reduce((e,t)=>{let r=function(e){if("char_location"===e.type&&z(e.document_title)&&U(e.start_char_index)&&U(e.end_char_index)&&z(e.cited_text)){let{document_title:t,start_char_index:r,end_char_index:a,cited_text:i,...n}=e;return{...n,type:"citation",source:"char",title:t??void 0,startIndex:r,endIndex:a,citedText:i}}if("page_location"===e.type&&z(e.document_title)&&U(e.start_page_number)&&U(e.end_page_number)&&z(e.cited_text)){let{document_title:t,start_page_number:r,end_page_number:a,cited_text:i,...n}=e;return{...n,type:"citation",source:"page",title:t??void 0,startIndex:r,endIndex:a,citedText:i}}if("content_block_location"===e.type&&z(e.document_title)&&U(e.start_block_index)&&U(e.end_block_index)&&z(e.cited_text)){let{document_title:t,start_block_index:r,end_block_index:a,cited_text:i,...n}=e;return{...n,type:"citation",source:"block",title:t??void 0,startIndex:r,endIndex:a,citedText:i}}if("web_search_result_location"===e.type&&z(e.url)&&z(e.title)&&z(e.encrypted_index)&&z(e.cited_text)){let{url:t,title:r,encrypted_index:a,cited_text:i,...n}=e;return{...n,type:"citation",source:"url",url:t,title:r,startIndex:Number(a),endIndex:Number(a),citedText:i}}if("search_result_location"===e.type&&z(e.source)&&z(e.title)&&U(e.start_block_index)&&U(e.end_block_index)&&z(e.cited_text)){let{source:t,title:r,start_block_index:a,end_block_index:i,cited_text:n,...s}=e;return{...s,type:"citation",source:"search",url:t,title:r??void 0,startIndex:a,endIndex:i,citedText:n}}}(t);return r?[...e,r]:e},[]);yield{...a,type:"text",text:e,annotations:r};continue}yield{...a,type:"text",text:e};continue}if(R(r,"thinking")&&z(r.thinking)){let{thinking:e,signature:t,...a}=r;yield{...a,type:"reasoning",reasoning:e,signature:t};continue}if(R(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(R(r,"tool_use")&&z(r.name)&&z(r.id)){yield{type:"tool_call",id:r.id,name:r.name,args:r.input};continue}else if(R(r,"input_json_delta")){var t;if(t=e,"function"==typeof t?._getType&&"function"==typeof t.concat&&"ai"===t._getType()&&e.tool_call_chunks?.length){let t=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args,index:t.index};continue}}else if(R(r,"server_tool_use")&&z(r.name)&&z(r.id)){let{name:e,id:t}=r;if("web_search"===e){yield{id:t,type:"server_tool_call",name:"web_search",args:{query:F(()=>{if("string"==typeof r.input)return r.input;if(M(r.input)&&z(r.input.query))return r.input.query;if(z(r.partial_json)){let e=D(r.partial_json);if(e?.query)return e.query}return""})}};continue}if("code_execution"===r.name){yield{id:t,type:"server_tool_call",name:"code_execution",args:{code:F(()=>{if("string"==typeof r.input)return r.input;if(M(r.input)&&z(r.input.code))return r.input.code;if(z(r.partial_json)){let e=D(r.partial_json);if(e?.code)return e.code}return""})}};continue}}else if(R(r,"web_search_tool_result")&&z(r.tool_use_id)&&L(r.content)){let{content:e,tool_use_id:t}=r;yield{type:"server_tool_call_result",name:"web_search",toolCallId:t,status:"success",output:{urls:e.reduce((e,t)=>R(t,"web_search_result")?[...e,t.url]:e,[])}};continue}else if(R(r,"code_execution_tool_result")&&z(r.tool_use_id)&&M(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(R(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(R(r,"mcp_tool_result")&&z(r.tool_use_id)&&M(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(R(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(R(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(R(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}else{let e=Z(r);if(e){yield e;continue}}yield{type:"non_standard",value:r}}}())}function J(e){return T(e)&&"url"===e.source_type&&"url"in e&&"string"==typeof e.url?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:T(e)&&"base64"===e.source_type&&"data"in e&&"string"==typeof e.data?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:T(e)&&"id"===e.source_type&&"id"in e&&"string"==typeof e.id?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function G(e){return e.map(J)}function W(e){let t=[];for(let r of e)(R(r,"image_url")&&M(r.image_url)||R(r,"input_audio")&&M(r.input_audio)||R(r,"file")&&M(r.file)?0:1)?t.push(r):t.push(function(e){if(R(e,"image_url")&&M(e.image_url)&&z(e.image_url.url)){let t=A({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}if(R(e,"input_audio")&&M(e.input_audio)&&z(e.input_audio.data)&&z(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(R(e,"file")&&M(e.file)&&z(e.file.data)){let t=A({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(z(e.file.file_id))return{type:"file",fileId:e.file.file_id}}return e}(r));return t}function V(e){if("url_citation"===e.type){let{url:t,title:r,start_index:a,end_index:i}=e;return{type:"citation",url:t,title:r,startIndex:a,endIndex:i}}if("file_citation"===e.type){let{file_id:t,filename:r,index:a}=e;return{type:"citation",title:r,startIndex:a,endIndex:a,fileId:t}}return e}function K(e){return Array.from(function*(){for(let t of(M(e.additional_kwargs?.reasoning)&&L(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((e,t)=>M(t)&&z(t.text)?`${e}${t.text}`:e,"")}),"string"==typeof e.content?[{type:"text",text:e.content}]:e.content))if(R(t,"text")){let{text:e,annotations:r,phase:a,extras:i,...n}=t,s=M(i)?{...i}:{};z(a)&&(s.phase=a);let o=Object.keys(s).length>0?{extras:s}:{};Array.isArray(r)?yield{...n,...o,type:"text",text:String(e),annotations:r.map(V)}:yield{...n,...o,type:"text",text:String(e)}}for(let t of e.tool_calls??[])yield{type:"tool_call",id:t.id,name:t.name,args:t.args};if(M(e.additional_kwargs)&&L(e.additional_kwargs.tool_outputs))for(let t of e.additional_kwargs.tool_outputs){if(R(t,"web_search_call")){let e={};if(M(t.action)&&z(t.action.query)&&(e.query=t.action.query),yield{id:t.id,type:"server_tool_call",name:"web_search",args:e},"completed"===t.status||"failed"===t.status){let e={};M(t.action)&&(e.action=t.action),yield{type:"server_tool_call_result",toolCallId:z(t.id)?t.id:"",status:"completed"===t.status?"success":"error",output:e}}continue}if(R(t,"file_search_call")){yield{id:t.id,type:"server_tool_call",name:"file_search",args:{queries:L(t.queries)?t.queries:[]}},("completed"===t.status||"failed"===t.status)&&(yield{type:"server_tool_call_result",toolCallId:z(t.id)?t.id:"",status:"completed"===t.status?"success":"error",output:L(t.results)?{results:t.results}:{}});continue}if(R(t,"computer_call")){yield{type:"non_standard",value:t};continue}else if(R(t,"code_interpreter_call")){if(z(t.code)&&(yield{id:t.id,type:"server_tool_call",name:"code_interpreter",args:{code:t.code}}),L(t.outputs)){let e=F(()=>{if("in_progress"!==t.status){if("completed"===t.status)return 0;if("incomplete"===t.status)return 127;if("interpreting"!==t.status&&"failed"===t.status)return 1}});for(let r of t.outputs)if(R(r,"logs")){yield{type:"server_tool_call_result",toolCallId:t.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:e??0,stderr:[0,void 0].includes(e)?void 0:String(r.logs),stdout:[0,void 0].includes(e)?String(r.logs):void 0}};continue}}continue}else if(R(t,"mcp_call")){yield{id:t.id,type:"server_tool_call",name:"mcp_call",args:t.input};continue}else if(R(t,"mcp_list_tools")){yield{id:t.id,type:"server_tool_call",name:"mcp_list_tools",args:t.input};continue}else if(R(t,"mcp_approval_request")){yield{type:"non_standard",value:t};continue}else if(R(t,"tool_search_call")){let e={};M(t.arguments)&&Object.assign(e,t.arguments);let r={};z(t.execution)&&(r.execution=t.execution),z(t.status)&&(r.status=t.status),z(t.call_id)&&(r.call_id=t.call_id),yield{id:z(t.id)?t.id:"",type:"server_tool_call",name:"tool_search",args:e,...Object.keys(r).length>0?{extras:r}:{}};continue}else if(R(t,"tool_search_output")){let e={name:"tool_search"};z(t.execution)&&(e.execution=t.execution),yield{type:"server_tool_call_result",toolCallId:z(t.id)?t.id:"",status:"completed"===t.status?"success":"failed"===t.status?"error":"success",output:{tools:L(t.tools)?t.tools:[]},extras:e};continue}else if(R(t,"image_generation_call")){z(t.result)&&(yield{type:"image",mimeType:"image/png",data:t.result,id:z(t.id)?t.id:void 0,metadata:{status:z(t.status)?t.status:void 0}}),yield{type:"non_standard",value:t};continue}M(t)&&(yield{type:"non_standard",value:t})}}())}let Q=Symbol.for("langchain.message");function Y(e){return Array.isArray(e)?e:"string"==typeof e?""===e?[]:[{type:"text",text:e}]:null==e?[]:[e]}function X(e,t){if("string"==typeof e)return""===e?t:"string"==typeof t?e+t:Array.isArray(t)&&0===t.length?e:Array.isArray(t)&&t.some(e=>T(e))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t];if(Array.isArray(t)){let r=Y(e);return eo(r,t)??[...r,...t]}return""===t?e:Array.isArray(e)&&e.some(e=>T(e))?[...e,{type:"file",source_type:"text",text:t}]:[...Y(e),{type:"text",text:t}]}function ee(e,t){return"error"===e||"error"===t?"error":"success"}var et=class extends N{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Q]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t="string"==typeof e||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,void 0===t.content&&void 0!==t.contentBlocks?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):(void 0!==t.content?this.content=t.content??[]:this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return"string"==typeof this.content?this.content:Array.isArray(this.content)?this.content.map(e=>"string"==typeof e?e:"text"===e.type?e.text:"").join(""):""}get contentBlocks(){return[G,W,H].reduce((e,t)=>t(e),"string"==typeof this.content?[{type:"text",text:this.content}]:this.content)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){var t;return"object"==typeof e&&null!==e&&Q in e&&!0===e[Q]&&"object"==typeof(t=e)&&null!==t&&"type"in t&&"content"in t&&("string"==typeof t.content||Array.isArray(t.content))}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){var t,r;if(null===e)return this;let a=(t=this._printableFields,r=Math.max(4,e),JSON.stringify(function e(t,a){if("object"!=typeof t||null==t)return t;if(a>=r)return Array.isArray(t)?"[Array]":"[Object]";if(Array.isArray(t))return t.map(t=>e(t,a+1));let i={};for(let r of Object.keys(t))i[r]=e(t[r],a+1);return i}(t,0),null,2));return`${this.constructor.lc_name()} ${a}`}toFormattedString(e="pretty"){return function(e,t="pretty"){return"pretty"===t?function(e){let t=[],r=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-r.length)/2),i="=".repeat(a),n=r.length%2==0?i:`${i}=`;if(t.push(`${i}${r}${n}`),"ai"===e.type&&e.tool_calls&&e.tool_calls.length>0)for(let r of(t.push("Tool Calls:"),e.tool_calls))for(let[e,a]of(t.push(` ${r.name} (${r.id})`),t.push(` Call ID: ${r.id}`),t.push(" Args:"),Object.entries(r.args)))t.push(` ${e}: ${"object"==typeof a?JSON.stringify(a):a}`);return"tool"===e.type&&e.name&&t.push(`Name: ${e.name}`),"string"==typeof e.content&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join("\n")}(e):JSON.stringify(e)}(this,e)}};let er=["index","created","timestamp"];function ea(e,t,r){let a=r?.ignoreKeys??er;if(null==e&&null==t)return;if(null==e||null==t)return e??t;let i={...e};for(let[e,n]of Object.entries(t))if(null==i[e])i[e]=n;else if(null==n)continue;else if(typeof i[e]!=typeof n||Array.isArray(i[e])!==Array.isArray(n))throw Error(`field[${e}] already exists in the message chunk, but with a different type.`);else if("string"==typeof i[e])if("type"===e)continue;else if(["id","name","output_version","model_provider"].includes(e))n&&(i[e]=n);else{if(a.includes(e))continue;i[e]+=n}else if("number"==typeof i[e]){if(a.includes(e))continue;i[e]=i[e]+n}else if("object"!=typeof i[e]||Array.isArray(i[e]))if(Array.isArray(i[e]))i[e]=eo(i[e],n,r);else{if(i[e]===n)continue;console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`)}else i[e]=ea(i[e],n,r);return i}function ei(e){var t;return"object"==typeof e&&null!==e&&"index"in e&&("number"==typeof(t=e.index)||"string"==typeof t)}function en(e){if("object"!=typeof e||null===e||!("id"in e))return!1;let t=e.id;return null!=t&&""!==t}function es(e){return e.endsWith("_delta")?e.slice(0,-6):e}function eo(e,t,r){if(null!=e||null!=t){if(null==e||null==t)return e||t;let a=[...e];for(let e of t){let t=function(e,t){let r=ei(t),a=en(t);return r||a?e.findIndex(e=>{let i=ei(e),n=en(e);if(r&&i)return e.index===t.index&&("object"!=typeof e||null===e||"object"!=typeof t||null===t||!("type"in e)||!("type"in t)||"string"!=typeof e.type||"string"!=typeof t.type||es(e.type)===es(t.type))&&(!n||!a||e.id===t.id);return!r&&!i&&!!a&&!!n&&e.id===t.id}):-1}(a,e);if(-1!==t)a[t]=ea(a[t],e,r);else{if("object"==typeof e&&null!==e&&"text"in e&&""===e.text)continue;a.push(e)}}return a}}function el(e,t,r){if(null!=e||null!=t)if(null==e||null==t)return e??t;else if(typeof e!=typeof t)throw Error(`Cannot merge objects of different types.
|
|
1
|
+
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,88906,364964,e=>{"use strict";var t=e.i(43073),r=e.i(827179),a=e.i(846001),i=e.i(41348),n=class{name;index;namespace;cause;graphName;toolStartedEvent;#e;#t;#r;#a;#i;#n;#s;#o=!1;#l;#u;#d;#c;constructor(e,t,r,a,i){this.name=e,this.index=t,this.namespace=r,this.cause=i?.cause,this.graphName=i?.graphName,this.toolStartedEvent=i?.toolStartedEvent,this.#e=a}get messages(){if(this.#t)return this.#t;let e=new t.MultiCursorBuffer;this.#t=e;let r=new a.StreamingMessageAssembler;return this.#h(["messages"],t=>{if("messages"!==t.method)return;let a=r.consume(t);a&&e.push(a)},()=>e.close()),e}get values(){let e,r;if(this.#r)return this.#r;let a=new t.MultiCursorBuffer,i=new Promise(e=>{r=e});this.#s=i;let n=Object.assign(a,{then:(e,t)=>i.then(e,t)});return this.#r=n,this.#h(["values"],t=>{if("values"!==t.method)return;let r=t.params.data;e=r,a.push(r)},()=>{r(e),a.close()}),n}get toolCalls(){if(this.#a)return this.#a;let e=new t.MultiCursorBuffer;this.#a=e;let a=new r.ToolCallAssembler;return this.#h(["tools"],t=>{if("tools"!==t.method)return;let i=a.consume(t);i&&e.push((0,r.toClientAssembledToolCall)(i))},()=>e.close()),e}get subgraphs(){if(this.#i)return this.#i;let e=new t.MultiCursorBuffer;return this.#i=e,(async()=>{for await(let t of new s(await this.#e.subscribe({channels:["lifecycle","tools"],namespaces:[this.namespace]}),this.#e,this.namespace))e.push(t);e.close()})(),e}get subagents(){if(this.#n)return this.#n;let r=new t.MultiCursorBuffer;return this.#n=r,(async()=>{let t=await this.#e.subscribe({channels:["tools","lifecycle"],namespaces:[this.namespace]}),{SubagentDiscoveryHandle:a}=await e.A(337539);for await(let e of new a(t,this.#e))r.push(e);r.close()})(),r}get audio(){return this.#p(),this.#l}get images(){return this.#p(),this.#u}get video(){return this.#p(),this.#d}get files(){return this.#p(),this.#c}get output(){return this.values,this.#s}#p(){if(this.#o)return;this.#o=!0;let e=new t.MultiCursorBuffer,r=new t.MultiCursorBuffer,a=new t.MultiCursorBuffer,n=new t.MultiCursorBuffer;this.#l=e,this.#u=r,this.#d=a,this.#c=n;let s=new i.MediaAssembler({onAudio:t=>e.push(t),onImage:e=>r.push(e),onVideo:e=>a.push(e),onFile:e=>n.push(e)});this.#h(["messages"],e=>{"messages"===e.method&&s.consume(e)},()=>{s.close(),e.close(),r.close(),a.close(),n.close()})}subscribe(e,t={}){return"object"==typeof e&&!Array.isArray(e)&&"channels"in e?this.#e.subscribe({...e,namespaces:e.namespaces??[this.namespace]}):this.#e.subscribe(e,{...t,namespaces:t.namespaces??[this.namespace]})}async #h(e,t,r){try{for await(let r of(await this.#e.subscribe({channels:e,namespaces:[this.namespace]})))t(r)}finally{r()}}},s=class{#f;#e;#m;#g=new Set;#y=new Map;#_=new Map;#b=[];#v=[];#w;#x=!1;constructor(e,t,r=[]){this.#f=e,this.#e=t,this.#m=r}#k(e){let t=this.#v.shift();t?t({done:!1,value:e}):this.#b.push(e)}#S(e){if("tools"!==e.method)return!1;let t=e.params.data;if("tool-started"!==t.event)return!0;let r=t.tool_call_id;if(!r)return!0;let a=this.#_.get(r);return a?(a.toolStartedEvent=e,this.#_.delete(r)):this.#y.set(r,e),!0}#T(e){let t,r,a;if(this.#S(e)||"lifecycle"!==e.method||"started"!==e.params.data.event)return;let i=e.params.namespace;if(i.length!==this.#m.length+1||!this.#m.every((e,t)=>i[t]===e))return;let s=i.join("/");if(this.#g.has(s))return;this.#g.add(s);let o=i[i.length-1]??"",l=o.lastIndexOf(":");if(l>=0){t=o.slice(0,l);let e=o.slice(l+1);r=/^\d+$/.test(e)?Number(e):0}else t=o,r=0;let u=e.params.data,d=u.cause&&"object"==typeof u.cause?u.cause:void 0;if(d?.type==="toolCall"){let e=d.tool_call_id;e&&(a=this.#y.get(e),this.#y.delete(e))}let c=new n(t,r,[...i],this.#e,{cause:d,graphName:u.graph_name,toolStartedEvent:a});if(d?.type==="toolCall"&&null==a){let e=d.tool_call_id;e&&this.#_.set(e,c)}return c}#E(){this.#w||(this.#w=(async()=>{for await(let e of this.#f){let t=this.#T(e);t&&this.#k(t)}for(this.#y.clear(),this.#_.clear(),this.#x=!0;this.#v.length>0;)this.#v.shift()?.({done:!0,value:void 0})})())}async close(){this.#x=!0,await this.#f.unsubscribe()}[Symbol.asyncIterator](){return this.#E(),{next:async()=>this.#b.length>0?{done:!1,value:this.#b.shift()}:this.#x?{done:!0,value:void 0}:await new Promise(e=>{this.#v.push(e)}),return:async()=>(await this.close(),{done:!0,value:void 0})}}};e.s(["SubgraphDiscoveryHandle",0,s],364964);var o=class{name;callId;taskInput;output;namespace;#e;#t;#a;#i;#o=!1;#l;#u;#d;#c;constructor(e,t,r,a,i,n){this.name=e,this.callId=t,this.namespace=r,this.taskInput=a,this.output=i,this.#e=n}get messages(){if(this.#t)return this.#t;let e=new t.MultiCursorBuffer;this.#t=e;let r=new a.StreamingMessageAssembler;return this.#h(["messages"],t=>{if("messages"!==t.method)return;let a=r.consume(t);a&&e.push(a)},()=>e.close()),e}get toolCalls(){if(this.#a)return this.#a;let e=new t.MultiCursorBuffer;this.#a=e;let a=new r.ToolCallAssembler;return this.#h(["tools"],t=>{if("tools"!==t.method||(0,r.shouldIgnoreScopedTaskToolEvent)(this.namespace,t))return;let i=a.consume(t);i&&e.push((0,r.toClientAssembledToolCall)(i))},()=>e.close()),e}get audio(){return this.#p(),this.#l}get images(){return this.#p(),this.#u}get video(){return this.#p(),this.#d}get files(){return this.#p(),this.#c}#p(){if(this.#o)return;this.#o=!0;let e=new t.MultiCursorBuffer,r=new t.MultiCursorBuffer,a=new t.MultiCursorBuffer,n=new t.MultiCursorBuffer;this.#l=e,this.#u=r,this.#d=a,this.#c=n;let s=new i.MediaAssembler({onAudio:t=>e.push(t),onImage:e=>r.push(e),onVideo:e=>a.push(e),onFile:e=>n.push(e)});this.#h(["messages"],e=>{"messages"===e.method&&s.consume(e)},()=>{s.close(),e.close(),r.close(),a.close(),n.close()})}get subgraphs(){if(this.#i)return this.#i;let e=new t.MultiCursorBuffer;return this.#i=e,(async()=>{for await(let t of new s(await this.#e.subscribe({channels:["lifecycle"],namespaces:[this.namespace]}),this.#e,this.namespace))e.push(t);e.close()})(),e}subscribe(e,t={}){return"object"==typeof e&&!Array.isArray(e)&&"channels"in e?this.#e.subscribe({...e,namespaces:e.namespaces??[this.namespace]}):this.#e.subscribe(e,{...t,namespaces:t.namespaces??[this.namespace]})}async #h(e,t,r){try{for await(let r of(await this.#e.subscribe({channels:e,namespaces:[this.namespace]})))t(r)}finally{r()}}},l=class{#f;#e;#b=[];#v=[];#A=new Map;#w;#x=!1;constructor(e,t){this.#f=e,this.#e=t}#T(e){if("tools"!==e.method)return;let t=e.params.data,r=t.tool_call_id;if("task"===t.tool_name&&"tool-started"===t.event){let a,i,n,s=t.input,l="string"==typeof s?JSON.parse(s):s??{},u=l.subagent_type??"unknown",d=l.description??"",c=new Promise(e=>{a=e}),h=new Promise((e,t)=>{i=e,n=t});return a(d),this.#A.set(r,{resolveOutput:i,rejectOutput:n}),new o(u,r,[...e.params.namespace],c,h,this.#e)}if(r){let e=this.#A.get(r);if(e){if("tool-finished"===t.event)e.resolveOutput(t.output),this.#A.delete(r);else if("tool-error"===t.event){let a=t.message??"unknown error";e.rejectOutput(Error(a)),this.#A.delete(r)}}}}#E(){this.#w||(this.#w=(async()=>{for await(let e of this.#f){let t=this.#T(e);if(!t)continue;let r=this.#v.shift();r?r({done:!1,value:t}):this.#b.push(t)}for(let e of(this.#x=!0,this.#A.values()))e.resolveOutput(void 0);for(this.#A.clear();this.#v.length>0;)this.#v.shift()?.({done:!0,value:void 0})})())}async close(){this.#x=!0,await this.#f.unsubscribe()}[Symbol.asyncIterator](){return this.#E(),{next:async()=>this.#b.length>0?{done:!1,value:this.#b.shift()}:this.#x?{done:!0,value:void 0}:await new Promise(e=>{this.#v.push(e)}),return:async()=>(await this.close(),{done:!0,value:void 0})}}};e.s(["SubagentDiscoveryHandle",0,l],88906)},827179,e=>{"use strict";function t(e){if("string"!=typeof e)return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function r(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return;if(t in e)return e[t];let r=e.kwargs;if(null!=r&&t in r)return r[t];let a=e.lc_kwargs;if(null!=a&&t in a)return a[t]}function a(e){return!!e&&"object"==typeof e&&("tool"===e.type||"tool"===r(e,"type")||"string"==typeof r(e,"tool_call_id")&&void 0!==r(e,"content"))}function i(e){if(null==e)return null;if("string"==typeof e)return 0===e.trim().length?null:t(e);if(Array.isArray(e)){let r=function(e){let t="";for(let r of e)r&&"object"==typeof r&&"text"===r.type&&"string"==typeof r.text&&(t+=r.text);return t}(e);return 0===r.length?null:t(r)}return"object"==typeof e?e:null}function n(e){return i(r(e,"content"))}function s(e,s){let o=t(e);if(o&&"object"==typeof o&&"Command"===o.lg_name){let e=function(e,t){let i=e.update;if(null==i||"object"!=typeof i||Array.isArray(i))return{found:!1};let s=i.messages;if(!Array.isArray(s))return{found:!1};let o=s.filter(e=>a(e));if(0===o.length)return{found:!1};if(null!=t){for(let e of o)if(r(e,"tool_call_id")===t)return{found:!0,value:n(e)};return{found:!1}}if(1===o.length)return{found:!0,value:n(o[0])};for(let e=o.length-1;e>=0;e-=1){let t=n(o[e]);if(null!=t)return{found:!0,value:t}}return{found:!0,value:null}}(o,s);return e.found?e.value:o}return a(o)?i(r(o,"content")):o??null}var o=class{active=new Map;consume(e){let t=e.params.data;return"tool-started"===t.event?this.handleStarted(e,t):"tool-finished"===t.event?this.handleFinished(t):"tool-error"===t.event?this.handleError(t):void 0}failAll(e){for(let t of this.active.values())t.rejectOutput(e),t.handle.status="error",t.handle.error=e.message;this.active.clear()}handleStarted(e,r){let a,i,n=new Promise((e,t)=>{a=e,i=t});n.catch(()=>void 0);let s=t(r.input),o=r.tool_name,l=r.tool_call_id,u={name:o,callId:l,id:l,namespace:[...e.params.namespace],input:s,args:s,output:null,status:"running",error:void 0,outputPromise:n};return this.active.set(l,{handle:u,resolveOutput:a,rejectOutput:i}),u}handleFinished(e){let t=this.active.get(e.tool_call_id);if(!t)return;this.active.delete(e.tool_call_id);let r=s(e.output,e.tool_call_id);return t.resolveOutput(r),t.handle.output=r,t.handle.status="finished",t.handle.error=void 0,t.handle}handleError(e){let t=this.active.get(e.tool_call_id);if(t)return this.active.delete(e.tool_call_id),t.rejectOutput(Error(e.message)),t.handle.output=null,t.handle.status="error",t.handle.error=e.message,t.handle}};e.s(["ToolCallAssembler",0,o,"parseToolOutput",0,s,"parseToolPayload",0,t,"shouldIgnoreScopedTaskToolEvent",0,function(e,t){let r=t.params.data;return e.length>0&&t.params.namespace.length===e.length&&t.params.namespace.every((t,r)=>t===e[r])&&"tool_name"in r&&"task"===r.tool_name},"toClientAssembledToolCall",0,function(e){return{name:e.name,callId:e.callId,id:e.id,namespace:e.namespace,input:e.input,args:e.args,output:e.outputPromise}}])},846001,44649,399855,165161,795529,265898,457933,641290,230125,833953,41348,e=>{"use strict";let t,r,a,i,n,s,o,l,u,d,c,h,p;e.s(["AIMessage",()=>e1,"AIMessageChunk",()=>e9,"isAIMessage",()=>e2,"isAIMessageChunk",()=>e4],641290),e.s(["coerceMessageLikeToMessage",()=>eG,"collapseToolCallChunks",()=>e0,"convertToChunk",()=>eX,"getBufferString",()=>eV,"iife",()=>eH,"mapChatMessagesToStoredMessages",()=>eY,"mapStoredMessageToChatMessage",()=>eK,"mapStoredMessagesToChatMessages",()=>eQ],457933);var f,m,g,y,_,b,v,w,x,k,S,T=e.i(43073);function E(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"source_type"in e&&("url"===e.source_type||"base64"===e.source_type||"text"===e.source_type||"id"===e.source_type)}function A({dataUrl:e,asTypedArray:t=!1}){let r=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);if(r)return{mime_type:r[1].toLowerCase(),data:t?Uint8Array.from(atob(r[2]),e=>e.charCodeAt(0)):r[2]}}let I=/([A-Z]+)([A-Z][a-z0-9]+)/g,O=/([a-z0-9])([A-Z])/g,C=/[-_\s]+/g;function j(e,t){return t?.[e]||e.replace(I,"$1_$2").replace(O,"$1_$2").replace(C,"_").toLowerCase()}function $(e){return Array.isArray(e)?[...e]:{...e}}function P(e){let t=Object.getPrototypeOf(e);return"function"==typeof e.lc_name&&("function"!=typeof t.lc_name||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var N=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,P(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){void 0!==this.lc_serializable_keys?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable||this.lc_kwargs instanceof e||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},r={},a=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let e=Object.getPrototypeOf(this);e;e=Object.getPrototypeOf(e))Object.assign(t,Reflect.get(e,"lc_aliases",this)),Object.assign(r,Reflect.get(e,"lc_secrets",this)),Object.assign(a,Reflect.get(e,"lc_attributes",this));Object.keys(r).forEach(e=>{let t=this,r=a,[i,...n]=e.split(".").reverse();for(let e of n.reverse()){if(!(e in t)||void 0===t[e])return;e in r&&void 0!==r[e]||("object"==typeof t[e]&&null!=t[e]?r[e]={}:Array.isArray(t[e])&&(r[e]=[])),t=t[e],r=r[e]}i in t&&void 0!==t[i]&&(r[i]=r[i]||t[i])});let i={},n=new WeakSet;for(let[e,t]of(n.add(this),Object.entries(a)))i[e]=function e(t,r=new WeakSet){if(null!==t&&"object"==typeof t&&!Array.isArray(t)){if(r.has(t))return{lc:1,type:"not_implemented",id:null!==t&&"object"==typeof t?"lc_id"in t&&Array.isArray(t.lc_id)?t.lc_id:[t.constructor?.name??"Object"]:[typeof t]};if(null!==t&&"object"==typeof t&&"lc_serializable"in t&&"function"==typeof t.toJSON)return t;if(r.add(t),"lc"in t||1===Object.keys(t).length&&"__lc_escaped__"in t)return r.delete(t),{__lc_escaped__:t};let a={};for(let[i,n]of Object.entries(t))a[i]=e(n,r);return r.delete(t),a}return Array.isArray(t)?t.map(t=>e(t,r)):t}(t,n);let s=function(e,t,r){let a={};for(let i in e)Object.hasOwn(e,i)&&(a[t(i,r)]=e[i]);return a}(Object.keys(r).length?function(e,t){let r=$(e);for(let[e,a]of Object.entries(t)){let[t,...i]=e.split(".").reverse(),n=r;for(let e of i.reverse()){if(void 0===n[e])break;n[e]=$(n[e]),n=n[e]}void 0!==n[t]&&(n[t]={lc:1,type:"secret",id:[a]})}return r}(i,r):i,j,t);return{lc:1,type:"constructor",id:this.lc_id,kwargs:s}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function R(e,t){return M(e)&&e.type===t}function M(e){return"object"==typeof e&&null!==e}function z(e){return Array.isArray(e)}function L(e){return"string"==typeof e}function U(e){return"number"==typeof e}function D(e){return e instanceof Uint8Array}function B(e){try{return JSON.parse(e)}catch{return}}let F=e=>e();function Z(e){if(R(e,"document")&&M(e.source)&&"type"in e.source){if("base64"===e.source.type&&L(e.source.media_type)&&L(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};else if("url"===e.source.type&&L(e.source.url))return{type:"file",url:e.source.url};else if("file"===e.source.type&&L(e.source.file_id))return{type:"file",fileId:e.source.file_id};else if("text"===e.source.type&&L(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(R(e,"image")&&M(e.source)&&"type"in e.source){if("base64"===e.source.type&&L(e.source.media_type)&&L(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};else if("url"===e.source.type&&L(e.source.url))return{type:"image",url:e.source.url};else if("file"===e.source.type&&L(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function H(e){return Array.from(function*(){for(let t of e){let e=Z(t);e?yield e:yield t}}())}function q(e){return Array.from(function*(){for(let r of"string"==typeof e.content?[{type:"text",text:e.content}]:e.content){if(R(r,"text")&&L(r.text)){let{text:e,citations:t,...a}=r;if(z(t)&&t.length){let r=t.reduce((e,t)=>{let r=function(e){if("char_location"===e.type&&L(e.document_title)&&U(e.start_char_index)&&U(e.end_char_index)&&L(e.cited_text)){let{document_title:t,start_char_index:r,end_char_index:a,cited_text:i,...n}=e;return{...n,type:"citation",source:"char",title:t??void 0,startIndex:r,endIndex:a,citedText:i}}if("page_location"===e.type&&L(e.document_title)&&U(e.start_page_number)&&U(e.end_page_number)&&L(e.cited_text)){let{document_title:t,start_page_number:r,end_page_number:a,cited_text:i,...n}=e;return{...n,type:"citation",source:"page",title:t??void 0,startIndex:r,endIndex:a,citedText:i}}if("content_block_location"===e.type&&L(e.document_title)&&U(e.start_block_index)&&U(e.end_block_index)&&L(e.cited_text)){let{document_title:t,start_block_index:r,end_block_index:a,cited_text:i,...n}=e;return{...n,type:"citation",source:"block",title:t??void 0,startIndex:r,endIndex:a,citedText:i}}if("web_search_result_location"===e.type&&L(e.url)&&L(e.title)&&L(e.encrypted_index)&&L(e.cited_text)){let{url:t,title:r,encrypted_index:a,cited_text:i,...n}=e;return{...n,type:"citation",source:"url",url:t,title:r,startIndex:Number(a),endIndex:Number(a),citedText:i}}if("search_result_location"===e.type&&L(e.source)&&L(e.title)&&U(e.start_block_index)&&U(e.end_block_index)&&L(e.cited_text)){let{source:t,title:r,start_block_index:a,end_block_index:i,cited_text:n,...s}=e;return{...s,type:"citation",source:"search",url:t,title:r??void 0,startIndex:a,endIndex:i,citedText:n}}}(t);return r?[...e,r]:e},[]);yield{...a,type:"text",text:e,annotations:r};continue}yield{...a,type:"text",text:e};continue}if(R(r,"thinking")&&L(r.thinking)){let{thinking:e,signature:t,...a}=r;yield{...a,type:"reasoning",reasoning:e,signature:t};continue}if(R(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(R(r,"tool_use")&&L(r.name)&&L(r.id)){yield{type:"tool_call",id:r.id,name:r.name,args:r.input};continue}else if(R(r,"input_json_delta")){var t;if(t=e,"function"==typeof t?._getType&&"function"==typeof t.concat&&"ai"===t._getType()&&e.tool_call_chunks?.length){let t=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args,index:t.index};continue}}else if(R(r,"server_tool_use")&&L(r.name)&&L(r.id)){let{name:e,id:t}=r;if("web_search"===e){yield{id:t,type:"server_tool_call",name:"web_search",args:{query:F(()=>{if("string"==typeof r.input)return r.input;if(M(r.input)&&L(r.input.query))return r.input.query;if(L(r.partial_json)){let e=B(r.partial_json);if(e?.query)return e.query}return""})}};continue}if("code_execution"===r.name){yield{id:t,type:"server_tool_call",name:"code_execution",args:{code:F(()=>{if("string"==typeof r.input)return r.input;if(M(r.input)&&L(r.input.code))return r.input.code;if(L(r.partial_json)){let e=B(r.partial_json);if(e?.code)return e.code}return""})}};continue}}else if(R(r,"web_search_tool_result")&&L(r.tool_use_id)&&z(r.content)){let{content:e,tool_use_id:t}=r;yield{type:"server_tool_call_result",name:"web_search",toolCallId:t,status:"success",output:{urls:e.reduce((e,t)=>R(t,"web_search_result")?[...e,t.url]:e,[])}};continue}else if(R(r,"code_execution_tool_result")&&L(r.tool_use_id)&&M(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(R(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(R(r,"mcp_tool_result")&&L(r.tool_use_id)&&M(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(R(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(R(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(R(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}else{let e=Z(r);if(e){yield e;continue}}yield{type:"non_standard",value:r}}}())}function J(e){return E(e)&&"url"===e.source_type&&"url"in e&&"string"==typeof e.url?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:E(e)&&"base64"===e.source_type&&"data"in e&&"string"==typeof e.data?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:E(e)&&"id"===e.source_type&&"id"in e&&"string"==typeof e.id?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function G(e){return e.map(J)}function W(e){let t=[];for(let r of e)(R(r,"image_url")&&M(r.image_url)||R(r,"input_audio")&&M(r.input_audio)||R(r,"file")&&M(r.file)?0:1)?t.push(r):t.push(function(e){if(R(e,"image_url")&&M(e.image_url)&&L(e.image_url.url)){let t=A({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}if(R(e,"input_audio")&&M(e.input_audio)&&L(e.input_audio.data)&&L(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(R(e,"file")&&M(e.file)&&L(e.file.data)){let t=A({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(L(e.file.file_id))return{type:"file",fileId:e.file.file_id}}return e}(r));return t}function V(e){if("url_citation"===e.type){let{url:t,title:r,start_index:a,end_index:i}=e;return{type:"citation",url:t,title:r,startIndex:a,endIndex:i}}if("file_citation"===e.type){let{file_id:t,filename:r,index:a}=e;return{type:"citation",title:r,startIndex:a,endIndex:a,fileId:t}}return e}function K(e){return Array.from(function*(){for(let t of(M(e.additional_kwargs?.reasoning)&&z(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((e,t)=>M(t)&&L(t.text)?`${e}${t.text}`:e,"")}),"string"==typeof e.content?[{type:"text",text:e.content}]:e.content))if(R(t,"text")){let{text:e,annotations:r,phase:a,extras:i,...n}=t,s=M(i)?{...i}:{};L(a)&&(s.phase=a);let o=Object.keys(s).length>0?{extras:s}:{};Array.isArray(r)?yield{...n,...o,type:"text",text:String(e),annotations:r.map(V)}:yield{...n,...o,type:"text",text:String(e)}}for(let t of e.tool_calls??[])yield{type:"tool_call",id:t.id,name:t.name,args:t.args};if(M(e.additional_kwargs)&&z(e.additional_kwargs.tool_outputs))for(let t of e.additional_kwargs.tool_outputs){if(R(t,"web_search_call")){let e={};if(M(t.action)&&L(t.action.query)&&(e.query=t.action.query),yield{id:t.id,type:"server_tool_call",name:"web_search",args:e},"completed"===t.status||"failed"===t.status){let e={};M(t.action)&&(e.action=t.action),yield{type:"server_tool_call_result",toolCallId:L(t.id)?t.id:"",status:"completed"===t.status?"success":"error",output:e}}continue}if(R(t,"file_search_call")){yield{id:t.id,type:"server_tool_call",name:"file_search",args:{queries:z(t.queries)?t.queries:[]}},("completed"===t.status||"failed"===t.status)&&(yield{type:"server_tool_call_result",toolCallId:L(t.id)?t.id:"",status:"completed"===t.status?"success":"error",output:z(t.results)?{results:t.results}:{}});continue}if(R(t,"computer_call")){yield{type:"non_standard",value:t};continue}else if(R(t,"code_interpreter_call")){if(L(t.code)&&(yield{id:t.id,type:"server_tool_call",name:"code_interpreter",args:{code:t.code}}),z(t.outputs)){let e=F(()=>{if("in_progress"!==t.status){if("completed"===t.status)return 0;if("incomplete"===t.status)return 127;if("interpreting"!==t.status&&"failed"===t.status)return 1}});for(let r of t.outputs)if(R(r,"logs")){yield{type:"server_tool_call_result",toolCallId:t.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:e??0,stderr:[0,void 0].includes(e)?void 0:String(r.logs),stdout:[0,void 0].includes(e)?String(r.logs):void 0}};continue}}continue}else if(R(t,"mcp_call")){yield{id:t.id,type:"server_tool_call",name:"mcp_call",args:t.input};continue}else if(R(t,"mcp_list_tools")){yield{id:t.id,type:"server_tool_call",name:"mcp_list_tools",args:t.input};continue}else if(R(t,"mcp_approval_request")){yield{type:"non_standard",value:t};continue}else if(R(t,"tool_search_call")){let e={};M(t.arguments)&&Object.assign(e,t.arguments);let r={};L(t.execution)&&(r.execution=t.execution),L(t.status)&&(r.status=t.status),L(t.call_id)&&(r.call_id=t.call_id),yield{id:L(t.id)?t.id:"",type:"server_tool_call",name:"tool_search",args:e,...Object.keys(r).length>0?{extras:r}:{}};continue}else if(R(t,"tool_search_output")){let e={name:"tool_search"};L(t.execution)&&(e.execution=t.execution),yield{type:"server_tool_call_result",toolCallId:L(t.id)?t.id:"",status:"completed"===t.status?"success":"failed"===t.status?"error":"success",output:{tools:z(t.tools)?t.tools:[]},extras:e};continue}else if(R(t,"image_generation_call")){L(t.result)&&(yield{type:"image",mimeType:"image/png",data:t.result,id:L(t.id)?t.id:void 0,metadata:{status:L(t.status)?t.status:void 0}}),yield{type:"non_standard",value:t};continue}M(t)&&(yield{type:"non_standard",value:t})}}())}let Q=Symbol.for("langchain.message");function Y(e){return Array.isArray(e)?e:"string"==typeof e?""===e?[]:[{type:"text",text:e}]:null==e?[]:[e]}function X(e,t){if("string"==typeof e)return""===e?t:"string"==typeof t?e+t:Array.isArray(t)&&0===t.length?e:Array.isArray(t)&&t.some(e=>E(e))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t];if(Array.isArray(t)){let r=Y(e);return eo(r,t)??[...r,...t]}return""===t?e:Array.isArray(e)&&e.some(e=>E(e))?[...e,{type:"file",source_type:"text",text:t}]:[...Y(e),{type:"text",text:t}]}function ee(e,t){return"error"===e||"error"===t?"error":"success"}var et=class extends N{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Q]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t="string"==typeof e||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,void 0===t.content&&void 0!==t.contentBlocks?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):(void 0!==t.content?this.content=t.content??[]:this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return"string"==typeof this.content?this.content:Array.isArray(this.content)?this.content.map(e=>"string"==typeof e?e:"text"===e.type?e.text:"").join(""):""}get contentBlocks(){return[G,W,H].reduce((e,t)=>t(e),"string"==typeof this.content?[{type:"text",text:this.content}]:this.content)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){var t;return"object"==typeof e&&null!==e&&Q in e&&!0===e[Q]&&"object"==typeof(t=e)&&null!==t&&"type"in t&&"content"in t&&("string"==typeof t.content||Array.isArray(t.content))}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){var t,r;if(null===e)return this;let a=(t=this._printableFields,r=Math.max(4,e),JSON.stringify(function e(t,a){if("object"!=typeof t||null==t)return t;if(a>=r)return Array.isArray(t)?"[Array]":"[Object]";if(Array.isArray(t))return t.map(t=>e(t,a+1));let i={};for(let r of Object.keys(t))i[r]=e(t[r],a+1);return i}(t,0),null,2));return`${this.constructor.lc_name()} ${a}`}toFormattedString(e="pretty"){return function(e,t="pretty"){return"pretty"===t?function(e){let t=[],r=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-r.length)/2),i="=".repeat(a),n=r.length%2==0?i:`${i}=`;if(t.push(`${i}${r}${n}`),"ai"===e.type&&e.tool_calls&&e.tool_calls.length>0)for(let r of(t.push("Tool Calls:"),e.tool_calls))for(let[e,a]of(t.push(` ${r.name} (${r.id})`),t.push(` Call ID: ${r.id}`),t.push(" Args:"),Object.entries(r.args)))t.push(` ${e}: ${"object"==typeof a?JSON.stringify(a):a}`);return"tool"===e.type&&e.name&&t.push(`Name: ${e.name}`),"string"==typeof e.content&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join("\n")}(e):JSON.stringify(e)}(this,e)}};let er=["index","created","timestamp"];function ea(e,t,r){let a=r?.ignoreKeys??er;if(null==e&&null==t)return;if(null==e||null==t)return e??t;let i={...e};for(let[e,n]of Object.entries(t))if(null==i[e])i[e]=n;else if(null==n)continue;else if(typeof i[e]!=typeof n||Array.isArray(i[e])!==Array.isArray(n))throw Error(`field[${e}] already exists in the message chunk, but with a different type.`);else if("string"==typeof i[e])if("type"===e)continue;else if(["id","name","output_version","model_provider"].includes(e))n&&(i[e]=n);else{if(a.includes(e))continue;i[e]+=n}else if("number"==typeof i[e]){if(a.includes(e))continue;i[e]=i[e]+n}else if("object"!=typeof i[e]||Array.isArray(i[e]))if(Array.isArray(i[e]))i[e]=eo(i[e],n,r);else{if(i[e]===n)continue;console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`)}else i[e]=ea(i[e],n,r);return i}function ei(e){var t;return"object"==typeof e&&null!==e&&"index"in e&&("number"==typeof(t=e.index)||"string"==typeof t)}function en(e){if("object"!=typeof e||null===e||!("id"in e))return!1;let t=e.id;return null!=t&&""!==t}function es(e){return e.endsWith("_delta")?e.slice(0,-6):e}function eo(e,t,r){if(null!=e||null!=t){if(null==e||null==t)return e||t;let a=[...e];for(let e of t){let t=function(e,t){let r=ei(t),a=en(t);return r||a?e.findIndex(e=>{let i=ei(e),n=en(e);if(r&&i)return e.index===t.index&&("object"!=typeof e||null===e||"object"!=typeof t||null===t||!("type"in e)||!("type"in t)||"string"!=typeof e.type||"string"!=typeof t.type||es(e.type)===es(t.type))&&(!n||!a||e.id===t.id);return!r&&!i&&!!a&&!!n&&e.id===t.id}):-1}(a,e);if(-1!==t)a[t]=ea(a[t],e,r);else{if("object"==typeof e&&null!==e&&"text"in e&&""===e.text)continue;a.push(e)}}return a}}function el(e,t,r){if(null!=e||null!=t)if(null==e||null==t)return e??t;else if(typeof e!=typeof t)throw Error(`Cannot merge objects of different types.
|
|
2
2
|
Left ${typeof e}
|
|
3
3
|
Right ${typeof t}`);else if("string"==typeof e&&"string"==typeof t)return e+t;else if(Array.isArray(e)&&Array.isArray(t))return eo(e,t,r);else if("object"==typeof e&&"object"==typeof t)return ea(e,t,r);else if(e===t)return e;else throw Error(`Can not merge objects of different types.
|
|
4
4
|
Left ${e}
|
|
5
|
-
Right ${t}`)}var eu=class e extends et{static isInstance(t){if(!super.isInstance(t))return!1;let r=Object.getPrototypeOf(t);for(;null!==r;){if(r===e.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}};function ed(e){return"string"==typeof e.role}function ec(e){return"function"==typeof e?._getType}function eh(e){return eu.isInstance(e)}function ep(e,t){let r={};return(e?.audio!==void 0||t?.audio!==void 0)&&(r.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(r.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(r.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(r.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(r.text=(e?.text??0)+(t?.text??0)),r}function ef(e,t){var r,a,i,n;let s,o;return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:(s={...ep(r=e?.input_token_details,a=t?.input_token_details)},(r?.cache_read!==void 0||a?.cache_read!==void 0)&&(s.cache_read=(r?.cache_read??0)+(a?.cache_read??0)),(r?.cache_creation!==void 0||a?.cache_creation!==void 0)&&(s.cache_creation=(r?.cache_creation??0)+(a?.cache_creation??0)),s),output_token_details:(o={...ep(i=e?.output_token_details,n=t?.output_token_details)},(i?.reasoning!==void 0||n?.reasoning!==void 0)&&(o.reasoning=(i?.reasoning??0)+(n?.reasoning??0)),o)}}e.s(["BaseMessage",0,et,"BaseMessageChunk",0,eu,"DEFAULT_MERGE_IGNORE_KEYS",0,er,"_isMessageFieldWithRole",0,ed,"_mergeDicts",0,ea,"_mergeLists",0,eo,"_mergeObj",0,el,"_mergeStatus",0,ee,"isBaseMessage",0,ec,"isBaseMessageChunk",0,eh,"isOpenAIToolCallArray",0,function(e){return Array.isArray(e)&&e.every(e=>"number"==typeof e.index)},"mergeContent",0,X],44649);var em=class extends et{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(e,t,r){const a="string"==typeof e||Array.isArray(e)?{content:e,name:r,tool_call_id:t}:e;super(a),this.tool_call_id=a.tool_call_id,this.artifact=a.artifact,this.status=a.status,this.metadata=a.metadata}static isInstance(e){return super.isInstance(e)&&"tool"===e.type}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},eg=class extends eu{type="tool";tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){return new this.constructor({content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata),artifact:el(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:ee(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function ey(e){let t=[],r=[];for(let a of e)if(!a.function)continue;else{let e=a.function.name;try{let r=JSON.parse(a.function.arguments);t.push({name:e||"",args:r||{},id:a.id})}catch{r.push({name:e,args:a.function.arguments,id:a.id,error:"Malformed args."})}}return[t,r]}e.s(["ToolMessage",0,em,"ToolMessageChunk",0,eg,"defaultToolCallParser",0,ey,"isDirectToolOutput",0,function(e){return null!=e&&"object"==typeof e&&"lc_direct_tool_output"in e&&!0===e.lc_direct_tool_output},"isToolMessage",0,function(e){return"object"==typeof e&&null!==e&&"getType"in e&&"function"==typeof e.getType&&"tool"===e.getType()},"isToolMessageChunk",0,function(e){return"tool"===e._getType()}],399855);var e_=e.i(467034);function eb(e){switch(e){case"csv":return"text/csv";case"doc":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":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 ev(e){return Array.from(function*(){for(let t of"string"==typeof e.content?[{type:"text",text:e.content}]:e.content){if(R(t,"cache_point")){yield{type:"non_standard",value:t};continue}if(R(t,"citations_content")&&M(t.citationsContent)){yield{type:"text",text:L(t.citationsContent.content)?t.citationsContent.content.reduce((e,t)=>M(t)&&z(t.text)?e+t.text:e,""):"",annotations:L(t.citationsContent.citations)?t.citationsContent.citations.reduce((e,t)=>{if(M(t)){let r=L(t.sourceContent)?t.sourceContent.reduce((e,t)=>M(t)&&z(t.text)?e+t.text:e,""):"",a=F(()=>{if(M(t.location)){let e=t.location.documentChar||t.location.documentPage||t.location.documentChunk;if(M(e))return{source:U(e.documentIndex)?e.documentIndex.toString():void 0,startIndex:U(e.start)?e.start:void 0,endIndex:U(e.end)?e.end:void 0}}return{}});e.push({type:"citation",citedText:r,...a})}return e},[]):[]};continue}if(R(t,"document")&&M(t.document)){yield function(e){if(M(e.document)&&M(e.document.source)){let t=eb(M(e.document)&&z(e.document.format)?e.document.format:"");if(M(e.document.source)){if(M(e.document.source.s3Location)&&z(e.document.source.s3Location.uri))return{type:"file",mimeType:t,fileId:e.document.source.s3Location.uri};if(B(e.document.source.bytes))return{type:"file",mimeType:t,data:e.document.source.bytes};if(z(e.document.source.text))return{type:"file",mimeType:t,data:e_.Buffer.from(e.document.source.text).toString("base64")};if(L(e.document.source.content))return{type:"file",mimeType:t,data:e.document.source.content.reduce((e,t)=>M(t)&&z(t.text)?e+t.text:e,"")}}}return{type:"non_standard",value:e}}(t);continue}else if(R(t,"guard_content")){yield{type:"non_standard",value:t};continue}else if(R(t,"image")&&M(t.image)){yield function(e){if(R(e,"image")&&M(e.image)){let t=eb(M(e.image)&&z(e.image.format)?e.image.format:"");if(M(e.image.source)){if(M(e.image.source.s3Location)&&z(e.image.source.s3Location.uri))return{type:"image",mimeType:t,fileId:e.image.source.s3Location.uri};if(B(e.image.source.bytes))return{type:"image",mimeType:t,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}(t);continue}else if(R(t,"reasoning_content")&&z(t.reasoningText)){yield{type:"reasoning",reasoning:t.reasoningText};continue}else if(R(t,"text")&&z(t.text)){yield{type:"text",text:t.text};continue}else if(R(t,"tool_result")){yield{type:"non_standard",value:t};continue}else if(R(t,"tool_call"))continue;else if(R(t,"video")&&M(t.video)){yield function(e){if(R(e,"video")&&M(e.video)){let t=eb(M(e.video)&&z(e.video.format)?e.video.format:"");if(M(e.video.source)){if(M(e.video.source.s3Location)&&z(e.video.source.s3Location.uri))return{type:"video",mimeType:t,fileId:e.video.source.s3Location.uri};if(B(e.video.source.bytes))return{type:"video",mimeType:t,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}(t);continue}yield{type:"non_standard",value:t}}}())}function ew(e){let t=[],r=e.additional_kwargs?.reasoning_content;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(let r of e.content)"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&z(r.text)&&t.push({type:"text",text:r.text});for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function ex(e){return Array.from(function*(){for(let t of"string"==typeof e.content?[{type:"text",text:e.content}]:e.content){if(R(t,"text")&&z(t.text)){yield{type:"text",text:t.text};continue}if(R(t,"thinking")&&z(t.thinking)){yield{type:"reasoning",reasoning:t.thinking,...t.signature?{signature:t.signature}:{}};continue}if(R(t,"inlineData")&&M(t.inlineData)&&z(t.inlineData.mimeType)&&z(t.inlineData.data)){yield{type:"file",mimeType:t.inlineData.mimeType,data:t.inlineData.data};continue}else if(R(t,"functionCall")&&M(t.functionCall)&&z(t.functionCall.name)&&M(t.functionCall.args)){yield{type:"tool_call",id:e.id,name:t.functionCall.name,args:t.functionCall.args};continue}else if(R(t,"functionResponse")){yield{type:"non_standard",value:t};continue}else if(R(t,"fileData")&&M(t.fileData)&&z(t.fileData.mimeType)&&z(t.fileData.fileUri)){yield{type:"file",mimeType:t.fileData.mimeType,fileId:t.fileData.fileUri};continue}else if(R(t,"executableCode")){yield{type:"non_standard",value:t};continue}else if(R(t,"codeExecutionResult")){yield{type:"non_standard",value:t};continue}yield{type:"non_standard",value:t}}}())}function ek(e){return Array.from(function*(){let t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(let r of t){if(R(r,"reasoning")&&z(r.reasoning)){let a=F(()=>{let a=t.indexOf(r);if(L(e.additional_kwargs?.signatures)&&a>=0)return e.additional_kwargs.signatures.at(a)});z(a)?yield{type:"reasoning",reasoning:r.reasoning,signature:a}:yield{type:"reasoning",reasoning:r.reasoning};continue}if(R(r,"thinking")&&z(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}if(R(r,"text")&&z(r.text)){yield{type:"text",text:r.text};continue}else if(R(r,"image_url")){if(z(r.image_url))if(r.image_url.startsWith("data:")){let e=r.image_url.match(/^data:([^;]+);base64,(.+)$/);e?yield{type:"image",data:e[2],mimeType:e[1]}:yield{type:"image",url:r.image_url}}else yield{type:"image",url:r.image_url};continue}else if(R(r,"media")&&z(r.mimeType)&&z(r.data)){yield{type:"file",mimeType:r.mimeType,data:r.data};continue}yield{type:"non_standard",value:r}}}())}function eS(e){let t=[],r=e.additional_kwargs?.reasoning;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content){let r=e.content,a=r.match(/<think>([\s\S]*?)<\/think>/);if(a){let e=a[1].trim();e.length>0&&t.push({type:"reasoning",reasoning:e}),r=r.replace(/<think>[\s\S]*?<\/think>/,"").trim()}r.length>0&&t.push({type:"text",text:r})}else for(let r of e.content)if("object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&z(r.text)){let e=r.text,a=e.match(/<think>([\s\S]*?)<\/think>/);if(a){let r=a[1].trim();r.length>0&&t.push({type:"reasoning",reasoning:r}),e=e.replace(/<think>[\s\S]*?<\/think>/,"").trim()}e.length>0&&t.push({type:"text",text:e})}for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function eE(e){let t=[],r=e.additional_kwargs?.reasoning_content;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(let r of e.content)"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&z(r.text)&&t.push({type:"text",text:r.text});for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function eT(e){let t=[],r=e.additional_kwargs?.reasoning_details,a=!1;if(Array.isArray(r)&&r.length>0)for(let e of r){if(null==e||"object"!=typeof e)continue;let r=e.type;if("reasoning.summary"===r){let r=e.summary;z(r)&&r.length>0&&(t.push({type:"reasoning",reasoning:r}),a=!0)}else if("reasoning.text"===r){let r=e.text;z(r)&&r.length>0&&(t.push({type:"reasoning",reasoning:r}),a=!0)}}if(!a){let r=e.additional_kwargs?.reasoning_content;z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r})}if("string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(let r of e.content)"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&z(r.text)&&t.push({type:"text",text:r.text});for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function eA(e){let t=[];if(M(e.additional_kwargs?.reasoning)){let r=e.additional_kwargs.reasoning;if(L(r.summary)){let e=r.summary.reduce((e,t)=>M(t)&&z(t.text)?`${e}${t.text}`:e,"");e.length>0&&t.push({type:"reasoning",reasoning:e})}}let r=e.additional_kwargs?.reasoning_content;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(let r of e.content)"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&z(r.text)&&t.push({type:"text",text:r.text});for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function eI(e){return Array.from(function*(){for(let t of F(()=>{if("string"==typeof e.content)if(e.additional_kwargs.originalTextContentBlock)return[{...e.additional_kwargs.originalTextContentBlock,type:"text"}];else return[{type:"text",text:e.content}];{let t=e.additional_kwargs?.originalTextContentBlock;if(t?.thoughtSignature&&!e.content.some(e=>"thoughtSignature"in e)){let r=[...e.content];for(let e=r.length-1;e>=0;e--){let a=r[e];if("text"===a.type&&!a.thought)return a.thoughtSignature=t.thoughtSignature,r}}return e.content}})){let r=F(()=>{if(R(t,"text")&&z(t.text))return{type:"text",text:t.text};if(R(t,"inlineData")&&M(t.inlineData)&&z(t.inlineData.mimeType)&&z(t.inlineData.data))return{type:"file",mimeType:t.inlineData.mimeType,data:t.inlineData.data};if(R(t,"functionCall")&&M(t.functionCall)&&z(t.functionCall.name)&&M(t.functionCall.args))return{type:"tool_call",id:e.id,name:t.functionCall.name,args:t.functionCall.args};if(R(t,"functionResponse"));else{if(R(t,"fileData")&&M(t.fileData)&&z(t.fileData.mimeType)&&z(t.fileData.fileUri))return{type:"file",mimeType:t.fileData.mimeType,fileId:t.fileData.fileUri};R(t,"executableCode")||R(t,"codeExecutionResult")}return{type:"non_standard",value:t}}),a=F(()=>"thought"in t&&t.thought?{type:"reasoning",reasoning:"text"===r.type?r.text:"",reasoningContentBlock:r}:r),i={thought:t.thought,thoughtSignature:t.thoughtSignature,partMetadata:t.partMetadata,...a};for(let e in i)void 0===i[e]&&delete i[e];yield i}}())}function eO(e){return globalThis.lc_block_translators_registry.get(e)}globalThis.lc_block_translators_registry??=new Map([["anthropic",{translateContent:q,translateContentChunk:q}],["bedrock-converse",{translateContent:ev,translateContentChunk:ev}],["deepseek",{translateContent:ew,translateContentChunk:ew}],["google",{translateContent:eI,translateContentChunk:eI}],["google-genai",{translateContent:ex,translateContentChunk:ex}],["google-vertexai",{translateContent:ek,translateContentChunk:ek}],["groq",{translateContent:eS,translateContentChunk:eS}],["ollama",{translateContent:eE,translateContentChunk:eE}],["openai",{translateContent:e=>{if("string"==typeof e.content){let t=[];for(let r of("string"==typeof e.content?e.content.length>0&&t.push({type:"text",text:e.content}):t.push(...W(e.content)),e.tool_calls??[]))t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}return K(e)},translateContentChunk:e=>{if("string"==typeof e.content){let t=[];for(let r of("string"==typeof e.content?e.content.length>0&&t.push({type:"text",text:e.content}):t.push(...W(e.content)),e.tool_calls??[]))t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}return Array.from(function*(){for(let t of(yield*K(e),e.tool_call_chunks??[]))yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args}}())}}],["openrouter",{translateContent:eT,translateContentChunk:eT}],["xai",{translateContent:eA,translateContentChunk:eA}]]);let eC=(function e(t){let r=Symbol.for(t);return{brand(e,a){let i=a?Symbol.for(`${t}.${a}`):r;class n extends e{[i]=!0;constructor(...e){super(...e)}static isInstance(e){return"object"==typeof e&&null!==e&&i in e&&!0===e[i]}}return Object.defineProperty(n,"name",{value:e.name}),n},sub:r=>e(`${t}.${r}`),isInstance:e=>"object"==typeof e&&null!==e&&r in e&&!0===e[r]}})("langchain").sub("error");var ej=class extends eC.brand(Error){name="LangChainError";constructor(e){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};function eP(e){return!!(e&&"object"==typeof e&&"type"in e&&"tool_call"===e.type)}eC.brand(ej,"model-abort"),eC.brand(ej,"context-overflow");var e$=class extends Error{output;constructor(e,t){super(e),this.output=t}},eN=class e extends et{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return e}constructor(e,t){("string"==typeof e||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&"generic"===e.type}get _printableFields(){return{...super._printableFields,role:this.role}}},eR=class extends eu{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(e,t){("string"==typeof e||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){return new this.constructor({content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"generic"===e.type}get _printableFields(){return{...super._printableFields,role:this.role}}},eM=class extends et{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},eL=class extends eu{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){return new this.constructor({content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}},ez=class extends et{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&"human"===e.type}},eU=class extends eu{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){return new this.constructor({content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"human"===e.type}};e.s(["HumanMessage",0,ez,"HumanMessageChunk",0,eU,"isHumanMessage",0,function(e){return"human"===e.getType()},"isHumanMessageChunk",0,function(e){return"human"===e.getType()}],165161);var eB=class extends et{type="remove";id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&"remove"===e.type}};e.s(["RemoveMessage",0,eB],795529);var eD=class e extends et{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}concat(t){if("string"==typeof t)return new e({content:X(this.content,t),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(e.isInstance(t))return new e({content:X(this.content,t.content),additional_kwargs:{...this.additional_kwargs,...t.additional_kwargs},response_metadata:{...this.response_metadata,...t.response_metadata},id:this.id??t.id,name:this.name??t.name});throw Error("Unexpected chunk type for system message")}static isInstance(e){return super.isInstance(e)&&"system"===e.type}},eF=class extends eu{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){return new this.constructor({content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"system"===e.type}};function eZ(e){return!0===e.isCustomTool}e.s(["SystemMessage",0,eD,"SystemMessageChunk",0,eF,"isSystemMessage",0,function(e){return"system"===e._getType()},"isSystemMessageChunk",0,function(e){return"system"===e._getType()}],265898);let eH=e=>e();function eq(e){return eP(e)?e:"string"==typeof e.id&&"function"===e.type&&"object"==typeof e.function&&null!==e.function&&"arguments"in e.function&&"string"==typeof e.function.arguments&&"name"in e.function&&"string"==typeof e.function.name?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function eJ(e){var t;let r,a;if("object"==typeof e&&null!=e&&1===e.lc&&Array.isArray(e.id)&&null!=e.kwargs&&"object"==typeof e.kwargs){let t=e.id.at(-1);r="HumanMessage"===t||"HumanMessageChunk"===t?"user":"AIMessage"===t||"AIMessageChunk"===t?"assistant":"SystemMessage"===t||"SystemMessageChunk"===t?"system":"FunctionMessage"===t||"FunctionMessageChunk"===t?"function":"ToolMessage"===t||"ToolMessageChunk"===t?"tool":"unknown",a=e.kwargs}else{let{type:t,...i}=e;r=t,a=i}if("human"===r||"user"===r)return new ez(a);if("ai"===r||"assistant"===r){let{tool_calls:e,...t}=a;if(!Array.isArray(e))return new e1(a);let r=e.map(eq);return new e1({...t,tool_calls:r})}if("system"===r)return new eD(a);if("developer"===r)return new eD({...a,additional_kwargs:{...a.additional_kwargs,__openai_role__:"developer"}});if("tool"===r&&"tool_call_id"in a)return new em({...a,content:a.content,tool_call_id:a.tool_call_id,name:a.name});if("remove"===r&&"id"in a&&"string"==typeof a.id)return new eB({...a,id:a.id});throw(t=Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
5
|
+
Right ${t}`)}var eu=class e extends et{static isInstance(t){if(!super.isInstance(t))return!1;let r=Object.getPrototypeOf(t);for(;null!==r;){if(r===e.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}};function ed(e){return"string"==typeof e.role}function ec(e){return"function"==typeof e?._getType}function eh(e){return eu.isInstance(e)}function ep(e,t){let r={};return(e?.audio!==void 0||t?.audio!==void 0)&&(r.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(r.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(r.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(r.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(r.text=(e?.text??0)+(t?.text??0)),r}function ef(e,t){var r,a,i,n;let s,o;return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:(s={...ep(r=e?.input_token_details,a=t?.input_token_details)},(r?.cache_read!==void 0||a?.cache_read!==void 0)&&(s.cache_read=(r?.cache_read??0)+(a?.cache_read??0)),(r?.cache_creation!==void 0||a?.cache_creation!==void 0)&&(s.cache_creation=(r?.cache_creation??0)+(a?.cache_creation??0)),s),output_token_details:(o={...ep(i=e?.output_token_details,n=t?.output_token_details)},(i?.reasoning!==void 0||n?.reasoning!==void 0)&&(o.reasoning=(i?.reasoning??0)+(n?.reasoning??0)),o)}}e.s(["BaseMessage",0,et,"BaseMessageChunk",0,eu,"DEFAULT_MERGE_IGNORE_KEYS",0,er,"_isMessageFieldWithRole",0,ed,"_mergeDicts",0,ea,"_mergeLists",0,eo,"_mergeObj",0,el,"_mergeStatus",0,ee,"isBaseMessage",0,ec,"isBaseMessageChunk",0,eh,"isOpenAIToolCallArray",0,function(e){return Array.isArray(e)&&e.every(e=>"number"==typeof e.index)},"mergeContent",0,X],44649);var em=class extends et{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(e,t,r){const a="string"==typeof e||Array.isArray(e)?{content:e,name:r,tool_call_id:t}:e;super(a),this.tool_call_id=a.tool_call_id,this.artifact=a.artifact,this.status=a.status,this.metadata=a.metadata}static isInstance(e){return super.isInstance(e)&&"tool"===e.type}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},eg=class extends eu{type="tool";tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){return new this.constructor({content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata),artifact:el(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:ee(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function ey(e){let t=[],r=[];for(let a of e)if(!a.function)continue;else{let e=a.function.name;try{let r=JSON.parse(a.function.arguments);t.push({name:e||"",args:r||{},id:a.id})}catch{r.push({name:e,args:a.function.arguments,id:a.id,error:"Malformed args."})}}return[t,r]}e.s(["ToolMessage",0,em,"ToolMessageChunk",0,eg,"defaultToolCallParser",0,ey,"isDirectToolOutput",0,function(e){return null!=e&&"object"==typeof e&&"lc_direct_tool_output"in e&&!0===e.lc_direct_tool_output},"isToolMessage",0,function(e){return"object"==typeof e&&null!==e&&"getType"in e&&"function"==typeof e.getType&&"tool"===e.getType()},"isToolMessageChunk",0,function(e){return"tool"===e._getType()}],399855);var e_=e.i(467034);function eb(e){switch(e){case"csv":return"text/csv";case"doc":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":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 ev(e){return Array.from(function*(){for(let t of"string"==typeof e.content?[{type:"text",text:e.content}]:e.content){if(R(t,"cache_point")){yield{type:"non_standard",value:t};continue}if(R(t,"citations_content")&&M(t.citationsContent)){yield{type:"text",text:z(t.citationsContent.content)?t.citationsContent.content.reduce((e,t)=>M(t)&&L(t.text)?e+t.text:e,""):"",annotations:z(t.citationsContent.citations)?t.citationsContent.citations.reduce((e,t)=>{if(M(t)){let r=z(t.sourceContent)?t.sourceContent.reduce((e,t)=>M(t)&&L(t.text)?e+t.text:e,""):"",a=F(()=>{if(M(t.location)){let e=t.location.documentChar||t.location.documentPage||t.location.documentChunk;if(M(e))return{source:U(e.documentIndex)?e.documentIndex.toString():void 0,startIndex:U(e.start)?e.start:void 0,endIndex:U(e.end)?e.end:void 0}}return{}});e.push({type:"citation",citedText:r,...a})}return e},[]):[]};continue}if(R(t,"document")&&M(t.document)){yield function(e){if(M(e.document)&&M(e.document.source)){let t=eb(M(e.document)&&L(e.document.format)?e.document.format:"");if(M(e.document.source)){if(M(e.document.source.s3Location)&&L(e.document.source.s3Location.uri))return{type:"file",mimeType:t,fileId:e.document.source.s3Location.uri};if(D(e.document.source.bytes))return{type:"file",mimeType:t,data:e.document.source.bytes};if(L(e.document.source.text))return{type:"file",mimeType:t,data:e_.Buffer.from(e.document.source.text).toString("base64")};if(z(e.document.source.content))return{type:"file",mimeType:t,data:e.document.source.content.reduce((e,t)=>M(t)&&L(t.text)?e+t.text:e,"")}}}return{type:"non_standard",value:e}}(t);continue}else if(R(t,"guard_content")){yield{type:"non_standard",value:t};continue}else if(R(t,"image")&&M(t.image)){yield function(e){if(R(e,"image")&&M(e.image)){let t=eb(M(e.image)&&L(e.image.format)?e.image.format:"");if(M(e.image.source)){if(M(e.image.source.s3Location)&&L(e.image.source.s3Location.uri))return{type:"image",mimeType:t,fileId:e.image.source.s3Location.uri};if(D(e.image.source.bytes))return{type:"image",mimeType:t,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}(t);continue}else if(R(t,"reasoning_content")&&L(t.reasoningText)){yield{type:"reasoning",reasoning:t.reasoningText};continue}else if(R(t,"text")&&L(t.text)){yield{type:"text",text:t.text};continue}else if(R(t,"tool_result")){yield{type:"non_standard",value:t};continue}else if(R(t,"tool_call"))continue;else if(R(t,"video")&&M(t.video)){yield function(e){if(R(e,"video")&&M(e.video)){let t=eb(M(e.video)&&L(e.video.format)?e.video.format:"");if(M(e.video.source)){if(M(e.video.source.s3Location)&&L(e.video.source.s3Location.uri))return{type:"video",mimeType:t,fileId:e.video.source.s3Location.uri};if(D(e.video.source.bytes))return{type:"video",mimeType:t,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}(t);continue}yield{type:"non_standard",value:t}}}())}function ew(e){let t=[],r=e.additional_kwargs?.reasoning_content;if(L(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(let r of e.content)"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&L(r.text)&&t.push({type:"text",text:r.text});for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function ex(e){return Array.from(function*(){for(let t of"string"==typeof e.content?[{type:"text",text:e.content}]:e.content){if(R(t,"text")&&L(t.text)){yield{type:"text",text:t.text};continue}if(R(t,"thinking")&&L(t.thinking)){yield{type:"reasoning",reasoning:t.thinking,...t.signature?{signature:t.signature}:{}};continue}if(R(t,"inlineData")&&M(t.inlineData)&&L(t.inlineData.mimeType)&&L(t.inlineData.data)){yield{type:"file",mimeType:t.inlineData.mimeType,data:t.inlineData.data};continue}else if(R(t,"functionCall")&&M(t.functionCall)&&L(t.functionCall.name)&&M(t.functionCall.args)){yield{type:"tool_call",id:e.id,name:t.functionCall.name,args:t.functionCall.args};continue}else if(R(t,"functionResponse")){yield{type:"non_standard",value:t};continue}else if(R(t,"fileData")&&M(t.fileData)&&L(t.fileData.mimeType)&&L(t.fileData.fileUri)){yield{type:"file",mimeType:t.fileData.mimeType,fileId:t.fileData.fileUri};continue}else if(R(t,"executableCode")){yield{type:"non_standard",value:t};continue}else if(R(t,"codeExecutionResult")){yield{type:"non_standard",value:t};continue}yield{type:"non_standard",value:t}}}())}function ek(e){return Array.from(function*(){let t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(let r of t){if(R(r,"reasoning")&&L(r.reasoning)){let a=F(()=>{let a=t.indexOf(r);if(z(e.additional_kwargs?.signatures)&&a>=0)return e.additional_kwargs.signatures.at(a)});L(a)?yield{type:"reasoning",reasoning:r.reasoning,signature:a}:yield{type:"reasoning",reasoning:r.reasoning};continue}if(R(r,"thinking")&&L(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}if(R(r,"text")&&L(r.text)){yield{type:"text",text:r.text};continue}else if(R(r,"image_url")){if(L(r.image_url))if(r.image_url.startsWith("data:")){let e=r.image_url.match(/^data:([^;]+);base64,(.+)$/);e?yield{type:"image",data:e[2],mimeType:e[1]}:yield{type:"image",url:r.image_url}}else yield{type:"image",url:r.image_url};continue}else if(R(r,"media")&&L(r.mimeType)&&L(r.data)){yield{type:"file",mimeType:r.mimeType,data:r.data};continue}yield{type:"non_standard",value:r}}}())}function eS(e){let t=[],r=e.additional_kwargs?.reasoning;if(L(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content){let r=e.content,a=r.match(/<think>([\s\S]*?)<\/think>/);if(a){let e=a[1].trim();e.length>0&&t.push({type:"reasoning",reasoning:e}),r=r.replace(/<think>[\s\S]*?<\/think>/,"").trim()}r.length>0&&t.push({type:"text",text:r})}else for(let r of e.content)if("object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&L(r.text)){let e=r.text,a=e.match(/<think>([\s\S]*?)<\/think>/);if(a){let r=a[1].trim();r.length>0&&t.push({type:"reasoning",reasoning:r}),e=e.replace(/<think>[\s\S]*?<\/think>/,"").trim()}e.length>0&&t.push({type:"text",text:e})}for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function eT(e){let t=[],r=e.additional_kwargs?.reasoning_content;if(L(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(let r of e.content)"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&L(r.text)&&t.push({type:"text",text:r.text});for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function eE(e){let t=[],r=e.additional_kwargs?.reasoning_details,a=!1;if(Array.isArray(r)&&r.length>0)for(let e of r){if(null==e||"object"!=typeof e)continue;let r=e.type;if("reasoning.summary"===r){let r=e.summary;L(r)&&r.length>0&&(t.push({type:"reasoning",reasoning:r}),a=!0)}else if("reasoning.text"===r){let r=e.text;L(r)&&r.length>0&&(t.push({type:"reasoning",reasoning:r}),a=!0)}}if(!a){let r=e.additional_kwargs?.reasoning_content;L(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r})}if("string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(let r of e.content)"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&L(r.text)&&t.push({type:"text",text:r.text});for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function eA(e){let t=[];if(M(e.additional_kwargs?.reasoning)){let r=e.additional_kwargs.reasoning;if(z(r.summary)){let e=r.summary.reduce((e,t)=>M(t)&&L(t.text)?`${e}${t.text}`:e,"");e.length>0&&t.push({type:"reasoning",reasoning:e})}}let r=e.additional_kwargs?.reasoning_content;if(L(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(let r of e.content)"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&L(r.text)&&t.push({type:"text",text:r.text});for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function eI(e){return Array.from(function*(){for(let t of F(()=>{if("string"==typeof e.content)if(e.additional_kwargs.originalTextContentBlock)return[{...e.additional_kwargs.originalTextContentBlock,type:"text"}];else return[{type:"text",text:e.content}];{let t=e.additional_kwargs?.originalTextContentBlock;if(t?.thoughtSignature&&!e.content.some(e=>"thoughtSignature"in e)){let r=[...e.content];for(let e=r.length-1;e>=0;e--){let a=r[e];if("text"===a.type&&!a.thought)return a.thoughtSignature=t.thoughtSignature,r}}return e.content}})){let r=F(()=>{if(R(t,"text")&&L(t.text))return{type:"text",text:t.text};if(R(t,"inlineData")&&M(t.inlineData)&&L(t.inlineData.mimeType)&&L(t.inlineData.data))return{type:"file",mimeType:t.inlineData.mimeType,data:t.inlineData.data};if(R(t,"functionCall")&&M(t.functionCall)&&L(t.functionCall.name)&&M(t.functionCall.args))return{type:"tool_call",id:e.id,name:t.functionCall.name,args:t.functionCall.args};if(R(t,"functionResponse"));else{if(R(t,"fileData")&&M(t.fileData)&&L(t.fileData.mimeType)&&L(t.fileData.fileUri))return{type:"file",mimeType:t.fileData.mimeType,fileId:t.fileData.fileUri};R(t,"executableCode")||R(t,"codeExecutionResult")}return{type:"non_standard",value:t}}),a=F(()=>"thought"in t&&t.thought?{type:"reasoning",reasoning:"text"===r.type?r.text:"",reasoningContentBlock:r}:r),i={thought:t.thought,thoughtSignature:t.thoughtSignature,partMetadata:t.partMetadata,...a};for(let e in i)void 0===i[e]&&delete i[e];yield i}}())}function eO(e){return globalThis.lc_block_translators_registry.get(e)}globalThis.lc_block_translators_registry??=new Map([["anthropic",{translateContent:q,translateContentChunk:q}],["bedrock-converse",{translateContent:ev,translateContentChunk:ev}],["deepseek",{translateContent:ew,translateContentChunk:ew}],["google",{translateContent:eI,translateContentChunk:eI}],["google-genai",{translateContent:ex,translateContentChunk:ex}],["google-vertexai",{translateContent:ek,translateContentChunk:ek}],["groq",{translateContent:eS,translateContentChunk:eS}],["ollama",{translateContent:eT,translateContentChunk:eT}],["openai",{translateContent:e=>{if("string"==typeof e.content){let t=[];for(let r of("string"==typeof e.content?e.content.length>0&&t.push({type:"text",text:e.content}):t.push(...W(e.content)),e.tool_calls??[]))t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}return K(e)},translateContentChunk:e=>{if("string"==typeof e.content){let t=[];for(let r of("string"==typeof e.content?e.content.length>0&&t.push({type:"text",text:e.content}):t.push(...W(e.content)),e.tool_calls??[]))t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}return Array.from(function*(){for(let t of(yield*K(e),e.tool_call_chunks??[]))yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args}}())}}],["openrouter",{translateContent:eE,translateContentChunk:eE}],["xai",{translateContent:eA,translateContentChunk:eA}]]);let eC=(function e(t){let r=Symbol.for(t);return{brand(e,a){let i=a?Symbol.for(`${t}.${a}`):r;class n extends e{[i]=!0;constructor(...e){super(...e)}static isInstance(e){return"object"==typeof e&&null!==e&&i in e&&!0===e[i]}}return Object.defineProperty(n,"name",{value:e.name}),n},sub:r=>e(`${t}.${r}`),isInstance:e=>"object"==typeof e&&null!==e&&r in e&&!0===e[r]}})("langchain").sub("error");var ej=class extends eC.brand(Error){name="LangChainError";constructor(e){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};function e$(e){return!!(e&&"object"==typeof e&&"type"in e&&"tool_call"===e.type)}eC.brand(ej,"model-abort"),eC.brand(ej,"context-overflow");var eP=class extends Error{output;constructor(e,t){super(e),this.output=t}},eN=class e extends et{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return e}constructor(e,t){("string"==typeof e||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&"generic"===e.type}get _printableFields(){return{...super._printableFields,role:this.role}}},eR=class extends eu{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(e,t){("string"==typeof e||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){return new this.constructor({content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"generic"===e.type}get _printableFields(){return{...super._printableFields,role:this.role}}},eM=class extends et{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},ez=class extends eu{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){return new this.constructor({content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}},eL=class extends et{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&"human"===e.type}},eU=class extends eu{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){return new this.constructor({content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"human"===e.type}};e.s(["HumanMessage",0,eL,"HumanMessageChunk",0,eU,"isHumanMessage",0,function(e){return"human"===e.getType()},"isHumanMessageChunk",0,function(e){return"human"===e.getType()}],165161);var eD=class extends et{type="remove";id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&"remove"===e.type}};e.s(["RemoveMessage",0,eD],795529);var eB=class e extends et{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}concat(t){if("string"==typeof t)return new e({content:X(this.content,t),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(e.isInstance(t))return new e({content:X(this.content,t.content),additional_kwargs:{...this.additional_kwargs,...t.additional_kwargs},response_metadata:{...this.response_metadata,...t.response_metadata},id:this.id??t.id,name:this.name??t.name});throw Error("Unexpected chunk type for system message")}static isInstance(e){return super.isInstance(e)&&"system"===e.type}},eF=class extends eu{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){return new this.constructor({content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"system"===e.type}};function eZ(e){return!0===e.isCustomTool}e.s(["SystemMessage",0,eB,"SystemMessageChunk",0,eF,"isSystemMessage",0,function(e){return"system"===e._getType()},"isSystemMessageChunk",0,function(e){return"system"===e._getType()}],265898);let eH=e=>e();function eq(e){return e$(e)?e:"string"==typeof e.id&&"function"===e.type&&"object"==typeof e.function&&null!==e.function&&"arguments"in e.function&&"string"==typeof e.function.arguments&&"name"in e.function&&"string"==typeof e.function.name?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function eJ(e){var t;let r,a;if("object"==typeof e&&null!=e&&1===e.lc&&Array.isArray(e.id)&&null!=e.kwargs&&"object"==typeof e.kwargs){let t=e.id.at(-1);r="HumanMessage"===t||"HumanMessageChunk"===t?"user":"AIMessage"===t||"AIMessageChunk"===t?"assistant":"SystemMessage"===t||"SystemMessageChunk"===t?"system":"FunctionMessage"===t||"FunctionMessageChunk"===t?"function":"ToolMessage"===t||"ToolMessageChunk"===t?"tool":"unknown",a=e.kwargs}else{let{type:t,...i}=e;r=t,a=i}if("human"===r||"user"===r)return new eL(a);if("ai"===r||"assistant"===r){let{tool_calls:e,...t}=a;if(!Array.isArray(e))return new e1(a);let r=e.map(eq);return new e1({...t,tool_calls:r})}if("system"===r)return new eB(a);if("developer"===r)return new eB({...a,additional_kwargs:{...a.additional_kwargs,__openai_role__:"developer"}});if("tool"===r&&"tool_call_id"in a)return new em({...a,content:a.content,tool_call_id:a.tool_call_id,name:a.name});if("remove"===r&&"id"in a&&"string"==typeof a.id)return new eD({...a,id:a.id});throw(t=Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
6
6
|
|
|
7
7
|
Received: ${JSON.stringify(e,null,2)}`)).lc_error_code="MESSAGE_COERCION_FAILURE",t.message=`${t.message}
|
|
8
8
|
|
|
9
9
|
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/MESSAGE_COERCION_FAILURE/
|
|
10
|
-
`,t}function eG(e){if("string"==typeof e)return new ez(e);if(ec(e))return e;if(Array.isArray(e)){let[t,r]=e;return eJ({type:t,content:r})}if(!ed(e))return eJ(e);{let{role:t,...r}=e;return eJ({...r,type:t})}}function eW(e){if("string"==typeof e)return e;switch(e.type){case"text":return e.text??"";case"text-plain":return e.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return e.type?`[${e.type}]`:""}}function eV(e,t="Human",r="AI"){let a=[];for(let i of e){let e;if("human"===i.type)e=t;else if("ai"===i.type)e=r;else if("system"===i.type)e="System";else if("tool"===i.type)e="Tool";else if("generic"===i.type)e=i.role;else throw Error(`Got unsupported message type: ${i.type}`);let n=i.name?`${i.name}, `:"",s="string"==typeof i.content?i.content:Array.isArray(i.content)?i.content.map(eW).filter(Boolean).join(""):"",o=`${e}: ${n}${s}`;"ai"===i.type&&(i.tool_calls&&i.tool_calls.length>0?o+=JSON.stringify(i.tool_calls):i.additional_kwargs&&"function_call"in i.additional_kwargs&&(o+=JSON.stringify(i.additional_kwargs.function_call))),a.push(o)}return a.join("\n")}function eK(e){let t=void 0!==e.data?e:{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}};switch(t.type){case"human":return new ez(t.data);case"ai":return new e1(t.data);case"system":return new eD(t.data);case"function":if(void 0===t.data.name)throw Error("Name must be defined for function messages");return new eM(t.data);case"tool":if(void 0===t.data.tool_call_id)throw Error("Tool call ID must be defined for tool messages");return new em(t.data);case"generic":if(void 0===t.data.role)throw Error("Role must be defined for chat messages");return new eN(t.data);default:throw Error(`Got unexpected type: ${t.type}`)}}function eQ(e){return e.map(eK)}function eY(e){return e.map(e=>e.toDict())}function eX(e){let t=e._getType();if("human"===t)return new eU({...e});if("ai"===t){let t={...e};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)}))}),new e6({...t})}if("system"===t)return new eF({...e});if("function"===t)return new eL({...e});if(eN.isInstance(e))return new eR({...e});else throw Error("Unknown message type.")}function e0(e){let t=e.reduce((e,t)=>{let r=e.findIndex(([e])=>"id"in t&&t.id&&"index"in t&&void 0!==t.index?t.id===e.id&&t.index===e.index:"id"in t&&t.id?t.id===e.id:"index"in t&&void 0!==t.index&&t.index===e.index);return -1!==r?e[r].push(t):e.push([t]),e},[]),r=[],a=[];for(let e of t){let t=null,i=e.some(eZ),n=e[0]?.name??"",s=e.map(e=>e.args||"").join(""),o=i?s:s.trim(),l=o.length?o:"{}",u=e.find(e=>e.id)?.id??e[0]?.id;if(i&&u){r.push({name:n,args:{input:o},id:u,type:"tool_call"});continue}try{if(t=function(e){try{if(void 0===e)return null;return function(e){try{return JSON.parse(e)}catch{}let t=e.trim();if(0===t.length)throw Error("Unexpected end of JSON input");let r=0;function a(){for(;r<t.length&&/\s/.test(t[r]);)r+=1}function i(){if('"'!==t[r])throw Error(`Expected '"' at position ${r}, got '${t[r]}'`);r+=1;let e="",a=!1;for(;r<t.length;){let i=t[r];if(a){if("n"===i)e+="\n";else if("t"===i)e+=" ";else if("r"===i)e+="\r";else if("\\"===i)e+="\\";else if('"'===i)e+='"';else if("b"===i)e+="\b";else if("f"===i)e+="\f";else if("/"===i)e+="/";else if("u"===i){let a=t.substring(r+1,r+5);if(/^[0-9A-Fa-f]{0,4}$/.test(a))4===a.length?e+=String.fromCharCode(Number.parseInt(a,16)):e+=`u${a}`,r+=a.length;else throw Error(`Invalid unicode escape sequence '\\u${a}' at position ${r}`)}else throw Error(`Invalid escape sequence '\\${i}' at position ${r}`);a=!1}else if("\\"===i)a=!0;else{if('"'===i)return r+=1,e;e+=i}r+=1}return a&&(e+="\\"),e}let n=function e(){if(a(),r>=t.length)throw Error(`Unexpected end of input at position ${r}`);let n=t[r];if("{"===n)return function(){if("{"!==t[r])throw Error(`Expected '{' at position ${r}, got '${t[r]}'`);let n={};if(r+=1,a(),r>=t.length)return n;if("}"===t[r])return r+=1,n;for(;r<t.length&&(a(),!(r>=t.length));){let s=i();if(a(),r>=t.length)break;if(":"!==t[r])throw Error(`Expected ':' at position ${r}, got '${t[r]}'`);if(r+=1,a(),r>=t.length||(n[s]=e(),a(),r>=t.length))break;if("}"===t[r]){r+=1;break}if(","===t[r]){r+=1;continue}throw Error(`Expected ',' or '}' at position ${r}, got '${t[r]}'`)}return n}();if("["===n)return function(){if("["!==t[r])throw Error(`Expected '[' at position ${r}, got '${t[r]}'`);let i=[];if(r+=1,a(),r>=t.length)return i;if("]"===t[r])return r+=1,i;for(;r<t.length&&(a(),!(r>=t.length))&&(i.push(e()),a(),!(r>=t.length));){;if("]"===t[r]){r+=1;break}if(","===t[r]){r+=1;continue}throw Error(`Expected ',' or ']' at position ${r}, got '${t[r]}'`)}return i}();if('"'===n)return i();if("null".startsWith(t.substring(r,r+4)))return r+=Math.min(4,t.length-r),null;if("true".startsWith(t.substring(r,r+4)))return r+=Math.min(4,t.length-r),!0;if("false".startsWith(t.substring(r,r+5)))return r+=Math.min(5,t.length-r),!1;if("-"===n||n>="0"&&n<="9"){let e=r,a="";if("-"===t[r]&&(a+="-",r+=1),r<t.length&&"0"===t[r]&&(a+="0",t[r+=1]>="0"&&t[r]<="9"))throw Error(`Invalid number at position ${e}`);if(r<t.length&&t[r]>="1"&&t[r]<="9")for(;r<t.length&&t[r]>="0"&&t[r]<="9";)a+=t[r],r+=1;if(r<t.length&&"."===t[r])for(a+=".",r+=1;r<t.length&&t[r]>="0"&&t[r]<="9";)a+=t[r],r+=1;if(r<t.length&&("e"===t[r]||"E"===t[r]))for(a+=t[r],(r+=1)<t.length&&("+"===t[r]||"-"===t[r])&&(a+=t[r],r+=1);r<t.length&&t[r]>="0"&&t[r]<="9";)a+=t[r],r+=1;if("-"===a)return -0;let i=Number.parseFloat(a);if(Number.isNaN(i))throw r=e,Error(`Invalid number '${a}' at position ${e}`);return i}throw Error(`Unexpected character '${n}' at position ${r}`)}();if(a(),r<t.length)throw Error(`Unexpected character '${t[r]}' at position ${r}`);return n}(e)}catch{return null}}(l),!u||null===t||"object"!=typeof t||Array.isArray(t))throw Error("Malformed tool call chunk args.");r.push({name:n,args:t,id:u,type:"tool_call"})}catch{a.push({name:n,args:l,id:u,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:e,tool_calls:r,invalid_tool_calls:a}}var e1=class extends et{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(e){let t;if("string"==typeof e||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;const r=t.additional_kwargs?.tool_calls,a=t.tool_calls;null!=r&&r.length>0&&(void 0===a||0===a.length)&&console.warn("New LangChain packages are available that more efficiently handle tool calling.\n\nPlease upgrade your packages to versions that set message tool calls. e.g., `pnpm install @langchain/anthropic`, pnpm install @langchain/openai`, etc.");try{if(null!=r&&void 0===a){const[e,a]=ey(r);t.tool_calls=e??[],t.invalid_tool_calls=a??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(void 0!==t.response_metadata&&"output_version"in t.response_metadata&&"v1"===t.response_metadata.output_version&&(t.contentBlocks=t.content,t.content=void 0),void 0!==t.contentBlocks){if(t.tool_calls){const e=t.tool_calls.filter(e=>!t.contentBlocks?.some(t=>"tool_call"===t.type&&t.id===e.id&&t.name===e.name));t.contentBlocks.push(...e.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args})))}const e=t.contentBlocks.filter(e=>"tool_call"===e.type).filter(e=>!t.tool_calls?.some(t=>t.id===e.id&&t.name===e.name));e.length>0&&(t.tool_calls=[...t.tool_calls??[],...e.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args}))])}}super(t),"string"!=typeof t&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&"v1"===this.response_metadata.output_version)return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&"string"==typeof this.response_metadata.model_provider){let e=eO(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let t=this.tool_calls.filter(t=>!e.some(e=>e.id===t.id&&e.name===t.name));e.push(...t.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&"ai"===e.type}};function e2(e){return"ai"===e._getType()}function e4(e){return"ai"===e._getType()}var e6=class extends eu{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if("string"==typeof e||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(void 0===e.tool_call_chunks||0===e.tool_call_chunks.length)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0};else{const r=e0(e.tool_call_chunks??[]);t={...e,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&"v1"===this.response_metadata.output_version)return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&"string"==typeof this.response_metadata.model_provider){let e=eO(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&"string"!=typeof this.content){let t=this.content.filter(e=>"tool_call"===e.type).map(e=>e.id);for(let r of this.tool_calls)r.id&&!t.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let t={content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata)??{},tool_call_chunks:[],tool_calls:[],id:this.id??e.id};if(void 0!==this.tool_call_chunks||void 0!==e.tool_call_chunks){let r=eo(this.tool_call_chunks,e.tool_call_chunks);void 0!==r&&r.length>0&&(t.tool_call_chunks=r)}if(void 0!==this.tool_calls||void 0!==e.tool_calls){let r=eo(this.tool_calls,e.tool_calls);void 0!==r&&r.length>0&&(t.tool_calls=r)}return(void 0!==this.usage_metadata||void 0!==e.usage_metadata)&&(t.usage_metadata=ef(this.usage_metadata,e.usage_metadata)),new this.constructor(t)}static isInstance(e){return super.isInstance(e)&&"ai"===e.type}},e5=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function e9(e){return"string"==typeof e&&e5.test(e)}function e3(e){let t;if(!e9(e))throw TypeError("Invalid UUID");return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/0x10000000000&255,t/0x100000000&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)}let e8=[];for(let e=0;e<256;++e)e8.push((e+256).toString(16).slice(1));function e7(e,t=0){return(e8[e[t+0]]+e8[e[t+1]]+e8[e[t+2]]+e8[e[t+3]]+"-"+e8[e[t+4]]+e8[e[t+5]]+"-"+e8[e[t+6]]+e8[e[t+7]]+"-"+e8[e[t+8]]+e8[e[t+9]]+"-"+e8[e[t+10]]+e8[e[t+11]]+e8[e[t+12]]+e8[e[t+13]]+e8[e[t+14]]+e8[e[t+15]]).toLowerCase()}let te=new Uint8Array(16);function tt(){return crypto.getRandomValues(te)}function tr(e,t){return e<<t|e>>>32-t}function ta(e){let t=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6],r=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],a=new Uint8Array(e.length+1);a.set(e),a[e.length]=128;let i=Math.ceil(((e=a).length/4+2)/16),n=Array(i);for(let t=0;t<i;++t){let r=new Uint32Array(16);for(let a=0;a<16;++a)r[a]=e[64*t+4*a]<<24|e[64*t+4*a+1]<<16|e[64*t+4*a+2]<<8|e[64*t+4*a+3];n[t]=r}n[i-1][14]=(e.length-1)*8/0x100000000,n[i-1][14]=Math.floor(n[i-1][14]),n[i-1][15]=(e.length-1)*8|0;for(let e=0;e<i;++e){let a=new Uint32Array(80);for(let t=0;t<16;++t)a[t]=n[e][t];for(let e=16;e<80;++e)a[e]=tr(a[e-3]^a[e-8]^a[e-14]^a[e-16],1);let i=r[0],s=r[1],o=r[2],l=r[3],u=r[4];for(let e=0;e<80;++e){let r=Math.floor(e/20),n=tr(i,5)+function(e,t,r,a){switch(e){case 0:return t&r^~t&a;case 1:case 3:return t^r^a;case 2:return t&r^t&a^r&a}}(r,s,o,l)+u+t[r]+a[e]>>>0;u=l,l=o,o=tr(s,30)>>>0,s=i,i=n}r[0]=r[0]+i>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+o>>>0,r[3]=r[3]+l>>>0,r[4]=r[4]+u>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}function ti(e,t,r,a){var i=t,n=a;let s="string"==typeof e?function(e){let t=new Uint8Array((e=unescape(encodeURIComponent(e))).length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}(e):e,o="string"==typeof i?e3(i):i;if("string"==typeof i&&(i=e3(i)),i?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+s.length);if(l.set(o),l.set(s,o.length),(l=ta(l))[6]=15&l[6]|80,l[8]=63&l[8]|128,r){if((n??=0)<0||n+16>r.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)r[n+e]=l[e];return r}return e7(l)}ti.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ti.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";let tn={};function ts(e,t,r,a,i=0){if(e.length<16)throw Error("Random bytes length must be >= 16");if(a){if(i<0||i+16>a.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`)}else a=new Uint8Array(16),i=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],a[i++]=t/0x10000000000&255,a[i++]=t/0x100000000&255,a[i++]=t/0x1000000&255,a[i++]=t/65536&255,a[i++]=t/256&255,a[i++]=255&t,a[i++]=112|r>>>28&15,a[i++]=r>>>20&255,a[i++]=128|r>>>14&63,a[i++]=r>>>6&255,a[i++]=r<<2&255|3&e[10],a[i++]=e[11],a[i++]=e[12],a[i++]=e[13],a[i++]=e[14],a[i++]=e[15],a}let to=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){let a=(e=e||{}).random??e.rng?.()??tt();if(a.length<16)throw Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){if((r=r||0)<0||r+16>t.length)throw RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=a[e];return t}return e7(a)}(e,t,r):crypto.randomUUID()},tl=function(e,t,r){let a;if(e)a=ts(e.random??e.rng?.()??tt(),e.msecs,e.seq,t,r);else{var i,n,s;let e=Date.now(),o=tt();i=tn,n=e,s=o,i.msecs??=-1/0,i.seq??=0,n>i.msecs?(i.seq=s[6]<<23|s[7]<<16|s[8]<<8|s[9],i.msecs=n):(i.seq=i.seq+1|0,0===i.seq&&i.msecs++),a=ts(o,tn.msecs,tn.seq,t,r)}return t??e7(a)};e.s(["v4",0,to,"v7",0,tl,"validate",0,e9],230125);let tu=Symbol.for("ls:tracing_async_local_storage"),td=Symbol.for("lc:context_variables"),tc=()=>globalThis[tu];var th=e.i(247167);function tp(e){try{if(void 0!==th.default)return th.default.env?.[e];if("u">typeof Deno)return Deno?.env.get(e);return}catch{return}}var tf=class{},tm=class extends tf{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,$(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers="false"===tp("LANGCHAIN_CALLBACKS_BACKGROUND");constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return N.prototype.toJSON.call(this)}toJSONNotImplemented(){return N.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends tm{name=tl();constructor(){super(),Object.assign(this,e)}}return new t}};let tg=e=>void 0!==e&&"function"==typeof e.copy&&"string"==typeof e.name&&"boolean"==typeof e.awaitHandlers,ty=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i,t_=[];for(let e=0;e<256;++e)t_.push((e+256).toString(16).slice(1));function tb(e,t=0){return(t_[e[t+0]]+t_[e[t+1]]+t_[e[t+2]]+t_[e[t+3]]+"-"+t_[e[t+4]]+t_[e[t+5]]+"-"+t_[e[t+6]]+t_[e[t+7]]+"-"+t_[e[t+8]]+t_[e[t+9]]+"-"+t_[e[t+10]]+t_[e[t+11]]+t_[e[t+12]]+t_[e[t+13]]+t_[e[t+14]]+t_[e[t+15]]).toLowerCase()}let tv=new Uint8Array(16);function tw(){return crypto.getRandomValues(tv)}let tx=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){let a=(e=e||{}).random??e.rng?.()??tw();if(a.length<16)throw Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){if((r=r||0)<0||r+16>t.length)throw RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=a[e];return t}return tb(a)}(e,t,r):crypto.randomUUID()};function tk(e,t){return e<<t|e>>>32-t}let tS=function(e){let t=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6],r=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],a=new Uint8Array(e.length+1);a.set(e),a[e.length]=128;let i=Math.ceil(((e=a).length/4+2)/16),n=Array(i);for(let t=0;t<i;++t){let r=new Uint32Array(16);for(let a=0;a<16;++a)r[a]=e[64*t+4*a]<<24|e[64*t+4*a+1]<<16|e[64*t+4*a+2]<<8|e[64*t+4*a+3];n[t]=r}n[i-1][14]=(e.length-1)*8/0x100000000,n[i-1][14]=Math.floor(n[i-1][14]),n[i-1][15]=(e.length-1)*8|0;for(let e=0;e<i;++e){let a=new Uint32Array(80);for(let t=0;t<16;++t)a[t]=n[e][t];for(let e=16;e<80;++e)a[e]=tk(a[e-3]^a[e-8]^a[e-14]^a[e-16],1);let i=r[0],s=r[1],o=r[2],l=r[3],u=r[4];for(let e=0;e<80;++e){let r=Math.floor(e/20),n=tk(i,5)+function(e,t,r,a){switch(e){case 0:return t&r^~t&a;case 1:case 3:return t^r^a;case 2:return t&r^t&a^r&a}}(r,s,o,l)+u+t[r]+a[e]>>>0;u=l,l=o,o=tk(s,30)>>>0,s=i,i=n}r[0]=r[0]+i>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+o>>>0,r[3]=r[3]+l>>>0,r[4]=r[4]+u>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])},tE=function(e){let t;if(!("string"==typeof e&&ty.test(e)))throw TypeError("Invalid UUID");return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/0x10000000000&255,t/0x100000000&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)};function tT(e,t,r,a){var i=t,n=a;let s="string"==typeof e?function(e){let t=new Uint8Array((e=unescape(encodeURIComponent(e))).length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}(e):e,o="string"==typeof i?tE(i):i;if("string"==typeof i&&(i=tE(i)),i?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+s.length);if(l.set(o),l.set(s,o.length),(l=tS(l))[6]=15&l[6]|80,l[8]=63&l[8]|128,r){if((n??=0)<0||n+16>r.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)r[n+e]=l[e];return r}return tb(l)}tT.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",tT.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";let tA={};function tI(e,t,r,a,i=0){if(e.length<16)throw Error("Random bytes length must be >= 16");if(a){if(i<0||i+16>a.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`)}else a=new Uint8Array(16),i=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],a[i++]=t/0x10000000000&255,a[i++]=t/0x100000000&255,a[i++]=t/0x1000000&255,a[i++]=t/65536&255,a[i++]=t/256&255,a[i++]=255&t,a[i++]=112|r>>>28&15,a[i++]=r>>>20&255,a[i++]=128|r>>>14&63,a[i++]=r>>>6&255,a[i++]=r<<2&255|3&e[10],a[i++]=e[11],a[i++]=e[12],a[i++]=e[13],a[i++]=e[14],a[i++]=e[15],a}let tO=function(e,t,r){let a;if(e)a=tI(e.random??e.rng?.()??tw(),e.msecs,e.seq,t,r);else{var i,n,s;let e=Date.now(),o=tw();i=tA,n=e,s=o,i.msecs??=-1/0,i.seq??=0,n>i.msecs?(i.seq=s[6]<<23|s[7]<<16|s[8]<<8|s[9],i.msecs=n):(i.seq=i.seq+1|0,0===i.seq&&i.msecs++),a=tI(o,tA.msecs,tA.seq,t,r)}return t??tb(a)},tC="gen_ai.request.model",tj="gen_ai.usage.input_tokens",tP="gen_ai.usage.output_tokens",t$="gen_ai.usage.total_tokens",tN="langsmith.span.tags",tR="langsmith.usage_metadata",tM=Symbol.for("ls:fetch_implementation"),tL=()=>rw("PROJECT")??rv("LANGCHAIN_SESSION")??"default",tz=e=>BigInt(e),tU=tz("0x9E3779B1"),tB=tz("0x85EBCA77"),tD=tz("0xC2B2AE3D"),tF=tz("0x9E3779B185EBCA87"),tZ=tz("0xC2B2AE3D27D4EB4F"),tH=tz("0x165667B19E3779F9"),tq=tz("0x85EBCA77C2B2AE63"),tJ=tz("0x27D4EB2F165667C5"),tG=tz("0x165667919E3779F9"),tW=tz("0x9FB21C651E98DF25"),tV=function(e){let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substring(r,r+2),16);return t}("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),tK=(tz(1)<<tz(128))-tz(1),tQ=(tz(1)<<tz(64))-tz(1),tY=(tz(1)<<tz(32))-tz(1);function tX(e,t=0){return new Uint8Array(e.buffer,e.byteOffset+t,e.length-t)}function t0(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getBigUint64(0,!0)}function t1(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getUint32(0,!0)}function t2(e,t=0){return e[t]}let t4=(e,t)=>(e&tY)*(t&tY)&tQ,t6=e=>{if(!e)throw Error("Assert failed")};function t5(e,t,r){for(let a=0;a<8;a++){let i=t0(t,8*a),n=i^t0(r,8*a);e[1^a]+=i,e[a]+=t4(n,n>>tz(32))}return e}function t9(e,t,r,a){for(let i=0;i<a;i++)t5(e,tX(t,64*i),tX(r,8*i));return e}function t3(e,t){for(let a=0;a<8;a++){var r;let i=t0(t,8*a),n=e[a];n=((r=n)^r>>tz(47)^i)*tU,e[a]=n&tQ}return e}function t8(e,t){return re(e[0]^t0(t,0),e[1]^t0(t,8))}function t7(e,t,r){let a=r;return a+=t8(e.slice(0),tX(t,0)),a+=t8(e.slice(2),tX(t,16)),a+=t8(e.slice(4),tX(t,32)),ra((a+=t8(e.slice(6),tX(t,48)))&tQ)}function re(e,t){let r=e*t&tK;return r&tQ^r>>tz(64)}function rt(e,t,r){return re((t0(e,0)^t0(t,0)+r)&tQ,(t0(e,8)^t0(t,8)-r)&tQ)}function rr(e,t,r,a,i){let n=e&tQ,s=e>>tz(64)&tQ;return n+=rt(t,a,i),n^=t0(r,0)+t0(r,8),n&=tQ,s+=rt(r,tX(a,16),i),s^=t0(t,0)+t0(t,8),(s&=tQ)<<tz(64)|n}function ra(e){return e^=e>>tz(37),e*=tG,e&=tQ,e^=e>>tz(32)}function ri(e){return e^=e>>tz(33),e*=tZ,e&=tQ,e^=e>>tz(29),e*=tH,e&=tQ,e^=e>>tz(32)}function rn(e){return~e+tz(1)&tQ}let rs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ro(e,t){if(!rs.test(e))throw Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`);return e}let rl=new TextEncoder;function ru(e,t){var r,a;let i,n,s,o,l=(r=`${e}:${t}`,a=function(e,t=tz(0)){let r,a,i=e.byteLength;return i<=16?function(e,t){var r,a,i,n,s;let o=e.byteLength;if(t6(o<=16),o>8){let r,a,i,n,s,o,l,u;return t6((r=e.byteLength)>=9&&r<=16),a=(t0(tV,32)^t0(tV,40))+t&tQ,i=(t0(tV,48)^t0(tV,56))-t&tQ,o=((s=(t0(e)^(n=t0(e,r-8))^a)*tF)&tQ)+(tz(r-1)<<tz(54)),s=s&(tK^tQ)|o,n^=i,s+=n+(n&tY)*(tB-tz(1))<<tz(64),s&=tK,s^=((l=s>>tz(64))&tz(255))<<tz(56)|(l&tz(65280))<<tz(40)|(l&tz(0xff0000))<<tz(24)|(l&tz(0xff000000))<<tz(8)|(l&tz(0xff00000000))>>tz(8)|(l&tz(0xff0000000000))>>tz(24)|(l&tz(0xff000000000000))>>tz(40)|(l&tz(0xff00000000000000))>>tz(56),ra((u=(s&tQ)*tZ+((s>>tz(64))*tZ<<tz(64))&tK)&tQ)|ra(u>>tz(64))<<tz(64)}if(o>=4){let i,n,s,o,l;return t6((i=e.byteLength)>=4&&i<=8),n=t1(e,0),s=t1(e,i-4),o=tz(n)|tz(s)<<tz(32),l=(o^(t0(tV,16)^t0(tV,24))+t&tQ)*(tF+(tz(i)<<tz(2)))&tK,l+=(l&tQ)<<tz(65),l&=tK,l^=l>>tz(67),(a=((r=l&tQ)^r>>tz(35))*tW&tQ)^a>>tz(28)|ra(l>>tz(64))<<tz(64)}if(o>0){let r,a,o,l;return t6((r=e.byteLength)>0&&r<=3),o=((a=tz(t2(e,r-1))|tz(r<<8)|tz(t2(e,0)<<16)|tz(t2(e,r>>1)<<24))^(tz(t1(tV,0))^tz(t1(tV,4)))+t)&tQ,l=(tz(t1(tV,8))^tz(t1(tV,12)))-t,(ri((((n=i=((i=((i=a)&tz(65535))<<tz(16)|(i&tz(0xffff0000))>>tz(16))&tz(0xff00ff))<<tz(8)|(i&tz(0xff00ff00))>>tz(8))<<(s=tz(13))|n>>tz(32)-s)&tY^l)&tQ)&tQ)<<tz(64)|ri(o)}return ri(t^t0(tV,64)^t0(tV,72))|ri(t^t0(tV,80)^t0(tV,88))<<tz(64)}(e,t):i<=128?function(e,t,r){let a=tz(e.byteLength)*tF&tQ,i=tz(e.byteLength-1)/tz(32);for(;i>=0;){let n=Number(i);a=rr(a,tX(e,16*n),tX(e,e.byteLength-16*(n+1)),tX(t,32*n),r),i--}let n=a+(a>>tz(64))&tQ;n=ra(n);let s=(a&tQ)*tF+(a>>tz(64))*tq+(tz(e.byteLength)-r&tQ)*tZ;return s&=tQ,n|(s=rn(ra(s)))<<tz(64)}(e,tV,t):i<=240?function(e,t,r){let a=tz(e.byteLength)*tF&tQ;for(let i=32;i<160;i+=32)a=rr(a,tX(e,i-32),tX(e,i-16),tX(t,i-32),r);a=ra(a&tQ)|ra(a>>tz(64))<<tz(64);for(let i=160;i<=e.byteLength;i+=32)a=rr(a,tX(e,i-32),tX(e,i-16),tX(t,3+i-160),r);let i=(a=rr(a,tX(e,e.byteLength-16),tX(e,e.byteLength-32),tX(t,103),rn(r)))+(a>>tz(64))&tQ;i=ra(i);let n=(a&tQ)*tF+(a>>tz(64))*tq+(tz(e.byteLength)-r&tQ)*tZ;return n&=tQ,i|(n=rn(ra(n)))<<tz(64)}(e,tV,t):(r=new BigUint64Array([tD,tF,tZ,tH,tq,tB,tJ,tU]),t6(e.length>128),t6(8*(r=function(e,t,r,a,i){let n=Math.floor((r.byteLength-64)/8),s=64*n,o=Math.floor((t.byteLength-1)/s);for(let a=0;a<o;a++)e=i(e=t9(e,tX(t,a*s),r,n),tX(r,r.byteLength-64));{let i=Math.floor((t.byteLength-1-s*o)/64);e=a(e=t9(e,tX(t,o*s),r,i),tX(t,t.byteLength-64),tX(r,r.byteLength-64-7))}return e}(r,e,tV,t5,t3)).length==64),a=t7(r,tX(tV,11),tz(e.byteLength)*tF&tQ),t7(r,tX(tV,tV.byteLength-64-11),~(tz(e.byteLength)*tZ)&tQ)<<tz(64)|a)}(rl.encode(r)),n=new DataView((i=new Uint8Array(16)).buffer),s=a>>tz(64),n.setBigUint64(0,s,!1),n.setBigUint64(8,a&tQ,!1),i),u=new Uint8Array(16);if(7===(rs.test(e)?parseInt(e[14],16):null)){let t=function(e){let t=e.replace(/-/g,""),r=new Uint8Array(16);for(let e=0;e<16;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}(e);u.set(t.slice(0,6),0)}else{let e=Date.now();u[0]=e/0x10000000000&255,u[1]=e/0x100000000&255,u[2]=e/0x1000000&255,u[3]=e/65536&255,u[4]=e/256&255,u[5]=255&e}return u[6]=112|15&l[0],u[7]=l[1],u[8]=128|63&l[2],u.set(l.slice(3,10),9),o=Array.from(u).map(e=>e.toString(16).padStart(2,"0")).join(""),`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}let rd=(...e)=>e.join("/");async function rc(e){}async function rh(e,t){}async function rp(e){return[]}async function rf(e){return{size:0}}let rm=new class{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"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(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,t){if(0===this.maxSize)return;let r=this.cache.get(e);if(!r){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...r,refreshFunc:t}),this._metrics.hits+=1,r.value}set(e,t,r){if(0===this.maxSize)return;if(void 0===this.refreshTimer&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}let a={value:t,createdAt:Date.now(),refreshFunc:r};this.cache.delete(e),this.cache.set(e,a)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let t={};for(let[e,r]of this.cache.entries())t[e]=r.value;e.split("/").slice(0,-1).join("/");try{JSON.stringify({entries:t},null,2)}catch(e){throw e}}load(e){return 0}startRefreshLoop(){this.stop(),null!==this.ttlSeconds&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},1e3*this.refreshIntervalSeconds),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[r,a]of this.cache.entries()){var t;null!==(t=this.ttlSeconds)&&Date.now()-a.createdAt>1e3*t&&e.push([r,a])}return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(0!==e.length){for(let[t,r]of e)if(void 0!==r.refreshFunc)try{let e=await r.refreshFunc();this.set(t,e,r.refreshFunc),this._metrics.refreshes+=1}catch(e){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${t}:`,e)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},rg="0.7.3",ry=()=>r||(r="u">typeof Bun?"bun":"u">typeof window&&void 0!==window.document?"browser":void 0===th.default||void 0===th.default.versions||void 0===th.default.versions.node||"u">typeof Deno?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"u">typeof window&&"nodejs"===window.name||"u">typeof navigator&&navigator.userAgent.includes("jsdom")?"jsdom":"u">typeof Deno?"deno":"other":"node");function r_(){return void 0===a&&(a={library:"langsmith",runtime:ry(),sdk:"langsmith-js",sdk_version:rg,...function(){if(void 0!==i)return i;let e={};for(let t of["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"]){let r=rv(t);void 0!==r&&(e[t]=r)}return i=e,e}()}),a}function rb(){let e=function(){let e={};try{if(void 0!==th.default&&th.default.env)for(let[t,r]of Object.entries(th.default.env))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&null!=r&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&"string"==typeof r?e[t]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):e[t]=r)}catch(e){}return e}(),t={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_CONFIG_FILE","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[a,i]of Object.entries(e))"string"!=typeof i||r.includes(a)||a.toLowerCase().includes("key")||a.toLowerCase().includes("secret")||a.toLowerCase().includes("token")||("LANGCHAIN_REVISION_ID"===a?t.revision_id=i:t[a]=i);return t}function rv(e){try{return void 0!==th.default?th.default.env?.[e]:void 0}catch(e){return}}function rw(e){return rv(`LANGSMITH_${e}`)||rv(`LANGCHAIN_${e}`)}function rx(){return"true"===rv("OTEL_ENABLED")||"true"===rw("OTEL_ENABLED")}let rk=new Set(["langsmith","otel"]);function rS(e){if(void 0!==e)return e;let t=rw("TRACING_MODE");if(void 0!==t&&""!==t){let e=t.toLowerCase();if(!rk.has(e))throw Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(t)}. Must be one of: ${[...rk].sort().join(", ")}`);return rx()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),e}return rx()?"otel":"langsmith"}class rE{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){let r;if(this.hasWarned||"otel"!==rS()||(console.warn('OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0),1===t.length&&"function"==typeof t[0]?r=t[0]:2===t.length&&"function"==typeof t[1]?r=t[1]:3===t.length&&"function"==typeof t[2]&&(r=t[2]),"function"==typeof r)return r()}}let rT=Symbol.for("ls:otel_trace"),rA=Symbol.for("ls:otel_context"),rI=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),rO=new class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new rE})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},rC=new class{active(){return{}}with(e,t){return t()}},rj=new class{getTraceInstance(){return globalThis[rT]??rO}getContextInstance(){return globalThis[rA]??rC}initializeGlobalInstances(e){void 0===globalThis[rT]&&(globalThis[rT]=e.trace),void 0===globalThis[rA]&&(globalThis[rA]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[rI]=e}getDefaultOTLPTracerComponents(){return globalThis[rI]??void 0}};function rP(){return rj.getTraceInstance()}let r$={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};class rN{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(let r of e)try{if(!r.run)continue;if("post"===r.operation){let e=this.createSpanForRun(r,r.run,t.get(r.id));e&&!r.run.end_time&&this.spans.set(r.id,e)}else this.updateSpanForRun(r,r.run)}catch(e){console.error(`Error processing operation ${r.id}:`,e)}}createSpanForRun(e,t,r){let a=r&&rP().getSpan(r);if(a)try{return this.finishSpanSetup(a,t,e)}catch(t){console.error(`Failed to create span for run ${e.id}:`,t);return}}finishSpanSetup(e,t,r){return this.setSpanAttributes(e,t,r),t.error?(e.setStatus({code:2}),e.recordException(Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{let r=this.spans.get(e.id);if(!r)return void console.debug(`No span found for run ${e.id} during update`);this.setSpanAttributes(r,t,e),t.error?(r.setStatus({code:2}),r.recordException(Error(t.error))):r.setStatus({code:1});let a=t.end_time;a&&(r.end(new Date(a)),this.spans.delete(e.id))}catch(t){console.error(`Failed to update span for run ${e.id}:`,t)}}extractModelName(e){if(e.extra?.metadata){let t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){let e=t.invocation_params;if(e.model)return e.model;if(e.model_name)return e.model_name}}}setSpanAttributes(e,t,r){var a;if("run_type"in t&&t.run_type){e.setAttribute("langsmith.span.kind",t.run_type);let r=r$[a=t.run_type||"chain"]||a;e.setAttribute("gen_ai.operation.name",r)}"name"in t&&t.name&&e.setAttribute("langsmith.trace.name",t.name),"session_id"in t&&t.session_id&&e.setAttribute("langsmith.trace.session_id",t.session_id),"session_name"in t&&t.session_name&&e.setAttribute("langsmith.trace.session_name",t.session_name),this.setGenAiSystem(e,t);let i=this.extractModelName(t);for(let[r,a]of(i&&e.setAttribute(tC,i),t.extra?.metadata?.usage_metadata&&"object"==typeof t.extra.metadata.usage_metadata&&e.setAttribute(tR,JSON.stringify(t.extra.metadata.usage_metadata)),"prompt_tokens"in t&&"number"==typeof t.prompt_tokens&&e.setAttribute(tj,t.prompt_tokens),"completion_tokens"in t&&"number"==typeof t.completion_tokens&&e.setAttribute(tP,t.completion_tokens),"total_tokens"in t&&"number"==typeof t.total_tokens&&e.setAttribute(t$,t.total_tokens),this.setInvocationParameters(e,t),Object.entries(t.extra?.metadata||{})))null!=a&&e.setAttribute(`langsmith.metadata.${r}`,"string"==typeof a||"number"==typeof a||"boolean"==typeof a?String(a):JSON.stringify(a));let n=t.tags;if(n&&Array.isArray(n)?e.setAttribute(tN,n.join(", ")):n&&e.setAttribute(tN,String(n)),"serialized"in t&&"object"==typeof t.serialized){let r=t.serialized;r.name&&e.setAttribute("gen_ai.serialized.name",String(r.name)),r.signature&&e.setAttribute("gen_ai.serialized.signature",String(r.signature)),r.doc&&e.setAttribute("gen_ai.serialized.doc",String(r.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,t){let r="langchain",a=this.extractModelName(t);if(a){let e=a.toLowerCase();e.includes("anthropic")||e.startsWith("claude")?r="anthropic":e.includes("bedrock")?r="aws.bedrock":e.includes("azure")&&e.includes("openai")?r="az.ai.openai":e.includes("azure")&&e.includes("inference")?r="az.ai.inference":e.includes("cohere")?r="cohere":e.includes("deepseek")?r="deepseek":e.includes("gemini")?r="gemini":e.includes("groq")?r="groq":e.includes("watson")||e.includes("ibm")?r="ibm.watsonx.ai":e.includes("mistral")?r="mistral_ai":e.includes("gpt")||e.includes("openai")?r="openai":e.includes("perplexity")||e.includes("sonar")?r="perplexity":e.includes("vertex")?r="vertex_ai":(e.includes("xai")||e.includes("grok"))&&(r="xai")}e.setAttribute("gen_ai.system",r)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;let r=t.extra.metadata.invocation_params;void 0!==r.max_tokens&&e.setAttribute("gen_ai.request.max_tokens",r.max_tokens),void 0!==r.temperature&&e.setAttribute("gen_ai.request.temperature",r.temperature),void 0!==r.top_p&&e.setAttribute("gen_ai.request.top_p",r.top_p),void 0!==r.frequency_penalty&&e.setAttribute("gen_ai.request.frequency_penalty",r.frequency_penalty),void 0!==r.presence_penalty&&e.setAttribute("gen_ai.request.presence_penalty",r.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{let r=t.run.inputs;"object"==typeof r&&null!==r&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(tC,r.model),void 0!==r.stream&&e.setAttribute("langsmith.request.streaming",r.stream),r.extra_headers&&e.setAttribute("langsmith.request.headers",JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute("gen_ai.request.extra_query",JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute("gen_ai.request.extra_body",JSON.stringify(r.extra_body))),e.setAttribute("gen_ai.prompt",JSON.stringify(r))}catch(e){console.debug(`Failed to process inputs for run ${t.id}`,e)}if(t.run.outputs)try{let r=t.run.outputs,a=this.getUnifiedRunTokens(r);if(a&&(e.setAttribute(tj,a[0]),e.setAttribute(tP,a[1]),e.setAttribute(t$,a[0]+a[1])),r&&"object"==typeof r){if(r.model&&e.setAttribute("gen_ai.response.model",String(r.model)),r.id&&e.setAttribute("gen_ai.response.id",r.id),r.choices&&Array.isArray(r.choices)){let t=r.choices.map(e=>e.finish_reason).filter(e=>e).map(String);t.length>0&&e.setAttribute("gen_ai.response.finish_reasons",t.join(", "))}if(r.service_tier&&e.setAttribute("gen_ai.response.service_tier",r.service_tier),r.system_fingerprint&&e.setAttribute("gen_ai.response.system_fingerprint",r.system_fingerprint),r.usage_metadata&&"object"==typeof r.usage_metadata){let t=r.usage_metadata;e.setAttribute(tR,JSON.stringify(t)),t.input_token_details&&e.setAttribute("gen_ai.usage.input_token_details",JSON.stringify(t.input_token_details)),t.output_token_details&&e.setAttribute("gen_ai.usage.output_token_details",JSON.stringify(t.output_token_details))}}e.setAttribute("gen_ai.completion",JSON.stringify(r))}catch(e){console.debug(`Failed to process outputs for run ${t.id}`,e)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;for(let r of Object.keys(e)){let a=e[r];if(a&&"object"==typeof a&&((t=this.extractUnifiedRunTokens(a.usage_metadata))||1===a.lc&&a.kwargs&&"object"==typeof a.kwargs&&(t=this.extractUnifiedRunTokens(a.kwargs.usage_metadata))))return t}let r=e.generations||[];if(!Array.isArray(r))return null;for(let e of Array.isArray(r[0])?r.flat():r)if("object"==typeof e&&e.message&&"object"==typeof e.message&&e.message.kwargs&&"object"==typeof e.message.kwargs&&(t=this.extractUnifiedRunTokens(e.message.kwargs.usage_metadata)))return t;return null}extractUnifiedRunTokens(e){return e&&"object"==typeof e&&"number"==typeof e.input_tokens&&"number"==typeof e.output_tokens?[e.input_tokens,e.output_tokens]:null}}let rR=Object.prototype.toString,rM=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 rL(e,t,{min:r=0,allowInfinity:a=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${a?" or Infinity":""}.`);if(!a&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}class rz extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}function rU(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function rB({error:e,attemptNumber:t,retriesConsumed:r,startTime:a,options:i}){let n,s=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof rz)throw s.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,l=i.maxRetryTime??1/0,u=Object.freeze({error:s,attemptNumber:t,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(u),0>=rU(a,l))throw s;let d=await i.shouldConsumeRetry(u),c=rU(a,l);if(c<=0||o<=0)throw s;if(s instanceof TypeError&&!function(e){if(!(e&&"[object Error]"===rR.call(e)&&"TypeError"===e.name&&"string"==typeof e.message))return!1;let{message:t,stack:r}=e;return"Load failed"===t?void 0===r||"__sentry_captured__"in e:!!t.startsWith("error sending request for url")||rM.has(t)}(s)){if(d)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(u))throw s;if(!d)return i.signal?.throwIfAborted(),!1;let h=Math.min((n=Math.max(1,r+1),Math.min(Math.round((i.randomize?Math.random()+1:1)*i.minTimeout*i.factor**(n-1)),i.maxTimeout)),c);return h>0&&await new Promise((e,t)=>{let r=()=>{clearTimeout(a),i.signal?.removeEventListener("abort",r),t(i.signal.reason)},a=setTimeout(()=>{i.signal?.removeEventListener("abort",r),e()},h);i.unref&&a.unref?.(),i.signal?.addEventListener("abort",r,{once:!0})}),i.signal?.throwIfAborted(),!0}async function rD(e,t={}){var r=(t={...t}).retries;if("number"==typeof r){if(r<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(void 0!==r)throw TypeError("Expected `retries` to be a number or Infinity.");if(Object.hasOwn(t,"forever"))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,rL("factor",t.factor,{min:0,allowInfinity:!1}),rL("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),rL("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),rL("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let a=0,i=0,n=performance.now();for(;!Number.isFinite(t.retries)||i<=t.retries;){a++;try{t.signal?.throwIfAborted();let r=await e(a);return t.signal?.throwIfAborted(),r}catch(e){await rB({error:e,attemptNumber:a,retriesConsumed:i,startTime:n,options:t})&&i++}}throw Error("Retry attempts exhausted without throwing an error.")}var rF=e.i(753274);let rZ="default"in rF.default?rF.default.default:rF.default,rH=[408,425,429,500,502,503,504];class rq{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new rZ({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){return this.callWithOptions({},e,...t)}callWithOptions(e,t,...r){let a=e.sizeBytes??0;if(void 0!==this.maxQueueSizeBytes&&a>0&&this.queueSizeBytes+a>this.maxQueueSizeBytes)return Promise.reject(Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${a} bytes.`));a>0&&(this.queueSizeBytes+=a);let i=this.onFailedResponseHook,n=this.queue.add(()=>rD(()=>t(...r).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{async onFailedAttempt({error:e}){if("object"!=typeof e||null==e)throw e;let t="message"in e&&"string"==typeof e.message?e.message:void 0;if(t?.startsWith("Cancel")||t?.startsWith("TimeoutError")||t?.startsWith("AbortError")||"name"in e&&"TimeoutError"===e.name||"code"in e&&"ECONNABORTED"===e.code)throw e;let r="response"in e?e.response:void 0;if(i&&await i(r))return;let a=r?.status??("status"in e?e.status:void 0);if(null!=a&&("number"==typeof a||"string"==typeof a)&&!rH.includes(+a))throw e},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return(a>0&&(n=n.finally(()=>{this.queueSizeBytes-=a})),e.signal)?Promise.race([n,new Promise((t,r)=>{e.signal?.addEventListener("abort",()=>{r(Error("AbortError"))})})]):n}}function rJ(e){return"function"==typeof e?._getType}function rG(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}let rW={};function rV(e){rW[e]||(console.warn(e),rW[e]=!0)}function rK(e){return`Invalid prompt identifier format: "${e}". Expected one of:
|
|
10
|
+
`,t}function eG(e){if("string"==typeof e)return new eL(e);if(ec(e))return e;if(Array.isArray(e)){let[t,r]=e;return eJ({type:t,content:r})}if(!ed(e))return eJ(e);{let{role:t,...r}=e;return eJ({...r,type:t})}}function eW(e){if("string"==typeof e)return e;switch(e.type){case"text":return e.text??"";case"text-plain":return e.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return e.type?`[${e.type}]`:""}}function eV(e,t="Human",r="AI"){let a=[];for(let i of e){let e;if("human"===i.type)e=t;else if("ai"===i.type)e=r;else if("system"===i.type)e="System";else if("tool"===i.type)e="Tool";else if("generic"===i.type)e=i.role;else throw Error(`Got unsupported message type: ${i.type}`);let n=i.name?`${i.name}, `:"",s="string"==typeof i.content?i.content:Array.isArray(i.content)?i.content.map(eW).filter(Boolean).join(""):"",o=`${e}: ${n}${s}`;"ai"===i.type&&(i.tool_calls&&i.tool_calls.length>0?o+=JSON.stringify(i.tool_calls):i.additional_kwargs&&"function_call"in i.additional_kwargs&&(o+=JSON.stringify(i.additional_kwargs.function_call))),a.push(o)}return a.join("\n")}function eK(e){let t=void 0!==e.data?e:{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}};switch(t.type){case"human":return new eL(t.data);case"ai":return new e1(t.data);case"system":return new eB(t.data);case"function":if(void 0===t.data.name)throw Error("Name must be defined for function messages");return new eM(t.data);case"tool":if(void 0===t.data.tool_call_id)throw Error("Tool call ID must be defined for tool messages");return new em(t.data);case"generic":if(void 0===t.data.role)throw Error("Role must be defined for chat messages");return new eN(t.data);default:throw Error(`Got unexpected type: ${t.type}`)}}function eQ(e){return e.map(eK)}function eY(e){return e.map(e=>e.toDict())}function eX(e){let t=e._getType();if("human"===t)return new eU({...e});if("ai"===t){let t={...e};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)}))}),new e9({...t})}if("system"===t)return new eF({...e});if("function"===t)return new ez({...e});if(eN.isInstance(e))return new eR({...e});else throw Error("Unknown message type.")}function e0(e){let t=e.reduce((e,t)=>{let r=e.findIndex(([e])=>"id"in t&&t.id&&"index"in t&&void 0!==t.index?t.id===e.id&&t.index===e.index:"id"in t&&t.id?t.id===e.id:"index"in t&&void 0!==t.index&&t.index===e.index);return -1!==r?e[r].push(t):e.push([t]),e},[]),r=[],a=[];for(let e of t){let t=null,i=e.some(eZ),n=e[0]?.name??"",s=e.map(e=>e.args||"").join(""),o=i?s:s.trim(),l=o.length?o:"{}",u=e.find(e=>e.id)?.id??e[0]?.id;if(i&&u){r.push({name:n,args:{input:o},id:u,type:"tool_call"});continue}try{if(t=function(e){try{if(void 0===e)return null;return function(e){try{return JSON.parse(e)}catch{}let t=e.trim();if(0===t.length)throw Error("Unexpected end of JSON input");let r=0;function a(){for(;r<t.length&&/\s/.test(t[r]);)r+=1}function i(){if('"'!==t[r])throw Error(`Expected '"' at position ${r}, got '${t[r]}'`);r+=1;let e="",a=!1;for(;r<t.length;){let i=t[r];if(a){if("n"===i)e+="\n";else if("t"===i)e+=" ";else if("r"===i)e+="\r";else if("\\"===i)e+="\\";else if('"'===i)e+='"';else if("b"===i)e+="\b";else if("f"===i)e+="\f";else if("/"===i)e+="/";else if("u"===i){let a=t.substring(r+1,r+5);if(/^[0-9A-Fa-f]{0,4}$/.test(a))4===a.length?e+=String.fromCharCode(Number.parseInt(a,16)):e+=`u${a}`,r+=a.length;else throw Error(`Invalid unicode escape sequence '\\u${a}' at position ${r}`)}else throw Error(`Invalid escape sequence '\\${i}' at position ${r}`);a=!1}else if("\\"===i)a=!0;else{if('"'===i)return r+=1,e;e+=i}r+=1}return a&&(e+="\\"),e}let n=function e(){if(a(),r>=t.length)throw Error(`Unexpected end of input at position ${r}`);let n=t[r];if("{"===n)return function(){if("{"!==t[r])throw Error(`Expected '{' at position ${r}, got '${t[r]}'`);let n={};if(r+=1,a(),r>=t.length)return n;if("}"===t[r])return r+=1,n;for(;r<t.length&&(a(),!(r>=t.length));){let s=i();if(a(),r>=t.length)break;if(":"!==t[r])throw Error(`Expected ':' at position ${r}, got '${t[r]}'`);if(r+=1,a(),r>=t.length||(n[s]=e(),a(),r>=t.length))break;if("}"===t[r]){r+=1;break}if(","===t[r]){r+=1;continue}throw Error(`Expected ',' or '}' at position ${r}, got '${t[r]}'`)}return n}();if("["===n)return function(){if("["!==t[r])throw Error(`Expected '[' at position ${r}, got '${t[r]}'`);let i=[];if(r+=1,a(),r>=t.length)return i;if("]"===t[r])return r+=1,i;for(;r<t.length&&(a(),!(r>=t.length))&&(i.push(e()),a(),!(r>=t.length));){;if("]"===t[r]){r+=1;break}if(","===t[r]){r+=1;continue}throw Error(`Expected ',' or ']' at position ${r}, got '${t[r]}'`)}return i}();if('"'===n)return i();if("null".startsWith(t.substring(r,r+4)))return r+=Math.min(4,t.length-r),null;if("true".startsWith(t.substring(r,r+4)))return r+=Math.min(4,t.length-r),!0;if("false".startsWith(t.substring(r,r+5)))return r+=Math.min(5,t.length-r),!1;if("-"===n||n>="0"&&n<="9"){let e=r,a="";if("-"===t[r]&&(a+="-",r+=1),r<t.length&&"0"===t[r]&&(a+="0",t[r+=1]>="0"&&t[r]<="9"))throw Error(`Invalid number at position ${e}`);if(r<t.length&&t[r]>="1"&&t[r]<="9")for(;r<t.length&&t[r]>="0"&&t[r]<="9";)a+=t[r],r+=1;if(r<t.length&&"."===t[r])for(a+=".",r+=1;r<t.length&&t[r]>="0"&&t[r]<="9";)a+=t[r],r+=1;if(r<t.length&&("e"===t[r]||"E"===t[r]))for(a+=t[r],(r+=1)<t.length&&("+"===t[r]||"-"===t[r])&&(a+=t[r],r+=1);r<t.length&&t[r]>="0"&&t[r]<="9";)a+=t[r],r+=1;if("-"===a)return -0;let i=Number.parseFloat(a);if(Number.isNaN(i))throw r=e,Error(`Invalid number '${a}' at position ${e}`);return i}throw Error(`Unexpected character '${n}' at position ${r}`)}();if(a(),r<t.length)throw Error(`Unexpected character '${t[r]}' at position ${r}`);return n}(e)}catch{return null}}(l),!u||null===t||"object"!=typeof t||Array.isArray(t))throw Error("Malformed tool call chunk args.");r.push({name:n,args:t,id:u,type:"tool_call"})}catch{a.push({name:n,args:l,id:u,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:e,tool_calls:r,invalid_tool_calls:a}}var e1=class extends et{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(e){let t;if("string"==typeof e||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;const r=t.additional_kwargs?.tool_calls,a=t.tool_calls;null!=r&&r.length>0&&(void 0===a||0===a.length)&&console.warn("New LangChain packages are available that more efficiently handle tool calling.\n\nPlease upgrade your packages to versions that set message tool calls. e.g., `pnpm install @langchain/anthropic`, pnpm install @langchain/openai`, etc.");try{if(null!=r&&void 0===a){const[e,a]=ey(r);t.tool_calls=e??[],t.invalid_tool_calls=a??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(void 0!==t.response_metadata&&"output_version"in t.response_metadata&&"v1"===t.response_metadata.output_version&&(t.contentBlocks=t.content,t.content=void 0),void 0!==t.contentBlocks){if(t.tool_calls){const e=t.tool_calls.filter(e=>!t.contentBlocks?.some(t=>"tool_call"===t.type&&t.id===e.id&&t.name===e.name));t.contentBlocks.push(...e.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args})))}const e=t.contentBlocks.filter(e=>"tool_call"===e.type).filter(e=>!t.tool_calls?.some(t=>t.id===e.id&&t.name===e.name));e.length>0&&(t.tool_calls=[...t.tool_calls??[],...e.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args}))])}}super(t),"string"!=typeof t&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&"v1"===this.response_metadata.output_version)return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&"string"==typeof this.response_metadata.model_provider){let e=eO(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let t=this.tool_calls.filter(t=>!e.some(e=>e.id===t.id&&e.name===t.name));e.push(...t.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&"ai"===e.type}};function e2(e){return"ai"===e._getType()}function e4(e){return"ai"===e._getType()}var e9=class extends eu{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if("string"==typeof e||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(void 0===e.tool_call_chunks||0===e.tool_call_chunks.length)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0};else{const r=e0(e.tool_call_chunks??[]);t={...e,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&"v1"===this.response_metadata.output_version)return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&"string"==typeof this.response_metadata.model_provider){let e=eO(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&"string"!=typeof this.content){let t=this.content.filter(e=>"tool_call"===e.type).map(e=>e.id);for(let r of this.tool_calls)r.id&&!t.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let t={content:X(this.content,e.content),additional_kwargs:ea(this.additional_kwargs,e.additional_kwargs),response_metadata:ea(this.response_metadata,e.response_metadata)??{},tool_call_chunks:[],tool_calls:[],id:this.id??e.id};if(void 0!==this.tool_call_chunks||void 0!==e.tool_call_chunks){let r=eo(this.tool_call_chunks,e.tool_call_chunks);void 0!==r&&r.length>0&&(t.tool_call_chunks=r)}if(void 0!==this.tool_calls||void 0!==e.tool_calls){let r=eo(this.tool_calls,e.tool_calls);void 0!==r&&r.length>0&&(t.tool_calls=r)}return(void 0!==this.usage_metadata||void 0!==e.usage_metadata)&&(t.usage_metadata=ef(this.usage_metadata,e.usage_metadata)),new this.constructor(t)}static isInstance(e){return super.isInstance(e)&&"ai"===e.type}},e6=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function e5(e){return"string"==typeof e&&e6.test(e)}function e3(e){let t;if(!e5(e))throw TypeError("Invalid UUID");return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/0x10000000000&255,t/0x100000000&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)}let e8=[];for(let e=0;e<256;++e)e8.push((e+256).toString(16).slice(1));function e7(e,t=0){return(e8[e[t+0]]+e8[e[t+1]]+e8[e[t+2]]+e8[e[t+3]]+"-"+e8[e[t+4]]+e8[e[t+5]]+"-"+e8[e[t+6]]+e8[e[t+7]]+"-"+e8[e[t+8]]+e8[e[t+9]]+"-"+e8[e[t+10]]+e8[e[t+11]]+e8[e[t+12]]+e8[e[t+13]]+e8[e[t+14]]+e8[e[t+15]]).toLowerCase()}let te=new Uint8Array(16);function tt(){return crypto.getRandomValues(te)}function tr(e,t){return e<<t|e>>>32-t}function ta(e){let t=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6],r=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],a=new Uint8Array(e.length+1);a.set(e),a[e.length]=128;let i=Math.ceil(((e=a).length/4+2)/16),n=Array(i);for(let t=0;t<i;++t){let r=new Uint32Array(16);for(let a=0;a<16;++a)r[a]=e[64*t+4*a]<<24|e[64*t+4*a+1]<<16|e[64*t+4*a+2]<<8|e[64*t+4*a+3];n[t]=r}n[i-1][14]=(e.length-1)*8/0x100000000,n[i-1][14]=Math.floor(n[i-1][14]),n[i-1][15]=(e.length-1)*8|0;for(let e=0;e<i;++e){let a=new Uint32Array(80);for(let t=0;t<16;++t)a[t]=n[e][t];for(let e=16;e<80;++e)a[e]=tr(a[e-3]^a[e-8]^a[e-14]^a[e-16],1);let i=r[0],s=r[1],o=r[2],l=r[3],u=r[4];for(let e=0;e<80;++e){let r=Math.floor(e/20),n=tr(i,5)+function(e,t,r,a){switch(e){case 0:return t&r^~t&a;case 1:case 3:return t^r^a;case 2:return t&r^t&a^r&a}}(r,s,o,l)+u+t[r]+a[e]>>>0;u=l,l=o,o=tr(s,30)>>>0,s=i,i=n}r[0]=r[0]+i>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+o>>>0,r[3]=r[3]+l>>>0,r[4]=r[4]+u>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}function ti(e,t,r,a){var i=t,n=a;let s="string"==typeof e?function(e){let t=new Uint8Array((e=unescape(encodeURIComponent(e))).length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}(e):e,o="string"==typeof i?e3(i):i;if("string"==typeof i&&(i=e3(i)),i?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+s.length);if(l.set(o),l.set(s,o.length),(l=ta(l))[6]=15&l[6]|80,l[8]=63&l[8]|128,r){if((n??=0)<0||n+16>r.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)r[n+e]=l[e];return r}return e7(l)}ti.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ti.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";let tn={};function ts(e,t,r,a,i=0){if(e.length<16)throw Error("Random bytes length must be >= 16");if(a){if(i<0||i+16>a.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`)}else a=new Uint8Array(16),i=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],a[i++]=t/0x10000000000&255,a[i++]=t/0x100000000&255,a[i++]=t/0x1000000&255,a[i++]=t/65536&255,a[i++]=t/256&255,a[i++]=255&t,a[i++]=112|r>>>28&15,a[i++]=r>>>20&255,a[i++]=128|r>>>14&63,a[i++]=r>>>6&255,a[i++]=r<<2&255|3&e[10],a[i++]=e[11],a[i++]=e[12],a[i++]=e[13],a[i++]=e[14],a[i++]=e[15],a}let to=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){let a=(e=e||{}).random??e.rng?.()??tt();if(a.length<16)throw Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){if((r=r||0)<0||r+16>t.length)throw RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=a[e];return t}return e7(a)}(e,t,r):crypto.randomUUID()},tl=function(e,t,r){let a;if(e)a=ts(e.random??e.rng?.()??tt(),e.msecs,e.seq,t,r);else{var i,n,s;let e=Date.now(),o=tt();i=tn,n=e,s=o,i.msecs??=-1/0,i.seq??=0,n>i.msecs?(i.seq=s[6]<<23|s[7]<<16|s[8]<<8|s[9],i.msecs=n):(i.seq=i.seq+1|0,0===i.seq&&i.msecs++),a=ts(o,tn.msecs,tn.seq,t,r)}return t??e7(a)};e.s(["v4",0,to,"v7",0,tl,"validate",0,e5],230125);let tu=Symbol.for("ls:tracing_async_local_storage"),td=Symbol.for("lc:context_variables"),tc=()=>globalThis[tu];var th=e.i(247167);function tp(e){try{if(void 0!==th.default)return th.default.env?.[e];if("u">typeof Deno)return Deno?.env.get(e);return}catch{return}}var tf=class{},tm=class extends tf{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,P(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers="false"===tp("LANGCHAIN_CALLBACKS_BACKGROUND");constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return N.prototype.toJSON.call(this)}toJSONNotImplemented(){return N.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends tm{name=tl();constructor(){super(),Object.assign(this,e)}}return new t}};let tg=e=>void 0!==e&&"function"==typeof e.copy&&"string"==typeof e.name&&"boolean"==typeof e.awaitHandlers,ty=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i,t_=[];for(let e=0;e<256;++e)t_.push((e+256).toString(16).slice(1));function tb(e,t=0){return(t_[e[t+0]]+t_[e[t+1]]+t_[e[t+2]]+t_[e[t+3]]+"-"+t_[e[t+4]]+t_[e[t+5]]+"-"+t_[e[t+6]]+t_[e[t+7]]+"-"+t_[e[t+8]]+t_[e[t+9]]+"-"+t_[e[t+10]]+t_[e[t+11]]+t_[e[t+12]]+t_[e[t+13]]+t_[e[t+14]]+t_[e[t+15]]).toLowerCase()}let tv=new Uint8Array(16);function tw(){return crypto.getRandomValues(tv)}let tx=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){let a=(e=e||{}).random??e.rng?.()??tw();if(a.length<16)throw Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){if((r=r||0)<0||r+16>t.length)throw RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=a[e];return t}return tb(a)}(e,t,r):crypto.randomUUID()};function tk(e,t){return e<<t|e>>>32-t}let tS=function(e){let t=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6],r=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],a=new Uint8Array(e.length+1);a.set(e),a[e.length]=128;let i=Math.ceil(((e=a).length/4+2)/16),n=Array(i);for(let t=0;t<i;++t){let r=new Uint32Array(16);for(let a=0;a<16;++a)r[a]=e[64*t+4*a]<<24|e[64*t+4*a+1]<<16|e[64*t+4*a+2]<<8|e[64*t+4*a+3];n[t]=r}n[i-1][14]=(e.length-1)*8/0x100000000,n[i-1][14]=Math.floor(n[i-1][14]),n[i-1][15]=(e.length-1)*8|0;for(let e=0;e<i;++e){let a=new Uint32Array(80);for(let t=0;t<16;++t)a[t]=n[e][t];for(let e=16;e<80;++e)a[e]=tk(a[e-3]^a[e-8]^a[e-14]^a[e-16],1);let i=r[0],s=r[1],o=r[2],l=r[3],u=r[4];for(let e=0;e<80;++e){let r=Math.floor(e/20),n=tk(i,5)+function(e,t,r,a){switch(e){case 0:return t&r^~t&a;case 1:case 3:return t^r^a;case 2:return t&r^t&a^r&a}}(r,s,o,l)+u+t[r]+a[e]>>>0;u=l,l=o,o=tk(s,30)>>>0,s=i,i=n}r[0]=r[0]+i>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+o>>>0,r[3]=r[3]+l>>>0,r[4]=r[4]+u>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])},tT=function(e){let t;if(!("string"==typeof e&&ty.test(e)))throw TypeError("Invalid UUID");return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/0x10000000000&255,t/0x100000000&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)};function tE(e,t,r,a){var i=t,n=a;let s="string"==typeof e?function(e){let t=new Uint8Array((e=unescape(encodeURIComponent(e))).length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}(e):e,o="string"==typeof i?tT(i):i;if("string"==typeof i&&(i=tT(i)),i?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+s.length);if(l.set(o),l.set(s,o.length),(l=tS(l))[6]=15&l[6]|80,l[8]=63&l[8]|128,r){if((n??=0)<0||n+16>r.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)r[n+e]=l[e];return r}return tb(l)}tE.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",tE.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";let tA={};function tI(e,t,r,a,i=0){if(e.length<16)throw Error("Random bytes length must be >= 16");if(a){if(i<0||i+16>a.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`)}else a=new Uint8Array(16),i=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],a[i++]=t/0x10000000000&255,a[i++]=t/0x100000000&255,a[i++]=t/0x1000000&255,a[i++]=t/65536&255,a[i++]=t/256&255,a[i++]=255&t,a[i++]=112|r>>>28&15,a[i++]=r>>>20&255,a[i++]=128|r>>>14&63,a[i++]=r>>>6&255,a[i++]=r<<2&255|3&e[10],a[i++]=e[11],a[i++]=e[12],a[i++]=e[13],a[i++]=e[14],a[i++]=e[15],a}let tO=function(e,t,r){let a;if(e)a=tI(e.random??e.rng?.()??tw(),e.msecs,e.seq,t,r);else{var i,n,s;let e=Date.now(),o=tw();i=tA,n=e,s=o,i.msecs??=-1/0,i.seq??=0,n>i.msecs?(i.seq=s[6]<<23|s[7]<<16|s[8]<<8|s[9],i.msecs=n):(i.seq=i.seq+1|0,0===i.seq&&i.msecs++),a=tI(o,tA.msecs,tA.seq,t,r)}return t??tb(a)},tC="gen_ai.request.model",tj="gen_ai.usage.input_tokens",t$="gen_ai.usage.output_tokens",tP="gen_ai.usage.total_tokens",tN="langsmith.span.tags",tR="langsmith.usage_metadata",tM=Symbol.for("ls:fetch_implementation"),tz=()=>rw("PROJECT")??rv("LANGCHAIN_SESSION")??"default",tL=e=>BigInt(e),tU=tL("0x9E3779B1"),tD=tL("0x85EBCA77"),tB=tL("0xC2B2AE3D"),tF=tL("0x9E3779B185EBCA87"),tZ=tL("0xC2B2AE3D27D4EB4F"),tH=tL("0x165667B19E3779F9"),tq=tL("0x85EBCA77C2B2AE63"),tJ=tL("0x27D4EB2F165667C5"),tG=tL("0x165667919E3779F9"),tW=tL("0x9FB21C651E98DF25"),tV=function(e){let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substring(r,r+2),16);return t}("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),tK=(tL(1)<<tL(128))-tL(1),tQ=(tL(1)<<tL(64))-tL(1),tY=(tL(1)<<tL(32))-tL(1);function tX(e,t=0){return new Uint8Array(e.buffer,e.byteOffset+t,e.length-t)}function t0(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getBigUint64(0,!0)}function t1(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getUint32(0,!0)}function t2(e,t=0){return e[t]}let t4=(e,t)=>(e&tY)*(t&tY)&tQ,t9=e=>{if(!e)throw Error("Assert failed")};function t6(e,t,r){for(let a=0;a<8;a++){let i=t0(t,8*a),n=i^t0(r,8*a);e[1^a]+=i,e[a]+=t4(n,n>>tL(32))}return e}function t5(e,t,r,a){for(let i=0;i<a;i++)t6(e,tX(t,64*i),tX(r,8*i));return e}function t3(e,t){for(let a=0;a<8;a++){var r;let i=t0(t,8*a),n=e[a];n=((r=n)^r>>tL(47)^i)*tU,e[a]=n&tQ}return e}function t8(e,t){return re(e[0]^t0(t,0),e[1]^t0(t,8))}function t7(e,t,r){let a=r;return a+=t8(e.slice(0),tX(t,0)),a+=t8(e.slice(2),tX(t,16)),a+=t8(e.slice(4),tX(t,32)),ra((a+=t8(e.slice(6),tX(t,48)))&tQ)}function re(e,t){let r=e*t&tK;return r&tQ^r>>tL(64)}function rt(e,t,r){return re((t0(e,0)^t0(t,0)+r)&tQ,(t0(e,8)^t0(t,8)-r)&tQ)}function rr(e,t,r,a,i){let n=e&tQ,s=e>>tL(64)&tQ;return n+=rt(t,a,i),n^=t0(r,0)+t0(r,8),n&=tQ,s+=rt(r,tX(a,16),i),s^=t0(t,0)+t0(t,8),(s&=tQ)<<tL(64)|n}function ra(e){return e^=e>>tL(37),e*=tG,e&=tQ,e^=e>>tL(32)}function ri(e){return e^=e>>tL(33),e*=tZ,e&=tQ,e^=e>>tL(29),e*=tH,e&=tQ,e^=e>>tL(32)}function rn(e){return~e+tL(1)&tQ}let rs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ro(e,t){if(!rs.test(e))throw Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`);return e}let rl=new TextEncoder;function ru(e,t){var r,a;let i,n,s,o,l=(r=`${e}:${t}`,a=function(e,t=tL(0)){let r,a,i=e.byteLength;return i<=16?function(e,t){var r,a,i,n,s;let o=e.byteLength;if(t9(o<=16),o>8){let r,a,i,n,s,o,l,u;return t9((r=e.byteLength)>=9&&r<=16),a=(t0(tV,32)^t0(tV,40))+t&tQ,i=(t0(tV,48)^t0(tV,56))-t&tQ,o=((s=(t0(e)^(n=t0(e,r-8))^a)*tF)&tQ)+(tL(r-1)<<tL(54)),s=s&(tK^tQ)|o,n^=i,s+=n+(n&tY)*(tD-tL(1))<<tL(64),s&=tK,s^=((l=s>>tL(64))&tL(255))<<tL(56)|(l&tL(65280))<<tL(40)|(l&tL(0xff0000))<<tL(24)|(l&tL(0xff000000))<<tL(8)|(l&tL(0xff00000000))>>tL(8)|(l&tL(0xff0000000000))>>tL(24)|(l&tL(0xff000000000000))>>tL(40)|(l&tL(0xff00000000000000))>>tL(56),ra((u=(s&tQ)*tZ+((s>>tL(64))*tZ<<tL(64))&tK)&tQ)|ra(u>>tL(64))<<tL(64)}if(o>=4){let i,n,s,o,l;return t9((i=e.byteLength)>=4&&i<=8),n=t1(e,0),s=t1(e,i-4),o=tL(n)|tL(s)<<tL(32),l=(o^(t0(tV,16)^t0(tV,24))+t&tQ)*(tF+(tL(i)<<tL(2)))&tK,l+=(l&tQ)<<tL(65),l&=tK,l^=l>>tL(67),(a=((r=l&tQ)^r>>tL(35))*tW&tQ)^a>>tL(28)|ra(l>>tL(64))<<tL(64)}if(o>0){let r,a,o,l;return t9((r=e.byteLength)>0&&r<=3),o=((a=tL(t2(e,r-1))|tL(r<<8)|tL(t2(e,0)<<16)|tL(t2(e,r>>1)<<24))^(tL(t1(tV,0))^tL(t1(tV,4)))+t)&tQ,l=(tL(t1(tV,8))^tL(t1(tV,12)))-t,(ri((((n=i=((i=((i=a)&tL(65535))<<tL(16)|(i&tL(0xffff0000))>>tL(16))&tL(0xff00ff))<<tL(8)|(i&tL(0xff00ff00))>>tL(8))<<(s=tL(13))|n>>tL(32)-s)&tY^l)&tQ)&tQ)<<tL(64)|ri(o)}return ri(t^t0(tV,64)^t0(tV,72))|ri(t^t0(tV,80)^t0(tV,88))<<tL(64)}(e,t):i<=128?function(e,t,r){let a=tL(e.byteLength)*tF&tQ,i=tL(e.byteLength-1)/tL(32);for(;i>=0;){let n=Number(i);a=rr(a,tX(e,16*n),tX(e,e.byteLength-16*(n+1)),tX(t,32*n),r),i--}let n=a+(a>>tL(64))&tQ;n=ra(n);let s=(a&tQ)*tF+(a>>tL(64))*tq+(tL(e.byteLength)-r&tQ)*tZ;return s&=tQ,n|(s=rn(ra(s)))<<tL(64)}(e,tV,t):i<=240?function(e,t,r){let a=tL(e.byteLength)*tF&tQ;for(let i=32;i<160;i+=32)a=rr(a,tX(e,i-32),tX(e,i-16),tX(t,i-32),r);a=ra(a&tQ)|ra(a>>tL(64))<<tL(64);for(let i=160;i<=e.byteLength;i+=32)a=rr(a,tX(e,i-32),tX(e,i-16),tX(t,3+i-160),r);let i=(a=rr(a,tX(e,e.byteLength-16),tX(e,e.byteLength-32),tX(t,103),rn(r)))+(a>>tL(64))&tQ;i=ra(i);let n=(a&tQ)*tF+(a>>tL(64))*tq+(tL(e.byteLength)-r&tQ)*tZ;return n&=tQ,i|(n=rn(ra(n)))<<tL(64)}(e,tV,t):(r=new BigUint64Array([tB,tF,tZ,tH,tq,tD,tJ,tU]),t9(e.length>128),t9(8*(r=function(e,t,r,a,i){let n=Math.floor((r.byteLength-64)/8),s=64*n,o=Math.floor((t.byteLength-1)/s);for(let a=0;a<o;a++)e=i(e=t5(e,tX(t,a*s),r,n),tX(r,r.byteLength-64));{let i=Math.floor((t.byteLength-1-s*o)/64);e=a(e=t5(e,tX(t,o*s),r,i),tX(t,t.byteLength-64),tX(r,r.byteLength-64-7))}return e}(r,e,tV,t6,t3)).length==64),a=t7(r,tX(tV,11),tL(e.byteLength)*tF&tQ),t7(r,tX(tV,tV.byteLength-64-11),~(tL(e.byteLength)*tZ)&tQ)<<tL(64)|a)}(rl.encode(r)),n=new DataView((i=new Uint8Array(16)).buffer),s=a>>tL(64),n.setBigUint64(0,s,!1),n.setBigUint64(8,a&tQ,!1),i),u=new Uint8Array(16);if(7===(rs.test(e)?parseInt(e[14],16):null)){let t=function(e){let t=e.replace(/-/g,""),r=new Uint8Array(16);for(let e=0;e<16;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}(e);u.set(t.slice(0,6),0)}else{let e=Date.now();u[0]=e/0x10000000000&255,u[1]=e/0x100000000&255,u[2]=e/0x1000000&255,u[3]=e/65536&255,u[4]=e/256&255,u[5]=255&e}return u[6]=112|15&l[0],u[7]=l[1],u[8]=128|63&l[2],u.set(l.slice(3,10),9),o=Array.from(u).map(e=>e.toString(16).padStart(2,"0")).join(""),`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}let rd=(...e)=>e.join("/");async function rc(e){}async function rh(e,t){}async function rp(e){return[]}async function rf(e){return{size:0}}let rm=new class{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"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(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,t){if(0===this.maxSize)return;let r=this.cache.get(e);if(!r){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...r,refreshFunc:t}),this._metrics.hits+=1,r.value}set(e,t,r){if(0===this.maxSize)return;if(void 0===this.refreshTimer&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}let a={value:t,createdAt:Date.now(),refreshFunc:r};this.cache.delete(e),this.cache.set(e,a)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let t={};for(let[e,r]of this.cache.entries())t[e]=r.value;e.split("/").slice(0,-1).join("/");try{JSON.stringify({entries:t},null,2)}catch(e){throw e}}load(e){return 0}startRefreshLoop(){this.stop(),null!==this.ttlSeconds&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},1e3*this.refreshIntervalSeconds),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[r,a]of this.cache.entries()){var t;null!==(t=this.ttlSeconds)&&Date.now()-a.createdAt>1e3*t&&e.push([r,a])}return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(0!==e.length){for(let[t,r]of e)if(void 0!==r.refreshFunc)try{let e=await r.refreshFunc();this.set(t,e,r.refreshFunc),this._metrics.refreshes+=1}catch(e){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${t}:`,e)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},rg="0.7.3",ry=()=>r||(r="u">typeof Bun?"bun":"u">typeof window&&void 0!==window.document?"browser":void 0===th.default||void 0===th.default.versions||void 0===th.default.versions.node||"u">typeof Deno?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"u">typeof window&&"nodejs"===window.name||"u">typeof navigator&&navigator.userAgent.includes("jsdom")?"jsdom":"u">typeof Deno?"deno":"other":"node");function r_(){return void 0===a&&(a={library:"langsmith",runtime:ry(),sdk:"langsmith-js",sdk_version:rg,...function(){if(void 0!==i)return i;let e={};for(let t of["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"]){let r=rv(t);void 0!==r&&(e[t]=r)}return i=e,e}()}),a}function rb(){let e=function(){let e={};try{if(void 0!==th.default&&th.default.env)for(let[t,r]of Object.entries(th.default.env))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&null!=r&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&"string"==typeof r?e[t]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):e[t]=r)}catch(e){}return e}(),t={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_CONFIG_FILE","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[a,i]of Object.entries(e))"string"!=typeof i||r.includes(a)||a.toLowerCase().includes("key")||a.toLowerCase().includes("secret")||a.toLowerCase().includes("token")||("LANGCHAIN_REVISION_ID"===a?t.revision_id=i:t[a]=i);return t}function rv(e){try{return void 0!==th.default?th.default.env?.[e]:void 0}catch(e){return}}function rw(e){return rv(`LANGSMITH_${e}`)||rv(`LANGCHAIN_${e}`)}function rx(){return"true"===rv("OTEL_ENABLED")||"true"===rw("OTEL_ENABLED")}let rk=new Set(["langsmith","otel"]);function rS(e){if(void 0!==e)return e;let t=rw("TRACING_MODE");if(void 0!==t&&""!==t){let e=t.toLowerCase();if(!rk.has(e))throw Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(t)}. Must be one of: ${[...rk].sort().join(", ")}`);return rx()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),e}return rx()?"otel":"langsmith"}class rT{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){let r;if(this.hasWarned||"otel"!==rS()||(console.warn('OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0),1===t.length&&"function"==typeof t[0]?r=t[0]:2===t.length&&"function"==typeof t[1]?r=t[1]:3===t.length&&"function"==typeof t[2]&&(r=t[2]),"function"==typeof r)return r()}}let rE=Symbol.for("ls:otel_trace"),rA=Symbol.for("ls:otel_context"),rI=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),rO=new class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new rT})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},rC=new class{active(){return{}}with(e,t){return t()}},rj=new class{getTraceInstance(){return globalThis[rE]??rO}getContextInstance(){return globalThis[rA]??rC}initializeGlobalInstances(e){void 0===globalThis[rE]&&(globalThis[rE]=e.trace),void 0===globalThis[rA]&&(globalThis[rA]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[rI]=e}getDefaultOTLPTracerComponents(){return globalThis[rI]??void 0}};function r$(){return rj.getTraceInstance()}let rP={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};class rN{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(let r of e)try{if(!r.run)continue;if("post"===r.operation){let e=this.createSpanForRun(r,r.run,t.get(r.id));e&&!r.run.end_time&&this.spans.set(r.id,e)}else this.updateSpanForRun(r,r.run)}catch(e){console.error(`Error processing operation ${r.id}:`,e)}}createSpanForRun(e,t,r){let a=r&&r$().getSpan(r);if(a)try{return this.finishSpanSetup(a,t,e)}catch(t){console.error(`Failed to create span for run ${e.id}:`,t);return}}finishSpanSetup(e,t,r){return this.setSpanAttributes(e,t,r),t.error?(e.setStatus({code:2}),e.recordException(Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{let r=this.spans.get(e.id);if(!r)return void console.debug(`No span found for run ${e.id} during update`);this.setSpanAttributes(r,t,e),t.error?(r.setStatus({code:2}),r.recordException(Error(t.error))):r.setStatus({code:1});let a=t.end_time;a&&(r.end(new Date(a)),this.spans.delete(e.id))}catch(t){console.error(`Failed to update span for run ${e.id}:`,t)}}extractModelName(e){if(e.extra?.metadata){let t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){let e=t.invocation_params;if(e.model)return e.model;if(e.model_name)return e.model_name}}}setSpanAttributes(e,t,r){var a;if("run_type"in t&&t.run_type){e.setAttribute("langsmith.span.kind",t.run_type);let r=rP[a=t.run_type||"chain"]||a;e.setAttribute("gen_ai.operation.name",r)}"name"in t&&t.name&&e.setAttribute("langsmith.trace.name",t.name),"session_id"in t&&t.session_id&&e.setAttribute("langsmith.trace.session_id",t.session_id),"session_name"in t&&t.session_name&&e.setAttribute("langsmith.trace.session_name",t.session_name),this.setGenAiSystem(e,t);let i=this.extractModelName(t);for(let[r,a]of(i&&e.setAttribute(tC,i),t.extra?.metadata?.usage_metadata&&"object"==typeof t.extra.metadata.usage_metadata&&e.setAttribute(tR,JSON.stringify(t.extra.metadata.usage_metadata)),"prompt_tokens"in t&&"number"==typeof t.prompt_tokens&&e.setAttribute(tj,t.prompt_tokens),"completion_tokens"in t&&"number"==typeof t.completion_tokens&&e.setAttribute(t$,t.completion_tokens),"total_tokens"in t&&"number"==typeof t.total_tokens&&e.setAttribute(tP,t.total_tokens),this.setInvocationParameters(e,t),Object.entries(t.extra?.metadata||{})))null!=a&&e.setAttribute(`langsmith.metadata.${r}`,"string"==typeof a||"number"==typeof a||"boolean"==typeof a?String(a):JSON.stringify(a));let n=t.tags;if(n&&Array.isArray(n)?e.setAttribute(tN,n.join(", ")):n&&e.setAttribute(tN,String(n)),"serialized"in t&&"object"==typeof t.serialized){let r=t.serialized;r.name&&e.setAttribute("gen_ai.serialized.name",String(r.name)),r.signature&&e.setAttribute("gen_ai.serialized.signature",String(r.signature)),r.doc&&e.setAttribute("gen_ai.serialized.doc",String(r.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,t){let r="langchain",a=this.extractModelName(t);if(a){let e=a.toLowerCase();e.includes("anthropic")||e.startsWith("claude")?r="anthropic":e.includes("bedrock")?r="aws.bedrock":e.includes("azure")&&e.includes("openai")?r="az.ai.openai":e.includes("azure")&&e.includes("inference")?r="az.ai.inference":e.includes("cohere")?r="cohere":e.includes("deepseek")?r="deepseek":e.includes("gemini")?r="gemini":e.includes("groq")?r="groq":e.includes("watson")||e.includes("ibm")?r="ibm.watsonx.ai":e.includes("mistral")?r="mistral_ai":e.includes("gpt")||e.includes("openai")?r="openai":e.includes("perplexity")||e.includes("sonar")?r="perplexity":e.includes("vertex")?r="vertex_ai":(e.includes("xai")||e.includes("grok"))&&(r="xai")}e.setAttribute("gen_ai.system",r)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;let r=t.extra.metadata.invocation_params;void 0!==r.max_tokens&&e.setAttribute("gen_ai.request.max_tokens",r.max_tokens),void 0!==r.temperature&&e.setAttribute("gen_ai.request.temperature",r.temperature),void 0!==r.top_p&&e.setAttribute("gen_ai.request.top_p",r.top_p),void 0!==r.frequency_penalty&&e.setAttribute("gen_ai.request.frequency_penalty",r.frequency_penalty),void 0!==r.presence_penalty&&e.setAttribute("gen_ai.request.presence_penalty",r.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{let r=t.run.inputs;"object"==typeof r&&null!==r&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(tC,r.model),void 0!==r.stream&&e.setAttribute("langsmith.request.streaming",r.stream),r.extra_headers&&e.setAttribute("langsmith.request.headers",JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute("gen_ai.request.extra_query",JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute("gen_ai.request.extra_body",JSON.stringify(r.extra_body))),e.setAttribute("gen_ai.prompt",JSON.stringify(r))}catch(e){console.debug(`Failed to process inputs for run ${t.id}`,e)}if(t.run.outputs)try{let r=t.run.outputs,a=this.getUnifiedRunTokens(r);if(a&&(e.setAttribute(tj,a[0]),e.setAttribute(t$,a[1]),e.setAttribute(tP,a[0]+a[1])),r&&"object"==typeof r){if(r.model&&e.setAttribute("gen_ai.response.model",String(r.model)),r.id&&e.setAttribute("gen_ai.response.id",r.id),r.choices&&Array.isArray(r.choices)){let t=r.choices.map(e=>e.finish_reason).filter(e=>e).map(String);t.length>0&&e.setAttribute("gen_ai.response.finish_reasons",t.join(", "))}if(r.service_tier&&e.setAttribute("gen_ai.response.service_tier",r.service_tier),r.system_fingerprint&&e.setAttribute("gen_ai.response.system_fingerprint",r.system_fingerprint),r.usage_metadata&&"object"==typeof r.usage_metadata){let t=r.usage_metadata;e.setAttribute(tR,JSON.stringify(t)),t.input_token_details&&e.setAttribute("gen_ai.usage.input_token_details",JSON.stringify(t.input_token_details)),t.output_token_details&&e.setAttribute("gen_ai.usage.output_token_details",JSON.stringify(t.output_token_details))}}e.setAttribute("gen_ai.completion",JSON.stringify(r))}catch(e){console.debug(`Failed to process outputs for run ${t.id}`,e)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;for(let r of Object.keys(e)){let a=e[r];if(a&&"object"==typeof a&&((t=this.extractUnifiedRunTokens(a.usage_metadata))||1===a.lc&&a.kwargs&&"object"==typeof a.kwargs&&(t=this.extractUnifiedRunTokens(a.kwargs.usage_metadata))))return t}let r=e.generations||[];if(!Array.isArray(r))return null;for(let e of Array.isArray(r[0])?r.flat():r)if("object"==typeof e&&e.message&&"object"==typeof e.message&&e.message.kwargs&&"object"==typeof e.message.kwargs&&(t=this.extractUnifiedRunTokens(e.message.kwargs.usage_metadata)))return t;return null}extractUnifiedRunTokens(e){return e&&"object"==typeof e&&"number"==typeof e.input_tokens&&"number"==typeof e.output_tokens?[e.input_tokens,e.output_tokens]:null}}let rR=Object.prototype.toString,rM=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 rz(e,t,{min:r=0,allowInfinity:a=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${a?" or Infinity":""}.`);if(!a&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}class rL extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}function rU(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function rD({error:e,attemptNumber:t,retriesConsumed:r,startTime:a,options:i}){let n,s=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof rL)throw s.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,l=i.maxRetryTime??1/0,u=Object.freeze({error:s,attemptNumber:t,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(u),0>=rU(a,l))throw s;let d=await i.shouldConsumeRetry(u),c=rU(a,l);if(c<=0||o<=0)throw s;if(s instanceof TypeError&&!function(e){if(!(e&&"[object Error]"===rR.call(e)&&"TypeError"===e.name&&"string"==typeof e.message))return!1;let{message:t,stack:r}=e;return"Load failed"===t?void 0===r||"__sentry_captured__"in e:!!t.startsWith("error sending request for url")||rM.has(t)}(s)){if(d)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(u))throw s;if(!d)return i.signal?.throwIfAborted(),!1;let h=Math.min((n=Math.max(1,r+1),Math.min(Math.round((i.randomize?Math.random()+1:1)*i.minTimeout*i.factor**(n-1)),i.maxTimeout)),c);return h>0&&await new Promise((e,t)=>{let r=()=>{clearTimeout(a),i.signal?.removeEventListener("abort",r),t(i.signal.reason)},a=setTimeout(()=>{i.signal?.removeEventListener("abort",r),e()},h);i.unref&&a.unref?.(),i.signal?.addEventListener("abort",r,{once:!0})}),i.signal?.throwIfAborted(),!0}async function rB(e,t={}){var r=(t={...t}).retries;if("number"==typeof r){if(r<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(void 0!==r)throw TypeError("Expected `retries` to be a number or Infinity.");if(Object.hasOwn(t,"forever"))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,rz("factor",t.factor,{min:0,allowInfinity:!1}),rz("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),rz("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),rz("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let a=0,i=0,n=performance.now();for(;!Number.isFinite(t.retries)||i<=t.retries;){a++;try{t.signal?.throwIfAborted();let r=await e(a);return t.signal?.throwIfAborted(),r}catch(e){await rD({error:e,attemptNumber:a,retriesConsumed:i,startTime:n,options:t})&&i++}}throw Error("Retry attempts exhausted without throwing an error.")}var rF=e.i(753274);let rZ="default"in rF.default?rF.default.default:rF.default,rH=[408,425,429,500,502,503,504];class rq{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new rZ({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){return this.callWithOptions({},e,...t)}callWithOptions(e,t,...r){let a=e.sizeBytes??0;if(void 0!==this.maxQueueSizeBytes&&a>0&&this.queueSizeBytes+a>this.maxQueueSizeBytes)return Promise.reject(Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${a} bytes.`));a>0&&(this.queueSizeBytes+=a);let i=this.onFailedResponseHook,n=this.queue.add(()=>rB(()=>t(...r).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{async onFailedAttempt({error:e}){if("object"!=typeof e||null==e)throw e;let t="message"in e&&"string"==typeof e.message?e.message:void 0;if(t?.startsWith("Cancel")||t?.startsWith("TimeoutError")||t?.startsWith("AbortError")||"name"in e&&"TimeoutError"===e.name||"code"in e&&"ECONNABORTED"===e.code)throw e;let r="response"in e?e.response:void 0;if(i&&await i(r))return;let a=r?.status??("status"in e?e.status:void 0);if(null!=a&&("number"==typeof a||"string"==typeof a)&&!rH.includes(+a))throw e},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return(a>0&&(n=n.finally(()=>{this.queueSizeBytes-=a})),e.signal)?Promise.race([n,new Promise((t,r)=>{e.signal?.addEventListener("abort",()=>{r(Error("AbortError"))})})]):n}}function rJ(e){return"function"==typeof e?._getType}function rG(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}let rW={};function rV(e){rW[e]||(console.warn(e),rW[e]=!0)}function rK(e){return`Invalid prompt identifier format: "${e}". Expected one of:
|
|
11
11
|
- "prompt-name" (for private prompts)
|
|
12
12
|
- "owner/prompt-name" (for prompts with explicit owner)
|
|
13
13
|
- "prompt-name:commit-hash" (with commit reference)
|
|
14
|
-
- "owner/prompt-name:commit-hash" (with owner and commit)`}class rQ extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}class rY extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}}function rX(e){return null!=e&&"object"==typeof e&&"name"in e&&e?.name==="LangSmithNotFoundError"}async function r0(e,t,r){let a;if(e.ok){r&&(a=await e.text());return}if(403===e.status)try{let t=await e.json(),r=t?.error;"org_scoped_key_requires_workspace"===r&&(a="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch(r){let t=Error(`${e.status} ${e.statusText}`);throw t.status=e?.status,t}if(void 0===a)try{a=await e.text()}catch(e){a=""}let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${a}`;if(404===e.status)throw new rY(i);if(409===e.status)throw new rQ(i);let n=Error(i);throw n.status=e.status,n}let r1="ERR_CONFLICTING_ENDPOINTS";class r2 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:r1}),this.name="ConflictingEndpointsError"}}function r4(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw Error(rK(e));let[t,r]=e.split(":"),a=r||"latest";if(t.includes("/")){let[r,i]=t.split("/",2);if(!r||!i)throw Error(rK(e));return[r,i,a]}if(!t)throw Error(rK(e));return["-",t,a]}let
|
|
15
|
-
`)}catch{return}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=e?.name==="Authorization"?e.value:void 0}}function ae(e){let t=
|
|
14
|
+
- "owner/prompt-name:commit-hash" (with owner and commit)`}class rQ extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}class rY extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}}function rX(e){return null!=e&&"object"==typeof e&&"name"in e&&e?.name==="LangSmithNotFoundError"}async function r0(e,t,r){let a;if(e.ok){r&&(a=await e.text());return}if(403===e.status)try{let t=await e.json(),r=t?.error;"org_scoped_key_requires_workspace"===r&&(a="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch(r){let t=Error(`${e.status} ${e.statusText}`);throw t.status=e?.status,t}if(void 0===a)try{a=await e.text()}catch(e){a=""}let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${a}`;if(404===e.status)throw new rY(i);if(409===e.status)throw new rQ(i);let n=Error(i);throw n.status=e.status,n}let r1="ERR_CONFLICTING_ENDPOINTS";class r2 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:r1}),this.name="ConflictingEndpointsError"}}function r4(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw Error(rK(e));let[t,r]=e.split(":"),a=r||"latest";if(t.includes("/")){let[r,i]=t.split("/",2);if(!r||!i)throw Error(rK(e));return[r,i,a]}if(!t)throw Error(rK(e));return["-",t,a]}let r9="https://api.smith.langchain.com";function r6(e){return null!=e&&""!==e.trim()}function r5(e){return e?.trim().replace(/^["']|["']$/g,"")}function r3(e){return e.reason??Error("The operation was aborted.")}async function r8(e,t){let r;if(!t)return e;if(t.aborted)throw r3(t);let a=new Promise((e,a)=>{let i=()=>{a(r3(t))};t.addEventListener("abort",i,{once:!0}),r=()=>{t.removeEventListener("abort",i)}});try{return await Promise.race([e,a])}finally{r?.()}}class r7{constructor(e){Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"refreshPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedAuthorizationValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.rememberProfileAuthHeader(this.currentAuthHeader())}currentAuthHeader(){var e;let t,r=(e=this.state.profile,(t=r5(e.oauth?.access_token))?{name:"Authorization",value:`Bearer ${t}`}:r5(e.oauth?.refresh_token)?void 0:ae(e));return this.rememberProfileAuthHeader(r),r}async getAuthHeader(e,t){(function(e){let t=e.oauth;if(!t?.refresh_token)return!1;if(!t.access_token)return!0;if(!t.expires_at)return!1;let r=Date.parse(t.expires_at);return!Number.isNaN(r)&&r<=Date.now()+6e4})(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await r8(this.refreshPromise,t));let r=ae(this.state.profile);return this.rememberProfileAuthHeader(r),r}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}async refreshOAuthToken(e){let t=this.state.profile.oauth?.refresh_token;if(!t)return;let r=r5(this.state.profile.api_url)??r9;try{var a;let i=new URLSearchParams({grant_type:"refresh_token",client_id:"langsmith-cli",refresh_token:t}),n=await e(`${function(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);let r="/api/v1";return t.endsWith(r)?t.slice(0,-r.length):t}(r)}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString(),signal:AbortSignal.timeout(1e4)});if(!n.ok)return;let s=await n.json();if(!s.access_token)return;a=this.state.profile,a.oauth??={},s.access_token&&(a.oauth.access_token=s.access_token),s.refresh_token&&(a.oauth.refresh_token=s.refresh_token),"number"==typeof s.expires_in&&s.expires_in>0&&(a.oauth.expires_at=new Date(Date.now()+1e3*s.expires_in).toISOString()),this.state.config.profiles??={},this.state.config.profiles[this.state.profileName]=this.state.profile,await rh(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}
|
|
15
|
+
`)}catch{return}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=e?.name==="Authorization"?e.value:void 0}}function ae(e){let t=r5(e.oauth?.access_token);if(t)return{name:"Authorization",value:`Bearer ${t}`};let r=r5(e.api_key);if(r)return{name:"x-api-key",value:r}}var at={result:"[Circular]"},ar=[],aa=[];let ai=new TextEncoder;function an(e){return ai.encode(e)}function as(e){if(e&&"object"==typeof e&&null!==e){if(e instanceof Map)return Object.fromEntries(e);else if(e instanceof Set)return Array.from(e);else if(e instanceof Date)return e.toISOString();else if(e instanceof RegExp)return e.toString();else if(e instanceof Error)return{name:e.name,message:e.message}}else if("bigint"==typeof e)return e.toString();return e}function ao(e,t,r,a,i){try{let t=JSON.stringify(e,function(e,t){if(r){let a=r.call(this,e,t);if(void 0!==a)return a}return as(t)},a);return an(t)}catch(o){let s;if(!o.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
|
|
16
16
|
Context: ${t}`:""}`),an("[Unserializable]");"true"!==rw("SUPPRESS_CIRCULAR_JSON_WARNINGS")&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`
|
|
17
|
-
Context: ${t}`:""}`),void 0===i&&(i={depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}),function e(t,r,a,i,n,s,o){if(s+=1,"object"==typeof t&&null!==t){for(l=0;l<i.length;l++)if(i[l]===t)return void al(at,t,r,n);if(void 0!==o.depthLimit&&s>o.depthLimit||void 0!==o.edgesLimit&&a+1>o.edgesLimit)return void al("[...]",t,r,n);if(i.push(t),Array.isArray(t))for(l=0;l<t.length;l++)e(t[l],l,l,i,t,s,o);else{var l,u=Object.keys(t=as(t));for(l=0;l<u.length;l++){var d=u[l];e(t[d],d,l,i,t,s,o)}}i.pop()}}(e,"",0,[],void 0,0,i);try{var n;s=0===aa.length?JSON.stringify(e,r,a):JSON.stringify(e,(n=r,n=void 0!==n?n:function(e,t){return t},function(e,t){if(aa.length>0)for(var r=0;r<aa.length;r++){var a=aa[r];if(a[1]===e&&a[0]===t){t=a[2],aa.splice(r,1);break}}return n.call(this,e,t)}),a)}catch(e){return an("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==ar.length;){let e=ar.pop();4===e.length?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return an(s)}}function al(e,t,r,a){var i=Object.getOwnPropertyDescriptor(a,r);void 0!==i.get?i.configurable?(Object.defineProperty(a,r,{value:e}),ar.push([a,r,t,i])):aa.push([t,r,e]):(a[r]=e,ar.push([a,r,t]))}class au{constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(null!==this.worker)return!0;if(null!==this.startPromise)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){return this.disabled=!0,!1}async serialize(e){if(!await this.ensureStarted())return null;let t=this.nextId++;return new Promise((r,a)=>{this.pending.set(t,{resolve:r,reject:a});try{this.worker.postMessage({id:t,op:"serialize",payload:e})}catch(e){this.pending.delete(t),a(e)}})}async terminate(){for(let[,e]of(this.worker&&(await this.worker.terminate(),this.worker=null),this.pending))e.reject(Error("worker terminated"));this.pending.clear()}}let ad=null;function ac(e){return"string"!=typeof e||!(e.length>0)||e.includes("Z")||e.includes("+")||e.includes("-",10)?e:e+"Z"}function ah(e){return{...e,start_time:ac(e.start_time),end_time:ac(e.end_time)}}function ap(e,t,r){if(r)return e;let a=r_(),i=t??rb(),n=e.extra??{},s=n.metadata;return e.extra={...n,runtime:{...a,...n?.runtime},metadata:{...i,...i.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??i.revision_id}:{},...s}},e}async function af(e){let t=[];for await(let r of e)t.push(r);return t}function am(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}let ag=async e=>{if(e?.status===429){let t=1e3*parseInt(e.headers.get("retry-after")??"10",10);if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};function ay(e){return"number"==typeof e?Number(e.toFixed(4)):e}class a_{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??0x40000000}peek(){return this.items[0]}push(e){let t,r=new Promise(e=>{t=e}),a=function(e){try{let i=new Set,n=0,s=void 0!==e_.Buffer&&"function"==typeof e_.Buffer.byteLength?e=>e_.Buffer.byteLength(e,"utf8"):e=>e.length;function t(e){return void 0===e||"function"==typeof e||"symbol"==typeof e}function r(e){return void 0===e||"function"==typeof e||"symbol"==typeof e?4:a(e)}function a(e){var o;let l;if(null===e)return 4;if(void 0===e)return 0;let u=typeof e;if("boolean"===u)return 5;if("number"===u)return Number.isFinite(e)?e.toString().length:4;if("bigint"===u)return e.toString().length+2;if("string"===u){let t;return(t=s(e))>n&&(n=t),t+2}if("function"===u||"symbol"===u)return 0;if(e instanceof Date)return 26;if(e instanceof RegExp)return s(e.toString())+2;if(e instanceof Error){let t=e.name??"",r=e.message??"";return 22+s(t)+s(r)}if(void 0!==e_.Buffer&&e instanceof e_.Buffer)return 28+(o=e.byteLength,0===o?2:2+4*o);if(ArrayBuffer.isView(e)){if(e instanceof DataView)return 2;let t=e.length??0,r=e instanceof Float32Array||e instanceof Float64Array;return 2+t*(r?30:12)}if(e instanceof ArrayBuffer)return 2;if(i.has(e))return 24;if("function"==typeof e.toJSON){let t;try{t=e.toJSON("")}catch{return 16}i.add(e);let r=a(t);return i.delete(e),r}if(i.add(e),Array.isArray(e)){l=2;let t=e.length;for(let a=0;a<t;a++)l+=r(e[a]),a<t-1&&(l+=1)}else if(e instanceof Map){l=2;let r=0;for(let[i,n]of e){if(t(n))continue;r>0&&(l+=1);let e="string"==typeof i?i:String(i);l+=s(e)+3,l+=a(n),r++}}else if(e instanceof Set){l=2;let t=0;for(let a of e)t>0&&(l+=1),l+=r(a),t++}else{l=2;let r=0,i=Object.keys(e);for(let n=0;n<i.length;n++){let o=i[n],u=e[o];!t(u)&&(r>0&&(l+=1),l+=s(o)+3,l+=a(u),r++)}}return i.delete(e),l}return{size:a(e),maxStringLen:n}}catch{return{size:ao(e).length,maxStringLen:0}}}(e.item).size;return this.sizeBytes+a>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${a} bytes.`),t()):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:r,size:a}),this.sizeBytes+=a),r}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw Error("Number of bytes to pop off may not be less than 1.");let r=[],a=0;for(;a+(this.peek()?.size??0)<e&&this.items.length>0&&r.length<t;){let e=this.items.shift();e&&(r.push(e),a+=e.size,this.sizeBytes-=e.size)}if(0===r.length&&this.items.length>0){let e=this.items.shift();r.push(e),a+=e.size,this.sizeBytes-=e.size}return[r.map(e=>({action:e.action,item:e.payload,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,size:e.size})),()=>r.forEach(e=>e.itemPromiseResolve())]}}class ab{get tracingMode(){return this._tracingMode}get _fetch(){let e,t=this.fetchImplementation||(e=this.debug,async(...t)=>{if(e||"true"===rw("DEBUG")){let[e,r]=t;console.log(`→ ${r?.method||"GET"} ${e}`)}let r=await (globalThis[tM]??((...e)=>fetch(...e)))(...t);return(e||"true"===rw("DEBUG"))&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r});return async(e,r)=>{let a,i=this.getProfileManagedAuthorizationHeader(r);return void 0!==this.apiKey?a={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(r,i)||(a=await this.profileAuth?.getAuthHeader(t,r?.signal)),t(e,this.applyCurrentAuthHeaders(r,a,i))}}getProfileManagedAuthorizationHeader(e){if(!e?.headers||!this.profileAuth)return;let t=new Headers(e.headers).get("Authorization");if(r5(t))return this.profileAuth.isProfileAuthorizationHeader(t??"")?t??void 0:void 0}isProfileManagedAuthorizationHeader(e,t){return e===t||this.profileAuth?.isProfileAuthorizationHeader(e)===!0}hasExplicitAuthHeader(e,t){if(!e?.headers)return!1;let r=new Headers(e.headers);if(r5(r.get("x-api-key")))return!0;let a=r.get("Authorization");return!!r5(a)&&!this.isProfileManagedAuthorizationHeader(a??"",t)}applyCurrentAuthHeaders(e,t,r){if(!t)return e;let a=e=>{if(void 0!==this.apiKey&&"x-api-key"===t.name)return e.delete("Authorization"),e.has("x-api-key")||e.set("x-api-key",t.value),e;if("Authorization"===t.name){if(r5(e.get("x-api-key")))return e;let a=e.get("Authorization");return r5(a)&&!this.isProfileManagedAuthorizationHeader(a??"",r)||e.set("Authorization",t.value),e}let a=e.get("Authorization");return r5(a)&&!this.isProfileManagedAuthorizationHeader(a??"",r)||(r5(a)&&e.delete("Authorization"),e.has("x-api-key")||e.set("x-api-key",t.value)),e};if(!e)return{headers:{[t.name]:t.value}};if(e.headers instanceof Headers||Array.isArray(e.headers))return{...e,headers:a(new Headers(e.headers))};let i={...e.headers??{}},n=e=>Object.keys(i).find(t=>t.toLowerCase()===e),s=e=>{let t=n(e);return t?i[t]:void 0},o=r5(s("x-api-key")),l=s("authorization"),u=r5(l)&&!this.isProfileManagedAuthorizationHeader(l??"",r);if(void 0!==this.apiKey&&"x-api-key"===t.name){let r=n("authorization");return r&&delete i[r],o||(i["x-api-key"]=t.value),{...e,headers:i}}if("Authorization"===t.name){if(!o&&!u){let e=n("authorization");e&&"Authorization"!==e&&delete i[e],i.Authorization=t.value}return{...e,headers:i}}if(!u){let e=n("authorization");e&&delete i[e],o||(i["x-api-key"]=t.value)}return{...e,headers:i}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,t){if(this.manualFlushMode||!function(e,t=65536,r=2048){if(null===e||"object"!=typeof e)return"string"==typeof e&&e.length>=t;let a=[e],i=new Set,n=0;for(;a.length>0&&!(n++>=r);){let e=a.pop();if(null==e)continue;let r=typeof e;if("string"===r){if(e.length>=t)return!0;continue}if("object"!==r||i.has(e)||(i.add(e),e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof ArrayBuffer||ArrayBuffer.isView(e)))continue;if(Array.isArray(e)){for(let t=e.length-1;t>=0;t--)a.push(e[t]);continue}if(e instanceof Map){for(let[,t]of e)a.push(t);continue}if(e instanceof Set){for(let t of e)a.push(t);continue}let n=Object.keys(e);for(let t=n.length-1;t>=0;t--)a.push(e[n[t]])}return!1}(e)||(void 0===this._serializeWorker&&(this._serializeWorker=(null===ad&&(ad=new au),ad)),null===this._serializeWorker))return ao(e,t);try{let r=await this._serializeWorker.serialize(e);if(null===r)return this._serializeWorker=null,ao(e,t);return r}catch{return ao(e,t)}}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideMetadata",{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:"false"===rv("LANGSMITH_TRACING_BACKGROUND")}),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,"_serializeWorker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingDrains",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tracingMode",{enumerable:!0,configurable:!0,writable:!0,value:"langsmith"}),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,"profileAuth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:"true"===rw("DISABLE_MULTIPART_STREAMING")}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:"true"===rw("DISABLE_RUN_COMPRESSION")}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:0x6400000}),Object.defineProperty(this,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:"true"===rv("LANGSMITH_DEBUG")});const t=ab.getDefaultClientConfig();this.tracingSampleRate=(e=>{let t=e?.toString()??rw("TRACING_SAMPLING_RATE");if(void 0===t)return;let r=parseFloat(t);if(r<0||r>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r})(e.tracingSamplingRate),this.apiUrl=am(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));const r=am(e.apiKey??t.apiKey);if(this.apiKey=r5(r)?r:void 0,this.profileAuth=void 0!==this.apiKey?void 0:t.profileAuth,this.webUrl=am(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=am(e.workspaceId??t.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new rq({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=rw("FAILED_TRACES_DIR")||void 0;const a=rw("FAILED_TRACES_MAX_MB");if(a){const e=parseInt(a,10);Number.isFinite(e)&&e>0&&(this.failedTracesMaxBytes=1024*e*1024)}const i=e.maxIngestMemoryBytes??0x40000000;this.batchIngestCaller=new rq({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:i,...e.callerOptions??{},onFailedResponseHook:ag,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.hideMetadata=e.hideMetadata??t.hideMetadata,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new a_(i),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=rS(e.tracingMode),"otel"===this._tracingMode&&(this.langSmithToOTELTranslator=new rN),this.cachedLSEnvVarsForMetadata=rb(),void 0!==e.cache&&e.disablePromptCache&&rV("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),void 0!==e.cache?(rV("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."),!1===e.cache?this._promptCache=void 0:!0===e.cache?this._promptCache=rm:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=rm),this._customHeaders=e.headers??{}}static getDefaultClientConfig(){let e=function(){let e=function(){let e;if("browser"!==(e=ry())&&"webworker"!==e)(function(){let e=rv("LANGSMITH_CONFIG_FILE");if(e)return;let t=rv("HOME")??rv("USERPROFILE");if(t)rd(t,".langsmith","config.json")})()}(),t=e?.profile;if(!e||!t)return{};let r=r9(t.api_key),a=r9(t.oauth?.access_token),i=r9(t.oauth?.refresh_token);return{apiUrl:t.api_url,apiKey:r,workspaceId:t.workspace_id,oauthAccessToken:a,oauthRefreshToken:i,profileAuth:r||a||i?new r7(e):void 0}}(),t=rw("API_KEY"),r=rw("ENDPOINT"),a=rw("WORKSPACE_ID"),i=r5(t),n=r??e.apiUrl??r6,s=a??e.workspaceId;return{apiUrl:n,apiKey:t,webUrl:void 0,hideInputs:"true"===rw("HIDE_INPUTS"),hideOutputs:"true"===rw("HIDE_OUTPUTS"),hideMetadata:"true"===rw("HIDE_METADATA"),workspaceId:s,oauthAccessToken:i?void 0:e.oauthAccessToken,oauthRefreshToken:i?void 0:e.oauthRefreshToken,profileAuth:i?void 0:e.profileAuth}}getHostUrl(){let e;if(this.webUrl)return this.webUrl;if("localhost"===(e=this.apiUrl.replace("http://","").replace("https://","").split("/")[0].split(":")[0])||"127.0.0.1"===e||"::1"===e)return this.webUrl="http://localhost:3000",this.webUrl;if(this.apiUrl.endsWith("/api/v1"))return this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl;if(this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api"))return this.webUrl=this.apiUrl.replace("/api",""),this.webUrl;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("aws"))return this.webUrl="https://aws.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("apac"))return this.webUrl="https://apac.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 _mergedHeaders(){let e={"User-Agent":`langsmith-js/${rg}`,...this._customHeaders};if(void 0!==this.apiKey)e["x-api-key"]=`${this.apiKey}`;else{let t=this.profileAuth?.currentAuthHeader();t&&(e[t.name]=t.value)}return this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get headers(){return this._customHeaders}set headers(e){this._customHeaders=e??{}}_getPlatformEndpointPath(e){return"/v1"!==this.apiUrl.slice(-3)&&"/v1/"!==this.apiUrl.slice(-4)?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}async processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}async processMetadata(e){return!1===this.hideMetadata?e:!0===this.hideMetadata?{}:"function"==typeof this.hideMetadata?this.hideMetadata(e):e}_filterNewTokenEvents(e){return e&&0!==e.length?e.map(e=>{if("new_token"===e.name){let{kwargs:t,...r}=e;return r}return e}):e}async prepareRunCreateOrUpdateInputs(e){let t={...e};return void 0!==t.inputs&&(t.inputs=await this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),null!=t.extra&&"metadata"in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),void 0!==t.events&&(t.events=this._filterNewTokenEvents(t.events)),t}async _getResponse(e,t){let r=t?.toString()??"",a=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{let t=await this._fetch(a,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(t,`fetch ${e}`),t})}async _get(e,t){return(await this._getResponse(e,t)).json()}async *_getPaginated(e,t=new URLSearchParams,r){let a=Number(t.get("offset"))||0,i=Number(t.get("limit"))||100;for(;;){t.set("offset",String(a)),t.set("limit",String(i));let n=`${this.apiUrl}${e}?${t}`,s=await this.caller.call(async()=>{let t=await this._fetch(n,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(t,`fetch ${e}`),t}),o=r?r(await s.json()):await s.json();if(0===o.length||(yield o,o.length<i))break;a+=o.length}}async *_getCursorPaginatedList(e,t=null,r="POST",a="runs"){let i=t?{...t}:{};for(;;){let t=JSON.stringify(i),n=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await r0(a,`fetch ${e}`),a}),s=await n.json();if(!s||!s[a])break;yield s[a];let o=s.cursors;if(!o||!o.next)break;i.cursor=o.next}}_shouldSample(){return void 0===this.tracingSampleRate||Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(void 0===this.tracingSampleRate)return e;if(t){let t=[];for(let r of e)this.filteredPostUuids.has(r.trace_id)?r.id===r.trace_id&&this.filteredPostUuids.delete(r.trace_id):t.push(r);return t}{let t=[];for(let r of e){let e=r.trace_id??r.id;this.filteredPostUuids.has(e)||(r.id===e?this._shouldSample()?t.push(r):this.filteredPostUuids.add(e):t.push(r))}return t}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??0x1800000}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??100}async _getDatasetExamplesMultiPartSupport(){let e=await this._ensureServerInfo();return e.instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){let r=[];for(;this.autoBatchQueue.items.length>0;){let[a,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!a.length){i();break}let n=a.reduce((e,t)=>{let r=t.apiUrl??this.apiUrl,a=t.apiKey??this.apiKey,i=t.apiKey===this.apiKey&&t.apiUrl===this.apiUrl?"default":`${r}|${a}`;return e[i]||(e[i]=[]),e[i].push(t),e},{}),s=[];for(let[e,t]of Object.entries(n)){let r=this._processBatch(t,{apiUrl:"default"===e?void 0:e.split("|")[0],apiKey:"default"===e?void 0:e.split("|")[1]});s.push(r)}let o=Promise.all(s).finally(i);r.push(o)}return Promise.all(r)}static async _writeTraceToFallbackDir(e,t,r,a,i){try{let n="string"==typeof t?e_.Buffer.from(t,"utf8"):e_.Buffer.from(t),s=JSON.stringify({version:1,endpoint:a,headers:r,body_base64:n.toString("base64")}),o=`trace_${Date.now()}_${tx().slice(0,8)}.json`,l=rd(e,o);if(ab._fallbackDirsCreated.has(e)||(await rc(e),ab._fallbackDirsCreated.add(e)),void 0!==i&&i>0)try{let t=(await rp(e)).filter(e=>e.startsWith("trace_")&&e.endsWith(".json")),r=0;for(let a of t){let{size:t}=await rf(rd(e,a));r+=t}if(r>=i)return void console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${r} bytes >= ${i} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`)}catch{}await rh(l,s),console.warn(`LangSmith trace upload failed; data saved to ${l} for later replay.`)}catch(t){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,t)}}async _processBatch(e,t){if(!e.length)return;let r=e.reduce((e,t)=>e+(t.size??0),0);try{if(void 0!==this.langSmithToOTELTranslator)this._sendBatchToOTELTranslator(e);else{let a={runCreates:e.filter(e=>"create"===e.action).map(e=>e.item),runUpdates:e.filter(e=>"update"===e.action).map(e=>e.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let e=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(a,{...t,useGzip:e,sizeBytes:r})}catch(e){if(rX(e))this._multipartDisabled=!0,await this.batchIngestRuns(a,{...t,sizeBytes:r});else throw e}}else await this.batchIngestRuns(a,{...t,sizeBytes:r})}}catch(e){console.error("Error exporting batch:",e)}}_sendBatchToOTELTranslator(e){if(void 0!==this.langSmithToOTELTranslator){let t=new Map,r=[];for(let a of e)a.item.id&&a.otelContext&&(t.set(a.item.id,a.otelContext),"create"===a.action?r.push({operation:"post",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}):r.push({operation:"patch",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}));this.langSmithToOTELTranslator.exportBatch(r,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=ap(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;let r=await this._getBatchSizeLimitBytes(),a=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>a)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:a})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:a}))},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){let e=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(1e4),...this.fetchOptions});return await r0(e,"get server info"),e}),t=await e.json();return this.debug&&console.log("\n=== LangSmith Server Configuration ===\n"+JSON.stringify(t,null,2)+"\n"),t}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){let e=rP(),t=rj.getContextInstance();if(void 0!==this.langSmithToOTELTranslator){let r=e.getActiveSpan();if(r)return e.setSpan(t.active(),r)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;let r={...this._mergedHeaders,"Content-Type":"application/json"},a=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:a,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==i.trace_id&&void 0!==i.dotted_order){let e=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:e,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}let n=ap(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),t?.workspaceId!==void 0&&(r["x-tenant-id"]=t.workspaceId);let s=ao(n,`Creating run with id: ${n.id}`);await this.caller.call(async()=>{let e=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await r0(e,"create run",!0),e})}async batchIngestRuns({runCreates:e,runUpdates:t},r){if(void 0===e&&void 0===t)return;let a=await Promise.all(e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]),i=await Promise.all(t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]);if(a.length>0&&i.length>0){let e=a.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of i)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);a=Object.values(e),i=t}let n={post:a,patch:i};if(!n.post.length&&!n.patch.length)return;let s={post:[],patch:[]};for(let e of["post","patch"]){let t=n[e].reverse(),r=t.pop();for(;void 0!==r;)s[e].push(r),r=t.pop()}if(s.post.length>0||s.patch.length>0){let e=s.post.map(e=>e.id).concat(s.patch.map(e=>e.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(s,`Ingesting runs with ids: ${e}`),r)}}async _postBatchIngestRuns(e,t){let r={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:t?.sizeBytes},async()=>{let a=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await r0(a,"batch create run",!0),a})}async multipartIngestRuns({runCreates:e,runUpdates:t},r){if(void 0===e&&void 0===t)return;let a={},i=[];for(let t of e??[]){let e=await this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(a[e.id]=e.attachments),delete e.attachments,i.push(e)}let n=[];for(let e of t??[])n.push(await this.prepareRunCreateOrUpdateInputs(e));if(void 0!==i.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==n.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&n.length>0){let e=i.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of n)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);i=Object.values(e),n=t}if(0===i.length&&0===n.length)return;let s=[],o=[];for(let[e,t]of[["post",i],["patch",n]])for(let r of t){let{inputs:t,outputs:i,events:n,extra:l,error:u,serialized:d,attachments:c,...h}=r,p={inputs:t,outputs:i,events:n,extra:l,error:u,serialized:d},f=await this._serializeBody(h,`Serializing for multipart ingestion of run with id: ${h.id}`);for(let[t,r]of(o.push({name:`${e}.${h.id}`,payload:new Blob([f],{type:`application/json; length=${f.length}`})}),Object.entries(p))){if(void 0===r)continue;let a=await this._serializeBody(r,`Serializing ${t} for multipart ingestion of run with id: ${h.id}`);o.push({name:`${e}.${h.id}.${t}`,payload:new Blob([a],{type:`application/json; length=${a.length}`})})}if(void 0!==h.id){let e=a[h.id];if(e)for(let[t,r]of(delete a[h.id],Object.entries(e))){let e,a;if(Array.isArray(r)?[e,a]=r:(e=r.mimeType,a=r.data),t.includes(".")){console.warn(`Skipping attachment '${t}' for run ${h.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}o.push({name:`attachment.${h.id}.${t}`,payload:new Blob([a],{type:`${e}; length=${a.byteLength}`})})}}s.push(`trace=${h.trace_id},id=${h.id}`)}await this._sendMultipartRequest(o,s.join("; "),r)}async _createNodeFetchBody(e,t){let r=[];for(let a of e)r.push(new Blob([`--${t}\r
|
|
17
|
+
Context: ${t}`:""}`),void 0===i&&(i={depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}),function e(t,r,a,i,n,s,o){if(s+=1,"object"==typeof t&&null!==t){for(l=0;l<i.length;l++)if(i[l]===t)return void al(at,t,r,n);if(void 0!==o.depthLimit&&s>o.depthLimit||void 0!==o.edgesLimit&&a+1>o.edgesLimit)return void al("[...]",t,r,n);if(i.push(t),Array.isArray(t))for(l=0;l<t.length;l++)e(t[l],l,l,i,t,s,o);else{var l,u=Object.keys(t=as(t));for(l=0;l<u.length;l++){var d=u[l];e(t[d],d,l,i,t,s,o)}}i.pop()}}(e,"",0,[],void 0,0,i);try{var n;s=0===aa.length?JSON.stringify(e,r,a):JSON.stringify(e,(n=r,n=void 0!==n?n:function(e,t){return t},function(e,t){if(aa.length>0)for(var r=0;r<aa.length;r++){var a=aa[r];if(a[1]===e&&a[0]===t){t=a[2],aa.splice(r,1);break}}return n.call(this,e,t)}),a)}catch(e){return an("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==ar.length;){let e=ar.pop();4===e.length?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return an(s)}}function al(e,t,r,a){var i=Object.getOwnPropertyDescriptor(a,r);void 0!==i.get?i.configurable?(Object.defineProperty(a,r,{value:e}),ar.push([a,r,t,i])):aa.push([t,r,e]):(a[r]=e,ar.push([a,r,t]))}class au{constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(null!==this.worker)return!0;if(null!==this.startPromise)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){return this.disabled=!0,!1}async serialize(e){if(!await this.ensureStarted())return null;let t=this.nextId++;return new Promise((r,a)=>{this.pending.set(t,{resolve:r,reject:a});try{this.worker.postMessage({id:t,op:"serialize",payload:e})}catch(e){this.pending.delete(t),a(e)}})}async terminate(){for(let[,e]of(this.worker&&(await this.worker.terminate(),this.worker=null),this.pending))e.reject(Error("worker terminated"));this.pending.clear()}}let ad=null;function ac(e){return"string"!=typeof e||!(e.length>0)||e.includes("Z")||e.includes("+")||e.includes("-",10)?e:e+"Z"}function ah(e){return{...e,start_time:ac(e.start_time),end_time:ac(e.end_time)}}function ap(e,t,r){if(r)return e;let a=r_(),i=t??rb(),n=e.extra??{},s=n.metadata;return e.extra={...n,runtime:{...a,...n?.runtime},metadata:{...i,...i.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??i.revision_id}:{},...s}},e}async function af(e){let t=[];for await(let r of e)t.push(r);return t}function am(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}let ag=async e=>{if(e?.status===429){let t=1e3*parseInt(e.headers.get("retry-after")??"10",10);if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};function ay(e){return"number"==typeof e?Number(e.toFixed(4)):e}class a_{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??0x40000000}peek(){return this.items[0]}push(e){let t,r=new Promise(e=>{t=e}),a=function(e){try{let i=new Set,n=0,s=void 0!==e_.Buffer&&"function"==typeof e_.Buffer.byteLength?e=>e_.Buffer.byteLength(e,"utf8"):e=>e.length;function t(e){return void 0===e||"function"==typeof e||"symbol"==typeof e}function r(e){return void 0===e||"function"==typeof e||"symbol"==typeof e?4:a(e)}function a(e){var o;let l;if(null===e)return 4;if(void 0===e)return 0;let u=typeof e;if("boolean"===u)return 5;if("number"===u)return Number.isFinite(e)?e.toString().length:4;if("bigint"===u)return e.toString().length+2;if("string"===u){let t;return(t=s(e))>n&&(n=t),t+2}if("function"===u||"symbol"===u)return 0;if(e instanceof Date)return 26;if(e instanceof RegExp)return s(e.toString())+2;if(e instanceof Error){let t=e.name??"",r=e.message??"";return 22+s(t)+s(r)}if(void 0!==e_.Buffer&&e instanceof e_.Buffer)return 28+(o=e.byteLength,0===o?2:2+4*o);if(ArrayBuffer.isView(e)){if(e instanceof DataView)return 2;let t=e.length??0,r=e instanceof Float32Array||e instanceof Float64Array;return 2+t*(r?30:12)}if(e instanceof ArrayBuffer)return 2;if(i.has(e))return 24;if("function"==typeof e.toJSON){let t;try{t=e.toJSON("")}catch{return 16}i.add(e);let r=a(t);return i.delete(e),r}if(i.add(e),Array.isArray(e)){l=2;let t=e.length;for(let a=0;a<t;a++)l+=r(e[a]),a<t-1&&(l+=1)}else if(e instanceof Map){l=2;let r=0;for(let[i,n]of e){if(t(n))continue;r>0&&(l+=1);let e="string"==typeof i?i:String(i);l+=s(e)+3,l+=a(n),r++}}else if(e instanceof Set){l=2;let t=0;for(let a of e)t>0&&(l+=1),l+=r(a),t++}else{l=2;let r=0,i=Object.keys(e);for(let n=0;n<i.length;n++){let o=i[n],u=e[o];!t(u)&&(r>0&&(l+=1),l+=s(o)+3,l+=a(u),r++)}}return i.delete(e),l}return{size:a(e),maxStringLen:n}}catch{return{size:ao(e).length,maxStringLen:0}}}(e.item).size;return this.sizeBytes+a>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${a} bytes.`),t()):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:r,size:a}),this.sizeBytes+=a),r}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw Error("Number of bytes to pop off may not be less than 1.");let r=[],a=0;for(;a+(this.peek()?.size??0)<e&&this.items.length>0&&r.length<t;){let e=this.items.shift();e&&(r.push(e),a+=e.size,this.sizeBytes-=e.size)}if(0===r.length&&this.items.length>0){let e=this.items.shift();r.push(e),a+=e.size,this.sizeBytes-=e.size}return[r.map(e=>({action:e.action,item:e.payload,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,size:e.size})),()=>r.forEach(e=>e.itemPromiseResolve())]}}class ab{get tracingMode(){return this._tracingMode}get _fetch(){let e,t=this.fetchImplementation||(e=this.debug,async(...t)=>{if(e||"true"===rw("DEBUG")){let[e,r]=t;console.log(`→ ${r?.method||"GET"} ${e}`)}let r=await (globalThis[tM]??((...e)=>fetch(...e)))(...t);return(e||"true"===rw("DEBUG"))&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r});return async(e,r)=>{let a,i=this.getProfileManagedAuthorizationHeader(r);return void 0!==this.apiKey?a={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(r,i)||(a=await this.profileAuth?.getAuthHeader(t,r?.signal)),t(e,this.applyCurrentAuthHeaders(r,a,i))}}getProfileManagedAuthorizationHeader(e){if(!e?.headers||!this.profileAuth)return;let t=new Headers(e.headers).get("Authorization");if(r6(t))return this.profileAuth.isProfileAuthorizationHeader(t??"")?t??void 0:void 0}isProfileManagedAuthorizationHeader(e,t){return e===t||this.profileAuth?.isProfileAuthorizationHeader(e)===!0}hasExplicitAuthHeader(e,t){if(!e?.headers)return!1;let r=new Headers(e.headers);if(r6(r.get("x-api-key")))return!0;let a=r.get("Authorization");return!!r6(a)&&!this.isProfileManagedAuthorizationHeader(a??"",t)}applyCurrentAuthHeaders(e,t,r){if(!t)return e;let a=e=>{if(void 0!==this.apiKey&&"x-api-key"===t.name)return e.delete("Authorization"),e.has("x-api-key")||e.set("x-api-key",t.value),e;if("Authorization"===t.name){if(r6(e.get("x-api-key")))return e;let a=e.get("Authorization");return r6(a)&&!this.isProfileManagedAuthorizationHeader(a??"",r)||e.set("Authorization",t.value),e}let a=e.get("Authorization");return r6(a)&&!this.isProfileManagedAuthorizationHeader(a??"",r)||(r6(a)&&e.delete("Authorization"),e.has("x-api-key")||e.set("x-api-key",t.value)),e};if(!e)return{headers:{[t.name]:t.value}};if(e.headers instanceof Headers||Array.isArray(e.headers))return{...e,headers:a(new Headers(e.headers))};let i={...e.headers??{}},n=e=>Object.keys(i).find(t=>t.toLowerCase()===e),s=e=>{let t=n(e);return t?i[t]:void 0},o=r6(s("x-api-key")),l=s("authorization"),u=r6(l)&&!this.isProfileManagedAuthorizationHeader(l??"",r);if(void 0!==this.apiKey&&"x-api-key"===t.name){let r=n("authorization");return r&&delete i[r],o||(i["x-api-key"]=t.value),{...e,headers:i}}if("Authorization"===t.name){if(!o&&!u){let e=n("authorization");e&&"Authorization"!==e&&delete i[e],i.Authorization=t.value}return{...e,headers:i}}if(!u){let e=n("authorization");e&&delete i[e],o||(i["x-api-key"]=t.value)}return{...e,headers:i}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,t){if(this.manualFlushMode||!function(e,t=65536,r=2048){if(null===e||"object"!=typeof e)return"string"==typeof e&&e.length>=t;let a=[e],i=new Set,n=0;for(;a.length>0&&!(n++>=r);){let e=a.pop();if(null==e)continue;let r=typeof e;if("string"===r){if(e.length>=t)return!0;continue}if("object"!==r||i.has(e)||(i.add(e),e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof ArrayBuffer||ArrayBuffer.isView(e)))continue;if(Array.isArray(e)){for(let t=e.length-1;t>=0;t--)a.push(e[t]);continue}if(e instanceof Map){for(let[,t]of e)a.push(t);continue}if(e instanceof Set){for(let t of e)a.push(t);continue}let n=Object.keys(e);for(let t=n.length-1;t>=0;t--)a.push(e[n[t]])}return!1}(e)||(void 0===this._serializeWorker&&(this._serializeWorker=(null===ad&&(ad=new au),ad)),null===this._serializeWorker))return ao(e,t);try{let r=await this._serializeWorker.serialize(e);if(null===r)return this._serializeWorker=null,ao(e,t);return r}catch{return ao(e,t)}}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideMetadata",{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:"false"===rv("LANGSMITH_TRACING_BACKGROUND")}),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,"_serializeWorker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingDrains",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tracingMode",{enumerable:!0,configurable:!0,writable:!0,value:"langsmith"}),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,"profileAuth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:"true"===rw("DISABLE_MULTIPART_STREAMING")}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:"true"===rw("DISABLE_RUN_COMPRESSION")}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:0x6400000}),Object.defineProperty(this,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:"true"===rv("LANGSMITH_DEBUG")});const t=ab.getDefaultClientConfig();this.tracingSampleRate=(e=>{let t=e?.toString()??rw("TRACING_SAMPLING_RATE");if(void 0===t)return;let r=parseFloat(t);if(r<0||r>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r})(e.tracingSamplingRate),this.apiUrl=am(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));const r=am(e.apiKey??t.apiKey);if(this.apiKey=r6(r)?r:void 0,this.profileAuth=void 0!==this.apiKey?void 0:t.profileAuth,this.webUrl=am(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=am(e.workspaceId??t.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new rq({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=rw("FAILED_TRACES_DIR")||void 0;const a=rw("FAILED_TRACES_MAX_MB");if(a){const e=parseInt(a,10);Number.isFinite(e)&&e>0&&(this.failedTracesMaxBytes=1024*e*1024)}const i=e.maxIngestMemoryBytes??0x40000000;this.batchIngestCaller=new rq({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:i,...e.callerOptions??{},onFailedResponseHook:ag,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.hideMetadata=e.hideMetadata??t.hideMetadata,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new a_(i),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=rS(e.tracingMode),"otel"===this._tracingMode&&(this.langSmithToOTELTranslator=new rN),this.cachedLSEnvVarsForMetadata=rb(),void 0!==e.cache&&e.disablePromptCache&&rV("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),void 0!==e.cache?(rV("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."),!1===e.cache?this._promptCache=void 0:!0===e.cache?this._promptCache=rm:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=rm),this._customHeaders=e.headers??{}}static getDefaultClientConfig(){let e=function(){let e=function(){let e;if("browser"!==(e=ry())&&"webworker"!==e)(function(){let e=rv("LANGSMITH_CONFIG_FILE");if(e)return;let t=rv("HOME")??rv("USERPROFILE");if(t)rd(t,".langsmith","config.json")})()}(),t=e?.profile;if(!e||!t)return{};let r=r5(t.api_key),a=r5(t.oauth?.access_token),i=r5(t.oauth?.refresh_token);return{apiUrl:t.api_url,apiKey:r,workspaceId:t.workspace_id,oauthAccessToken:a,oauthRefreshToken:i,profileAuth:r||a||i?new r7(e):void 0}}(),t=rw("API_KEY"),r=rw("ENDPOINT"),a=rw("WORKSPACE_ID"),i=r6(t),n=r??e.apiUrl??r9,s=a??e.workspaceId;return{apiUrl:n,apiKey:t,webUrl:void 0,hideInputs:"true"===rw("HIDE_INPUTS"),hideOutputs:"true"===rw("HIDE_OUTPUTS"),hideMetadata:"true"===rw("HIDE_METADATA"),workspaceId:s,oauthAccessToken:i?void 0:e.oauthAccessToken,oauthRefreshToken:i?void 0:e.oauthRefreshToken,profileAuth:i?void 0:e.profileAuth}}getHostUrl(){let e;if(this.webUrl)return this.webUrl;if("localhost"===(e=this.apiUrl.replace("http://","").replace("https://","").split("/")[0].split(":")[0])||"127.0.0.1"===e||"::1"===e)return this.webUrl="http://localhost:3000",this.webUrl;if(this.apiUrl.endsWith("/api/v1"))return this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl;if(this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api"))return this.webUrl=this.apiUrl.replace("/api",""),this.webUrl;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("aws"))return this.webUrl="https://aws.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("apac"))return this.webUrl="https://apac.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 _mergedHeaders(){let e={"User-Agent":`langsmith-js/${rg}`,...this._customHeaders};if(void 0!==this.apiKey)e["x-api-key"]=`${this.apiKey}`;else{let t=this.profileAuth?.currentAuthHeader();t&&(e[t.name]=t.value)}return this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get headers(){return this._customHeaders}set headers(e){this._customHeaders=e??{}}_getPlatformEndpointPath(e){return"/v1"!==this.apiUrl.slice(-3)&&"/v1/"!==this.apiUrl.slice(-4)?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}async processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}async processMetadata(e){return!1===this.hideMetadata?e:!0===this.hideMetadata?{}:"function"==typeof this.hideMetadata?this.hideMetadata(e):e}_filterNewTokenEvents(e){return e&&0!==e.length?e.map(e=>{if("new_token"===e.name){let{kwargs:t,...r}=e;return r}return e}):e}async prepareRunCreateOrUpdateInputs(e){let t={...e};return void 0!==t.inputs&&(t.inputs=await this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),null!=t.extra&&"metadata"in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),void 0!==t.events&&(t.events=this._filterNewTokenEvents(t.events)),t}async _getResponse(e,t){let r=t?.toString()??"",a=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{let t=await this._fetch(a,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(t,`fetch ${e}`),t})}async _get(e,t){return(await this._getResponse(e,t)).json()}async *_getPaginated(e,t=new URLSearchParams,r){let a=Number(t.get("offset"))||0,i=Number(t.get("limit"))||100;for(;;){t.set("offset",String(a)),t.set("limit",String(i));let n=`${this.apiUrl}${e}?${t}`,s=await this.caller.call(async()=>{let t=await this._fetch(n,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(t,`fetch ${e}`),t}),o=r?r(await s.json()):await s.json();if(0===o.length||(yield o,o.length<i))break;a+=o.length}}async *_getCursorPaginatedList(e,t=null,r="POST",a="runs"){let i=t?{...t}:{};for(;;){let t=JSON.stringify(i),n=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await r0(a,`fetch ${e}`),a}),s=await n.json();if(!s||!s[a])break;yield s[a];let o=s.cursors;if(!o||!o.next)break;i.cursor=o.next}}_shouldSample(){return void 0===this.tracingSampleRate||Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(void 0===this.tracingSampleRate)return e;if(t){let t=[];for(let r of e)this.filteredPostUuids.has(r.trace_id)?r.id===r.trace_id&&this.filteredPostUuids.delete(r.trace_id):t.push(r);return t}{let t=[];for(let r of e){let e=r.trace_id??r.id;this.filteredPostUuids.has(e)||(r.id===e?this._shouldSample()?t.push(r):this.filteredPostUuids.add(e):t.push(r))}return t}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??0x1800000}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??100}async _getDatasetExamplesMultiPartSupport(){let e=await this._ensureServerInfo();return e.instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){let r=[];for(;this.autoBatchQueue.items.length>0;){let[a,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!a.length){i();break}let n=a.reduce((e,t)=>{let r=t.apiUrl??this.apiUrl,a=t.apiKey??this.apiKey,i=t.apiKey===this.apiKey&&t.apiUrl===this.apiUrl?"default":`${r}|${a}`;return e[i]||(e[i]=[]),e[i].push(t),e},{}),s=[];for(let[e,t]of Object.entries(n)){let r=this._processBatch(t,{apiUrl:"default"===e?void 0:e.split("|")[0],apiKey:"default"===e?void 0:e.split("|")[1]});s.push(r)}let o=Promise.all(s).finally(i);r.push(o)}return Promise.all(r)}static async _writeTraceToFallbackDir(e,t,r,a,i){try{let n="string"==typeof t?e_.Buffer.from(t,"utf8"):e_.Buffer.from(t),s=JSON.stringify({version:1,endpoint:a,headers:r,body_base64:n.toString("base64")}),o=`trace_${Date.now()}_${tx().slice(0,8)}.json`,l=rd(e,o);if(ab._fallbackDirsCreated.has(e)||(await rc(e),ab._fallbackDirsCreated.add(e)),void 0!==i&&i>0)try{let t=(await rp(e)).filter(e=>e.startsWith("trace_")&&e.endsWith(".json")),r=0;for(let a of t){let{size:t}=await rf(rd(e,a));r+=t}if(r>=i)return void console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${r} bytes >= ${i} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`)}catch{}await rh(l,s),console.warn(`LangSmith trace upload failed; data saved to ${l} for later replay.`)}catch(t){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,t)}}async _processBatch(e,t){if(!e.length)return;let r=e.reduce((e,t)=>e+(t.size??0),0);try{if(void 0!==this.langSmithToOTELTranslator)this._sendBatchToOTELTranslator(e);else{let a={runCreates:e.filter(e=>"create"===e.action).map(e=>e.item),runUpdates:e.filter(e=>"update"===e.action).map(e=>e.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let e=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(a,{...t,useGzip:e,sizeBytes:r})}catch(e){if(rX(e))this._multipartDisabled=!0,await this.batchIngestRuns(a,{...t,sizeBytes:r});else throw e}}else await this.batchIngestRuns(a,{...t,sizeBytes:r})}}catch(e){console.error("Error exporting batch:",e)}}_sendBatchToOTELTranslator(e){if(void 0!==this.langSmithToOTELTranslator){let t=new Map,r=[];for(let a of e)a.item.id&&a.otelContext&&(t.set(a.item.id,a.otelContext),"create"===a.action?r.push({operation:"post",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}):r.push({operation:"patch",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}));this.langSmithToOTELTranslator.exportBatch(r,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=ap(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;let r=await this._getBatchSizeLimitBytes(),a=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>a)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:a})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:a}))},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){let e=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(1e4),...this.fetchOptions});return await r0(e,"get server info"),e}),t=await e.json();return this.debug&&console.log("\n=== LangSmith Server Configuration ===\n"+JSON.stringify(t,null,2)+"\n"),t}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){let e=r$(),t=rj.getContextInstance();if(void 0!==this.langSmithToOTELTranslator){let r=e.getActiveSpan();if(r)return e.setSpan(t.active(),r)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;let r={...this._mergedHeaders,"Content-Type":"application/json"},a=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:a,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==i.trace_id&&void 0!==i.dotted_order){let e=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:e,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}let n=ap(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),t?.workspaceId!==void 0&&(r["x-tenant-id"]=t.workspaceId);let s=ao(n,`Creating run with id: ${n.id}`);await this.caller.call(async()=>{let e=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await r0(e,"create run",!0),e})}async batchIngestRuns({runCreates:e,runUpdates:t},r){if(void 0===e&&void 0===t)return;let a=await Promise.all(e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]),i=await Promise.all(t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]);if(a.length>0&&i.length>0){let e=a.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of i)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);a=Object.values(e),i=t}let n={post:a,patch:i};if(!n.post.length&&!n.patch.length)return;let s={post:[],patch:[]};for(let e of["post","patch"]){let t=n[e].reverse(),r=t.pop();for(;void 0!==r;)s[e].push(r),r=t.pop()}if(s.post.length>0||s.patch.length>0){let e=s.post.map(e=>e.id).concat(s.patch.map(e=>e.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(s,`Ingesting runs with ids: ${e}`),r)}}async _postBatchIngestRuns(e,t){let r={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:t?.sizeBytes},async()=>{let a=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await r0(a,"batch create run",!0),a})}async multipartIngestRuns({runCreates:e,runUpdates:t},r){if(void 0===e&&void 0===t)return;let a={},i=[];for(let t of e??[]){let e=await this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(a[e.id]=e.attachments),delete e.attachments,i.push(e)}let n=[];for(let e of t??[])n.push(await this.prepareRunCreateOrUpdateInputs(e));if(void 0!==i.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==n.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&n.length>0){let e=i.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of n)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);i=Object.values(e),n=t}if(0===i.length&&0===n.length)return;let s=[],o=[];for(let[e,t]of[["post",i],["patch",n]])for(let r of t){let{inputs:t,outputs:i,events:n,extra:l,error:u,serialized:d,attachments:c,...h}=r,p={inputs:t,outputs:i,events:n,extra:l,error:u,serialized:d},f=await this._serializeBody(h,`Serializing for multipart ingestion of run with id: ${h.id}`);for(let[t,r]of(o.push({name:`${e}.${h.id}`,payload:new Blob([f],{type:`application/json; length=${f.length}`})}),Object.entries(p))){if(void 0===r)continue;let a=await this._serializeBody(r,`Serializing ${t} for multipart ingestion of run with id: ${h.id}`);o.push({name:`${e}.${h.id}.${t}`,payload:new Blob([a],{type:`application/json; length=${a.length}`})})}if(void 0!==h.id){let e=a[h.id];if(e)for(let[t,r]of(delete a[h.id],Object.entries(e))){let e,a;if(Array.isArray(r)?[e,a]=r:(e=r.mimeType,a=r.data),t.includes(".")){console.warn(`Skipping attachment '${t}' for run ${h.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}o.push({name:`attachment.${h.id}.${t}`,payload:new Blob([a],{type:`${e}; length=${a.byteLength}`})})}}s.push(`trace=${h.trace_id},id=${h.id}`)}await this._sendMultipartRequest(o,s.join("; "),r)}async _createNodeFetchBody(e,t){let r=[];for(let a of e)r.push(new Blob([`--${t}\r
|
|
18
18
|
`])),r.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
|
|
19
19
|
`,`Content-Type: ${a.payload.type}\r
|
|
20
20
|
\r
|
|
@@ -24,7 +24,7 @@ Context: ${t}`:""}`),void 0===i&&(i={depthLimit:Number.MAX_SAFE_INTEGER,edgesLim
|
|
|
24
24
|
`),await i(`Content-Type: ${r.payload.type}\r
|
|
25
25
|
\r
|
|
26
26
|
`);let e=r.payload.stream().getReader();try{let t;for(;!(t=await e.read()).done;)a.enqueue(t.value)}finally{e.releaseLock()}await i("\r\n")}await i(`--${t}--\r
|
|
27
|
-
`),a.close()}})}async _sendMultipartRequest(e,t,r){let a="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=()=>this._createNodeFetchBody(e,a),n=()=>this._createMultipartStream(e,a),s=async e=>this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let t=await e(),i={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${a}`};r?.apiKey!==void 0&&(i["x-api-key"]=r.apiKey);let n=t;r?.useGzip&&"object"==typeof t&&"pipeThrough"in t&&(n=t.pipeThrough(new CompressionStream("gzip")),i["Content-Encoding"]="gzip");let s=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:i,body:n,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(s,"Failed to send multipart request",!0),s});try{let e,a=!1;(void 0===globalThis[tM]||l)&&!this.multipartStreamingDisabled&&"bun"!==ry()?(a=!0,e=await s(n)):e=await s(i),(!this.multipartStreamingDisabled||a)&&422===e.status&&(r?.apiUrl??this.apiUrl)!==
|
|
27
|
+
`),a.close()}})}async _sendMultipartRequest(e,t,r){let a="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=()=>this._createNodeFetchBody(e,a),n=()=>this._createMultipartStream(e,a),s=async e=>this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let t=await e(),i={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${a}`};r?.apiKey!==void 0&&(i["x-api-key"]=r.apiKey);let n=t;r?.useGzip&&"object"==typeof t&&"pipeThrough"in t&&(n=t.pipeThrough(new CompressionStream("gzip")),i["Content-Encoding"]="gzip");let s=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:i,body:n,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(s,"Failed to send multipart request",!0),s});try{let e,a=!1;(void 0===globalThis[tM]||l)&&!this.multipartStreamingDisabled&&"bun"!==ry()?(a=!0,e=await s(n)):e=await s(i),(!this.multipartStreamingDisabled||a)&&422===e.status&&(r?.apiUrl??this.apiUrl)!==r9&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${t}".`),this.multipartStreamingDisabled=!0,e=await s(i))}catch(r){if(rX(r))throw r;if(console.warn(`${r.message.trim()}
|
|
28
28
|
|
|
29
29
|
Context: ${t}`),this.failedTracesDir){let t=await this._createNodeFetchBody(e,a).catch(()=>null);t&&await ab._writeTraceToFallbackDir(this.failedTracesDir,t,{"Content-Type":`multipart/form-data; boundary=${a}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,t,r){ro(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),null!=t.extra&&"metadata"in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),t.events&&(t.events=this._filterNewTokenEvents(t.events));let a={...t,id:e};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&void 0!==a.trace_id&&void 0!==a.dotted_order){let e=this._cloneCurrentOTELContext();return void 0!==t.end_time&&void 0===a.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:a,otelContext:e,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error):void this.processRunOperation({action:"update",item:a,otelContext:e,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error)}let i={...this._mergedHeaders,"Content-Type":"application/json"};r?.apiKey!==void 0&&(i["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(i["x-tenant-id"]=r.workspaceId);let n=ao(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let t=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await r0(t,"update run",!0),t})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){ro(e);let r=ah(await this._get(`/runs/${e}`));return t&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(void 0!==t){let e;e=t.session_id?t.session_id:r?.projectName?(await this.readProject({projectName:r?.projectName})).id:r?.projectId?r?.projectId:(await this.readProject({projectName:rw("PROJECT")||"default"})).id;let a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){let t=await this.readRun(e);if(!t.app_path)throw Error(`Run ${e} has no app_path`);let r=this.getHostUrl();return`${r}${t.app_path}`}throw Error("Must provide either runId or run")}async _loadChildRuns(e){let t=await af(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},a={};for(let i of(t.sort((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??"")),t)){if(null===i.parent_run_id||void 0===i.parent_run_id)throw Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in r||(r[i.parent_run_id]=[]),r[i.parent_run_id].push(i),a[i.id]=i)}for(let t in e.child_runs=r[e.id]||[],r)t!==e.id&&(a[t].child_runs=r[t]);return e}async *listRuns(e){let{projectId:t,projectName:r,parentRunId:a,traceId:i,referenceExampleId:n,startTime:s,executionOrder:o,isRoot:l,runType:u,error:d,id:c,query:h,filter:p,traceFilter:f,treeFilter:m,limit:g,select:y,order:_}=e,b=[];if(t&&(b=Array.isArray(t)?t:[t]),r){let e=Array.isArray(r)?r:[r],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));b.push(...t)}let v={session:b.length?b:null,run_type:u,reference_example:n,query:h,filter:p,trace_filter:f,tree_filter:m,execution_order:o,parent_run:a,start_time:s?s.toISOString():null,error:d,id:c,limit:g,trace:i,select:y||["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"],is_root:l,order:_};v.select.includes("child_run_ids")&&rV("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let w=0;for await(let e of this._getCursorPaginatedList("/runs/query",v)){let t=e.map(ah);if(g){if(w>=g)break;if(t.length+w>g){let e=t.slice(0,g-w);yield*e;break}w+=t.length,yield*t}else yield*t}}async *listGroupRuns(e){let{projectId:t,projectName:r,groupBy:a,filter:i,startTime:n,endTime:s,limit:o,offset:l}=e,u={session_id:t||(await this.readProject({projectName:r})).id,group_by:a,filter:i,start_time:n?n.toISOString():null,end_time:s?s.toISOString():null,limit:Number(o)||100},d=Number(l)||0,c="/runs/group",h=`${this.apiUrl}${c}`;for(;;){let e=JSON.stringify(Object.fromEntries(Object.entries({...u,offset:d}).filter(([e,t])=>void 0!==t))),t=await this.caller.call(async()=>{let t=await this._fetch(h,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await r0(t,`Failed to fetch ${c}`),t}),{groups:r,total:a}=await t.json();if(0===r.length)break;for(let e of r)yield e;if((d+=r.length)>=a)break}}async *readThread(e){let{threadId:t,projectId:r,projectName:a,isRoot:i=!0,limit:n,filter:s,order:o="asc"}=e;if(!r&&!a)throw Error("threadId requires projectId or projectName");let l=`eq(thread_id, ${JSON.stringify(t)})`,u=s?`and(${l}, ${s})`:l;yield*this.listRuns({projectId:r??void 0,projectName:a??void 0,isRoot:i,limit:n,filter:u,order:o})}async listThreads(e){let{projectId:t,projectName:r,limit:a,offset:i=0,filter:n,startTime:s,isRoot:o=!0}=e;if(!t&&!r)throw Error("Either projectId or projectName must be provided");if(t&&r)throw Error("Provide exactly one of projectId or projectName");let l={session:[t??(await this.readProject({projectName:r})).id],is_root:o,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:(s??new Date(Date.now()-864e5)).toISOString()};null!=n&&(l.filter=n);let u=new Map;for await(let e of this._getCursorPaginatedList("/runs/query",l))for(let t of e){let e=ah(t),r=e.thread_id;if(r){let t=u.get(r)??[];t.push(e),u.set(r,t)}}let d=[];for(let[e,t]of u.entries()){t.sort((e,t)=>{let r=e.start_time??"",a=t.start_time??"";if(r!==a)return r.localeCompare(a);let i=e.dotted_order??"",n=t.dotted_order??"";return i.localeCompare(n)});let r=[...t.map(e=>e.start_time).filter(Boolean)].sort(),a=r.length?r[0]:"",i=r.length?r[r.length-1]:"";d.push({thread_id:e,runs:t,count:t.length,filter:"",total_tokens:0,total_cost:null,min_start_time:a,max_start_time:i,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}d.sort((e,t)=>{let r=e.max_start_time??"";return(t.max_start_time??"").localeCompare(r)});let c=i>0?d.slice(i):d;return void 0!==a?c.slice(0,a):c}async getRunStats({id:e,trace:t,parentRun:r,runType:a,projectNames:i,projectIds:n,referenceExampleIds:s,startTime:o,endTime:l,error:u,query:d,filter:c,traceFilter:h,treeFilter:p,isRoot:f,dataSourceType:m}){let g=n||[];i&&(g=[...n||[],...await Promise.all(i.map(e=>this.readProject({projectName:e}).then(e=>e.id)))]);let y=JSON.stringify(Object.fromEntries(Object.entries({id:e,trace:t,parent_run:r,run_type:a,session:g,reference_example:s,start_time:o,end_time:l,error:u,query:d,filter:c,trace_filter:h,tree_filter:p,is_root:f,data_source_type:m}).filter(([e,t])=>void 0!==t))),_=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:y});return await r0(e,"get run stats"),e});return await _.json()}async shareRun(e,{shareId:t}={}){let r={run_id:e,share_token:t||tx()};ro(e);let a=JSON.stringify(r),i=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await r0(t,"share run"),t}),n=await i.json();if(null===n||!("share_token"in n))throw Error("Invalid response from server");return`${this.getHostUrl()}/public/${n.share_token}/r`}async unshareRun(e){ro(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(t,"unshare run",!0),t})}async readRunSharedLink(e){ro(e);let t=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(t,"read run shared link"),t}),r=await t.json();if(null!==r&&"share_token"in r)return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){let r=new URLSearchParams({share_token:e});if(void 0!==t)for(let e of t)r.append("id",e);ro(e);let a=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(t,"list shared runs"),t});return(await a.json()).map(ah)}async readDatasetSharedSchema(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),ro(e);let r=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(t,"read dataset shared schema"),t}),a=await r.json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);let r={dataset_id:e};ro(e);let a=JSON.stringify(r),i=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await r0(t,"share dataset"),t}),n=await i.json();return n.url=`${this.getHostUrl()}/public/${n.share_token}/d`,n}async unshareDataset(e){ro(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(t,"unshare dataset",!0),t})}async readSharedDataset(e){ro(e);let t=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(t,"read shared dataset"),t});return await t.json()}async listSharedExamples(e,t){let r={};t?.exampleIds&&(r.id=t.exampleIds);let a=new URLSearchParams;Object.entries(r).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>a.append(e,t)):a.append(e,t)});let i=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(t,"list shared examples"),t}),n=await i.json();if(!i.ok){if("detail"in n)throw Error(`Failed to list shared examples.
|
|
30
30
|
Status: ${i.status}
|
|
@@ -37,24 +37,24 @@ Message: ${Array.isArray(n.detail)?n.detail.join("\n"):"Unspecified error"}`);th
|
|
|
37
37
|
creating a LangChain Hub handle.
|
|
38
38
|
You can add a handle by creating a public prompt at:
|
|
39
39
|
|
|
40
|
-
https://smith.langchain.com/prompts`);let[a,i,n]=r4(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);let s=JSON.stringify({repo_handle:i,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic}),o=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await r0(e,"create prompt"),e}),{repo:l}=await o.json();return l}async createCommit(e,t,r){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[a,i,n]=r4(e),s=r?.parentCommitHash!=="latest"&&r?.parentCommitHash?r?.parentCommitHash:await this._getLatestCommitHash(`${a}/${i}`),o=JSON.stringify({manifest:JSON.parse(JSON.stringify(t)),parent_commit:s,...r?.description!==void 0&&{description:r.description}}),l=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${a}/${i}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await r0(e,"create commit"),e}),u=await l.json();return this._getPromptUrl(`${a}/${i}${u.commit_hash?`:${u.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){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 r=new FormData;for(let e of t){let t=e.id,a=new Blob([ao({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}},`Serializing body for example with id: ${t}`)],{type:"application/json"});if(r.append(t,a),e.inputs){let a=new Blob([ao(e.inputs,`Serializing inputs for example with id: ${t}`)],{type:"application/json"});r.append(`${t}.inputs`,a)}if(e.outputs){let a=new Blob([ao(e.outputs,`Serializing outputs whle updating example with id: ${t}`)],{type:"application/json"});r.append(`${t}.outputs`,a)}if(e.attachments)for(let[a,i]of Object.entries(e.attachments)){let e,n;Array.isArray(i)?[e,n]=i:(e=i.mimeType,n=i.data);let s=new Blob([n],{type:`${e}; length=${n.byteLength}`});r.append(`${t}.attachment.${a}`,s)}if(e.attachments_operations){let a=new Blob([ao(e.attachments_operations,`Serializing attachments while updating example with id: ${t}`)],{type:"application/json"});r.append(`${t}.attachments_operations`,a)}}let a=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await r0(e,"update examples"),e})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){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 r=new FormData;for(let e of t){let t=(e.id??tx()).toString(),a=new Blob([ao({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}},`Serializing body for uploaded example with id: ${t}`)],{type:"application/json"});if(r.append(t,a),e.inputs){let a=new Blob([ao(e.inputs,`Serializing inputs for uploaded example with id: ${t}`)],{type:"application/json"});r.append(`${t}.inputs`,a)}if(e.outputs){let a=new Blob([ao(e.outputs,`Serializing outputs for uploaded example with id: ${t}`)],{type:"application/json"});r.append(`${t}.outputs`,a)}if(e.attachments)for(let[a,i]of Object.entries(e.attachments)){let e,n;Array.isArray(i)?[e,n]=i:(e=i.mimeType,n=i.data);let s=new Blob([n],{type:`${e}; length=${n.byteLength}`});r.append(`${t}.attachment.${a}`,s)}}return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await r0(t,"upload examples"),t})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[r,a]=r4(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);let i={};if(t?.description!==void 0&&(i.description=t.description),t?.readme!==void 0&&(i.readme=t.readme),t?.tags!==void 0&&(i.tags=t.tags),t?.isPublic!==void 0&&(i.is_public=t.isPublic),t?.isArchived!==void 0&&(i.is_archived=t.isArchived),0===Object.keys(i).length)throw Error("No valid update options provided");let n=JSON.stringify(i);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${r}/${a}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await r0(e,"update prompt"),e})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[t,r,a]=r4(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(e,"delete prompt"),e})).json()}_getPromptCacheKey(e,t){return`${e}${t?":with_model":""}`}async _fetchPromptFromApi(e,t){let[r,a,i]=r4(e),n=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${r}/${a}/${i}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(e,"pull prompt commit"),e}),s=await n.json();return{owner:r,repo:a,commit_hash:s.commit_hash,manifest:s.manifest,examples:s.examples,hub_model_config:s.model_config,hub_model_provider:s.model_provider}}async pullPromptCommit(e,t){!function(e,t){let[r]=r4(e);if("-"!==r&&!t)throw Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}(e,t?.dangerouslyPullPublicPrompt);let r=this._fetchPromptFromApi.bind(this,e,t);if(!t?.skipCache&&this._promptCache){let a=this._getPromptCacheKey(e,t?.includeModel),i=this._promptCache.get(a,r);if(i)return i;let n=await r();return this._promptCache.set(a,n,r),n}return this._fetchPromptFromApi(e,t)}async _pullPrompt(e,t){return JSON.stringify((await this.pullPromptCommit(e,{includeModel:t?.includeModel,skipCache:t?.skipCache,dangerouslyPullPublicPrompt:t?.dangerouslyPullPublicPrompt})).manifest)}async pushPrompt(e,t){return(await this.promptExists(e)?t&&Object.keys(t).some(e=>"object"!==e)&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object)?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash,description:t?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[t,r]=r4(e);return this._repoExists(t,r)}async skillExists(e){let[t,r]=r4(e);return this._repoExists(t,r)}async pullAgent(e,t){return await this._pullDirectory(e,"agent",t?.version)}async pullSkill(e,t){return await this._pullDirectory(e,"skill",t?.version)}async pushAgent(e,t){return this._pushDirectory(e,"agent",t)}async pushSkill(e,t){return this._pushDirectory(e,"skill",t)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async *listAgents(e){yield*this._listReposByType("agent",e)}async *listSkills(e){yield*this._listReposByType("skill",e)}async *_listReposByType(e,t){let r=new URLSearchParams;for await(let a of(r.append("repo_type",e),r.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&r.append("is_public",t.isPublic.toString()),t?.query&&r.append("query",t.query),this._getPaginated("/repos",r,e=>e.repos)))yield*a}async _pullDirectory(e,t,r){let[a,i,n]=r4(e),s=r??("latest"!==n?n:void 0),o=new URL(`${this.apiUrl}/v1/platform/hub/repos/${a}/${i}/directories`);o.searchParams.set("repo_type",t),s&&o.searchParams.set("commit",s);let l=await this.caller.call(async()=>{let e=await this._fetch(o.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(e,"pull directory"),e});return await l.json()}async _pushDirectory(e,t,r){if(void 0!==r.parentCommit&&(r.parentCommit.length<8||r.parentCommit.length>64))throw Error("parent_commit must be 8-64 characters");let[a,i]=r4(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError(`push ${t}`,a);if(await this._repoExists(a,i))(void 0!==r.description||void 0!==r.readme||void 0!==r.tags||void 0!==r.isPublic)&&await this._updateRepoMetadata(a,i,r);else{let e=/^[a-z][a-z0-9-_]*$/;if(!e.test(i))throw Error(`Invalid repo_handle ${JSON.stringify(i)}: must match ${e}`);await this._createRepo(i,t,r)}let n={files:r.files};r.parentCommit&&(n.parent_commit=r.parentCommit);let s=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${a}/${i}/directories/commits`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(n)});return await r0(e,`push ${t}`),e}),o=(await s.json()).commit.commit_hash;return`${this.getHostUrl()}/context/${i}/${o.slice(0,8)}`}async _deleteDirectory(e){let[t,r]=r4(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete",t);await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${t}/${r}/directories`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(e,"delete directory"),e})}async _repoExists(e,t){try{return await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(r,"check repo exists"),r}),!0}catch(e){if(rX(e))return!1;throw e}}async _createRepo(e,t,r){let a={repo_handle:e,repo_type:t,is_public:!!r.isPublic};void 0!==r.description&&(a.description=r.description),void 0!==r.readme&&(a.readme=r.readme),void 0!==r.tags&&(a.tags=r.tags);try{await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await r0(e,`create ${t}`),e})}catch(e){if(null!=e&&"object"==typeof e&&"name"in e&&e?.name==="LangSmithConflictError")return;throw e}}async _updateRepoMetadata(e,t,r){let a={};void 0!==r.description&&(a.description=r.description),void 0!==r.readme&&(a.readme=r.readme),void 0!==r.tags&&(a.tags=r.tags),void 0!==r.isPublic&&(a.is_public=r.isPublic),0!==Object.keys(a).length&&await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await r0(r,"update repo metadata"),r})}async clonePublicDataset(e,t={}){let{sourceApiUrl:r=this.apiUrl,datasetName:a}=t,[i,n]=this.parseTokenOrUrl(e,r),s=new ab({apiUrl:i,apiKey:"placeholder"}),o=await s.readSharedDataset(n),l=a||o.name;try{if(await this.hasDataset({datasetId:l}))return void console.log(`Dataset ${l} already exists in your tenant. Skipping.`)}catch(e){}let u=await s.listSharedExamples(n),d=await this.createDataset(l,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(e=>e.inputs),outputs:u.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:d.id})}catch(e){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,r=2,a="dataset"){try{return ro(e),[t,e]}catch(e){}try{let i=new URL(e).pathname.split("/").filter(e=>""!==e);if(i.length>=r){let e=i[i.length-r];return[t,e]}throw Error(`Invalid public ${a} URL: ${e}`)}catch(t){throw Error(`Invalid public ${a} URL or token: ${e}`)}}cleanup(){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();for(await new Promise(e=>setTimeout(e,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),void 0!==this.langSmithToOTELTranslator&&await rj.getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return void 0!==this.webUrl&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),void 0!==this.workspaceId&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function av(e){return"dataset_id"in e||"dataset_name"in e}Object.defineProperty(ab,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});let aw=Symbol.for("lc:context_variables");Symbol.for("lc:child_run_end_promises");let ax=Symbol.for("langsmith:replica_trace_roots");function ak(e,t){if(aw in e)return e[aw][t]}function aS(e){return tT(Object.keys(e).sort().map(t=>`${t}:${e[t]??""}`).join("|"),"6ba7b810-9dad-11d1-80b4-00c04fd430c8")}function aE(e,t=1){let r=t.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${r}Z`}function aT(e,t,r=1){let a=aE(e,r);return{dottedOrder:a.replace(/[-:.]/g,"")+t,microsecondPrecisionDatestring:a}}let aA=new Set(["projectName","updates","reroot"]);class aI{constructor(e,t,r,a){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=r,this.replicas=a}static fromHeader(e){let t,r,a=e.split(","),i={},n=[];for(let e of a){let[a,s]=e.split("="),o=decodeURIComponent(s);"langsmith-metadata"===a?i=JSON.parse(o):"langsmith-tags"===a?n=o.split(","):"langsmith-project"===a?t=o:"langsmith-replicas"===a&&(r=JSON.parse(o).map(e=>Array.isArray(e)?e:function(e){let t={};for(let r of Object.keys(e))aA.has(r)&&(t[r]=e[r]);return t}(e)))}return new aI(i,n,t,r)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class aO{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),function(e){return null!=e&&"function"==typeof e.createChild&&"function"==typeof e.postRun}(e))return void Object.assign(this,{...e});const t=aO.getDefaultConfig(),{metadata:r,...a}=e,i=a.client??aO.getSharedClient(),n={...r,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:n},"id"in a&&null==a.id&&delete a.id,Object.assign(this,{...t,...a,client:i}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=aE(this.start_time,this.execution_order)),this.id||(this.id=function(e){return tO({msecs:"string"==typeof e?Date.parse(e):e,seq:0})}(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=function(e){return e?e.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):function(){let e=rv("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{let r=JSON.parse(e);if(Array.isArray(r)){let e=[];for(let t of r){if("object"!=typeof t||null===t){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof t}`);continue}if("string"!=typeof t.api_url){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof t.api_url}`);continue}if("string"!=typeof t.api_key){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof t.api_key}`);continue}e.push({apiUrl:t.api_url.replace(/\/$/,""),apiKey:t.api_key})}return e}if("object"!=typeof r||null===r)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 r}`),[];{var t=r;if(Object.keys(t).length>0&&rw("ENDPOINT"))throw new r2;let e=[];for(let[t,a]of Object.entries(r)){let r=t.replace(/\/$/,"");if("string"==typeof a)e.push({apiUrl:r,apiKey:a});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${t}: expected string, got ${typeof a}`);continue}}return e}}catch(e){if("object"==typeof e&&null!==e&&e.code===r1)throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}()}(this.replicas),!this.dotted_order){const{dottedOrder:e}=aT(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:tL(),child_runs:[],api_url:rv("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:rv("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return aO.sharedClient||(aO.sharedClient=new ab),aO.sharedClient}createChild(e){var t,r;let a,i=this.child_execution_order+1,n=this.replicas?.map(e=>{let{reroot:t,...r}=e;return r}),s=e.replicas??n,o=new aO({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:i,child_execution_order:i}),l=this.extra?.metadata??{},u=o.extra?.metadata??{};Object.keys(l).length>0&&(o.extra={...o.extra,metadata:{...l,...u}}),aw in this&&(o[aw]=this[aw]);let d=Symbol.for("lc:child_config"),c=e.extra?.[d]??this.extra[d];if(t=c,a=t?.callbacks,null!=t&&"object"==typeof a&&(aj(a?.handlers)||aj(a))){let e={...c},t="object"==typeof(r=e.callbacks)&&null!=r&&Array.isArray(r.handlers)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:o.id}),t.handlers?.find(aC)?.updateFromRunTree?.(o),e.callbacks=t),o.extra[d]=e}let h=new Set,p=this;for(;null!=p&&!h.has(p.id);)h.add(p.id),p.child_execution_order=Math.max(p.child_execution_order,i),p=p.parent_run;return this.child_runs.push(o),o}async end(e,t,r=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,t,r=!0){let a,i=e.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),t))for(let[e,r]of Object.entries(t))i.runtime[e]||(i.runtime[e]=r);let n=e.parent_run?.id??e.parent_run_id;return a=r?[]:e.child_runs.map(e=>this._convertToCreate(e,t,r)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:i,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:n,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,t){if(t.dotted_order){let r=t.dotted_order.split("."),a=null;for(let t=0;t<r.length;t++)if(r[t].slice(-36)===e){a=t;break}if(null!==a){let e=r.slice(a+1);t.dotted_order=e.join("."),e.length>0?t.trace_id=e[0].slice(-36):t.trace_id=t.id}}t.parent_run_id===e&&(t.parent_run_id=void 0)}_setReplicaTraceRoot(e,t){let r,a=ak(this,ax)??{};for(let i of(a[e]=t,(r=aw in this?this[aw]:{})[ax]=a,this[aw]=r,this.child_runs))i._setReplicaTraceRoot(e,t)}_remapForProject(e){let t,r,a,i,{projectName:n,runtimeEnv:s,excludeChildRuns:o=!0,reroot:l=!1,distributedParentId:u,apiUrl:d,apiKey:c,workspaceId:h}=e,p=this._convertToCreate(this,s,o);if(n===this.project_name)return{...p,session_name:n};if(l){if(u)this._sliceParentId(u,p);else if(p.parent_run_id=void 0,p.dotted_order){let e=p.dotted_order.split(".");e.length>0&&(p.dotted_order=e[e.length-1],p.trace_id=p.id)}let e=aS({projectName:n,apiUrl:d,apiKey:c,workspaceId:h});this._setReplicaTraceRoot(e,p.id)}if(!l&&(t=(ak(this,ax)??{})[aS({projectName:n,apiUrl:d,apiKey:c,workspaceId:h})])&&(p.trace_id=t,p.dotted_order)){let e=p.dotted_order.split("."),r=null;for(let a=0;a<e.length;a++)if(e[a].slice(-36)===t){r=a;break}null!==r&&(p.dotted_order=e.slice(r).join("."))}let f=ru(p.id,n);return r=p.trace_id?ru(p.trace_id,n):f,p.parent_run_id&&(a=ru(p.parent_run_id,n)),p.dotted_order&&(i=p.dotted_order.split(".").map(e=>{let t=ru(e.slice(-36),n);return e.slice(0,-36)+t}).join(".")),{...p,id:f,trace_id:r,parent_run_id:a,dotted_order:i,session_name:n}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let t=r_();if(this.replicas&&this.replicas.length>0)for(let{projectName:e,apiKey:r,apiUrl:a,workspaceId:i,reroot:n,client:s}of this.replicas){let o=this._remapForProject({projectName:e??this.project_name,runtimeEnv:t,excludeChildRuns:!0,reroot:n,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:r,workspaceId:i}),l=s??this.client;await l.createRun(o,{apiKey:r,apiUrl:a,workspaceId:i})}else{let r=this._convertToCreate(this,t,e);await this.client.createRun(r)}if(!e)for(let e of(rV("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."),this.child_runs))await e.postRun(!1);this.child_runs=[]}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:t,apiKey:r,apiUrl:a,workspaceId:i,updates:n,reroot:s,client:o}of this.replicas){let l=this._remapForProject({projectName:t??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:s,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:r,workspaceId:i}),u={id:l.id,name:l.name,run_type:l.run_type,start_time:l.start_time,outputs:l.outputs,error:l.error,parent_run_id:l.parent_run_id,session_name:l.session_name,reference_example_id:l.reference_example_id,end_time:l.end_time,dotted_order:l.dotted_order,trace_id:l.trace_id,events:l.events,tags:l.tags,extra:l.extra,attachments:this.attachments,...n};e?.excludeInputs||(u.inputs=l.inputs);let d=o??this.client;await d.updateRun(l.id,u,{apiKey:r,apiUrl:a,workspaceId:i})}else try{let t={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),"string"==typeof e?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,t){let r,a,i,n=e?.callbacks,s=!!["TRACING_V2","TRACING"].find(e=>"true"===rw(e));if(n){let e=n?.getParentRunId?.()??"",t=n?.handlers?.find(e=>e?.name=="langchain_tracer");r=t?.getRun?.(e),a=t?.projectName,i=t?.client,s=s||!!t}return r?new aO({name:r.name,id:r.id,trace_id:r.trace_id,dotted_order:r.dotted_order,client:i,tracingEnabled:s,project_name:a,tags:[...new Set((r?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...r?.extra?.metadata,...e?.metadata}}}).createChild(t):new aO({...t,client:i,tracingEnabled:s,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){let r="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=r["langsmith-trace"];if(!a||"string"!=typeof a)return;let i=a.trim(),n=i.split(".").map(e=>{let[t,r]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:r}}),s=n[0].uuid,o={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:n.at(-1)?.uuid,trace_id:s,dotted_order:i};if(r.baggage&&"string"==typeof r.baggage){let e=aI.fromHeader(r.baggage);o.metadata=e.metadata,o.tags=e.tags,o.project_name=e.project_name,o.replicas=e.replicas}let l=new aO(o);return l.distributedParentId=l.id,l}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new aI(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[r,a]of Object.entries(t))e.set(r,a);return t}}function aC(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function aj(e){return Array.isArray(e)&&e.some(e=>aC(e))}function aP(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function a$(e){return"function"==typeof e._addRunToRunMap}Object.defineProperty(aO,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});var aN=class extends tm{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(void 0!==e)return this.usesRunTreeMap?(e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e})(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
|
|
40
|
+
https://smith.langchain.com/prompts`);let[a,i,n]=r4(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);let s=JSON.stringify({repo_handle:i,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic}),o=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await r0(e,"create prompt"),e}),{repo:l}=await o.json();return l}async createCommit(e,t,r){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[a,i,n]=r4(e),s=r?.parentCommitHash!=="latest"&&r?.parentCommitHash?r?.parentCommitHash:await this._getLatestCommitHash(`${a}/${i}`),o=JSON.stringify({manifest:JSON.parse(JSON.stringify(t)),parent_commit:s,...r?.description!==void 0&&{description:r.description}}),l=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${a}/${i}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await r0(e,"create commit"),e}),u=await l.json();return this._getPromptUrl(`${a}/${i}${u.commit_hash?`:${u.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){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 r=new FormData;for(let e of t){let t=e.id,a=new Blob([ao({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}},`Serializing body for example with id: ${t}`)],{type:"application/json"});if(r.append(t,a),e.inputs){let a=new Blob([ao(e.inputs,`Serializing inputs for example with id: ${t}`)],{type:"application/json"});r.append(`${t}.inputs`,a)}if(e.outputs){let a=new Blob([ao(e.outputs,`Serializing outputs whle updating example with id: ${t}`)],{type:"application/json"});r.append(`${t}.outputs`,a)}if(e.attachments)for(let[a,i]of Object.entries(e.attachments)){let e,n;Array.isArray(i)?[e,n]=i:(e=i.mimeType,n=i.data);let s=new Blob([n],{type:`${e}; length=${n.byteLength}`});r.append(`${t}.attachment.${a}`,s)}if(e.attachments_operations){let a=new Blob([ao(e.attachments_operations,`Serializing attachments while updating example with id: ${t}`)],{type:"application/json"});r.append(`${t}.attachments_operations`,a)}}let a=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await r0(e,"update examples"),e})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){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 r=new FormData;for(let e of t){let t=(e.id??tx()).toString(),a=new Blob([ao({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}},`Serializing body for uploaded example with id: ${t}`)],{type:"application/json"});if(r.append(t,a),e.inputs){let a=new Blob([ao(e.inputs,`Serializing inputs for uploaded example with id: ${t}`)],{type:"application/json"});r.append(`${t}.inputs`,a)}if(e.outputs){let a=new Blob([ao(e.outputs,`Serializing outputs for uploaded example with id: ${t}`)],{type:"application/json"});r.append(`${t}.outputs`,a)}if(e.attachments)for(let[a,i]of Object.entries(e.attachments)){let e,n;Array.isArray(i)?[e,n]=i:(e=i.mimeType,n=i.data);let s=new Blob([n],{type:`${e}; length=${n.byteLength}`});r.append(`${t}.attachment.${a}`,s)}}return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await r0(t,"upload examples"),t})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[r,a]=r4(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);let i={};if(t?.description!==void 0&&(i.description=t.description),t?.readme!==void 0&&(i.readme=t.readme),t?.tags!==void 0&&(i.tags=t.tags),t?.isPublic!==void 0&&(i.is_public=t.isPublic),t?.isArchived!==void 0&&(i.is_archived=t.isArchived),0===Object.keys(i).length)throw Error("No valid update options provided");let n=JSON.stringify(i);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${r}/${a}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await r0(e,"update prompt"),e})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[t,r,a]=r4(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(e,"delete prompt"),e})).json()}_getPromptCacheKey(e,t){return`${e}${t?":with_model":""}`}async _fetchPromptFromApi(e,t){let[r,a,i]=r4(e),n=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${r}/${a}/${i}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(e,"pull prompt commit"),e}),s=await n.json();return{owner:r,repo:a,commit_hash:s.commit_hash,manifest:s.manifest,examples:s.examples,hub_model_config:s.model_config,hub_model_provider:s.model_provider}}async pullPromptCommit(e,t){!function(e,t){let[r]=r4(e);if("-"!==r&&!t)throw Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}(e,t?.dangerouslyPullPublicPrompt);let r=this._fetchPromptFromApi.bind(this,e,t);if(!t?.skipCache&&this._promptCache){let a=this._getPromptCacheKey(e,t?.includeModel),i=this._promptCache.get(a,r);if(i)return i;let n=await r();return this._promptCache.set(a,n,r),n}return this._fetchPromptFromApi(e,t)}async _pullPrompt(e,t){return JSON.stringify((await this.pullPromptCommit(e,{includeModel:t?.includeModel,skipCache:t?.skipCache,dangerouslyPullPublicPrompt:t?.dangerouslyPullPublicPrompt})).manifest)}async pushPrompt(e,t){return(await this.promptExists(e)?t&&Object.keys(t).some(e=>"object"!==e)&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object)?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash,description:t?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[t,r]=r4(e);return this._repoExists(t,r)}async skillExists(e){let[t,r]=r4(e);return this._repoExists(t,r)}async pullAgent(e,t){return await this._pullDirectory(e,"agent",t?.version)}async pullSkill(e,t){return await this._pullDirectory(e,"skill",t?.version)}async pushAgent(e,t){return this._pushDirectory(e,"agent",t)}async pushSkill(e,t){return this._pushDirectory(e,"skill",t)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async *listAgents(e){yield*this._listReposByType("agent",e)}async *listSkills(e){yield*this._listReposByType("skill",e)}async *_listReposByType(e,t){let r=new URLSearchParams;for await(let a of(r.append("repo_type",e),r.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&r.append("is_public",t.isPublic.toString()),t?.query&&r.append("query",t.query),this._getPaginated("/repos",r,e=>e.repos)))yield*a}async _pullDirectory(e,t,r){let[a,i,n]=r4(e),s=r??("latest"!==n?n:void 0),o=new URL(`${this.apiUrl}/v1/platform/hub/repos/${a}/${i}/directories`);o.searchParams.set("repo_type",t),s&&o.searchParams.set("commit",s);let l=await this.caller.call(async()=>{let e=await this._fetch(o.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(e,"pull directory"),e});return await l.json()}async _pushDirectory(e,t,r){if(void 0!==r.parentCommit&&(r.parentCommit.length<8||r.parentCommit.length>64))throw Error("parent_commit must be 8-64 characters");let[a,i]=r4(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError(`push ${t}`,a);if(await this._repoExists(a,i))(void 0!==r.description||void 0!==r.readme||void 0!==r.tags||void 0!==r.isPublic)&&await this._updateRepoMetadata(a,i,r);else{let e=/^[a-z][a-z0-9-_]*$/;if(!e.test(i))throw Error(`Invalid repo_handle ${JSON.stringify(i)}: must match ${e}`);await this._createRepo(i,t,r)}let n={files:r.files};r.parentCommit&&(n.parent_commit=r.parentCommit);let s=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${a}/${i}/directories/commits`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(n)});return await r0(e,`push ${t}`),e}),o=(await s.json()).commit.commit_hash;return`${this.getHostUrl()}/context/${i}/${o.slice(0,8)}`}async _deleteDirectory(e){let[t,r]=r4(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete",t);await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${t}/${r}/directories`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(e,"delete directory"),e})}async _repoExists(e,t){try{return await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r0(r,"check repo exists"),r}),!0}catch(e){if(rX(e))return!1;throw e}}async _createRepo(e,t,r){let a={repo_handle:e,repo_type:t,is_public:!!r.isPublic};void 0!==r.description&&(a.description=r.description),void 0!==r.readme&&(a.readme=r.readme),void 0!==r.tags&&(a.tags=r.tags);try{await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await r0(e,`create ${t}`),e})}catch(e){if(null!=e&&"object"==typeof e&&"name"in e&&e?.name==="LangSmithConflictError")return;throw e}}async _updateRepoMetadata(e,t,r){let a={};void 0!==r.description&&(a.description=r.description),void 0!==r.readme&&(a.readme=r.readme),void 0!==r.tags&&(a.tags=r.tags),void 0!==r.isPublic&&(a.is_public=r.isPublic),0!==Object.keys(a).length&&await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await r0(r,"update repo metadata"),r})}async clonePublicDataset(e,t={}){let{sourceApiUrl:r=this.apiUrl,datasetName:a}=t,[i,n]=this.parseTokenOrUrl(e,r),s=new ab({apiUrl:i,apiKey:"placeholder"}),o=await s.readSharedDataset(n),l=a||o.name;try{if(await this.hasDataset({datasetId:l}))return void console.log(`Dataset ${l} already exists in your tenant. Skipping.`)}catch(e){}let u=await s.listSharedExamples(n),d=await this.createDataset(l,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(e=>e.inputs),outputs:u.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:d.id})}catch(e){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,r=2,a="dataset"){try{return ro(e),[t,e]}catch(e){}try{let i=new URL(e).pathname.split("/").filter(e=>""!==e);if(i.length>=r){let e=i[i.length-r];return[t,e]}throw Error(`Invalid public ${a} URL: ${e}`)}catch(t){throw Error(`Invalid public ${a} URL or token: ${e}`)}}cleanup(){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();for(await new Promise(e=>setTimeout(e,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),void 0!==this.langSmithToOTELTranslator&&await rj.getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return void 0!==this.webUrl&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),void 0!==this.workspaceId&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function av(e){return"dataset_id"in e||"dataset_name"in e}Object.defineProperty(ab,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});let aw=Symbol.for("lc:context_variables");Symbol.for("lc:child_run_end_promises");let ax=Symbol.for("langsmith:replica_trace_roots");function ak(e,t){if(aw in e)return e[aw][t]}function aS(e){return tE(Object.keys(e).sort().map(t=>`${t}:${e[t]??""}`).join("|"),"6ba7b810-9dad-11d1-80b4-00c04fd430c8")}function aT(e,t=1){let r=t.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${r}Z`}function aE(e,t,r=1){let a=aT(e,r);return{dottedOrder:a.replace(/[-:.]/g,"")+t,microsecondPrecisionDatestring:a}}let aA=new Set(["projectName","updates","reroot"]);class aI{constructor(e,t,r,a){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=r,this.replicas=a}static fromHeader(e){let t,r,a=e.split(","),i={},n=[];for(let e of a){let[a,s]=e.split("="),o=decodeURIComponent(s);"langsmith-metadata"===a?i=JSON.parse(o):"langsmith-tags"===a?n=o.split(","):"langsmith-project"===a?t=o:"langsmith-replicas"===a&&(r=JSON.parse(o).map(e=>Array.isArray(e)?e:function(e){let t={};for(let r of Object.keys(e))aA.has(r)&&(t[r]=e[r]);return t}(e)))}return new aI(i,n,t,r)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class aO{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),function(e){return null!=e&&"function"==typeof e.createChild&&"function"==typeof e.postRun}(e))return void Object.assign(this,{...e});const t=aO.getDefaultConfig(),{metadata:r,...a}=e,i=a.client??aO.getSharedClient(),n={...r,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:n},"id"in a&&null==a.id&&delete a.id,Object.assign(this,{...t,...a,client:i}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=aT(this.start_time,this.execution_order)),this.id||(this.id=function(e){return tO({msecs:"string"==typeof e?Date.parse(e):e,seq:0})}(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=function(e){return e?e.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):function(){let e=rv("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{let r=JSON.parse(e);if(Array.isArray(r)){let e=[];for(let t of r){if("object"!=typeof t||null===t){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof t}`);continue}if("string"!=typeof t.api_url){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof t.api_url}`);continue}if("string"!=typeof t.api_key){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof t.api_key}`);continue}e.push({apiUrl:t.api_url.replace(/\/$/,""),apiKey:t.api_key})}return e}if("object"!=typeof r||null===r)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 r}`),[];{var t=r;if(Object.keys(t).length>0&&rw("ENDPOINT"))throw new r2;let e=[];for(let[t,a]of Object.entries(r)){let r=t.replace(/\/$/,"");if("string"==typeof a)e.push({apiUrl:r,apiKey:a});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${t}: expected string, got ${typeof a}`);continue}}return e}}catch(e){if("object"==typeof e&&null!==e&&e.code===r1)throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}()}(this.replicas),!this.dotted_order){const{dottedOrder:e}=aE(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:tz(),child_runs:[],api_url:rv("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:rv("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return aO.sharedClient||(aO.sharedClient=new ab),aO.sharedClient}createChild(e){var t,r;let a,i=this.child_execution_order+1,n=this.replicas?.map(e=>{let{reroot:t,...r}=e;return r}),s=e.replicas??n,o=new aO({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:i,child_execution_order:i}),l=this.extra?.metadata??{},u=o.extra?.metadata??{};Object.keys(l).length>0&&(o.extra={...o.extra,metadata:{...l,...u}}),aw in this&&(o[aw]=this[aw]);let d=Symbol.for("lc:child_config"),c=e.extra?.[d]??this.extra[d];if(t=c,a=t?.callbacks,null!=t&&"object"==typeof a&&(aj(a?.handlers)||aj(a))){let e={...c},t="object"==typeof(r=e.callbacks)&&null!=r&&Array.isArray(r.handlers)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:o.id}),t.handlers?.find(aC)?.updateFromRunTree?.(o),e.callbacks=t),o.extra[d]=e}let h=new Set,p=this;for(;null!=p&&!h.has(p.id);)h.add(p.id),p.child_execution_order=Math.max(p.child_execution_order,i),p=p.parent_run;return this.child_runs.push(o),o}async end(e,t,r=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,t,r=!0){let a,i=e.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),t))for(let[e,r]of Object.entries(t))i.runtime[e]||(i.runtime[e]=r);let n=e.parent_run?.id??e.parent_run_id;return a=r?[]:e.child_runs.map(e=>this._convertToCreate(e,t,r)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:i,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:n,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,t){if(t.dotted_order){let r=t.dotted_order.split("."),a=null;for(let t=0;t<r.length;t++)if(r[t].slice(-36)===e){a=t;break}if(null!==a){let e=r.slice(a+1);t.dotted_order=e.join("."),e.length>0?t.trace_id=e[0].slice(-36):t.trace_id=t.id}}t.parent_run_id===e&&(t.parent_run_id=void 0)}_setReplicaTraceRoot(e,t){let r,a=ak(this,ax)??{};for(let i of(a[e]=t,(r=aw in this?this[aw]:{})[ax]=a,this[aw]=r,this.child_runs))i._setReplicaTraceRoot(e,t)}_remapForProject(e){let t,r,a,i,{projectName:n,runtimeEnv:s,excludeChildRuns:o=!0,reroot:l=!1,distributedParentId:u,apiUrl:d,apiKey:c,workspaceId:h}=e,p=this._convertToCreate(this,s,o);if(n===this.project_name)return{...p,session_name:n};if(l){if(u)this._sliceParentId(u,p);else if(p.parent_run_id=void 0,p.dotted_order){let e=p.dotted_order.split(".");e.length>0&&(p.dotted_order=e[e.length-1],p.trace_id=p.id)}let e=aS({projectName:n,apiUrl:d,apiKey:c,workspaceId:h});this._setReplicaTraceRoot(e,p.id)}if(!l&&(t=(ak(this,ax)??{})[aS({projectName:n,apiUrl:d,apiKey:c,workspaceId:h})])&&(p.trace_id=t,p.dotted_order)){let e=p.dotted_order.split("."),r=null;for(let a=0;a<e.length;a++)if(e[a].slice(-36)===t){r=a;break}null!==r&&(p.dotted_order=e.slice(r).join("."))}let f=ru(p.id,n);return r=p.trace_id?ru(p.trace_id,n):f,p.parent_run_id&&(a=ru(p.parent_run_id,n)),p.dotted_order&&(i=p.dotted_order.split(".").map(e=>{let t=ru(e.slice(-36),n);return e.slice(0,-36)+t}).join(".")),{...p,id:f,trace_id:r,parent_run_id:a,dotted_order:i,session_name:n}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let t=r_();if(this.replicas&&this.replicas.length>0)for(let{projectName:e,apiKey:r,apiUrl:a,workspaceId:i,reroot:n,client:s}of this.replicas){let o=this._remapForProject({projectName:e??this.project_name,runtimeEnv:t,excludeChildRuns:!0,reroot:n,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:r,workspaceId:i}),l=s??this.client;await l.createRun(o,{apiKey:r,apiUrl:a,workspaceId:i})}else{let r=this._convertToCreate(this,t,e);await this.client.createRun(r)}if(!e)for(let e of(rV("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."),this.child_runs))await e.postRun(!1);this.child_runs=[]}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:t,apiKey:r,apiUrl:a,workspaceId:i,updates:n,reroot:s,client:o}of this.replicas){let l=this._remapForProject({projectName:t??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:s,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:r,workspaceId:i}),u={id:l.id,name:l.name,run_type:l.run_type,start_time:l.start_time,outputs:l.outputs,error:l.error,parent_run_id:l.parent_run_id,session_name:l.session_name,reference_example_id:l.reference_example_id,end_time:l.end_time,dotted_order:l.dotted_order,trace_id:l.trace_id,events:l.events,tags:l.tags,extra:l.extra,attachments:this.attachments,...n};e?.excludeInputs||(u.inputs=l.inputs);let d=o??this.client;await d.updateRun(l.id,u,{apiKey:r,apiUrl:a,workspaceId:i})}else try{let t={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),"string"==typeof e?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,t){let r,a,i,n=e?.callbacks,s=!!["TRACING_V2","TRACING"].find(e=>"true"===rw(e));if(n){let e=n?.getParentRunId?.()??"",t=n?.handlers?.find(e=>e?.name=="langchain_tracer");r=t?.getRun?.(e),a=t?.projectName,i=t?.client,s=s||!!t}return r?new aO({name:r.name,id:r.id,trace_id:r.trace_id,dotted_order:r.dotted_order,client:i,tracingEnabled:s,project_name:a,tags:[...new Set((r?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...r?.extra?.metadata,...e?.metadata}}}).createChild(t):new aO({...t,client:i,tracingEnabled:s,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){let r="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=r["langsmith-trace"];if(!a||"string"!=typeof a)return;let i=a.trim(),n=i.split(".").map(e=>{let[t,r]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:r}}),s=n[0].uuid,o={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:n.at(-1)?.uuid,trace_id:s,dotted_order:i};if(r.baggage&&"string"==typeof r.baggage){let e=aI.fromHeader(r.baggage);o.metadata=e.metadata,o.tags=e.tags,o.project_name=e.project_name,o.replicas=e.replicas}let l=new aO(o);return l.distributedParentId=l.id,l}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new aI(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[r,a]of Object.entries(t))e.set(r,a);return t}}function aC(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function aj(e){return Array.isArray(e)&&e.some(e=>aC(e))}function a$(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function aP(e){return"function"==typeof e._addRunToRunMap}Object.defineProperty(aO,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});var aN=class extends tm{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(void 0!==e)return this.usesRunTreeMap?(e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e})(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
|
|
41
41
|
|
|
42
|
-
${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:r,microsecondPrecisionDatestring:a}=aT(new Date(e.start_time).getTime(),e.id,e.execution_order),i={...e},n=this.getRunById(i.parent_run_id);if(void 0!==i.parent_run_id?n?(this._addChildRun(n,i),n.child_execution_order=Math.max(n.child_execution_order,i.child_execution_order),i.trace_id=n.trace_id,void 0!==n.dotted_order&&(i.dotted_order=[n.dotted_order,r].join("."),i._serialized_start_time=a)):i.parent_run_id=void 0:(i.trace_id=i.id,i.dotted_order=r,i._serialized_start_time=a),this.usesRunTreeMap){let e=function e(r,a){if(r)return new aO({...r,start_time:r._serialized_start_time??r.start_time,parent_run:e(a),child_runs:r.child_runs.map(t=>e(t)).filter(e=>void 0!==e),extra:{...r.extra,runtime:(void 0===t&&(t={library:"langchain-js",runtime:"u">typeof window&&void 0!==window.document?"browser":void 0===th.default||void 0===th.default.versions||void 0===th.default.versions.node||"u">typeof Deno?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"u">typeof window&&"nodejs"===window.name||"u">typeof navigator&&navigator.userAgent.includes("jsdom")?"jsdom":"u">typeof Deno?"deno":"other":"node"}),t)},tracingEnabled:!1})}(i,n);void 0!==e&&this.runTreeMap.set(i.id,e)}else this.runMap.set(i.id,i);return i}async _endTrace(e){let t=void 0!==e.parent_run_id&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let t=void 0!==e&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,a,i,n,s,o){let l=this._getExecutionOrder(a),u=Date.now(),d=s?{...i,metadata:s}:i,c={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:n||[]};return this._addRunToRunMap(c)}async handleLLMStart(e,t,r,a,i,n,s,o){let l=this.getRunById(r)??this._createRunForLLMStart(e,t,r,a,i,n,s,o);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(e,t,r,a,i,n,s,o){let l=this._getExecutionOrder(a),u=Date.now(),d=s?{...i,metadata:s}:i,c={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:n||[]};return this._addRunToRunMap(c)}async handleChatModelStart(e,t,r,a,i,n,s,o){let l=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,a,i,n,s,o);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(e,t,r,a,i){let n=this.getRunById(t);if(!n||n?.run_type!=="llm")throw Error("No LLM run to end.");return n.end_time=Date.now(),n.outputs=e,n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),n.extra={...n.extra,...i},await this.onLLMEnd?.(n),await this._endTrace(n),n}async handleLLMError(e,t,r,a,i){let n=this.getRunById(t);if(!n||n?.run_type!=="llm")throw Error("No LLM run to end.");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),n.extra={...n.extra,...i},await this.onLLMError?.(n),await this._endTrace(n),n}_createRunForChainStart(e,t,r,a,i,n,s,o,l){let u=this._getExecutionOrder(a),d=Date.now(),c={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:t,execution_order:u,child_execution_order:u,run_type:s??"chain",child_runs:[],extra:n?{...l,metadata:n}:{...l},tags:i||[]};return this._addRunToRunMap(c)}async handleChainStart(e,t,r,a,i,n,s,o){let l=this.getRunById(r)??this._createRunForChainStart(e,t,r,a,i,n,s,o);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(e,t,r,a,i){let n=this.getRunById(t);if(!n)throw Error("No chain run to end.");return n.end_time=Date.now(),n.outputs=aP(e,"output"),n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),i?.inputs!==void 0&&(n.inputs=aP(i.inputs,"input")),await this.onChainEnd?.(n),await this._endTrace(n),n}async handleChainError(e,t,r,a,i){let n=this.getRunById(t);if(!n)throw Error("No chain run to end.");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),i?.inputs!==void 0&&(n.inputs=aP(i.inputs,"input")),await this.onChainError?.(n),await this._endTrace(n),n}_createRunForToolStart(e,t,r,a,i,n,s){let o=this._getExecutionOrder(a),l=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:n?{metadata:n}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(e,t,r,a,i,n,s){let o=this.getRunById(r)??this._createRunForToolStart(e,t,r,a,i,n,s);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){let r=this.getRunById(t);r&&r?.run_type==="chain"&&(r.actions=r.actions||[],r.actions.push(e),r.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r))}async handleAgentEnd(e,t){let r=this.getRunById(t);r&&r?.run_type==="chain"&&(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,a,i,n,s){let o=this._getExecutionOrder(a),l=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:n?{metadata:n}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,t,r,a,i,n,s){let o=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,a,i,n,s);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){let r=this.getRunById(t);r&&r?.run_type==="chain"&&(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,a,i,n){let s=this.getRunById(r);if(!s||s?.run_type!=="llm")throw Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:n?.chunk}}),await this.onLLMNewToken?.(s,e,{chunk:n?.chunk}),s}};let aR={bold:{open:"\x1b[1m",close:"\x1b[22m"},color:{grey:{open:"\x1b[90m",close:"\x1b[39m"},green:{open:"\x1b[32m",close:"\x1b[39m"},cyan:{open:"\x1b[36m",close:"\x1b[39m"},red:{open:"\x1b[31m",close:"\x1b[39m"},blue:{open:"\x1b[34m",close:"\x1b[39m"}}};function aM(e,t){return`${e.open}${t}${e.close}`}function aL(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function az(e){return"string"==typeof e?e.trim():null==e?e:aL(e,e.toString())}function aU(e){if(!e.end_time)return"";let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}let{color:aB}=aR;var aD=class extends aN{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){let t=[],r=e;for(;r.parent_run_id;){let e=this.runMap.get(r.parent_run_id);if(e)t.push(e),r=e;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((e,t,r)=>{let a=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?aM(aR.bold,a):a}).join(" > ");return aM(aB.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.green,"[chain/start]")} [${t}] Entering Chain run with input: ${aL(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.cyan,"[chain/end]")} [${t}] [${aU(e)}] Exiting Chain run with output: ${aL(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.red,"[chain/error]")} [${t}] [${aU(e)}] Chain run errored with error: ${aL(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${aM(aB.green,"[llm/start]")} [${t}] Entering LLM run with input: ${aL(r,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.cyan,"[llm/end]")} [${t}] [${aU(e)}] Exiting LLM run with output: ${aL(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.red,"[llm/error]")} [${t}] [${aU(e)}] LLM run errored with error: ${aL(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.green,"[tool/start]")} [${t}] Entering Tool run with input: "${az(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.cyan,"[tool/end]")} [${t}] [${aU(e)}] Exiting Tool run with output: "${az(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.red,"[tool/error]")} [${t}] [${aU(e)}] Tool run errored with error: ${aL(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${aL(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.cyan,"[retriever/end]")} [${t}] [${aU(e)}] Exiting Retriever run with output: ${aL(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.red,"[retriever/error]")} [${t}] [${aU(e)}] Retriever run errored with error: ${aL(e.error,"[error]")}`)}onAgentAction(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aB.blue,"[agent/action]")} [${t}] Agent selected action: ${aL(e.actions[e.actions.length-1],"[action]")}`)}};let aF=Symbol.for("ls:tracing_async_local_storage"),aZ=new class{getStore(){}run(e,t){return t()}},aH=new class{getInstance(){return globalThis[aF]??aZ}initializeGlobalInstance(e){void 0===globalThis[aF]&&(globalThis[aF]=e)}};function aq(e){return"function"==typeof e&&"langsmith:traceable"in e}Symbol.for("langsmith:traceable:root");let aJ=new Set(["ls_agent_type"]);var aG=class e extends aN{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(t={}){super(t),this.fields=t;const{exampleId:r,projectName:a,client:i,replicas:s,metadata:o,tags:l}=t;this.projectName=a??tL(),this.replicas=s,this.exampleId=r,this.client=i??(void 0===n&&(n=new ab("false"===tp("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{})),n),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=l??[];const u=e.getTraceableRunTree();u&&this.updateFromRunTree(u)}async persistRun(e){}async onRunCreate(e){aW(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){aW(this,e);let t=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await t?.postRun():await t?.patchRun()}onLLMEnd(e){let t=e.outputs;if(t?.generations){let r=function(e){let t;for(let r of e)for(let e of r)e1.isInstance(e.message)&&void 0!==e.message.usage_metadata&&(t=ef(t,e.message.usage_metadata));return t}(t.generations);if(void 0!==r){e.extra=e.extra??{};let t=e.extra.metadata??{};t.usage_metadata=r,e.extra.metadata=t}}}copyWithTracingConfig({metadata:t,tags:r}){let a;if(void 0===t)a=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(void 0===this.tracingMetadata)a={...t};else for(let[e,r]of(a={...this.tracingMetadata},Object.entries(t)))(!Object.prototype.hasOwnProperty.call(a,e)||aJ.has(e))&&(a[e]=r);let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],n=new e({...this.fields,metadata:a,tags:i});return n.runMap=this.runMap,n.runTreeMap=this.runTreeMap,n}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e,r=new Set;for(;t.parent_run&&!r.has(t.id)&&(r.add(t.id),t.parent_run);){;t=t.parent_run}r.clear();let a=[t];for(;a.length>0;){let e=a.shift();!(!e||r.has(e.id))&&(r.add(e.id),this.runTreeMap.set(e.id,e),e.child_runs&&a.push(...e.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let t=this.runTreeMap.get(e);if(t)return new aO({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return function(e=!1){let t=aH.getInstance().getStore();if(!e&&void 0===t)throw Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.");return t}(!0)}catch{return}}static[Symbol.hasInstance](e){return"object"==typeof e&&null!==e&&"name"in e&&"langchain_tracer"===e.name&&"copyWithTracingConfig"in e&&"function"==typeof e.copyWithTracingConfig&&"getRunTreeWithTracingConfig"in e&&"function"==typeof e.getRunTreeWithTracingConfig}};function aW(e,t){if(e.tracingMetadata){t.extra??={};let r=t.extra.metadata??{},a=!1;for(let[t,i]of Object.entries(e.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,t)||aJ.has(t))&&r[t]!==i&&(r[t]=i,a=!0);a&&(t.extra.metadata=r)}e.tracingTags.length>0&&(t.tags=Array.from(new Set([...t.tags??[],...e.tracingTags])))}async function aV(e,t){if(!0===t){let t=tc();void 0!==t?await t.run(void 0,async()=>e()):await e()}else void 0===s&&(s=new("default"in rF.default?rF.default.default:rF.default)({autoStart:!0,concurrency:1})),s.add(async()=>{let t=tc();void 0!==t?await t.run(void 0,async()=>e()):await e()})}function aK(e){let t=tc();if(void 0!==t)return t.getStore()?.[td]?.[e]}let aQ=Symbol("lc:configure_hooks");var aY=class{setHandler(e){return this.setHandlers([e])}},aX=class{constructor(e,t,r,a,i,n,s,o){this.runId=e,this.handlers=t,this.inheritableHandlers=r,this.tags=a,this.inheritableTags=i,this.metadata=n,this.inheritableMetadata=s,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>aV(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,a,i){await Promise.all(this.handlers.map(r=>aV(async()=>{try{await r.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}},a0=class extends aX{getChild(e){let t=new a6(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}},a1=class extends aX{async handleLLMNewToken(e,t,r,a,i,n){await Promise.all(this.handlers.map(r=>aV(async()=>{if(!r.ignoreLLM)try{await r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,n)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMNewToken: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}async handleChatModelStreamEvent(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreLLM)try{await t.handleChatModelStreamEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChatModelStreamEvent: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMError(e,t,r,a,i){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreLLM)try{await t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMEnd(e,t,r,a,i){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreLLM)try{await t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},a2=class extends aX{getChild(e){let t=new a6(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,a,i){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreChain)try{await t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleChainEnd(e,t,r,a,i){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreChain)try{await t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},a4=class extends aX{getChild(e){let t=new a6(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEvent(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreAgent)try{await t.handleToolEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if(t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},a6=class e extends aY{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,t){super(),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r,a,i,n,s,o){return Promise.all(t.map(async(t,a)=>{let n=0===a&&r?r:tl();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return a$(r)&&r._createRunForLLMStart(e,[t],n,this._parentRunId,i,this.tags,this.metadata,o),aV(async()=>{try{await r.handleLLMStart?.(e,[t],n,this._parentRunId,i,this.tags,this.metadata,o)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new a1(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r,a,i,n,s,o){return Promise.all(t.map(async(t,a)=>{let n=0===a&&r?r:tl();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return a$(r)&&r._createRunForChatModelStart(e,[t],n,this._parentRunId,i,this.tags,this.metadata,o),aV(async()=>{try{if(r.handleChatModelStart)await r.handleChatModelStart?.(e,[t],n,this._parentRunId,i,this.tags,this.metadata,o);else if(r.handleLLMStart){let a=eV(t);await r.handleLLMStart?.(e,[a],n,this._parentRunId,i,this.tags,this.metadata,o)}}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new a1(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=tl(),a,i,n,s,o,l){return await Promise.all(this.handlers.map(i=>{if(!i.ignoreChain)return a$(i)&&i._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,a,s,l),aV(async()=>{try{await i.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,a,s,l)}catch(e){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainStart: ${e}`),i.raiseError)throw e}},i.awaitHandlers)})),new a2(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=tl(),a,i,n,s,o){return await Promise.all(this.handlers.map(a=>{if(!a.ignoreAgent)return a$(a)&&a._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),aV(async()=>{try{await a.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s,o)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleToolStart: ${e}`),a.raiseError)throw e}},a.awaitHandlers)})),new a4(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=tl(),a,i,n,s){return await Promise.all(this.handlers.map(a=>{if(!a.ignoreRetriever)return a$(a)&&a._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),aV(async()=>{try{await a.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleRetrieverStart: ${e}`),a.raiseError)throw e}},a.awaitHandlers)})),new a0(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,a,i){await Promise.all(this.handlers.map(a=>aV(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(e,t,r,this.tags,this.metadata)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${e}`),a.raiseError)throw e}},a.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){for(let r of(this.handlers=[],this.inheritableHandlers=[],e))this.addHandler(r,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(t=[],r=!0){let a=new e(this._parentRunId);for(let e of this.handlers){let t=this.inheritableHandlers.includes(e);a.addHandler(e,t)}for(let e of this.tags){let t=this.inheritableTags.includes(e);a.addTags([e],t)}for(let e of Object.keys(this.metadata)){let t=Object.keys(this.inheritableMetadata).includes(e);a.addMetadata({[e]:this.metadata[e]},t)}for(let e of t)a.handlers.filter(e=>"console_callback_handler"===e.name).some(t=>t.name===e.name)||a.addHandler(e,r);return a}static fromHandlers(e){class t extends tm{name=tl();constructor(){super(),Object.assign(this,e)}}let r=new this;return r.addHandler(new t),r}static configure(e,t,r,a,i,n,s){return this._configureSync(e,t,r,a,i,n,s)}static _configureSync(t,r,a,i,n,s,o){let l;(t||r)&&(Array.isArray(t)||!t?(l=new e).setHandlers(t?.map(a5)??[],!0):l=t,l=l.copy(Array.isArray(r)?r.map(a5):r?.handlers,!1));let u="true"===tp("LANGCHAIN_VERBOSE")||o?.verbose,d=aG.getTraceableRunTree(),c=d?.tracingEnabled??!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>"true"===tp(e));if(d?.tracingEnabled===!1&&l)for(let e of l.handlers.filter(e=>"langchain_tracer"===e.name))l.removeHandler(e);let h=c||(tp("LANGCHAIN_TRACING")??!1);if(u||h){if(l||(l=new e),u&&!l.handlers.some(e=>e.name===aD.prototype.name)){let e=new aD;l.addHandler(e,!0)}if(h&&!l.handlers.some(e=>"langchain_tracer"===e.name)&&c){let e=new aG;l.addHandler(e,!0)}c&&d&&void 0===l._parentRunId&&(l._parentRunId=d.id,l.handlers.find(e=>"langchain_tracer"===e.name)?.updateFromRunTree(d))}for(let{contextVar:t,inheritable:r=!0,handlerClass:a,envVar:i}of aK(aQ)||[]){let n,s=i&&"true"===tp(i)&&a,o=void 0!==t?aK(t):void 0;o&&tg(o)?n=o:s&&(n=new a({})),void 0!==n&&(l||(l=new e),l.handlers.some(e=>e.name===n.name)||l.addHandler(n,r))}(a||i)&&l&&(l.addTags(a??[]),l.addTags(i??[],!1)),(n||s)&&l&&(l.addMetadata(n??{}),l.addMetadata(s??{},!1));let p=o?.tracerInheritableMetadata,f=o?.tracerInheritableTags;return l&&(p||f)&&(l.handlers=l.handlers.map(e=>e instanceof aG?e.copyWithTracingConfig({metadata:p,tags:f}):e),l.inheritableHandlers=l.inheritableHandlers.map(e=>e instanceof aG?e.copyWithTracingConfig({metadata:p,tags:f}):e)),l}};function a5(e){return"name"in e?e:tm.fromMethods(e)}let a9=new class{getStore(){}run(e,t){return t()}enterWith(e){}},a3=Symbol.for("lc:child_config"),a8=new class{getInstance(){return tc()??a9}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[a3]}runWithConfig(e,t,r){let a,i=a6._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),n=this.getInstance(),s=n.getStore(),o=i?.getParentRunId(),l=i?.handlers?.find(e=>e?.name==="langchain_tracer");return l&&o?a=l.getRunTreeWithTracingConfig(o):r||(a=new aO({name:"<runnable_lambda>",tracingEnabled:!1})),a&&(a.extra={...a.extra,[a3]:e}),void 0!==s&&void 0!==s[td]&&(void 0===a&&(a={}),a[td]=s[td]),n.run(a,t)}initializeGlobalInstance(e){void 0===tc()&&(globalThis[tu]=e)}},a7=new Set(["api_key"]),ie=new Set(["string","number","boolean"]);async function it(e){return a6._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata,void 0,{tracerInheritableMetadata:e?function(e){let t=e.configurable??{},r=e.metadata??{},a={};for(let[e,i]of Object.entries(t))!e.startsWith("__")&&!Object.prototype.hasOwnProperty.call(r,e)&&!a7.has(e)&&ie.has(typeof i)&&(a[e]=i);return Object.keys(a).length>0?a:void 0}(e):void 0})}function ir(...e){let t={};for(let r of e.filter(e=>!!e))for(let e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){let a=t[e]??[];t[e]=[...new Set(a.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){let e=t.callbacks,a=r.callbacks;if(Array.isArray(a))if(e)if(Array.isArray(e))t.callbacks=e.concat(a);else{let r=e.copy();for(let e of a)r.addHandler(a5(e),!0);t.callbacks=r}else t.callbacks=a;else if(a)if(e)if(Array.isArray(e)){let r=a.copy();for(let t of e)r.addHandler(a5(t),!0);t.callbacks=r}else t.callbacks=new a6(a._parentRunId,{handlers:e.handlers.concat(a.handlers),inheritableHandlers:e.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(a.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(a.inheritableTags))),metadata:{...e.metadata,...a.metadata}});else t.callbacks=a}else t[e]=r[e]??t[e];return t}function ia(e){let t=a8.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:e,runName:a,...i}=t;r=Object.entries(i).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)}if(e&&(r=Object.entries(e).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)),r?.configurable&&"string"==typeof r.configurable.model&&r.metadata?.model===void 0&&(r.metadata||(r.metadata={}),r.metadata.model=r.configurable.model),void 0!==r.timeout){if(r.timeout<=0)throw Error("Timeout must be a positive number");let e=r.timeout,t=AbortSignal.timeout(e);r.metadata||(r.metadata={}),void 0===r.metadata.timeoutMs&&(r.metadata.timeoutMs=e),void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,t])):r.signal=t,delete r.timeout}return r}function ii(e={},{callbacks:t,maxConcurrency:r,recursionLimit:a,runName:i,configurable:n,runId:s}={}){let o=ia(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==a&&(o.recursionLimit=a),void 0!==r&&(o.maxConcurrency=r),void 0!==i&&(o.runName=i),void 0!==n&&(o.configurable={...o.configurable,...n}),void 0!==s&&delete o.runId,o}function is(e){if(e)return{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal,store:e.store}}async function io(e,t){let r;return void 0===t?e:Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,a)=>{r=()=>{a(il(t))},t.addEventListener("abort",r,{once:!0}),t.aborted&&a(il(t))})]).finally(()=>t.removeEventListener("abort",r))}function il(e){return e?.reason instanceof Error?e.reason:"string"==typeof e?.reason?Error(e.reason):Error("Aborted")}var iu=class e extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let e=await this.reader.read();if(e.done)return this.reader.releaseLock(),{done:!0,value:void 0};return{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async [Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let r=t.getReader();return new e({start:e=>(function t(){return r.read().then(({done:r,value:a})=>r?void e.close():(e.enqueue(a),t()))})(),cancel(){r.releaseLock()}})}static fromAsyncGenerator(t){return new e({async pull(e){let{value:r,done:a}=await t.next();a&&e.close(),e.enqueue(r)},async cancel(e){await t.return(e)}})}};function id(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(t){for(;;)if(0===t.length){let t=await e.next();for(let e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}})}var ic=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{a8.runWithConfig(is(e.config),async()=>{this.firstResult=this.signal?io(e.generator.next(),this.signal):e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(e=>t(void 0),r)},!0)})}async next(...e){return(this.signal?.throwIfAborted(),this.firstResultUsed)?a8.runWithConfig(is(this.config),this.signal?async()=>io(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async [Symbol.asyncDispose](){await this.return()}};async function ih(e,t,r,a,...i){let n=new ic({generator:t,startSetup:r,signal:a}),s=await n.setup;return{output:e(n,s,...i),setup:s}}let ip=Object.prototype.hasOwnProperty;function im(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function ig(e){let t,r=0,a=e.length;for(;r<a;){if((t=e.charCodeAt(r))>=48&&t<=57){r++;continue}return!1}return!0}function iy(e,t){let r=[e];for(let e in t){let a="object"==typeof t[e]?JSON.stringify(t[e],null,2):t[e];void 0!==a&&r.push(`${e}: ${a}`)}return r.join("\n")}var i_=class extends Error{constructor(e,t,r,a,i){super(iy(e,{name:t,index:r,operation:a,tree:i})),this.name=t,this.index=r,this.operation=a,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=iy(e,{name:t,index:r,operation:a,tree:i})}};let ib={add:function(e,t,r){if("__proto__"===t||"constructor"===t)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){if("__proto__"===t||"constructor"===t)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var a=e[t];return delete e[t],{newDocument:r,removed:a}},replace:function(e,t,r){if("__proto__"===t||"constructor"===t)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var a=e[t];return e[t]=this.value,{newDocument:r,removed:a}},move:function(e,t,r){let a=iw(r,this.path);a&&(a=im(a));let i=ix(r,{op:"remove",path:this.from}).removed;return ix(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:a}},copy:function(e,t,r){let a=iw(r,this.from);return ix(r,{op:"add",path:this.path,value:im(a)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:iE(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}};var iv={add:function(e,t,r){return ig(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){return{newDocument:r,removed:e.splice(t,1)[0]}},replace:function(e,t,r){var a=e[t];return e[t]=this.value,{newDocument:r,removed:a}},move:ib.move,copy:ib.copy,test:ib.test,_get:ib._get};function iw(e,t){if(""==t)return e;var r={op:"_get",path:t};return ix(e,r),r.value}function ix(e,t,r=!1,a=!0,i=!0,n=0){if(r&&("function"==typeof r?r(t,0,e,t.path):iS(t,0)),""===t.path){let a={newDocument:e};if("add"===t.op)return a.newDocument=t.value,a;if("replace"===t.op)return a.newDocument=t.value,a.removed=e,a;if("move"===t.op||"copy"===t.op)return a.newDocument=iw(e,t.from),"move"===t.op&&(a.removed=e),a;else if("test"===t.op){if(a.test=iE(e,t.value),!1===a.test)throw new i_("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a.newDocument=e,a}else if("remove"===t.op)return a.removed=e,a.newDocument=null,a;else if("_get"===t.op)return t.value=e,a;else if(!r)return a;else throw new i_("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",n,t,e)}{let s,o,l;a||(e=im(e));let u=(t.path||"").split("/"),d=e,c=1,h=u.length;for(o="function"==typeof r?r:iS;;){if((s=u[c])&&-1!=s.indexOf("~")&&(s=s.replace(/~1/g,"/").replace(/~0/g,"~")),i&&("__proto__"==s||"prototype"==s&&c>0&&"constructor"==u[c-1]))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(r&&void 0===l&&(void 0===d[s]?l=u.slice(0,c).join("/"):c==h-1&&(l=t.path),void 0!==l&&o(t,0,e,l)),c++,Array.isArray(d)){if("-"===s)s=d.length;else if(r&&!ig(s))throw new i_("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",n,t,e);else ig(s)&&(s=~~s);if(c>=h){if(r&&"add"===t.op&&s>d.length)throw new i_("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",n,t,e);let a=iv[t.op].call(t,d,s,e);if(!1===a.test)throw new i_("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a}}else if(c>=h){let r=ib[t.op].call(t,d,s,e);if(!1===r.test)throw new i_("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return r}if(d=d[s],r&&c<h&&(!d||"object"!=typeof d))throw new i_("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",n,t,e)}}}function ik(e,t,r,a=!0,i=!0){if(r&&!Array.isArray(t))throw new i_("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");a||(e=im(e));let n=Array(t.length);for(let a=0,s=t.length;a<s;a++)n[a]=ix(e,t[a],r,!0,i,a),e=n[a].newDocument;return n.newDocument=e,n}function iS(e,t,r,a){if("object"!=typeof e||null===e||Array.isArray(e))throw new i_("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(ib[e.op]){if("string"!=typeof e.path)throw new i_("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);else if(0!==e.path.indexOf("/")&&e.path.length>0)throw new i_('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);else if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new i_("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new i_("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&function e(t){if(void 0===t)return!0;if(t){if(Array.isArray(t)){for(let r=0,a=t.length;r<a;r++)if(e(t[r]))return!0}else if("object"==typeof t){let a=function(e){if(Array.isArray(e)){let t=Array(e.length);for(let e=0;e<t.length;e++)t[e]=""+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)ip.call(e,r)&&t.push(r);return t}(t),i=a.length;for(var r=0;r<i;r++)if(e(t[a[r]]))return!0}}return!1}(e.value))throw new i_("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);else if(r){if("add"==e.op){var i=e.path.split("/").length,n=a.split("/").length;if(i!==n+1&&i!==n)throw new i_("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==a)throw new i_("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var s=function(e,t,r){try{if(!Array.isArray(e))throw new i_("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)ik(im(t),im(e),r||!0);else{r=r||iS;for(var a=0;a<e.length;a++)r(e[a],a,t,void 0)}}catch(e){if(e instanceof i_)return e;throw e}}([{op:"_get",path:e.from,value:void 0}],r);if(s&&"OPERATION_PATH_UNRESOLVABLE"===s.name)throw new i_("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new i_("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function iE(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){var r,a,i,n=Array.isArray(e),s=Array.isArray(t);if(n&&s){if((a=e.length)!=t.length)return!1;for(r=a;0!=r--;)if(!iE(e[r],t[r]))return!1;return!0}if(n!=s)return!1;var o=Object.keys(e);if((a=o.length)!==Object.keys(t).length)return!1;for(r=a;0!=r--;)if(!t.hasOwnProperty(o[r]))return!1;for(r=a;0!=r--;)if(!iE(e[i=o[r]],t[i]))return!1;return!0}return e!=e&&t!=t}var iT=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=ik({},t);return new iA({ops:t,state:r[r.length-1].newDocument})}},iA=class e extends iT{state;constructor(e){super(e),this.state=e.state}concat(t){let r=this.ops.concat(t.ops),a=ik(this.state,t.ops);return new e({ops:r,state:a[a.length-1].newDocument})}static fromRunLogPatch(t){let r=ik({},t.ops);return new e({ops:t.ops,state:r[r.length-1].newDocument})}};let iI=e=>"log_stream_tracer"===e.name;async function iO(e,t){if("original"===t)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:r}=e;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||r?.input!==""?r.input:void 0}async function iC(e,t){let{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&r?.output!==void 0?r.output:r}var ij=class extends aN{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=iu.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new iT({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new iT({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;let r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};"streaming_events"===this._schemaFormat&&(r.inputs=await iO(e,this._schemaFormat)),await this.writer.write(new iT({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(void 0===t)return;let r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await iO(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await iC(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let a=new iT({ops:r});await this.writer.write(a)}finally{if(e.id===this.rootId){let t=new iT({ops:[{op:"replace",path:"/final_output",value:await iC(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let a,i=this.keyMapByRunId[e.id];if(void 0===i)return;if(void 0!==e.inputs.messages){var n;a=void 0!==(n=r?.chunk)&&void 0!==n.message?r?.chunk:new e6({id:`run-${e.id}`,content:t})}else a=t;let s=new iT({ops:[{op:"add",path:`/logs/${i}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${i}/streamed_output/-`,value:a}]});await this.writer.write(s)}},iP=class e{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}};function i$({name:e,serialized:t}){return void 0!==e?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}let iN=e=>"event_stream_tracer"===e.name;var iR=class extends aN{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(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=iu.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){let r=await t.next();if(r.done)return;let a=this.runInfoMap.get(e);if(void 0===a)return void(yield r.value);function i(e,t){return"llm"===e&&"string"==typeof t?new iP({text:t}):t}let n=this.tappedPromises.get(e);if(void 0===n){let s;n=new Promise(e=>{s=e}),this.tappedPromises.set(e,n);try{let n={event:`on_${a.runType}_stream`,run_id:e,name:a.name,tags:a.tags,metadata:a.metadata,data:{}};for await(let e of(await this.send({...n,data:{chunk:i(a.runType,r.value)}},a),yield r.value,t))"tool"!==a.runType&&"retriever"!==a.runType&&await this.send({...n,data:{chunk:i(a.runType,e)}},a),yield e}finally{s?.()}}else for await(let e of(yield r.value,t))yield e}async send(e,t){!this.readableStreamClosed&&this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let r=this.tappedPromises.get(e.run_id);void 0!==r?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=i$(e),r=void 0!==e.inputs.messages?"chat_model":"llm",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,a);let i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onLLMNewToken(e,t,r){let a,i,n=this.runInfoMap.get(e.id);if(void 0===n)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===n.runType)i="on_chat_model_stream",a=r?.chunk===void 0?new e6({content:t,id:`run-${e.id}`}):r.chunk.message;else if("llm"===n.runType)i="on_llm_stream",a=r?.chunk===void 0?new iP({text:t}):r.chunk;else throw Error(`Unexpected run type ${n.runType}`);await this.send({event:i,data:{chunk:a},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){let t,r,a=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===a)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let i=e.outputs?.generations;if("chat_model"===a.runType){for(let e of i??[]){if(void 0!==r)break;r=e[0]?.message}t="on_chat_model_end"}else if("llm"===a.runType)r={generations:i?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},t="on_llm_end";else throw Error(`onLLMEnd: Unexpected run type: ${a.runType}`);await this.sendEndEvent({event:t,data:{output:r,input:a.inputs},run_id:e.id,name:a.name,tags:a.tags,metadata:a.metadata},a)}async onChainStart(e){let t=i$(e),r=e.run_type??"chain",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(i={},a.inputs={}):void 0!==e.inputs.input?(i.input=e.inputs.input,a.inputs=e.inputs.input):(i.input=e.inputs,a.inputs=e.inputs),this.runInfoMap.set(e.id,a),await this.send({event:`on_${r}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,a=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:a};a.input&&1===Object.keys(a).length&&(i.input=a.input,t.inputs=a.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=i$(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=i$(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){let a=this.runInfoMap.get(r);if(void 0===a)throw Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:a.tags,metadata:a.metadata,data:t},a)}async finish(){Promise.all([...this.tappedPromises.values()]).finally(()=>{this.writer.close()})}};let iM=Object.prototype.toString,iL=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 iz(e,t,{min:r=0,allowInfinity:a=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${a?" or Infinity":""}.`);if(!a&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}var iU=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function iB(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function iD({error:e,attemptNumber:t,retriesConsumed:r,startTime:a,options:i}){let n,s=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof iU)throw s.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,l=i.maxRetryTime??1/0,u=Object.freeze({error:s,attemptNumber:t,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(u),0>=iB(a,l))throw s;let d=await i.shouldConsumeRetry(u),c=iB(a,l);if(c<=0||o<=0)throw s;if(s instanceof TypeError&&!function(e){if(!(e&&"[object Error]"===iM.call(e)&&"TypeError"===e.name&&"string"==typeof e.message))return!1;let{message:t,stack:r}=e;return"Load failed"===t?void 0===r||"__sentry_captured__"in e:!!t.startsWith("error sending request for url")||iL.has(t)}(s)){if(d)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(u))throw s;if(!d)return i.signal?.throwIfAborted(),!1;let h=Math.min((n=Math.max(1,r+1),Math.min(Math.round((i.randomize?Math.random()+1:1)*i.minTimeout*i.factor**(n-1)),i.maxTimeout)),c);return h>0&&await new Promise((e,t)=>{let r=()=>{clearTimeout(a),i.signal?.removeEventListener("abort",r),t(i.signal.reason)},a=setTimeout(()=>{i.signal?.removeEventListener("abort",r),e()},h);i.unref&&a.unref?.(),i.signal?.addEventListener("abort",r,{once:!0})}),i.signal?.throwIfAborted(),!0}async function iF(e,t={}){var r=(t={...t}).retries;if("number"==typeof r){if(r<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(void 0!==r)throw TypeError("Expected `retries` to be a number or Infinity.");if(Object.hasOwn(t,"forever"))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,iz("factor",t.factor,{min:0,allowInfinity:!1}),iz("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),iz("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),iz("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let a=0,i=0,n=performance.now();for(;!Number.isFinite(t.retries)||i<=t.retries;){a++;try{t.signal?.throwIfAborted();let r=await e(a);return t.signal?.throwIfAborted(),r}catch(e){await iD({error:e,attemptNumber:a,retriesConsumed:i,startTime:n,options:t})&&i++}}throw Error("Retry attempts exhausted without throwing an error.")}let iZ=[400,401,402,403,404,405,406,407,409],iH=e=>{if("object"!=typeof e||null===e)return;if("message"in e&&"string"==typeof e.message&&(e.message.startsWith("Cancel")||e.message.startsWith("AbortError"))||"name"in e&&"string"==typeof e.name&&"AbortError"===e.name||"code"in e&&"string"==typeof e.code&&"ECONNABORTED"===e.code)throw e;let t="response"in e&&"object"==typeof e.response&&null!==e.response&&"status"in e.response&&"number"==typeof e.response.status?e.response.status:void 0,r="status"in e&&"number"==typeof e.status?e.status:void 0,a=t??r;if(a&&iZ.includes(+a))throw e;if(("error"in e&&"object"==typeof e.error&&null!==e.error&&"code"in e.error&&"string"==typeof e.error.code?e.error.code:void 0)==="insufficient_quota"){let t=Error("message"in e&&"string"==typeof e.message?e.message:"Insufficient quota");throw t.name="InsufficientQuotaError",t}};var iq=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??iH;const t="default"in rF.default?rF.default.default:rF.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>iF(()=>e(...t).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{onFailedAttempt:({error:e})=>this.onFailedAttempt?.(e),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){if(e.signal){let a;return Promise.race([this.call(t,...r),new Promise((t,r)=>{a=()=>{r(il(e.signal))},e.signal?.addEventListener("abort",a,{once:!0})})]).finally(()=>{e.signal&&a&&e.signal.removeEventListener("abort",a)})}return this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}},iJ=class extends aN{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:r,onError:a}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=a}persistRun(e){return Promise.resolve()}async onRunCreate(e){!this.rootId&&(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function iG(e){return!!e&&e.lc_runnable}var iW=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags,a=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||a.some(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&a.every(e=>!this.excludeTags?.includes(e))),r}};function iV(e,t,r){function a(r,a){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:a,constr:s,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,a);let i=s.prototype,n=Object.keys(i);for(let e=0;e<n.length;e++){let t=n[e];t in r||(r[t]=i[t].bind(r))}}let i=r?.Parent??Object;class n extends i{}function s(e){var t;let i=r?.Parent?new n:this;for(let r of(a(i,e),(t=i._zod).deferred??(t.deferred=[]),i._zod.deferred))r();return i}return Object.defineProperty(n,"name",{value:e}),Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}Symbol("zod_brand");class iK extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(_=globalThis).__zod_globalConfig??(_.__zod_globalConfig={});let iQ=globalThis.__zod_globalConfig;function iY(e){return e&&Object.assign(iQ,e),iQ}function iX(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function i0(e,t){return"bigint"==typeof t?t.toString():t}function i1(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function i2(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}let i4=Symbol("evaluating");function i6(e,t,r){let a;Object.defineProperty(e,t,{get(){if(a!==i4)return void 0===a&&(a=i4,a=r()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function i5(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function i9(...e){let t={};for(let r of e)Object.assign(t,Object.getOwnPropertyDescriptors(r));return Object.defineProperties({},t)}let i3="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function i8(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let i7=i1(()=>{if(iQ.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function ne(e){if(!1===i8(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==i8(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}let nt=new Set(["string","number","symbol"]),nr=new Set(["string","number","bigint","boolean","symbol","undefined"]);function na(e,t,r){let a=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(a._zod.parent=e),a}function ni(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function nn(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function ns(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}let no={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},nl={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function nu(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function nd(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function nc(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function nh(e){return"string"==typeof e?e:e?.message}function np(e,t,r){let a=e.message?e.message:nh(e.inst?._zod.def?.error?.(e))??nh(t?.error?.(e))??nh(r.customError?.(e))??nh(r.localeError?.(e))??"Invalid input",{inst:i,continue:n,input:s,...o}=e;return o.path??(o.path=[]),o.message=a,t?.reportInput&&(o.input=s),o}function nf(...e){let[t,r,a]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:a}:{...t}}function nm(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function ng(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}e.s(["BIGINT_FORMAT_RANGES",0,nl,"Class",0,class{constructor(...e){}},"NUMBER_FORMAT_RANGES",0,no,"aborted",0,nu,"allowsEval",0,i7,"assert",0,function(e){},"assertEqual",0,function(e){return e},"assertIs",0,function(e){},"assertNever",0,function(e){throw Error("Unexpected value in exhaustive check")},"assertNotEqual",0,function(e){return e},"assignProp",0,i5,"base64ToUint8Array",0,nm,"base64urlToUint8Array",0,function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return nm(t+r)},"cached",0,i1,"captureStackTrace",0,i3,"cleanEnum",0,function(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])},"cleanRegex",0,i2,"clone",0,na,"cloneDef",0,function(e){return i9(e._zod.def)},"createTransparentProxy",0,function(e){let t;return new Proxy({},{get:(r,a,i)=>(t??(t=e()),Reflect.get(t,a,i)),set:(r,a,i,n)=>(t??(t=e()),Reflect.set(t,a,i,n)),has:(r,a)=>(t??(t=e()),Reflect.has(t,a)),deleteProperty:(r,a)=>(t??(t=e()),Reflect.deleteProperty(t,a)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,a)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,a)),defineProperty:(r,a,i)=>(t??(t=e()),Reflect.defineProperty(t,a,i))})},"defineLazy",0,i6,"esc",0,function(e){return JSON.stringify(e)},"escapeRegex",0,function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")},"explicitlyAborted",0,nd,"extend",0,function(e,t){if(!ne(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let r=e._zod.def.shape;for(let e in t)if(void 0!==Object.getOwnPropertyDescriptor(r,e))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let a=i9(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return i5(this,"shape",r),r}});return na(e,a)},"finalizeIssue",0,np,"floatSafeRemainder",0,function(e,t){let r=e/t,a=Math.round(r),i=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-a)<i?0:r-a},"getElementAtPath",0,function(e,t){return t?t.reduce((e,t)=>e?.[t],e):e},"getEnumValues",0,iX,"getLengthableOrigin",0,function(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"},"getParsedType",0,e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return"promise";if("u">typeof Map&&e instanceof Map)return"map";if("u">typeof Set&&e instanceof Set)return"set";if("u">typeof Date&&e instanceof Date)return"date";if("u">typeof File&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},"getSizableOrigin",0,function(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"},"hexToUint8Array",0,function(e){let t=e.replace(/^0x/,"");if(t.length%2!=0)throw Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)r[e/2]=Number.parseInt(t.slice(e,e+2),16);return r},"isObject",0,i8,"isPlainObject",0,ne,"issue",0,nf,"joinValues",0,function(e,t="|"){return e.map(e=>nn(e)).join(t)},"jsonStringifyReplacer",0,i0,"merge",0,function(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=i9(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return i5(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return na(e,r)},"mergeDefs",0,i9,"normalizeParams",0,ni,"nullish",0,function(e){return null==e},"numKeys",0,function(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t},"objectClone",0,function(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))},"omit",0,function(e,t){let r=e._zod.def,a=r.checks;if(a&&a.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=i9(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete a[e]}return i5(this,"shape",a),a},checks:[]});return na(e,i)},"optionalKeys",0,ns,"parsedType",0,function(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":if(null===e)return"null";if(Array.isArray(e))return"array";if(e&&Object.getPrototypeOf(e)!==Object.prototype&&"constructor"in e&&e.constructor)return e.constructor.name}return t},"partial",0,function(e,t,r){let a=t._zod.def.checks;if(a&&a.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let i=i9(t._zod.def,{get shape(){let a=t._zod.def.shape,i={...a};if(r)for(let t in r){if(!(t in a))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:a[t]}):a[t])}else for(let t in a)i[t]=e?new e({type:"optional",innerType:a[t]}):a[t];return i5(this,"shape",i),i},checks:[]});return na(t,i)},"pick",0,function(e,t){let r=e._zod.def,a=r.checks;if(a&&a.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=i9(e._zod.def,{get shape(){let e={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);t[a]&&(e[a]=r.shape[a])}return i5(this,"shape",e),e},checks:[]});return na(e,i)},"prefixIssues",0,nc,"primitiveTypes",0,nr,"promiseAllObject",0,function(e){let t=Object.keys(e);return Promise.all(t.map(t=>e[t])).then(e=>{let r={};for(let a=0;a<t.length;a++)r[t[a]]=e[a];return r})},"propertyKeyTypes",0,nt,"randomString",0,function(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let a=0;a<e;a++)r+=t[Math.floor(Math.random()*t.length)];return r},"required",0,function(e,t,r){let a=i9(t._zod.def,{get shape(){let a=t._zod.def.shape,i={...a};if(r)for(let t in r){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:a[t]}))}else for(let t in a)i[t]=new e({type:"nonoptional",innerType:a[t]});return i5(this,"shape",i),i}});return na(t,a)},"safeExtend",0,function(e,t){if(!ne(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=i9(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return i5(this,"shape",r),r}});return na(e,r)},"shallowClone",0,function(e){return ne(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e},"slugify",0,function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")},"stringifyPrimitive",0,nn,"uint8ArrayToBase64",0,ng,"uint8ArrayToBase64url",0,function(e){return ng(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},"uint8ArrayToHex",0,function(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")},"unwrapMessage",0,nh],922143);let ny=/^-?\d+n?$/,n_=/^-?\d+$/,nb=/^-?\d+(?:\.\d+)?$/,nv=iV("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),nw=((e,t)=>{nv.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[i,n]=no[t.format];e._zod.onattach.push(e=>{let a=e._zod.bag;a.format=t.format,a.minimum=i,a.maximum=n,r&&(a.pattern=n_)}),e._zod.check=s=>{let o=s.value;if(r){if(!Number.isInteger(o))return void s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?s.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):s.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}))}o<i&&s.issues.push({origin:"number",input:o,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),o>n&&s.issues.push({origin:"number",input:o,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}},iV("$ZodCheckStringFormat",(e,t)=>{var r,a;nv.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})})),nx=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,i0,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},nk=iV("$ZodError",nx),nS=iV("$ZodError",nx,{Parent:Error}),nE=(d=nS,c=nS,async(e,t,r,a)=>{let i=r?{...r,async:!0}:{async:!0},n=e._zod.run({value:t,issues:[]},i);if(n instanceof Promise&&(n=await n),n.issues.length){let e=new(a?.Err??c)(n.issues.map(e=>np(e,i,iY())));throw i3(e,a?.callee),e}return n.value}),nT=(h=nS,(e,t,r)=>{let a=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise)throw new iK;return i.issues.length?{success:!1,error:new(h??nk)(i.issues.map(e=>np(e,a,iY())))}:{success:!0,data:i.value}}),nA=(p=nS,async(e,t,r)=>{let a=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:t,issues:[]},a);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new p(i.issues.map(e=>np(e,a,iY())))}:{success:!0,data:i.value}}),nI={major:4,minor:4,patch:3},nO=iV("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=nI;let a=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&a.unshift(e),a))for(let r of t._zod.onattach)r(e);if(0===a.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let a,i=nu(e);for(let n of t){if(n._zod.def.when){if(nd(e)||!n._zod.def.when(e))continue}else if(i)continue;let t=e.issues.length,s=n._zod.check(e);if(s instanceof Promise&&r?.async===!1)throw new iK;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(i||(i=nu(e,t)))});else{if(e.issues.length===t)continue;i||(i=nu(e,t))}}return a?a.then(()=>e):e},r=(r,i,n)=>{if(nu(r))return r.aborted=!0,r;let s=t(i,a,n);if(s instanceof Promise){if(!1===n.async)throw new iK;return s.then(t=>e._zod.parse(t,n))}return e._zod.parse(s,n)};e._zod.run=(i,n)=>{if(n.skipChecks)return e._zod.parse(i,n);if("backward"===n.direction){let t=e._zod.parse({value:i.value,issues:[]},{...n,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,i,n)):r(t,i,n)}let s=e._zod.parse(i,n);if(s instanceof Promise){if(!1===n.async)throw new iK;return s.then(e=>t(e,a,n))}return t(s,a,n)}}i6(e,"~standard",()=>({validate:t=>{try{let r=nT(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return nA(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),nC=iV("$ZodString",(e,t)=>{var r;let a;nO.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(a=(r=e._zod.bag)?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*",RegExp(`^${a}$`)),e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}});(e,t)=>{nw.init(e,t),nC.init(e,t)};(e,t)=>{nO.init(e,t),e._zod.pattern=e._zod.bag.pattern??nb,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;let n="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...n?{received:n}:{}}),r}},(e,t)=>{nO.init(e,t),e._zod.pattern=ny,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(e){}return"bigint"==typeof r.value||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}};let nj=iV("$ZodNever",(e,t)=>{nO.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function nP(e,t,r,a,i,n){let s=r in a;if(e.issues.length){if(i&&n&&!s)return;t.issues.push(...nc(r,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}void 0===e.value?s&&(t.value[r]=void 0):t.value[r]=e.value}function n$(e,t,r,a){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;let i=e.filter(e=>!nu(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>np(e,a,iY())))}),t)}(e,t)=>{let r;nO.init(e,t);let a=Object.getOwnPropertyDescriptor(t,"shape");if(!a?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}let i=i1(()=>(function(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=ns(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}})(t));i6(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let a=e[t]._zod;if(a.values)for(let e of(r[t]??(r[t]=new Set),a.values))r[t].add(e)}return r});let n=t.catchall;e._zod.parse=(t,a)=>{r??(r=i.value);let s=t.value;if(!i8(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};let o=[],l=r.shape;for(let e of r.keys){let r=l[e],i="optional"===r._zod.optin,n="optional"===r._zod.optout,u=r._zod.run({value:s[e],issues:[]},a);u instanceof Promise?o.push(u.then(r=>nP(r,t,e,s,i,n))):nP(u,t,e,s,i,n)}return n?function(e,t,r,a,i,n){let s=[],o=i.keySet,l=i.catchall._zod,u=l.def.type,d="optional"===l.optin,c="optional"===l.optout;for(let i in t){if("__proto__"===i||o.has(i))continue;if("never"===u){s.push(i);continue}let n=l.run({value:t[i],issues:[]},a);n instanceof Promise?e.push(n.then(e=>nP(e,r,i,t,d,c))):nP(n,r,i,t,d,c)}return(s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:n}),e.length)?Promise.all(e).then(()=>r):r}(o,s,t,a,i.value,e):o.length?Promise.all(o).then(()=>t):t}},(e,t)=>{nO.init(e,t),i6(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),i6(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),i6(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),i6(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>i2(e.source)).join("|")})$`)}});let r=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(a,i)=>{if(r)return r(a,i);let n=!1,s=[];for(let e of t.options){let t=e._zod.run({value:a.value,issues:[]},i);if(t instanceof Promise)s.push(t),n=!0;else{if(0===t.issues.length)return t;s.push(t)}}return n?Promise.all(s).then(t=>n$(t,a,e,i)):n$(s,a,e,i)}};function nN(e,t){for(let r=e.length-1;r>=0;r--)if("optional"!==e[r]._zod[t])return r+1;return 0}function nR(e,t,r){e.issues.length&&t.issues.push(...nc(r,e.issues)),t.value[r]=e.value}function nM(e,t,r,a,i){for(let n=0;n<r.length;n++){let r=e[n],s=n<a.length;if(r.issues.length){if(!s&&n>=i){t.value.length=n;break}t.issues.push(...nc(n,r.issues))}t.value[n]=r.value}for(let e=t.value.length-1;e>=a.length;e--)if("optional"===r[e]._zod.optout&&void 0===t.value[e])t.value.length=e;else break;return t}(e,t)=>{nO.init(e,t);let r=t.items;e._zod.parse=(a,i)=>{let n=a.value;if(!Array.isArray(n))return a.issues.push({input:n,inst:e,expected:"tuple",code:"invalid_type"}),a;a.value=[];let s=[],o=nN(r,"optin"),l=nN(r,"optout");if(!t.rest){if(n.length<o)return a.issues.push({code:"too_small",minimum:o,inclusive:!0,input:n,inst:e,origin:"array"}),a;n.length>r.length&&a.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:n,inst:e,origin:"array"})}let u=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e]._zod.run({value:n[e],issues:[]},i);t instanceof Promise?s.push(t.then(t=>{u[e]=t})):u[e]=t}if(t.rest){let e=r.length-1;for(let o of n.slice(r.length)){e++;let r=t.rest._zod.run({value:o,issues:[]},i);r instanceof Promise?s.push(r.then(t=>nR(t,a,e))):nR(r,a,e)}}return s.length?Promise.all(s).then(()=>nM(u,a,r,n,l)):nM(u,a,r,n,l)}};function nL(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}(e,t)=>{nO.init(e,t),e._zod.optin="optional",e._zod.optout="optional",i6(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),i6(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${i2(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){let a=e.value,i=t.innerType._zod.run(e,r);return i instanceof Promise?i.then(e=>nL(e,a)):nL(i,a)}return void 0===e.value?e:t.innerType._zod.run(e,r)}};function nz(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}(e,t)=>{nO.init(e,t),i6(e._zod,"values",()=>t.in._zod.values),i6(e._zod,"optin",()=>t.in._zod.optin),i6(e._zod,"optout",()=>t.out._zod.optout),i6(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("backward"===r.direction){let a=t.out._zod.run(e,r);return a instanceof Promise?a.then(e=>nz(e,t.in,r)):nz(a,t.in,r)}let a=t.in._zod.run(e,r);return a instanceof Promise?a.then(e=>nz(e,t.out,r)):nz(a,t.out,r)}};Symbol("ZodOutput"),Symbol("ZodInput");(b=globalThis).__zod_globalRegistry??(b.__zod_globalRegistry=new class e{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];return this._map.set(e,r),r&&"object"==typeof r&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let a={...r,...this._map.get(e)};return Object.keys(a).length?a:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});let nU=globalThis.__zod_globalRegistry;function nB(e){if("object"!=typeof e||null===e||!("_zod"in e))return!1;let t=e._zod;return"object"==typeof t&&null!==t&&"def"in t}function nD(e){if("object"!=typeof e||null===e||!("_def"in e)||"_zod"in e)return!1;let t=e._def;return"object"==typeof t&&null!=t&&"typeName"in t}async function nF(e,t){if(nB(e))return await nE(e,t);if(nD(e))return await e.parseAsync(t);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function nZ(e){return!!nB(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"object"===e._zod.def.type||!1)}function nH(e){return!!nB(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"array"===e._zod.def.type||!1)}function nq(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}e.i(922143);let nJ=["*","_","`"];async function nG(e,t){let r=t?.backgroundColor??"white",a=t?.imageType??"png",i=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");void 0===r||/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`);let n=`https://mermaid.ink/img/${i}?bgColor=${r}&type=${a}`,s=await fetch(n);if(!s.ok)throw Error(`Failed to render the graph using the Mermaid.INK API.
|
|
42
|
+
${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:r,microsecondPrecisionDatestring:a}=aE(new Date(e.start_time).getTime(),e.id,e.execution_order),i={...e},n=this.getRunById(i.parent_run_id);if(void 0!==i.parent_run_id?n?(this._addChildRun(n,i),n.child_execution_order=Math.max(n.child_execution_order,i.child_execution_order),i.trace_id=n.trace_id,void 0!==n.dotted_order&&(i.dotted_order=[n.dotted_order,r].join("."),i._serialized_start_time=a)):i.parent_run_id=void 0:(i.trace_id=i.id,i.dotted_order=r,i._serialized_start_time=a),this.usesRunTreeMap){let e=function e(r,a){if(r)return new aO({...r,start_time:r._serialized_start_time??r.start_time,parent_run:e(a),child_runs:r.child_runs.map(t=>e(t)).filter(e=>void 0!==e),extra:{...r.extra,runtime:(void 0===t&&(t={library:"langchain-js",runtime:"u">typeof window&&void 0!==window.document?"browser":void 0===th.default||void 0===th.default.versions||void 0===th.default.versions.node||"u">typeof Deno?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"u">typeof window&&"nodejs"===window.name||"u">typeof navigator&&navigator.userAgent.includes("jsdom")?"jsdom":"u">typeof Deno?"deno":"other":"node"}),t)},tracingEnabled:!1})}(i,n);void 0!==e&&this.runTreeMap.set(i.id,e)}else this.runMap.set(i.id,i);return i}async _endTrace(e){let t=void 0!==e.parent_run_id&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let t=void 0!==e&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,a,i,n,s,o){let l=this._getExecutionOrder(a),u=Date.now(),d=s?{...i,metadata:s}:i,c={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:n||[]};return this._addRunToRunMap(c)}async handleLLMStart(e,t,r,a,i,n,s,o){let l=this.getRunById(r)??this._createRunForLLMStart(e,t,r,a,i,n,s,o);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(e,t,r,a,i,n,s,o){let l=this._getExecutionOrder(a),u=Date.now(),d=s?{...i,metadata:s}:i,c={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:n||[]};return this._addRunToRunMap(c)}async handleChatModelStart(e,t,r,a,i,n,s,o){let l=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,a,i,n,s,o);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(e,t,r,a,i){let n=this.getRunById(t);if(!n||n?.run_type!=="llm")throw Error("No LLM run to end.");return n.end_time=Date.now(),n.outputs=e,n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),n.extra={...n.extra,...i},await this.onLLMEnd?.(n),await this._endTrace(n),n}async handleLLMError(e,t,r,a,i){let n=this.getRunById(t);if(!n||n?.run_type!=="llm")throw Error("No LLM run to end.");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),n.extra={...n.extra,...i},await this.onLLMError?.(n),await this._endTrace(n),n}_createRunForChainStart(e,t,r,a,i,n,s,o,l){let u=this._getExecutionOrder(a),d=Date.now(),c={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:t,execution_order:u,child_execution_order:u,run_type:s??"chain",child_runs:[],extra:n?{...l,metadata:n}:{...l},tags:i||[]};return this._addRunToRunMap(c)}async handleChainStart(e,t,r,a,i,n,s,o){let l=this.getRunById(r)??this._createRunForChainStart(e,t,r,a,i,n,s,o);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(e,t,r,a,i){let n=this.getRunById(t);if(!n)throw Error("No chain run to end.");return n.end_time=Date.now(),n.outputs=a$(e,"output"),n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),i?.inputs!==void 0&&(n.inputs=a$(i.inputs,"input")),await this.onChainEnd?.(n),await this._endTrace(n),n}async handleChainError(e,t,r,a,i){let n=this.getRunById(t);if(!n)throw Error("No chain run to end.");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),i?.inputs!==void 0&&(n.inputs=a$(i.inputs,"input")),await this.onChainError?.(n),await this._endTrace(n),n}_createRunForToolStart(e,t,r,a,i,n,s){let o=this._getExecutionOrder(a),l=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:n?{metadata:n}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(e,t,r,a,i,n,s){let o=this.getRunById(r)??this._createRunForToolStart(e,t,r,a,i,n,s);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){let r=this.getRunById(t);r&&r?.run_type==="chain"&&(r.actions=r.actions||[],r.actions.push(e),r.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r))}async handleAgentEnd(e,t){let r=this.getRunById(t);r&&r?.run_type==="chain"&&(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,a,i,n,s){let o=this._getExecutionOrder(a),l=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:n?{metadata:n}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,t,r,a,i,n,s){let o=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,a,i,n,s);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){let r=this.getRunById(t);r&&r?.run_type==="chain"&&(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,a,i,n){let s=this.getRunById(r);if(!s||s?.run_type!=="llm")throw Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:n?.chunk}}),await this.onLLMNewToken?.(s,e,{chunk:n?.chunk}),s}};let aR={bold:{open:"\x1b[1m",close:"\x1b[22m"},color:{grey:{open:"\x1b[90m",close:"\x1b[39m"},green:{open:"\x1b[32m",close:"\x1b[39m"},cyan:{open:"\x1b[36m",close:"\x1b[39m"},red:{open:"\x1b[31m",close:"\x1b[39m"},blue:{open:"\x1b[34m",close:"\x1b[39m"}}};function aM(e,t){return`${e.open}${t}${e.close}`}function az(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function aL(e){return"string"==typeof e?e.trim():null==e?e:az(e,e.toString())}function aU(e){if(!e.end_time)return"";let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}let{color:aD}=aR;var aB=class extends aN{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){let t=[],r=e;for(;r.parent_run_id;){let e=this.runMap.get(r.parent_run_id);if(e)t.push(e),r=e;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((e,t,r)=>{let a=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?aM(aR.bold,a):a}).join(" > ");return aM(aD.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.green,"[chain/start]")} [${t}] Entering Chain run with input: ${az(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.cyan,"[chain/end]")} [${t}] [${aU(e)}] Exiting Chain run with output: ${az(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.red,"[chain/error]")} [${t}] [${aU(e)}] Chain run errored with error: ${az(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${aM(aD.green,"[llm/start]")} [${t}] Entering LLM run with input: ${az(r,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.cyan,"[llm/end]")} [${t}] [${aU(e)}] Exiting LLM run with output: ${az(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.red,"[llm/error]")} [${t}] [${aU(e)}] LLM run errored with error: ${az(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.green,"[tool/start]")} [${t}] Entering Tool run with input: "${aL(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.cyan,"[tool/end]")} [${t}] [${aU(e)}] Exiting Tool run with output: "${aL(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.red,"[tool/error]")} [${t}] [${aU(e)}] Tool run errored with error: ${az(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${az(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.cyan,"[retriever/end]")} [${t}] [${aU(e)}] Exiting Retriever run with output: ${az(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.red,"[retriever/error]")} [${t}] [${aU(e)}] Retriever run errored with error: ${az(e.error,"[error]")}`)}onAgentAction(e){let t=this.getBreadcrumbs(e);console.log(`${aM(aD.blue,"[agent/action]")} [${t}] Agent selected action: ${az(e.actions[e.actions.length-1],"[action]")}`)}};let aF=Symbol.for("ls:tracing_async_local_storage"),aZ=new class{getStore(){}run(e,t){return t()}},aH=new class{getInstance(){return globalThis[aF]??aZ}initializeGlobalInstance(e){void 0===globalThis[aF]&&(globalThis[aF]=e)}};function aq(e){return"function"==typeof e&&"langsmith:traceable"in e}Symbol.for("langsmith:traceable:root");let aJ=new Set(["ls_agent_type"]);var aG=class e extends aN{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(t={}){super(t),this.fields=t;const{exampleId:r,projectName:a,client:i,replicas:s,metadata:o,tags:l}=t;this.projectName=a??tz(),this.replicas=s,this.exampleId=r,this.client=i??(void 0===n&&(n=new ab("false"===tp("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{})),n),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=l??[];const u=e.getTraceableRunTree();u&&this.updateFromRunTree(u)}async persistRun(e){}async onRunCreate(e){aW(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){aW(this,e);let t=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await t?.postRun():await t?.patchRun()}onLLMEnd(e){let t=e.outputs;if(t?.generations){let r=function(e){let t;for(let r of e)for(let e of r)e1.isInstance(e.message)&&void 0!==e.message.usage_metadata&&(t=ef(t,e.message.usage_metadata));return t}(t.generations);if(void 0!==r){e.extra=e.extra??{};let t=e.extra.metadata??{};t.usage_metadata=r,e.extra.metadata=t}}}copyWithTracingConfig({metadata:t,tags:r}){let a;if(void 0===t)a=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(void 0===this.tracingMetadata)a={...t};else for(let[e,r]of(a={...this.tracingMetadata},Object.entries(t)))(!Object.prototype.hasOwnProperty.call(a,e)||aJ.has(e))&&(a[e]=r);let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],n=new e({...this.fields,metadata:a,tags:i});return n.runMap=this.runMap,n.runTreeMap=this.runTreeMap,n}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e,r=new Set;for(;t.parent_run&&!r.has(t.id)&&(r.add(t.id),t.parent_run);){;t=t.parent_run}r.clear();let a=[t];for(;a.length>0;){let e=a.shift();!(!e||r.has(e.id))&&(r.add(e.id),this.runTreeMap.set(e.id,e),e.child_runs&&a.push(...e.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let t=this.runTreeMap.get(e);if(t)return new aO({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return function(e=!1){let t=aH.getInstance().getStore();if(!e&&void 0===t)throw Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.");return t}(!0)}catch{return}}static[Symbol.hasInstance](e){return"object"==typeof e&&null!==e&&"name"in e&&"langchain_tracer"===e.name&&"copyWithTracingConfig"in e&&"function"==typeof e.copyWithTracingConfig&&"getRunTreeWithTracingConfig"in e&&"function"==typeof e.getRunTreeWithTracingConfig}};function aW(e,t){if(e.tracingMetadata){t.extra??={};let r=t.extra.metadata??{},a=!1;for(let[t,i]of Object.entries(e.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,t)||aJ.has(t))&&r[t]!==i&&(r[t]=i,a=!0);a&&(t.extra.metadata=r)}e.tracingTags.length>0&&(t.tags=Array.from(new Set([...t.tags??[],...e.tracingTags])))}async function aV(e,t){if(!0===t){let t=tc();void 0!==t?await t.run(void 0,async()=>e()):await e()}else void 0===s&&(s=new("default"in rF.default?rF.default.default:rF.default)({autoStart:!0,concurrency:1})),s.add(async()=>{let t=tc();void 0!==t?await t.run(void 0,async()=>e()):await e()})}function aK(e){let t=tc();if(void 0!==t)return t.getStore()?.[td]?.[e]}let aQ=Symbol("lc:configure_hooks");var aY=class{setHandler(e){return this.setHandlers([e])}},aX=class{constructor(e,t,r,a,i,n,s,o){this.runId=e,this.handlers=t,this.inheritableHandlers=r,this.tags=a,this.inheritableTags=i,this.metadata=n,this.inheritableMetadata=s,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>aV(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,a,i){await Promise.all(this.handlers.map(r=>aV(async()=>{try{await r.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}},a0=class extends aX{getChild(e){let t=new a9(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}},a1=class extends aX{async handleLLMNewToken(e,t,r,a,i,n){await Promise.all(this.handlers.map(r=>aV(async()=>{if(!r.ignoreLLM)try{await r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,n)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMNewToken: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}async handleChatModelStreamEvent(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreLLM)try{await t.handleChatModelStreamEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChatModelStreamEvent: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMError(e,t,r,a,i){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreLLM)try{await t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMEnd(e,t,r,a,i){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreLLM)try{await t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},a2=class extends aX{getChild(e){let t=new a9(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,a,i){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreChain)try{await t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleChainEnd(e,t,r,a,i){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreChain)try{await t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},a4=class extends aX{getChild(e){let t=new a9(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEvent(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreAgent)try{await t.handleToolEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if(t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>aV(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},a9=class e extends aY{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,t){super(),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r,a,i,n,s,o){return Promise.all(t.map(async(t,a)=>{let n=0===a&&r?r:tl();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return aP(r)&&r._createRunForLLMStart(e,[t],n,this._parentRunId,i,this.tags,this.metadata,o),aV(async()=>{try{await r.handleLLMStart?.(e,[t],n,this._parentRunId,i,this.tags,this.metadata,o)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new a1(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r,a,i,n,s,o){return Promise.all(t.map(async(t,a)=>{let n=0===a&&r?r:tl();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return aP(r)&&r._createRunForChatModelStart(e,[t],n,this._parentRunId,i,this.tags,this.metadata,o),aV(async()=>{try{if(r.handleChatModelStart)await r.handleChatModelStart?.(e,[t],n,this._parentRunId,i,this.tags,this.metadata,o);else if(r.handleLLMStart){let a=eV(t);await r.handleLLMStart?.(e,[a],n,this._parentRunId,i,this.tags,this.metadata,o)}}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new a1(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=tl(),a,i,n,s,o,l){return await Promise.all(this.handlers.map(i=>{if(!i.ignoreChain)return aP(i)&&i._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,a,s,l),aV(async()=>{try{await i.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,a,s,l)}catch(e){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainStart: ${e}`),i.raiseError)throw e}},i.awaitHandlers)})),new a2(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=tl(),a,i,n,s,o){return await Promise.all(this.handlers.map(a=>{if(!a.ignoreAgent)return aP(a)&&a._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),aV(async()=>{try{await a.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s,o)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleToolStart: ${e}`),a.raiseError)throw e}},a.awaitHandlers)})),new a4(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=tl(),a,i,n,s){return await Promise.all(this.handlers.map(a=>{if(!a.ignoreRetriever)return aP(a)&&a._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),aV(async()=>{try{await a.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleRetrieverStart: ${e}`),a.raiseError)throw e}},a.awaitHandlers)})),new a0(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,a,i){await Promise.all(this.handlers.map(a=>aV(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(e,t,r,this.tags,this.metadata)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${e}`),a.raiseError)throw e}},a.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){for(let r of(this.handlers=[],this.inheritableHandlers=[],e))this.addHandler(r,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(t=[],r=!0){let a=new e(this._parentRunId);for(let e of this.handlers){let t=this.inheritableHandlers.includes(e);a.addHandler(e,t)}for(let e of this.tags){let t=this.inheritableTags.includes(e);a.addTags([e],t)}for(let e of Object.keys(this.metadata)){let t=Object.keys(this.inheritableMetadata).includes(e);a.addMetadata({[e]:this.metadata[e]},t)}for(let e of t)a.handlers.filter(e=>"console_callback_handler"===e.name).some(t=>t.name===e.name)||a.addHandler(e,r);return a}static fromHandlers(e){class t extends tm{name=tl();constructor(){super(),Object.assign(this,e)}}let r=new this;return r.addHandler(new t),r}static configure(e,t,r,a,i,n,s){return this._configureSync(e,t,r,a,i,n,s)}static _configureSync(t,r,a,i,n,s,o){let l;(t||r)&&(Array.isArray(t)||!t?(l=new e).setHandlers(t?.map(a6)??[],!0):l=t,l=l.copy(Array.isArray(r)?r.map(a6):r?.handlers,!1));let u="true"===tp("LANGCHAIN_VERBOSE")||o?.verbose,d=aG.getTraceableRunTree(),c=d?.tracingEnabled??!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>"true"===tp(e));if(d?.tracingEnabled===!1&&l)for(let e of l.handlers.filter(e=>"langchain_tracer"===e.name))l.removeHandler(e);let h=c||(tp("LANGCHAIN_TRACING")??!1);if(u||h){if(l||(l=new e),u&&!l.handlers.some(e=>e.name===aB.prototype.name)){let e=new aB;l.addHandler(e,!0)}if(h&&!l.handlers.some(e=>"langchain_tracer"===e.name)&&c){let e=new aG;l.addHandler(e,!0)}c&&d&&void 0===l._parentRunId&&(l._parentRunId=d.id,l.handlers.find(e=>"langchain_tracer"===e.name)?.updateFromRunTree(d))}for(let{contextVar:t,inheritable:r=!0,handlerClass:a,envVar:i}of aK(aQ)||[]){let n,s=i&&"true"===tp(i)&&a,o=void 0!==t?aK(t):void 0;o&&tg(o)?n=o:s&&(n=new a({})),void 0!==n&&(l||(l=new e),l.handlers.some(e=>e.name===n.name)||l.addHandler(n,r))}(a||i)&&l&&(l.addTags(a??[]),l.addTags(i??[],!1)),(n||s)&&l&&(l.addMetadata(n??{}),l.addMetadata(s??{},!1));let p=o?.tracerInheritableMetadata,f=o?.tracerInheritableTags;return l&&(p||f)&&(l.handlers=l.handlers.map(e=>e instanceof aG?e.copyWithTracingConfig({metadata:p,tags:f}):e),l.inheritableHandlers=l.inheritableHandlers.map(e=>e instanceof aG?e.copyWithTracingConfig({metadata:p,tags:f}):e)),l}};function a6(e){return"name"in e?e:tm.fromMethods(e)}let a5=new class{getStore(){}run(e,t){return t()}enterWith(e){}},a3=Symbol.for("lc:child_config"),a8=new class{getInstance(){return tc()??a5}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[a3]}runWithConfig(e,t,r){let a,i=a9._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),n=this.getInstance(),s=n.getStore(),o=i?.getParentRunId(),l=i?.handlers?.find(e=>e?.name==="langchain_tracer");return l&&o?a=l.getRunTreeWithTracingConfig(o):r||(a=new aO({name:"<runnable_lambda>",tracingEnabled:!1})),a&&(a.extra={...a.extra,[a3]:e}),void 0!==s&&void 0!==s[td]&&(void 0===a&&(a={}),a[td]=s[td]),n.run(a,t)}initializeGlobalInstance(e){void 0===tc()&&(globalThis[tu]=e)}},a7=new Set(["api_key"]),ie=new Set(["string","number","boolean"]);async function it(e){return a9._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata,void 0,{tracerInheritableMetadata:e?function(e){let t=e.configurable??{},r=e.metadata??{},a={};for(let[e,i]of Object.entries(t))!e.startsWith("__")&&!Object.prototype.hasOwnProperty.call(r,e)&&!a7.has(e)&&ie.has(typeof i)&&(a[e]=i);return Object.keys(a).length>0?a:void 0}(e):void 0})}function ir(...e){let t={};for(let r of e.filter(e=>!!e))for(let e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){let a=t[e]??[];t[e]=[...new Set(a.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){let e=t.callbacks,a=r.callbacks;if(Array.isArray(a))if(e)if(Array.isArray(e))t.callbacks=e.concat(a);else{let r=e.copy();for(let e of a)r.addHandler(a6(e),!0);t.callbacks=r}else t.callbacks=a;else if(a)if(e)if(Array.isArray(e)){let r=a.copy();for(let t of e)r.addHandler(a6(t),!0);t.callbacks=r}else t.callbacks=new a9(a._parentRunId,{handlers:e.handlers.concat(a.handlers),inheritableHandlers:e.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(a.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(a.inheritableTags))),metadata:{...e.metadata,...a.metadata}});else t.callbacks=a}else t[e]=r[e]??t[e];return t}function ia(e){let t=a8.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:e,runName:a,...i}=t;r=Object.entries(i).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)}if(e&&(r=Object.entries(e).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)),r?.configurable&&"string"==typeof r.configurable.model&&r.metadata?.model===void 0&&(r.metadata||(r.metadata={}),r.metadata.model=r.configurable.model),void 0!==r.timeout){if(r.timeout<=0)throw Error("Timeout must be a positive number");let e=r.timeout,t=AbortSignal.timeout(e);r.metadata||(r.metadata={}),void 0===r.metadata.timeoutMs&&(r.metadata.timeoutMs=e),void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,t])):r.signal=t,delete r.timeout}return r}function ii(e={},{callbacks:t,maxConcurrency:r,recursionLimit:a,runName:i,configurable:n,runId:s}={}){let o=ia(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==a&&(o.recursionLimit=a),void 0!==r&&(o.maxConcurrency=r),void 0!==i&&(o.runName=i),void 0!==n&&(o.configurable={...o.configurable,...n}),void 0!==s&&delete o.runId,o}function is(e){if(e)return{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal,store:e.store}}async function io(e,t){let r;return void 0===t?e:Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,a)=>{r=()=>{a(il(t))},t.addEventListener("abort",r,{once:!0}),t.aborted&&a(il(t))})]).finally(()=>t.removeEventListener("abort",r))}function il(e){return e?.reason instanceof Error?e.reason:"string"==typeof e?.reason?Error(e.reason):Error("Aborted")}var iu=class e extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let e=await this.reader.read();if(e.done)return this.reader.releaseLock(),{done:!0,value:void 0};return{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async [Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let r=t.getReader();return new e({start:e=>(function t(){return r.read().then(({done:r,value:a})=>r?void e.close():(e.enqueue(a),t()))})(),cancel(){r.releaseLock()}})}static fromAsyncGenerator(t){return new e({async pull(e){let{value:r,done:a}=await t.next();a&&e.close(),e.enqueue(r)},async cancel(e){await t.return(e)}})}};function id(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(t){for(;;)if(0===t.length){let t=await e.next();for(let e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}})}var ic=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{a8.runWithConfig(is(e.config),async()=>{this.firstResult=this.signal?io(e.generator.next(),this.signal):e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(e=>t(void 0),r)},!0)})}async next(...e){return(this.signal?.throwIfAborted(),this.firstResultUsed)?a8.runWithConfig(is(this.config),this.signal?async()=>io(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async [Symbol.asyncDispose](){await this.return()}};async function ih(e,t,r,a,...i){let n=new ic({generator:t,startSetup:r,signal:a}),s=await n.setup;return{output:e(n,s,...i),setup:s}}let ip=Object.prototype.hasOwnProperty;function im(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function ig(e){let t,r=0,a=e.length;for(;r<a;){if((t=e.charCodeAt(r))>=48&&t<=57){r++;continue}return!1}return!0}function iy(e,t){let r=[e];for(let e in t){let a="object"==typeof t[e]?JSON.stringify(t[e],null,2):t[e];void 0!==a&&r.push(`${e}: ${a}`)}return r.join("\n")}var i_=class extends Error{constructor(e,t,r,a,i){super(iy(e,{name:t,index:r,operation:a,tree:i})),this.name=t,this.index=r,this.operation=a,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=iy(e,{name:t,index:r,operation:a,tree:i})}};let ib={add:function(e,t,r){if("__proto__"===t||"constructor"===t)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){if("__proto__"===t||"constructor"===t)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var a=e[t];return delete e[t],{newDocument:r,removed:a}},replace:function(e,t,r){if("__proto__"===t||"constructor"===t)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var a=e[t];return e[t]=this.value,{newDocument:r,removed:a}},move:function(e,t,r){let a=iw(r,this.path);a&&(a=im(a));let i=ix(r,{op:"remove",path:this.from}).removed;return ix(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:a}},copy:function(e,t,r){let a=iw(r,this.from);return ix(r,{op:"add",path:this.path,value:im(a)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:iT(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}};var iv={add:function(e,t,r){return ig(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){return{newDocument:r,removed:e.splice(t,1)[0]}},replace:function(e,t,r){var a=e[t];return e[t]=this.value,{newDocument:r,removed:a}},move:ib.move,copy:ib.copy,test:ib.test,_get:ib._get};function iw(e,t){if(""==t)return e;var r={op:"_get",path:t};return ix(e,r),r.value}function ix(e,t,r=!1,a=!0,i=!0,n=0){if(r&&("function"==typeof r?r(t,0,e,t.path):iS(t,0)),""===t.path){let a={newDocument:e};if("add"===t.op)return a.newDocument=t.value,a;if("replace"===t.op)return a.newDocument=t.value,a.removed=e,a;if("move"===t.op||"copy"===t.op)return a.newDocument=iw(e,t.from),"move"===t.op&&(a.removed=e),a;else if("test"===t.op){if(a.test=iT(e,t.value),!1===a.test)throw new i_("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a.newDocument=e,a}else if("remove"===t.op)return a.removed=e,a.newDocument=null,a;else if("_get"===t.op)return t.value=e,a;else if(!r)return a;else throw new i_("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",n,t,e)}{let s,o,l;a||(e=im(e));let u=(t.path||"").split("/"),d=e,c=1,h=u.length;for(o="function"==typeof r?r:iS;;){if((s=u[c])&&-1!=s.indexOf("~")&&(s=s.replace(/~1/g,"/").replace(/~0/g,"~")),i&&("__proto__"==s||"prototype"==s&&c>0&&"constructor"==u[c-1]))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(r&&void 0===l&&(void 0===d[s]?l=u.slice(0,c).join("/"):c==h-1&&(l=t.path),void 0!==l&&o(t,0,e,l)),c++,Array.isArray(d)){if("-"===s)s=d.length;else if(r&&!ig(s))throw new i_("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",n,t,e);else ig(s)&&(s=~~s);if(c>=h){if(r&&"add"===t.op&&s>d.length)throw new i_("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",n,t,e);let a=iv[t.op].call(t,d,s,e);if(!1===a.test)throw new i_("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a}}else if(c>=h){let r=ib[t.op].call(t,d,s,e);if(!1===r.test)throw new i_("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return r}if(d=d[s],r&&c<h&&(!d||"object"!=typeof d))throw new i_("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",n,t,e)}}}function ik(e,t,r,a=!0,i=!0){if(r&&!Array.isArray(t))throw new i_("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");a||(e=im(e));let n=Array(t.length);for(let a=0,s=t.length;a<s;a++)n[a]=ix(e,t[a],r,!0,i,a),e=n[a].newDocument;return n.newDocument=e,n}function iS(e,t,r,a){if("object"!=typeof e||null===e||Array.isArray(e))throw new i_("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(ib[e.op]){if("string"!=typeof e.path)throw new i_("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);else if(0!==e.path.indexOf("/")&&e.path.length>0)throw new i_('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);else if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new i_("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new i_("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&function e(t){if(void 0===t)return!0;if(t){if(Array.isArray(t)){for(let r=0,a=t.length;r<a;r++)if(e(t[r]))return!0}else if("object"==typeof t){let a=function(e){if(Array.isArray(e)){let t=Array(e.length);for(let e=0;e<t.length;e++)t[e]=""+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)ip.call(e,r)&&t.push(r);return t}(t),i=a.length;for(var r=0;r<i;r++)if(e(t[a[r]]))return!0}}return!1}(e.value))throw new i_("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);else if(r){if("add"==e.op){var i=e.path.split("/").length,n=a.split("/").length;if(i!==n+1&&i!==n)throw new i_("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==a)throw new i_("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var s=function(e,t,r){try{if(!Array.isArray(e))throw new i_("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)ik(im(t),im(e),r||!0);else{r=r||iS;for(var a=0;a<e.length;a++)r(e[a],a,t,void 0)}}catch(e){if(e instanceof i_)return e;throw e}}([{op:"_get",path:e.from,value:void 0}],r);if(s&&"OPERATION_PATH_UNRESOLVABLE"===s.name)throw new i_("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new i_("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function iT(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){var r,a,i,n=Array.isArray(e),s=Array.isArray(t);if(n&&s){if((a=e.length)!=t.length)return!1;for(r=a;0!=r--;)if(!iT(e[r],t[r]))return!1;return!0}if(n!=s)return!1;var o=Object.keys(e);if((a=o.length)!==Object.keys(t).length)return!1;for(r=a;0!=r--;)if(!t.hasOwnProperty(o[r]))return!1;for(r=a;0!=r--;)if(!iT(e[i=o[r]],t[i]))return!1;return!0}return e!=e&&t!=t}var iE=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=ik({},t);return new iA({ops:t,state:r[r.length-1].newDocument})}},iA=class e extends iE{state;constructor(e){super(e),this.state=e.state}concat(t){let r=this.ops.concat(t.ops),a=ik(this.state,t.ops);return new e({ops:r,state:a[a.length-1].newDocument})}static fromRunLogPatch(t){let r=ik({},t.ops);return new e({ops:t.ops,state:r[r.length-1].newDocument})}};let iI=e=>"log_stream_tracer"===e.name;async function iO(e,t){if("original"===t)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:r}=e;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||r?.input!==""?r.input:void 0}async function iC(e,t){let{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&r?.output!==void 0?r.output:r}var ij=class extends aN{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=iu.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new iE({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new iE({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;let r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};"streaming_events"===this._schemaFormat&&(r.inputs=await iO(e,this._schemaFormat)),await this.writer.write(new iE({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(void 0===t)return;let r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await iO(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await iC(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let a=new iE({ops:r});await this.writer.write(a)}finally{if(e.id===this.rootId){let t=new iE({ops:[{op:"replace",path:"/final_output",value:await iC(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let a,i=this.keyMapByRunId[e.id];if(void 0===i)return;if(void 0!==e.inputs.messages){var n;a=void 0!==(n=r?.chunk)&&void 0!==n.message?r?.chunk:new e9({id:`run-${e.id}`,content:t})}else a=t;let s=new iE({ops:[{op:"add",path:`/logs/${i}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${i}/streamed_output/-`,value:a}]});await this.writer.write(s)}},i$=class e{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}};function iP({name:e,serialized:t}){return void 0!==e?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}let iN=e=>"event_stream_tracer"===e.name;var iR=class extends aN{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(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=iu.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){let r=await t.next();if(r.done)return;let a=this.runInfoMap.get(e);if(void 0===a)return void(yield r.value);function i(e,t){return"llm"===e&&"string"==typeof t?new i$({text:t}):t}let n=this.tappedPromises.get(e);if(void 0===n){let s;n=new Promise(e=>{s=e}),this.tappedPromises.set(e,n);try{let n={event:`on_${a.runType}_stream`,run_id:e,name:a.name,tags:a.tags,metadata:a.metadata,data:{}};for await(let e of(await this.send({...n,data:{chunk:i(a.runType,r.value)}},a),yield r.value,t))"tool"!==a.runType&&"retriever"!==a.runType&&await this.send({...n,data:{chunk:i(a.runType,e)}},a),yield e}finally{s?.()}}else for await(let e of(yield r.value,t))yield e}async send(e,t){!this.readableStreamClosed&&this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let r=this.tappedPromises.get(e.run_id);void 0!==r?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=iP(e),r=void 0!==e.inputs.messages?"chat_model":"llm",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,a);let i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onLLMNewToken(e,t,r){let a,i,n=this.runInfoMap.get(e.id);if(void 0===n)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===n.runType)i="on_chat_model_stream",a=r?.chunk===void 0?new e9({content:t,id:`run-${e.id}`}):r.chunk.message;else if("llm"===n.runType)i="on_llm_stream",a=r?.chunk===void 0?new i$({text:t}):r.chunk;else throw Error(`Unexpected run type ${n.runType}`);await this.send({event:i,data:{chunk:a},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){let t,r,a=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===a)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let i=e.outputs?.generations;if("chat_model"===a.runType){for(let e of i??[]){if(void 0!==r)break;r=e[0]?.message}t="on_chat_model_end"}else if("llm"===a.runType)r={generations:i?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},t="on_llm_end";else throw Error(`onLLMEnd: Unexpected run type: ${a.runType}`);await this.sendEndEvent({event:t,data:{output:r,input:a.inputs},run_id:e.id,name:a.name,tags:a.tags,metadata:a.metadata},a)}async onChainStart(e){let t=iP(e),r=e.run_type??"chain",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(i={},a.inputs={}):void 0!==e.inputs.input?(i.input=e.inputs.input,a.inputs=e.inputs.input):(i.input=e.inputs,a.inputs=e.inputs),this.runInfoMap.set(e.id,a),await this.send({event:`on_${r}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,a=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:a};a.input&&1===Object.keys(a).length&&(i.input=a.input,t.inputs=a.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=iP(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=iP(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){let a=this.runInfoMap.get(r);if(void 0===a)throw Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:a.tags,metadata:a.metadata,data:t},a)}async finish(){Promise.all([...this.tappedPromises.values()]).finally(()=>{this.writer.close()})}};let iM=Object.prototype.toString,iz=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 iL(e,t,{min:r=0,allowInfinity:a=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${a?" or Infinity":""}.`);if(!a&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}var iU=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function iD(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function iB({error:e,attemptNumber:t,retriesConsumed:r,startTime:a,options:i}){let n,s=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof iU)throw s.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,l=i.maxRetryTime??1/0,u=Object.freeze({error:s,attemptNumber:t,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(u),0>=iD(a,l))throw s;let d=await i.shouldConsumeRetry(u),c=iD(a,l);if(c<=0||o<=0)throw s;if(s instanceof TypeError&&!function(e){if(!(e&&"[object Error]"===iM.call(e)&&"TypeError"===e.name&&"string"==typeof e.message))return!1;let{message:t,stack:r}=e;return"Load failed"===t?void 0===r||"__sentry_captured__"in e:!!t.startsWith("error sending request for url")||iz.has(t)}(s)){if(d)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(u))throw s;if(!d)return i.signal?.throwIfAborted(),!1;let h=Math.min((n=Math.max(1,r+1),Math.min(Math.round((i.randomize?Math.random()+1:1)*i.minTimeout*i.factor**(n-1)),i.maxTimeout)),c);return h>0&&await new Promise((e,t)=>{let r=()=>{clearTimeout(a),i.signal?.removeEventListener("abort",r),t(i.signal.reason)},a=setTimeout(()=>{i.signal?.removeEventListener("abort",r),e()},h);i.unref&&a.unref?.(),i.signal?.addEventListener("abort",r,{once:!0})}),i.signal?.throwIfAborted(),!0}async function iF(e,t={}){var r=(t={...t}).retries;if("number"==typeof r){if(r<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(void 0!==r)throw TypeError("Expected `retries` to be a number or Infinity.");if(Object.hasOwn(t,"forever"))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,iL("factor",t.factor,{min:0,allowInfinity:!1}),iL("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),iL("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),iL("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let a=0,i=0,n=performance.now();for(;!Number.isFinite(t.retries)||i<=t.retries;){a++;try{t.signal?.throwIfAborted();let r=await e(a);return t.signal?.throwIfAborted(),r}catch(e){await iB({error:e,attemptNumber:a,retriesConsumed:i,startTime:n,options:t})&&i++}}throw Error("Retry attempts exhausted without throwing an error.")}let iZ=[400,401,402,403,404,405,406,407,409],iH=e=>{if("object"!=typeof e||null===e)return;if("message"in e&&"string"==typeof e.message&&(e.message.startsWith("Cancel")||e.message.startsWith("AbortError"))||"name"in e&&"string"==typeof e.name&&"AbortError"===e.name||"code"in e&&"string"==typeof e.code&&"ECONNABORTED"===e.code)throw e;let t="response"in e&&"object"==typeof e.response&&null!==e.response&&"status"in e.response&&"number"==typeof e.response.status?e.response.status:void 0,r="status"in e&&"number"==typeof e.status?e.status:void 0,a=t??r;if(a&&iZ.includes(+a))throw e;if(("error"in e&&"object"==typeof e.error&&null!==e.error&&"code"in e.error&&"string"==typeof e.error.code?e.error.code:void 0)==="insufficient_quota"){let t=Error("message"in e&&"string"==typeof e.message?e.message:"Insufficient quota");throw t.name="InsufficientQuotaError",t}};var iq=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??iH;const t="default"in rF.default?rF.default.default:rF.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>iF(()=>e(...t).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{onFailedAttempt:({error:e})=>this.onFailedAttempt?.(e),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){if(e.signal){let a;return Promise.race([this.call(t,...r),new Promise((t,r)=>{a=()=>{r(il(e.signal))},e.signal?.addEventListener("abort",a,{once:!0})})]).finally(()=>{e.signal&&a&&e.signal.removeEventListener("abort",a)})}return this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}},iJ=class extends aN{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:r,onError:a}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=a}persistRun(e){return Promise.resolve()}async onRunCreate(e){!this.rootId&&(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function iG(e){return!!e&&e.lc_runnable}var iW=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags,a=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||a.some(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&a.every(e=>!this.excludeTags?.includes(e))),r}};function iV(e,t,r){function a(r,a){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:a,constr:s,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,a);let i=s.prototype,n=Object.keys(i);for(let e=0;e<n.length;e++){let t=n[e];t in r||(r[t]=i[t].bind(r))}}let i=r?.Parent??Object;class n extends i{}function s(e){var t;let i=r?.Parent?new n:this;for(let r of(a(i,e),(t=i._zod).deferred??(t.deferred=[]),i._zod.deferred))r();return i}return Object.defineProperty(n,"name",{value:e}),Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}Symbol("zod_brand");class iK extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(_=globalThis).__zod_globalConfig??(_.__zod_globalConfig={});let iQ=globalThis.__zod_globalConfig;function iY(e){return e&&Object.assign(iQ,e),iQ}function iX(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function i0(e,t){return"bigint"==typeof t?t.toString():t}function i1(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function i2(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}let i4=Symbol("evaluating");function i9(e,t,r){let a;Object.defineProperty(e,t,{get(){if(a!==i4)return void 0===a&&(a=i4,a=r()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function i6(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function i5(...e){let t={};for(let r of e)Object.assign(t,Object.getOwnPropertyDescriptors(r));return Object.defineProperties({},t)}let i3="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function i8(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let i7=i1(()=>{if(iQ.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function ne(e){if(!1===i8(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==i8(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}let nt=new Set(["string","number","symbol"]),nr=new Set(["string","number","bigint","boolean","symbol","undefined"]);function na(e,t,r){let a=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(a._zod.parent=e),a}function ni(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function nn(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function ns(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}let no={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},nl={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function nu(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function nd(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function nc(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function nh(e){return"string"==typeof e?e:e?.message}function np(e,t,r){let a=e.message?e.message:nh(e.inst?._zod.def?.error?.(e))??nh(t?.error?.(e))??nh(r.customError?.(e))??nh(r.localeError?.(e))??"Invalid input",{inst:i,continue:n,input:s,...o}=e;return o.path??(o.path=[]),o.message=a,t?.reportInput&&(o.input=s),o}function nf(...e){let[t,r,a]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:a}:{...t}}function nm(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function ng(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}e.s(["BIGINT_FORMAT_RANGES",0,nl,"Class",0,class{constructor(...e){}},"NUMBER_FORMAT_RANGES",0,no,"aborted",0,nu,"allowsEval",0,i7,"assert",0,function(e){},"assertEqual",0,function(e){return e},"assertIs",0,function(e){},"assertNever",0,function(e){throw Error("Unexpected value in exhaustive check")},"assertNotEqual",0,function(e){return e},"assignProp",0,i6,"base64ToUint8Array",0,nm,"base64urlToUint8Array",0,function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return nm(t+r)},"cached",0,i1,"captureStackTrace",0,i3,"cleanEnum",0,function(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])},"cleanRegex",0,i2,"clone",0,na,"cloneDef",0,function(e){return i5(e._zod.def)},"createTransparentProxy",0,function(e){let t;return new Proxy({},{get:(r,a,i)=>(t??(t=e()),Reflect.get(t,a,i)),set:(r,a,i,n)=>(t??(t=e()),Reflect.set(t,a,i,n)),has:(r,a)=>(t??(t=e()),Reflect.has(t,a)),deleteProperty:(r,a)=>(t??(t=e()),Reflect.deleteProperty(t,a)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,a)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,a)),defineProperty:(r,a,i)=>(t??(t=e()),Reflect.defineProperty(t,a,i))})},"defineLazy",0,i9,"esc",0,function(e){return JSON.stringify(e)},"escapeRegex",0,function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")},"explicitlyAborted",0,nd,"extend",0,function(e,t){if(!ne(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let r=e._zod.def.shape;for(let e in t)if(void 0!==Object.getOwnPropertyDescriptor(r,e))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let a=i5(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return i6(this,"shape",r),r}});return na(e,a)},"finalizeIssue",0,np,"floatSafeRemainder",0,function(e,t){let r=e/t,a=Math.round(r),i=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-a)<i?0:r-a},"getElementAtPath",0,function(e,t){return t?t.reduce((e,t)=>e?.[t],e):e},"getEnumValues",0,iX,"getLengthableOrigin",0,function(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"},"getParsedType",0,e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return"promise";if("u">typeof Map&&e instanceof Map)return"map";if("u">typeof Set&&e instanceof Set)return"set";if("u">typeof Date&&e instanceof Date)return"date";if("u">typeof File&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},"getSizableOrigin",0,function(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"},"hexToUint8Array",0,function(e){let t=e.replace(/^0x/,"");if(t.length%2!=0)throw Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)r[e/2]=Number.parseInt(t.slice(e,e+2),16);return r},"isObject",0,i8,"isPlainObject",0,ne,"issue",0,nf,"joinValues",0,function(e,t="|"){return e.map(e=>nn(e)).join(t)},"jsonStringifyReplacer",0,i0,"merge",0,function(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=i5(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return i6(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return na(e,r)},"mergeDefs",0,i5,"normalizeParams",0,ni,"nullish",0,function(e){return null==e},"numKeys",0,function(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t},"objectClone",0,function(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))},"omit",0,function(e,t){let r=e._zod.def,a=r.checks;if(a&&a.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=i5(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete a[e]}return i6(this,"shape",a),a},checks:[]});return na(e,i)},"optionalKeys",0,ns,"parsedType",0,function(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":if(null===e)return"null";if(Array.isArray(e))return"array";if(e&&Object.getPrototypeOf(e)!==Object.prototype&&"constructor"in e&&e.constructor)return e.constructor.name}return t},"partial",0,function(e,t,r){let a=t._zod.def.checks;if(a&&a.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let i=i5(t._zod.def,{get shape(){let a=t._zod.def.shape,i={...a};if(r)for(let t in r){if(!(t in a))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:a[t]}):a[t])}else for(let t in a)i[t]=e?new e({type:"optional",innerType:a[t]}):a[t];return i6(this,"shape",i),i},checks:[]});return na(t,i)},"pick",0,function(e,t){let r=e._zod.def,a=r.checks;if(a&&a.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=i5(e._zod.def,{get shape(){let e={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);t[a]&&(e[a]=r.shape[a])}return i6(this,"shape",e),e},checks:[]});return na(e,i)},"prefixIssues",0,nc,"primitiveTypes",0,nr,"promiseAllObject",0,function(e){let t=Object.keys(e);return Promise.all(t.map(t=>e[t])).then(e=>{let r={};for(let a=0;a<t.length;a++)r[t[a]]=e[a];return r})},"propertyKeyTypes",0,nt,"randomString",0,function(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let a=0;a<e;a++)r+=t[Math.floor(Math.random()*t.length)];return r},"required",0,function(e,t,r){let a=i5(t._zod.def,{get shape(){let a=t._zod.def.shape,i={...a};if(r)for(let t in r){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:a[t]}))}else for(let t in a)i[t]=new e({type:"nonoptional",innerType:a[t]});return i6(this,"shape",i),i}});return na(t,a)},"safeExtend",0,function(e,t){if(!ne(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=i5(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return i6(this,"shape",r),r}});return na(e,r)},"shallowClone",0,function(e){return ne(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e},"slugify",0,function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")},"stringifyPrimitive",0,nn,"uint8ArrayToBase64",0,ng,"uint8ArrayToBase64url",0,function(e){return ng(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},"uint8ArrayToHex",0,function(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")},"unwrapMessage",0,nh],922143);let ny=/^-?\d+n?$/,n_=/^-?\d+$/,nb=/^-?\d+(?:\.\d+)?$/,nv=iV("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),nw=((e,t)=>{nv.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[i,n]=no[t.format];e._zod.onattach.push(e=>{let a=e._zod.bag;a.format=t.format,a.minimum=i,a.maximum=n,r&&(a.pattern=n_)}),e._zod.check=s=>{let o=s.value;if(r){if(!Number.isInteger(o))return void s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?s.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):s.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}))}o<i&&s.issues.push({origin:"number",input:o,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),o>n&&s.issues.push({origin:"number",input:o,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}},iV("$ZodCheckStringFormat",(e,t)=>{var r,a;nv.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})})),nx=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,i0,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},nk=iV("$ZodError",nx),nS=iV("$ZodError",nx,{Parent:Error}),nT=(d=nS,c=nS,async(e,t,r,a)=>{let i=r?{...r,async:!0}:{async:!0},n=e._zod.run({value:t,issues:[]},i);if(n instanceof Promise&&(n=await n),n.issues.length){let e=new(a?.Err??c)(n.issues.map(e=>np(e,i,iY())));throw i3(e,a?.callee),e}return n.value}),nE=(h=nS,(e,t,r)=>{let a=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise)throw new iK;return i.issues.length?{success:!1,error:new(h??nk)(i.issues.map(e=>np(e,a,iY())))}:{success:!0,data:i.value}}),nA=(p=nS,async(e,t,r)=>{let a=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:t,issues:[]},a);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new p(i.issues.map(e=>np(e,a,iY())))}:{success:!0,data:i.value}}),nI={major:4,minor:4,patch:3},nO=iV("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=nI;let a=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&a.unshift(e),a))for(let r of t._zod.onattach)r(e);if(0===a.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let a,i=nu(e);for(let n of t){if(n._zod.def.when){if(nd(e)||!n._zod.def.when(e))continue}else if(i)continue;let t=e.issues.length,s=n._zod.check(e);if(s instanceof Promise&&r?.async===!1)throw new iK;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(i||(i=nu(e,t)))});else{if(e.issues.length===t)continue;i||(i=nu(e,t))}}return a?a.then(()=>e):e},r=(r,i,n)=>{if(nu(r))return r.aborted=!0,r;let s=t(i,a,n);if(s instanceof Promise){if(!1===n.async)throw new iK;return s.then(t=>e._zod.parse(t,n))}return e._zod.parse(s,n)};e._zod.run=(i,n)=>{if(n.skipChecks)return e._zod.parse(i,n);if("backward"===n.direction){let t=e._zod.parse({value:i.value,issues:[]},{...n,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,i,n)):r(t,i,n)}let s=e._zod.parse(i,n);if(s instanceof Promise){if(!1===n.async)throw new iK;return s.then(e=>t(e,a,n))}return t(s,a,n)}}i9(e,"~standard",()=>({validate:t=>{try{let r=nE(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return nA(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),nC=iV("$ZodString",(e,t)=>{var r;let a;nO.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(a=(r=e._zod.bag)?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*",RegExp(`^${a}$`)),e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}});(e,t)=>{nw.init(e,t),nC.init(e,t)};(e,t)=>{nO.init(e,t),e._zod.pattern=e._zod.bag.pattern??nb,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;let n="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...n?{received:n}:{}}),r}},(e,t)=>{nO.init(e,t),e._zod.pattern=ny,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(e){}return"bigint"==typeof r.value||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}};let nj=iV("$ZodNever",(e,t)=>{nO.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function n$(e,t,r,a,i,n){let s=r in a;if(e.issues.length){if(i&&n&&!s)return;t.issues.push(...nc(r,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}void 0===e.value?s&&(t.value[r]=void 0):t.value[r]=e.value}function nP(e,t,r,a){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;let i=e.filter(e=>!nu(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>np(e,a,iY())))}),t)}(e,t)=>{let r;nO.init(e,t);let a=Object.getOwnPropertyDescriptor(t,"shape");if(!a?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}let i=i1(()=>(function(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=ns(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}})(t));i9(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let a=e[t]._zod;if(a.values)for(let e of(r[t]??(r[t]=new Set),a.values))r[t].add(e)}return r});let n=t.catchall;e._zod.parse=(t,a)=>{r??(r=i.value);let s=t.value;if(!i8(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};let o=[],l=r.shape;for(let e of r.keys){let r=l[e],i="optional"===r._zod.optin,n="optional"===r._zod.optout,u=r._zod.run({value:s[e],issues:[]},a);u instanceof Promise?o.push(u.then(r=>n$(r,t,e,s,i,n))):n$(u,t,e,s,i,n)}return n?function(e,t,r,a,i,n){let s=[],o=i.keySet,l=i.catchall._zod,u=l.def.type,d="optional"===l.optin,c="optional"===l.optout;for(let i in t){if("__proto__"===i||o.has(i))continue;if("never"===u){s.push(i);continue}let n=l.run({value:t[i],issues:[]},a);n instanceof Promise?e.push(n.then(e=>n$(e,r,i,t,d,c))):n$(n,r,i,t,d,c)}return(s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:n}),e.length)?Promise.all(e).then(()=>r):r}(o,s,t,a,i.value,e):o.length?Promise.all(o).then(()=>t):t}},(e,t)=>{nO.init(e,t),i9(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),i9(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),i9(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),i9(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>i2(e.source)).join("|")})$`)}});let r=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(a,i)=>{if(r)return r(a,i);let n=!1,s=[];for(let e of t.options){let t=e._zod.run({value:a.value,issues:[]},i);if(t instanceof Promise)s.push(t),n=!0;else{if(0===t.issues.length)return t;s.push(t)}}return n?Promise.all(s).then(t=>nP(t,a,e,i)):nP(s,a,e,i)}};function nN(e,t){for(let r=e.length-1;r>=0;r--)if("optional"!==e[r]._zod[t])return r+1;return 0}function nR(e,t,r){e.issues.length&&t.issues.push(...nc(r,e.issues)),t.value[r]=e.value}function nM(e,t,r,a,i){for(let n=0;n<r.length;n++){let r=e[n],s=n<a.length;if(r.issues.length){if(!s&&n>=i){t.value.length=n;break}t.issues.push(...nc(n,r.issues))}t.value[n]=r.value}for(let e=t.value.length-1;e>=a.length;e--)if("optional"===r[e]._zod.optout&&void 0===t.value[e])t.value.length=e;else break;return t}(e,t)=>{nO.init(e,t);let r=t.items;e._zod.parse=(a,i)=>{let n=a.value;if(!Array.isArray(n))return a.issues.push({input:n,inst:e,expected:"tuple",code:"invalid_type"}),a;a.value=[];let s=[],o=nN(r,"optin"),l=nN(r,"optout");if(!t.rest){if(n.length<o)return a.issues.push({code:"too_small",minimum:o,inclusive:!0,input:n,inst:e,origin:"array"}),a;n.length>r.length&&a.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:n,inst:e,origin:"array"})}let u=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e]._zod.run({value:n[e],issues:[]},i);t instanceof Promise?s.push(t.then(t=>{u[e]=t})):u[e]=t}if(t.rest){let e=r.length-1;for(let o of n.slice(r.length)){e++;let r=t.rest._zod.run({value:o,issues:[]},i);r instanceof Promise?s.push(r.then(t=>nR(t,a,e))):nR(r,a,e)}}return s.length?Promise.all(s).then(()=>nM(u,a,r,n,l)):nM(u,a,r,n,l)}};function nz(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}(e,t)=>{nO.init(e,t),e._zod.optin="optional",e._zod.optout="optional",i9(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),i9(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${i2(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){let a=e.value,i=t.innerType._zod.run(e,r);return i instanceof Promise?i.then(e=>nz(e,a)):nz(i,a)}return void 0===e.value?e:t.innerType._zod.run(e,r)}};function nL(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}(e,t)=>{nO.init(e,t),i9(e._zod,"values",()=>t.in._zod.values),i9(e._zod,"optin",()=>t.in._zod.optin),i9(e._zod,"optout",()=>t.out._zod.optout),i9(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("backward"===r.direction){let a=t.out._zod.run(e,r);return a instanceof Promise?a.then(e=>nL(e,t.in,r)):nL(a,t.in,r)}let a=t.in._zod.run(e,r);return a instanceof Promise?a.then(e=>nL(e,t.out,r)):nL(a,t.out,r)}};Symbol("ZodOutput"),Symbol("ZodInput");(b=globalThis).__zod_globalRegistry??(b.__zod_globalRegistry=new class e{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];return this._map.set(e,r),r&&"object"==typeof r&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let a={...r,...this._map.get(e)};return Object.keys(a).length?a:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});let nU=globalThis.__zod_globalRegistry;function nD(e){if("object"!=typeof e||null===e||!("_zod"in e))return!1;let t=e._zod;return"object"==typeof t&&null!==t&&"def"in t}function nB(e){if("object"!=typeof e||null===e||!("_def"in e)||"_zod"in e)return!1;let t=e._def;return"object"==typeof t&&null!=t&&"typeName"in t}async function nF(e,t){if(nD(e))return await nT(e,t);if(nB(e))return await e.parseAsync(t);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function nZ(e){return!!nD(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"object"===e._zod.def.type||!1)}function nH(e){return!!nD(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"array"===e._zod.def.type||!1)}function nq(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}e.i(922143);let nJ=["*","_","`"];async function nG(e,t){let r=t?.backgroundColor??"white",a=t?.imageType??"png",i=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");void 0===r||/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`);let n=`https://mermaid.ink/img/${i}?bgColor=${r}&type=${a}`,s=await fetch(n);if(!s.ok)throw Error(`Failed to render the graph using the Mermaid.INK API.
|
|
43
43
|
Status code: ${s.status}
|
|
44
|
-
Status text: ${s.statusText}`);return await s.blob()}let nW=Symbol("Let zodToJsonSchema decide on which parser to use"),nV={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"},nK=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function nQ(e){if("openAi"!==e.target)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?nK(t,e.currentPath):t.join("/")}}function nY(e,t,r,a){a?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function nX(e,t,r,a,i){e[t]=r,nY(e,t,a,i)}(f=v||(v={})).assertEqual=e=>{},f.assertIs=function(e){},f.assertNever=function(e){throw Error()},f.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},f.getValidEnumValues=e=>{let t=f.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(let a of t)r[a]=e[a];return f.objectValues(r)},f.objectValues=e=>f.objectKeys(e).map(function(t){return e[t]}),f.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},f.find=(e,t)=>{for(let r of e)if(t(r))return r},f.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,f.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},f.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(w||(w={})).mergeShapes=(e,t)=>({...e,...t});let n0=v.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),n1=e=>{switch(typeof e){case"undefined":return n0.undefined;case"string":return n0.string;case"number":return Number.isNaN(e)?n0.nan:n0.number;case"boolean":return n0.boolean;case"function":return n0.function;case"bigint":return n0.bigint;case"symbol":return n0.symbol;case"object":if(Array.isArray(e))return n0.array;if(null===e)return n0.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return n0.promise;if("u">typeof Map&&e instanceof Map)return n0.map;if("u">typeof Set&&e instanceof Set)return n0.set;if("u">typeof Date&&e instanceof Date)return n0.date;return n0.object;default:return n0.unknown}};e.s(["ZodParsedType",0,n0,"getParsedType",0,n1,"objectUtil",0,w,"util",0,v],904783);let n2=v.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),n4=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class n6 extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(let i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(a);else if("invalid_return_type"===i.code)a(i.returnTypeError);else if("invalid_arguments"===i.code)a(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,a=0;for(;a<i.path.length;){let r=i.path[a];a===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof n6))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t=Object.create(null),r=[];for(let a of this.issues)if(a.path.length>0){let r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}n6.create=e=>new n6(e),e.s(["ZodError",0,n6,"ZodIssueCode",0,n2,"quotelessJson",0,n4],169790);let n5=(e,t)=>{let r;switch(e.code){case n2.invalid_type:r=e.received===n0.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case n2.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,v.jsonStringifyReplacer)}`;break;case n2.unrecognized_keys:r=`Unrecognized key(s) in object: ${v.joinValues(e.keys,", ")}`;break;case n2.invalid_union:r="Invalid input";break;case n2.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${v.joinValues(e.options)}`;break;case n2.invalid_enum_value:r=`Invalid enum value. Expected ${v.joinValues(e.options)}, received '${e.received}'`;break;case n2.invalid_arguments:r="Invalid function arguments";break;case n2.invalid_return_type:r="Invalid function return type";break;case n2.invalid_date:r="Invalid date";break;case n2.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:v.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case n2.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case n2.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case n2.custom:r="Invalid input";break;case n2.invalid_intersection_types:r="Intersection results could not be merged";break;case n2.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case n2.not_finite:r="Number must be finite";break;default:r=t.defaultError,v.assertNever(e)}return{message:r}},n9=n5;function n3(e){n9=e}function n8(){return n9}e.s(["getErrorMap",0,n8,"setErrorMap",0,n3],937904),(m=x||(x={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},m.toString=e=>"string"==typeof e?e:e?.message;let n7=e=>{let{data:t,path:r,errorMaps:a,issueData:i}=e,n=[...r,...i.path||[]],s={...i,path:n};if(void 0!==i.message)return{...i,path:n,message:i.message};let o="";for(let e of a.filter(e=>!!e).slice().reverse())o=e(s,{data:t,defaultError:o}).message;return{...i,path:n,message:o}},se=[];function st(e,t){let r=n8(),a=n7({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===n5?void 0:n5].filter(e=>!!e)});e.common.issues.push(a)}class sr{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let a of t){if("aborted"===a.status)return sa;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,a=await e.value;r.push({key:t,value:a})}return sr.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let a of t){let{key:t,value:i}=a;if("aborted"===t.status||"aborted"===i.status)return sa;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==i.value||a.alwaysSet)&&(r[t.value]=i.value)}return{status:e.value,value:r}}}let sa=Object.freeze({status:"aborted"}),si=e=>({status:"dirty",value:e}),sn=e=>({status:"valid",value:e}),ss=e=>"aborted"===e.status,so=e=>"dirty"===e.status,sl=e=>"valid"===e.status,su=e=>"u">typeof Promise&&e instanceof Promise;e.s(["DIRTY",0,si,"EMPTY_PATH",0,se,"INVALID",0,sa,"OK",0,sn,"ParseStatus",0,sr,"addIssueToContext",0,st,"isAborted",0,ss,"isAsync",0,su,"isDirty",0,so,"isValid",0,sl,"makeIssue",0,n7],665354);class sd{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let sc=(e,t)=>{if(sl(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new n6(e.common.issues);return this._error=t,this._error}}};function sh(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:a,description:i}=e;if(t&&(r||a))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:n}=e;return"invalid_enum_value"===t.code?{message:n??i.defaultError}:void 0===i.data?{message:n??a??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:n??r??i.defaultError}},description:i}}class sp{get description(){return this._def.description}_getType(e){return n1(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:n1(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new sr,ctx:{common:e.parent.common,data:e.data,parsedType:n1(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(su(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:n1(e)},a=this._parseSync({data:e,path:r.path,parent:r});return sc(r,a)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:n1(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return sl(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>sl(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:n1(e)},a=this._parse({data:e,path:r.path,parent:r});return sc(r,await (su(a)?a:Promise.resolve(a)))}refine(e,t){return this._refinement((r,a)=>{let i=e(r),n=()=>a.addIssue({code:n2.custom,..."string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(r):t});return"u">typeof Promise&&i instanceof Promise?i.then(e=>!!e||(n(),!1)):!!i||(n(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new s3({schema:this,typeName:k.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return s8.create(this,this._def)}nullable(){return s7.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return sH.create(this)}promise(){return s9.create(this,this._def)}or(e){return sJ.create([this,e],this._def)}and(e){return sV.create(this,e,this._def)}transform(e){return new s3({...sh(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new oe({...sh(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:k.ZodDefault})}brand(){return new oi({typeName:k.ZodBranded,type:this,...sh(this._def)})}catch(e){return new ot({...sh(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:k.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return on.create(this,e)}readonly(){return os.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let sf=/^c[^\s-]{8,}$/i,sm=/^[0-9a-z]+$/,sg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sy=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,s_=/^[a-z0-9_-]{21}$/i,sb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sv=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,sw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sx=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,sk=/^(?:(?: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])$/,sS=/^(([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]))$/,sE=/^(([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])$/,sT=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sA=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,sI="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",sO=RegExp(`^${sI}$`);function sC(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function sj(e){let t=`${sI}T${sC(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)}class sP extends sp{_parse(e){var t,r,a,i;let n;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==n0.string){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.string,received:t.parsedType}),sa}let s=new sr;for(let l of this._def.checks)if("min"===l.kind)e.data.length<l.value&&(st(n=this._getOrReturnCtx(e,n),{code:n2.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("max"===l.kind)e.data.length>l.value&&(st(n=this._getOrReturnCtx(e,n),{code:n2.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("length"===l.kind){let t=e.data.length>l.value,r=e.data.length<l.value;(t||r)&&(n=this._getOrReturnCtx(e,n),t?st(n,{code:n2.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):r&&st(n,{code:n2.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),s.dirty())}else if("email"===l.kind)sw.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"email",code:n2.invalid_string,message:l.message}),s.dirty());else if("emoji"===l.kind)o||(o=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),o.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"emoji",code:n2.invalid_string,message:l.message}),s.dirty());else if("uuid"===l.kind)sy.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"uuid",code:n2.invalid_string,message:l.message}),s.dirty());else if("nanoid"===l.kind)s_.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"nanoid",code:n2.invalid_string,message:l.message}),s.dirty());else if("cuid"===l.kind)sf.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"cuid",code:n2.invalid_string,message:l.message}),s.dirty());else if("cuid2"===l.kind)sm.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"cuid2",code:n2.invalid_string,message:l.message}),s.dirty());else if("ulid"===l.kind)sg.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"ulid",code:n2.invalid_string,message:l.message}),s.dirty());else if("url"===l.kind)try{new URL(e.data)}catch{st(n=this._getOrReturnCtx(e,n),{validation:"url",code:n2.invalid_string,message:l.message}),s.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"regex",code:n2.invalid_string,message:l.message}),s.dirty())):"trim"===l.kind?e.data=e.data.trim():"includes"===l.kind?e.data.includes(l.value,l.position)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),s.dirty()):"toLowerCase"===l.kind?e.data=e.data.toLowerCase():"toUpperCase"===l.kind?e.data=e.data.toUpperCase():"startsWith"===l.kind?e.data.startsWith(l.value)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:{startsWith:l.value},message:l.message}),s.dirty()):"endsWith"===l.kind?e.data.endsWith(l.value)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:{endsWith:l.value},message:l.message}),s.dirty()):"datetime"===l.kind?sj(l).test(e.data)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:"datetime",message:l.message}),s.dirty()):"date"===l.kind?sO.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:"date",message:l.message}),s.dirty()):"time"===l.kind?RegExp(`^${sC(l)}$`).test(e.data)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:"time",message:l.message}),s.dirty()):"duration"===l.kind?sv.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"duration",code:n2.invalid_string,message:l.message}),s.dirty()):"ip"===l.kind?(t=e.data,!(("v4"===(r=l.version)||!r)&&sx.test(t)||("v6"===r||!r)&&sS.test(t))&&1&&(st(n=this._getOrReturnCtx(e,n),{validation:"ip",code:n2.invalid_string,message:l.message}),s.dirty())):"jwt"===l.kind?!function(e,t){if(!sb.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(a));if("object"!=typeof i||null===i||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)return!1;return!0}catch{return!1}}(e.data,l.alg)&&(st(n=this._getOrReturnCtx(e,n),{validation:"jwt",code:n2.invalid_string,message:l.message}),s.dirty()):"cidr"===l.kind?(a=e.data,!(("v4"===(i=l.version)||!i)&&sk.test(a)||("v6"===i||!i)&&sE.test(a))&&1&&(st(n=this._getOrReturnCtx(e,n),{validation:"cidr",code:n2.invalid_string,message:l.message}),s.dirty())):"base64"===l.kind?sT.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"base64",code:n2.invalid_string,message:l.message}),s.dirty()):"base64url"===l.kind?sA.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"base64url",code:n2.invalid_string,message:l.message}),s.dirty()):v.assertNever(l);return{status:s.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:n2.invalid_string,...x.errToObj(r)})}_addCheck(e){return new sP({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...x.errToObj(e)})}url(e){return this._addCheck({kind:"url",...x.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...x.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...x.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...x.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...x.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...x.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...x.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...x.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...x.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...x.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...x.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...x.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...x.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...x.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...x.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...x.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...x.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...x.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...x.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...x.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...x.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...x.errToObj(t)})}nonempty(e){return this.min(1,x.errToObj(e))}trim(){return new sP({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new sP({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new sP({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}sP.create=e=>new sP({checks:[],typeName:k.ZodString,coerce:e?.coerce??!1,...sh(e)});class s$ extends sp{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==n0.number){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.number,received:t.parsedType}),sa}let r=new sr;for(let a of this._def.checks)"int"===a.kind?v.isInteger(e.data)||(st(t=this._getOrReturnCtx(e,t),{code:n2.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty()):"min"===a.kind?(a.inclusive?e.data<a.value:e.data<=a.value)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):"max"===a.kind?(a.inclusive?e.data>a.value:e.data>=a.value)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):"multipleOf"===a.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,i=r>a?r:a;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}(e.data,a.value)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(st(t=this._getOrReturnCtx(e,t),{code:n2.not_finite,message:a.message}),r.dirty()):v.assertNever(a);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,x.toString(t))}gt(e,t){return this.setLimit("min",e,!1,x.toString(t))}lte(e,t){return this.setLimit("max",e,!0,x.toString(t))}lt(e,t){return this.setLimit("max",e,!1,x.toString(t))}setLimit(e,t,r,a){return new s$({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:x.toString(a)}]})}_addCheck(e){return new s$({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:x.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:x.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:x.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&v.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value);return Number.isFinite(t)&&Number.isFinite(e)}}s$.create=e=>new s$({checks:[],typeName:k.ZodNumber,coerce:e?.coerce||!1,...sh(e)});class sN extends sp{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==n0.bigint)return this._getInvalidInput(e);let r=new sr;for(let a of this._def.checks)"min"===a.kind?(a.inclusive?e.data<a.value:e.data<=a.value)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):"max"===a.kind?(a.inclusive?e.data>a.value:e.data>=a.value)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):v.assertNever(a);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.bigint,received:t.parsedType}),sa}gte(e,t){return this.setLimit("min",e,!0,x.toString(t))}gt(e,t){return this.setLimit("min",e,!1,x.toString(t))}lte(e,t){return this.setLimit("max",e,!0,x.toString(t))}lt(e,t){return this.setLimit("max",e,!1,x.toString(t))}setLimit(e,t,r,a){return new sN({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:x.toString(a)}]})}_addCheck(e){return new sN({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:x.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}sN.create=e=>new sN({checks:[],typeName:k.ZodBigInt,coerce:e?.coerce??!1,...sh(e)});class sR extends sp{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==n0.boolean){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.boolean,received:t.parsedType}),sa}return sn(e.data)}}sR.create=e=>new sR({typeName:k.ZodBoolean,coerce:e?.coerce||!1,...sh(e)});class sM extends sp{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==n0.date){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.date,received:t.parsedType}),sa}if(Number.isNaN(e.data.getTime()))return st(this._getOrReturnCtx(e),{code:n2.invalid_date}),sa;let r=new sr;for(let a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):v.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new sM({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:x.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:x.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}sM.create=e=>new sM({checks:[],coerce:e?.coerce||!1,typeName:k.ZodDate,...sh(e)});class sL extends sp{_parse(e){if(this._getType(e)!==n0.symbol){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.symbol,received:t.parsedType}),sa}return sn(e.data)}}sL.create=e=>new sL({typeName:k.ZodSymbol,...sh(e)});class sz extends sp{_parse(e){if(this._getType(e)!==n0.undefined){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.undefined,received:t.parsedType}),sa}return sn(e.data)}}sz.create=e=>new sz({typeName:k.ZodUndefined,...sh(e)});class sU extends sp{_parse(e){if(this._getType(e)!==n0.null){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.null,received:t.parsedType}),sa}return sn(e.data)}}sU.create=e=>new sU({typeName:k.ZodNull,...sh(e)});class sB extends sp{constructor(){super(...arguments),this._any=!0}_parse(e){return sn(e.data)}}sB.create=e=>new sB({typeName:k.ZodAny,...sh(e)});class sD extends sp{constructor(){super(...arguments),this._unknown=!0}_parse(e){return sn(e.data)}}sD.create=e=>new sD({typeName:k.ZodUnknown,...sh(e)});class sF extends sp{_parse(e){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.never,received:t.parsedType}),sa}}sF.create=e=>new sF({typeName:k.ZodNever,...sh(e)});class sZ extends sp{_parse(e){if(this._getType(e)!==n0.undefined){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.void,received:t.parsedType}),sa}return sn(e.data)}}sZ.create=e=>new sZ({typeName:k.ZodVoid,...sh(e)});class sH extends sp{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==n0.array)return st(t,{code:n2.invalid_type,expected:n0.array,received:t.parsedType}),sa;if(null!==a.exactLength){let e=t.data.length>a.exactLength.value,i=t.data.length<a.exactLength.value;(e||i)&&(st(t,{code:e?n2.too_big:n2.too_small,minimum:i?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(st(t,{code:n2.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(st(t,{code:n2.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new sd(t,e,t.path,r)))).then(e=>sr.mergeArray(r,e));let i=[...t.data].map((e,r)=>a.type._parseSync(new sd(t,e,t.path,r)));return sr.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new sH({...this._def,minLength:{value:e,message:x.toString(t)}})}max(e,t){return new sH({...this._def,maxLength:{value:e,message:x.toString(t)}})}length(e,t){return new sH({...this._def,exactLength:{value:e,message:x.toString(t)}})}nonempty(e){return this.min(1,e)}}sH.create=(e,t)=>new sH({type:e,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...sh(t)});class sq extends sp{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=v.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==n0.object){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.object,received:t.parsedType}),sa}let{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),n=[];if(!(this._def.catchall instanceof sF&&"strip"===this._def.unknownKeys))for(let e in r.data)i.includes(e)||n.push(e);let s=[];for(let e of i){let t=a[e],i=r.data[e];s.push({key:{status:"valid",value:e},value:t._parse(new sd(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof sF){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of n)s.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)n.length>0&&(st(r,{code:n2.unrecognized_keys,keys:n}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of n){let a=r.data[t];s.push({key:{status:"valid",value:t},value:e._parse(new sd(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of s){let r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>sr.mergeObjectSync(t,e)):sr.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return x.errToObj,new sq({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:x.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new sq({...this._def,unknownKeys:"strip"})}passthrough(){return new sq({...this._def,unknownKeys:"passthrough"})}extend(e){return new sq({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new sq({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new sq({...this._def,catchall:e})}pick(e){let t={};for(let r of v.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new sq({...this._def,shape:()=>t})}omit(e){let t={};for(let r of v.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new sq({...this._def,shape:()=>t})}deepPartial(){return function e(t){if(t instanceof sq){let r={};for(let a in t.shape){let i=t.shape[a];r[a]=s8.create(e(i))}return new sq({...t._def,shape:()=>r})}if(t instanceof sH)return new sH({...t._def,type:e(t.element)});if(t instanceof s8)return s8.create(e(t.unwrap()));if(t instanceof s7)return s7.create(e(t.unwrap()));if(t instanceof sK)return sK.create(t.items.map(t=>e(t)));else return t}(this)}partial(e){let t={};for(let r of v.objectKeys(this.shape)){let a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new sq({...this._def,shape:()=>t})}required(e){let t={};for(let r of v.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof s8;)e=e._def.innerType;t[r]=e}return new sq({...this._def,shape:()=>t})}keyof(){return s4(v.objectKeys(this.shape))}}sq.create=(e,t)=>new sq({shape:()=>e,unknownKeys:"strip",catchall:sF.create(),typeName:k.ZodObject,...sh(t)}),sq.strictCreate=(e,t)=>new sq({shape:()=>e,unknownKeys:"strict",catchall:sF.create(),typeName:k.ZodObject,...sh(t)}),sq.lazycreate=(e,t)=>new sq({shape:e,unknownKeys:"strip",catchall:sF.create(),typeName:k.ZodObject,...sh(t)});class sJ extends sp{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new n6(e.ctx.common.issues));return st(t,{code:n2.invalid_union,unionErrors:r}),sa});{let e,a=[];for(let i of r){let r={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=a.map(e=>new n6(e));return st(t,{code:n2.invalid_union,unionErrors:i}),sa}}get options(){return this._def.options}}sJ.create=(e,t)=>new sJ({options:e,typeName:k.ZodUnion,...sh(t)});let sG=e=>{if(e instanceof s1)return sG(e.schema);if(e instanceof s3)return sG(e.innerType());if(e instanceof s2)return[e.value];if(e instanceof s6)return e.options;if(e instanceof s5)return v.objectValues(e.enum);else if(e instanceof oe)return sG(e._def.innerType);else if(e instanceof sz)return[void 0];else if(e instanceof sU)return[null];else if(e instanceof s8)return[void 0,...sG(e.unwrap())];else if(e instanceof s7)return[null,...sG(e.unwrap())];else if(e instanceof oi)return sG(e.unwrap());else if(e instanceof os)return sG(e.unwrap());else if(e instanceof ot)return sG(e._def.innerType);else return[]};class sW extends sp{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==n0.object)return st(t,{code:n2.invalid_type,expected:n0.object,received:t.parsedType}),sa;let r=this.discriminator,a=t.data[r],i=this.optionsMap.get(a);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(st(t,{code:n2.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),sa)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let a=new Map;for(let r of t){let t=sG(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of t){if(a.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);a.set(i,r)}}return new sW({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...sh(r)})}}class sV extends sp{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),a=(e,a)=>{if(ss(e)||ss(a))return sa;let i=function e(t,r){let a=n1(t),i=n1(r);if(t===r)return{valid:!0,data:t};if(a===n0.object&&i===n0.object){let a=v.objectKeys(r),i=v.objectKeys(t).filter(e=>-1!==a.indexOf(e)),n={...t,...r};for(let a of i){let i=e(t[a],r[a]);if(!i.valid)return{valid:!1};n[a]=i.data}return{valid:!0,data:n}}if(a===n0.array&&i===n0.array){if(t.length!==r.length)return{valid:!1};let a=[];for(let i=0;i<t.length;i++){let n=e(t[i],r[i]);if(!n.valid)return{valid:!1};a.push(n.data)}return{valid:!0,data:a}}if(a===n0.date&&i===n0.date&&+t==+r)return{valid:!0,data:t};return{valid:!1}}(e.value,a.value);return i.valid?((so(e)||so(a))&&t.dirty(),{status:t.value,value:i.data}):(st(r,{code:n2.invalid_intersection_types}),sa)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>a(e,t)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}sV.create=(e,t,r)=>new sV({left:e,right:t,typeName:k.ZodIntersection,...sh(r)});class sK extends sp{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==n0.array)return st(r,{code:n2.invalid_type,expected:n0.array,received:r.parsedType}),sa;if(r.data.length<this._def.items.length)return st(r,{code:n2.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),sa;!this._def.rest&&r.data.length>this._def.items.length&&(st(r,{code:n2.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...r.data].map((e,t)=>{let a=this._def.items[t]||this._def.rest;return a?a._parse(new sd(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>sr.mergeArray(t,e)):sr.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new sK({...this._def,rest:e})}}sK.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new sK({items:e,typeName:k.ZodTuple,rest:null,...sh(t)})};class sQ extends sp{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==n0.object)return st(r,{code:n2.invalid_type,expected:n0.object,received:r.parsedType}),sa;let a=[],i=this._def.keyType,n=this._def.valueType;for(let e in r.data)a.push({key:i._parse(new sd(r,e,r.path,e)),value:n._parse(new sd(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?sr.mergeObjectAsync(t,a):sr.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new sQ(t instanceof sp?{keyType:e,valueType:t,typeName:k.ZodRecord,...sh(r)}:{keyType:sP.create(),valueType:e,typeName:k.ZodRecord,...sh(t)})}}class sY extends sp{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==n0.map)return st(r,{code:n2.invalid_type,expected:n0.map,received:r.parsedType}),sa;let a=this._def.keyType,i=this._def.valueType,n=[...r.data.entries()].map(([e,t],n)=>({key:a._parse(new sd(r,e,r.path,[n,"key"])),value:i._parse(new sd(r,t,r.path,[n,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of n){let a=await r.key,i=await r.value;if("aborted"===a.status||"aborted"===i.status)return sa;("dirty"===a.status||"dirty"===i.status)&&t.dirty(),e.set(a.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of n){let a=r.key,i=r.value;if("aborted"===a.status||"aborted"===i.status)return sa;("dirty"===a.status||"dirty"===i.status)&&t.dirty(),e.set(a.value,i.value)}return{status:t.value,value:e}}}}sY.create=(e,t,r)=>new sY({valueType:t,keyType:e,typeName:k.ZodMap,...sh(r)});class sX extends sp{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==n0.set)return st(r,{code:n2.invalid_type,expected:n0.set,received:r.parsedType}),sa;let a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(st(r,{code:n2.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(st(r,{code:n2.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());let i=this._def.valueType;function n(e){let r=new Set;for(let a of e){if("aborted"===a.status)return sa;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}let s=[...r.data.values()].map((e,t)=>i._parse(new sd(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>n(e)):n(s)}min(e,t){return new sX({...this._def,minSize:{value:e,message:x.toString(t)}})}max(e,t){return new sX({...this._def,maxSize:{value:e,message:x.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}sX.create=(e,t)=>new sX({valueType:e,minSize:null,maxSize:null,typeName:k.ZodSet,...sh(t)});class s0 extends sp{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==n0.function)return st(t,{code:n2.invalid_type,expected:n0.function,received:t.parsedType}),sa;function r(e,r){return n7({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n8(),n5].filter(e=>!!e),issueData:{code:n2.invalid_arguments,argumentsError:r}})}function a(e,r){return n7({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n8(),n5].filter(e=>!!e),issueData:{code:n2.invalid_return_type,returnTypeError:r}})}let i={errorMap:t.common.contextualErrorMap},n=t.data;if(this._def.returns instanceof s9){let e=this;return sn(async function(...t){let s=new n6([]),o=await e._def.args.parseAsync(t,i).catch(e=>{throw s.addIssue(r(t,e)),s}),l=await Reflect.apply(n,this,o);return await e._def.returns._def.type.parseAsync(l,i).catch(e=>{throw s.addIssue(a(l,e)),s})})}{let e=this;return sn(function(...t){let s=e._def.args.safeParse(t,i);if(!s.success)throw new n6([r(t,s.error)]);let o=Reflect.apply(n,this,s.data),l=e._def.returns.safeParse(o,i);if(!l.success)throw new n6([a(o,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new s0({...this._def,args:sK.create(e).rest(sD.create())})}returns(e){return new s0({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new s0({args:e||sK.create([]).rest(sD.create()),returns:t||sD.create(),typeName:k.ZodFunction,...sh(r)})}}class s1 extends sp{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}s1.create=(e,t)=>new s1({getter:e,typeName:k.ZodLazy,...sh(t)});class s2 extends sp{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return st(t,{received:t.data,code:n2.invalid_literal,expected:this._def.value}),sa}return{status:"valid",value:e.data}}get value(){return this._def.value}}function s4(e,t){return new s6({values:e,typeName:k.ZodEnum,...sh(t)})}s2.create=(e,t)=>new s2({value:e,typeName:k.ZodLiteral,...sh(t)});class s6 extends sp{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return st(t,{expected:v.joinValues(r),received:t.parsedType,code:n2.invalid_type}),sa}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return st(t,{received:t.data,code:n2.invalid_enum_value,options:r}),sa}return sn(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return s6.create(e,{...this._def,...t})}exclude(e,t=this._def){return s6.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}s6.create=s4;class s5 extends sp{_parse(e){let t=v.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==n0.string&&r.parsedType!==n0.number){let e=v.objectValues(t);return st(r,{expected:v.joinValues(e),received:r.parsedType,code:n2.invalid_type}),sa}if(this._cache||(this._cache=new Set(v.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=v.objectValues(t);return st(r,{received:r.data,code:n2.invalid_enum_value,options:e}),sa}return sn(e.data)}get enum(){return this._def.values}}s5.create=(e,t)=>new s5({values:e,typeName:k.ZodNativeEnum,...sh(t)});class s9 extends sp{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==n0.promise&&!1===t.common.async?(st(t,{code:n2.invalid_type,expected:n0.promise,received:t.parsedType}),sa):sn((t.parsedType===n0.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}s9.create=(e,t)=>new s9({type:e,typeName:k.ZodPromise,...sh(t)});class s3 extends sp{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,i={addIssue:e=>{st(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===a.type){let e=a.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return sa;let a=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===a.status?sa:"dirty"===a.status||"dirty"===t.value?si(a.value):a});{if("aborted"===t.value)return sa;let a=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===a.status?sa:"dirty"===a.status||"dirty"===t.value?si(a.value):a}}if("refinement"===a.type){let e=e=>{let t=a.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?sa:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?sa:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}}if("transform"===a.type)if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>sl(e)?Promise.resolve(a.transform(e.value,i)).then(e=>({status:t.value,value:e})):sa);else{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!sl(e))return sa;let n=a.transform(e.value,i);if(n instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}v.assertNever(a)}}s3.create=(e,t,r)=>new s3({schema:e,typeName:k.ZodEffects,effect:t,...sh(r)}),s3.createWithPreprocess=(e,t,r)=>new s3({schema:t,effect:{type:"preprocess",transform:e},typeName:k.ZodEffects,...sh(r)});class s8 extends sp{_parse(e){return this._getType(e)===n0.undefined?sn(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}s8.create=(e,t)=>new s8({innerType:e,typeName:k.ZodOptional,...sh(t)});class s7 extends sp{_parse(e){return this._getType(e)===n0.null?sn(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}s7.create=(e,t)=>new s7({innerType:e,typeName:k.ZodNullable,...sh(t)});class oe extends sp{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===n0.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}oe.create=(e,t)=>new oe({innerType:e,typeName:k.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...sh(t)});class ot extends sp{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return su(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new n6(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new n6(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ot.create=(e,t)=>new ot({innerType:e,typeName:k.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...sh(t)});class or extends sp{_parse(e){if(this._getType(e)!==n0.nan){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.nan,received:t.parsedType}),sa}return{status:"valid",value:e.data}}}or.create=e=>new or({typeName:k.ZodNaN,...sh(e)});let oa=Symbol("zod_brand");class oi extends sp{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class on extends sp{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?sa:"dirty"===e.status?(t.dirty(),si(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?sa:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new on({in:e,out:t,typeName:k.ZodPipeline})}}class os extends sp{_parse(e){let t=this._def.innerType._parse(e),r=e=>(sl(e)&&(e.value=Object.freeze(e.value)),e);return su(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function oo(e,t){let r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function ol(e,t={},r){return e?sB.create().superRefine((a,i)=>{let n=e(a);if(n instanceof Promise)return n.then(e=>{if(!e){let e=oo(t,a),n=e.fatal??r??!0;i.addIssue({code:"custom",...e,fatal:n})}});if(!n){let e=oo(t,a),n=e.fatal??r??!0;i.addIssue({code:"custom",...e,fatal:n})}}):sB.create()}os.create=(e,t)=>new os({innerType:e,typeName:k.ZodReadonly,...sh(t)});let ou={object:sq.lazycreate};(g=k||(k={})).ZodString="ZodString",g.ZodNumber="ZodNumber",g.ZodNaN="ZodNaN",g.ZodBigInt="ZodBigInt",g.ZodBoolean="ZodBoolean",g.ZodDate="ZodDate",g.ZodSymbol="ZodSymbol",g.ZodUndefined="ZodUndefined",g.ZodNull="ZodNull",g.ZodAny="ZodAny",g.ZodUnknown="ZodUnknown",g.ZodNever="ZodNever",g.ZodVoid="ZodVoid",g.ZodArray="ZodArray",g.ZodObject="ZodObject",g.ZodUnion="ZodUnion",g.ZodDiscriminatedUnion="ZodDiscriminatedUnion",g.ZodIntersection="ZodIntersection",g.ZodTuple="ZodTuple",g.ZodRecord="ZodRecord",g.ZodMap="ZodMap",g.ZodSet="ZodSet",g.ZodFunction="ZodFunction",g.ZodLazy="ZodLazy",g.ZodLiteral="ZodLiteral",g.ZodEnum="ZodEnum",g.ZodEffects="ZodEffects",g.ZodNativeEnum="ZodNativeEnum",g.ZodOptional="ZodOptional",g.ZodNullable="ZodNullable",g.ZodDefault="ZodDefault",g.ZodCatch="ZodCatch",g.ZodPromise="ZodPromise",g.ZodBranded="ZodBranded",g.ZodPipeline="ZodPipeline",g.ZodReadonly="ZodReadonly";let od=(e,t={message:`Input not instance of ${e.name}`})=>ol(t=>t instanceof e,t),oc=sP.create,oh=s$.create,op=or.create,of=sN.create,om=sR.create,og=sM.create,oy=sL.create,o_=sz.create,ob=sU.create,ov=sB.create,ow=sD.create,ox=sF.create,ok=sZ.create,oS=sH.create,oE=sq.create,oT=sq.strictCreate,oA=sJ.create,oI=sW.create,oO=sV.create,oC=sK.create,oj=sQ.create,oP=sY.create,o$=sX.create,oN=s0.create,oR=s1.create,oM=s2.create,oL=s6.create,oz=s5.create,oU=s9.create,oB=s3.create,oD=s8.create,oF=s7.create,oZ=s3.createWithPreprocess,oH=on.create,oq=()=>oc().optional(),oJ=()=>oh().optional(),oG=()=>om().optional(),oW={string:e=>sP.create({...e,coerce:!0}),number:e=>s$.create({...e,coerce:!0}),boolean:e=>sR.create({...e,coerce:!0}),bigint:e=>sN.create({...e,coerce:!0}),date:e=>sM.create({...e,coerce:!0})};function oV(e,t){return ls(e.type._def,t)}e.s(["BRAND",0,oa,"NEVER",0,sa,"Schema",0,sp,"ZodAny",0,sB,"ZodArray",0,sH,"ZodBigInt",0,sN,"ZodBoolean",0,sR,"ZodBranded",0,oi,"ZodCatch",0,ot,"ZodDate",0,sM,"ZodDefault",0,oe,"ZodDiscriminatedUnion",0,sW,"ZodEffects",0,s3,"ZodEnum",0,s6,"ZodFirstPartyTypeKind",0,k,"ZodFunction",0,s0,"ZodIntersection",0,sV,"ZodLazy",0,s1,"ZodLiteral",0,s2,"ZodMap",0,sY,"ZodNaN",0,or,"ZodNativeEnum",0,s5,"ZodNever",0,sF,"ZodNull",0,sU,"ZodNullable",0,s7,"ZodNumber",0,s$,"ZodObject",0,sq,"ZodOptional",0,s8,"ZodPipeline",0,on,"ZodPromise",0,s9,"ZodReadonly",0,os,"ZodRecord",0,sQ,"ZodSchema",0,sp,"ZodSet",0,sX,"ZodString",0,sP,"ZodSymbol",0,sL,"ZodTransformer",0,s3,"ZodTuple",0,sK,"ZodType",0,sp,"ZodUndefined",0,sz,"ZodUnion",0,sJ,"ZodUnknown",0,sD,"ZodVoid",0,sZ,"any",0,ov,"array",0,oS,"bigint",0,of,"boolean",0,om,"coerce",0,oW,"custom",0,ol,"date",0,og,"datetimeRegex",0,sj,"discriminatedUnion",0,oI,"effect",0,oB,"enum",0,oL,"function",0,oN,"instanceof",0,od,"intersection",0,oO,"late",0,ou,"lazy",0,oR,"literal",0,oM,"map",0,oP,"nan",0,op,"nativeEnum",0,oz,"never",0,ox,"null",0,ob,"nullable",0,oF,"number",0,oh,"object",0,oE,"oboolean",0,oG,"onumber",0,oJ,"optional",0,oD,"ostring",0,oq,"pipeline",0,oH,"preprocess",0,oZ,"promise",0,oU,"record",0,oj,"set",0,o$,"strictObject",0,oT,"string",0,oc,"symbol",0,oy,"transformer",0,oB,"tuple",0,oC,"undefined",0,o_,"union",0,oA,"unknown",0,ow,"void",0,ok],965638);let oK=/^[cC][^\s-]{8,}$/,oQ=/^[0-9a-z]+$/,oY=/^[0-9A-HJKMNP-TV-Z]{26}$/,oX=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,o0=()=>(void 0===u&&(u=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),u),o1=/^(?:(?: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])$/,o2=/^(([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])$/,o4=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,o6=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,o5=/^[a-zA-Z0-9_-]{21}$/,o9=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function o3(e,t){let r={type:"string"};if(e.checks)for(let a of e.checks)switch(a.kind){case"min":nX(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t);break;case"max":nX(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"email":switch(t.emailStrategy){case"format:email":le(r,"email",a.message,t);break;case"format:idn-email":le(r,"idn-email",a.message,t);break;case"pattern:zod":lt(r,oX,a.message,t)}break;case"url":le(r,"uri",a.message,t);break;case"uuid":le(r,"uuid",a.message,t);break;case"regex":lt(r,a.regex,a.message,t);break;case"cuid":lt(r,oK,a.message,t);break;case"cuid2":lt(r,oQ,a.message,t);break;case"startsWith":lt(r,RegExp(`^${o8(a.value,t)}`),a.message,t);break;case"endsWith":lt(r,RegExp(`${o8(a.value,t)}$`),a.message,t);break;case"datetime":le(r,"date-time",a.message,t);break;case"date":le(r,"date",a.message,t);break;case"time":le(r,"time",a.message,t);break;case"duration":le(r,"duration",a.message,t);break;case"length":nX(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t),nX(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"includes":lt(r,RegExp(o8(a.value,t)),a.message,t);break;case"ip":"v6"!==a.version&&le(r,"ipv4",a.message,t),"v4"!==a.version&&le(r,"ipv6",a.message,t);break;case"base64url":lt(r,o6,a.message,t);break;case"jwt":lt(r,o9,a.message,t);break;case"cidr":"v6"!==a.version&<(r,o1,a.message,t),"v4"!==a.version&<(r,o2,a.message,t);break;case"emoji":lt(r,o0(),a.message,t);break;case"ulid":lt(r,oY,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":le(r,"binary",a.message,t);break;case"contentEncoding:base64":nX(r,"contentEncoding","base64",a.message,t);break;case"pattern:zod":lt(r,o4,a.message,t)}break;case"nanoid":lt(r,o5,a.message,t)}return r}function o8(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)o7.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}let o7=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function le(e,t,r,a){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&a.errorMessages&&{errorMessage:{format:r}}})):nX(e,"format",t,r,a)}function lt(e,t,r,a){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:lr(t,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):nX(e,"pattern",lr(t,a),r,a)}function lr(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=r.i?e.source.toLowerCase():e.source,i="",n=!1,s=!1,o=!1;for(let e=0;e<a.length;e++){if(n){i+=a[e],n=!1;continue}if(r.i){if(s){if(a[e].match(/[a-z]/)){o?(i+=a[e],i+=`${a[e-2]}-${a[e]}`.toUpperCase(),o=!1):"-"===a[e+1]&&a[e+2]?.match(/[a-z]/)?(i+=a[e],o=!0):i+=`${a[e]}${a[e].toUpperCase()}`;continue}}else if(a[e].match(/[a-z]/)){i+=`[${a[e]}${a[e].toUpperCase()}]`;continue}}if(r.m){if("^"===a[e]){i+=`(^|(?<=[\r
|
|
44
|
+
Status text: ${s.statusText}`);return await s.blob()}let nW=Symbol("Let zodToJsonSchema decide on which parser to use"),nV={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"},nK=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function nQ(e){if("openAi"!==e.target)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?nK(t,e.currentPath):t.join("/")}}function nY(e,t,r,a){a?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function nX(e,t,r,a,i){e[t]=r,nY(e,t,a,i)}(f=v||(v={})).assertEqual=e=>{},f.assertIs=function(e){},f.assertNever=function(e){throw Error()},f.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},f.getValidEnumValues=e=>{let t=f.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(let a of t)r[a]=e[a];return f.objectValues(r)},f.objectValues=e=>f.objectKeys(e).map(function(t){return e[t]}),f.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},f.find=(e,t)=>{for(let r of e)if(t(r))return r},f.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,f.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},f.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(w||(w={})).mergeShapes=(e,t)=>({...e,...t});let n0=v.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),n1=e=>{switch(typeof e){case"undefined":return n0.undefined;case"string":return n0.string;case"number":return Number.isNaN(e)?n0.nan:n0.number;case"boolean":return n0.boolean;case"function":return n0.function;case"bigint":return n0.bigint;case"symbol":return n0.symbol;case"object":if(Array.isArray(e))return n0.array;if(null===e)return n0.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return n0.promise;if("u">typeof Map&&e instanceof Map)return n0.map;if("u">typeof Set&&e instanceof Set)return n0.set;if("u">typeof Date&&e instanceof Date)return n0.date;return n0.object;default:return n0.unknown}};e.s(["ZodParsedType",0,n0,"getParsedType",0,n1,"objectUtil",0,w,"util",0,v],904783);let n2=v.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),n4=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class n9 extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(let i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(a);else if("invalid_return_type"===i.code)a(i.returnTypeError);else if("invalid_arguments"===i.code)a(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,a=0;for(;a<i.path.length;){let r=i.path[a];a===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof n9))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t=Object.create(null),r=[];for(let a of this.issues)if(a.path.length>0){let r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}n9.create=e=>new n9(e),e.s(["ZodError",0,n9,"ZodIssueCode",0,n2,"quotelessJson",0,n4],169790);let n6=(e,t)=>{let r;switch(e.code){case n2.invalid_type:r=e.received===n0.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case n2.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,v.jsonStringifyReplacer)}`;break;case n2.unrecognized_keys:r=`Unrecognized key(s) in object: ${v.joinValues(e.keys,", ")}`;break;case n2.invalid_union:r="Invalid input";break;case n2.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${v.joinValues(e.options)}`;break;case n2.invalid_enum_value:r=`Invalid enum value. Expected ${v.joinValues(e.options)}, received '${e.received}'`;break;case n2.invalid_arguments:r="Invalid function arguments";break;case n2.invalid_return_type:r="Invalid function return type";break;case n2.invalid_date:r="Invalid date";break;case n2.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:v.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case n2.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case n2.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case n2.custom:r="Invalid input";break;case n2.invalid_intersection_types:r="Intersection results could not be merged";break;case n2.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case n2.not_finite:r="Number must be finite";break;default:r=t.defaultError,v.assertNever(e)}return{message:r}},n5=n6;function n3(e){n5=e}function n8(){return n5}e.s(["getErrorMap",0,n8,"setErrorMap",0,n3],937904),(m=x||(x={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},m.toString=e=>"string"==typeof e?e:e?.message;let n7=e=>{let{data:t,path:r,errorMaps:a,issueData:i}=e,n=[...r,...i.path||[]],s={...i,path:n};if(void 0!==i.message)return{...i,path:n,message:i.message};let o="";for(let e of a.filter(e=>!!e).slice().reverse())o=e(s,{data:t,defaultError:o}).message;return{...i,path:n,message:o}},se=[];function st(e,t){let r=n8(),a=n7({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===n6?void 0:n6].filter(e=>!!e)});e.common.issues.push(a)}class sr{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let a of t){if("aborted"===a.status)return sa;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,a=await e.value;r.push({key:t,value:a})}return sr.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let a of t){let{key:t,value:i}=a;if("aborted"===t.status||"aborted"===i.status)return sa;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==i.value||a.alwaysSet)&&(r[t.value]=i.value)}return{status:e.value,value:r}}}let sa=Object.freeze({status:"aborted"}),si=e=>({status:"dirty",value:e}),sn=e=>({status:"valid",value:e}),ss=e=>"aborted"===e.status,so=e=>"dirty"===e.status,sl=e=>"valid"===e.status,su=e=>"u">typeof Promise&&e instanceof Promise;e.s(["DIRTY",0,si,"EMPTY_PATH",0,se,"INVALID",0,sa,"OK",0,sn,"ParseStatus",0,sr,"addIssueToContext",0,st,"isAborted",0,ss,"isAsync",0,su,"isDirty",0,so,"isValid",0,sl,"makeIssue",0,n7],665354);class sd{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let sc=(e,t)=>{if(sl(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new n9(e.common.issues);return this._error=t,this._error}}};function sh(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:a,description:i}=e;if(t&&(r||a))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:n}=e;return"invalid_enum_value"===t.code?{message:n??i.defaultError}:void 0===i.data?{message:n??a??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:n??r??i.defaultError}},description:i}}class sp{get description(){return this._def.description}_getType(e){return n1(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:n1(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new sr,ctx:{common:e.parent.common,data:e.data,parsedType:n1(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(su(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:n1(e)},a=this._parseSync({data:e,path:r.path,parent:r});return sc(r,a)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:n1(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return sl(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>sl(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:n1(e)},a=this._parse({data:e,path:r.path,parent:r});return sc(r,await (su(a)?a:Promise.resolve(a)))}refine(e,t){return this._refinement((r,a)=>{let i=e(r),n=()=>a.addIssue({code:n2.custom,..."string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(r):t});return"u">typeof Promise&&i instanceof Promise?i.then(e=>!!e||(n(),!1)):!!i||(n(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new s3({schema:this,typeName:k.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return s8.create(this,this._def)}nullable(){return s7.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return sH.create(this)}promise(){return s5.create(this,this._def)}or(e){return sJ.create([this,e],this._def)}and(e){return sV.create(this,e,this._def)}transform(e){return new s3({...sh(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new oe({...sh(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:k.ZodDefault})}brand(){return new oi({typeName:k.ZodBranded,type:this,...sh(this._def)})}catch(e){return new ot({...sh(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:k.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return on.create(this,e)}readonly(){return os.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let sf=/^c[^\s-]{8,}$/i,sm=/^[0-9a-z]+$/,sg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sy=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,s_=/^[a-z0-9_-]{21}$/i,sb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sv=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,sw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sx=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,sk=/^(?:(?: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])$/,sS=/^(([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]))$/,sT=/^(([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])$/,sE=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sA=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,sI="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",sO=RegExp(`^${sI}$`);function sC(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function sj(e){let t=`${sI}T${sC(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)}class s$ extends sp{_parse(e){var t,r,a,i;let n;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==n0.string){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.string,received:t.parsedType}),sa}let s=new sr;for(let l of this._def.checks)if("min"===l.kind)e.data.length<l.value&&(st(n=this._getOrReturnCtx(e,n),{code:n2.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("max"===l.kind)e.data.length>l.value&&(st(n=this._getOrReturnCtx(e,n),{code:n2.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("length"===l.kind){let t=e.data.length>l.value,r=e.data.length<l.value;(t||r)&&(n=this._getOrReturnCtx(e,n),t?st(n,{code:n2.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):r&&st(n,{code:n2.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),s.dirty())}else if("email"===l.kind)sw.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"email",code:n2.invalid_string,message:l.message}),s.dirty());else if("emoji"===l.kind)o||(o=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),o.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"emoji",code:n2.invalid_string,message:l.message}),s.dirty());else if("uuid"===l.kind)sy.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"uuid",code:n2.invalid_string,message:l.message}),s.dirty());else if("nanoid"===l.kind)s_.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"nanoid",code:n2.invalid_string,message:l.message}),s.dirty());else if("cuid"===l.kind)sf.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"cuid",code:n2.invalid_string,message:l.message}),s.dirty());else if("cuid2"===l.kind)sm.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"cuid2",code:n2.invalid_string,message:l.message}),s.dirty());else if("ulid"===l.kind)sg.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"ulid",code:n2.invalid_string,message:l.message}),s.dirty());else if("url"===l.kind)try{new URL(e.data)}catch{st(n=this._getOrReturnCtx(e,n),{validation:"url",code:n2.invalid_string,message:l.message}),s.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"regex",code:n2.invalid_string,message:l.message}),s.dirty())):"trim"===l.kind?e.data=e.data.trim():"includes"===l.kind?e.data.includes(l.value,l.position)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),s.dirty()):"toLowerCase"===l.kind?e.data=e.data.toLowerCase():"toUpperCase"===l.kind?e.data=e.data.toUpperCase():"startsWith"===l.kind?e.data.startsWith(l.value)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:{startsWith:l.value},message:l.message}),s.dirty()):"endsWith"===l.kind?e.data.endsWith(l.value)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:{endsWith:l.value},message:l.message}),s.dirty()):"datetime"===l.kind?sj(l).test(e.data)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:"datetime",message:l.message}),s.dirty()):"date"===l.kind?sO.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:"date",message:l.message}),s.dirty()):"time"===l.kind?RegExp(`^${sC(l)}$`).test(e.data)||(st(n=this._getOrReturnCtx(e,n),{code:n2.invalid_string,validation:"time",message:l.message}),s.dirty()):"duration"===l.kind?sv.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"duration",code:n2.invalid_string,message:l.message}),s.dirty()):"ip"===l.kind?(t=e.data,!(("v4"===(r=l.version)||!r)&&sx.test(t)||("v6"===r||!r)&&sS.test(t))&&1&&(st(n=this._getOrReturnCtx(e,n),{validation:"ip",code:n2.invalid_string,message:l.message}),s.dirty())):"jwt"===l.kind?!function(e,t){if(!sb.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(a));if("object"!=typeof i||null===i||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)return!1;return!0}catch{return!1}}(e.data,l.alg)&&(st(n=this._getOrReturnCtx(e,n),{validation:"jwt",code:n2.invalid_string,message:l.message}),s.dirty()):"cidr"===l.kind?(a=e.data,!(("v4"===(i=l.version)||!i)&&sk.test(a)||("v6"===i||!i)&&sT.test(a))&&1&&(st(n=this._getOrReturnCtx(e,n),{validation:"cidr",code:n2.invalid_string,message:l.message}),s.dirty())):"base64"===l.kind?sE.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"base64",code:n2.invalid_string,message:l.message}),s.dirty()):"base64url"===l.kind?sA.test(e.data)||(st(n=this._getOrReturnCtx(e,n),{validation:"base64url",code:n2.invalid_string,message:l.message}),s.dirty()):v.assertNever(l);return{status:s.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:n2.invalid_string,...x.errToObj(r)})}_addCheck(e){return new s$({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...x.errToObj(e)})}url(e){return this._addCheck({kind:"url",...x.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...x.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...x.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...x.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...x.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...x.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...x.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...x.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...x.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...x.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...x.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...x.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...x.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...x.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...x.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...x.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...x.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...x.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...x.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...x.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...x.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...x.errToObj(t)})}nonempty(e){return this.min(1,x.errToObj(e))}trim(){return new s$({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new s$({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new s$({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}s$.create=e=>new s$({checks:[],typeName:k.ZodString,coerce:e?.coerce??!1,...sh(e)});class sP extends sp{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==n0.number){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.number,received:t.parsedType}),sa}let r=new sr;for(let a of this._def.checks)"int"===a.kind?v.isInteger(e.data)||(st(t=this._getOrReturnCtx(e,t),{code:n2.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty()):"min"===a.kind?(a.inclusive?e.data<a.value:e.data<=a.value)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):"max"===a.kind?(a.inclusive?e.data>a.value:e.data>=a.value)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):"multipleOf"===a.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,i=r>a?r:a;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}(e.data,a.value)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(st(t=this._getOrReturnCtx(e,t),{code:n2.not_finite,message:a.message}),r.dirty()):v.assertNever(a);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,x.toString(t))}gt(e,t){return this.setLimit("min",e,!1,x.toString(t))}lte(e,t){return this.setLimit("max",e,!0,x.toString(t))}lt(e,t){return this.setLimit("max",e,!1,x.toString(t))}setLimit(e,t,r,a){return new sP({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:x.toString(a)}]})}_addCheck(e){return new sP({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:x.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:x.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:x.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&v.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value);return Number.isFinite(t)&&Number.isFinite(e)}}sP.create=e=>new sP({checks:[],typeName:k.ZodNumber,coerce:e?.coerce||!1,...sh(e)});class sN extends sp{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==n0.bigint)return this._getInvalidInput(e);let r=new sr;for(let a of this._def.checks)"min"===a.kind?(a.inclusive?e.data<a.value:e.data<=a.value)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):"max"===a.kind?(a.inclusive?e.data>a.value:e.data>=a.value)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(st(t=this._getOrReturnCtx(e,t),{code:n2.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):v.assertNever(a);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.bigint,received:t.parsedType}),sa}gte(e,t){return this.setLimit("min",e,!0,x.toString(t))}gt(e,t){return this.setLimit("min",e,!1,x.toString(t))}lte(e,t){return this.setLimit("max",e,!0,x.toString(t))}lt(e,t){return this.setLimit("max",e,!1,x.toString(t))}setLimit(e,t,r,a){return new sN({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:x.toString(a)}]})}_addCheck(e){return new sN({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:x.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}sN.create=e=>new sN({checks:[],typeName:k.ZodBigInt,coerce:e?.coerce??!1,...sh(e)});class sR extends sp{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==n0.boolean){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.boolean,received:t.parsedType}),sa}return sn(e.data)}}sR.create=e=>new sR({typeName:k.ZodBoolean,coerce:e?.coerce||!1,...sh(e)});class sM extends sp{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==n0.date){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.date,received:t.parsedType}),sa}if(Number.isNaN(e.data.getTime()))return st(this._getOrReturnCtx(e),{code:n2.invalid_date}),sa;let r=new sr;for(let a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(st(t=this._getOrReturnCtx(e,t),{code:n2.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):v.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new sM({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:x.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:x.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}sM.create=e=>new sM({checks:[],coerce:e?.coerce||!1,typeName:k.ZodDate,...sh(e)});class sz extends sp{_parse(e){if(this._getType(e)!==n0.symbol){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.symbol,received:t.parsedType}),sa}return sn(e.data)}}sz.create=e=>new sz({typeName:k.ZodSymbol,...sh(e)});class sL extends sp{_parse(e){if(this._getType(e)!==n0.undefined){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.undefined,received:t.parsedType}),sa}return sn(e.data)}}sL.create=e=>new sL({typeName:k.ZodUndefined,...sh(e)});class sU extends sp{_parse(e){if(this._getType(e)!==n0.null){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.null,received:t.parsedType}),sa}return sn(e.data)}}sU.create=e=>new sU({typeName:k.ZodNull,...sh(e)});class sD extends sp{constructor(){super(...arguments),this._any=!0}_parse(e){return sn(e.data)}}sD.create=e=>new sD({typeName:k.ZodAny,...sh(e)});class sB extends sp{constructor(){super(...arguments),this._unknown=!0}_parse(e){return sn(e.data)}}sB.create=e=>new sB({typeName:k.ZodUnknown,...sh(e)});class sF extends sp{_parse(e){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.never,received:t.parsedType}),sa}}sF.create=e=>new sF({typeName:k.ZodNever,...sh(e)});class sZ extends sp{_parse(e){if(this._getType(e)!==n0.undefined){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.void,received:t.parsedType}),sa}return sn(e.data)}}sZ.create=e=>new sZ({typeName:k.ZodVoid,...sh(e)});class sH extends sp{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==n0.array)return st(t,{code:n2.invalid_type,expected:n0.array,received:t.parsedType}),sa;if(null!==a.exactLength){let e=t.data.length>a.exactLength.value,i=t.data.length<a.exactLength.value;(e||i)&&(st(t,{code:e?n2.too_big:n2.too_small,minimum:i?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(st(t,{code:n2.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(st(t,{code:n2.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new sd(t,e,t.path,r)))).then(e=>sr.mergeArray(r,e));let i=[...t.data].map((e,r)=>a.type._parseSync(new sd(t,e,t.path,r)));return sr.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new sH({...this._def,minLength:{value:e,message:x.toString(t)}})}max(e,t){return new sH({...this._def,maxLength:{value:e,message:x.toString(t)}})}length(e,t){return new sH({...this._def,exactLength:{value:e,message:x.toString(t)}})}nonempty(e){return this.min(1,e)}}sH.create=(e,t)=>new sH({type:e,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...sh(t)});class sq extends sp{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=v.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==n0.object){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.object,received:t.parsedType}),sa}let{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),n=[];if(!(this._def.catchall instanceof sF&&"strip"===this._def.unknownKeys))for(let e in r.data)i.includes(e)||n.push(e);let s=[];for(let e of i){let t=a[e],i=r.data[e];s.push({key:{status:"valid",value:e},value:t._parse(new sd(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof sF){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of n)s.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)n.length>0&&(st(r,{code:n2.unrecognized_keys,keys:n}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of n){let a=r.data[t];s.push({key:{status:"valid",value:t},value:e._parse(new sd(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of s){let r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>sr.mergeObjectSync(t,e)):sr.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return x.errToObj,new sq({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:x.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new sq({...this._def,unknownKeys:"strip"})}passthrough(){return new sq({...this._def,unknownKeys:"passthrough"})}extend(e){return new sq({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new sq({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new sq({...this._def,catchall:e})}pick(e){let t={};for(let r of v.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new sq({...this._def,shape:()=>t})}omit(e){let t={};for(let r of v.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new sq({...this._def,shape:()=>t})}deepPartial(){return function e(t){if(t instanceof sq){let r={};for(let a in t.shape){let i=t.shape[a];r[a]=s8.create(e(i))}return new sq({...t._def,shape:()=>r})}if(t instanceof sH)return new sH({...t._def,type:e(t.element)});if(t instanceof s8)return s8.create(e(t.unwrap()));if(t instanceof s7)return s7.create(e(t.unwrap()));if(t instanceof sK)return sK.create(t.items.map(t=>e(t)));else return t}(this)}partial(e){let t={};for(let r of v.objectKeys(this.shape)){let a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new sq({...this._def,shape:()=>t})}required(e){let t={};for(let r of v.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof s8;)e=e._def.innerType;t[r]=e}return new sq({...this._def,shape:()=>t})}keyof(){return s4(v.objectKeys(this.shape))}}sq.create=(e,t)=>new sq({shape:()=>e,unknownKeys:"strip",catchall:sF.create(),typeName:k.ZodObject,...sh(t)}),sq.strictCreate=(e,t)=>new sq({shape:()=>e,unknownKeys:"strict",catchall:sF.create(),typeName:k.ZodObject,...sh(t)}),sq.lazycreate=(e,t)=>new sq({shape:e,unknownKeys:"strip",catchall:sF.create(),typeName:k.ZodObject,...sh(t)});class sJ extends sp{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new n9(e.ctx.common.issues));return st(t,{code:n2.invalid_union,unionErrors:r}),sa});{let e,a=[];for(let i of r){let r={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=a.map(e=>new n9(e));return st(t,{code:n2.invalid_union,unionErrors:i}),sa}}get options(){return this._def.options}}sJ.create=(e,t)=>new sJ({options:e,typeName:k.ZodUnion,...sh(t)});let sG=e=>{if(e instanceof s1)return sG(e.schema);if(e instanceof s3)return sG(e.innerType());if(e instanceof s2)return[e.value];if(e instanceof s9)return e.options;if(e instanceof s6)return v.objectValues(e.enum);else if(e instanceof oe)return sG(e._def.innerType);else if(e instanceof sL)return[void 0];else if(e instanceof sU)return[null];else if(e instanceof s8)return[void 0,...sG(e.unwrap())];else if(e instanceof s7)return[null,...sG(e.unwrap())];else if(e instanceof oi)return sG(e.unwrap());else if(e instanceof os)return sG(e.unwrap());else if(e instanceof ot)return sG(e._def.innerType);else return[]};class sW extends sp{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==n0.object)return st(t,{code:n2.invalid_type,expected:n0.object,received:t.parsedType}),sa;let r=this.discriminator,a=t.data[r],i=this.optionsMap.get(a);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(st(t,{code:n2.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),sa)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let a=new Map;for(let r of t){let t=sG(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of t){if(a.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);a.set(i,r)}}return new sW({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...sh(r)})}}class sV extends sp{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),a=(e,a)=>{if(ss(e)||ss(a))return sa;let i=function e(t,r){let a=n1(t),i=n1(r);if(t===r)return{valid:!0,data:t};if(a===n0.object&&i===n0.object){let a=v.objectKeys(r),i=v.objectKeys(t).filter(e=>-1!==a.indexOf(e)),n={...t,...r};for(let a of i){let i=e(t[a],r[a]);if(!i.valid)return{valid:!1};n[a]=i.data}return{valid:!0,data:n}}if(a===n0.array&&i===n0.array){if(t.length!==r.length)return{valid:!1};let a=[];for(let i=0;i<t.length;i++){let n=e(t[i],r[i]);if(!n.valid)return{valid:!1};a.push(n.data)}return{valid:!0,data:a}}if(a===n0.date&&i===n0.date&&+t==+r)return{valid:!0,data:t};return{valid:!1}}(e.value,a.value);return i.valid?((so(e)||so(a))&&t.dirty(),{status:t.value,value:i.data}):(st(r,{code:n2.invalid_intersection_types}),sa)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>a(e,t)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}sV.create=(e,t,r)=>new sV({left:e,right:t,typeName:k.ZodIntersection,...sh(r)});class sK extends sp{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==n0.array)return st(r,{code:n2.invalid_type,expected:n0.array,received:r.parsedType}),sa;if(r.data.length<this._def.items.length)return st(r,{code:n2.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),sa;!this._def.rest&&r.data.length>this._def.items.length&&(st(r,{code:n2.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...r.data].map((e,t)=>{let a=this._def.items[t]||this._def.rest;return a?a._parse(new sd(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>sr.mergeArray(t,e)):sr.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new sK({...this._def,rest:e})}}sK.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new sK({items:e,typeName:k.ZodTuple,rest:null,...sh(t)})};class sQ extends sp{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==n0.object)return st(r,{code:n2.invalid_type,expected:n0.object,received:r.parsedType}),sa;let a=[],i=this._def.keyType,n=this._def.valueType;for(let e in r.data)a.push({key:i._parse(new sd(r,e,r.path,e)),value:n._parse(new sd(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?sr.mergeObjectAsync(t,a):sr.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new sQ(t instanceof sp?{keyType:e,valueType:t,typeName:k.ZodRecord,...sh(r)}:{keyType:s$.create(),valueType:e,typeName:k.ZodRecord,...sh(t)})}}class sY extends sp{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==n0.map)return st(r,{code:n2.invalid_type,expected:n0.map,received:r.parsedType}),sa;let a=this._def.keyType,i=this._def.valueType,n=[...r.data.entries()].map(([e,t],n)=>({key:a._parse(new sd(r,e,r.path,[n,"key"])),value:i._parse(new sd(r,t,r.path,[n,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of n){let a=await r.key,i=await r.value;if("aborted"===a.status||"aborted"===i.status)return sa;("dirty"===a.status||"dirty"===i.status)&&t.dirty(),e.set(a.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of n){let a=r.key,i=r.value;if("aborted"===a.status||"aborted"===i.status)return sa;("dirty"===a.status||"dirty"===i.status)&&t.dirty(),e.set(a.value,i.value)}return{status:t.value,value:e}}}}sY.create=(e,t,r)=>new sY({valueType:t,keyType:e,typeName:k.ZodMap,...sh(r)});class sX extends sp{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==n0.set)return st(r,{code:n2.invalid_type,expected:n0.set,received:r.parsedType}),sa;let a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(st(r,{code:n2.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(st(r,{code:n2.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());let i=this._def.valueType;function n(e){let r=new Set;for(let a of e){if("aborted"===a.status)return sa;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}let s=[...r.data.values()].map((e,t)=>i._parse(new sd(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>n(e)):n(s)}min(e,t){return new sX({...this._def,minSize:{value:e,message:x.toString(t)}})}max(e,t){return new sX({...this._def,maxSize:{value:e,message:x.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}sX.create=(e,t)=>new sX({valueType:e,minSize:null,maxSize:null,typeName:k.ZodSet,...sh(t)});class s0 extends sp{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==n0.function)return st(t,{code:n2.invalid_type,expected:n0.function,received:t.parsedType}),sa;function r(e,r){return n7({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n8(),n6].filter(e=>!!e),issueData:{code:n2.invalid_arguments,argumentsError:r}})}function a(e,r){return n7({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n8(),n6].filter(e=>!!e),issueData:{code:n2.invalid_return_type,returnTypeError:r}})}let i={errorMap:t.common.contextualErrorMap},n=t.data;if(this._def.returns instanceof s5){let e=this;return sn(async function(...t){let s=new n9([]),o=await e._def.args.parseAsync(t,i).catch(e=>{throw s.addIssue(r(t,e)),s}),l=await Reflect.apply(n,this,o);return await e._def.returns._def.type.parseAsync(l,i).catch(e=>{throw s.addIssue(a(l,e)),s})})}{let e=this;return sn(function(...t){let s=e._def.args.safeParse(t,i);if(!s.success)throw new n9([r(t,s.error)]);let o=Reflect.apply(n,this,s.data),l=e._def.returns.safeParse(o,i);if(!l.success)throw new n9([a(o,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new s0({...this._def,args:sK.create(e).rest(sB.create())})}returns(e){return new s0({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new s0({args:e||sK.create([]).rest(sB.create()),returns:t||sB.create(),typeName:k.ZodFunction,...sh(r)})}}class s1 extends sp{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}s1.create=(e,t)=>new s1({getter:e,typeName:k.ZodLazy,...sh(t)});class s2 extends sp{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return st(t,{received:t.data,code:n2.invalid_literal,expected:this._def.value}),sa}return{status:"valid",value:e.data}}get value(){return this._def.value}}function s4(e,t){return new s9({values:e,typeName:k.ZodEnum,...sh(t)})}s2.create=(e,t)=>new s2({value:e,typeName:k.ZodLiteral,...sh(t)});class s9 extends sp{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return st(t,{expected:v.joinValues(r),received:t.parsedType,code:n2.invalid_type}),sa}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return st(t,{received:t.data,code:n2.invalid_enum_value,options:r}),sa}return sn(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return s9.create(e,{...this._def,...t})}exclude(e,t=this._def){return s9.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}s9.create=s4;class s6 extends sp{_parse(e){let t=v.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==n0.string&&r.parsedType!==n0.number){let e=v.objectValues(t);return st(r,{expected:v.joinValues(e),received:r.parsedType,code:n2.invalid_type}),sa}if(this._cache||(this._cache=new Set(v.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=v.objectValues(t);return st(r,{received:r.data,code:n2.invalid_enum_value,options:e}),sa}return sn(e.data)}get enum(){return this._def.values}}s6.create=(e,t)=>new s6({values:e,typeName:k.ZodNativeEnum,...sh(t)});class s5 extends sp{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==n0.promise&&!1===t.common.async?(st(t,{code:n2.invalid_type,expected:n0.promise,received:t.parsedType}),sa):sn((t.parsedType===n0.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}s5.create=(e,t)=>new s5({type:e,typeName:k.ZodPromise,...sh(t)});class s3 extends sp{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,i={addIssue:e=>{st(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===a.type){let e=a.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return sa;let a=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===a.status?sa:"dirty"===a.status||"dirty"===t.value?si(a.value):a});{if("aborted"===t.value)return sa;let a=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===a.status?sa:"dirty"===a.status||"dirty"===t.value?si(a.value):a}}if("refinement"===a.type){let e=e=>{let t=a.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?sa:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?sa:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}}if("transform"===a.type)if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>sl(e)?Promise.resolve(a.transform(e.value,i)).then(e=>({status:t.value,value:e})):sa);else{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!sl(e))return sa;let n=a.transform(e.value,i);if(n instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}v.assertNever(a)}}s3.create=(e,t,r)=>new s3({schema:e,typeName:k.ZodEffects,effect:t,...sh(r)}),s3.createWithPreprocess=(e,t,r)=>new s3({schema:t,effect:{type:"preprocess",transform:e},typeName:k.ZodEffects,...sh(r)});class s8 extends sp{_parse(e){return this._getType(e)===n0.undefined?sn(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}s8.create=(e,t)=>new s8({innerType:e,typeName:k.ZodOptional,...sh(t)});class s7 extends sp{_parse(e){return this._getType(e)===n0.null?sn(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}s7.create=(e,t)=>new s7({innerType:e,typeName:k.ZodNullable,...sh(t)});class oe extends sp{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===n0.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}oe.create=(e,t)=>new oe({innerType:e,typeName:k.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...sh(t)});class ot extends sp{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return su(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new n9(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new n9(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ot.create=(e,t)=>new ot({innerType:e,typeName:k.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...sh(t)});class or extends sp{_parse(e){if(this._getType(e)!==n0.nan){let t=this._getOrReturnCtx(e);return st(t,{code:n2.invalid_type,expected:n0.nan,received:t.parsedType}),sa}return{status:"valid",value:e.data}}}or.create=e=>new or({typeName:k.ZodNaN,...sh(e)});let oa=Symbol("zod_brand");class oi extends sp{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class on extends sp{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?sa:"dirty"===e.status?(t.dirty(),si(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?sa:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new on({in:e,out:t,typeName:k.ZodPipeline})}}class os extends sp{_parse(e){let t=this._def.innerType._parse(e),r=e=>(sl(e)&&(e.value=Object.freeze(e.value)),e);return su(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function oo(e,t){let r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function ol(e,t={},r){return e?sD.create().superRefine((a,i)=>{let n=e(a);if(n instanceof Promise)return n.then(e=>{if(!e){let e=oo(t,a),n=e.fatal??r??!0;i.addIssue({code:"custom",...e,fatal:n})}});if(!n){let e=oo(t,a),n=e.fatal??r??!0;i.addIssue({code:"custom",...e,fatal:n})}}):sD.create()}os.create=(e,t)=>new os({innerType:e,typeName:k.ZodReadonly,...sh(t)});let ou={object:sq.lazycreate};(g=k||(k={})).ZodString="ZodString",g.ZodNumber="ZodNumber",g.ZodNaN="ZodNaN",g.ZodBigInt="ZodBigInt",g.ZodBoolean="ZodBoolean",g.ZodDate="ZodDate",g.ZodSymbol="ZodSymbol",g.ZodUndefined="ZodUndefined",g.ZodNull="ZodNull",g.ZodAny="ZodAny",g.ZodUnknown="ZodUnknown",g.ZodNever="ZodNever",g.ZodVoid="ZodVoid",g.ZodArray="ZodArray",g.ZodObject="ZodObject",g.ZodUnion="ZodUnion",g.ZodDiscriminatedUnion="ZodDiscriminatedUnion",g.ZodIntersection="ZodIntersection",g.ZodTuple="ZodTuple",g.ZodRecord="ZodRecord",g.ZodMap="ZodMap",g.ZodSet="ZodSet",g.ZodFunction="ZodFunction",g.ZodLazy="ZodLazy",g.ZodLiteral="ZodLiteral",g.ZodEnum="ZodEnum",g.ZodEffects="ZodEffects",g.ZodNativeEnum="ZodNativeEnum",g.ZodOptional="ZodOptional",g.ZodNullable="ZodNullable",g.ZodDefault="ZodDefault",g.ZodCatch="ZodCatch",g.ZodPromise="ZodPromise",g.ZodBranded="ZodBranded",g.ZodPipeline="ZodPipeline",g.ZodReadonly="ZodReadonly";let od=(e,t={message:`Input not instance of ${e.name}`})=>ol(t=>t instanceof e,t),oc=s$.create,oh=sP.create,op=or.create,of=sN.create,om=sR.create,og=sM.create,oy=sz.create,o_=sL.create,ob=sU.create,ov=sD.create,ow=sB.create,ox=sF.create,ok=sZ.create,oS=sH.create,oT=sq.create,oE=sq.strictCreate,oA=sJ.create,oI=sW.create,oO=sV.create,oC=sK.create,oj=sQ.create,o$=sY.create,oP=sX.create,oN=s0.create,oR=s1.create,oM=s2.create,oz=s9.create,oL=s6.create,oU=s5.create,oD=s3.create,oB=s8.create,oF=s7.create,oZ=s3.createWithPreprocess,oH=on.create,oq=()=>oc().optional(),oJ=()=>oh().optional(),oG=()=>om().optional(),oW={string:e=>s$.create({...e,coerce:!0}),number:e=>sP.create({...e,coerce:!0}),boolean:e=>sR.create({...e,coerce:!0}),bigint:e=>sN.create({...e,coerce:!0}),date:e=>sM.create({...e,coerce:!0})};function oV(e,t){return ls(e.type._def,t)}e.s(["BRAND",0,oa,"NEVER",0,sa,"Schema",0,sp,"ZodAny",0,sD,"ZodArray",0,sH,"ZodBigInt",0,sN,"ZodBoolean",0,sR,"ZodBranded",0,oi,"ZodCatch",0,ot,"ZodDate",0,sM,"ZodDefault",0,oe,"ZodDiscriminatedUnion",0,sW,"ZodEffects",0,s3,"ZodEnum",0,s9,"ZodFirstPartyTypeKind",0,k,"ZodFunction",0,s0,"ZodIntersection",0,sV,"ZodLazy",0,s1,"ZodLiteral",0,s2,"ZodMap",0,sY,"ZodNaN",0,or,"ZodNativeEnum",0,s6,"ZodNever",0,sF,"ZodNull",0,sU,"ZodNullable",0,s7,"ZodNumber",0,sP,"ZodObject",0,sq,"ZodOptional",0,s8,"ZodPipeline",0,on,"ZodPromise",0,s5,"ZodReadonly",0,os,"ZodRecord",0,sQ,"ZodSchema",0,sp,"ZodSet",0,sX,"ZodString",0,s$,"ZodSymbol",0,sz,"ZodTransformer",0,s3,"ZodTuple",0,sK,"ZodType",0,sp,"ZodUndefined",0,sL,"ZodUnion",0,sJ,"ZodUnknown",0,sB,"ZodVoid",0,sZ,"any",0,ov,"array",0,oS,"bigint",0,of,"boolean",0,om,"coerce",0,oW,"custom",0,ol,"date",0,og,"datetimeRegex",0,sj,"discriminatedUnion",0,oI,"effect",0,oD,"enum",0,oz,"function",0,oN,"instanceof",0,od,"intersection",0,oO,"late",0,ou,"lazy",0,oR,"literal",0,oM,"map",0,o$,"nan",0,op,"nativeEnum",0,oL,"never",0,ox,"null",0,ob,"nullable",0,oF,"number",0,oh,"object",0,oT,"oboolean",0,oG,"onumber",0,oJ,"optional",0,oB,"ostring",0,oq,"pipeline",0,oH,"preprocess",0,oZ,"promise",0,oU,"record",0,oj,"set",0,oP,"strictObject",0,oE,"string",0,oc,"symbol",0,oy,"transformer",0,oD,"tuple",0,oC,"undefined",0,o_,"union",0,oA,"unknown",0,ow,"void",0,ok],965638);let oK=/^[cC][^\s-]{8,}$/,oQ=/^[0-9a-z]+$/,oY=/^[0-9A-HJKMNP-TV-Z]{26}$/,oX=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,o0=()=>(void 0===u&&(u=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),u),o1=/^(?:(?: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])$/,o2=/^(([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])$/,o4=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,o9=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,o6=/^[a-zA-Z0-9_-]{21}$/,o5=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function o3(e,t){let r={type:"string"};if(e.checks)for(let a of e.checks)switch(a.kind){case"min":nX(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t);break;case"max":nX(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"email":switch(t.emailStrategy){case"format:email":le(r,"email",a.message,t);break;case"format:idn-email":le(r,"idn-email",a.message,t);break;case"pattern:zod":lt(r,oX,a.message,t)}break;case"url":le(r,"uri",a.message,t);break;case"uuid":le(r,"uuid",a.message,t);break;case"regex":lt(r,a.regex,a.message,t);break;case"cuid":lt(r,oK,a.message,t);break;case"cuid2":lt(r,oQ,a.message,t);break;case"startsWith":lt(r,RegExp(`^${o8(a.value,t)}`),a.message,t);break;case"endsWith":lt(r,RegExp(`${o8(a.value,t)}$`),a.message,t);break;case"datetime":le(r,"date-time",a.message,t);break;case"date":le(r,"date",a.message,t);break;case"time":le(r,"time",a.message,t);break;case"duration":le(r,"duration",a.message,t);break;case"length":nX(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t),nX(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"includes":lt(r,RegExp(o8(a.value,t)),a.message,t);break;case"ip":"v6"!==a.version&&le(r,"ipv4",a.message,t),"v4"!==a.version&&le(r,"ipv6",a.message,t);break;case"base64url":lt(r,o9,a.message,t);break;case"jwt":lt(r,o5,a.message,t);break;case"cidr":"v6"!==a.version&<(r,o1,a.message,t),"v4"!==a.version&<(r,o2,a.message,t);break;case"emoji":lt(r,o0(),a.message,t);break;case"ulid":lt(r,oY,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":le(r,"binary",a.message,t);break;case"contentEncoding:base64":nX(r,"contentEncoding","base64",a.message,t);break;case"pattern:zod":lt(r,o4,a.message,t)}break;case"nanoid":lt(r,o6,a.message,t)}return r}function o8(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)o7.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}let o7=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function le(e,t,r,a){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&a.errorMessages&&{errorMessage:{format:r}}})):nX(e,"format",t,r,a)}function lt(e,t,r,a){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:lr(t,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):nX(e,"pattern",lr(t,a),r,a)}function lr(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=r.i?e.source.toLowerCase():e.source,i="",n=!1,s=!1,o=!1;for(let e=0;e<a.length;e++){if(n){i+=a[e],n=!1;continue}if(r.i){if(s){if(a[e].match(/[a-z]/)){o?(i+=a[e],i+=`${a[e-2]}-${a[e]}`.toUpperCase(),o=!1):"-"===a[e+1]&&a[e+2]?.match(/[a-z]/)?(i+=a[e],o=!0):i+=`${a[e]}${a[e].toUpperCase()}`;continue}}else if(a[e].match(/[a-z]/)){i+=`[${a[e]}${a[e].toUpperCase()}]`;continue}}if(r.m){if("^"===a[e]){i+=`(^|(?<=[\r
|
|
45
45
|
]))`;continue}else if("$"===a[e]){i+=`($|(?=[\r
|
|
46
46
|
]))`;continue}}if(r.s&&"."===a[e]){i+=s?`${a[e]}\r
|
|
47
47
|
`:`[${a[e]}\r
|
|
48
48
|
]`;continue}i+=a[e],"\\"===a[e]?n=!0:s&&"]"===a[e]?s=!1:s||"["!==a[e]||(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function la(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===k.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,a)=>({...r,[a]:ls(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??nQ(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ls(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===k.ZodString&&e.keyType._def.checks?.length){let{type:a,...i}=o3(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===k.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===k.ZodBranded&&e.keyType._def.type._def.typeName===k.ZodString&&e.keyType._def.type._def.checks?.length){let{type:a,...i}=oV(e.keyType._def,t);return{...r,propertyNames:i}}return r}let li={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},ln=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>ls(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function ls(e,t,r=!1){let a=t.seen.get(e);if(t.override){let i=t.override?.(e,t,a,r);if(i!==nW)return i}if(a&&!r){let e=lo(a,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let n=((e,t,r)=>{switch(t){case k.ZodString:return o3(e,r);case k.ZodNumber:let a={type:"number"};if(!e.checks)return a;for(let t of e.checks)switch(t.kind){case"int":a.type="integer",nY(a,"type",t.message,r);break;case"min":"jsonSchema7"===r.target?t.inclusive?nX(a,"minimum",t.value,t.message,r):nX(a,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(a.exclusiveMinimum=!0),nX(a,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?nX(a,"maximum",t.value,t.message,r):nX(a,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(a.exclusiveMaximum=!0),nX(a,"maximum",t.value,t.message,r));break;case"multipleOf":nX(a,"multipleOf",t.value,t.message,r)}return a;case k.ZodObject:return function(e,t){let r="openAi"===t.target,a={type:"object",properties:{}},i=[],n=e.shape();for(let e in n){let s=n[e];if(void 0===s||void 0===s._def)continue;let o=function(e){try{return e.isOptional()}catch{return!0}}(s);o&&r&&("ZodOptional"===s._def.typeName&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),o=!1);let l=ls(s._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(a.properties[e]=l,o||i.push(e))}i.length&&(a.required=i);let s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return ls(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(a.additionalProperties=s),a}(e,r);case k.ZodBigInt:let i={type:"integer",format:"int64"};if(!e.checks)return i;for(let t of e.checks)switch(t.kind){case"min":"jsonSchema7"===r.target?t.inclusive?nX(i,"minimum",t.value,t.message,r):nX(i,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(i.exclusiveMinimum=!0),nX(i,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?nX(i,"maximum",t.value,t.message,r):nX(i,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(i.exclusiveMaximum=!0),nX(i,"maximum",t.value,t.message,r));break;case"multipleOf":nX(i,"multipleOf",t.value,t.message,r)}return i;case k.ZodBoolean:return{type:"boolean"};case k.ZodDate:return function e(t,r,a){let i=a??r.dateStrategy;if(Array.isArray(i))return{anyOf:i.map(a=>e(t,r,a))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var n=t,s=r;let o={type:"integer",format:"unix-time"};if("openApi3"===s.target)return o;for(let e of n.checks)switch(e.kind){case"min":nX(o,"minimum",e.value,e.message,s);break;case"max":nX(o,"maximum",e.value,e.message,s)}return o}}(e,r);case k.ZodUndefined:return{not:nQ(r)};case k.ZodNull:return"openApi3"===r.target?{enum:["null"],nullable:!0}:{type:"null"};case k.ZodArray:let n;return n={type:"array"},e.type?._def&&e.type?._def?.typeName!==k.ZodAny&&(n.items=ls(e.type._def,{...r,currentPath:[...r.currentPath,"items"]})),e.minLength&&nX(n,"minItems",e.minLength.value,e.minLength.message,r),e.maxLength&&nX(n,"maxItems",e.maxLength.value,e.maxLength.message,r),e.exactLength&&(nX(n,"minItems",e.exactLength.value,e.exactLength.message,r),nX(n,"maxItems",e.exactLength.value,e.exactLength.message,r)),n;case k.ZodUnion:case k.ZodDiscriminatedUnion:if("openApi3"===r.target)return ln(e,r);let s=e.options instanceof Map?Array.from(e.options.values()):e.options;if(s.every(e=>e._def.typeName in li&&(!e._def.checks||!e._def.checks.length))){let e=s.reduce((e,t)=>{let r=li[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(s.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=s.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];return e;default:return e}},[]);if(e.length===s.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:s.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(s.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:s.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return ln(e,r);case k.ZodIntersection:let o,l,u;return o=[ls(e.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),ls(e.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(e=>!!e),l="jsonSchema2019-09"===r.target?{unevaluatedProperties:!1}:void 0,u=[],o.forEach(e=>{if((!("type"in e)||"string"!==e.type)&&"allOf"in e)u.push(...e.allOf),void 0===e.unevaluatedProperties&&(l=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}else l=void 0;u.push(t)}}),u.length?{allOf:u,...l}:void 0;case k.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>ls(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:ls(e.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>ls(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case k.ZodRecord:return la(e,r);case k.ZodLiteral:let d;return"bigint"!=(d=typeof e.value)&&"number"!==d&&"boolean"!==d&&"string"!==d?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===r.target?{type:"bigint"===d?"integer":d,enum:[e.value]}:{type:"bigint"===d?"integer":d,const:e.value};case k.ZodEnum:return{type:"string",enum:Array.from(e.values)};case k.ZodNativeEnum:let c,h,p;return c=e.values,{type:1===(p=Array.from(new Set((h=Object.keys(e.values).filter(e=>"number"!=typeof c[c[e]]).map(e=>c[e])).map(e=>typeof e)))).length?"string"===p[0]?"string":"number":["string","number"],enum:h};case k.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===r.target?{type:li[e.innerType._def.typeName],nullable:!0}:{type:[li[e.innerType._def.typeName],"null"]};if("openApi3"===r.target){let t=ls(e.innerType._def,{...r,currentPath:[...r.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let f=ls(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return f&&{anyOf:[f,{type:"null"}]};case k.ZodOptional:if(r.currentPath.toString()===r.propertyPath?.toString())return ls(e.innerType._def,r);let m=ls(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return m?{anyOf:[{not:nQ(r)},m]}:nQ(r);case k.ZodMap:return"record"===r.mapStrategy?la(e,r):{type:"array",maxItems:125,items:{type:"array",items:[ls(e.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||nQ(r),ls(e.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||nQ(r)],minItems:2,maxItems:2}};case k.ZodSet:let g;return g={type:"array",uniqueItems:!0,items:ls(e.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})},e.minSize&&nX(g,"minItems",e.minSize.value,e.minSize.message,r),e.maxSize&&nX(g,"maxItems",e.maxSize.value,e.maxSize.message,r),g;case k.ZodLazy:return()=>e.getter()._def;case k.ZodPromise:return ls(e.type._def,r);case k.ZodNaN:case k.ZodNever:return"openAi"===r.target?void 0:{not:nQ({...r,currentPath:[...r.currentPath,"not"]})};case k.ZodEffects:return"input"===r.effectStrategy?ls(e.schema._def,r):nQ(r);case k.ZodAny:case k.ZodUnknown:return nQ(r);case k.ZodDefault:return{...ls(e.innerType._def,r),default:e.defaultValue()};case k.ZodBranded:return oV(e,r);case k.ZodReadonly:case k.ZodCatch:return ls(e.innerType._def,r);case k.ZodPipeline:if("input"===r.pipeStrategy)return ls(e.in._def,r);if("output"===r.pipeStrategy)return ls(e.out._def,r);let y=ls(e.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]});return{allOf:[y,ls(e.out._def,{...r,currentPath:[...r.currentPath,"allOf",y?"1":"0"]})].filter(e=>void 0!==e)};case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:default:return}})(e,e.typeName,t),s="function"==typeof n?ls(n(),t):n;if(s&&ll(e,t,s),t.postProcess){let r=t.postProcess(s,e,t);return i.jsonSchema=s,r}return i.jsonSchema=s,s}let lo=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:nK(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),nQ(t);return"seen"===t.$refStrategy?nQ(t):void 0}},ll=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function lu(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??nU,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function ld(e,t,r={path:[],schemaPath:[]}){var a;let i=e._zod.def,n=t.seen.get(e);if(n)return n.count++,r.schemaPath.includes(e)&&(n.cycle=r.path),n.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s);let o=e._zod.toJSONSchema?.();if(o)s.schema=o;else{let a={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,a);else{let r=s.schema,n=t.processors[i.type];if(!n)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);n(e,t,r,a)}let n=e._zod.parent;n&&(s.ref||(s.ref=n),ld(n,t,a),t.seen.get(n).isParent=!0)}let l=t.metadataRegistry.get(e);return l&&Object.assign(s.schema,l),"input"===t.io&&function e(t,r){let a=r??{seen:new Set};if(a.seen.has(t))return!1;a.seen.add(t);let i=t._zod.def;if("transform"===i.type)return!0;if("array"===i.type)return e(i.element,a);if("set"===i.type)return e(i.valueType,a);if("lazy"===i.type)return e(i.getter(),a);if("promise"===i.type||"optional"===i.type||"nonoptional"===i.type||"nullable"===i.type||"readonly"===i.type||"default"===i.type||"prefault"===i.type)return e(i.innerType,a);if("intersection"===i.type)return e(i.left,a)||e(i.right,a);if("record"===i.type||"map"===i.type)return e(i.keyType,a)||e(i.valueType,a);if("pipe"===i.type)return!!t._zod.traits.has("$ZodCodec")||e(i.in,a)||e(i.out,a);if("object"===i.type){for(let t in i.shape)if(e(i.shape[t],a))return!0;return!1}if("union"===i.type){for(let t of i.options)if(e(t,a))return!0;return!1}if("tuple"===i.type){for(let t of i.items)if(e(t,a))return!0;if(i.rest&&e(i.rest,a))return!0}return!1}(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&"_prefault"in s.schema&&((a=s.schema).default??(a.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function lc(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let a=new Map;for(let t of e.seen.entries()){let r=e.metadataRegistry.get(t[0])?.id;if(r){let e=a.get(r);if(e&&e!==t[0])throw Error(`Duplicate schema id "${r}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(r,t[0])}}let i=t=>{if(t[1].schema.$ref)return;let a=t[1],{ref:i,defId:n}=(t=>{let a="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){let r=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(r)return{ref:i(r)};let n=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=n,{defId:n,ref:`${i("__shared")}#/${a}/${n}`}}if(t[1]===r)return{ref:"#"};let i=`#/${a}/`,n=t[1].schema.id??`__schema${e.counter++}`;return{defId:n,ref:i+n}})(t);a.def={...a.schema},n&&(a.defId=n);let s=a.schema;for(let e in s)delete s[e];s.$ref=i};if("throw"===e.cycles)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>
|
|
49
49
|
|
|
50
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let r of e.seen.entries()){let a=r[1];if(t===r[0]){i(r);continue}if(e.external){let a=e.external.registry.get(r[0])?.id;if(t!==r[0]&&a){i(r);continue}}if(e.metadataRegistry.get(r[0])?.id||a.cycle||a.count>1&&"ref"===e.reused){i(r);continue}}}function lh(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let a=t=>{let r=e.seen.get(t);if(null===r.ref)return;let i=r.def??r.schema,n={...i},s=r.ref;if(r.ref=null,s){a(s);let r=e.seen.get(s),o=r.schema;if(o.$ref&&("draft-07"===e.target||"draft-04"===e.target||"openapi-3.0"===e.target)?(i.allOf=i.allOf??[],i.allOf.push(o)):Object.assign(i,o),Object.assign(i,n),t._zod.parent===s)for(let e in i)"$ref"!==e&&"allOf"!==e&&(e in n||delete i[e]);if(o.$ref&&r.def)for(let e in i)"$ref"!==e&&"allOf"!==e&&e in r.def&&JSON.stringify(i[e])===JSON.stringify(r.def[e])&&delete i[e]}let o=t._zod.parent;if(o&&o!==s){a(o);let t=e.seen.get(o);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:r.path??[]})};for(let t of[...e.seen.entries()].reverse())a(t[0]);let i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let r=e.external.registry.get(t)?.id;if(!r)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(r)}Object.assign(i,r.def??r.schema);let n=e.metadataRegistry.get(t)?.id;void 0!==n&&i.id===n&&delete i.id;let s=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,s[e.defId]=e.def)}e.external||Object.keys(s).length>0&&("draft-2020-12"===e.target?i.$defs=s:i.definitions=s);try{let r=JSON.parse(JSON.stringify(i));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:lp(t,"input",e.processors),output:lp(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch(e){throw Error("Error converting schema to JSON.")}}let lp=(e,t,r={})=>a=>{let{libraryOptions:i,target:n}=a??{},s=lu({...i??{},target:n,io:t,processors:r});return ld(e,s),lc(s,e),lh(s,e)},lf={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},lm={string:(e,t,r,a)=>{r.type="string";let{minimum:i,maximum:n,format:s,patterns:o,contentEncoding:l}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof n&&(r.maxLength=n),s&&(r.format=lf[s]??s,""===r.format&&delete r.format,"time"===s&&delete r.format),l&&(r.contentEncoding=l),o&&o.size>0){let e=[...o];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}},number:(e,t,r,a)=>{let{minimum:i,maximum:n,format:s,multipleOf:o,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;"string"==typeof s&&s.includes("int")?r.type="integer":r.type="number";let d="number"==typeof u&&u>=(i??-1/0),c="number"==typeof l&&l<=(n??1/0),h="draft-04"===t.target||"openapi-3.0"===t.target;d?h?(r.minimum=u,r.exclusiveMinimum=!0):r.exclusiveMinimum=u:"number"==typeof i&&(r.minimum=i),c?h?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l:"number"==typeof n&&(r.maximum=n),"number"==typeof o&&(r.multipleOf=o)},boolean:(e,t,r,a)=>{r.type="boolean"},bigint:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema")},symbol:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Symbols cannot be represented in JSON Schema")},null:(e,t,r,a)=>{"openapi-3.0"===t.target?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},undefined:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Undefined cannot be represented in JSON Schema")},void:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Void cannot be represented in JSON Schema")},never:(e,t,r,a)=>{r.not={}},any:(e,t,r,a)=>{},unknown:(e,t,r,a)=>{},date:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Date cannot be represented in JSON Schema")},enum:(e,t,r,a)=>{let i=iX(e._zod.def.entries);i.every(e=>"number"==typeof e)&&(r.type="number"),i.every(e=>"string"==typeof e)&&(r.type="string"),r.enum=i},literal:(e,t,r,a)=>{let i=e._zod.def,n=[];for(let e of i.values)if(void 0===e){if("throw"===t.unrepresentable)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e)if("throw"===t.unrepresentable)throw Error("BigInt literals cannot be represented in JSON Schema");else n.push(Number(e));else n.push(e);if(0===n.length);else if(1===n.length){let e=n[0];r.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?r.enum=[e]:r.const=e}else n.every(e=>"number"==typeof e)&&(r.type="number"),n.every(e=>"string"==typeof e)&&(r.type="string"),n.every(e=>"boolean"==typeof e)&&(r.type="boolean"),n.every(e=>null===e)&&(r.type="null"),r.enum=n},nan:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("NaN cannot be represented in JSON Schema")},template_literal:(e,t,r,a)=>{let i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");r.type="string",r.pattern=i.source},file:(e,t,r,a)=>{let i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:n,maximum:s,mime:o}=e._zod.bag;void 0!==n&&(i.minLength=n),void 0!==s&&(i.maxLength=s),o?1===o.length?(i.contentMediaType=o[0],Object.assign(r,i)):(Object.assign(r,i),r.anyOf=o.map(e=>({contentMediaType:e}))):Object.assign(r,i)},success:(e,t,r,a)=>{r.type="boolean"},custom:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")},function:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Function types cannot be represented in JSON Schema")},transform:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema")},map:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Map cannot be represented in JSON Schema")},set:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Set cannot be represented in JSON Schema")},array:(e,t,r,a)=>{let i=e._zod.def,{minimum:n,maximum:s}=e._zod.bag;"number"==typeof n&&(r.minItems=n),"number"==typeof s&&(r.maxItems=s),r.type="array",r.items=ld(i.element,t,{...a,path:[...a.path,"items"]})},object:(e,t,r,a)=>{let i=e._zod.def;r.type="object",r.properties={};let n=i.shape;for(let e in n)r.properties[e]=ld(n[e],t,{...a,path:[...a.path,"properties",e]});let s=new Set([...new Set(Object.keys(n))].filter(e=>{let r=i.shape[e]._zod;return"input"===t.io?void 0===r.optin:void 0===r.optout}));s.size>0&&(r.required=Array.from(s)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=ld(i.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):"output"===t.io&&(r.additionalProperties=!1)},union:(e,t,r,a)=>{let i=e._zod.def,n=!1===i.inclusive,s=i.options.map((e,r)=>ld(e,t,{...a,path:[...a.path,n?"oneOf":"anyOf",r]}));n?r.oneOf=s:r.anyOf=s},intersection:(e,t,r,a)=>{let i=e._zod.def,n=ld(i.left,t,{...a,path:[...a.path,"allOf",0]}),s=ld(i.right,t,{...a,path:[...a.path,"allOf",1]}),o=e=>"allOf"in e&&1===Object.keys(e).length;r.allOf=[...o(n)?n.allOf:[n],...o(s)?s.allOf:[s]]},tuple:(e,t,r,a)=>{let i=e._zod.def;r.type="array";let n="draft-2020-12"===t.target?"prefixItems":"items",s="draft-2020-12"===t.target||"openapi-3.0"===t.target?"items":"additionalItems",o=i.items.map((e,r)=>ld(e,t,{...a,path:[...a.path,n,r]})),l=i.rest?ld(i.rest,t,{...a,path:[...a.path,s,..."openapi-3.0"===t.target?[i.items.length]:[]]}):null;"draft-2020-12"===t.target?(r.prefixItems=o,l&&(r.items=l)):"openapi-3.0"===t.target?(r.items={anyOf:o},l&&r.items.anyOf.push(l),r.minItems=o.length,l||(r.maxItems=o.length)):(r.items=o,l&&(r.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;"number"==typeof u&&(r.minItems=u),"number"==typeof d&&(r.maxItems=d)},record:(e,t,r,a)=>{let i=e._zod.def;r.type="object";let n=i.keyType,s=n._zod.bag,o=s?.patterns;if("loose"===i.mode&&o&&o.size>0){let e=ld(i.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});for(let t of(r.patternProperties={},o))r.patternProperties[t.source]=e}else("draft-07"===t.target||"draft-2020-12"===t.target)&&(r.propertyNames=ld(i.keyType,t,{...a,path:[...a.path,"propertyNames"]})),r.additionalProperties=ld(i.valueType,t,{...a,path:[...a.path,"additionalProperties"]});let l=n._zod.values;if(l){let e=[...l].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(r.required=e)}},nullable:(e,t,r,a)=>{let i=e._zod.def,n=ld(i.innerType,t,a),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=i.innerType,r.nullable=!0):r.anyOf=[n,{type:"null"}]},nonoptional:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType},default:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},prefault:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType,"input"===t.io&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},catch:(e,t,r,a)=>{let i,n=e._zod.def;ld(n.innerType,t,a),t.seen.get(e).ref=n.innerType;try{i=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},pipe:(e,t,r,a)=>{let i=e._zod.def,n=i.in._zod.traits.has("$ZodTransform"),s="input"===t.io?n?i.out:i.in:i.out;ld(s,t,a),t.seen.get(e).ref=s},readonly:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType,r.readOnly=!0},promise:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType},optional:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType},lazy:(e,t,r,a)=>{let i=e._zod.innerType;ld(i,t,a),t.seen.get(e).ref=i}};function lg(e,t){if("_idmap"in e){let r=lu({...t,processors:lm}),a={};for(let t of e._idmap.entries()){let[e,a]=t;ld(a,r)}let i={};for(let n of(r.external={registry:e,uri:t?.uri,defs:a},e._idmap.entries())){let[e,t]=n;lc(r,t),i[e]=lh(r,t)}return Object.keys(a).length>0&&(i.__shared={["draft-2020-12"===r.target?"$defs":"definitions"]:a}),{schemas:i}}let r=lu({...t,processors:lm});return ld(e,r),lc(r,e),lh(r,e)}let ly=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function l_(e){return e.test.bind(e)}function lb(e,t){let r=t.match(ly);if(!r)return!1;let a=+r[1],i=+r[2],n=+r[3],s=!!r[5];return(a<=23&&i<=59&&n<=59||23==a&&59==i&&60==n)&&(!e||s)}lb.bind(void 0,!1),l_(/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i),l_(/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i),l_(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu),l_(/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i),l_(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),l_(/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i),l_(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),l_(/^(?:\/(?:[^~/]|~0|~1)*)*$/),l_(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),l_(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/);(y=S||(S={}))[y.Flag=1]="Flag",y[y.Basic=2]="Basic",y[y.Detailed=4]="Detailed";"u">typeof self&&self.location&&"null"!==self.location.origin?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");let lv=new WeakMap;var lw=class e{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=e9(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...iG(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...function(e){var t,r;let a,i=null!=e&&"object"==typeof e;if(i){let t=lv.get(e);if(t)return t}if(("object"==typeof(t=e)||"function"==typeof t)&&null!==t&&"~standard"in t&&"object"==typeof t["~standard"]&&null!==t["~standard"]&&"jsonSchema"in t["~standard"]&&!nB(e))a=e["~standard"].jsonSchema.input({target:"draft-07"});else if(nB(e)){let t=function(e,t=!1){return function e(t,r,a){var i,n;let s=a.get(t);if(void 0!==s)return s;if(nD(t))return nD(t)&&"typeName"in t._def&&"ZodEffects"===t._def.typeName?e(t._def.schema,r,a):t;if(nB(t)){let s=t;if(nB(t)&&"pipe"===t._zod.def.type&&(s=e(t._zod.def.in,r,a)),r)if(nZ(s)){let t={};for(let[i,n]of Object.entries(s._zod.def.shape))t[i]=e(n,r,a);s=na(s,{...s._zod.def,shape:t})}else if(nH(s)){let t=e(s._zod.def.element,r,a);s=na(s,{...s._zod.def,element:t})}else if(nB(i=s)&&"object"==typeof i&&null!==i&&"_zod"in i&&"object"==typeof i._zod&&null!==i._zod&&"def"in i._zod&&"object"==typeof i._zod.def&&null!==i._zod.def&&"type"in i._zod.def&&"optional"===i._zod.def.type?0:1){if(nB(n=s)&&"object"==typeof n&&null!==n&&"_zod"in n&&"object"==typeof n._zod&&null!==n._zod&&"def"in n._zod&&"object"==typeof n._zod.def&&null!==n._zod.def&&"type"in n._zod.def&&"nullable"===n._zod.def.type){let t=e(s._zod.def.innerType,r,a);s=na(s,{...s._zod.def,innerType:t})}}else{let t=e(s._zod.def.innerType,r,a);s=na(s,{...s._zod.def,innerType:t})}let o=nU.get(t);return o&&nU.add(s,o),a.set(t,s),s}throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}(e,t,new WeakMap)}(e,!0);a=nZ(t)?lg(function e(t,r=!1){if("object"==typeof t&&null!==t&&"_def"in t&&"object"==typeof t._def&&null!==t._def&&"typeName"in t._def&&"ZodObject"===t._def.typeName)return t.strict();if(nZ(t)){let a=t._zod.def.shape;if(r)for(let[i,n]of Object.entries(t._zod.def.shape)){if(nZ(n))a[i]=e(n,r);else if(nH(n)){let t=n._zod.def.element;nZ(t)&&(t=e(t,r)),a[i]=na(n,{...n._zod.def,element:t})}else a[i]=n;let t=nU.get(n);t&&nU.add(a[i],t)}let i=na(t,{...t._zod.def,shape:a,catchall:new nj({type:"never",...ni(void 0)})}),n=nU.get(t);return n&&nU.add(i,n),i}throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}(t,!0),void 0):lg(e,void 0)}else{let t,i,n,s,o,l,u,d,c;a=nD(e)?(r=e,s=(n=void 0!==(i="string"==typeof(t=void 0)?{...nV,name:t}:{...nV,...t}).name?[...i.basePath,i.definitionPath,i.name]:i.basePath,{...i,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(i.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...i.basePath,i.definitionPath,e],jsonSchema:void 0}]))}),u=ls(r._def,void 0===l?s:{...s,currentPath:[...s.basePath,s.definitionPath,l]},!1)??nQ(s),void 0!==d&&(u.title=d),s.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[s.openAiAnyTypeName]||(o[s.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===s.$refStrategy?"1":[...s.basePath,s.definitionPath,s.openAiAnyTypeName].join("/")}})),c=void 0===l?o?{...u,[s.definitionPath]:o}:u:{$ref:[..."relative"===s.$refStrategy?[]:s.basePath,s.definitionPath,l].join("/"),[s.definitionPath]:{...o,[l]:u}},"jsonSchema7"===s.target?c.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===s.target||"openAi"===s.target)&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===s.target&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c):e}return i&&null!=a&&"object"==typeof a&&lv.set(e,a),a}(t.data.schema),title:t.data.name}}})),edges:this.edges.map(t=>{let r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r})}}addNode(e,t,r){if(void 0!==t&&void 0!==this.nodes[t])throw Error(`Node with id ${t} already exists`);let a=t??to(),i={id:a,data:e,name:function(e,t){if(void 0!==e&&!e9(e))return e;if(!iG(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e}catch{return t.getName()}}(t,e),metadata:r};return this.nodes[a]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,r,a){if(void 0===this.nodes[e.id])throw Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw Error(`Target node ${t.id} not in graph`);let i={source:e.id,target:t.id,data:r,conditional:a};return this.edges.push(i),i}firstNode(){return lx(this)}lastNode(){return lk(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map(e=>e.id).every(e9)&&(r="");let a=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[a(e)]={...t,id:a(e)}});let i=e.edges.map(e=>({...e,source:a(e.source),target:a(e.target)}));this.edges=[...this.edges,...i];let n=e.firstNode(),s=e.lastNode();return[n?{id:a(n.id),data:n.data}:void 0,s?{id:a(s.id),data:s.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&lx(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&lk(this,[e.id])&&this.removeNode(e)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),r=new Map;Object.values(t).forEach(e=>{r.set(e,(r.get(e)||0)+1)});let a=e=>{let a=t[e];return e9(e)&&1===r.get(a)?a:e};return new e({nodes:Object.fromEntries(Object.entries(this.nodes).map(([e,t])=>[a(e),{...t,id:a(e)}])),edges:this.edges.map(e=>({...e,source:a(e.source),target:a(e.target)}))})}drawMermaid(e){let{withStyles:t,curveStyle:r,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},n=this.reid(),s=n.firstNode(),o=n.lastNode();return function(e,t,r){let{firstNode:a,lastNode:i,nodeColors:n,withStyles:s=!0,curveStyle:o="linear",wrapLabelNWords:l=9}=r??{},u=s?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
|
|
50
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let r of e.seen.entries()){let a=r[1];if(t===r[0]){i(r);continue}if(e.external){let a=e.external.registry.get(r[0])?.id;if(t!==r[0]&&a){i(r);continue}}if(e.metadataRegistry.get(r[0])?.id||a.cycle||a.count>1&&"ref"===e.reused){i(r);continue}}}function lh(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let a=t=>{let r=e.seen.get(t);if(null===r.ref)return;let i=r.def??r.schema,n={...i},s=r.ref;if(r.ref=null,s){a(s);let r=e.seen.get(s),o=r.schema;if(o.$ref&&("draft-07"===e.target||"draft-04"===e.target||"openapi-3.0"===e.target)?(i.allOf=i.allOf??[],i.allOf.push(o)):Object.assign(i,o),Object.assign(i,n),t._zod.parent===s)for(let e in i)"$ref"!==e&&"allOf"!==e&&(e in n||delete i[e]);if(o.$ref&&r.def)for(let e in i)"$ref"!==e&&"allOf"!==e&&e in r.def&&JSON.stringify(i[e])===JSON.stringify(r.def[e])&&delete i[e]}let o=t._zod.parent;if(o&&o!==s){a(o);let t=e.seen.get(o);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:r.path??[]})};for(let t of[...e.seen.entries()].reverse())a(t[0]);let i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let r=e.external.registry.get(t)?.id;if(!r)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(r)}Object.assign(i,r.def??r.schema);let n=e.metadataRegistry.get(t)?.id;void 0!==n&&i.id===n&&delete i.id;let s=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,s[e.defId]=e.def)}e.external||Object.keys(s).length>0&&("draft-2020-12"===e.target?i.$defs=s:i.definitions=s);try{let r=JSON.parse(JSON.stringify(i));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:lp(t,"input",e.processors),output:lp(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch(e){throw Error("Error converting schema to JSON.")}}let lp=(e,t,r={})=>a=>{let{libraryOptions:i,target:n}=a??{},s=lu({...i??{},target:n,io:t,processors:r});return ld(e,s),lc(s,e),lh(s,e)},lf={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},lm={string:(e,t,r,a)=>{r.type="string";let{minimum:i,maximum:n,format:s,patterns:o,contentEncoding:l}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof n&&(r.maxLength=n),s&&(r.format=lf[s]??s,""===r.format&&delete r.format,"time"===s&&delete r.format),l&&(r.contentEncoding=l),o&&o.size>0){let e=[...o];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}},number:(e,t,r,a)=>{let{minimum:i,maximum:n,format:s,multipleOf:o,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;"string"==typeof s&&s.includes("int")?r.type="integer":r.type="number";let d="number"==typeof u&&u>=(i??-1/0),c="number"==typeof l&&l<=(n??1/0),h="draft-04"===t.target||"openapi-3.0"===t.target;d?h?(r.minimum=u,r.exclusiveMinimum=!0):r.exclusiveMinimum=u:"number"==typeof i&&(r.minimum=i),c?h?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l:"number"==typeof n&&(r.maximum=n),"number"==typeof o&&(r.multipleOf=o)},boolean:(e,t,r,a)=>{r.type="boolean"},bigint:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema")},symbol:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Symbols cannot be represented in JSON Schema")},null:(e,t,r,a)=>{"openapi-3.0"===t.target?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},undefined:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Undefined cannot be represented in JSON Schema")},void:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Void cannot be represented in JSON Schema")},never:(e,t,r,a)=>{r.not={}},any:(e,t,r,a)=>{},unknown:(e,t,r,a)=>{},date:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Date cannot be represented in JSON Schema")},enum:(e,t,r,a)=>{let i=iX(e._zod.def.entries);i.every(e=>"number"==typeof e)&&(r.type="number"),i.every(e=>"string"==typeof e)&&(r.type="string"),r.enum=i},literal:(e,t,r,a)=>{let i=e._zod.def,n=[];for(let e of i.values)if(void 0===e){if("throw"===t.unrepresentable)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e)if("throw"===t.unrepresentable)throw Error("BigInt literals cannot be represented in JSON Schema");else n.push(Number(e));else n.push(e);if(0===n.length);else if(1===n.length){let e=n[0];r.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?r.enum=[e]:r.const=e}else n.every(e=>"number"==typeof e)&&(r.type="number"),n.every(e=>"string"==typeof e)&&(r.type="string"),n.every(e=>"boolean"==typeof e)&&(r.type="boolean"),n.every(e=>null===e)&&(r.type="null"),r.enum=n},nan:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("NaN cannot be represented in JSON Schema")},template_literal:(e,t,r,a)=>{let i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");r.type="string",r.pattern=i.source},file:(e,t,r,a)=>{let i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:n,maximum:s,mime:o}=e._zod.bag;void 0!==n&&(i.minLength=n),void 0!==s&&(i.maxLength=s),o?1===o.length?(i.contentMediaType=o[0],Object.assign(r,i)):(Object.assign(r,i),r.anyOf=o.map(e=>({contentMediaType:e}))):Object.assign(r,i)},success:(e,t,r,a)=>{r.type="boolean"},custom:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")},function:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Function types cannot be represented in JSON Schema")},transform:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema")},map:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Map cannot be represented in JSON Schema")},set:(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Set cannot be represented in JSON Schema")},array:(e,t,r,a)=>{let i=e._zod.def,{minimum:n,maximum:s}=e._zod.bag;"number"==typeof n&&(r.minItems=n),"number"==typeof s&&(r.maxItems=s),r.type="array",r.items=ld(i.element,t,{...a,path:[...a.path,"items"]})},object:(e,t,r,a)=>{let i=e._zod.def;r.type="object",r.properties={};let n=i.shape;for(let e in n)r.properties[e]=ld(n[e],t,{...a,path:[...a.path,"properties",e]});let s=new Set([...new Set(Object.keys(n))].filter(e=>{let r=i.shape[e]._zod;return"input"===t.io?void 0===r.optin:void 0===r.optout}));s.size>0&&(r.required=Array.from(s)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=ld(i.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):"output"===t.io&&(r.additionalProperties=!1)},union:(e,t,r,a)=>{let i=e._zod.def,n=!1===i.inclusive,s=i.options.map((e,r)=>ld(e,t,{...a,path:[...a.path,n?"oneOf":"anyOf",r]}));n?r.oneOf=s:r.anyOf=s},intersection:(e,t,r,a)=>{let i=e._zod.def,n=ld(i.left,t,{...a,path:[...a.path,"allOf",0]}),s=ld(i.right,t,{...a,path:[...a.path,"allOf",1]}),o=e=>"allOf"in e&&1===Object.keys(e).length;r.allOf=[...o(n)?n.allOf:[n],...o(s)?s.allOf:[s]]},tuple:(e,t,r,a)=>{let i=e._zod.def;r.type="array";let n="draft-2020-12"===t.target?"prefixItems":"items",s="draft-2020-12"===t.target||"openapi-3.0"===t.target?"items":"additionalItems",o=i.items.map((e,r)=>ld(e,t,{...a,path:[...a.path,n,r]})),l=i.rest?ld(i.rest,t,{...a,path:[...a.path,s,..."openapi-3.0"===t.target?[i.items.length]:[]]}):null;"draft-2020-12"===t.target?(r.prefixItems=o,l&&(r.items=l)):"openapi-3.0"===t.target?(r.items={anyOf:o},l&&r.items.anyOf.push(l),r.minItems=o.length,l||(r.maxItems=o.length)):(r.items=o,l&&(r.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;"number"==typeof u&&(r.minItems=u),"number"==typeof d&&(r.maxItems=d)},record:(e,t,r,a)=>{let i=e._zod.def;r.type="object";let n=i.keyType,s=n._zod.bag,o=s?.patterns;if("loose"===i.mode&&o&&o.size>0){let e=ld(i.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});for(let t of(r.patternProperties={},o))r.patternProperties[t.source]=e}else("draft-07"===t.target||"draft-2020-12"===t.target)&&(r.propertyNames=ld(i.keyType,t,{...a,path:[...a.path,"propertyNames"]})),r.additionalProperties=ld(i.valueType,t,{...a,path:[...a.path,"additionalProperties"]});let l=n._zod.values;if(l){let e=[...l].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(r.required=e)}},nullable:(e,t,r,a)=>{let i=e._zod.def,n=ld(i.innerType,t,a),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=i.innerType,r.nullable=!0):r.anyOf=[n,{type:"null"}]},nonoptional:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType},default:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},prefault:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType,"input"===t.io&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},catch:(e,t,r,a)=>{let i,n=e._zod.def;ld(n.innerType,t,a),t.seen.get(e).ref=n.innerType;try{i=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},pipe:(e,t,r,a)=>{let i=e._zod.def,n=i.in._zod.traits.has("$ZodTransform"),s="input"===t.io?n?i.out:i.in:i.out;ld(s,t,a),t.seen.get(e).ref=s},readonly:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType,r.readOnly=!0},promise:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType},optional:(e,t,r,a)=>{let i=e._zod.def;ld(i.innerType,t,a),t.seen.get(e).ref=i.innerType},lazy:(e,t,r,a)=>{let i=e._zod.innerType;ld(i,t,a),t.seen.get(e).ref=i}};function lg(e,t){if("_idmap"in e){let r=lu({...t,processors:lm}),a={};for(let t of e._idmap.entries()){let[e,a]=t;ld(a,r)}let i={};for(let n of(r.external={registry:e,uri:t?.uri,defs:a},e._idmap.entries())){let[e,t]=n;lc(r,t),i[e]=lh(r,t)}return Object.keys(a).length>0&&(i.__shared={["draft-2020-12"===r.target?"$defs":"definitions"]:a}),{schemas:i}}let r=lu({...t,processors:lm});return ld(e,r),lc(r,e),lh(r,e)}let ly=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function l_(e){return e.test.bind(e)}function lb(e,t){let r=t.match(ly);if(!r)return!1;let a=+r[1],i=+r[2],n=+r[3],s=!!r[5];return(a<=23&&i<=59&&n<=59||23==a&&59==i&&60==n)&&(!e||s)}lb.bind(void 0,!1),l_(/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i),l_(/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i),l_(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu),l_(/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i),l_(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),l_(/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i),l_(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),l_(/^(?:\/(?:[^~/]|~0|~1)*)*$/),l_(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),l_(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/);(y=S||(S={}))[y.Flag=1]="Flag",y[y.Basic=2]="Basic",y[y.Detailed=4]="Detailed";"u">typeof self&&self.location&&"null"!==self.location.origin?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");let lv=new WeakMap;var lw=class e{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=e5(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...iG(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...function(e){var t,r;let a,i=null!=e&&"object"==typeof e;if(i){let t=lv.get(e);if(t)return t}if(("object"==typeof(t=e)||"function"==typeof t)&&null!==t&&"~standard"in t&&"object"==typeof t["~standard"]&&null!==t["~standard"]&&"jsonSchema"in t["~standard"]&&!nD(e))a=e["~standard"].jsonSchema.input({target:"draft-07"});else if(nD(e)){let t=function(e,t=!1){return function e(t,r,a){var i,n;let s=a.get(t);if(void 0!==s)return s;if(nB(t))return nB(t)&&"typeName"in t._def&&"ZodEffects"===t._def.typeName?e(t._def.schema,r,a):t;if(nD(t)){let s=t;if(nD(t)&&"pipe"===t._zod.def.type&&(s=e(t._zod.def.in,r,a)),r)if(nZ(s)){let t={};for(let[i,n]of Object.entries(s._zod.def.shape))t[i]=e(n,r,a);s=na(s,{...s._zod.def,shape:t})}else if(nH(s)){let t=e(s._zod.def.element,r,a);s=na(s,{...s._zod.def,element:t})}else if(nD(i=s)&&"object"==typeof i&&null!==i&&"_zod"in i&&"object"==typeof i._zod&&null!==i._zod&&"def"in i._zod&&"object"==typeof i._zod.def&&null!==i._zod.def&&"type"in i._zod.def&&"optional"===i._zod.def.type?0:1){if(nD(n=s)&&"object"==typeof n&&null!==n&&"_zod"in n&&"object"==typeof n._zod&&null!==n._zod&&"def"in n._zod&&"object"==typeof n._zod.def&&null!==n._zod.def&&"type"in n._zod.def&&"nullable"===n._zod.def.type){let t=e(s._zod.def.innerType,r,a);s=na(s,{...s._zod.def,innerType:t})}}else{let t=e(s._zod.def.innerType,r,a);s=na(s,{...s._zod.def,innerType:t})}let o=nU.get(t);return o&&nU.add(s,o),a.set(t,s),s}throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}(e,t,new WeakMap)}(e,!0);a=nZ(t)?lg(function e(t,r=!1){if("object"==typeof t&&null!==t&&"_def"in t&&"object"==typeof t._def&&null!==t._def&&"typeName"in t._def&&"ZodObject"===t._def.typeName)return t.strict();if(nZ(t)){let a=t._zod.def.shape;if(r)for(let[i,n]of Object.entries(t._zod.def.shape)){if(nZ(n))a[i]=e(n,r);else if(nH(n)){let t=n._zod.def.element;nZ(t)&&(t=e(t,r)),a[i]=na(n,{...n._zod.def,element:t})}else a[i]=n;let t=nU.get(n);t&&nU.add(a[i],t)}let i=na(t,{...t._zod.def,shape:a,catchall:new nj({type:"never",...ni(void 0)})}),n=nU.get(t);return n&&nU.add(i,n),i}throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}(t,!0),void 0):lg(e,void 0)}else{let t,i,n,s,o,l,u,d,c;a=nB(e)?(r=e,s=(n=void 0!==(i="string"==typeof(t=void 0)?{...nV,name:t}:{...nV,...t}).name?[...i.basePath,i.definitionPath,i.name]:i.basePath,{...i,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(i.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...i.basePath,i.definitionPath,e],jsonSchema:void 0}]))}),u=ls(r._def,void 0===l?s:{...s,currentPath:[...s.basePath,s.definitionPath,l]},!1)??nQ(s),void 0!==d&&(u.title=d),s.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[s.openAiAnyTypeName]||(o[s.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===s.$refStrategy?"1":[...s.basePath,s.definitionPath,s.openAiAnyTypeName].join("/")}})),c=void 0===l?o?{...u,[s.definitionPath]:o}:u:{$ref:[..."relative"===s.$refStrategy?[]:s.basePath,s.definitionPath,l].join("/"),[s.definitionPath]:{...o,[l]:u}},"jsonSchema7"===s.target?c.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===s.target||"openAi"===s.target)&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===s.target&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c):e}return i&&null!=a&&"object"==typeof a&&lv.set(e,a),a}(t.data.schema),title:t.data.name}}})),edges:this.edges.map(t=>{let r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r})}}addNode(e,t,r){if(void 0!==t&&void 0!==this.nodes[t])throw Error(`Node with id ${t} already exists`);let a=t??to(),i={id:a,data:e,name:function(e,t){if(void 0!==e&&!e5(e))return e;if(!iG(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e}catch{return t.getName()}}(t,e),metadata:r};return this.nodes[a]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,r,a){if(void 0===this.nodes[e.id])throw Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw Error(`Target node ${t.id} not in graph`);let i={source:e.id,target:t.id,data:r,conditional:a};return this.edges.push(i),i}firstNode(){return lx(this)}lastNode(){return lk(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map(e=>e.id).every(e5)&&(r="");let a=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[a(e)]={...t,id:a(e)}});let i=e.edges.map(e=>({...e,source:a(e.source),target:a(e.target)}));this.edges=[...this.edges,...i];let n=e.firstNode(),s=e.lastNode();return[n?{id:a(n.id),data:n.data}:void 0,s?{id:a(s.id),data:s.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&lx(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&lk(this,[e.id])&&this.removeNode(e)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),r=new Map;Object.values(t).forEach(e=>{r.set(e,(r.get(e)||0)+1)});let a=e=>{let a=t[e];return e5(e)&&1===r.get(a)?a:e};return new e({nodes:Object.fromEntries(Object.entries(this.nodes).map(([e,t])=>[a(e),{...t,id:a(e)}])),edges:this.edges.map(e=>({...e,source:a(e.source),target:a(e.target)}))})}drawMermaid(e){let{withStyles:t,curveStyle:r,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},n=this.reid(),s=n.firstNode(),o=n.lastNode();return function(e,t,r){let{firstNode:a,lastNode:i,nodeColors:n,withStyles:s=!0,curveStyle:o="linear",wrapLabelNWords:l=9}=r??{},u=s?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
|
|
51
51
|
graph TD;
|
|
52
52
|
`:"graph TD;\n";if(s){let t="default",r={[t]:"{0}({1})"};for(let[n,s]of(void 0!==a&&(r[a]="{0}([{1}]):::first"),void 0!==i&&(r[i]="{0}([{1}]):::last"),Object.entries(e))){let e=s.name.split(":").pop()??"",a=nJ.some(t=>e.startsWith(t)&&e.endsWith(t))?`<p>${e}</p>`:e;Object.keys(s.metadata??{}).length&&(a+=`<hr/><small><em>${Object.entries(s.metadata??{}).map(([e,t])=>`${e} = ${t}`).join("\n")}</em></small>`);let i=(r[n]??r[t]).replace("{0}",nq(n)).replace("{1}",a);u+=` ${i}
|
|
53
53
|
`}}let d={};for(let e of t){let t=e.source.split(":"),r=e.target.split(":"),a=t.filter((e,t)=>e===r[t]).join(":");d[a]||(d[a]=[]),d[a].push(e)}let c=new Set;function h(e,t){let r=1===e.length&&e[0].source===e[0].target;if(t&&!r){let e=t.split(":").pop();if(c.has(t))throw Error(`Found duplicate subgraph '${e}' at '${t} -- 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.`);c.add(t),u+=` subgraph ${e}
|
|
54
54
|
`}for(let e of[...Object.keys(d).filter(e=>e.startsWith(`${t}:`)&&e!==t&&e.split(":").length===t.split(":").length+1)].sort((e,t)=>e.split(":").length-t.split(":").length))h(d[e],e);for(let t of e){let{source:e,target:r,data:a,conditional:i}=t,n="";if(void 0!==a){let e=a,t=e.split(" ");t.length>l&&(e=Array.from({length:Math.ceil(t.length/l)},(e,r)=>t.slice(r*l,(r+1)*l).join(" ")).join(" <br> ")),n=i?` -. ${e} .-> `:` -- ${e} --> `}else n=i?" -.-> ":" --> ";u+=` ${nq(e)}${n}${nq(r)};
|
|
55
55
|
`}t&&!r&&(u+=" end\n")}for(let e in h(d[""]??[],""),d)e.includes(":")||""===e||h(d[e],e);return s&&(u+=function(e){let t="";for(let[r,a]of Object.entries(e))t+=` classDef ${r} ${a};
|
|
56
|
-
`;return t}(n??{})),u}(n.nodes,n.edges,{firstNode:s?.id,lastNode:o?.id,withStyles:t,curveStyle:r,nodeColors:a,wrapLabelNWords:i})}async drawMermaidPng(e){return nG(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function lx(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),a=[];for(let i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||a.push(i);return 1===a.length?a[0]:void 0}function lk(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),a=[];for(let i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||a.push(i);return 1===a.length?a[0]:void 0}function lS(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}function
|
|
56
|
+
`;return t}(n??{})),u}(n.nodes,n.edges,{firstNode:s?.id,lastNode:o?.id,withStyles:t,curveStyle:r,nodeColors:a,wrapLabelNWords:i})}async drawMermaidPng(e){return nG(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function lx(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),a=[];for(let i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||a.push(i);return 1===a.length?a[0]:void 0}function lk(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),a=[];for(let i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||a.push(i);return 1===a.length?a[0]:void 0}function lS(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}function lT(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*lE(e,t){for(;;){let{value:r,done:a}=a8.runWithConfig(is(e),t.next.bind(t),!0);if(a)break;yield r}}async function*lA(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:a,done:i}=await a8.runWithConfig(is(e),r.next.bind(t),!0);if(i)break;yield a}}e.s([],38570),e.i(38570),e.i(937904),e.s(["defaultErrorMap",0,n6,"getErrorMap",0,n8,"setErrorMap",0,n3],277290),e.i(277290),e.i(665354),e.s([],527404),e.i(527404),e.i(904783),e.i(965638),e.i(169790),e.s(["BRAND",0,oa,"DIRTY",0,si,"EMPTY_PATH",0,se,"INVALID",0,sa,"NEVER",0,sa,"OK",0,sn,"ParseStatus",0,sr,"Schema",0,sp,"ZodAny",0,sD,"ZodArray",0,sH,"ZodBigInt",0,sN,"ZodBoolean",0,sR,"ZodBranded",0,oi,"ZodCatch",0,ot,"ZodDate",0,sM,"ZodDefault",0,oe,"ZodDiscriminatedUnion",0,sW,"ZodEffects",0,s3,"ZodEnum",0,s9,"ZodError",0,n9,"ZodFirstPartyTypeKind",0,k,"ZodFunction",0,s0,"ZodIntersection",0,sV,"ZodIssueCode",0,n2,"ZodLazy",0,s1,"ZodLiteral",0,s2,"ZodMap",0,sY,"ZodNaN",0,or,"ZodNativeEnum",0,s6,"ZodNever",0,sF,"ZodNull",0,sU,"ZodNullable",0,s7,"ZodNumber",0,sP,"ZodObject",0,sq,"ZodOptional",0,s8,"ZodParsedType",0,n0,"ZodPipeline",0,on,"ZodPromise",0,s5,"ZodReadonly",0,os,"ZodRecord",0,sQ,"ZodSchema",0,sp,"ZodSet",0,sX,"ZodString",0,s$,"ZodSymbol",0,sz,"ZodTransformer",0,s3,"ZodTuple",0,sK,"ZodType",0,sp,"ZodUndefined",0,sL,"ZodUnion",0,sJ,"ZodUnknown",0,sB,"ZodVoid",0,sZ,"addIssueToContext",0,st,"any",0,ov,"array",0,oS,"bigint",0,of,"boolean",0,om,"coerce",0,oW,"custom",0,ol,"date",0,og,"datetimeRegex",0,sj,"defaultErrorMap",0,n6,"discriminatedUnion",0,oI,"effect",0,oD,"enum",0,oz,"function",0,oN,"getErrorMap",0,n8,"getParsedType",0,n1,"instanceof",0,od,"intersection",0,oO,"isAborted",0,ss,"isAsync",0,su,"isDirty",0,so,"isValid",0,sl,"late",0,ou,"lazy",0,oR,"literal",0,oM,"makeIssue",0,n7,"map",0,o$,"nan",0,op,"nativeEnum",0,oL,"never",0,ox,"null",0,ob,"nullable",0,oF,"number",0,oh,"object",0,oT,"objectUtil",0,w,"oboolean",0,oG,"onumber",0,oJ,"optional",0,oB,"ostring",0,oq,"pipeline",0,oH,"preprocess",0,oZ,"promise",0,oU,"quotelessJson",0,n4,"record",0,oj,"set",0,oP,"setErrorMap",0,n3,"strictObject",0,oE,"string",0,oc,"symbol",0,oy,"transformer",0,oD,"tuple",0,oC,"undefined",0,o_,"union",0,oA,"unknown",0,ow,"util",0,v,"void",0,ok],788685);var lI=e.i(788685),lI=lI;function lO(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}var lC=class extends N{lc_runnable=!0;name;getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new l$({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new lj({bound:this,config:e,kwargs:{}})}withFallbacks(e){return new lz({runnable:this,fallbacks:Array.isArray(e)?e:e.fallbacks})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(ia);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([e])=>"runId"!==e));return Array.from({length:t},(t,a)=>ia(0===a?e:r))}return Array.from({length:t},()=>ia(e))}async batch(e,t,r){let a=this._getOptionsList(t??{},e.length),i=new iq({maxConcurrency:a[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:e=>{throw e}});return Promise.all(e.map((e,t)=>i.call(async()=>{try{return await this.invoke(e,a[t])}catch(e){if(r?.returnExceptions)return e;throw e}})))}async *_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let r=ia(t),a=new ic({generator:this._streamIterator(e,r),config:r});return await a.setup,iu.fromAsyncGenerator(a)}_separateRunnableConfigFromCallOptions(e){let t;t=void 0===e?ia(e):ia({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){let a,i=ia(r),n=await (await it(i))?.handleChainStart(this.toJSON(),lO(t,"input"),i.runId,i?.runType,void 0,void 0,i?.runName??this.getName());delete i.runId;try{a=await io(e.call(this,t,i,n),i.signal)}catch(e){throw await n?.handleChainError(e),e}return await n?.handleChainEnd(lO(a,"output")),a}async _batchWithConfig(e,t,r,a){let i,n=this._getOptionsList(r??{},t.length),s=await Promise.all(n.map(it)),o=await Promise.all(s.map(async(e,r)=>{let a=await e?.handleChainStart(this.toJSON(),lO(t[r],"input"),n[r].runId,n[r].runType,void 0,void 0,n[r].runName??this.getName());return delete n[r].runId,a}));try{i=await io(e.call(this,t,n,o,a),n?.[0]?.signal)}catch(e){throw await Promise.all(o.map(t=>t?.handleChainError(e))),e}return await Promise.all(o.map(e=>e?.handleChainEnd(lO(i,"output")))),i}_concatOutputChunks(e,t){return function e(t,r){if(Array.isArray(t)&&Array.isArray(r))return t.concat(r);if("string"==typeof t&&"string"==typeof r)return t+r;if("number"==typeof t&&"number"==typeof r)return t+r;if("concat"in t&&"function"==typeof t.concat)return t.concat(r);if("object"==typeof t&&"object"==typeof r){let a={...t};for(let[t,i]of Object.entries(r))t in a&&!Array.isArray(a[t])?a[t]=e(a[t],i):a[t]=i;return a}else throw Error(`Cannot concat ${typeof t} and ${typeof r}`)}(e,t)}async *_transformStreamWithConfig(e,t,r){let a,i,n,s=!0,o=!0,l=ia(r),u=await it(l),d=this;async function*c(){for await(let t of e){if(s)if(void 0===a)a=t;else try{a=d._concatOutputChunks(a,t)}catch{a=void 0,s=!1}yield t}}try{let e=await ih(t.bind(this),c(),async()=>u?.handleChainStart(this.toJSON(),{input:""},l.runId,l.runType,void 0,void 0,l.runName??this.getName(),void 0,{lc_defers_inputs:!0}),l.signal,l);delete l.runId,n=e.setup;let r=n?.handlers.find(iN),a=e.output;void 0!==r&&void 0!==n&&(a=r.tapOutputIterable(n.runId,a));let s=n?.handlers.find(iI);for await(let e of(void 0!==s&&void 0!==n&&(a=s.tapOutputIterable(n.runId,a)),a))if(yield e,o)if(void 0===i)i=e;else try{i=this._concatOutputChunks(i,e)}catch{i=void 0,o=!1}}catch(e){throw await n?.handleChainError(e,void 0,void 0,void 0,{inputs:lO(a,"input")}),e}await n?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:lO(a,"input")})}getGraph(e){let t=new lw,r=t.addNode({name:`${this.getName()}Input`,schema:lI.any()}),a=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:lI.any()});return t.addEdge(r,a),t.addEdge(a,i),t}pipe(e){return new lP({first:this,last:lL(e)})}pick(e){return this.pipe(new lD(e))}assign(e){return this.pipe(new lU(new lN({steps:e})))}async *transform(e,t){let r;for await(let t of e)r=void 0===r?t:this._concatOutputChunks(r,t);yield*this._streamIterator(r,ia(t))}async *streamLog(e,t,r){let a=new ij({...r,autoClose:!1,_schemaFormat:"original"}),i=ia(t);yield*this._streamLog(e,a,i)}async *_streamLog(e,t,r){let{callbacks:a}=r;if(void 0===a)r.callbacks=[t];else if(Array.isArray(a))r.callbacks=a.concat([t]);else{let e=a.copy();e.addHandler(t,!0),r.callbacks=e}let i=this.stream(e,r),n=async function(){try{for await(let e of(await i)){let r=new iE({ops:[{op:"add",path:"/streamed_output/-",value:e}]});await t.writer.write(r)}}finally{await t.writer.close()}}();try{for await(let e of t)yield e}finally{await n}}streamEvents(e,t,r){var a;let i,n,s;if("v1"===t.version)i=this._streamEventsV1(e,t,r);else if("v2"===t.version)i=this._streamEventsV2(e,t,r);else throw Error('Only versions "v1" and "v2" of the schema are currently supported.');if("text/event-stream"!==t.encoding)return iu.fromAsyncGenerator(i);return a=i,n=new TextEncoder,s=new ReadableStream({async start(e){for await(let t of a)e.enqueue(n.encode(`event: data
|
|
57
57
|
data: ${JSON.stringify(t)}
|
|
58
58
|
|
|
59
|
-
`));e.enqueue(n.encode("event: end\n\n")),e.close()}}),iu.fromReadableStream(s)}async *_streamEventsV2(e,t,r){let a,i=new iR({...r,autoClose:!1}),n=ia(t),s=n.runId??tl();n.runId=s;let o=n.callbacks;if(void 0===o)n.callbacks=[i];else if(Array.isArray(o))n.callbacks=o.concat(i);else{let e=o.copy();e.addHandler(i,!0),n.callbacks=e}let l=new AbortController,u=this,d=async function(){let t;try{if(n.signal)if("any"in AbortSignal)t=AbortSignal.any([l.signal,n.signal]);else{let e=new AbortController;n.signal.addEventListener("abort",()=>e.abort(),{once:!0}),l.signal.addEventListener("abort",()=>e.abort(),{once:!0}),t=e.signal}else t=l.signal;let r=await u.stream(e,{...n,signal:t});for await(let e of i.tapOutputIterable(s,r))if(l.signal.aborted)break}finally{await i.finish()}}(),c=!1;try{for await(let t of i){if(!c){t.data.input=e,c=!0,a=t.run_id,yield t;continue}t.run_id===a&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t}}finally{l.abort(),await d}}async *_streamEventsV1(e,t,r){let a,i=!1,n=ia(t),s=n.tags??[],o=n.metadata??{},l=n.runName??this.getName(),u=new ij({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new iW({...r});for await(let t of this._streamLog(e,u,n)){if(void 0===(a=a?a.concat(t):iA.fromRunLogPatch(t)).state)throw Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let t={...a.state},r={run_id:t.id,event:`on_${t.type}_start`,name:l,tags:s,metadata:o,data:{input:e}};d.includeEvent(r,t.type)&&(yield r)}for(let e of[...new Set(t.ops.filter(e=>e.path.startsWith("/logs/")).map(e=>e.path.split("/")[2]))]){let t,r={},i=a.state.logs[e];if("start"==(t=void 0===i.end_time?i.streamed_output.length>0?"stream":"start":"end"))void 0!==i.inputs&&(r.input=i.inputs);else if("end"===t)void 0!==i.inputs&&(r.input=i.inputs),r.output=i.final_output;else if("stream"===t){let e=i.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);r={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:r}}let{state:r}=a;if(r.streamed_output.length>0){let e=r.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${r.name}"`);let t={chunk:r.streamed_output[0]};r.streamed_output=[];let a={event:`on_${r.type}_stream`,run_id:r.id,tags:s,metadata:o,name:l,data:t};d.includeEvent(a,r.type)&&(yield a)}}let c=a?.state;if(void 0!==c){let e={event:`on_${c.type}_end`,name:l,run_id:c.id,tags:s,metadata:o,data:{output:c.final_output}};d.includeEvent(e,c.type)&&(yield e)}}static isRunnable(e){return iG(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new lj({bound:this,config:{},configFactories:[a=>({callbacks:[new iJ({config:a,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){var t,r,a,i,n;let s,o;return t=this,s=(r=e).name??t.getName(),o=r.description??(nB(a=r.schema)?nU.get(a)?.description:nD(a)||"description"in a&&"string"==typeof a.description?a.description:void 0),new lD(!(!(n=i=r.schema)||"object"!=typeof n||Array.isArray(n))&&(nB(n)||nD(n))&&(nD(i)?"ZodString"===i._def.typeName:!!nB(i)&&"string"===i._zod.def.type)?{name:s,description:o,schema:lI.object({input:lI.string()}).transform(e=>e.input),bound:t}:{name:s,description:o,schema:r.schema,bound:t})}},lj=class e extends lC{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let t=ir(this.config,...e);return ir(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new lP({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(t,this.kwargs))}async batch(e,t,r){let a=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig(ia(e),this.kwargs))):await this._mergeConfig(ia(t),this.kwargs);return this.bound.batch(e,a,r)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async *_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(ia(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(ia(t),this.kwargs))}async *transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(ia(t),this.kwargs))}streamEvents(e,t,r){let a=this,i=async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig(ia(t),a.kwargs),version:t.version},r)};return iu.fromAsyncGenerator(i())}static isRunnableBinding(e){return e.bound&&lC.isRunnable(e.bound)}withListeners({onStart:t,onEnd:r,onError:a}){return new e({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[e=>({callbacks:[new iJ({config:e,onStart:t,onEnd:r,onError:a})]})]})}},lP=class extends lj{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){let a=e>1?`retry:attempt:${e}`:void 0;return ii(t,{callbacks:r?.getChild(a)})}async _invoke(e,t,r){return iF(a=>super.invoke(e,this._patchConfigForRetry(a,t,r)),{onFailedAttempt:({error:t})=>this.onFailedAttempt(t,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,a){let i={};try{await iF(async n=>{let s,o=e.map((e,t)=>t).filter(e=>void 0===i[e.toString()]||i[e.toString()]instanceof Error),l=o.map(t=>e[t]),u=o.map(e=>this._patchConfigForRetry(n,t?.[e],r?.[e])),d=await super.batch(l,u,{...a,returnExceptions:!0});for(let e=0;e<d.length;e+=1){let t=d[e],r=o[e];t instanceof Error&&void 0===s&&((s=t).input=l[e]),i[r.toString()]=t}if(s)throw s;return d},{onFailedAttempt:({error:e})=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(a?.returnExceptions!==!0)throw e}return Object.keys(i).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>i[parseInt(e,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}},l$=class e extends lC{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){let r,a=ia(t),i=await (await it(a))?.handleChainStart(this.toJSON(),lO(e,"input"),a.runId,void 0,void 0,void 0,a?.runName);delete a.runId;let n=e;try{let e=[this.first,...this.middle];for(let t=0;t<e.length;t+=1)n=await io(e[t].invoke(n,ii(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)})),a.signal);if(a.signal?.aborted)throw il(a.signal);r=await this.last.invoke(n,ii(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(lO(r,"output")),r}async batch(e,t,r){let a=this._getOptionsList(t??{},e.length),i=await Promise.all(a.map(it)),n=await Promise.all(i.map(async(t,r)=>{let i=await t?.handleChainStart(this.toJSON(),lO(e[r],"input"),a[r].runId,void 0,void 0,void 0,a[r].runName);return delete a[r].runId,i})),s=e;try{for(let e=0;e<this.steps.length;e+=1)s=await io(this.steps[e].batch(s,n.map((t,r)=>{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return ii(a[r],{callbacks:i})}),r),a[0]?.signal)}catch(e){throw await Promise.all(n.map(t=>t?.handleChainError(e))),e}return await Promise.all(n.map(e=>e?.handleChainEnd(lO(s,"output")))),s}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async *_streamIterator(e,t){let r,a=await it(t),{runId:i,...n}=t??{},s=await a?.handleChainStart(this.toJSON(),lO(e,"input"),i,void 0,void 0,void 0,n?.runName),o=[this.first,...this.middle,this.last],l=!0;async function*u(){yield e}try{let e=o[0].transform(u(),ii(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let t=1;t<o.length;t+=1)e=await o[t].transform(e,ii(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)}));for await(let a of e)if(t?.signal?.throwIfAborted(),yield a,l)if(void 0===r)r=a;else try{r=this._concatOutputChunks(r,a)}catch{r=void 0,l=!1}}catch(e){throw await s?.handleChainError(e),e}await s?.handleChainEnd(lO(r,"output"))}getGraph(e){let t=new lw,r=null;return this.steps.forEach((a,i)=>{let n=a.getGraph(e);0!==i&&n.trimFirstNode(),i!==this.steps.length-1&&n.trimLastNode(),t.extend(n);let s=n.firstNode();if(!s)throw Error(`Runnable ${a} has no first node`);r&&t.addEdge(r,s),r=n.lastNode()}),t}pipe(t){return new e(e.isRunnableSequence(t)?{first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}:{first:this.first,middle:[...this.middle,this.last],last:lz(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&lC.isRunnable(e)}static from([t,...r],a){let i={};return"string"==typeof a?i.name=a:void 0!==a&&(i=a),new e({...i,first:lz(t),middle:r.slice(0,-1).map(lz),last:lz(r[r.length-1])})}},lN=class e extends lC{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){for(const[t,r]of(super(e),this.steps={},Object.entries(e.steps)))this.steps[t]=lz(r)}static from(t){return new e({steps:t})}async invoke(e,t){let r=ia(t),a=await (await it(r))?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let i={};try{let t=Object.entries(this.steps).map(async([t,n])=>{i[t]=await n.invoke(e,ii(r,{callbacks:a?.getChild(`map:key:${t}`)}))});await io(Promise.all(t),r.signal)}catch(e){throw await a?.handleChainError(e),e}return await a?.handleChainEnd(i),i}async *_transform(e,t,r){let a={...this.steps},i=id(e,Object.keys(a).length),n=new Map(Object.entries(a).map(([e,a],n)=>{let s=a.transform(i[n],ii(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,s.next().then(t=>({key:e,gen:s,result:t}))]}));for(;n.size;){let{key:e,result:t,gen:a}=await io(Promise.race(n.values()),r?.signal);n.delete(e),t.done||(yield{[e]:t.value},n.set(e,a.next().then(t=>({key:e,gen:a,result:t}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=ia(t),i=new ic({generator:this.transform(r(),a),config:a});return await i.setup,iu.fromAsyncGenerator(i)}},lR=class e extends lC{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!aq(e.func))throw Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){let[r]=this._getOptionsList(t??{},1),a=await it(r);return io(this.func(ii(r,{callbacks:a}),e),r?.signal)}async *_streamIterator(e,t){let[r]=this._getOptionsList(t??{},1),a=await this.invoke(e,t);if(lE(a)){for await(let e of a)r?.signal?.throwIfAborted(),yield e;return}if(null!=a&&"object"==typeof a&&"next"in a&&"function"==typeof a.next){for(;;){r?.signal?.throwIfAborted();let e=a.next();if(e.done)break;yield e.value}return}yield a}static from(t){return new e({func:t})}},lM=class e extends lC{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(aq(e.func))return lR.from(e.func);super(e),function(e){if(aq(e))throw Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}(e.func),this.func=e.func}static from(t){return new e({func:t})}async _invoke(e,t,r){return new Promise((a,i)=>{let n=ii(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});a8.runWithConfig(is(n),async()=>{try{let r=await this.func(e,{...n});if(r&&lC.isRunnable(r)){if(t?.recursionLimit===0)throw Error("Recursion limit reached.");r=await r.invoke(e,{...n,recursionLimit:(n.recursionLimit??25)-1})}else if(lE(r)){let e;for await(let a of lA(n,r))if(t?.signal?.throwIfAborted(),void 0===e)e=a;else try{e=this._concatOutputChunks(e,a)}catch{e=a}r=e}else if(lS(r)){let e;for(let a of lT(n,r))if(t?.signal?.throwIfAborted(),void 0===e)e=a;else try{e=this._concatOutputChunks(e,a)}catch{e=a}r=e}a(r)}catch(e){i(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async *_transform(e,t,r){let a;for await(let t of e)if(void 0===a)a=t;else try{a=this._concatOutputChunks(a,t)}catch{a=t}let i=ii(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??25)-1}),n=await new Promise((e,t)=>{a8.runWithConfig(is(i),async()=>{try{e(await this.func(a,{...i,config:i}))}catch(e){t(e)}})});if(n&&lC.isRunnable(n)){if(r?.recursionLimit===0)throw Error("Recursion limit reached.");for await(let e of(await n.stream(a,i)))yield e}else if(lE(n))for await(let e of lA(i,n))r?.signal?.throwIfAborted(),yield e;else if(lS(n))for(let e of lT(i,n))r?.signal?.throwIfAborted(),yield e;else yield n}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=ia(t),i=new ic({generator:this.transform(r(),a),config:a});return await i.setup,iu.fromAsyncGenerator(i)}},lL=class extends lC{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){for(let e of(yield this.runnable,this.fallbacks))yield e}async invoke(e,t){let r=ia(t),a=await it(r),{runId:i,...n}=r,s=await a?.handleChainStart(this.toJSON(),lO(e,"input"),i,void 0,void 0,void 0,n?.runName),o=ii(n,{callbacks:s?.getChild()});return await a8.runWithConfig(o,async()=>{let t;for(let a of this.runnables()){r?.signal?.throwIfAborted();try{let t=await a.invoke(e,o);return await s?.handleChainEnd(lO(t,"output")),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw Error("No error stored at end of fallback.");throw await s?.handleChainError(t),t})}async *_streamIterator(e,t){let r,a,i,n=ia(t),s=await it(n),{runId:o,...l}=n,u=await s?.handleChainStart(this.toJSON(),lO(e,"input"),o,void 0,void 0,void 0,l?.runName);for(let t of this.runnables()){n?.signal?.throwIfAborted();let i=ii(l,{callbacks:u?.getChild()});try{a=lA(i,await t.stream(e,i));break}catch(e){void 0===r&&(r=e)}}if(void 0===a){let e=r??Error("No error stored at end of fallback.");throw await u?.handleChainError(e),e}try{for await(let e of a){yield e;try{i=void 0===i?i:this._concatOutputChunks(i,e)}catch{i=void 0}}}catch(e){throw await u?.handleChainError(e),e}await u?.handleChainEnd(lO(i,"output"))}async batch(e,t,r){let a;if(r?.returnExceptions)throw Error("Not implemented.");let i=this._getOptionsList(t??{},e.length),n=await Promise.all(i.map(e=>it(e))),s=await Promise.all(n.map(async(t,r)=>{let a=await t?.handleChainStart(this.toJSON(),lO(e[r],"input"),i[r].runId,void 0,void 0,void 0,i[r].runName);return delete i[r].runId,a}));for(let t of this.runnables()){i[0].signal?.throwIfAborted();try{let a=await t.batch(e,s.map((e,t)=>ii(i[t],{callbacks:e?.getChild()})),r);return await Promise.all(s.map((e,t)=>e?.handleChainEnd(lO(a[t],"output")))),a}catch(e){void 0===a&&(a=e)}}if(!a)throw Error("No error stored at end of fallbacks.");throw await Promise.all(s.map(e=>e?.handleChainError(a))),a}};function lz(e){if("function"==typeof e)return new lM({func:e});if(lC.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw Error(`Expected a Runnable, function or object.
|
|
60
|
-
Instead got an unsupported type.`);{let t={};for(let[r,a]of Object.entries(e))t[r]=lz(a);return new lN({steps:t})}}var lU=class extends lC{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof lN&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){let r=await this.mapper.invoke(e,t);return{...e,...r}}async *_transform(e,t,r){let a=this.mapper.getStepsKeys(),[i,n]=id(e),s=this.mapper.transform(n,ii(r,{callbacks:t?.getChild()})),o=s.next();for await(let e of i){if("object"!=typeof e||Array.isArray(e))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof e}`);let t=Object.fromEntries(Object.entries(e).filter(([e])=>!a.includes(e)));Object.keys(t).length>0&&(yield t)}for await(let e of(yield(await o).value,s))yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=ia(t),i=new ic({generator:this.transform(r(),a),config:a});return await i.setup,iu.fromAsyncGenerator(i)}},lB=class extends lC{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){("string"==typeof e||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if("string"==typeof this.keys)return e[this.keys];{let t=this.keys.map(t=>[t,e[t]]).filter(e=>void 0!==e[1]);return 0===t.length?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async *_transform(e){for await(let t of e){let e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=ia(t),i=new ic({generator:this.transform(r(),a),config:a});return await i.setup,iu.fromAsyncGenerator(i)}},lD=class extends lj{name;description;schema;constructor(e){super({bound:l$.from([lM.from(async e=>{let t;if(eP(e))try{t=await nF(this.schema,e.args)}catch{throw new e$("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function lF(e,t){switch(e.type){case"text-delta":return{type:"text",text:e.text};case"reasoning-delta":return{type:"reasoning",reasoning:e.reasoning};case"data-delta":{let r={...t??{},data:e.data};return e.encoding&&(r.encoding=e.encoding),r}case"block-delta":return e.fields}}function lZ(e,t){if(t.content)return e?function(e,t){if(e.type!==t.type)return structuredClone(t);switch(t.type){case"text":return{...e,...t,text:`${"text"in e?e.text:""}${t.text}`};case"reasoning":return{...e,...t,reasoning:`${"reasoning"in e?e.reasoning:""}${t.reasoning}`};case"tool_call_chunk":case"server_tool_call_chunk":{let r={...e,...t};return null==t.id&&"id"in e&&null!=e.id&&(r.id=e.id),null==t.name&&"name"in e&&null!=e.name&&(r.name=e.name),r.args=`${("args"in e?e.args:"")??""}${t.args??""}`,r}default:return{...e,...t}}}(e,t.content):t.content;switch(t.delta.type){case"text-delta":if(e?.type==="text")return{...e,text:`${"text"in e?e.text:""}${t.delta.text}`};return lF(t.delta,e);case"reasoning-delta":if(e?.type==="reasoning")return{...e,reasoning:`${"reasoning"in e?e.reasoning:""}${t.delta.reasoning}`};return lF(t.delta,e);case"data-delta":{let r={...e??{}};return r.data=`${r.data??""}${t.delta.data}`,t.delta.encoding&&(r.encoding=t.delta.encoding),r}case"block-delta":return{...e??{},...t.delta.fields}}}function lH(e){if(e)return{...e,input_tokens:e.input_tokens??0,output_tokens:e.output_tokens??0,total_tokens:e.total_tokens??0}}e.s([],833953);let lq=Symbol("pushText"),lJ=Symbol("pushReasoning"),lG=Symbol("pushEvent"),lW=Symbol("updateContext"),lV=Symbol("finish"),lK=Symbol("error");var lQ=class{id;namespace;node;metadata;assembled;#I=new E.MultiCursorBuffer;#O=[];#C=[];#j=[];#P=[];#$=!1;#N=!1;#R;#M;#L;#z;constructor(e){this.id=e.id,this.assembled=e,this.namespace=e.namespace,this.node=e.node,this.metadata=e.metadata,this.#L=new Promise(e=>{this.#R=e}),this.#z=new Promise(e=>{this.#M=e})}get text(){let e=this.#O,t=this.#j,r=()=>this.#$,a=0;return{[Symbol.asyncIterator]:()=>({async next(){for(;;){if(a<e.length)return{done:!1,value:e[a++]};if(r())return{done:!0,value:void 0};await new Promise(e=>{t.push(e)})}}}),then:this.#L.then.bind(this.#L),full:{async *[Symbol.asyncIterator](){let i="";for await(let n of{[Symbol.asyncIterator]:()=>({next:async()=>{for(;;){if(a<e.length)return{done:!1,value:e[a++]};if(r())return{done:!0,value:void 0};await new Promise(e=>{t.push(e)})}}})})i+=n,yield i}}}}get reasoning(){let e=this.#C,t=this.#P,r=()=>this.#N,a=0;return{[Symbol.asyncIterator]:()=>({async next(){for(;;){if(a<e.length)return{done:!1,value:e[a++]};if(r())return{done:!0,value:void 0};await new Promise(e=>{t.push(e)})}}}),then:this.#z.then.bind(this.#z),full:{async *[Symbol.asyncIterator](){let i="";for await(let n of{[Symbol.asyncIterator]:()=>({next:async()=>{for(;;){if(a<e.length)return{done:!1,value:e[a++]};if(r())return{done:!0,value:void 0};await new Promise(e=>{t.push(e)})}}})})i+=n,yield i}}}}get usage(){let e=(async()=>{let e;for await(let t of this.#U())e=t;return e})();return{[Symbol.asyncIterator]:()=>this.#U(),then:e.then.bind(e)}}get toolCalls(){let e=this.#I,t=async function*(){for await(let t of e)"content-block-finish"===t.event&&"tool_call"===t.content.type&&(yield t.content)};return{[Symbol.asyncIterator]:t,then:async(e,r)=>{try{let r=[];for await(let e of t())r.push(e);return e?e(r):r}catch(e){if(r)return r(e);throw e}},full:{async *[Symbol.asyncIterator](){let e=[];for await(let r of t())e.push(r),yield[...e]}}}}get output(){return{then:(e,t)=>this.#B().then(e,t)}}get blocks(){return this.assembled.blocks}[Symbol.asyncIterator](){return this.#I[Symbol.asyncIterator]()}then(e,t){return this.#B().then(e,t)}async *#U(){for await(let e of this.#I)"message-start"===e.event&&e.usage?yield lH(e.usage):"message-finish"===e.event&&e.usage&&(yield lH(e.usage))}async #B(){let e,t,r,a=[],i={};for await(let n of this.#I)switch(n.event){case"message-start":e=n.id??e,n.usage&&(t=lH(n.usage));break;case"content-block-start":case"content-block-finish":a[n.index]=n.content;break;case"content-block-delta":{let e=a[n.index];a[n.index]=lZ(e,n);break}case"message-finish":r=n.reason,n.usage&&(t=lH(n.usage)),n.responseMetadata&&(i={...i,...n.responseMetadata})}return new e1({id:e,content:a.filter(e=>null!=e),usage_metadata:t,response_metadata:{...i,...r?{finish_reason:r}:{},output_version:"v1"}})}[lG](e){this.#I.push(e)}[lW](e){this.node=e.params.node??this.node}[lq](e){for(let t of(this.#O.push(e),this.#j.splice(0,this.#j.length)))t()}[lJ](e){for(let t of(this.#C.push(e),this.#P.splice(0,this.#P.length)))t()}[lV](){for(let e of(this.#$=!0,this.#N=!0,this.#R(this.#O.join("")),this.#M(this.#C.join("")),this.#j.splice(0,this.#j.length)))e();for(let e of this.#P.splice(0,this.#P.length))e();this.#I.close()}[lK](){this[lV]()}};function lY(e){return structuredClone(e)}function lX(e){return e.params.data}var l0=class{activeMessages=new Map;activeByNamespaceNode=new Map;blockIndexByProtocolIndexAndType=new Map;consume(e){let t=e.params.data,r=`${e.params.namespace.join("/")}::${e.params.node??""}`;if("message-start"===t.event){let a=function(e){let{namespace:t,node:r,data:a}=e.params,i=t.join("/"),n="message-start"===a.event?a.id??"":"";return`${i}::${r??""}::${n}`}(e);this.activeByNamespaceNode.set(r,a);let i={id:t.id,namespace:[...e.params.namespace],node:e.params.node,metadata:t.metadata,blocks:[]};return this.activeMessages.set(a,i),{kind:"message-start",key:a,message:i,event:e}}let a=this.activeByNamespaceNode.get(r);if(!a){let a=`${r}::`;this.activeByNamespaceNode.set(r,a);let i={id:t.id,namespace:[...e.params.namespace],node:e.params.node,blocks:[]};return this.activeMessages.set(a,i),this.consume(e)}let i=this.activeMessages.get(a);if(!i)throw Error(`No active message state found for key ${a}`);if("usage"===t.event)return i.usage=t.usage,{kind:"usage",key:a,message:i,event:e};switch(t.event){case"content-block-start":return i.blocks[t.index]=lY(t.content),this.blockIndexByProtocolIndexAndType.set(l1(a,t.index,t.content.type),t.index),{kind:"content-block-start",key:a,message:i,index:t.index,block:t.content,event:e};case"content-block-delta":{let r=t.content??(null!=t.delta?lF(t.delta,i.blocks[t.index]):void 0);if(null==r)throw Error("Received content-block-delta without content");let n=this.resolveBlockIndex(a,i.blocks,t.index,r.type),s=i.blocks[n];return i.blocks[n]=null!=t.content?null==s?lY(t.content):function(e,t){if(e.type!==t.type)return lY(t);switch(t.type){case"text":return{...e,...t,text:`${"text"in e?e.text:""}${t.text}`};case"reasoning":return{...e,...t,reasoning:`${"reasoning"in e?e.reasoning:""}${t.reasoning}`};case"tool_call_chunk":case"server_tool_call_chunk":{let r={...e,...t};return null==t.id&&"id"in e&&null!=e.id&&(r.id=e.id),null==t.name&&"name"in e&&null!=e.name&&(r.name=e.name),r.args=`${("args"in e?e.args:"")??""}${t.args??""}`,r}default:return{...e,...t}}}(s,t.content):lZ(s,t),{kind:"content-block-delta",key:a,message:i,index:n,block:r,event:e}}case"content-block-finish":{let r=this.resolveFinishBlockIndex(a,t.index,t.content.type);return i.blocks[r]=lY(t.content),{kind:"content-block-finish",key:a,message:i,index:r,block:t.content,event:e}}case"message-finish":return i.usage=t.usage,i.finishMetadata=t.responseMetadata,this.activeMessages.delete(a),this.activeByNamespaceNode.delete(r),this.clearBlockIndexAliases(a),{kind:"message-finish",key:a,message:structuredClone(i),event:e};case"error":return i.error={message:t.message,code:t.code},this.activeMessages.delete(a),this.activeByNamespaceNode.delete(r),this.clearBlockIndexAliases(a),{kind:"message-error",key:a,message:structuredClone(i),event:e}}}resolveBlockIndex(e,t,r,a){var i,n;let s,o,l=t[r];if(null==l||l.type===a||(i=l.type,n=a,s=new Set(["tool_call","tool_call_chunk","tool_use","input_json_delta"]),o=new Set(["server_tool_call","server_tool_call_chunk"]),s.has(i)&&s.has(n)||o.has(i)&&o.has(n)))return this.blockIndexByProtocolIndexAndType.set(l1(e,r,a),r),r;let u=l1(e,r,a),d=this.blockIndexByProtocolIndexAndType.get(u);if(null!=d)return d;let c=t.length;return this.blockIndexByProtocolIndexAndType.set(u,c),c}resolveFinishBlockIndex(e,t,r){let a=l1(e,t,r),i=this.blockIndexByProtocolIndexAndType.get(a);return null!=i?i:(this.blockIndexByProtocolIndexAndType.set(a,t),t)}clearBlockIndexAliases(e){let t=`${e}::`;for(let e of this.blockIndexByProtocolIndexAndType.keys())e.startsWith(t)&&this.blockIndexByProtocolIndexAndType.delete(e)}};function l1(e,t,r){return`${e}::${t}::${r}`}var l2=class{#D=new l0;#F=new Map;consume(e){let t=this.#D.consume(e);if(null!=t)switch(t.kind){case"message-start":{let e=new lQ(t.message);return e[lW](t.event),e[lG](lX(t.event)),this.#F.set(t.key,e),e}case"content-block-start":{let e=this.#F.get(t.key);e&&(e[lW](t.event),e[lG](lX(t.event))),e&&"text"===t.block.type&&"text"in t.block&&t.block.text&&e[lq](t.block.text),e&&"reasoning"===t.block.type&&"reasoning"in t.block&&t.block.reasoning&&e[lJ](t.block.reasoning);return}case"content-block-delta":{let e=this.#F.get(t.key);if(!e)return;e[lW](t.event),e[lG](lX(t.event)),"text"===t.block.type&&"text"in t.block&&e[lq](t.block.text),"reasoning"===t.block.type&&"reasoning"in t.block&&e[lJ](t.block.reasoning);return}case"content-block-finish":{let e=this.#F.get(t.key);e&&(e[lW](t.event),e[lG](lX(t.event)));return}case"usage":{let e=this.#F.get(t.key);e&&(e[lW](t.event),e[lG](lX(t.event)));return}case"message-finish":{let e=this.#F.get(t.key);e&&(e[lW](t.event),e[lG](lX(t.event)),e[lV](),this.#F.delete(t.key));return}case"message-error":{let e=this.#F.get(t.key);e&&(e[lW](t.event),e[lG](lX(t.event)),e[lK](),this.#F.delete(t.key));return}}}};e.s(["MessageAssembler",0,l0,"StreamingMessageAssembler",0,l2,"toStreamingMessageHandle",0,function(e){return new Proxy(e,{get(e,t){if("then"===t)return;let r=Reflect.get(e,t,e);return"function"==typeof r?r.bind(e):r},has:(e,t)=>"then"!==t&&t in e})}],846001);let l4=new Set(["audio","image","video","file"]);var l6=class extends Error{kind;messageId;partialBytes;cause;constructor(e,t,r,a,i){super(a??`media ${e} for message ${t}`),this.name="MediaAssemblyError",this.kind=e,this.messageId=t,this.partialBytes=r,this.cause=i?.cause}};function l5(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}var l9=class{type;messageId;namespace;node;id;mimeType;url;width;height;filename;monotonic=!0;error;#Z=[];#H=0;#q=new Uint8Array(0);#J;#G;#W;#V;#K;#Q=[];#Y;#X;#ee;#et;#er=!1;#ea;#ei=-1;#en=!1;#es=!1;#eo;constructor(e){this.type=e.type,this.messageId=e.messageId,this.namespace=e.namespace,this.node=e.node,this.id=e.id,this.mimeType=e.mimeType,this.url=e.url,this.#eo=e.fetch,this.#K=new Promise((e,t)=>{this.#W=e,this.#V=t}),this.#K.catch(()=>void 0),this.#ee=new Promise((e,t)=>{this.#Y=e,this.#X=t}),this.#ee.catch(()=>void 0)}observeIndex(e){e!==this.#ei+1&&e!==this.#ei&&(this.monotonic=!1),e>this.#ei&&(this.#ei=e)}absorbBlock(e){this.#er||("audio"===e.type?this.#el(e):"image"===e.type?this.#eu(e):"video"===e.type?this.#ed(e):"file"===e.type&&this.#ec(e))}enterUrlMode(e){this.#er=!0,this.url=e}pushBytes(e){if(!this.#en&&!this.#es&&0!==e.byteLength&&(this.#Z.push(e),this.#H+=e.byteLength,this.#q=function(e,t){let r=new Uint8Array(t),a=0;for(let t of e)r.set(t,a),a+=t.byteLength;return r}(this.#Z,this.#H),null!=this.#G))try{this.#G.enqueue(e)}catch{}}pushTranscript(e){"audio"!==this.type||this.#en||this.#es||0!==e.length&&this.#Q.push(e)}finish(){if(this.#en||this.#es)return;this.#en=!0,this.#es=!0;let e=new Blob([this.#q],{type:this.mimeType??""});this.#W(e),this.#Y(0===this.#Q.length?void 0:this.#Q.join(""));try{this.#G?.close()}catch{}}fail(e,t,r){if(this.#es)return this.error??new l6(e,this.messageId,this.#q,t,{cause:r});this.#es=!0;let a=new l6(e,this.messageId,this.#q,t,{cause:r});this.error=a,this.#V(a),this.#X(a);try{this.#G?.error(a)}catch{}return a}get partialBytes(){return this.#q}get blob(){return this.#er?this.#eh().then(e=>new Blob([e],{type:this.mimeType??""})):this.#K}get transcript(){return this.#ee}get objectURL(){return null!=this.#et?Promise.resolve(this.#et):this.blob.then(e=>{if(null!=this.#et)return this.#et;let t=URL.createObjectURL(e);return this.#et=t,t})}revoke(){let e=this.#et;if(null!=e){this.#et=void 0;try{URL.revokeObjectURL(e)}catch{}}}get stream(){return null!=this.#J?this.#J:this.#er?this.#ep():this.#ef()}#el(e){let t=e.mime_type??e.mimeType;null==this.mimeType&&null!=t&&(this.mimeType=t),null!=e.transcript&&e.transcript.length>0&&this.pushTranscript(e.transcript)}#eu(e){let t=e.mime_type??e.mimeType;null==this.mimeType&&null!=t&&(this.mimeType=t),null==this.width&&null!=e.width&&(this.width=e.width),null==this.height&&null!=e.height&&(this.height=e.height)}#ed(e){let t=e.mime_type??e.mimeType;null==this.mimeType&&null!=t&&(this.mimeType=t)}#ec(e){let t=e.mime_type??e.mimeType;null==this.mimeType&&null!=t&&(this.mimeType=t),null==this.filename&&null!=e.filename&&(this.filename=e.filename)}#ef(){let e=this.#q,t=this.#en,r=this.error;return this.#J=new ReadableStream({start:a=>{(this.#G=a,e.byteLength>0&&a.enqueue(e),null!=r)?a.error(r):t&&a.close()},cancel:()=>{this.#G=void 0}}),this.#J}#ep(){let e=this.#em();return this.#J=new ReadableStream({start:async t=>{try{let r=await e;if(null==r.body){let e=new Uint8Array(await r.arrayBuffer());e.byteLength>0&&t.enqueue(e),t.close();return}let a=r.body.getReader();for(;;){let{done:e,value:r}=await a.read();if(e)break;null!=r&&t.enqueue(r)}t.close()}catch(e){t.error(this.fail("fetch-failed",e?.message,e))}},cancel:()=>{this.#G=void 0}}),this.#J}#em(){let e=this.url;return this.#eo(e).then(t=>{if(!t.ok)throw Error(`fetch(${e}) failed: ${t.status} ${t.statusText}`);return t})}#eh(){return null!=this.#ea||(this.#ea=(async()=>{try{let e=await this.#em(),t=new Uint8Array(await e.arrayBuffer());return this.#Z.length=0,this.#Z.push(t),this.#H=t.byteLength,this.#q=t,this.#en=!0,this.#es=!0,t}catch(e){throw this.fail("fetch-failed",e?.message,e)}})()),this.#ea}},l3=class{#eg;#ey;#e_=new Map;#eb=new Map;#ev=0;constructor(e={}){this.#eg=e,null!=e.fetch?this.#ey=e.fetch:"function"==typeof fetch?this.#ey=fetch:this.#ey=()=>{throw Error("MediaAssembler: no fetch implementation available. Pass `fetch` in options.")}}consume(e){let t=e.params.data,r=e.params.namespace,a=e.params.node,i=`${r.join("/")}::${a??""}`;if("message-start"===t.event){this.#ew(i,"finish"),this.#eb.set(i,{messageId:t.id??"",keys:new Set,indexKeys:new Map});return}if("message-finish"===t.event){this.#ew(i,"finish"),this.#eb.delete(i);return}if("error"===t.event){this.#ew(i,"error",t.message),this.#eb.delete(i);return}if("content-block-start"!==t.event&&"content-block-delta"!==t.event&&"content-block-finish"!==t.event)return;let n=t.content,s=t.index??0,o=this.#eb.get(i);if(null==o&&(o={messageId:`__synthetic_${++this.#ev}`,keys:new Set,indexKeys:new Map},this.#eb.set(i,o)),null==n&&"content-block-delta"===t.event){let e=t.delta,i=o.indexKeys.get(s),n=null!=i?this.#e_.get(i):void 0;if(null==e||"object"!=typeof e)return;if(null==n){if("block-delta"!==e.type||null==e.fields||"object"!=typeof e.fields)return;let i=e.fields;if(!l4.has(i.type))return;this.#ex({active:o,block:i,blockIndex:s,dataEvent:t.event,namespace:r,node:a,terminal:!1,createIfMissing:!0});return}if(n.observeIndex(s),"data-delta"===e.type&&"string"==typeof e.data){try{n.pushBytes(l5(e.data))}catch(e){n.fail("message-error","invalid base64 on delta",e)}return}if("block-delta"===e.type&&null!=e.fields&&"object"==typeof e.fields){let t=e.fields;if(n.absorbBlock(t),!n.error&&null!=t.data)try{n.pushBytes(l5(t.data))}catch(e){n.fail("message-error","invalid base64 on delta",e)}}return}if(null==n)return;let l=n.type;l4.has(l)&&this.#ex({active:o,block:n,blockIndex:s,dataEvent:t.event,namespace:r,node:a,terminal:"content-block-finish"===t.event,createIfMissing:"content-block-start"===t.event||"content-block-finish"===t.event})}#ex({active:e,block:t,blockIndex:r,dataEvent:a,namespace:i,node:n,terminal:s,createIfMissing:o}){let l=t.type;if(!l4.has(l))return;let u=`${e.messageId}::${l}::${r}`,d=this.#e_.get(u);if(null==d){if("content-block-start"!==a&&!s&&!o)return;if(d=new l9({type:l,messageId:e.messageId,namespace:[...i],node:n,id:t.id,mimeType:t.mime_type??t.mimeType,url:null!=t.url&&null==t.data?t.url:void 0,fetch:this.#ey}),null!=t.url&&null==t.data&&d.enterUrlMode(t.url),d.observeIndex(r),d.absorbBlock(t),null!=t.data)try{d.pushBytes(l5(t.data))}catch(e){d.fail("message-error","invalid base64 on initial block",e)}this.#e_.set(u,d),e.keys.add(u),e.indexKeys.set(r,u),this.#k(d),s&&(d.finish(),this.#e_.delete(u),e.keys.delete(u),e.indexKeys.delete(r));return}if(!s&&(d.observeIndex(r),d.absorbBlock(t),!d.error&&null!=t.data))try{d.pushBytes(l5(t.data))}catch(e){d.fail("message-error","invalid base64 on delta",e)}}#ew(e,t,r){let a=this.#eb.get(e);if(null!=a){for(let e of a.keys){let a=this.#e_.get(e);null!=a&&("finish"===t?a.finish():a.fail("message-error",r)),this.#e_.delete(e)}a.keys.clear(),a.indexKeys.clear()}}close(){for(let e of this.#e_.values())e.fail("stream-closed","upstream event stream closed");this.#e_.clear(),this.#eb.clear()}#k(e){switch(e.type){case"audio":this.#eg.onAudio?.(e);break;case"image":this.#eg.onImage?.(e);break;case"video":this.#eg.onVideo?.(e);break;case"file":this.#eg.onFile?.(e)}this.#eg.onMedia?.(e)}};e.s(["MediaAssembler",0,l3,"MediaAssemblyError",0,l6],41348)},43073,e=>{"use strict";var t=class{#ek=[];#eS=new Set;#x=!1;push(e){for(let t of(this.#ek.push(e),this.#eS))t();this.#eS.clear()}close(){for(let e of(this.#x=!0,this.#eS))e();this.#eS.clear()}get length(){return this.#ek.length}[Symbol.asyncIterator](){let e=0;return{next:async()=>{for(;;){if(e<this.#ek.length)return{done:!1,value:this.#ek[e++]};if(this.#x)return{done:!0,value:void 0};await new Promise(e=>{this.#eS.add(e)})}},return:async()=>({done:!0,value:void 0})}}};e.s(["MultiCursorBuffer",0,t])},478492,(e,t,r)=>{"use strict";var a=Object.prototype.hasOwnProperty,i="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,r,a,n){if("function"!=typeof r)throw TypeError("The listener must be a function");var o=new s(r,a||e,n),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function l(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function u(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(i=!1)),u.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)a.call(e,t)&&r.push(i?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},u.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var a=0,n=r.length,s=Array(n);a<n;a++)s[a]=r[a].fn;return s},u.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},u.prototype.emit=function(e,t,r,a,n,s){var o=i?i+e:e;if(!this._events[o])return!1;var l,u,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,a),!0;case 5:return d.fn.call(d.context,t,r,a,n),!0;case 6:return d.fn.call(d.context,t,r,a,n,s),!0}for(u=1,l=Array(c-1);u<c;u++)l[u-1]=arguments[u];d.fn.apply(d.context,l)}else{var h,p=d.length;for(u=0;u<p;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),c){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,r);break;case 4:d[u].fn.call(d[u].context,t,r,a);break;default:if(!l)for(h=1,l=Array(c-1);h<c;h++)l[h-1]=arguments[h];d[u].fn.apply(d[u].context,l)}}return!0},u.prototype.on=function(e,t,r){return o(this,e,t,r,!1)},u.prototype.once=function(e,t,r){return o(this,e,t,r,!0)},u.prototype.removeListener=function(e,t,r,a){var n=i?i+e:e;if(!this._events[n])return this;if(!t)return l(this,n),this;var s=this._events[n];if(s.fn)s.fn!==t||a&&!s.once||r&&s.context!==r||l(this,n);else{for(var o=0,u=[],d=s.length;o<d;o++)(s[o].fn!==t||a&&!s[o].once||r&&s[o].context!==r)&&u.push(s[o]);u.length?this._events[n]=1===u.length?u[0]:u:l(this,n)}return this},u.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&l(this,t)):(this._events=new n,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=i,u.EventEmitter=u,t.exports=u},297422,(e,t,r)=>{"use strict";t.exports=(e,t)=>(t=t||(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))},625441,(e,t,r)=>{"use strict";let a=e.r(297422);class i extends Error{constructor(e){super(e),this.name="TimeoutError"}}let n=(e,t,r)=>new Promise((n,s)=>{if("number"!=typeof t||t<0)throw TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void n(e);let o=setTimeout(()=>{if("function"==typeof r){try{n(r())}catch(e){s(e)}return}let a="string"==typeof r?r:`Promise timed out after ${t} milliseconds`,o=r instanceof Error?r:new i(a);"function"==typeof e.cancel&&e.cancel(),s(o)},t);a(e.then(n,s),()=>{clearTimeout(o)})});t.exports=n,t.exports.default=n,t.exports.TimeoutError=i},345541,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r){let a=0,i=e.length;for(;i>0;){let n=i/2|0,s=a+n;0>=r(e[s],t)?(a=++s,i-=n+1):i=n}return a}},311102,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let a=e.r(345541);r.default=class{constructor(){this._queue=[]}enqueue(e,t){let r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(r);let i=a.default(this._queue,r,(e,t)=>t.priority-e.priority);this._queue.splice(i,0,r)}dequeue(){let e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this._queue.length}}},753274,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let a=e.r(478492),i=e.r(625441),n=e.r(311102),s=()=>{},o=new i.TimeoutError;r.default=class extends a{constructor(e){var t,r,a,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=s,this._resolveIdle=s,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:n.default},e)).intervalCap&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!=(r=null==(t=e.intervalCap)?void 0:t.toString())?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!=(i=null==(a=e.interval)?void 0:a.toString())?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=s,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=s,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(void 0===this._intervalId){let t=this._intervalEnd-e;if(!(t<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((r,a)=>{let n=async()=>{this._pendingCount++,this._intervalCount++;try{let n=void 0===this._timeout&&void 0===t.timeout?e():i.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&a(o)});r(await n)}catch(e){a(e)}this._next()};this._queue.enqueue(n,t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this._isPaused&&(this._isPaused=!1,this._processQueue()),this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}},467034,(e,t,r)=>{var a={872:function(e,t){"use strict";t.byteLength=function(e){var t=l(e),r=t[0],a=t[1];return(r+a)*3/4-a},t.toByteArray=function(e){var t,r,n=l(e),s=n[0],o=n[1],u=new i((s+o)*3/4-o),d=0,c=o>0?s-4:s;for(r=0;r<c;r+=4)t=a[e.charCodeAt(r)]<<18|a[e.charCodeAt(r+1)]<<12|a[e.charCodeAt(r+2)]<<6|a[e.charCodeAt(r+3)],u[d++]=t>>16&255,u[d++]=t>>8&255,u[d++]=255&t;return 2===o&&(t=a[e.charCodeAt(r)]<<2|a[e.charCodeAt(r+1)]>>4,u[d++]=255&t),1===o&&(t=a[e.charCodeAt(r)]<<10|a[e.charCodeAt(r+1)]<<4|a[e.charCodeAt(r+2)]>>2,u[d++]=t>>8&255,u[d++]=255&t),u},t.fromByteArray=function(e){for(var t,a=e.length,i=a%3,n=[],s=0,o=a-i;s<o;s+=16383)n.push(function(e,t,a){for(var i,n=[],s=t;s<a;s+=3)i=(e[s]<<16&0xff0000)+(e[s+1]<<8&65280)+(255&e[s+2]),n.push(r[i>>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return n.join("")}(e,s,s+16383>o?o:s+16383));return 1===i?n.push(r[(t=e[a-1])>>2]+r[t<<4&63]+"=="):2===i&&n.push(r[(t=(e[a-2]<<8)+e[a-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),n.join("")};for(var r=[],a=[],i="u">typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,o=n.length;s<o;++s)r[s]=n[s],a[n.charCodeAt(s)]=s;function l(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var a=r===t?0:4-r%4;return[r,a]}a[45]=62,a[95]=63},230:function(e,t,r){"use strict";var a=r(872),i=r(321),n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function s(e){if(e>0x7fffffff)throw RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,o.prototype),t}function o(e,t,r){if("number"==typeof e){if("string"==typeof t)throw TypeError('The "string" argument must be of type string. Received type number');return d(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e){var a=e,i=t;if(("string"!=typeof i||""===i)&&(i="utf8"),!o.isEncoding(i))throw TypeError("Unknown encoding: "+i);var n=0|p(a,i),l=s(n),u=l.write(a,i);return u!==n&&(l=l.slice(0,u)),l}if(ArrayBuffer.isView(e))return c(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(O(e,ArrayBuffer)||e&&O(e.buffer,ArrayBuffer)||"u">typeof SharedArrayBuffer&&(O(e,SharedArrayBuffer)||e&&O(e.buffer,SharedArrayBuffer)))return function(e,t,r){var a;if(t<0||e.byteLength<t)throw RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw RangeError('"length" is outside of buffer bounds');return Object.setPrototypeOf(a=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),o.prototype),a}(e,t,r);if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type number');var d=e.valueOf&&e.valueOf();if(null!=d&&d!==e)return o.from(d,t,r);var f=function(e){if(o.isBuffer(e)){var t=0|h(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||function(e){return e!=e}(e.length)?s(0):c(e):"Buffer"===e.type&&Array.isArray(e.data)?c(e.data):void 0}(e);if(f)return f;if("u">typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,r);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw TypeError('"size" argument must be of type number');if(e<0)throw RangeError('The value "'+e+'" is invalid for option "size"')}function d(e){return u(e),s(e<0?0:0|h(e))}function c(e){for(var t=e.length<0?0:0|h(e.length),r=s(t),a=0;a<t;a+=1)r[a]=255&e[a];return r}t.Buffer=o,t.SlowBuffer=function(e){return+e!=e&&(e=0),o.alloc(+e)},t.INSPECT_MAX_BYTES=50,t.kMaxLength=0x7fffffff,o.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!o.TYPED_ARRAY_SUPPORT&&"u">typeof console&&"function"==typeof console.error&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(e,t,r){return l(e,t,r)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(e,t,r){return(u(e),e<=0)?s(e):void 0!==t?"string"==typeof r?s(e).fill(t,r):s(e).fill(t):s(e)},o.allocUnsafe=function(e){return d(e)},o.allocUnsafeSlow=function(e){return d(e)};function h(e){if(e>=0x7fffffff)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function p(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||O(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,a=arguments.length>2&&!0===arguments[2];if(!a&&0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return E(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return A(e).length;default:if(i)return a?-1:E(e).length;t=(""+t).toLowerCase(),i=!0}}function f(e,t,r){var i,n,s,o=!1;if((void 0===t||t<0)&&(t=0),t>this.length||((void 0===r||r>this.length)&&(r=this.length),r<=0||(r>>>=0)<=(t>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,r){var a=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>a)&&(r=a);for(var i="",n=t;n<r;++n)i+=C[e[n]];return i}(this,t,r);case"utf8":case"utf-8":return _(this,t,r);case"ascii":return function(e,t,r){var a="";r=Math.min(e.length,r);for(var i=t;i<r;++i)a+=String.fromCharCode(127&e[i]);return a}(this,t,r);case"latin1":case"binary":return function(e,t,r){var a="";r=Math.min(e.length,r);for(var i=t;i<r;++i)a+=String.fromCharCode(e[i]);return a}(this,t,r);case"base64":return i=this,n=t,s=r,0===n&&s===i.length?a.fromByteArray(i):a.fromByteArray(i.slice(n,s));case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return function(e,t,r){for(var a=e.slice(t,r),i="",n=0;n<a.length;n+=2)i+=String.fromCharCode(a[n]+256*a[n+1]);return i}(this,t,r);default:if(o)throw TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function m(e,t,r){var a=e[t];e[t]=e[r],e[r]=a}function g(e,t,r,a,i){var n;if(0===e.length)return -1;if("string"==typeof r?(a=r,r=0):r>0x7fffffff?r=0x7fffffff:r<-0x80000000&&(r=-0x80000000),(n=r*=1)!=n&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length)if(i)return -1;else r=e.length-1;else if(r<0)if(!i)return -1;else r=0;if("string"==typeof t&&(t=o.from(t,a)),o.isBuffer(t))return 0===t.length?-1:y(e,t,r,a,i);if("number"==typeof t){if(t&=255,"function"==typeof Uint8Array.prototype.indexOf)if(i)return Uint8Array.prototype.indexOf.call(e,t,r);else return Uint8Array.prototype.lastIndexOf.call(e,t,r);return y(e,[t],r,a,i)}throw TypeError("val must be string, number or Buffer")}function y(e,t,r,a,i){var n,s=1,o=e.length,l=t.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(e.length<2||t.length<2)return -1;s=2,o/=2,l/=2,r/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var d=-1;for(n=r;n<o;n++)if(u(e,n)===u(t,-1===d?0:n-d)){if(-1===d&&(d=n),n-d+1===l)return d*s}else -1!==d&&(n-=n-d),d=-1}else for(r+l>o&&(r=o-l),n=r;n>=0;n--){for(var c=!0,h=0;h<l;h++)if(u(e,n+h)!==u(t,h)){c=!1;break}if(c)return n}return -1}o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(O(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),O(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var r=e.length,a=t.length,i=0,n=Math.min(r,a);i<n;++i)if(e[i]!==t[i]){r=e[i],a=t[i];break}return r<a?-1:+(a<r)},o.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Array.isArray(e))throw TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);if(void 0===t)for(r=0,t=0;r<e.length;++r)t+=e[r].length;var r,a=o.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){var n=e[r];if(O(n,Uint8Array)&&(n=o.from(n)),!o.isBuffer(n))throw TypeError('"list" argument must be an Array of Buffers');n.copy(a,i),i+=n.length}return a},o.byteLength=p,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)m(this,t,t+1);return this},o.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)m(this,t,t+3),m(this,t+1,t+2);return this},o.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)m(this,t,t+7),m(this,t+1,t+6),m(this,t+2,t+5),m(this,t+3,t+4);return this},o.prototype.toString=function(){var e=this.length;return 0===e?"":0==arguments.length?_(this,0,e):f.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){var e="",r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(e,t,r,a,i){if(O(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===a&&(a=0),void 0===i&&(i=this.length),t<0||r>e.length||a<0||i>this.length)throw RangeError("out of range index");if(a>=i&&t>=r)return 0;if(a>=i)return -1;if(t>=r)return 1;if(t>>>=0,r>>>=0,a>>>=0,i>>>=0,this===e)return 0;for(var n=i-a,s=r-t,l=Math.min(n,s),u=this.slice(a,i),d=e.slice(t,r),c=0;c<l;++c)if(u[c]!==d[c]){n=u[c],s=d[c];break}return n<s?-1:+(s<n)},o.prototype.includes=function(e,t,r){return -1!==this.indexOf(e,t,r)},o.prototype.indexOf=function(e,t,r){return g(this,e,t,r,!0)},o.prototype.lastIndexOf=function(e,t,r){return g(this,e,t,r,!1)};function _(e,t,r){r=Math.min(e.length,r);for(var a=[],i=t;i<r;){var n,s,o,l,u=e[i],d=null,c=u>239?4:u>223?3:u>191?2:1;if(i+c<=r)switch(c){case 1:u<128&&(d=u);break;case 2:(192&(n=e[i+1]))==128&&(l=(31&u)<<6|63&n)>127&&(d=l);break;case 3:n=e[i+1],s=e[i+2],(192&n)==128&&(192&s)==128&&(l=(15&u)<<12|(63&n)<<6|63&s)>2047&&(l<55296||l>57343)&&(d=l);break;case 4:n=e[i+1],s=e[i+2],o=e[i+3],(192&n)==128&&(192&s)==128&&(192&o)==128&&(l=(15&u)<<18|(63&n)<<12|(63&s)<<6|63&o)>65535&&l<1114112&&(d=l)}null===d?(d=65533,c=1):d>65535&&(d-=65536,a.push(d>>>10&1023|55296),d=56320|1023&d),a.push(d),i+=c}var h=a,p=h.length;if(p<=4096)return String.fromCharCode.apply(String,h);for(var f="",m=0;m<p;)f+=String.fromCharCode.apply(String,h.slice(m,m+=4096));return f}function b(e,t,r){if(e%1!=0||e<0)throw RangeError("offset is not uint");if(e+t>r)throw RangeError("Trying to access beyond buffer length")}function v(e,t,r,a,i,n){if(!o.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<n)throw RangeError('"value" argument is out of bounds');if(r+a>e.length)throw RangeError("Index out of range")}function w(e,t,r,a,i,n){if(r+a>e.length||r<0)throw RangeError("Index out of range")}function x(e,t,r,a,n){return t*=1,r>>>=0,n||w(e,t,r,4,34028234663852886e22,-34028234663852886e22),i.write(e,t,r,a,23,4),r+4}function k(e,t,r,a,n){return t*=1,r>>>=0,n||w(e,t,r,8,17976931348623157e292,-17976931348623157e292),i.write(e,t,r,a,52,8),r+8}o.prototype.write=function(e,t,r,a){if(void 0===t)a="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)a=t,r=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(r)?(r>>>=0,void 0===a&&(a="utf8")):(a=r,r=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var i,n,s,o,l,u,d,c,h=this.length-t;if((void 0===r||r>h)&&(r=h),e.length>0&&(r<0||t<0)||t>this.length)throw RangeError("Attempt to write outside buffer bounds");a||(a="utf8");for(var p=!1;;)switch(a){case"hex":return function(e,t,r,a){r=Number(r)||0;var i=e.length-r;a?(a=Number(a))>i&&(a=i):a=i;var n=t.length;a>n/2&&(a=n/2);for(var s=0;s<a;++s){var o,l=parseInt(t.substr(2*s,2),16);if((o=l)!=o)break;e[r+s]=l}return s}(this,e,t,r);case"utf8":case"utf-8":return i=t,n=r,I(E(e,this.length-i),this,i,n);case"ascii":return s=t,o=r,I(T(e),this,s,o);case"latin1":case"binary":return function(e,t,r,a){return I(T(t),e,r,a)}(this,e,t,r);case"base64":return l=t,u=r,I(A(e),this,l,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return d=t,c=r,I(function(e,t){for(var r,a,i=[],n=0;n<e.length&&!((t-=2)<0);++n)a=(r=e.charCodeAt(n))>>8,i.push(r%256),i.push(a);return i}(e,this.length-d),this,d,c);default:if(p)throw TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),p=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},o.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);var a=this.subarray(e,t);return Object.setPrototypeOf(a,o.prototype),a},o.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var a=this[e],i=1,n=0;++n<t&&(i*=256);)a+=this[e+n]*i;return a},o.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var a=this[e+--t],i=1;t>0&&(i*=256);)a+=this[e+--t]*i;return a},o.prototype.readUInt8=function(e,t){return e>>>=0,t||b(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||b(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||b(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||b(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+0x1000000*this[e+3]},o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||b(e,4,this.length),0x1000000*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var a=this[e],i=1,n=0;++n<t&&(i*=256);)a+=this[e+n]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*t)),a},o.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var a=t,i=1,n=this[e+--a];a>0&&(i*=256);)n+=this[e+--a]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*t)),n},o.prototype.readInt8=function(e,t){return(e>>>=0,t||b(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||b(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?0xffff0000|r:r},o.prototype.readInt16BE=function(e,t){e>>>=0,t||b(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?0xffff0000|r:r},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||b(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||b(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||b(e,4,this.length),i.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||b(e,4,this.length),i.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||b(e,8,this.length),i.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||b(e,8,this.length),i.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,r,a){if(e*=1,t>>>=0,r>>>=0,!a){var i=Math.pow(2,8*r)-1;v(this,e,t,r,i,0)}var n=1,s=0;for(this[t]=255&e;++s<r&&(n*=256);)this[t+s]=e/n&255;return t+r},o.prototype.writeUIntBE=function(e,t,r,a){if(e*=1,t>>>=0,r>>>=0,!a){var i=Math.pow(2,8*r)-1;v(this,e,t,r,i,0)}var n=r-1,s=1;for(this[t+n]=255&e;--n>=0&&(s*=256);)this[t+n]=e/s&255;return t+r},o.prototype.writeUInt8=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUInt16BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUInt32LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0xffffffff,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUInt32BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0xffffffff,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,r,a){if(e*=1,t>>>=0,!a){var i=Math.pow(2,8*r-1);v(this,e,t,r,i-1,-i)}var n=0,s=1,o=0;for(this[t]=255&e;++n<r&&(s*=256);)e<0&&0===o&&0!==this[t+n-1]&&(o=1),this[t+n]=(e/s|0)-o&255;return t+r},o.prototype.writeIntBE=function(e,t,r,a){if(e*=1,t>>>=0,!a){var i=Math.pow(2,8*r-1);v(this,e,t,r,i-1,-i)}var n=r-1,s=1,o=0;for(this[t+n]=255&e;--n>=0&&(s*=256);)e<0&&0===o&&0!==this[t+n+1]&&(o=1),this[t+n]=(e/s|0)-o&255;return t+r},o.prototype.writeInt8=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0x7fffffff,-0x80000000),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0x7fffffff,-0x80000000),e<0&&(e=0xffffffff+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,r){return x(this,e,t,!0,r)},o.prototype.writeFloatBE=function(e,t,r){return x(this,e,t,!1,r)},o.prototype.writeDoubleLE=function(e,t,r){return k(this,e,t,!0,r)},o.prototype.writeDoubleBE=function(e,t,r){return k(this,e,t,!1,r)},o.prototype.copy=function(e,t,r,a){if(!o.isBuffer(e))throw TypeError("argument should be a Buffer");if(r||(r=0),a||0===a||(a=this.length),t>=e.length&&(t=e.length),t||(t=0),a>0&&a<r&&(a=r),a===r||0===e.length||0===this.length)return 0;if(t<0)throw RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw RangeError("Index out of range");if(a<0)throw RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),e.length-t<a-r&&(a=e.length-t+r);var i=a-r;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,r,a);else if(this===e&&r<t&&t<a)for(var n=i-1;n>=0;--n)e[n+t]=this[n+r];else Uint8Array.prototype.set.call(e,this.subarray(r,a),t);return i},o.prototype.fill=function(e,t,r,a){if("string"==typeof e){if("string"==typeof t?(a=t,t=0,r=this.length):"string"==typeof r&&(a=r,r=this.length),void 0!==a&&"string"!=typeof a)throw TypeError("encoding must be a string");if("string"==typeof a&&!o.isEncoding(a))throw TypeError("Unknown encoding: "+a);if(1===e.length){var i,n=e.charCodeAt(0);("utf8"===a&&n<128||"latin1"===a)&&(e=n)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw RangeError("Out of range index");if(r<=t)return this;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{var s=o.isBuffer(e)?e:o.from(e,a),l=s.length;if(0===l)throw TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=s[i%l]}return this};var S=/[^+/0-9A-Za-z-_]/g;function E(e,t){t=t||1/0;for(var r,a=e.length,i=null,n=[],s=0;s<a;++s){if((r=e.charCodeAt(s))>55295&&r<57344){if(!i){if(r>56319||s+1===a){(t-=3)>-1&&n.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(t-=3)>-1&&n.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else if(r<1114112){if((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}else throw Error("Invalid code point")}return n}function T(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}function A(e){return a.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(S,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function I(e,t,r,a){for(var i=0;i<a&&!(i+r>=t.length)&&!(i>=e.length);++i)t[i+r]=e[i];return i}function O(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}var C=function(){for(var e="0123456789abcdef",t=Array(256),r=0;r<16;++r)for(var a=16*r,i=0;i<16;++i)t[a+i]=e[r]+e[i];return t}()},321:function(e,t){t.read=function(e,t,r,a,i){var n,s,o=8*i-a-1,l=(1<<o)-1,u=l>>1,d=-7,c=r?i-1:0,h=r?-1:1,p=e[t+c];for(c+=h,n=p&(1<<-d)-1,p>>=-d,d+=o;d>0;n=256*n+e[t+c],c+=h,d-=8);for(s=n&(1<<-d)-1,n>>=-d,d+=a;d>0;s=256*s+e[t+c],c+=h,d-=8);if(0===n)n=1-u;else{if(n===l)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,a),n-=u}return(p?-1:1)*s*Math.pow(2,n-a)},t.write=function(e,t,r,a,i,n){var s,o,l,u=8*n-i-1,d=(1<<u)-1,c=d>>1,h=5960464477539062e-23*(23===i),p=a?0:n-1,f=a?1:-1,m=+(t<0||0===t&&1/t<0);for(isNaN(t=Math.abs(t))||t===1/0?(o=+!!isNaN(t),s=d):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+c>=1?t+=h/l:t+=h*Math.pow(2,1-c),t*l>=2&&(s++,l/=2),s+c>=d?(o=0,s=d):s+c>=1?(o=(t*l-1)*Math.pow(2,i),s+=c):(o=t*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;e[r+p]=255&o,p+=f,o/=256,i-=8);for(s=s<<i|o,u+=i;u>0;e[r+p]=255&s,p+=f,s/=256,u-=8);e[r+p-f]|=128*m}}},i={};function n(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={exports:{}},s=!0;try{a[e](r,r.exports,n),s=!1}finally{s&&delete i[e]}return r.exports}n.ab="/ROOT/node_modules/next/dist/compiled/buffer/",t.exports=n(230)}]);
|
|
59
|
+
`));e.enqueue(n.encode("event: end\n\n")),e.close()}}),iu.fromReadableStream(s)}async *_streamEventsV2(e,t,r){let a,i=new iR({...r,autoClose:!1}),n=ia(t),s=n.runId??tl();n.runId=s;let o=n.callbacks;if(void 0===o)n.callbacks=[i];else if(Array.isArray(o))n.callbacks=o.concat(i);else{let e=o.copy();e.addHandler(i,!0),n.callbacks=e}let l=new AbortController,u=this,d=async function(){let t;try{if(n.signal)if("any"in AbortSignal)t=AbortSignal.any([l.signal,n.signal]);else{let e=new AbortController;n.signal.addEventListener("abort",()=>e.abort(),{once:!0}),l.signal.addEventListener("abort",()=>e.abort(),{once:!0}),t=e.signal}else t=l.signal;let r=await u.stream(e,{...n,signal:t});for await(let e of i.tapOutputIterable(s,r))if(l.signal.aborted)break}finally{await i.finish()}}(),c=!1;try{for await(let t of i){if(!c){t.data.input=e,c=!0,a=t.run_id,yield t;continue}t.run_id===a&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t}}finally{l.abort(),await d}}async *_streamEventsV1(e,t,r){let a,i=!1,n=ia(t),s=n.tags??[],o=n.metadata??{},l=n.runName??this.getName(),u=new ij({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new iW({...r});for await(let t of this._streamLog(e,u,n)){if(void 0===(a=a?a.concat(t):iA.fromRunLogPatch(t)).state)throw Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let t={...a.state},r={run_id:t.id,event:`on_${t.type}_start`,name:l,tags:s,metadata:o,data:{input:e}};d.includeEvent(r,t.type)&&(yield r)}for(let e of[...new Set(t.ops.filter(e=>e.path.startsWith("/logs/")).map(e=>e.path.split("/")[2]))]){let t,r={},i=a.state.logs[e];if("start"==(t=void 0===i.end_time?i.streamed_output.length>0?"stream":"start":"end"))void 0!==i.inputs&&(r.input=i.inputs);else if("end"===t)void 0!==i.inputs&&(r.input=i.inputs),r.output=i.final_output;else if("stream"===t){let e=i.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);r={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:r}}let{state:r}=a;if(r.streamed_output.length>0){let e=r.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${r.name}"`);let t={chunk:r.streamed_output[0]};r.streamed_output=[];let a={event:`on_${r.type}_stream`,run_id:r.id,tags:s,metadata:o,name:l,data:t};d.includeEvent(a,r.type)&&(yield a)}}let c=a?.state;if(void 0!==c){let e={event:`on_${c.type}_end`,name:l,run_id:c.id,tags:s,metadata:o,data:{output:c.final_output}};d.includeEvent(e,c.type)&&(yield e)}}static isRunnable(e){return iG(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new lj({bound:this,config:{},configFactories:[a=>({callbacks:[new iJ({config:a,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){var t,r,a,i,n;let s,o;return t=this,s=(r=e).name??t.getName(),o=r.description??(nD(a=r.schema)?nU.get(a)?.description:nB(a)||"description"in a&&"string"==typeof a.description?a.description:void 0),new lB(!(!(n=i=r.schema)||"object"!=typeof n||Array.isArray(n))&&(nD(n)||nB(n))&&(nB(i)?"ZodString"===i._def.typeName:!!nD(i)&&"string"===i._zod.def.type)?{name:s,description:o,schema:lI.object({input:lI.string()}).transform(e=>e.input),bound:t}:{name:s,description:o,schema:r.schema,bound:t})}},lj=class e extends lC{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let t=ir(this.config,...e);return ir(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new l$({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(t,this.kwargs))}async batch(e,t,r){let a=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig(ia(e),this.kwargs))):await this._mergeConfig(ia(t),this.kwargs);return this.bound.batch(e,a,r)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async *_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(ia(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(ia(t),this.kwargs))}async *transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(ia(t),this.kwargs))}streamEvents(e,t,r){let a=this,i=async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig(ia(t),a.kwargs),version:t.version},r)};return iu.fromAsyncGenerator(i())}static isRunnableBinding(e){return e.bound&&lC.isRunnable(e.bound)}withListeners({onStart:t,onEnd:r,onError:a}){return new e({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[e=>({callbacks:[new iJ({config:e,onStart:t,onEnd:r,onError:a})]})]})}},l$=class extends lj{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){let a=e>1?`retry:attempt:${e}`:void 0;return ii(t,{callbacks:r?.getChild(a)})}async _invoke(e,t,r){return iF(a=>super.invoke(e,this._patchConfigForRetry(a,t,r)),{onFailedAttempt:({error:t})=>this.onFailedAttempt(t,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,a){let i={};try{await iF(async n=>{let s,o=e.map((e,t)=>t).filter(e=>void 0===i[e.toString()]||i[e.toString()]instanceof Error),l=o.map(t=>e[t]),u=o.map(e=>this._patchConfigForRetry(n,t?.[e],r?.[e])),d=await super.batch(l,u,{...a,returnExceptions:!0});for(let e=0;e<d.length;e+=1){let t=d[e],r=o[e];t instanceof Error&&void 0===s&&((s=t).input=l[e]),i[r.toString()]=t}if(s)throw s;return d},{onFailedAttempt:({error:e})=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(a?.returnExceptions!==!0)throw e}return Object.keys(i).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>i[parseInt(e,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}},lP=class e extends lC{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){let r,a=ia(t),i=await (await it(a))?.handleChainStart(this.toJSON(),lO(e,"input"),a.runId,void 0,void 0,void 0,a?.runName);delete a.runId;let n=e;try{let e=[this.first,...this.middle];for(let t=0;t<e.length;t+=1)n=await io(e[t].invoke(n,ii(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)})),a.signal);if(a.signal?.aborted)throw il(a.signal);r=await this.last.invoke(n,ii(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(lO(r,"output")),r}async batch(e,t,r){let a=this._getOptionsList(t??{},e.length),i=await Promise.all(a.map(it)),n=await Promise.all(i.map(async(t,r)=>{let i=await t?.handleChainStart(this.toJSON(),lO(e[r],"input"),a[r].runId,void 0,void 0,void 0,a[r].runName);return delete a[r].runId,i})),s=e;try{for(let e=0;e<this.steps.length;e+=1)s=await io(this.steps[e].batch(s,n.map((t,r)=>{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return ii(a[r],{callbacks:i})}),r),a[0]?.signal)}catch(e){throw await Promise.all(n.map(t=>t?.handleChainError(e))),e}return await Promise.all(n.map(e=>e?.handleChainEnd(lO(s,"output")))),s}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async *_streamIterator(e,t){let r,a=await it(t),{runId:i,...n}=t??{},s=await a?.handleChainStart(this.toJSON(),lO(e,"input"),i,void 0,void 0,void 0,n?.runName),o=[this.first,...this.middle,this.last],l=!0;async function*u(){yield e}try{let e=o[0].transform(u(),ii(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let t=1;t<o.length;t+=1)e=await o[t].transform(e,ii(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)}));for await(let a of e)if(t?.signal?.throwIfAborted(),yield a,l)if(void 0===r)r=a;else try{r=this._concatOutputChunks(r,a)}catch{r=void 0,l=!1}}catch(e){throw await s?.handleChainError(e),e}await s?.handleChainEnd(lO(r,"output"))}getGraph(e){let t=new lw,r=null;return this.steps.forEach((a,i)=>{let n=a.getGraph(e);0!==i&&n.trimFirstNode(),i!==this.steps.length-1&&n.trimLastNode(),t.extend(n);let s=n.firstNode();if(!s)throw Error(`Runnable ${a} has no first node`);r&&t.addEdge(r,s),r=n.lastNode()}),t}pipe(t){return new e(e.isRunnableSequence(t)?{first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}:{first:this.first,middle:[...this.middle,this.last],last:lL(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&lC.isRunnable(e)}static from([t,...r],a){let i={};return"string"==typeof a?i.name=a:void 0!==a&&(i=a),new e({...i,first:lL(t),middle:r.slice(0,-1).map(lL),last:lL(r[r.length-1])})}},lN=class e extends lC{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){for(const[t,r]of(super(e),this.steps={},Object.entries(e.steps)))this.steps[t]=lL(r)}static from(t){return new e({steps:t})}async invoke(e,t){let r=ia(t),a=await (await it(r))?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let i={};try{let t=Object.entries(this.steps).map(async([t,n])=>{i[t]=await n.invoke(e,ii(r,{callbacks:a?.getChild(`map:key:${t}`)}))});await io(Promise.all(t),r.signal)}catch(e){throw await a?.handleChainError(e),e}return await a?.handleChainEnd(i),i}async *_transform(e,t,r){let a={...this.steps},i=id(e,Object.keys(a).length),n=new Map(Object.entries(a).map(([e,a],n)=>{let s=a.transform(i[n],ii(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,s.next().then(t=>({key:e,gen:s,result:t}))]}));for(;n.size;){let{key:e,result:t,gen:a}=await io(Promise.race(n.values()),r?.signal);n.delete(e),t.done||(yield{[e]:t.value},n.set(e,a.next().then(t=>({key:e,gen:a,result:t}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=ia(t),i=new ic({generator:this.transform(r(),a),config:a});return await i.setup,iu.fromAsyncGenerator(i)}},lR=class e extends lC{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!aq(e.func))throw Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){let[r]=this._getOptionsList(t??{},1),a=await it(r);return io(this.func(ii(r,{callbacks:a}),e),r?.signal)}async *_streamIterator(e,t){let[r]=this._getOptionsList(t??{},1),a=await this.invoke(e,t);if(lT(a)){for await(let e of a)r?.signal?.throwIfAborted(),yield e;return}if(null!=a&&"object"==typeof a&&"next"in a&&"function"==typeof a.next){for(;;){r?.signal?.throwIfAborted();let e=a.next();if(e.done)break;yield e.value}return}yield a}static from(t){return new e({func:t})}},lM=class e extends lC{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(aq(e.func))return lR.from(e.func);super(e),function(e){if(aq(e))throw Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}(e.func),this.func=e.func}static from(t){return new e({func:t})}async _invoke(e,t,r){return new Promise((a,i)=>{let n=ii(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});a8.runWithConfig(is(n),async()=>{try{let r=await this.func(e,{...n});if(r&&lC.isRunnable(r)){if(t?.recursionLimit===0)throw Error("Recursion limit reached.");r=await r.invoke(e,{...n,recursionLimit:(n.recursionLimit??25)-1})}else if(lT(r)){let e;for await(let a of lA(n,r))if(t?.signal?.throwIfAborted(),void 0===e)e=a;else try{e=this._concatOutputChunks(e,a)}catch{e=a}r=e}else if(lS(r)){let e;for(let a of lE(n,r))if(t?.signal?.throwIfAborted(),void 0===e)e=a;else try{e=this._concatOutputChunks(e,a)}catch{e=a}r=e}a(r)}catch(e){i(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async *_transform(e,t,r){let a;for await(let t of e)if(void 0===a)a=t;else try{a=this._concatOutputChunks(a,t)}catch{a=t}let i=ii(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??25)-1}),n=await new Promise((e,t)=>{a8.runWithConfig(is(i),async()=>{try{e(await this.func(a,{...i,config:i}))}catch(e){t(e)}})});if(n&&lC.isRunnable(n)){if(r?.recursionLimit===0)throw Error("Recursion limit reached.");for await(let e of(await n.stream(a,i)))yield e}else if(lT(n))for await(let e of lA(i,n))r?.signal?.throwIfAborted(),yield e;else if(lS(n))for(let e of lE(i,n))r?.signal?.throwIfAborted(),yield e;else yield n}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=ia(t),i=new ic({generator:this.transform(r(),a),config:a});return await i.setup,iu.fromAsyncGenerator(i)}},lz=class extends lC{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){for(let e of(yield this.runnable,this.fallbacks))yield e}async invoke(e,t){let r=ia(t),a=await it(r),{runId:i,...n}=r,s=await a?.handleChainStart(this.toJSON(),lO(e,"input"),i,void 0,void 0,void 0,n?.runName),o=ii(n,{callbacks:s?.getChild()});return await a8.runWithConfig(o,async()=>{let t;for(let a of this.runnables()){r?.signal?.throwIfAborted();try{let t=await a.invoke(e,o);return await s?.handleChainEnd(lO(t,"output")),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw Error("No error stored at end of fallback.");throw await s?.handleChainError(t),t})}async *_streamIterator(e,t){let r,a,i,n=ia(t),s=await it(n),{runId:o,...l}=n,u=await s?.handleChainStart(this.toJSON(),lO(e,"input"),o,void 0,void 0,void 0,l?.runName);for(let t of this.runnables()){n?.signal?.throwIfAborted();let i=ii(l,{callbacks:u?.getChild()});try{a=lA(i,await t.stream(e,i));break}catch(e){void 0===r&&(r=e)}}if(void 0===a){let e=r??Error("No error stored at end of fallback.");throw await u?.handleChainError(e),e}try{for await(let e of a){yield e;try{i=void 0===i?i:this._concatOutputChunks(i,e)}catch{i=void 0}}}catch(e){throw await u?.handleChainError(e),e}await u?.handleChainEnd(lO(i,"output"))}async batch(e,t,r){let a;if(r?.returnExceptions)throw Error("Not implemented.");let i=this._getOptionsList(t??{},e.length),n=await Promise.all(i.map(e=>it(e))),s=await Promise.all(n.map(async(t,r)=>{let a=await t?.handleChainStart(this.toJSON(),lO(e[r],"input"),i[r].runId,void 0,void 0,void 0,i[r].runName);return delete i[r].runId,a}));for(let t of this.runnables()){i[0].signal?.throwIfAborted();try{let a=await t.batch(e,s.map((e,t)=>ii(i[t],{callbacks:e?.getChild()})),r);return await Promise.all(s.map((e,t)=>e?.handleChainEnd(lO(a[t],"output")))),a}catch(e){void 0===a&&(a=e)}}if(!a)throw Error("No error stored at end of fallbacks.");throw await Promise.all(s.map(e=>e?.handleChainError(a))),a}};function lL(e){if("function"==typeof e)return new lM({func:e});if(lC.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw Error(`Expected a Runnable, function or object.
|
|
60
|
+
Instead got an unsupported type.`);{let t={};for(let[r,a]of Object.entries(e))t[r]=lL(a);return new lN({steps:t})}}var lU=class extends lC{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof lN&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){let r=await this.mapper.invoke(e,t);return{...e,...r}}async *_transform(e,t,r){let a=this.mapper.getStepsKeys(),[i,n]=id(e),s=this.mapper.transform(n,ii(r,{callbacks:t?.getChild()})),o=s.next();for await(let e of i){if("object"!=typeof e||Array.isArray(e))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof e}`);let t=Object.fromEntries(Object.entries(e).filter(([e])=>!a.includes(e)));Object.keys(t).length>0&&(yield t)}for await(let e of(yield(await o).value,s))yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=ia(t),i=new ic({generator:this.transform(r(),a),config:a});return await i.setup,iu.fromAsyncGenerator(i)}},lD=class extends lC{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){("string"==typeof e||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if("string"==typeof this.keys)return e[this.keys];{let t=this.keys.map(t=>[t,e[t]]).filter(e=>void 0!==e[1]);return 0===t.length?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async *_transform(e){for await(let t of e){let e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=ia(t),i=new ic({generator:this.transform(r(),a),config:a});return await i.setup,iu.fromAsyncGenerator(i)}},lB=class extends lj{name;description;schema;constructor(e){super({bound:lP.from([lM.from(async e=>{let t;if(e$(e))try{t=await nF(this.schema,e.args)}catch{throw new eP("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function lF(e,t){switch(e.type){case"text-delta":return{type:"text",text:e.text};case"reasoning-delta":return{type:"reasoning",reasoning:e.reasoning};case"data-delta":{let r={...t??{},data:e.data};return e.encoding&&(r.encoding=e.encoding),r}case"block-delta":return e.fields}}function lZ(e,t){if(t.content)return e?function(e,t){if(e.type!==t.type)return structuredClone(t);switch(t.type){case"text":return{...e,...t,text:`${"text"in e?e.text:""}${t.text}`};case"reasoning":return{...e,...t,reasoning:`${"reasoning"in e?e.reasoning:""}${t.reasoning}`};case"tool_call_chunk":case"server_tool_call_chunk":{let r={...e,...t};return null==t.id&&"id"in e&&null!=e.id&&(r.id=e.id),null==t.name&&"name"in e&&null!=e.name&&(r.name=e.name),r.args=`${("args"in e?e.args:"")??""}${t.args??""}`,r}default:return{...e,...t}}}(e,t.content):t.content;switch(t.delta.type){case"text-delta":if(e?.type==="text")return{...e,text:`${"text"in e?e.text:""}${t.delta.text}`};return lF(t.delta,e);case"reasoning-delta":if(e?.type==="reasoning")return{...e,reasoning:`${"reasoning"in e?e.reasoning:""}${t.delta.reasoning}`};return lF(t.delta,e);case"data-delta":{let r={...e??{}};return r.data=`${r.data??""}${t.delta.data}`,t.delta.encoding&&(r.encoding=t.delta.encoding),r}case"block-delta":return{...e??{},...t.delta.fields}}}function lH(e){if(e)return{...e,input_tokens:e.input_tokens??0,output_tokens:e.output_tokens??0,total_tokens:e.total_tokens??0}}e.s([],833953);let lq=Symbol("pushText"),lJ=Symbol("pushReasoning"),lG=Symbol("pushEvent"),lW=Symbol("updateContext"),lV=Symbol("finish"),lK=Symbol("error");var lQ=class{id;namespace;node;metadata;assembled;#I=new T.MultiCursorBuffer;#O=[];#C=[];#j=[];#$=[];#P=!1;#N=!1;#R;#M;#z;#L;constructor(e){this.id=e.id,this.assembled=e,this.namespace=e.namespace,this.node=e.node,this.metadata=e.metadata,this.#z=new Promise(e=>{this.#R=e}),this.#L=new Promise(e=>{this.#M=e})}get text(){let e=this.#O,t=this.#j,r=()=>this.#P,a=0;return{[Symbol.asyncIterator]:()=>({async next(){for(;;){if(a<e.length)return{done:!1,value:e[a++]};if(r())return{done:!0,value:void 0};await new Promise(e=>{t.push(e)})}}}),then:this.#z.then.bind(this.#z),full:{async *[Symbol.asyncIterator](){let i="";for await(let n of{[Symbol.asyncIterator]:()=>({next:async()=>{for(;;){if(a<e.length)return{done:!1,value:e[a++]};if(r())return{done:!0,value:void 0};await new Promise(e=>{t.push(e)})}}})})i+=n,yield i}}}}get reasoning(){let e=this.#C,t=this.#$,r=()=>this.#N,a=0;return{[Symbol.asyncIterator]:()=>({async next(){for(;;){if(a<e.length)return{done:!1,value:e[a++]};if(r())return{done:!0,value:void 0};await new Promise(e=>{t.push(e)})}}}),then:this.#L.then.bind(this.#L),full:{async *[Symbol.asyncIterator](){let i="";for await(let n of{[Symbol.asyncIterator]:()=>({next:async()=>{for(;;){if(a<e.length)return{done:!1,value:e[a++]};if(r())return{done:!0,value:void 0};await new Promise(e=>{t.push(e)})}}})})i+=n,yield i}}}}get usage(){let e=(async()=>{let e;for await(let t of this.#U())e=t;return e})();return{[Symbol.asyncIterator]:()=>this.#U(),then:e.then.bind(e)}}get toolCalls(){let e=this.#I,t=async function*(){for await(let t of e)"content-block-finish"===t.event&&"tool_call"===t.content.type&&(yield t.content)};return{[Symbol.asyncIterator]:t,then:async(e,r)=>{try{let r=[];for await(let e of t())r.push(e);return e?e(r):r}catch(e){if(r)return r(e);throw e}},full:{async *[Symbol.asyncIterator](){let e=[];for await(let r of t())e.push(r),yield[...e]}}}}get output(){return{then:(e,t)=>this.#D().then(e,t)}}get blocks(){return this.assembled.blocks}[Symbol.asyncIterator](){return this.#I[Symbol.asyncIterator]()}then(e,t){return this.#D().then(e,t)}async *#U(){for await(let e of this.#I)"message-start"===e.event&&e.usage?yield lH(e.usage):"message-finish"===e.event&&e.usage&&(yield lH(e.usage))}async #D(){let e,t,r,a=[],i={};for await(let n of this.#I)switch(n.event){case"message-start":e=n.id??e,n.usage&&(t=lH(n.usage));break;case"content-block-start":case"content-block-finish":a[n.index]=n.content;break;case"content-block-delta":{let e=a[n.index];a[n.index]=lZ(e,n);break}case"message-finish":r=n.reason,n.usage&&(t=lH(n.usage)),n.responseMetadata&&(i={...i,...n.responseMetadata})}return new e1({id:e,content:a.filter(e=>null!=e),usage_metadata:t,response_metadata:{...i,...r?{finish_reason:r}:{},output_version:"v1"}})}[lG](e){this.#I.push(e)}[lW](e){this.node=e.params.node??this.node}[lq](e){for(let t of(this.#O.push(e),this.#j.splice(0,this.#j.length)))t()}[lJ](e){for(let t of(this.#C.push(e),this.#$.splice(0,this.#$.length)))t()}[lV](){for(let e of(this.#P=!0,this.#N=!0,this.#R(this.#O.join("")),this.#M(this.#C.join("")),this.#j.splice(0,this.#j.length)))e();for(let e of this.#$.splice(0,this.#$.length))e();this.#I.close()}[lK](){this[lV]()}};function lY(e){return structuredClone(e)}function lX(e){return e.params.data}var l0=class{activeMessages=new Map;activeByNamespaceNode=new Map;blockIndexByProtocolIndexAndType=new Map;consume(e){let t=e.params.data,r=`${e.params.namespace.join("/")}::${e.params.node??""}`;if("message-start"===t.event){let a=function(e){let{namespace:t,node:r,data:a}=e.params,i=t.join("/"),n="message-start"===a.event?a.id??"":"";return`${i}::${r??""}::${n}`}(e);this.activeByNamespaceNode.set(r,a);let i={id:t.id,namespace:[...e.params.namespace],node:e.params.node,metadata:t.metadata,blocks:[]};return this.activeMessages.set(a,i),{kind:"message-start",key:a,message:i,event:e}}let a=this.activeByNamespaceNode.get(r);if(!a){let a=`${r}::`;this.activeByNamespaceNode.set(r,a);let i={id:t.id,namespace:[...e.params.namespace],node:e.params.node,blocks:[]};return this.activeMessages.set(a,i),this.consume(e)}let i=this.activeMessages.get(a);if(!i)throw Error(`No active message state found for key ${a}`);if("usage"===t.event)return i.usage=t.usage,{kind:"usage",key:a,message:i,event:e};switch(t.event){case"content-block-start":return i.blocks[t.index]=lY(t.content),this.blockIndexByProtocolIndexAndType.set(l1(a,t.index,t.content.type),t.index),{kind:"content-block-start",key:a,message:i,index:t.index,block:t.content,event:e};case"content-block-delta":{let r=t.content??(null!=t.delta?lF(t.delta,i.blocks[t.index]):void 0);if(null==r)throw Error("Received content-block-delta without content");let n=this.resolveBlockIndex(a,i.blocks,t.index,r.type),s=i.blocks[n];return i.blocks[n]=null!=t.content?null==s?lY(t.content):function(e,t){if(e.type!==t.type)return lY(t);switch(t.type){case"text":return{...e,...t,text:`${"text"in e?e.text:""}${t.text}`};case"reasoning":return{...e,...t,reasoning:`${"reasoning"in e?e.reasoning:""}${t.reasoning}`};case"tool_call_chunk":case"server_tool_call_chunk":{let r={...e,...t};return null==t.id&&"id"in e&&null!=e.id&&(r.id=e.id),null==t.name&&"name"in e&&null!=e.name&&(r.name=e.name),r.args=`${("args"in e?e.args:"")??""}${t.args??""}`,r}default:return{...e,...t}}}(s,t.content):lZ(s,t),{kind:"content-block-delta",key:a,message:i,index:n,block:r,event:e}}case"content-block-finish":{let r=this.resolveFinishBlockIndex(a,t.index,t.content.type);return i.blocks[r]=lY(t.content),{kind:"content-block-finish",key:a,message:i,index:r,block:t.content,event:e}}case"message-finish":return i.usage=t.usage,i.finishMetadata=t.responseMetadata,this.activeMessages.delete(a),this.activeByNamespaceNode.delete(r),this.clearBlockIndexAliases(a),{kind:"message-finish",key:a,message:structuredClone(i),event:e};case"error":return i.error={message:t.message,code:t.code},this.activeMessages.delete(a),this.activeByNamespaceNode.delete(r),this.clearBlockIndexAliases(a),{kind:"message-error",key:a,message:structuredClone(i),event:e}}}resolveBlockIndex(e,t,r,a){var i,n;let s,o,l=t[r];if(null==l||l.type===a||(i=l.type,n=a,s=new Set(["tool_call","tool_call_chunk","tool_use","input_json_delta"]),o=new Set(["server_tool_call","server_tool_call_chunk"]),s.has(i)&&s.has(n)||o.has(i)&&o.has(n)))return this.blockIndexByProtocolIndexAndType.set(l1(e,r,a),r),r;let u=l1(e,r,a),d=this.blockIndexByProtocolIndexAndType.get(u);if(null!=d)return d;let c=t.length;return this.blockIndexByProtocolIndexAndType.set(u,c),c}resolveFinishBlockIndex(e,t,r){let a=l1(e,t,r),i=this.blockIndexByProtocolIndexAndType.get(a);return null!=i?i:(this.blockIndexByProtocolIndexAndType.set(a,t),t)}clearBlockIndexAliases(e){let t=`${e}::`;for(let e of this.blockIndexByProtocolIndexAndType.keys())e.startsWith(t)&&this.blockIndexByProtocolIndexAndType.delete(e)}};function l1(e,t,r){return`${e}::${t}::${r}`}var l2=class{#B=new l0;#F=new Map;consume(e){let t=this.#B.consume(e);if(null!=t)switch(t.kind){case"message-start":{let e=new lQ(t.message);return e[lW](t.event),e[lG](lX(t.event)),this.#F.set(t.key,e),e}case"content-block-start":{let e=this.#F.get(t.key);e&&(e[lW](t.event),e[lG](lX(t.event))),e&&"text"===t.block.type&&"text"in t.block&&t.block.text&&e[lq](t.block.text),e&&"reasoning"===t.block.type&&"reasoning"in t.block&&t.block.reasoning&&e[lJ](t.block.reasoning);return}case"content-block-delta":{let e=this.#F.get(t.key);if(!e)return;e[lW](t.event),e[lG](lX(t.event)),"text"===t.block.type&&"text"in t.block&&e[lq](t.block.text),"reasoning"===t.block.type&&"reasoning"in t.block&&e[lJ](t.block.reasoning);return}case"content-block-finish":{let e=this.#F.get(t.key);e&&(e[lW](t.event),e[lG](lX(t.event)));return}case"usage":{let e=this.#F.get(t.key);e&&(e[lW](t.event),e[lG](lX(t.event)));return}case"message-finish":{let e=this.#F.get(t.key);e&&(e[lW](t.event),e[lG](lX(t.event)),e[lV](),this.#F.delete(t.key));return}case"message-error":{let e=this.#F.get(t.key);e&&(e[lW](t.event),e[lG](lX(t.event)),e[lK](),this.#F.delete(t.key));return}}}};e.s(["MessageAssembler",0,l0,"StreamingMessageAssembler",0,l2,"toStreamingMessageHandle",0,function(e){return new Proxy(e,{get(e,t){if("then"===t)return;let r=Reflect.get(e,t,e);return"function"==typeof r?r.bind(e):r},has:(e,t)=>"then"!==t&&t in e})}],846001);let l4=new Set(["audio","image","video","file"]);var l9=class extends Error{kind;messageId;partialBytes;cause;constructor(e,t,r,a,i){super(a??`media ${e} for message ${t}`),this.name="MediaAssemblyError",this.kind=e,this.messageId=t,this.partialBytes=r,this.cause=i?.cause}};function l6(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}var l5=class{type;messageId;namespace;node;id;mimeType;url;width;height;filename;monotonic=!0;error;#Z=[];#H=0;#q=new Uint8Array(0);#J;#G;#W;#V;#K;#Q=[];#Y;#X;#ee;#et;#er=!1;#ea;#ei=-1;#en=!1;#es=!1;#eo;constructor(e){this.type=e.type,this.messageId=e.messageId,this.namespace=e.namespace,this.node=e.node,this.id=e.id,this.mimeType=e.mimeType,this.url=e.url,this.#eo=e.fetch,this.#K=new Promise((e,t)=>{this.#W=e,this.#V=t}),this.#K.catch(()=>void 0),this.#ee=new Promise((e,t)=>{this.#Y=e,this.#X=t}),this.#ee.catch(()=>void 0)}observeIndex(e){e!==this.#ei+1&&e!==this.#ei&&(this.monotonic=!1),e>this.#ei&&(this.#ei=e)}absorbBlock(e){this.#er||("audio"===e.type?this.#el(e):"image"===e.type?this.#eu(e):"video"===e.type?this.#ed(e):"file"===e.type&&this.#ec(e))}enterUrlMode(e){this.#er=!0,this.url=e}pushBytes(e){if(!this.#en&&!this.#es&&0!==e.byteLength&&(this.#Z.push(e),this.#H+=e.byteLength,this.#q=function(e,t){let r=new Uint8Array(t),a=0;for(let t of e)r.set(t,a),a+=t.byteLength;return r}(this.#Z,this.#H),null!=this.#G))try{this.#G.enqueue(e)}catch{}}pushTranscript(e){"audio"!==this.type||this.#en||this.#es||0!==e.length&&this.#Q.push(e)}finish(){if(this.#en||this.#es)return;this.#en=!0,this.#es=!0;let e=new Blob([this.#q],{type:this.mimeType??""});this.#W(e),this.#Y(0===this.#Q.length?void 0:this.#Q.join(""));try{this.#G?.close()}catch{}}fail(e,t,r){if(this.#es)return this.error??new l9(e,this.messageId,this.#q,t,{cause:r});this.#es=!0;let a=new l9(e,this.messageId,this.#q,t,{cause:r});this.error=a,this.#V(a),this.#X(a);try{this.#G?.error(a)}catch{}return a}get partialBytes(){return this.#q}get blob(){return this.#er?this.#eh().then(e=>new Blob([e],{type:this.mimeType??""})):this.#K}get transcript(){return this.#ee}get objectURL(){return null!=this.#et?Promise.resolve(this.#et):this.blob.then(e=>{if(null!=this.#et)return this.#et;let t=URL.createObjectURL(e);return this.#et=t,t})}revoke(){let e=this.#et;if(null!=e){this.#et=void 0;try{URL.revokeObjectURL(e)}catch{}}}get stream(){return null!=this.#J?this.#J:this.#er?this.#ep():this.#ef()}#el(e){let t=e.mime_type??e.mimeType;null==this.mimeType&&null!=t&&(this.mimeType=t),null!=e.transcript&&e.transcript.length>0&&this.pushTranscript(e.transcript)}#eu(e){let t=e.mime_type??e.mimeType;null==this.mimeType&&null!=t&&(this.mimeType=t),null==this.width&&null!=e.width&&(this.width=e.width),null==this.height&&null!=e.height&&(this.height=e.height)}#ed(e){let t=e.mime_type??e.mimeType;null==this.mimeType&&null!=t&&(this.mimeType=t)}#ec(e){let t=e.mime_type??e.mimeType;null==this.mimeType&&null!=t&&(this.mimeType=t),null==this.filename&&null!=e.filename&&(this.filename=e.filename)}#ef(){let e=this.#q,t=this.#en,r=this.error;return this.#J=new ReadableStream({start:a=>{(this.#G=a,e.byteLength>0&&a.enqueue(e),null!=r)?a.error(r):t&&a.close()},cancel:()=>{this.#G=void 0}}),this.#J}#ep(){let e=this.#em();return this.#J=new ReadableStream({start:async t=>{try{let r=await e;if(null==r.body){let e=new Uint8Array(await r.arrayBuffer());e.byteLength>0&&t.enqueue(e),t.close();return}let a=r.body.getReader();for(;;){let{done:e,value:r}=await a.read();if(e)break;null!=r&&t.enqueue(r)}t.close()}catch(e){t.error(this.fail("fetch-failed",e?.message,e))}},cancel:()=>{this.#G=void 0}}),this.#J}#em(){let e=this.url;return this.#eo(e).then(t=>{if(!t.ok)throw Error(`fetch(${e}) failed: ${t.status} ${t.statusText}`);return t})}#eh(){return null!=this.#ea||(this.#ea=(async()=>{try{let e=await this.#em(),t=new Uint8Array(await e.arrayBuffer());return this.#Z.length=0,this.#Z.push(t),this.#H=t.byteLength,this.#q=t,this.#en=!0,this.#es=!0,t}catch(e){throw this.fail("fetch-failed",e?.message,e)}})()),this.#ea}},l3=class{#eg;#ey;#e_=new Map;#eb=new Map;#ev=0;constructor(e={}){this.#eg=e,null!=e.fetch?this.#ey=e.fetch:"function"==typeof fetch?this.#ey=fetch:this.#ey=()=>{throw Error("MediaAssembler: no fetch implementation available. Pass `fetch` in options.")}}consume(e){let t=e.params.data,r=e.params.namespace,a=e.params.node,i=`${r.join("/")}::${a??""}`;if("message-start"===t.event){this.#ew(i,"finish"),this.#eb.set(i,{messageId:t.id??"",keys:new Set,indexKeys:new Map});return}if("message-finish"===t.event){this.#ew(i,"finish"),this.#eb.delete(i);return}if("error"===t.event){this.#ew(i,"error",t.message),this.#eb.delete(i);return}if("content-block-start"!==t.event&&"content-block-delta"!==t.event&&"content-block-finish"!==t.event)return;let n=t.content,s=t.index??0,o=this.#eb.get(i);if(null==o&&(o={messageId:`__synthetic_${++this.#ev}`,keys:new Set,indexKeys:new Map},this.#eb.set(i,o)),null==n&&"content-block-delta"===t.event){let e=t.delta,i=o.indexKeys.get(s),n=null!=i?this.#e_.get(i):void 0;if(null==e||"object"!=typeof e)return;if(null==n){if("block-delta"!==e.type||null==e.fields||"object"!=typeof e.fields)return;let i=e.fields;if(!l4.has(i.type))return;this.#ex({active:o,block:i,blockIndex:s,dataEvent:t.event,namespace:r,node:a,terminal:!1,createIfMissing:!0});return}if(n.observeIndex(s),"data-delta"===e.type&&"string"==typeof e.data){try{n.pushBytes(l6(e.data))}catch(e){n.fail("message-error","invalid base64 on delta",e)}return}if("block-delta"===e.type&&null!=e.fields&&"object"==typeof e.fields){let t=e.fields;if(n.absorbBlock(t),!n.error&&null!=t.data)try{n.pushBytes(l6(t.data))}catch(e){n.fail("message-error","invalid base64 on delta",e)}}return}if(null==n)return;let l=n.type;l4.has(l)&&this.#ex({active:o,block:n,blockIndex:s,dataEvent:t.event,namespace:r,node:a,terminal:"content-block-finish"===t.event,createIfMissing:"content-block-start"===t.event||"content-block-finish"===t.event})}#ex({active:e,block:t,blockIndex:r,dataEvent:a,namespace:i,node:n,terminal:s,createIfMissing:o}){let l=t.type;if(!l4.has(l))return;let u=`${e.messageId}::${l}::${r}`,d=this.#e_.get(u);if(null==d){if("content-block-start"!==a&&!s&&!o)return;if(d=new l5({type:l,messageId:e.messageId,namespace:[...i],node:n,id:t.id,mimeType:t.mime_type??t.mimeType,url:null!=t.url&&null==t.data?t.url:void 0,fetch:this.#ey}),null!=t.url&&null==t.data&&d.enterUrlMode(t.url),d.observeIndex(r),d.absorbBlock(t),null!=t.data)try{d.pushBytes(l6(t.data))}catch(e){d.fail("message-error","invalid base64 on initial block",e)}this.#e_.set(u,d),e.keys.add(u),e.indexKeys.set(r,u),this.#k(d),s&&(d.finish(),this.#e_.delete(u),e.keys.delete(u),e.indexKeys.delete(r));return}if(!s&&(d.observeIndex(r),d.absorbBlock(t),!d.error&&null!=t.data))try{d.pushBytes(l6(t.data))}catch(e){d.fail("message-error","invalid base64 on delta",e)}}#ew(e,t,r){let a=this.#eb.get(e);if(null!=a){for(let e of a.keys){let a=this.#e_.get(e);null!=a&&("finish"===t?a.finish():a.fail("message-error",r)),this.#e_.delete(e)}a.keys.clear(),a.indexKeys.clear()}}close(){for(let e of this.#e_.values())e.fail("stream-closed","upstream event stream closed");this.#e_.clear(),this.#eb.clear()}#k(e){switch(e.type){case"audio":this.#eg.onAudio?.(e);break;case"image":this.#eg.onImage?.(e);break;case"video":this.#eg.onVideo?.(e);break;case"file":this.#eg.onFile?.(e)}this.#eg.onMedia?.(e)}};e.s(["MediaAssembler",0,l3,"MediaAssemblyError",0,l9],41348)},43073,e=>{"use strict";var t=class{#ek=[];#eS=new Set;#x=!1;push(e){for(let t of(this.#ek.push(e),this.#eS))t();this.#eS.clear()}close(){for(let e of(this.#x=!0,this.#eS))e();this.#eS.clear()}get length(){return this.#ek.length}[Symbol.asyncIterator](){let e=0;return{next:async()=>{for(;;){if(e<this.#ek.length)return{done:!1,value:this.#ek[e++]};if(this.#x)return{done:!0,value:void 0};await new Promise(e=>{this.#eS.add(e)})}},return:async()=>({done:!0,value:void 0})}}};e.s(["MultiCursorBuffer",0,t])},478492,(e,t,r)=>{"use strict";var a=Object.prototype.hasOwnProperty,i="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,r,a,n){if("function"!=typeof r)throw TypeError("The listener must be a function");var o=new s(r,a||e,n),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function l(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function u(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(i=!1)),u.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)a.call(e,t)&&r.push(i?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},u.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var a=0,n=r.length,s=Array(n);a<n;a++)s[a]=r[a].fn;return s},u.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},u.prototype.emit=function(e,t,r,a,n,s){var o=i?i+e:e;if(!this._events[o])return!1;var l,u,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,a),!0;case 5:return d.fn.call(d.context,t,r,a,n),!0;case 6:return d.fn.call(d.context,t,r,a,n,s),!0}for(u=1,l=Array(c-1);u<c;u++)l[u-1]=arguments[u];d.fn.apply(d.context,l)}else{var h,p=d.length;for(u=0;u<p;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),c){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,r);break;case 4:d[u].fn.call(d[u].context,t,r,a);break;default:if(!l)for(h=1,l=Array(c-1);h<c;h++)l[h-1]=arguments[h];d[u].fn.apply(d[u].context,l)}}return!0},u.prototype.on=function(e,t,r){return o(this,e,t,r,!1)},u.prototype.once=function(e,t,r){return o(this,e,t,r,!0)},u.prototype.removeListener=function(e,t,r,a){var n=i?i+e:e;if(!this._events[n])return this;if(!t)return l(this,n),this;var s=this._events[n];if(s.fn)s.fn!==t||a&&!s.once||r&&s.context!==r||l(this,n);else{for(var o=0,u=[],d=s.length;o<d;o++)(s[o].fn!==t||a&&!s[o].once||r&&s[o].context!==r)&&u.push(s[o]);u.length?this._events[n]=1===u.length?u[0]:u:l(this,n)}return this},u.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&l(this,t)):(this._events=new n,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=i,u.EventEmitter=u,t.exports=u},297422,(e,t,r)=>{"use strict";t.exports=(e,t)=>(t=t||(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))},625441,(e,t,r)=>{"use strict";let a=e.r(297422);class i extends Error{constructor(e){super(e),this.name="TimeoutError"}}let n=(e,t,r)=>new Promise((n,s)=>{if("number"!=typeof t||t<0)throw TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void n(e);let o=setTimeout(()=>{if("function"==typeof r){try{n(r())}catch(e){s(e)}return}let a="string"==typeof r?r:`Promise timed out after ${t} milliseconds`,o=r instanceof Error?r:new i(a);"function"==typeof e.cancel&&e.cancel(),s(o)},t);a(e.then(n,s),()=>{clearTimeout(o)})});t.exports=n,t.exports.default=n,t.exports.TimeoutError=i},345541,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r){let a=0,i=e.length;for(;i>0;){let n=i/2|0,s=a+n;0>=r(e[s],t)?(a=++s,i-=n+1):i=n}return a}},311102,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let a=e.r(345541);r.default=class{constructor(){this._queue=[]}enqueue(e,t){let r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(r);let i=a.default(this._queue,r,(e,t)=>t.priority-e.priority);this._queue.splice(i,0,r)}dequeue(){let e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this._queue.length}}},753274,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let a=e.r(478492),i=e.r(625441),n=e.r(311102),s=()=>{},o=new i.TimeoutError;r.default=class extends a{constructor(e){var t,r,a,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=s,this._resolveIdle=s,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:n.default},e)).intervalCap&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!=(r=null==(t=e.intervalCap)?void 0:t.toString())?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!=(i=null==(a=e.interval)?void 0:a.toString())?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=s,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=s,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(void 0===this._intervalId){let t=this._intervalEnd-e;if(!(t<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((r,a)=>{let n=async()=>{this._pendingCount++,this._intervalCount++;try{let n=void 0===this._timeout&&void 0===t.timeout?e():i.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&a(o)});r(await n)}catch(e){a(e)}this._next()};this._queue.enqueue(n,t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this._isPaused&&(this._isPaused=!1,this._processQueue()),this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}}]);
|