@mcp-use/inspector 1.0.0-canary.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (246) hide show
  1. package/dist/cdn/inspector.css +1 -1
  2. package/dist/cdn/inspector.js +81264 -80633
  3. package/dist/client/hooks/useMCPPrompts.d.ts +3 -3
  4. package/dist/client/index.js +13657 -775
  5. package/dist/web/assets/browser-BwHKNEau.js +380 -0
  6. package/dist/web/assets/chunk-BBSBHVGK-D4wCPq_w.js +1 -0
  7. package/dist/web/assets/{chunk-KJ5RBDDO-DJkMH4KI.js → chunk-ECXMLUNG-CSRGaMIB.js} +1 -1
  8. package/dist/web/assets/chunk-JU7W27UC-CMTI_w7A.js +1 -0
  9. package/dist/web/assets/{chunk-QWQYAQCK-CyFuZlX8.js → chunk-QWQYAQCK-BR4V0xsV.js} +1 -1
  10. package/dist/web/assets/{chunk-RPN2XO5I-Boiv0wCv.js → chunk-RPN2XO5I-Cr13Miz-.js} +1 -1
  11. package/dist/web/assets/{chunk-UJPHRNQP-C81GjauI.js → chunk-UJPHRNQP-B14ZPq5a.js} +1 -1
  12. package/dist/web/assets/chunk_array-Bw1lTtex.js +1 -0
  13. package/dist/web/assets/{client-MLH2Q2DK-UzuK4Kji.js → client-2BTCLEUX-BhvJZmo-.js} +3 -3
  14. package/dist/web/assets/client-z1GrRUEs.js +68 -0
  15. package/dist/web/assets/{core-DktjxGrT.js → core-CsUyNVs5.js} +1 -1
  16. package/dist/web/assets/{core-B6Kp8rMh.js → core-GZZnkE26.js} +1 -1
  17. package/dist/web/assets/{display-A5IEINAP-BFwsYEHq.js → display-A5IEINAP-B8BJrcag.js} +2 -2
  18. package/dist/web/assets/{dist-CY62NsuD.js → dist-BZmXa__p.js} +2 -2
  19. package/dist/web/assets/{dist-B_dkmahO.js → dist-DlypDwtn.js} +1 -1
  20. package/dist/web/assets/dist-JsQmV3pO.js +21 -0
  21. package/dist/web/assets/dist-t5Yo0YiG.js +41 -0
  22. package/dist/web/assets/function_calling-kK7um7Ye.js +61 -0
  23. package/dist/web/assets/index-CM9P_1sf.css +2 -0
  24. package/dist/web/assets/index-zlrXpRSB.js +720 -0
  25. package/dist/web/assets/{json-schema-processors-DSIsU0go.js → json-schema-processors-DNSjFPrk.js} +1 -1
  26. package/dist/web/assets/langfuse-U2OEF7K7-BF5JV8uu.js +1 -0
  27. package/dist/web/assets/{llms-ByHaqvCr.js → llms-ByyTYk2T.js} +2 -2
  28. package/dist/web/assets/messages-D4_mH1tk.js +36 -0
  29. package/dist/web/assets/{module-DCsrdi7m.js → module-DbiflUeG.js} +2 -2
  30. package/dist/web/assets/react-C6BFTceN.js +1 -0
  31. package/dist/web/assets/rpc-logger-TPNV75J4-CMVlzCN7.js +1 -0
  32. package/dist/web/assets/{schemas-79owEkeD.js → schemas-BrqAD_Qo.js} +1 -1
  33. package/dist/web/assets/{source-1h9sRCfR.js → source-DeHaVNLZ.js} +1 -1
  34. package/dist/web/assets/stan-r2rUHRuO.js +1 -0
  35. package/dist/web/assets/{stdio-DH6BP75M-C4--HtGN.js → stdio-RWLH66ZO-C753VwJ7.js} +1 -1
  36. package/dist/web/assets/tools-kLe9X8V8.js +2 -0
  37. package/dist/web/index.html +13 -10
  38. package/package.json +8 -17
  39. package/dist/web/assets/browser-DeFVa-Up.js +0 -380
  40. package/dist/web/assets/chunk_array-CT_rI3GZ.js +0 -1
  41. package/dist/web/assets/client-DaI4JaTs.js +0 -68
  42. package/dist/web/assets/dist-Cjn62jmL.js +0 -21
  43. package/dist/web/assets/dist-DWk4vNzA.js +0 -41
  44. package/dist/web/assets/function_calling-BHFkMa4W.js +0 -61
  45. package/dist/web/assets/index-Bd0WP6Xj.js +0 -465
  46. package/dist/web/assets/index-DAB6h2wg.css +0 -2
  47. package/dist/web/assets/langfuse-U2OEF7K7-UPVEn4-O.js +0 -1
  48. package/dist/web/assets/messages-DQuC8BOl.js +0 -1
  49. package/dist/web/assets/react-C-wC1s-h.js +0 -1
  50. package/dist/web/assets/rpc-logger-TPNV75J4-DBofHjaa.js +0 -1
  51. package/dist/web/assets/stan-btJKTWsQ.js +0 -1
  52. package/dist/web/assets/tools-CFpbqXW1.js +0 -2
  53. /package/dist/web/assets/{1c-xAwF9KHw.js → 1c-AGlpZ3Bo.js} +0 -0
  54. /package/dist/web/assets/{abnf-57JF8nOy.js → abnf-CY04oKOo.js} +0 -0
  55. /package/dist/web/assets/{accesslog-C2D2ESC1.js → accesslog-BW-XYbZ-.js} +0 -0
  56. /package/dist/web/assets/{actionscript-BA90Z6ek.js → actionscript-CyrdwIe8.js} +0 -0
  57. /package/dist/web/assets/{ada-BOZemNeY.js → ada-C-TrrrBy.js} +0 -0
  58. /package/dist/web/assets/{angelscript-BPuRd7Au.js → angelscript-CRTYantF.js} +0 -0
  59. /package/dist/web/assets/{apache-CRejwSR0.js → apache-BtWb7jui.js} +0 -0
  60. /package/dist/web/assets/{applescript-DRWfnP7q.js → applescript-B5uiivcX.js} +0 -0
  61. /package/dist/web/assets/{arcade-c4fxT6cy.js → arcade-CKXflcFV.js} +0 -0
  62. /package/dist/web/assets/{arduino-D-GQgoAg.js → arduino-9WdEHP7F.js} +0 -0
  63. /package/dist/web/assets/{armasm-DW6aLB45.js → armasm-B1n3-9gm.js} +0 -0
  64. /package/dist/web/assets/{asciidoc-l4rRUjBn.js → asciidoc-DnpyabXI.js} +0 -0
  65. /package/dist/web/assets/{aspectj-CBoSaF_P.js → aspectj-DHfRYIO6.js} +0 -0
  66. /package/dist/web/assets/{autohotkey-oklQZH_e.js → autohotkey-D4kyAzbx.js} +0 -0
  67. /package/dist/web/assets/{autoit-CCOhikpq.js → autoit-Dkm5j0Id.js} +0 -0
  68. /package/dist/web/assets/{avrasm-DQyyIbM0.js → avrasm-DDWyveTc.js} +0 -0
  69. /package/dist/web/assets/{awk-Bpx3OGwB.js → awk-0C9tJhw5.js} +0 -0
  70. /package/dist/web/assets/{axapta-ConOtNUD.js → axapta-7WyvVgTr.js} +0 -0
  71. /package/dist/web/assets/{bash-CG9dvFVQ.js → bash-BU3h1nvY.js} +0 -0
  72. /package/dist/web/assets/{basic-D55fg9VU.js → basic-cvnVWdBh.js} +0 -0
  73. /package/dist/web/assets/{bnf-BRHfvdnF.js → bnf-DqQP6RvA.js} +0 -0
  74. /package/dist/web/assets/{brainfuck-CvIc7KgZ.js → brainfuck-9Gnm7MFh.js} +0 -0
  75. /package/dist/web/assets/{c-BYqCyjPu.js → c-CR0xII_C.js} +0 -0
  76. /package/dist/web/assets/{c-like-BiZIVjlk.js → c-like-DQRMjEeJ.js} +0 -0
  77. /package/dist/web/assets/{cal-BI45EWE9.js → cal-BupHjSW7.js} +0 -0
  78. /package/dist/web/assets/{capnproto-CT4_QH7U.js → capnproto-BJz3QcqE.js} +0 -0
  79. /package/dist/web/assets/{ceylon-DEhPqbQs.js → ceylon-Cm5BiqjN.js} +0 -0
  80. /package/dist/web/assets/{chunk-3GQAWCBQ-C-9Cm0Np.js → chunk-3GQAWCBQ-ntjTDD_C.js} +0 -0
  81. /package/dist/web/assets/{clean-Dj90Ldo4.js → clean-yd5cdwwQ.js} +0 -0
  82. /package/dist/web/assets/{clojure-nGPdvoWZ.js → clojure-BEy8uY0S.js} +0 -0
  83. /package/dist/web/assets/{clojure-repl-CoLrBnNB.js → clojure-repl-4mYnspW8.js} +0 -0
  84. /package/dist/web/assets/{cmake-Cau5qcoL.js → cmake-D6UxhUeW.js} +0 -0
  85. /package/dist/web/assets/{coffeescript-CRI19SN5.js → coffeescript-BKMS6sen.js} +0 -0
  86. /package/dist/web/assets/{coq-cKQTGfiT.js → coq-ByIcAboL.js} +0 -0
  87. /package/dist/web/assets/{cos-BvDn-C7W.js → cos-WtGXvK46.js} +0 -0
  88. /package/dist/web/assets/{cpp-Cm8w5GBK.js → cpp-7GTPyvMa.js} +0 -0
  89. /package/dist/web/assets/{crmsh-BphFuWfQ.js → crmsh-C5mOafXq.js} +0 -0
  90. /package/dist/web/assets/{crystal-CjeRzStm.js → crystal-CDkEXhx-.js} +0 -0
  91. /package/dist/web/assets/{csharp-BjNNmcwi.js → csharp-BB5evbyJ.js} +0 -0
  92. /package/dist/web/assets/{csp-BDakTyDq.js → csp-C5gCtA0-.js} +0 -0
  93. /package/dist/web/assets/{css-BS5Bw9la.js → css-BxJzVbPg.js} +0 -0
  94. /package/dist/web/assets/{d-iafwvjhA.js → d-pa4_Cp7t.js} +0 -0
  95. /package/dist/web/assets/{dart-CJj6VfDK.js → dart-BX2VLXw3.js} +0 -0
  96. /package/dist/web/assets/{delphi-CiYfdpeB.js → delphi-DdHGjuIZ.js} +0 -0
  97. /package/dist/web/assets/{diff-C0_uVc7j.js → diff-CBEZzUzk.js} +0 -0
  98. /package/dist/web/assets/{django-D2hgH-Q1.js → django-D4YuT7a9.js} +0 -0
  99. /package/dist/web/assets/{dns-Cl4dGnK7.js → dns-r4HMRPCv.js} +0 -0
  100. /package/dist/web/assets/{dockerfile-meWkyaPv.js → dockerfile-ZfcC6nOD.js} +0 -0
  101. /package/dist/web/assets/{dos-AwMP_0oM.js → dos-CIXc_2yf.js} +0 -0
  102. /package/dist/web/assets/{dsconfig-CnDR2ZdU.js → dsconfig-DlugHtUP.js} +0 -0
  103. /package/dist/web/assets/{dts-BzC-HwM_.js → dts-DaEIYGjQ.js} +0 -0
  104. /package/dist/web/assets/{dust-C7Vcl3-X.js → dust-D5BPeLmO.js} +0 -0
  105. /package/dist/web/assets/{ebnf-CL9qQEga.js → ebnf-FDSeI3Uq.js} +0 -0
  106. /package/dist/web/assets/{elixir-CfaDenjY.js → elixir-BW6MO0JC.js} +0 -0
  107. /package/dist/web/assets/{elm-Cy8gaJOl.js → elm-DlEB7oVS.js} +0 -0
  108. /package/dist/web/assets/{erb-C-4IIk8K.js → erb-Cfqar-lN.js} +0 -0
  109. /package/dist/web/assets/{erlang-B1M6fLuV.js → erlang-CAmVwVgE.js} +0 -0
  110. /package/dist/web/assets/{erlang-repl-BejU3MB_.js → erlang-repl-ynjzGTyJ.js} +0 -0
  111. /package/dist/web/assets/{excel-BkfhIrhj.js → excel-B4xDzPh0.js} +0 -0
  112. /package/dist/web/assets/{fix-BVmdZVAA.js → fix-DrIaqPya.js} +0 -0
  113. /package/dist/web/assets/{flix-D0avEvQY.js → flix-C1QBAYX7.js} +0 -0
  114. /package/dist/web/assets/{fortran-DakqiesO.js → fortran-13hn1qLz.js} +0 -0
  115. /package/dist/web/assets/{fsharp-DA54xfXW.js → fsharp-DsthWJmP.js} +0 -0
  116. /package/dist/web/assets/{gams-CXTQKphs.js → gams-CCIHfrc2.js} +0 -0
  117. /package/dist/web/assets/{gauss-CG12HF6_.js → gauss-DPE0fKXo.js} +0 -0
  118. /package/dist/web/assets/{gcode-BCEABt45.js → gcode-Cnu_Eke-.js} +0 -0
  119. /package/dist/web/assets/{gherkin-ZM-mRt_J.js → gherkin-6DphholZ.js} +0 -0
  120. /package/dist/web/assets/{glsl-CsBoWmwk.js → glsl-bxnyXALN.js} +0 -0
  121. /package/dist/web/assets/{gml-BpvmFz5F.js → gml-CNHkNLih.js} +0 -0
  122. /package/dist/web/assets/{go-oa77k3Q1.js → go-CNn2XrbH.js} +0 -0
  123. /package/dist/web/assets/{golo-DnSZZkzZ.js → golo-DiSoln2k.js} +0 -0
  124. /package/dist/web/assets/{gradle-xhSl5jRG.js → gradle-DwRwgn-A.js} +0 -0
  125. /package/dist/web/assets/{groovy-BUGEyqOY.js → groovy-B5vHRPUi.js} +0 -0
  126. /package/dist/web/assets/{haml-Q5moYl6B.js → haml-DyyQV85z.js} +0 -0
  127. /package/dist/web/assets/{handlebars-B8gHazwq.js → handlebars-BAEJweq7.js} +0 -0
  128. /package/dist/web/assets/{haskell-C_nTNVTF.js → haskell-ChxeibtB.js} +0 -0
  129. /package/dist/web/assets/{haxe-DEa-mhEM.js → haxe-Bnvb8PoO.js} +0 -0
  130. /package/dist/web/assets/{hsp-DAtUNrWr.js → hsp-BdBjqG0g.js} +0 -0
  131. /package/dist/web/assets/{htmlbars-IZ5H55KS.js → htmlbars-Dco0ls0x.js} +0 -0
  132. /package/dist/web/assets/{http-BlfIsTrN.js → http-BQrDnbm9.js} +0 -0
  133. /package/dist/web/assets/{hy-BKHwYI3U.js → hy-j_gy-_-v.js} +0 -0
  134. /package/dist/web/assets/{inform7-DBoQipSc.js → inform7-4lpsdkpY.js} +0 -0
  135. /package/dist/web/assets/{ini-rm_5Fj36.js → ini-CyoU_M9N.js} +0 -0
  136. /package/dist/web/assets/{irpf90-R1rxRBNO.js → irpf90-CA5ICZkt.js} +0 -0
  137. /package/dist/web/assets/{isbl-WbUbjWRI.js → isbl-D5MCB9gL.js} +0 -0
  138. /package/dist/web/assets/{java-flBTnDBg.js → java-C_cNvtw0.js} +0 -0
  139. /package/dist/web/assets/{javascript-Bi9wT7IL.js → javascript-Cx9Fh-yC.js} +0 -0
  140. /package/dist/web/assets/{jboss-cli-BVqHepEU.js → jboss-cli-n0a6upZq.js} +0 -0
  141. /package/dist/web/assets/{json-BvAVz8jQ.js → json-pS218i2Y.js} +0 -0
  142. /package/dist/web/assets/{julia-B3zW89kP.js → julia-ByIGgcyj.js} +0 -0
  143. /package/dist/web/assets/{julia-repl-Cpt_AFpB.js → julia-repl-DoKEpX79.js} +0 -0
  144. /package/dist/web/assets/{kotlin-CMZ_9XJI.js → kotlin-D7EVUsdH.js} +0 -0
  145. /package/dist/web/assets/{lasso-DVqtNSau.js → lasso-CfHzza_u.js} +0 -0
  146. /package/dist/web/assets/{latex-CFJv-UA6.js → latex-DEpVEzU4.js} +0 -0
  147. /package/dist/web/assets/{ldif-BS-KKOy0.js → ldif-CztKIlXq.js} +0 -0
  148. /package/dist/web/assets/{leaf--Z87tMVa.js → leaf-BeXHCQvG.js} +0 -0
  149. /package/dist/web/assets/{less-CXBPSZIU.js → less-BYuoMNFC.js} +0 -0
  150. /package/dist/web/assets/{lisp-cVmS95gk.js → lisp-DENj9Gb0.js} +0 -0
  151. /package/dist/web/assets/{livecodeserver-BOOiQrUz.js → livecodeserver-DzZuZBA6.js} +0 -0
  152. /package/dist/web/assets/{livescript-CVxJe7N1.js → livescript-Dcoaf4MP.js} +0 -0
  153. /package/dist/web/assets/{llvm-DQeHJJ2W.js → llvm-B_NkXFs1.js} +0 -0
  154. /package/dist/web/assets/{lsl-Bfxi34aD.js → lsl-sr9xRjsv.js} +0 -0
  155. /package/dist/web/assets/{lua-DXxL7Qnq.js → lua-DOwApfze.js} +0 -0
  156. /package/dist/web/assets/{makefile-B5Fr6EdB.js → makefile-Dnbo7dYF.js} +0 -0
  157. /package/dist/web/assets/{markdown-DTODmQHl.js → markdown-DGgwjJWS.js} +0 -0
  158. /package/dist/web/assets/{mathematica-XsKNpYVI.js → mathematica-DvU9l120.js} +0 -0
  159. /package/dist/web/assets/{matlab-BQHIwHUE.js → matlab-flr6798G.js} +0 -0
  160. /package/dist/web/assets/{maxima-4gc2wOHL.js → maxima-DCd2nSGc.js} +0 -0
  161. /package/dist/web/assets/{mel-tWDc8R_0.js → mel-NmXTNXHL.js} +0 -0
  162. /package/dist/web/assets/{mercury-CMAR8Kmo.js → mercury-PVmYLiQ2.js} +0 -0
  163. /package/dist/web/assets/{mipsasm-CuThUvs6.js → mipsasm-LHYPiOXU.js} +0 -0
  164. /package/dist/web/assets/{mizar-DJiOXbyw.js → mizar-BbJKfTOL.js} +0 -0
  165. /package/dist/web/assets/{mojolicious-BHZ1FyrY.js → mojolicious-Dw8SBiyk.js} +0 -0
  166. /package/dist/web/assets/{monkey-Ckr0R6Af.js → monkey-CYCsHKco.js} +0 -0
  167. /package/dist/web/assets/{moonscript-rPHoYTbB.js → moonscript-BndWJdyg.js} +0 -0
  168. /package/dist/web/assets/{n1ql-CVbFFpfR.js → n1ql-p64i6r1f.js} +0 -0
  169. /package/dist/web/assets/{nginx-piKHOi7C.js → nginx-Clg11n23.js} +0 -0
  170. /package/dist/web/assets/{nim-D2ljN6dK.js → nim-BF6erjkH.js} +0 -0
  171. /package/dist/web/assets/{nix-BE-MXto5.js → nix-aqHU_7Cj.js} +0 -0
  172. /package/dist/web/assets/{node-repl-DywEPp9w.js → node-repl-DuuOln4U.js} +0 -0
  173. /package/dist/web/assets/{nsis-DQnnPyE6.js → nsis-BZNwabo3.js} +0 -0
  174. /package/dist/web/assets/{objectivec-DVFSpwpL.js → objectivec-BD-A2eRS.js} +0 -0
  175. /package/dist/web/assets/{ocaml-B9_ypEp1.js → ocaml-Dtfm3HD8.js} +0 -0
  176. /package/dist/web/assets/{openscad-Cquxty4i.js → openscad-3uP221Jx.js} +0 -0
  177. /package/dist/web/assets/{oxygene-BtOMSMR6.js → oxygene-DBIMAfJO.js} +0 -0
  178. /package/dist/web/assets/{parser3-CWVyPD7l.js → parser3-C9bjRYvd.js} +0 -0
  179. /package/dist/web/assets/{path-BzTN_bR6.js → path-CG3438uq.js} +0 -0
  180. /package/dist/web/assets/{perl-DQMBOVA5.js → perl-Be1CLDbh.js} +0 -0
  181. /package/dist/web/assets/{pf-DhGORkJd.js → pf-BEYn9RX1.js} +0 -0
  182. /package/dist/web/assets/{pgsql-awwi5nDK.js → pgsql-Bp-7Jjz8.js} +0 -0
  183. /package/dist/web/assets/{php-_c_VoeVa.js → php-D8HtobZG.js} +0 -0
  184. /package/dist/web/assets/{php-template-Dsp4D0jE.js → php-template-5wDTa_KR.js} +0 -0
  185. /package/dist/web/assets/{plaintext-7v3vLFp3.js → plaintext-DF3cBN5Y.js} +0 -0
  186. /package/dist/web/assets/{pony-BVahP-cB.js → pony-CA_LuLTd.js} +0 -0
  187. /package/dist/web/assets/{powershell-DDAkbMgT.js → powershell-CfylS3qM.js} +0 -0
  188. /package/dist/web/assets/{preload-helper-XLr9-hSf.js → preload-helper-ckxxtgMM.js} +0 -0
  189. /package/dist/web/assets/{processing-CCja83Ot.js → processing-BOdw1uey.js} +0 -0
  190. /package/dist/web/assets/{profile-BjuA8z3S.js → profile-BMNLdTbz.js} +0 -0
  191. /package/dist/web/assets/{prolog-jJiPeztA.js → prolog-wnuVaQNI.js} +0 -0
  192. /package/dist/web/assets/{properties-DK40DOVd.js → properties-BY2UjzIx.js} +0 -0
  193. /package/dist/web/assets/{protobuf-DJs85Lp7.js → protobuf-W4tuiDUG.js} +0 -0
  194. /package/dist/web/assets/{puppet-BPdGz-Jp.js → puppet-CcAPsi7F.js} +0 -0
  195. /package/dist/web/assets/{purebasic-C8c2xseX.js → purebasic-Cx_iSilj.js} +0 -0
  196. /package/dist/web/assets/{python-B-gHuzXK.js → python-DtGc5unX.js} +0 -0
  197. /package/dist/web/assets/{python-repl-CLJQcHH8.js → python-repl-B1V7zIpU.js} +0 -0
  198. /package/dist/web/assets/{q-VmMkCWpr.js → q-DwgFecwj.js} +0 -0
  199. /package/dist/web/assets/{qml-BkIM5RCI.js → qml-CxtqwNEV.js} +0 -0
  200. /package/dist/web/assets/{r-CHi-Wrw8.js → r-Vyl1b83h.js} +0 -0
  201. /package/dist/web/assets/{reasonml-B05iQ6f2.js → reasonml-D1BWml10.js} +0 -0
  202. /package/dist/web/assets/{rib-DzxrqgFS.js → rib-WKK4Jb_l.js} +0 -0
  203. /package/dist/web/assets/{roboconf-DVxtd4X5.js → roboconf-DD9St8Le.js} +0 -0
  204. /package/dist/web/assets/{routeros-C7PRtmmR.js → routeros-DIyDrw3W.js} +0 -0
  205. /package/dist/web/assets/{rsl-CcIHTLD_.js → rsl-CfigMFVZ.js} +0 -0
  206. /package/dist/web/assets/{ruby-BGhMoiTk.js → ruby-YHScF8rv.js} +0 -0
  207. /package/dist/web/assets/{ruleslanguage-2nOGmUbL.js → ruleslanguage-BYwdQsZF.js} +0 -0
  208. /package/dist/web/assets/{rust-Bn5K3sZf.js → rust-B5YXnMyV.js} +0 -0
  209. /package/dist/web/assets/{sas-BOCzodK2.js → sas-CCTr8w16.js} +0 -0
  210. /package/dist/web/assets/{scala-BRv9Y1Gl.js → scala-Cbxd3VFS.js} +0 -0
  211. /package/dist/web/assets/{scheme-DgxU7T27.js → scheme-BsN3DINT.js} +0 -0
  212. /package/dist/web/assets/{scilab-CDpHNnol.js → scilab-DPKVNXPG.js} +0 -0
  213. /package/dist/web/assets/{scss-_DXiA8XH.js → scss-DbQAKOek.js} +0 -0
  214. /package/dist/web/assets/{shell-JZbpHYqw.js → shell-DWzkAqOf.js} +0 -0
  215. /package/dist/web/assets/{smali-D-pxIQI6.js → smali-BftjeLb5.js} +0 -0
  216. /package/dist/web/assets/{smalltalk-BgHXrgWH.js → smalltalk-CRiQmXNN.js} +0 -0
  217. /package/dist/web/assets/{sml-XMsOdlaX.js → sml-StzcQc9I.js} +0 -0
  218. /package/dist/web/assets/{sqf-BAJmpDEs.js → sqf-DD5HJChz.js} +0 -0
  219. /package/dist/web/assets/{sql-qDDDtU5U.js → sql-DPgh6LFW.js} +0 -0
  220. /package/dist/web/assets/{sql_more-OsRq2zw0.js → sql_more-CtzXbTQc.js} +0 -0
  221. /package/dist/web/assets/{stata-Bk4QaRj1.js → stata-BVbnRiot.js} +0 -0
  222. /package/dist/web/assets/{step21-JBksYMyW.js → step21-Dq-6Zq9y.js} +0 -0
  223. /package/dist/web/assets/{stylus-B2-KoW99.js → stylus-BBnpEkBq.js} +0 -0
  224. /package/dist/web/assets/{subunit-Dms0B4fv.js → subunit-ELCErEkQ.js} +0 -0
  225. /package/dist/web/assets/{swift-BDkC6DWd.js → swift-DaAs7qTh.js} +0 -0
  226. /package/dist/web/assets/{taggerscript-BQuVNykw.js → taggerscript-1FPav-0a.js} +0 -0
  227. /package/dist/web/assets/{tap-Bwup7RHy.js → tap-EToQ4lhN.js} +0 -0
  228. /package/dist/web/assets/{tcl-CbpGYImD.js → tcl-D3o49C6L.js} +0 -0
  229. /package/dist/web/assets/{thrift-B_z8wKcZ.js → thrift-CWhyiqPB.js} +0 -0
  230. /package/dist/web/assets/{tp-BJLBEN3J.js → tp-B6O9yM_7.js} +0 -0
  231. /package/dist/web/assets/{twig-nUEnJWT1.js → twig-CtXlonbL.js} +0 -0
  232. /package/dist/web/assets/{typescript-CrQbuH5h.js → typescript-CCrKHjvE.js} +0 -0
  233. /package/dist/web/assets/{util-BS7JSiXp.js → util-_DavpSWv.js} +0 -0
  234. /package/dist/web/assets/{vala-2XexN6SZ.js → vala-DqTbJvZE.js} +0 -0
  235. /package/dist/web/assets/{vbnet-BAt8krwo.js → vbnet-BIMC8kyn.js} +0 -0
  236. /package/dist/web/assets/{vbscript--ebsjfOw.js → vbscript-CwHfrTEX.js} +0 -0
  237. /package/dist/web/assets/{vbscript-html-yaZI43iV.js → vbscript-html-6BIOjkqb.js} +0 -0
  238. /package/dist/web/assets/{verilog-emU2h0-4.js → verilog-Br3eYmwZ.js} +0 -0
  239. /package/dist/web/assets/{vhdl-CPuOZFR2.js → vhdl-CDlnDphM.js} +0 -0
  240. /package/dist/web/assets/{vim-ZfleAGCY.js → vim-BOZojkV6.js} +0 -0
  241. /package/dist/web/assets/{x86asm-BHTiWqya.js → x86asm-Br9iqCtX.js} +0 -0
  242. /package/dist/web/assets/{xl-MlLWG0U8.js → xl-eSTclZWH.js} +0 -0
  243. /package/dist/web/assets/{xml-CJKMw8W2.js → xml-C775tW_n.js} +0 -0
  244. /package/dist/web/assets/{xquery-B4Yi49S8.js → xquery-DimlVJ6h.js} +0 -0
  245. /package/dist/web/assets/{yaml-5C-oV2Cp.js → yaml-Dnhus5cp.js} +0 -0
  246. /package/dist/web/assets/{zephir-Dig9AotJ.js → zephir-j3mL6he_.js} +0 -0
@@ -0,0 +1,36 @@
1
+ import{o as e,r as t,t as n}from"./chunk-zsgVPwQN.js";import{Et as r,Fn as i,Lt as a,S as o,Xn as s,Yn as c,dt as l,mn as u,rr as d,tr as f,ur as p,xn as m}from"./json-schema-processors-DNSjFPrk.js";var h;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(h||={});var g;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(g||={});var _=h.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),v=e=>{switch(typeof e){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`:return Array.isArray(e)?_.array:e===null?_.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?_.promise:typeof Map<`u`&&e instanceof Map?_.map:typeof Set<`u`&&e instanceof Set?_.set:typeof Date<`u`&&e instanceof Date?_.date:_.object;default:return _.unknown}},y=h.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`]),b=class e 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]};let 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},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,h.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};b.create=e=>new b(e);var ee=(e,t)=>{let n;switch(e.code){case y.invalid_type:n=e.received===_.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,h.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:n=`Unrecognized key(s) in object: ${h.joinValues(e.keys,`, `)}`;break;case y.invalid_union:n=`Invalid input`;break;case y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${h.joinValues(e.options)}`;break;case y.invalid_enum_value:n=`Invalid enum value. Expected ${h.joinValues(e.options)}, received '${e.received}'`;break;case y.invalid_arguments:n=`Invalid function arguments`;break;case y.invalid_return_type:n=`Invalid function return type`;break;case y.invalid_date:n=`Invalid date`;break;case y.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:h.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case y.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`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 y.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case y.custom:n=`Invalid input`;break;case y.invalid_intersection_types:n=`Intersection results could not be merged`;break;case y.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case y.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,h.assertNever(e)}return{message:n}},te=ee;function ne(){return te}var re=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function x(e,t){let n=ne(),r=re({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ee?void 0:ee].filter(e=>!!e)});e.common.issues.push(r)}var S=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return C;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return C;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},C=Object.freeze({status:`aborted`}),ie=e=>({status:`dirty`,value:e}),w=e=>({status:`valid`,value:e}),ae=e=>e.status===`aborted`,oe=e=>e.status===`dirty`,se=e=>e.status===`valid`,ce=e=>typeof Promise<`u`&&e instanceof Promise,T;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(T||={});var le=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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}},ue=(e,t)=>{if(se(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(){return this._error||=new b(e.common.issues),this._error}}};function E(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))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:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var D=class{get description(){return this._def.description}_getType(e){return v(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:v(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new S,ctx:{common:e.parent.common,data:e.data,parsedType:v(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ce(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:v(e)};return ue(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:v(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return se(n)?{value:n.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=>se(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:v(e)},r=this._parse({data:e,path:n.path,parent:n});return ue(n,await(ce(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:y.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ft({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 pt.create(this,this._def)}nullable(){return mt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return qe.create(this)}promise(){return dt.create(this,this._def)}or(e){return Xe.create([this,e],this._def)}and(e){return et.create(this,e,this._def)}transform(e){return new ft({...E(this._def),schema:this,typeName:k.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ht({...E(this._def),innerType:this,defaultValue:t,typeName:k.ZodDefault})}brand(){return new vt({typeName:k.ZodBranded,type:this,...E(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new gt({...E(this._def),innerType:this,catchValue:t,typeName:k.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return yt.create(this,e)}readonly(){return bt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},de=/^c[^\s-]{8,}$/i,fe=/^[0-9a-z]+$/,pe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,me=/^[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,he=/^[a-z0-9_-]{21}$/i,ge=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,_e=/^[-+]?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)?)??$/,ve=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ye=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,be,xe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Se=/^(?:(?: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])$/,Ce=/^(([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]))$/,we=/^(([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])$/,Te=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ee=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,De=`((\\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])))`,O=RegExp(`^${De}$`);function Oe(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function ke(e){return RegExp(`^${Oe(e)}$`)}function Ae(e){let t=`${De}T${Oe(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function je(e,t){return!!((t===`v4`||!t)&&xe.test(e)||(t===`v6`||!t)&&Ce.test(e))}function Me(e,t){if(!ge.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Ne(e,t){return!!((t===`v4`||!t)&&Se.test(e)||(t===`v6`||!t)&&we.test(e))}var Pe=class e extends D{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==_.string){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.string,received:t.parsedType}),C}let t=new S,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?x(n,{code:y.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&x(n,{code:y.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)ve.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`email`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)be||=new RegExp(ye,`u`),be.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`emoji`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)me.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`uuid`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)he.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`nanoid`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)de.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`cuid`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)fe.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`cuid2`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)pe.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`ulid`,code:y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),x(n,{validation:`url`,code:y.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`regex`,code:y.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),x(n,{code:y.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),x(n,{code:y.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),x(n,{code:y.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Ae(r).test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{code:y.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?O.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{code:y.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?ke(r).test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{code:y.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?_e.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`duration`,code:y.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?je(e.data,r.version)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`ip`,code:y.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Me(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`jwt`,code:y.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Ne(e.data,r.version)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`cidr`,code:y.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Te.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`base64`,code:y.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ee.test(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{validation:`base64url`,code:y.invalid_string,message:r.message}),t.dirty()):h.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:y.invalid_string,...T.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...T.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...T.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...T.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...T.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...T.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...T.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...T.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...T.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...T.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...T.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...T.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...T.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...T.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...T.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...T.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...T.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...T.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...T.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...T.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...T.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...T.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...T.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...T.errToObj(t)})}nonempty(e){return this.min(1,T.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Pe.create=e=>new Pe({checks:[],typeName:k.ZodString,coerce:e?.coerce??!1,...E(e)});function Fe(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Ie=class e extends D{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==_.number){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.number,received:t.parsedType}),C}let t,n=new S;for(let r of this._def.checks)r.kind===`int`?h.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),x(t,{code:y.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),x(t,{code:y.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),x(t,{code:y.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Fe(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),x(t,{code:y.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),x(t,{code:y.not_finite,message:r.message}),n.dirty()):h.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,T.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,T.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,T.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,T.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:T.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:T.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:T.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:T.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:T.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:T.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&h.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Ie.create=e=>new Ie({checks:[],typeName:k.ZodNumber,coerce:e?.coerce||!1,...E(e)});var Le=class e extends D{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==_.bigint)return this._getInvalidInput(e);let t,n=new S;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),x(t,{code:y.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),x(t,{code:y.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),x(t,{code:y.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):h.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.bigint,received:t.parsedType}),C}gte(e,t){return this.setLimit(`min`,e,!0,T.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,T.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,T.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,T.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:T.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:T.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Le.create=e=>new Le({checks:[],typeName:k.ZodBigInt,coerce:e?.coerce??!1,...E(e)});var Re=class extends D{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==_.boolean){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.boolean,received:t.parsedType}),C}return w(e.data)}};Re.create=e=>new Re({typeName:k.ZodBoolean,coerce:e?.coerce||!1,...E(e)});var ze=class e extends D{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==_.date){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.date,received:t.parsedType}),C}if(Number.isNaN(e.data.getTime()))return x(this._getOrReturnCtx(e),{code:y.invalid_date}),C;let t=new S,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):h.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:T.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:T.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ze.create=e=>new ze({checks:[],coerce:e?.coerce||!1,typeName:k.ZodDate,...E(e)});var Be=class extends D{_parse(e){if(this._getType(e)!==_.symbol){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.symbol,received:t.parsedType}),C}return w(e.data)}};Be.create=e=>new Be({typeName:k.ZodSymbol,...E(e)});var Ve=class extends D{_parse(e){if(this._getType(e)!==_.undefined){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.undefined,received:t.parsedType}),C}return w(e.data)}};Ve.create=e=>new Ve({typeName:k.ZodUndefined,...E(e)});var He=class extends D{_parse(e){if(this._getType(e)!==_.null){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.null,received:t.parsedType}),C}return w(e.data)}};He.create=e=>new He({typeName:k.ZodNull,...E(e)});var Ue=class extends D{constructor(){super(...arguments),this._any=!0}_parse(e){return w(e.data)}};Ue.create=e=>new Ue({typeName:k.ZodAny,...E(e)});var We=class extends D{constructor(){super(...arguments),this._unknown=!0}_parse(e){return w(e.data)}};We.create=e=>new We({typeName:k.ZodUnknown,...E(e)});var Ge=class extends D{_parse(e){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.never,received:t.parsedType}),C}};Ge.create=e=>new Ge({typeName:k.ZodNever,...E(e)});var Ke=class extends D{_parse(e){if(this._getType(e)!==_.undefined){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.void,received:t.parsedType}),C}return w(e.data)}};Ke.create=e=>new Ke({typeName:k.ZodVoid,...E(e)});var qe=class e extends D{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==_.array)return x(t,{code:y.invalid_type,expected:_.array,received:t.parsedType}),C;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(x(t,{code:e?y.too_big:y.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(x(t,{code:y.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(x(t,{code:y.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new le(t,e,t.path,n)))).then(e=>S.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new le(t,e,t.path,n)));return S.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:T.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:T.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:T.toString(n)}})}nonempty(e){return this.min(1,e)}};qe.create=(e,t)=>new qe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...E(t)});function Je(e){if(e instanceof Ye){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=pt.create(Je(r))}return new Ye({...e._def,shape:()=>t})}else if(e instanceof qe)return new qe({...e._def,type:Je(e.element)});else if(e instanceof pt)return pt.create(Je(e.unwrap()));else if(e instanceof mt)return mt.create(Je(e.unwrap()));else if(e instanceof tt)return tt.create(e.items.map(e=>Je(e)));else return e}var Ye=class e extends D{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:h.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==_.object){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.object,received:t.parsedType}),C}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ge&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new le(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Ge){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(x(n,{code:y.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new le(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>S.mergeObjectSync(t,e)):S.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return T.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:T.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:k.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of h.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of h.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Je(this)}partial(t){let n={};for(let e of h.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of h.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof pt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return ct(h.objectKeys(this.shape))}};Ye.create=(e,t)=>new Ye({shape:()=>e,unknownKeys:`strip`,catchall:Ge.create(),typeName:k.ZodObject,...E(t)}),Ye.strictCreate=(e,t)=>new Ye({shape:()=>e,unknownKeys:`strict`,catchall:Ge.create(),typeName:k.ZodObject,...E(t)}),Ye.lazycreate=(e,t)=>new Ye({shape:e,unknownKeys:`strip`,catchall:Ge.create(),typeName:k.ZodObject,...E(t)});var Xe=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new b(e.ctx.common.issues));return x(t,{code:y.invalid_union,unionErrors:n}),C}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new b(e));return x(t,{code:y.invalid_union,unionErrors:i}),C}}get options(){return this._def.options}};Xe.create=(e,t)=>new Xe({options:e,typeName:k.ZodUnion,...E(t)});var Ze=e=>e instanceof ot?Ze(e.schema):e instanceof ft?Ze(e.innerType()):e instanceof st?[e.value]:e instanceof lt?e.options:e instanceof ut?h.objectValues(e.enum):e instanceof ht?Ze(e._def.innerType):e instanceof Ve?[void 0]:e instanceof He?[null]:e instanceof pt?[void 0,...Ze(e.unwrap())]:e instanceof mt?[null,...Ze(e.unwrap())]:e instanceof vt||e instanceof bt?Ze(e.unwrap()):e instanceof gt?Ze(e._def.innerType):[],Qe=class e extends D{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.object)return x(t,{code:y.invalid_type,expected:_.object,received:t.parsedType}),C;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);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}):(x(t,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),C)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Ze(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:k.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...E(r)})}};function $e(e,t){let n=v(e),r=v(t);if(e===t)return{valid:!0,data:e};if(n===_.object&&r===_.object){let n=h.objectKeys(t),r=h.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=$e(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===_.array&&r===_.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=$e(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===_.date&&r===_.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var et=class extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ae(e)||ae(r))return C;let i=$e(e.value,r.value);return i.valid?((oe(e)||oe(r))&&t.dirty(),{status:t.value,value:i.data}):(x(n,{code:y.invalid_intersection_types}),C)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};et.create=(e,t,n)=>new et({left:e,right:t,typeName:k.ZodIntersection,...E(n)});var tt=class e extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.array)return x(n,{code:y.invalid_type,expected:_.array,received:n.parsedType}),C;if(n.data.length<this._def.items.length)return x(n,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),C;!this._def.rest&&n.data.length>this._def.items.length&&(x(n,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new le(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>S.mergeArray(t,e)):S.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};tt.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new tt({items:e,typeName:k.ZodTuple,rest:null,...E(t)})};var nt=class e extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.object)return x(n,{code:y.invalid_type,expected:_.object,received:n.parsedType}),C;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new le(n,e,n.path,e)),value:a._parse(new le(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?S.mergeObjectAsync(t,r):S.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof D?new e({keyType:t,valueType:n,typeName:k.ZodRecord,...E(r)}):new e({keyType:Pe.create(),valueType:t,typeName:k.ZodRecord,...E(n)})}},rt=class extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.map)return x(n,{code:y.invalid_type,expected:_.map,received:n.parsedType}),C;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new le(n,e,n.path,[a,`key`])),value:i._parse(new le(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return C;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return C;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};rt.create=(e,t,n)=>new rt({valueType:t,keyType:e,typeName:k.ZodMap,...E(n)});var it=class e extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.set)return x(n,{code:y.invalid_type,expected:_.set,received:n.parsedType}),C;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(x(n,{code:y.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(x(n,{code:y.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return C;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new le(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:T.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:T.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};it.create=(e,t)=>new it({valueType:e,minSize:null,maxSize:null,typeName:k.ZodSet,...E(t)});var at=class e extends D{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.function)return x(t,{code:y.invalid_type,expected:_.function,received:t.parsedType}),C;function n(e,n){return re({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ne(),ee].filter(e=>!!e),issueData:{code:y.invalid_arguments,argumentsError:n}})}function r(e,n){return re({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ne(),ee].filter(e=>!!e),issueData:{code:y.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof dt){let e=this;return w(async function(...t){let o=new b([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return w(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new b([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new b([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:tt.create(t).rest(We.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||tt.create([]).rest(We.create()),returns:n||We.create(),typeName:k.ZodFunction,...E(r)})}},ot=class extends D{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})}};ot.create=(e,t)=>new ot({getter:e,typeName:k.ZodLazy,...E(t)});var st=class extends D{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return x(t,{received:t.data,code:y.invalid_literal,expected:this._def.value}),C}return{status:`valid`,value:e.data}}get value(){return this._def.value}};st.create=(e,t)=>new st({value:e,typeName:k.ZodLiteral,...E(t)});function ct(e,t){return new lt({values:e,typeName:k.ZodEnum,...E(t)})}var lt=class e extends D{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return x(t,{expected:h.joinValues(n),received:t.parsedType,code:y.invalid_type}),C}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return x(t,{received:t.data,code:y.invalid_enum_value,options:n}),C}return w(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(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};lt.create=ct;var ut=class extends D{_parse(e){let t=h.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==_.string&&n.parsedType!==_.number){let e=h.objectValues(t);return x(n,{expected:h.joinValues(e),received:n.parsedType,code:y.invalid_type}),C}if(this._cache||=new Set(h.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=h.objectValues(t);return x(n,{received:n.data,code:y.invalid_enum_value,options:e}),C}return w(e.data)}get enum(){return this._def.values}};ut.create=(e,t)=>new ut({values:e,typeName:k.ZodNativeEnum,...E(t)});var dt=class extends D{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==_.promise&&t.common.async===!1?(x(t,{code:y.invalid_type,expected:_.promise,received:t.parsedType}),C):w((t.parsedType===_.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};dt.create=(e,t)=>new dt({type:e,typeName:k.ZodPromise,...E(t)});var ft=class extends D{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:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{x(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return C;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?C:r.status===`dirty`||t.value===`dirty`?ie(r.value):r});{if(t.value===`aborted`)return C;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?C:r.status===`dirty`||t.value===`dirty`?ie(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.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(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?C:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?C:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!se(e))return C;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>se(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):C);h.assertNever(r)}};ft.create=(e,t,n)=>new ft({schema:e,typeName:k.ZodEffects,effect:t,...E(n)}),ft.createWithPreprocess=(e,t,n)=>new ft({schema:t,effect:{type:`preprocess`,transform:e},typeName:k.ZodEffects,...E(n)});var pt=class extends D{_parse(e){return this._getType(e)===_.undefined?w(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};pt.create=(e,t)=>new pt({innerType:e,typeName:k.ZodOptional,...E(t)});var mt=class extends D{_parse(e){return this._getType(e)===_.null?w(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};mt.create=(e,t)=>new mt({innerType:e,typeName:k.ZodNullable,...E(t)});var ht=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===_.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ht.create=(e,t)=>new ht({innerType:e,typeName:k.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...E(t)});var gt=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ce(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new b(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new b(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};gt.create=(e,t)=>new gt({innerType:e,typeName:k.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...E(t)});var _t=class extends D{_parse(e){if(this._getType(e)!==_.nan){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:_.nan,received:t.parsedType}),C}return{status:`valid`,value:e.data}}};_t.create=e=>new _t({typeName:k.ZodNaN,...E(e)});var vt=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},yt=class e extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?C:e.status===`dirty`?(t.dirty(),ie(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?C:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:k.ZodPipeline})}},bt=class extends D{_parse(e){let t=this._def.innerType._parse(e),n=e=>(se(e)&&(e.value=Object.freeze(e.value)),e);return ce(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};bt.create=(e,t)=>new bt({innerType:e,typeName:k.ZodReadonly,...E(t)});function xt(e,t){let n=typeof e==`function`?e(t):typeof e==`string`?{message:e}:e;return typeof n==`string`?{message:n}:n}function St(e,t={},n){return e?Ue.create().superRefine((r,i)=>{let a=e(r);if(a instanceof Promise)return a.then(e=>{if(!e){let e=xt(t,r),a=e.fatal??n??!0;i.addIssue({code:`custom`,...e,fatal:a})}});if(!a){let e=xt(t,r),a=e.fatal??n??!0;i.addIssue({code:`custom`,...e,fatal:a})}}):Ue.create()}Ye.lazycreate;var k;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(k||={});var Ct=(e,t={message:`Input not instance of ${e.name}`})=>St(t=>t instanceof e,t),wt=Pe.create,Tt=Ie.create;_t.create,Le.create;var Et=Re.create;ze.create,Be.create,Ve.create,He.create;var Dt=Ue.create;We.create,Ge.create,Ke.create;var Ot=qe.create,kt=Ye.create;Ye.strictCreate;var At=Xe.create;Qe.create,et.create,tt.create;var jt=nt.create;rt.create,it.create;var Mt=at.create;ot.create;var Nt=st.create,Pt=lt.create;ut.create;var Ft=dt.create;ft.create,pt.create,mt.create,ft.createWithPreprocess,yt.create;var It=Object.defineProperty,A=(e,t)=>{for(var n in t)It(e,n,{get:t[n],enumerable:!0})};function Lt(e){return typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`&&`source_type`in e&&(e.source_type===`url`||e.source_type===`base64`||e.source_type===`text`||e.source_type===`id`)}function Rt(e){return Lt(e)&&e.source_type===`url`&&`url`in e&&typeof e.url==`string`}function zt(e){return Lt(e)&&e.source_type===`base64`&&`data`in e&&typeof e.data==`string`}function Bt(e){return Lt(e)&&e.source_type===`text`&&`text`in e&&typeof e.text==`string`}function Vt(e){return Lt(e)&&e.source_type===`id`&&`id`in e&&typeof e.id==`string`}function Ht(e){if(Lt(e)){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url}};if(e.source_type===`base64`){if(!e.mime_type)throw Error(`mime_type key is required for base64 data.`);return{type:`image_url`,image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw Error(`Unsupported source type. Only 'url' and 'base64' are supported.`)}function Ut(e){let t=e.split(`;`)[0].split(`/`);if(t.length!==2)throw Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);let n=t[0].trim(),r=t[1].trim();if(n===``||r===``)throw Error(`Invalid mime type: "${e}" - type or subtype is empty.`);let i={};for(let t of e.split(`;`).slice(1)){let n=t.split(`=`);if(n.length!==2)throw Error(`Invalid parameter syntax in mime type: "${e}".`);let r=n[0].trim(),a=n[1].trim();if(r===``)throw Error(`Invalid parameter syntax in mime type: "${e}".`);i[r]=a}return{type:n,subtype:r,parameters:i}}function Wt({dataUrl:e,asTypedArray:t=!1}){let n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),r;if(n){r=n[1].toLowerCase();let e=t?Uint8Array.from(atob(n[2]),e=>e.charCodeAt(0)):n[2];return{mime_type:r,data:e}}}function Gt(e,t){if(e.type===`text`){if(!t.fromStandardTextBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type===`image`){if(!t.fromStandardImageBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type===`audio`){if(!t.fromStandardAudioBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type===`file`){if(!t.fromStandardFileBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function Kt(e){return typeof e==`object`&&!!e&&`type`in e&&`content`in e&&(typeof e.content==`string`||Array.isArray(e.content))}var qt=n(((e,t)=>{t.exports=function(e,t){if(typeof e!=`string`)throw TypeError(`Expected a string`);return t=t===void 0?`_`:t,e.replace(/([a-z\d])([A-Z])/g,`$1`+t+`$2`).replace(/([A-Z]+)([A-Z][a-z\d]+)/g,`$1`+t+`$2`).toLowerCase()}})),Jt=n(((e,t)=>{var n=/[\p{Lu}]/u,r=/[\p{Ll}]/u,i=/^[\p{Lu}](?![\p{Lu}])/gu,a=/([\p{Alpha}\p{N}_]|$)/u,o=/[_.\- ]+/,s=RegExp(`^`+o.source),c=new RegExp(o.source+a.source,`gu`),l=RegExp(`\\d+`+a.source,`gu`),u=(e,t,i)=>{let a=!1,o=!1,s=!1;for(let c=0;c<e.length;c++){let l=e[c];a&&n.test(l)?(e=e.slice(0,c)+`-`+e.slice(c),a=!1,s=o,o=!0,c++):o&&s&&r.test(l)?(e=e.slice(0,c-1)+`-`+e.slice(c-1),s=o,o=!1,a=!0):(a=t(l)===l&&i(l)!==l,s=o,o=i(l)===l&&t(l)!==l)}return e},d=(e,t)=>(i.lastIndex=0,e.replace(i,e=>t(e))),f=(e,t)=>(c.lastIndex=0,l.lastIndex=0,e.replace(c,(e,n)=>t(n)).replace(l,e=>t(e))),p=(e,t)=>{if(!(typeof e==`string`||Array.isArray(e)))throw TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},e=Array.isArray(e)?e.map(e=>e.trim()).filter(e=>e.length).join(`-`):e.trim(),e.length===0)return``;let n=t.locale===!1?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale),r=t.locale===!1?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);return e.length===1?t.pascalCase?r(e):n(e):(e!==n(e)&&(e=u(e,n,r)),e=e.replace(s,``),e=t.preserveConsecutiveUppercase?d(e,n):n(e),t.pascalCase&&(e=r(e.charAt(0))+e.slice(1)),f(e,r))};t.exports=p,t.exports.default=p})),Yt=e(qt(),1),Xt=e(Jt(),1);function Zt(e,t){return t?.[e]||(0,Yt.default)(e)}function Qt(e,t){return t?.[e]||(0,Xt.default)(e)}function $t(e,t,n){let r={};for(let i in e)Object.hasOwn(e,i)&&(r[t(i,n)]=e[i]);return r}var en=`__lc_escaped__`;function tn(e){return`lc`in e||Object.keys(e).length===1&&en in e}function nn(e){return{[en]:e}}function rn(e){return Object.keys(e).length===1&&en in e}function an(e){return typeof e==`object`&&!!e&&`lc_serializable`in e&&typeof e.toJSON==`function`}function on(e){let t;return t=typeof e==`object`&&e?`lc_id`in e&&Array.isArray(e.lc_id)?e.lc_id:[e.constructor?.name??`Object`]:[typeof e],{lc:1,type:`not_implemented`,id:t}}function sn(e,t=new WeakSet){if(typeof e==`object`&&e&&!Array.isArray(e)){if(t.has(e))return on(e);if(an(e))return e;t.add(e);let n=e;if(tn(n))return t.delete(e),nn(n);let r={};for(let[e,i]of Object.entries(n))r[e]=sn(i,t);return t.delete(e),r}return Array.isArray(e)?e.map(e=>sn(e,t)):e}function cn(e){if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e;if(rn(t))return t[en];let n={};for(let[e,r]of Object.entries(t))n[e]=cn(r);return n}return Array.isArray(e)?e.map(e=>cn(e)):e}var ln={};A(ln,{Serializable:()=>pn,get_lc_unique_name:()=>fn});function un(e){return Array.isArray(e)?[...e]:{...e}}function dn(e,t){let n=un(e);for(let[e,r]of Object.entries(t)){let[t,...i]=e.split(`.`).reverse(),a=n;for(let e of i.reverse()){if(a[e]===void 0)break;a[e]=un(a[e]),a=a[e]}a[t]!==void 0&&(a[t]={lc:1,type:`secret`,id:[r]})}return n}function fn(e){let t=Object.getPrototypeOf(e);return typeof e.lc_name==`function`&&(typeof t.lc_name!=`function`||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var pn=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,fn(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){this.lc_serializable_keys===void 0?this.lc_kwargs=e??{}:this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e)))}toJSON(){if(!this.lc_serializable||this.lc_kwargs instanceof e||typeof this.lc_kwargs!=`object`||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},n={},r=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(n,Reflect.get(e,`lc_secrets`,this)),Object.assign(r,Reflect.get(e,`lc_attributes`,this));Object.keys(n).forEach(e=>{let t=this,n=r,[i,...a]=e.split(`.`).reverse();for(let e of a.reverse()){if(!(e in t)||t[e]===void 0)return;(!(e in n)||n[e]===void 0)&&(typeof t[e]==`object`&&t[e]!=null?n[e]={}:Array.isArray(t[e])&&(n[e]=[])),t=t[e],n=n[e]}i in t&&t[i]!==void 0&&(n[i]=n[i]||t[i])});let i={},a=new WeakSet;a.add(this);for(let[e,t]of Object.entries(r))i[e]=sn(t,a);let o=$t(Object.keys(n).length?dn(i,n):i,Zt,t);return{lc:1,type:`constructor`,id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:`not_implemented`,id:this.lc_id}}};function j(e,t){return M(e)&&e.type===t}function M(e){return typeof e==`object`&&!!e}function mn(e){return Array.isArray(e)}function N(e){return typeof e==`string`}function hn(e){return typeof e==`number`}function gn(e){return e instanceof Uint8Array}function _n(e){try{return JSON.parse(e)}catch{return}}var vn=e=>e();function yn(e){if(e.type===`char_location`&&N(e.document_title)&&hn(e.start_char_index)&&hn(e.end_char_index)&&N(e.cited_text)){let{document_title:t,start_char_index:n,end_char_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`char`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`page_location`&&N(e.document_title)&&hn(e.start_page_number)&&hn(e.end_page_number)&&N(e.cited_text)){let{document_title:t,start_page_number:n,end_page_number:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`page`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`content_block_location`&&N(e.document_title)&&hn(e.start_block_index)&&hn(e.end_block_index)&&N(e.cited_text)){let{document_title:t,start_block_index:n,end_block_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`block`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`web_search_result_location`&&N(e.url)&&N(e.title)&&N(e.encrypted_index)&&N(e.cited_text)){let{url:t,title:n,encrypted_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`url`,url:t,title:n,startIndex:Number(r),endIndex:Number(r),citedText:i}}if(e.type===`search_result_location`&&N(e.source)&&N(e.title)&&hn(e.start_block_index)&&hn(e.end_block_index)&&N(e.cited_text)){let{source:t,title:n,start_block_index:r,end_block_index:i,cited_text:a,...o}=e;return{...o,type:`citation`,source:`search`,url:t,title:n??void 0,startIndex:r,endIndex:i,citedText:a}}}function bn(e){if(j(e,`document`)&&M(e.source)&&`type`in e.source){if(e.source.type===`base64`&&N(e.source.media_type)&&N(e.source.data))return{type:`file`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&N(e.source.url))return{type:`file`,url:e.source.url};if(e.source.type===`file`&&N(e.source.file_id))return{type:`file`,fileId:e.source.file_id};if(e.source.type===`text`&&N(e.source.data))return{type:`file`,mimeType:String(e.source.media_type??`text/plain`),data:e.source.data}}else if(j(e,`image`)&&M(e.source)&&`type`in e.source){if(e.source.type===`base64`&&N(e.source.media_type)&&N(e.source.data))return{type:`image`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&N(e.source.url))return{type:`image`,url:e.source.url};if(e.source.type===`file`&&N(e.source.file_id))return{type:`image`,fileId:e.source.file_id}}}function xn(e){function*t(){for(let t of e){let e=bn(t);e?yield e:yield t}}return Array.from(t())}function Sn(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(j(n,`text`)&&N(n.text)){let{text:e,citations:t,...r}=n;if(mn(t)&&t.length){let n=t.reduce((e,t)=>{let n=yn(t);return n?[...e,n]:e},[]);yield{...r,type:`text`,text:e,annotations:n};continue}else{yield{...r,type:`text`,text:e};continue}}else if(j(n,`thinking`)&&N(n.thinking)){let{thinking:e,signature:t,...r}=n;yield{...r,type:`reasoning`,reasoning:e,signature:t};continue}else if(j(n,`redacted_thinking`)){yield{type:`non_standard`,value:n};continue}else if(j(n,`tool_use`)&&N(n.name)&&N(n.id)){yield{type:`tool_call`,id:n.id,name:n.name,args:n.input};continue}else if(j(n,`input_json_delta`)){if(wn(e)&&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(j(n,`server_tool_use`)&&N(n.name)&&N(n.id)){let{name:e,id:t}=n;if(e===`web_search`){yield{id:t,type:`server_tool_call`,name:`web_search`,args:{query:vn(()=>{if(typeof n.input==`string`)return n.input;if(M(n.input)&&N(n.input.query))return n.input.query;if(N(n.partial_json)){let e=_n(n.partial_json);if(e?.query)return e.query}return``})}};continue}else if(n.name===`code_execution`){yield{id:t,type:`server_tool_call`,name:`code_execution`,args:{code:vn(()=>{if(typeof n.input==`string`)return n.input;if(M(n.input)&&N(n.input.code))return n.input.code;if(N(n.partial_json)){let e=_n(n.partial_json);if(e?.code)return e.code}return``})}};continue}}else if(j(n,`web_search_tool_result`)&&N(n.tool_use_id)&&mn(n.content)){let{content:e,tool_use_id:t}=n;yield{type:`server_tool_call_result`,name:`web_search`,toolCallId:t,status:`success`,output:{urls:e.reduce((e,t)=>j(t,`web_search_result`)?[...e,t.url]:e,[])}};continue}else if(j(n,`code_execution_tool_result`)&&N(n.tool_use_id)&&M(n.content)){yield{type:`server_tool_call_result`,name:`code_execution`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(j(n,`mcp_tool_use`)){yield{id:n.id,type:`server_tool_call`,name:`mcp_tool_use`,args:n.input};continue}else if(j(n,`mcp_tool_result`)&&N(n.tool_use_id)&&M(n.content)){yield{type:`server_tool_call_result`,name:`mcp_tool_use`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(j(n,`container_upload`)){yield{type:`server_tool_call`,name:`container_upload`,args:n.input};continue}else if(j(n,`search_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else if(j(n,`tool_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else{let e=bn(n);if(e){yield e;continue}}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Cn={translateContent:Sn,translateContentChunk:Sn};function wn(e){return typeof e?._getType==`function`&&typeof e.concat==`function`&&e._getType()===`ai`}function Tn(e){return Rt(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:zt(e)?{type:e.type,mimeType:e.mime_type??`application/octet-stream`,data:e.data,metadata:e.metadata}:Vt(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function En(e){return e.map(Tn)}function Dn(e){return!!(j(e,`image_url`)&&M(e.image_url)||j(e,`input_audio`)&&M(e.input_audio)||j(e,`file`)&&M(e.file))}function On(e){if(j(e,`image_url`)&&M(e.image_url)&&N(e.image_url.url)){let t=Wt({dataUrl:e.image_url.url});return t?{type:`image`,mimeType:t.mime_type,data:t.data}:{type:`image`,url:e.image_url.url}}else if(j(e,`input_audio`)&&M(e.input_audio)&&N(e.input_audio.data)&&N(e.input_audio.format))return{type:`audio`,data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};else if(j(e,`file`)&&M(e.file)&&N(e.file.data)){let t=Wt({dataUrl:e.file.data});if(t)return{type:`file`,data:t.data,mimeType:t.mime_type};if(N(e.file.file_id))return{type:`file`,fileId:e.file.file_id}}return e}function kn(e){let t=[];typeof e.content==`string`?t.push({type:`text`,text:e.content}):t.push(...jn(e.content));for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}function An(e){let t=[];typeof e.content==`string`?t.push({type:`text`,text:e.content}):t.push(...jn(e.content));for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}function jn(e){let t=[];for(let n of e)Dn(n)?t.push(On(n)):t.push(n);return t}function Mn(e){if(e.type===`url_citation`){let{url:t,title:n,start_index:r,end_index:i}=e;return{type:`citation`,url:t,title:n,startIndex:r,endIndex:i}}if(e.type===`file_citation`){let{file_id:t,filename:n,index:r}=e;return{type:`citation`,title:n,startIndex:r,endIndex:r,fileId:t}}return e}function Nn(e){function*t(){M(e.additional_kwargs?.reasoning)&&mn(e.additional_kwargs.reasoning.summary)&&(yield{type:`reasoning`,reasoning:e.additional_kwargs.reasoning.summary.reduce((e,t)=>M(t)&&N(t.text)?`${e}${t.text}`:e,``)});let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let e of t)if(j(e,`text`)){let{text:t,annotations:n,...r}=e;Array.isArray(n)?yield{...r,type:`text`,text:String(t),annotations:n.map(Mn)}:yield{...r,type:`text`,text:String(t)}}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)&&mn(e.additional_kwargs.tool_outputs))for(let t of e.additional_kwargs.tool_outputs){if(j(t,`web_search_call`)){yield{id:t.id,type:`server_tool_call`,name:`web_search`,args:{query:t.query}};continue}else if(j(t,`file_search_call`)){yield{id:t.id,type:`server_tool_call`,name:`file_search`,args:{query:t.query}};continue}else if(j(t,`computer_call`)){yield{type:`non_standard`,value:t};continue}else if(j(t,`code_interpreter_call`)){if(N(t.code)&&(yield{id:t.id,type:`server_tool_call`,name:`code_interpreter`,args:{code:t.code}}),mn(t.outputs)){let e=vn(()=>{if(t.status!==`in_progress`){if(t.status===`completed`)return 0;if(t.status===`incomplete`)return 127;if(t.status!==`interpreting`&&t.status===`failed`)return 1}});for(let n of t.outputs)if(j(n,`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(n.logs),stdout:[0,void 0].includes(e)?String(n.logs):void 0}};continue}}continue}else if(j(t,`mcp_call`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_call`,args:t.input};continue}else if(j(t,`mcp_list_tools`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_list_tools`,args:t.input};continue}else if(j(t,`mcp_approval_request`)){yield{type:`non_standard`,value:t};continue}else if(j(t,`image_generation_call`)){N(t.result)&&(yield{type:`image`,mimeType:`image/png`,data:t.result,id:N(t.id)?t.id:void 0,metadata:{status:N(t.status)?t.status:void 0}}),yield{type:`non_standard`,value:t};continue}M(t)&&(yield{type:`non_standard`,value:t})}}return Array.from(t())}function Pn(e){function*t(){yield*Nn(e);for(let t of e.tool_call_chunks??[])yield{type:`tool_call_chunk`,id:t.id,name:t.name,args:t.args}}return Array.from(t())}var Fn={translateContent:e=>typeof e.content==`string`?kn(e):Nn(e),translateContentChunk:e=>typeof e.content==`string`?An(e):Pn(e)};function In(e,t=`pretty`){return t===`pretty`?Ln(e):JSON.stringify(e)}function Ln(e){let t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),i=`=`.repeat(r),a=n.length%2==0?i:`${i}=`;if(t.push(`${i}${n}${a}`),e.type===`ai`){let n=e;if(n.tool_calls&&n.tool_calls.length>0){t.push(`Tool Calls:`);for(let e of n.tool_calls){t.push(` ${e.name} (${e.id})`),t.push(` Call ID: ${e.id}`),t.push(` Args:`);for(let[n,r]of Object.entries(e.args))t.push(` ${n}: ${typeof r==`object`?JSON.stringify(r):r}`)}}}if(e.type===`tool`){let n=e;n.name&&t.push(`Name: ${n.name}`)}return typeof e.content==`string`&&e.content.trim()&&(t.length>1&&t.push(``),t.push(e.content)),t.join(`
2
+ `)}var Rn=Symbol.for(`langchain.message`);function zn(e,t){return typeof e==`string`?e===``?t:typeof t==`string`?e+t:Array.isArray(t)&&t.length===0?e:Array.isArray(t)&&t.some(e=>Lt(e))?[{type:`text`,source_type:`text`,text:e},...t]:[{type:`text`,text:e},...t]:Array.isArray(t)?Gn(e,t)??[...e,...t]:t===``?e:Array.isArray(e)&&e.some(e=>Lt(e))?[...e,{type:`file`,source_type:`text`,text:t}]:[...e,{type:`text`,text:t}]}function Bn(e,t){return e===`error`||t===`error`?`error`:`success`}function Vn(e,t){function n(e,r){if(typeof e!=`object`||!e||e===void 0)return e;if(r>=t)return Array.isArray(e)?`[Array]`:`[Object]`;if(Array.isArray(e))return e.map(e=>n(e,r+1));let i={};for(let t of Object.keys(e))i[t]=n(e[t],r+1);return i}return JSON.stringify(n(e,0),null,2)}var Hn=class extends pn{lc_namespace=[`langchain_core`,`messages`];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:`additional_kwargs`,response_metadata:`response_metadata`}}[Rn]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){let t=typeof e==`string`||Array.isArray(e)?{content:e}:e;t.additional_kwargs||={},t.response_metadata||={},super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:`v1`,...t.response_metadata}):t.content===void 0?(this.content=[],this.response_metadata=t.response_metadata):(this.content=t.content??[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return typeof this.content==`string`?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e==`string`?e:e.type===`text`?e.text:``).join(``):``}get contentBlocks(){let e=typeof this.content==`string`?[{type:`text`,text:this.content}]:this.content;return[En,jn,xn].reduce((e,t)=>t(e),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return`BaseMessage`}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e==`object`&&!!e&&Rn in e&&e[Rn]===!0&&Kt(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for(`nodejs.util.inspect.custom`)](e){if(e===null)return this;let t=Vn(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e=`pretty`){return In(this,e)}};function Un(e){return Array.isArray(e)&&e.every(e=>typeof e.index==`number`)}var Wn=[`index`,`created`,`timestamp`];function P(e,t,n){let r=n?.ignoreKeys??Wn;if(e==null&&t==null)return;if(e==null||t==null)return e??t;let i={...e};for(let[e,a]of Object.entries(t))if(i[e]==null)i[e]=a;else if(a==null)continue;else if(typeof i[e]!=typeof a||Array.isArray(i[e])!==Array.isArray(a))throw Error(`field[${e}] already exists in the message chunk, but with a different type.`);else if(typeof i[e]==`string`){if(e===`type`)continue;if([`id`,`name`,`output_version`,`model_provider`].includes(e))a&&(i[e]=a);else if(r.includes(e))continue;else i[e]+=a}else if(typeof i[e]==`number`){if(r.includes(e))continue;i[e]=i[e]+a}else if(typeof i[e]==`object`&&!Array.isArray(i[e]))i[e]=P(i[e],a,n);else if(Array.isArray(i[e]))i[e]=Gn(i[e],a,n);else if(i[e]===a)continue;else console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`);return i}function Gn(e,t,n){if(!(e==null&&t==null)){if(e==null||t==null)return e||t;{let r=[...e];for(let e of t)if(typeof e==`object`&&e&&`index`in e&&typeof e.index==`number`){let t=r.findIndex(t=>{let n=typeof t==`object`,r=`index`in t&&t.index===e.index,i=`id`in t&&`id`in e&&t?.id===e?.id,a=!(`id`in t)||!t?.id||!(`id`in e)||!e?.id;return n&&r&&(i||a)});t!==-1&&typeof r[t]==`object`&&r[t]!==null?r[t]=P(r[t],e,n):r.push(e)}else if(typeof e==`object`&&e&&`text`in e&&e.text===``)continue;else r.push(e);return r}}}function Kn(e,t,n){if(!(e==null&&t==null)){if(e==null||t==null)return e??t;if(typeof e!=typeof t)throw Error(`Cannot merge objects of different types.\nLeft ${typeof e}\nRight ${typeof t}`);if(typeof e==`string`&&typeof t==`string`)return e+t;if(Array.isArray(e)&&Array.isArray(t))return Gn(e,t,n);if(typeof e==`object`&&typeof t==`object`)return P(e,t,n);if(e===t)return e;throw Error(`Can not merge objects of different types.\nLeft ${e}\nRight ${t}`)}}var qn=class e extends Hn{static isInstance(t){if(!super.isInstance(t))return!1;let n=Object.getPrototypeOf(t);for(;n!==null;){if(n===e.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}};function Jn(e){return typeof e.role==`string`}function Yn(e){return typeof e?._getType==`function`}function Xn(e){return qn.isInstance(e)}function Zn(e,t){return P(e,t)??{}}function Qn(e,t){let n={};return(e?.audio!==void 0||t?.audio!==void 0)&&(n.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(n.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(n.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(n.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(n.text=(e?.text??0)+(t?.text??0)),n}function $n(e,t){let n={...Qn(e,t)};return(e?.cache_read!==void 0||t?.cache_read!==void 0)&&(n.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),(e?.cache_creation!==void 0||t?.cache_creation!==void 0)&&(n.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),n}function er(e,t){let n={...Qn(e,t)};return(e?.reasoning!==void 0||t?.reasoning!==void 0)&&(n.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),n}function tr(e,t){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:$n(e?.input_token_details,t?.input_token_details),output_token_details:er(e?.output_token_details,t?.output_token_details)}}var nr={};A(nr,{ToolMessage:()=>ir,ToolMessageChunk:()=>ar,defaultToolCallParser:()=>or,isDirectToolOutput:()=>rr,isToolMessage:()=>sr,isToolMessageChunk:()=>cr});function rr(e){return typeof e==`object`&&!!e&&`lc_direct_tool_output`in e&&e.lc_direct_tool_output===!0}var ir=class extends Hn{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,n){let r=typeof e==`string`||Array.isArray(e)?{content:e,name:n,tool_call_id:t}:e;super(r),this.tool_call_id=r.tool_call_id,this.artifact=r.artifact,this.status=r.status,this.metadata=r.metadata}static isInstance(e){return super.isInstance(e)&&e.type===`tool`}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},ar=class extends qn{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){let t=this.constructor;return new t({content:zn(this.content,e.content),additional_kwargs:P(this.additional_kwargs,e.additional_kwargs),response_metadata:P(this.response_metadata,e.response_metadata),artifact:Kn(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:Bn(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function or(e){let t=[],n=[];for(let r of e)if(r.function){let e=r.function.name;try{let n=JSON.parse(r.function.arguments);t.push({name:e||``,args:n||{},id:r.id})}catch{n.push({name:e,args:r.function.arguments,id:r.id,error:`Malformed args.`})}}else continue;return[t,n]}function sr(e){return typeof e==`object`&&!!e&&`getType`in e&&typeof e.getType==`function`&&e.getType()===`tool`}function cr(e){return e._getType()===`tool`}var lr=class e extends Hn{static lc_name(){return`ChatMessage`}type=`generic`;role;static _chatMessageClass(){return e}constructor(e,t){(typeof e==`string`||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&e.type===`generic`}get _printableFields(){return{...super._printableFields,role:this.role}}},ur=class extends qn{static lc_name(){return`ChatMessageChunk`}type=`generic`;role;constructor(e,t){(typeof e==`string`||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){let t=this.constructor;return new t({content:zn(this.content,e.content),additional_kwargs:P(this.additional_kwargs,e.additional_kwargs),response_metadata:P(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type===`generic`}get _printableFields(){return{...super._printableFields,role:this.role}}};function dr(e){return e._getType()===`generic`}function fr(e){return e._getType()===`generic`}var pr=class extends Hn{static lc_name(){return`FunctionMessage`}type=`function`;name;constructor(e){super(e),this.name=e.name}},mr=class extends qn{static lc_name(){return`FunctionMessageChunk`}type=`function`;concat(e){let t=this.constructor;return new t({content:zn(this.content,e.content),additional_kwargs:P(this.additional_kwargs,e.additional_kwargs),response_metadata:P(this.response_metadata,e.response_metadata),name:this.name??``,id:this.id??e.id})}};function hr(e){return e._getType()===`function`}function gr(e){return e._getType()===`function`}var _r=class extends Hn{static lc_name(){return`HumanMessage`}type=`human`;constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type===`human`}},vr=class extends qn{static lc_name(){return`HumanMessageChunk`}type=`human`;constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:zn(this.content,e.content),additional_kwargs:P(this.additional_kwargs,e.additional_kwargs),response_metadata:P(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type===`human`}};function yr(e){return e.getType()===`human`}function br(e){return e.getType()===`human`}var xr=class extends Hn{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)&&e.type===`remove`}},Sr=class e extends Hn{static lc_name(){return`SystemMessage`}type=`system`;constructor(e){super(e)}concat(t){if(typeof t==`string`)return new e({...this,content:zn(this.content,t)});if(e.isInstance(t))return new e({...this,additional_kwargs:{...this.additional_kwargs,...t.additional_kwargs},response_metadata:{...this.response_metadata,...t.response_metadata},content:zn(this.content,t.content)});throw Error(`Unexpected chunk type for system message`)}static isInstance(e){return super.isInstance(e)&&e.type===`system`}},Cr=class extends qn{static lc_name(){return`SystemMessageChunk`}type=`system`;constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:zn(this.content,e.content),additional_kwargs:P(this.additional_kwargs,e.additional_kwargs),response_metadata:P(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type===`system`}};function wr(e){return e._getType()===`system`}function Tr(e){return e._getType()===`system`}var Er={};A(Er,{ModelAbortError:()=>Or,addLangChainErrorFields:()=>Dr});function Dr(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}var Or=class e extends Error{name=`ModelAbortError`;lc_error_code=`MODEL_ABORTED`;partialOutput;constructor(t,n){super(t),this.partialOutput=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}static isInstance(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`ModelAbortError`&&`lc_error_code`in e&&e.lc_error_code===`MODEL_ABORTED`}};function kr(e){return!!(e&&typeof e==`object`&&`type`in e&&e.type===`tool_call`)}function Ar(e){return!!(e&&typeof e==`object`&&`toolCall`in e&&e.toolCall!=null&&typeof e.toolCall==`object`&&`id`in e.toolCall&&typeof e.toolCall.id==`string`)}var jr=class extends Error{output;constructor(e,t){super(e),this.output=t}};function Mr(e,t=Pr){e=e.trim();let n=e.indexOf("```");if(n===-1)return t(e);let r=e.substring(n+3);r.startsWith(`json
3
+ `)?r=r.substring(5):r.startsWith(`json`)?r=r.substring(4):r.startsWith(`
4
+ `)&&(r=r.substring(1));let i=r.indexOf("```"),a=r;return i!==-1&&(a=r.substring(0,i)),t(a.trim())}function Nr(e){try{return JSON.parse(e)}catch{}let t=e.trim();if(t.length===0)throw Error(`Unexpected end of JSON input`);let n=0;function r(){for(;n<t.length&&/\s/.test(t[n]);)n+=1}function i(){if(t[n]!==`"`)throw Error(`Expected '"' at position ${n}, got '${t[n]}'`);n+=1;let e=``,r=!1;for(;n<t.length;){let i=t[n];if(r){if(i===`n`)e+=`
5
+ `;else if(i===`t`)e+=` `;else if(i===`r`)e+=`\r`;else if(i===`\\`)e+=`\\`;else if(i===`"`)e+=`"`;else if(i===`b`)e+=`\b`;else if(i===`f`)e+=`\f`;else if(i===`/`)e+=`/`;else if(i===`u`){let r=t.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(r))r.length===4?e+=String.fromCharCode(Number.parseInt(r,16)):e+=`u${r}`,n+=r.length;else throw Error(`Invalid unicode escape sequence '\\u${r}' at position ${n}`)}else throw Error(`Invalid escape sequence '\\${i}' at position ${n}`);r=!1}else if(i===`\\`)r=!0;else if(i===`"`)return n+=1,e;else e+=i;n+=1}return r&&(e+=`\\`),e}function a(){let e=n,r=``;if(t[n]===`-`&&(r+=`-`,n+=1),n<t.length&&t[n]===`0`&&(r+=`0`,n+=1,t[n]>=`0`&&t[n]<=`9`))throw Error(`Invalid number at position ${e}`);if(n<t.length&&t[n]>=`1`&&t[n]<=`9`)for(;n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(n<t.length&&t[n]===`.`)for(r+=`.`,n+=1;n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(n<t.length&&(t[n]===`e`||t[n]===`E`))for(r+=t[n],n+=1,n<t.length&&(t[n]===`+`||t[n]===`-`)&&(r+=t[n],n+=1);n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(r===`-`)return-0;let i=Number.parseFloat(r);if(Number.isNaN(i))throw n=e,Error(`Invalid number '${r}' at position ${e}`);return i}function o(){if(r(),n>=t.length)throw Error(`Unexpected end of input at position ${n}`);let e=t[n];if(e===`{`)return c();if(e===`[`)return s();if(e===`"`)return i();if(`null`.startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),null;if(`true`.startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),!0;if(`false`.startsWith(t.substring(n,n+5)))return n+=Math.min(5,t.length-n),!1;if(e===`-`||e>=`0`&&e<=`9`)return a();throw Error(`Unexpected character '${e}' at position ${n}`)}function s(){if(t[n]!==`[`)throw Error(`Expected '[' at position ${n}, got '${t[n]}'`);let e=[];if(n+=1,r(),n>=t.length)return e;if(t[n]===`]`)return n+=1,e;for(;n<t.length;){if(r(),n>=t.length||(e.push(o()),r(),n>=t.length))return e;if(t[n]===`]`)return n+=1,e;if(t[n]===`,`){n+=1;continue}throw Error(`Expected ',' or ']' at position ${n}, got '${t[n]}'`)}return e}function c(){if(t[n]!==`{`)throw Error(`Expected '{' at position ${n}, got '${t[n]}'`);let e={};if(n+=1,r(),n>=t.length)return e;if(t[n]===`}`)return n+=1,e;for(;n<t.length;){if(r(),n>=t.length)return e;let a=i();if(r(),n>=t.length)return e;if(t[n]!==`:`)throw Error(`Expected ':' at position ${n}, got '${t[n]}'`);if(n+=1,r(),n>=t.length||(e[a]=o(),r(),n>=t.length))return e;if(t[n]===`}`)return n+=1,e;if(t[n]===`,`){n+=1;continue}throw Error(`Expected ',' or '}' at position ${n}, got '${t[n]}'`)}return e}let l=o();if(r(),n<t.length)throw Error(`Unexpected character '${t[n]}' at position ${n}`);return l}function Pr(e){try{return e===void 0?null:Nr(e)}catch{return null}}function Fr(e){switch(e){case`csv`:return`text/csv`;case`doc`:return`application/vnd.openxmlformats-officedocument.wordprocessingml.document`;case`docx`:return`application/vnd.openxmlformats-officedocument.wordprocessingml.document`;case`html`:return`text/html`;case`md`:return`text/markdown`;case`pdf`:return`application/pdf`;case`txt`:return`text/plain`;case`xls`:return`application/vnd.ms-excel`;case`xlsx`:return`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`;case`gif`:return`image/gif`;case`jpeg`:return`image/jpeg`;case`jpg`:return`image/jpeg`;case`png`:return`image/png`;case`webp`:return`image/webp`;case`flv`:return`video/flv`;case`mkv`:return`video/mkv`;case`mov`:return`video/mov`;case`mp4`:return`video/mp4`;case`mpeg`:return`video/mpeg`;case`mpg`:return`video/mpg`;case`three_gp`:return`video/three_gp`;case`webm`:return`video/webm`;case`wmv`:return`video/wmv`;default:return`application/octet-stream`}}function Ir(e){if(M(e.document)&&M(e.document.source)){let t=Fr(M(e.document)&&N(e.document.format)?e.document.format:``);if(M(e.document.source)){if(M(e.document.source.s3Location)&&N(e.document.source.s3Location.uri))return{type:`file`,mimeType:t,fileId:e.document.source.s3Location.uri};if(gn(e.document.source.bytes))return{type:`file`,mimeType:t,data:e.document.source.bytes};if(N(e.document.source.text))return{type:`file`,mimeType:t,data:Buffer.from(e.document.source.text).toString(`base64`)};if(mn(e.document.source.content))return{type:`file`,mimeType:t,data:e.document.source.content.reduce((e,t)=>M(t)&&N(t.text)?e+t.text:e,``)}}}return{type:`non_standard`,value:e}}function Lr(e){if(j(e,`image`)&&M(e.image)){let t=Fr(M(e.image)&&N(e.image.format)?e.image.format:``);if(M(e.image.source)){if(M(e.image.source.s3Location)&&N(e.image.source.s3Location.uri))return{type:`image`,mimeType:t,fileId:e.image.source.s3Location.uri};if(gn(e.image.source.bytes))return{type:`image`,mimeType:t,data:e.image.source.bytes}}}return{type:`non_standard`,value:e}}function Rr(e){if(j(e,`video`)&&M(e.video)){let t=Fr(M(e.video)&&N(e.video.format)?e.video.format:``);if(M(e.video.source)){if(M(e.video.source.s3Location)&&N(e.video.source.s3Location.uri))return{type:`video`,mimeType:t,fileId:e.video.source.s3Location.uri};if(gn(e.video.source.bytes))return{type:`video`,mimeType:t,data:e.video.source.bytes}}}return{type:`non_standard`,value:e}}function zr(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let e of t){if(j(e,`cache_point`)){yield{type:`non_standard`,value:e};continue}else if(j(e,`citations_content`)&&M(e.citationsContent)){yield{type:`text`,text:mn(e.citationsContent.content)?e.citationsContent.content.reduce((e,t)=>M(t)&&N(t.text)?e+t.text:e,``):``,annotations:mn(e.citationsContent.citations)?e.citationsContent.citations.reduce((e,t)=>{if(M(t)){let n=mn(t.sourceContent)?t.sourceContent.reduce((e,t)=>M(t)&&N(t.text)?e+t.text:e,``):``,r=vn(()=>{if(M(t.location)){let e=t.location.documentChar||t.location.documentPage||t.location.documentChunk;if(M(e))return{source:hn(e.documentIndex)?e.documentIndex.toString():void 0,startIndex:hn(e.start)?e.start:void 0,endIndex:hn(e.end)?e.end:void 0}}return{}});e.push({type:`citation`,citedText:n,...r})}return e},[]):[]};continue}else if(j(e,`document`)&&M(e.document)){yield Ir(e);continue}else if(j(e,`guard_content`)){yield{type:`non_standard`,value:e};continue}else if(j(e,`image`)&&M(e.image)){yield Lr(e);continue}else if(j(e,`reasoning_content`)&&N(e.reasoningText)){yield{type:`reasoning`,reasoning:e.reasoningText};continue}else if(j(e,`text`)&&N(e.text)){yield{type:`text`,text:e.text};continue}else if(j(e,`tool_result`)){yield{type:`non_standard`,value:e};continue}else if(j(e,`tool_call`))continue;else if(j(e,`video`)&&M(e.video)){yield Rr(e);continue}yield{type:`non_standard`,value:e}}}return Array.from(t())}var Br={translateContent:zr,translateContentChunk:zr};function Vr(e){let t=[],n=e.additional_kwargs?.reasoning_content;if(N(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`)e.content.length>0&&t.push({type:`text`,text:e.content});else for(let n of e.content)typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&N(n.text)&&t.push({type:`text`,text:n.text});for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var Hr={translateContent:Vr,translateContentChunk:Vr};function Ur(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(j(n,`text`)&&N(n.text)){yield{type:`text`,text:n.text};continue}else if(j(n,`thinking`)&&N(n.thinking)){yield{type:`reasoning`,reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(j(n,`inlineData`)&&M(n.inlineData)&&N(n.inlineData.mimeType)&&N(n.inlineData.data)){yield{type:`file`,mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(j(n,`functionCall`)&&M(n.functionCall)&&N(n.functionCall.name)&&M(n.functionCall.args)){yield{type:`tool_call`,id:e.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(j(n,`functionResponse`)){yield{type:`non_standard`,value:n};continue}else if(j(n,`fileData`)&&M(n.fileData)&&N(n.fileData.mimeType)&&N(n.fileData.fileUri)){yield{type:`file`,mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(j(n,`executableCode`)){yield{type:`non_standard`,value:n};continue}else if(j(n,`codeExecutionResult`)){yield{type:`non_standard`,value:n};continue}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Wr={translateContent:Ur,translateContentChunk:Ur};function Gr(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(j(n,`reasoning`)&&N(n.reasoning)){let r=vn(()=>{let r=t.indexOf(n);if(mn(e.additional_kwargs?.signatures)&&r>=0)return e.additional_kwargs.signatures.at(r)});N(r)?yield{type:`reasoning`,reasoning:n.reasoning,signature:r}:yield{type:`reasoning`,reasoning:n.reasoning};continue}else if(j(n,`thinking`)&&N(n.thinking)){yield{type:`reasoning`,reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(j(n,`text`)&&N(n.text)){yield{type:`text`,text:n.text};continue}else if(j(n,`image_url`)){if(N(n.image_url))if(n.image_url.startsWith(`data:`)){let e=n.image_url.match(/^data:([^;]+);base64,(.+)$/);e?yield{type:`image`,data:e[2],mimeType:e[1]}:yield{type:`image`,url:n.image_url}}else yield{type:`image`,url:n.image_url};continue}else if(j(n,`media`)&&N(n.mimeType)&&N(n.data)){yield{type:`file`,mimeType:n.mimeType,data:n.data};continue}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Kr={translateContent:Gr,translateContentChunk:Gr};function qr(e){let t=[],n=e.additional_kwargs?.reasoning;if(N(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`){let n=e.content,r=n.match(/<think>([\s\S]*?)<\/think>/);if(r){let e=r[1].trim();e.length>0&&t.push({type:`reasoning`,reasoning:e}),n=n.replace(/<think>[\s\S]*?<\/think>/,``).trim()}n.length>0&&t.push({type:`text`,text:n})}else for(let n of e.content)if(typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&N(n.text)){let e=n.text,r=e.match(/<think>([\s\S]*?)<\/think>/);if(r){let n=r[1].trim();n.length>0&&t.push({type:`reasoning`,reasoning:n}),e=e.replace(/<think>[\s\S]*?<\/think>/,``).trim()}e.length>0&&t.push({type:`text`,text:e})}for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var Jr={translateContent:qr,translateContentChunk:qr};function Yr(e){let t=[],n=e.additional_kwargs?.reasoning_content;if(N(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`)e.content.length>0&&t.push({type:`text`,text:e.content});else for(let n of e.content)typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&N(n.text)&&t.push({type:`text`,text:n.text});for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var Xr={translateContent:Yr,translateContentChunk:Yr};function Zr(e){let t=[];if(M(e.additional_kwargs?.reasoning)){let n=e.additional_kwargs.reasoning;if(mn(n.summary)){let e=n.summary.reduce((e,t)=>M(t)&&N(t.text)?`${e}${t.text}`:e,``);e.length>0&&t.push({type:`reasoning`,reasoning:e})}}let n=e.additional_kwargs?.reasoning_content;if(N(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`)e.content.length>0&&t.push({type:`text`,text:e.content});else for(let n of e.content)typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&N(n.text)&&t.push({type:`text`,text:n.text});for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}globalThis.lc_block_translators_registry??=new Map([[`anthropic`,Cn],[`bedrock-converse`,Br],[`deepseek`,Hr],[`google-genai`,Wr],[`google-vertexai`,Kr],[`groq`,Jr],[`ollama`,Xr],[`openai`,Fn],[`xai`,{translateContent:Zr,translateContentChunk:Zr}]]);function Qr(e){return globalThis.lc_block_translators_registry.get(e)}var $r=class extends Hn{type=`ai`;tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:`tool_calls`,invalid_tool_calls:`invalid_tool_calls`}}constructor(e){let t;if(typeof e==`string`||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;let n=t.additional_kwargs?.tool_calls,r=t.tool_calls;n!=null&&n.length>0&&(r===void 0||r.length===0)&&console.warn([`New LangChain packages are available that more efficiently handle`,`tool calling.
6
+
7
+ Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(` `));try{if(n!=null&&r===void 0){let[e,r]=or(n);t.tool_calls=e??[],t.invalid_tool_calls=r??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(t.response_metadata!==void 0&&`output_version`in t.response_metadata&&t.response_metadata.output_version===`v1`&&(t.contentBlocks=t.content,t.content=void 0),t.contentBlocks!==void 0){t.tool_calls&&t.contentBlocks.push(...t.tool_calls.map(e=>({type:`tool_call`,id:e.id,name:e.name,args:e.args})));let e=t.contentBlocks.filter(e=>e.type===`tool_call`).filter(e=>!t.tool_calls?.some(t=>t.id===e.id&&t.name===e.name));e.length>0&&(t.tool_calls=e.map(e=>({type:`tool_call`,id:e.id,name:e.name,args:e.args})))}}super(t),typeof t!=`string`&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}static lc_name(){return`AIMessage`}get contentBlocks(){if(this.response_metadata&&`output_version`in this.response_metadata&&this.response_metadata.output_version===`v1`)return this.content;if(this.response_metadata&&`model_provider`in this.response_metadata&&typeof this.response_metadata.model_provider==`string`){let e=Qr(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)&&e.type===`ai`}};function ei(e){return e._getType()===`ai`}function ti(e){return e._getType()===`ai`}var ni=class extends qn{type=`ai`;tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if(typeof e==`string`||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata===void 0?void 0:e.usage_metadata};else{let n=mi(e.tool_call_chunks??[]);t={...e,tool_call_chunks:n.tool_call_chunks,tool_calls:n.tool_calls,invalid_tool_calls:n.invalid_tool_calls,usage_metadata:e.usage_metadata===void 0?void 0:e.usage_metadata}}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`}}static lc_name(){return`AIMessageChunk`}get contentBlocks(){if(this.response_metadata&&`output_version`in this.response_metadata&&this.response_metadata.output_version===`v1`)return this.content;if(this.response_metadata&&`model_provider`in this.response_metadata&&typeof this.response_metadata.model_provider==`string`){let e=Qr(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!=`string`){let t=this.content.filter(e=>e.type===`tool_call`).map(e=>e.id);for(let n of this.tool_calls)n.id&&!t.includes(n.id)&&e.push({...n,type:`tool_call`,id:n.id,name:n.name,args:n.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let t={content:zn(this.content,e.content),additional_kwargs:P(this.additional_kwargs,e.additional_kwargs),response_metadata:Zn(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){let n=Gn(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(t.tool_call_chunks=n)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(t.usage_metadata=tr(this.usage_metadata,e.usage_metadata));let n=this.constructor;return new n(t)}static isInstance(e){return super.isInstance(e)&&e.type===`ai`}},ri=e=>e();function ii(e){return kr(e)?e:typeof e.id==`string`&&e.type===`function`&&typeof e.function==`object`&&e.function!==null&&`arguments`in e.function&&typeof e.function.arguments==`string`&&`name`in e.function&&typeof e.function.name==`string`?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:`tool_call`}:e}function ai(e){return typeof e==`object`&&!!e&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs==`object`}function oi(e){let t,n;if(ai(e)){let r=e.id.at(-1);t=r===`HumanMessage`||r===`HumanMessageChunk`?`user`:r===`AIMessage`||r===`AIMessageChunk`?`assistant`:r===`SystemMessage`||r===`SystemMessageChunk`?`system`:r===`FunctionMessage`||r===`FunctionMessageChunk`?`function`:r===`ToolMessage`||r===`ToolMessageChunk`?`tool`:`unknown`,n=e.kwargs}else{let{type:r,...i}=e;t=r,n=i}if(t===`human`||t===`user`)return new _r(n);if(t===`ai`||t===`assistant`){let{tool_calls:e,...t}=n;if(!Array.isArray(e))return new $r(n);let r=e.map(ii);return new $r({...t,tool_calls:r})}else if(t===`system`)return new Sr(n);else if(t===`developer`)return new Sr({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:`developer`}});else if(t===`tool`&&`tool_call_id`in n)return new ir({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});else if(t===`remove`&&`id`in n&&typeof n.id==`string`)return new xr({...n,id:n.id});else throw Dr(Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(e,null,2)}`),`MESSAGE_COERCION_FAILURE`)}function si(e){if(typeof e==`string`)return new _r(e);if(Yn(e))return e;if(Array.isArray(e)){let[t,n]=e;return oi({type:t,content:n})}else if(Jn(e)){let{role:t,...n}=e;return oi({...n,type:t})}else return oi(e)}function ci(e,t=`Human`,n=`AI`){let r=[];for(let i of e){let e;if(i.type===`human`)e=t;else if(i.type===`ai`)e=n;else if(i.type===`system`)e=`System`;else if(i.type===`tool`)e=`Tool`;else if(i.type===`generic`)e=i.role;else throw Error(`Got unsupported message type: ${i.type}`);let a=i.name?`${i.name}, `:``,o=i.text,s=`${e}: ${a}${o}`;if(i.type===`ai`){let e=i;e.tool_calls&&e.tool_calls.length>0?s+=JSON.stringify(e.tool_calls):e.additional_kwargs&&`function_call`in e.additional_kwargs&&(s+=JSON.stringify(e.additional_kwargs.function_call))}r.push(s)}return r.join(`
8
+ `)}function li(e){if(e.data!==void 0)return e;{let t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function ui(e){let t=li(e);switch(t.type){case`human`:return new _r(t.data);case`ai`:return new $r(t.data);case`system`:return new Sr(t.data);case`function`:if(t.data.name===void 0)throw Error(`Name must be defined for function messages`);return new pr(t.data);case`tool`:if(t.data.tool_call_id===void 0)throw Error(`Tool call ID must be defined for tool messages`);return new ir(t.data);case`generic`:if(t.data.role===void 0)throw Error(`Role must be defined for chat messages`);return new lr(t.data);default:throw Error(`Got unexpected type: ${t.type}`)}}function di(e){return e.map(ui)}function fi(e){return e.map(e=>e.toDict())}function pi(e){let t=e._getType();if(t===`human`)return new vr({...e});if(t===`ai`){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 ni({...t})}else if(t===`system`)return new Cr({...e});else if(t===`function`)return new mr({...e});else if(lr.isInstance(e))return new ur({...e});else throw Error(`Unknown message type.`)}function mi(e){let t=e.reduce((e,t)=>{let n=e.findIndex(([e])=>`id`in t&&t.id&&`index`in t&&t.index!==void 0?t.id===e.id&&t.index===e.index:`id`in t&&t.id?t.id===e.id:`index`in t&&t.index!==void 0?t.index===e.index:!1);return n===-1?e.push([t]):e[n].push(t),e},[]),n=[],r=[];for(let e of t){let t=null,i=e[0]?.name??``,a=e.map(e=>e.args||``).join(``).trim(),o=a.length?a:`{}`,s=e[0]?.id;try{if(t=Pr(o),!s||typeof t!=`object`||!t||Array.isArray(t))throw Error(`Malformed tool call chunk args.`);n.push({name:i,args:t,id:s,type:`tool_call`})}catch{r.push({name:i,args:o,id:s,error:`Malformed args.`,type:`invalid_tool_call`})}}return{tool_call_chunks:e,tool_calls:n,invalid_tool_calls:r}}var hi=Symbol.for(`ls:tracing_async_local_storage`),gi=Symbol.for(`lc:context_variables`),_i=e=>{globalThis[hi]=e},vi=()=>globalThis[hi],yi={};A(yi,{getEnv:()=>Ti,getEnvironmentVariable:()=>Oi,getRuntimeEnvironment:()=>Di,isBrowser:()=>bi,isDeno:()=>Ci,isJsDom:()=>Si,isNode:()=>wi,isWebWorker:()=>xi});var bi=()=>typeof window<`u`&&window.document!==void 0,xi=()=>typeof globalThis==`object`&&globalThis.constructor&&globalThis.constructor.name===`DedicatedWorkerGlobalScope`,Si=()=>typeof window<`u`&&window.name===`nodejs`||typeof navigator<`u`&&navigator.userAgent.includes(`jsdom`),Ci=()=>typeof Deno<`u`,wi=()=>typeof process<`u`&&process.versions!==void 0&&process.versions.node!==void 0&&!Ci(),Ti=()=>{let e;return e=bi()?`browser`:wi()?`node`:xi()?`webworker`:Si()?`jsdom`:Ci()?`deno`:`other`,e},Ei;function Di(){return Ei===void 0&&(Ei={library:`langchain-js`,runtime:Ti()}),Ei}function Oi(e){try{return typeof process<`u`?{}?.[e]:Ci()?Deno?.env.get(e):void 0}catch{return}}var ki=/^(?:[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 Ai(e){return typeof e==`string`&&ki.test(e)}function ji(e){if(!Ai(e))throw TypeError(`Invalid UUID`);var t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=t&255,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=t&255,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=t&255,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=t&255,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=t&255,n}for(var F=[],Mi=0;Mi<256;++Mi)F.push((Mi+256).toString(16).slice(1));function Ni(e,t=0){return(F[e[t+0]]+F[e[t+1]]+F[e[t+2]]+F[e[t+3]]+`-`+F[e[t+4]]+F[e[t+5]]+`-`+F[e[t+6]]+F[e[t+7]]+`-`+F[e[t+8]]+F[e[t+9]]+`-`+F[e[t+10]]+F[e[t+11]]+F[e[t+12]]+F[e[t+13]]+F[e[t+14]]+F[e[t+15]]).toLowerCase()}var Pi,Fi=new Uint8Array(16);function Ii(){if(!Pi&&(Pi=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Pi))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return Pi(Fi)}function Li(e){e=unescape(encodeURIComponent(e));for(var t=[],n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t}var Ri=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,zi=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function Bi(e,t,n){function r(e,r,i,a){if(typeof e==`string`&&(e=Li(e)),typeof r==`string`&&(r=ji(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);var o=new Uint8Array(16+e.length);if(o.set(r),o.set(e,r.length),o=n(o),o[6]=o[6]&15|t,o[8]=o[8]&63|128,i){a||=0;for(var s=0;s<16;++s)i[a+s]=o[s];return i}return Ni(o)}try{r.name=e}catch{}return r.DNS=Ri,r.URL=zi,r}var Vi={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Hi(e,t,n){if(Vi.randomUUID&&!t&&!e)return Vi.randomUUID();e||={};var r=e.random||(e.rng||Ii)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n||=0;for(var i=0;i<16;++i)t[n+i]=r[i];return t}return Ni(r)}function Ui(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:return t^n^r;case 2:return t&n^t&r^n&r;case 3:return t^n^r}}function Wi(e,t){return e<<t|e>>>32-t}function Gi(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof e==`string`){var r=unescape(encodeURIComponent(e));e=[];for(var i=0;i<r.length;++i)e.push(r.charCodeAt(i))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);for(var a=e.length/4+2,o=Math.ceil(a/16),s=Array(o),c=0;c<o;++c){for(var l=new Uint32Array(16),u=0;u<16;++u)l[u]=e[c*64+u*4]<<24|e[c*64+u*4+1]<<16|e[c*64+u*4+2]<<8|e[c*64+u*4+3];s[c]=l}s[o-1][14]=(e.length-1)*8/2**32,s[o-1][14]=Math.floor(s[o-1][14]),s[o-1][15]=(e.length-1)*8&4294967295;for(var d=0;d<o;++d){for(var f=new Uint32Array(80),p=0;p<16;++p)f[p]=s[d][p];for(var m=16;m<80;++m)f[m]=Wi(f[m-3]^f[m-8]^f[m-14]^f[m-16],1);for(var h=n[0],g=n[1],_=n[2],v=n[3],y=n[4],b=0;b<80;++b){var ee=Math.floor(b/20),te=Wi(h,5)+Ui(ee,g,_,v)+y+t[ee]+f[b]>>>0;y=v,v=_,_=Wi(g,30)>>>0,g=h,h=te}n[0]=n[0]+h>>>0,n[1]=n[1]+g>>>0,n[2]=n[2]+_>>>0,n[3]=n[3]+v>>>0,n[4]=n[4]+y>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,n[0]&255,n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,n[1]&255,n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,n[2]&255,n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,n[3]&255,n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,n[4]&255]}var Ki=Bi(`v5`,80,Gi),qi=null,Ji=null,Yi=0;function Xi(e,t,n){e||={};var r=t&&n||0,i=t||new Uint8Array(16),a=e.random||(e.rng||Ii)(),o=e.msecs===void 0?Date.now():e.msecs,s=e.seq===void 0?null:e.seq,c=Ji,l=qi;return o>Yi&&e.msecs===void 0&&(Yi=o,s!==null&&(c=null,l=null)),s!==null&&(s>2147483647&&(s=2147483647),c=s>>>19&4095,l=s&524287),(c===null||l===null)&&(c=a[6]&127,c=c<<8|a[7],l=a[8]&63,l=l<<8|a[9],l=l<<5|a[10]>>>3),o+1e4>Yi&&s===null?++l>524287&&(l=0,++c>4095&&(c=0,Yi++)):Yi=o,Ji=c,qi=l,i[r++]=Yi/1099511627776&255,i[r++]=Yi/4294967296&255,i[r++]=Yi/16777216&255,i[r++]=Yi/65536&255,i[r++]=Yi/256&255,i[r++]=Yi&255,i[r++]=c>>>4&15|112,i[r++]=c&255,i[r++]=l>>>13&63|128,i[r++]=l>>>5&255,i[r++]=l<<3&255|a[10]&7,i[r++]=a[11],i[r++]=a[12],i[r++]=a[13],i[r++]=a[14],i[r++]=a[15],t||Ni(i)}var Zi={};A(Zi,{BaseCallbackHandler:()=>ea,callbackHandlerPrefersStreaming:()=>$i,isBaseCallbackHandler:()=>ta});var Qi=class{};function $i(e){return`lc_prefer_streaming`in e&&e.lc_prefer_streaming}var ea=class extends Qi{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,fn(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Oi(`LANGCHAIN_CALLBACKS_BACKGROUND`)===`false`;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 pn.prototype.toJSON.call(this)}toJSONNotImplemented(){return pn.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends ea{name=Xi();constructor(){super(),Object.assign(this,e)}}return new t}},ta=e=>{let t=e;return t!==void 0&&typeof t.copy==`function`&&typeof t.name==`string`&&typeof t.awaitHandlers==`boolean`},na=`gen_ai.operation.name`,ra=`gen_ai.system`,ia=`gen_ai.request.model`,aa=`gen_ai.response.model`,oa=`gen_ai.usage.input_tokens`,sa=`gen_ai.usage.output_tokens`,ca=`gen_ai.usage.total_tokens`,la=`gen_ai.request.max_tokens`,ua=`gen_ai.request.temperature`,da=`gen_ai.request.top_p`,fa=`gen_ai.request.frequency_penalty`,pa=`gen_ai.request.presence_penalty`,ma=`gen_ai.response.finish_reasons`,ha=`gen_ai.prompt`,ga=`gen_ai.completion`,_a=`gen_ai.request.extra_query`,va=`gen_ai.request.extra_body`,ya=`gen_ai.serialized.name`,ba=`gen_ai.serialized.signature`,xa=`gen_ai.serialized.doc`,Sa=`gen_ai.response.id`,Ca=`gen_ai.response.service_tier`,wa=`gen_ai.response.system_fingerprint`,Ta=`gen_ai.usage.input_token_details`,Ea=`gen_ai.usage.output_token_details`,Da=`langsmith.trace.session_id`,Oa=`langsmith.trace.session_name`,ka=`langsmith.span.kind`,Aa=`langsmith.trace.name`,ja=`langsmith.metadata`,Ma=`langsmith.span.tags`,Na=`langsmith.request.streaming`,Pa=`langsmith.request.headers`,Fa=(...e)=>fetch(...e),Ia=Symbol.for(`ls:fetch_implementation`),La=()=>{let e=globalThis[Ia];return e?typeof e==`function`&&`Headers`in e&&`Request`in e&&`Response`in e:!1},Ra=e=>async(...t)=>{if(e||V(`DEBUG`)===`true`){let[e,n]=t;console.log(`→ ${n?.method||`GET`} ${e}`)}let n=await(globalThis[Ia]??Fa)(...t);return(e||V(`DEBUG`)===`true`)&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},za=()=>V(`PROJECT`)??os(`LANGCHAIN_SESSION`)??`default`,Ba={};function Va(e){Ba[e]||(console.warn(e),Ba[e]=!0)}var I=e=>BigInt(e),Ha=I(`0x9E3779B1`),Ua=I(`0x85EBCA77`),Wa=I(`0xC2B2AE3D`),Ga=I(`0x9E3779B185EBCA87`),Ka=I(`0xC2B2AE3D27D4EB4F`),qa=I(`0x165667B19E3779F9`),Ja=I(`0x85EBCA77C2B2AE63`),Ya=I(`0x27D4EB2F165667C5`),Xa=I(`0x165667919E3779F9`),Za=I(`0x9FB21C651E98DF25`);function Qa(e){let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substring(n,n+2),16);return t}var $a=Qa(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),eo=(I(1)<<I(128))-I(1),L=(I(1)<<I(64))-I(1),to=(I(1)<<I(32))-I(1),no=64,ro=no/8,io=8,ao=4;function R(e,t=0){return new Uint8Array(e.buffer,e.byteOffset+t,e.length-t)}function z(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getBigUint64(0,!0)}function oo(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getUint32(0,!0)}function so(e,t=0){return e[t]}var co=e=>(e&I(255))<<I(56)|(e&I(65280))<<I(40)|(e&I(16711680))<<I(24)|(e&I(4278190080))<<I(8)|(e&I(0xff00000000))>>I(8)|(e&I(0xff0000000000))>>I(24)|(e&I(0xff000000000000))>>I(40)|(e&I(0xff00000000000000))>>I(56),lo=e=>(e=(e&I(65535))<<I(16)|(e&I(4294901760))>>I(16),e=(e&I(16711935))<<I(8)|(e&I(4278255360))>>I(8),e),uo=(e,t)=>(e&to)*(t&to)&L,fo=e=>{if(!e)throw Error(`Assert failed`)};function po(e,t){return(e<<t|e>>I(32)-t)&to}function mo(e,t,n){for(let r=0;r<ro;r++){let i=z(t,r*8),a=i^z(n,r*8);e[r^1]+=i,e[r]+=uo(a,a>>I(32))}return e}function ho(e,t,n,r){for(let i=0;i<r;i++)mo(e,R(t,i*no),R(n,i*8));return e}function go(e,t){for(let n=0;n<ro;n++){let r=z(t,n*8),i=e[n];i=Do(i,I(47)),i^=r,i*=Ha,e[n]=i&L}return e}function _o(e,t){return xo(e[0]^z(t,0),e[1]^z(t,io))}function vo(e,t,n){let r=n;return r+=_o(e.slice(0),R(t,0*ao)),r+=_o(e.slice(2),R(t,4*ao)),r+=_o(e.slice(4),R(t,8*ao)),r+=_o(e.slice(6),R(t,12*ao)),wo(r&L)}function yo(e,t,n,r,i){let a=Math.floor((n.byteLength-no)/8),o=no*a,s=Math.floor((t.byteLength-1)/o);for(let r=0;r<s;r++)e=ho(e,R(t,r*o),n,a),e=i(e,R(n,n.byteLength-no));{let i=Math.floor((t.byteLength-1-o*s)/no);e=ho(e,R(t,s*o),n,i),e=r(e,R(t,t.byteLength-no),R(n,n.byteLength-no-7))}return e}function bo(e,t,n){let r=new BigUint64Array([Wa,Ga,Ka,qa,Ja,Ua,Ya,Ha]);fo(e.length>128),r=yo(r,e,t,mo,go),fo(r.length*8==64);{let n=vo(r,R(t,11),I(e.byteLength)*Ga&L);return vo(r,R(t,t.byteLength-no-11),~(I(e.byteLength)*Ka)&L)<<I(64)|n}}function xo(e,t){let n=e*t&eo;return n&L^n>>I(64)}function So(e,t,n){return xo((z(e,0)^z(t,0)+n)&L,(z(e,8)^z(t,8)-n)&L)}function Co(e,t,n,r,i){let a=e&L,o=e>>I(64)&L;return a+=So(t,r,i),a^=z(n,0)+z(n,8),a&=L,o+=So(n,R(r,16),i),o^=z(t,0)+z(t,8),o&=L,o<<I(64)|a}function wo(e){return e^=e>>I(37),e*=Xa,e&=L,e^=e>>I(32),e}function To(e){return e^=e>>I(33),e*=Ka,e&=L,e^=e>>I(29),e*=qa,e&=L,e^=e>>I(32),e}function Eo(e,t,n){let r=e.byteLength;fo(r>0&&r<=3);let i=I(so(e,r-1))|I(r<<8)|I(so(e,0)<<16)|I(so(e,r>>1)<<24),a=(i^(I(oo(t,0))^I(oo(t,4)))+n)&L,o=(I(oo(t,8))^I(oo(t,12)))-n;return(To((po(lo(i),I(13))^o)&L)&L)<<I(64)|To(a)}function Do(e,t){return e^e>>t}function Oo(e,t,n){let r=e.byteLength;fo(r>=4&&r<=8);{let i=oo(e,0),a=oo(e,r-4),o=((I(i)|I(a)<<I(32))^(z(t,16)^z(t,24))+n&L)*(Ga+(I(r)<<I(2)))&eo;return o+=(o&L)<<I(65),o&=eo,o^=o>>I(67),Do(Do(o&L,I(35))*Za&L,I(28))|wo(o>>I(64))<<I(64)}}function ko(e,t,n){let r=e.byteLength;fo(r>=9&&r<=16);{let i=(z(t,32)^z(t,40))+n&L,a=(z(t,48)^z(t,56))-n&L,o=z(e),s=z(e,r-8),c=(o^s^i)*Ga,l=(c&L)+(I(r-1)<<I(54));c=c&(eo^L)|l,s^=a,c+=s+(s&to)*(Ua-I(1))<<I(64),c&=eo,c^=co(c>>I(64));let u=(c&L)*Ka;return u+=(c>>I(64))*Ka<<I(64),u&=eo,wo(u&L)|wo(u>>I(64))<<I(64)}}function Ao(e,t){let n=e.byteLength;return fo(n<=16),n>8?ko(e,$a,t):n>=4?Oo(e,$a,t):n>0?Eo(e,$a,t):To(t^z($a,64)^z($a,72))|To(t^z($a,80)^z($a,88))<<I(64)}function jo(e){return~e+I(1)&L}function Mo(e,t,n){let r=I(e.byteLength)*Ga&L,i=I(e.byteLength-1)/I(32);for(;i>=0;){let a=Number(i);r=Co(r,R(e,16*a),R(e,e.byteLength-16*(a+1)),R(t,32*a),n),i--}let a=r+(r>>I(64))&L;a=wo(a);let o=(r&L)*Ga+(r>>I(64))*Ja+(I(e.byteLength)-n&L)*Ka;return o&=L,o=jo(wo(o)),a|o<<I(64)}function No(e,t,n){let r=I(e.byteLength)*Ga&L;for(let i=32;i<160;i+=32)r=Co(r,R(e,i-32),R(e,i-16),R(t,i-32),n);r=wo(r&L)|wo(r>>I(64))<<I(64);for(let i=160;i<=e.byteLength;i+=32)r=Co(r,R(e,i-32),R(e,i-16),R(t,3+i-160),n);r=Co(r,R(e,e.byteLength-16),R(e,e.byteLength-32),R(t,103),jo(n));let i=r+(r>>I(64))&L;i=wo(i);let a=(r&L)*Ga+(r>>I(64))*Ja+(I(e.byteLength)-n&L)*Ka;return a&=L,a=jo(wo(a)),i|a<<I(64)}function Po(e,t=I(0)){let n=e.byteLength;return n<=16?Ao(e,t):n<=128?Mo(e,$a,t):n<=240?No(e,$a,t):bo(e,$a,t)}function Fo(e){let t=new Uint8Array(16),n=new DataView(t.buffer),r=e&L,i=e>>I(64);return n.setBigUint64(0,i,!1),n.setBigUint64(8,r,!1),t}var Io=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function B(e,t){if(!Io.test(e)){let n=t===void 0?`Invalid UUID: ${e}`:`Invalid UUID for ${t}: ${e}`;throw Error(n)}return e}function Lo(e){return Xi({msecs:typeof e==`string`?Date.parse(e):e,seq:0})}function Ro(e){if(!Io.test(e))return null;let t=e[14];return parseInt(t,16)}function zo(e){let t=e.replace(/-/g,``),n=new Uint8Array(16);for(let e=0;e<16;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}function Bo(e){let t=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Vo=new TextEncoder;function Ho(e){return Fo(Po(Vo.encode(e)))}function Uo(e,t){let n=Ho(`${e}:${t}`),r=new Uint8Array(16);if(Ro(e)===7){let t=zo(e);r.set(t.slice(0,6),0)}else{let e=Date.now();r[0]=e/1099511627776&255,r[1]=e/4294967296&255,r[2]=e/16777216&255,r[3]=e/65536&255,r[4]=e/256&255,r[5]=e&255}return r[6]=112|n[0]&15,r[7]=n[1],r[8]=128|n[2]&63,r.set(n.slice(3,10),9),Bo(r)}function Wo(e,t){throw Error(`dump() is not supported in browser environments.`)}function Go(e){throw Error(`load() is not supported in browser environments.`)}function Ko(e,t){return t===null?!1:Date.now()-e.createdAt>t*1e3}var qo=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,`fetchFunc`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`refreshTimer`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`_metrics`,{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??3600,this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.fetchFunc=e.fetchFunc,this.fetchFunc&&this.ttlSeconds!==null&&this.startRefreshLoop()}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){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){let t=this.cache.get(e);if(!t){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,t),this._metrics.hits+=1,t.value}set(e,t){if(!this.cache.has(e)&&this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;e!==void 0&&this.cache.delete(e)}let n={value:t,createdAt:Date.now()};this.cache.delete(e),this.cache.set(e,n)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&=(clearInterval(this.refreshTimer),void 0)}dump(e){let t={};for(let[e,n]of this.cache.entries())t[e]=n.value;Wo(e,t)}load(e){let t=Go(e);if(!t)return 0;let n=0,r=Date.now();for(let[e,i]of Object.entries(t)){if(this.cache.size>=this.maxSize)break;let t={value:i,createdAt:r};this.cache.set(e,t),n+=1}return n}startRefreshLoop(){this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn(`Unexpected error in cache refresh loop:`,e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref()}getStaleKeys(){let e=[];for(let[t,n]of this.cache.entries())Ko(n,this.ttlSeconds)&&e.push(t);return e}async refreshStaleEntries(){if(!this.fetchFunc)return;let e=this.getStaleKeys();if(e.length!==0)for(let t of e)try{let e=await this.fetchFunc(t);this.set(t,e),this._metrics.refreshes+=1}catch(e){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${t}:`,e)}}},Jo=`0.4.12`,Yo,Xo=()=>typeof window<`u`&&window.document!==void 0,Zo=()=>typeof globalThis==`object`&&globalThis.constructor&&globalThis.constructor.name===`DedicatedWorkerGlobalScope`,Qo=()=>typeof window<`u`&&window.name===`nodejs`||typeof navigator<`u`&&navigator.userAgent.includes(`jsdom`),$o=()=>typeof Deno<`u`,es=()=>typeof process<`u`&&process.versions!==void 0&&process.versions.node!==void 0&&!$o(),ts=()=>Yo||(Yo=typeof Bun<`u`?`bun`:Xo()?`browser`:es()?`node`:Zo()?`webworker`:Qo()?`jsdom`:$o()?`deno`:`other`,Yo),ns;function rs(){return ns===void 0&&(ns={library:`langsmith`,runtime:ts(),sdk:`langsmith-js`,sdk_version:Jo,...cs()}),ns}function is(){let e=as(),t={},n=[`LANGCHAIN_API_KEY`,`LANGCHAIN_ENDPOINT`,`LANGCHAIN_TRACING_V2`,`LANGCHAIN_PROJECT`,`LANGCHAIN_SESSION`,`LANGSMITH_API_KEY`,`LANGSMITH_ENDPOINT`,`LANGSMITH_TRACING_V2`,`LANGSMITH_PROJECT`,`LANGSMITH_SESSION`];for(let[r,i]of Object.entries(e))typeof i==`string`&&!n.includes(r)&&!r.toLowerCase().includes(`key`)&&!r.toLowerCase().includes(`secret`)&&!r.toLowerCase().includes(`token`)&&(r===`LANGCHAIN_REVISION_ID`?t.revision_id=i:t[r]=i);return t}function as(){let e={};try{if(typeof process<`u`)for(let[t,n]of Object.entries({}))(t.startsWith(`LANGCHAIN_`)||t.startsWith(`LANGSMITH_`))&&n!=null&&((t.toLowerCase().includes(`key`)||t.toLowerCase().includes(`secret`)||t.toLowerCase().includes(`token`))&&typeof n==`string`?e[t]=n.slice(0,2)+`*`.repeat(n.length-4)+n.slice(-2):e[t]=n)}catch{}return e}function os(e){try{return typeof process<`u`?{}?.[e]:void 0}catch{return}}function V(e){return os(`LANGSMITH_${e}`)||os(`LANGCHAIN_${e}`)}var ss;function cs(){if(ss!==void 0)return ss;let e=[`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`],t={};for(let n of e){let e=os(n);e!==void 0&&(t[n]=e)}return ss=t,t}function ls(){return os(`OTEL_ENABLED`)===`true`||V(`OTEL_ENABLED`)===`true`}var us=class{constructor(){Object.defineProperty(this,`hasWarned`,{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&ls()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(t.length===1&&typeof t[0]==`function`?n=t[0]:t.length===2&&typeof t[1]==`function`?n=t[1]:t.length===3&&typeof t[2]==`function`&&(n=t[2]),typeof n==`function`)return n()}},ds=class{constructor(){Object.defineProperty(this,`mockTracer`,{enumerable:!0,configurable:!0,writable:!0,value:new us})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},fs=class{active(){return{}}with(e,t){return t()}},ps=Symbol.for(`ls:otel_trace`),ms=Symbol.for(`ls:otel_context`),hs=Symbol.for(`ls:otel_get_default_otlp_tracer_provider`),gs=new ds,_s=new fs,vs=new class{getTraceInstance(){return globalThis[ps]??gs}getContextInstance(){return globalThis[ms]??_s}initializeGlobalInstances(e){globalThis[ps]===void 0&&(globalThis[ps]=e.trace),globalThis[ms]===void 0&&(globalThis[ms]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[hs]=e}getDefaultOTLPTracerComponents(){return globalThis[hs]??void 0}};function ys(){return vs.getTraceInstance()}function bs(){return vs.getContextInstance()}function xs(){return vs.getDefaultOTLPTracerComponents()}var Ss={llm:`chat`,tool:`execute_tool`,retriever:`embeddings`,embedding:`embeddings`,prompt:`chat`};function Cs(e){return Ss[e]||e}var ws=class{constructor(){Object.defineProperty(this,`spans`,{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(let n of e)try{if(!n.run)continue;if(n.operation===`post`){let e=this.createSpanForRun(n,n.run,t.get(n.id));e&&!n.run.end_time&&this.spans.set(n.id,e)}else this.updateSpanForRun(n,n.run)}catch(e){console.error(`Error processing operation ${n.id}:`,e)}}createSpanForRun(e,t,n){let r=n&&ys().getSpan(n);if(r)try{return this.finishSpanSetup(r,t,e)}catch(t){console.error(`Failed to create span for run ${e.id}:`,t);return}}finishSpanSetup(e,t,n){return this.setSpanAttributes(e,t,n),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 n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,t,e),t.error?(n.setStatus({code:2}),n.recordException(Error(t.error))):n.setStatus({code:1});let r=t.end_time;r&&(n.end(new Date(r)),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,n){if(`run_type`in t&&t.run_type){e.setAttribute(ka,t.run_type);let n=Cs(t.run_type||`chain`);e.setAttribute(na,n)}`name`in t&&t.name&&e.setAttribute(Aa,t.name),`session_id`in t&&t.session_id&&e.setAttribute(Da,t.session_id),`session_name`in t&&t.session_name&&e.setAttribute(Oa,t.session_name),this.setGenAiSystem(e,t);let r=this.extractModelName(t);r&&e.setAttribute(ia,r),`prompt_tokens`in t&&typeof t.prompt_tokens==`number`&&e.setAttribute(oa,t.prompt_tokens),`completion_tokens`in t&&typeof t.completion_tokens==`number`&&e.setAttribute(sa,t.completion_tokens),`total_tokens`in t&&typeof t.total_tokens==`number`&&e.setAttribute(ca,t.total_tokens),this.setInvocationParameters(e,t);let i=t.extra?.metadata||{};for(let[t,n]of Object.entries(i))n!=null&&e.setAttribute(`${ja}.${t}`,String(n));let a=t.tags;if(a&&Array.isArray(a)?e.setAttribute(Ma,a.join(`, `)):a&&e.setAttribute(Ma,String(a)),`serialized`in t&&typeof t.serialized==`object`){let n=t.serialized;n.name&&e.setAttribute(ya,String(n.name)),n.signature&&e.setAttribute(ba,String(n.signature)),n.doc&&e.setAttribute(xa,String(n.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,t){let n=`langchain`,r=this.extractModelName(t);if(r){let e=r.toLowerCase();e.includes(`anthropic`)||e.startsWith(`claude`)?n=`anthropic`:e.includes(`bedrock`)?n=`aws.bedrock`:e.includes(`azure`)&&e.includes(`openai`)?n=`az.ai.openai`:e.includes(`azure`)&&e.includes(`inference`)?n=`az.ai.inference`:e.includes(`cohere`)?n=`cohere`:e.includes(`deepseek`)?n=`deepseek`:e.includes(`gemini`)?n=`gemini`:e.includes(`groq`)?n=`groq`:e.includes(`watson`)||e.includes(`ibm`)?n=`ibm.watsonx.ai`:e.includes(`mistral`)?n=`mistral_ai`:e.includes(`gpt`)||e.includes(`openai`)?n=`openai`:e.includes(`perplexity`)||e.includes(`sonar`)?n=`perplexity`:e.includes(`vertex`)?n=`vertex_ai`:(e.includes(`xai`)||e.includes(`grok`))&&(n=`xai`)}e.setAttribute(ra,n)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;let n=t.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(la,n.max_tokens),n.temperature!==void 0&&e.setAttribute(ua,n.temperature),n.top_p!==void 0&&e.setAttribute(da,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(fa,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(pa,n.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{let n=t.run.inputs;typeof n==`object`&&n&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(ia,n.model),n.stream!==void 0&&e.setAttribute(Na,n.stream),n.extra_headers&&e.setAttribute(Pa,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(_a,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(va,JSON.stringify(n.extra_body))),e.setAttribute(ha,JSON.stringify(n))}catch(e){console.debug(`Failed to process inputs for run ${t.id}`,e)}if(t.run.outputs)try{let n=t.run.outputs,r=this.getUnifiedRunTokens(n);if(r&&(e.setAttribute(oa,r[0]),e.setAttribute(sa,r[1]),e.setAttribute(ca,r[0]+r[1])),n&&typeof n==`object`){if(n.model&&e.setAttribute(aa,String(n.model)),n.id&&e.setAttribute(Sa,n.id),n.choices&&Array.isArray(n.choices)){let t=n.choices.map(e=>e.finish_reason).filter(e=>e).map(String);t.length>0&&e.setAttribute(ma,t.join(`, `))}if(n.service_tier&&e.setAttribute(Ca,n.service_tier),n.system_fingerprint&&e.setAttribute(wa,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata==`object`){let t=n.usage_metadata;t.input_token_details&&e.setAttribute(Ta,JSON.stringify(t.input_token_details)),t.output_token_details&&e.setAttribute(Ea,JSON.stringify(t.output_token_details))}}e.setAttribute(ga,JSON.stringify(n))}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;let n=Object.keys(e);for(let r of n){let n=e[r];if(!(!n||typeof n!=`object`)&&(t=this.extractUnifiedRunTokens(n.usage_metadata),t||n.lc===1&&n.kwargs&&typeof n.kwargs==`object`&&(t=this.extractUnifiedRunTokens(n.kwargs.usage_metadata),t)))return t}let r=e.generations||[];if(!Array.isArray(r))return null;let i=Array.isArray(r[0])?r.flat():r;for(let e of i)if(typeof e==`object`&&e.message&&typeof e.message==`object`&&e.message.kwargs&&typeof e.message.kwargs==`object`&&(t=this.extractUnifiedRunTokens(e.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return!e||typeof e!=`object`||typeof e.input_tokens!=`number`||typeof e.output_tokens!=`number`?null:[e.input_tokens,e.output_tokens]}},Ts=Object.prototype.toString,Es=e=>Ts.call(e)===`[object Error]`,Ds=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 Os(e){if(!(e&&Es(e)&&e.name===`TypeError`&&typeof e.message==`string`))return!1;let{message:t,stack:n}=e;return t===`Load failed`?n===void 0||`__sentry_captured__`in e:t.startsWith(`error sending request for url`)?!0:Ds.has(t)}function ks(e){if(typeof e==`number`){if(e<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function As(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${r?` or Infinity`:``}.`);if(!r&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw TypeError(`Expected \`${e}\` to be \u2265 ${n}.`)}}var js=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 Ms(e,t){let n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1,i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}function Ns(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Ps({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){let a=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof js)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,s=i.maxRetryTime??1/0,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(c),Ns(r,s)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=Ns(r,s);if(u<=0||o<=0)throw a;if(a instanceof TypeError&&!Os(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=Ms(n,i),f=Math.min(d,u);return f>0&&await new Promise((e,t)=>{let n=()=>{clearTimeout(r),i.signal?.removeEventListener(`abort`,n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},f);i.unref&&r.unref?.(),i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.throwIfAborted(),!0}async function Fs(e,t={}){if(t={...t},ks(t.retries),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,As(`factor`,t.factor,{min:0,allowInfinity:!1}),As(`minTimeout`,t.minTimeout,{min:0,allowInfinity:!1}),As(`maxTimeout`,t.maxTimeout,{min:0,allowInfinity:!0}),As(`maxRetryTime`,t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0,i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();let r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await Ps({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw Error(`Retry attempts exhausted without throwing an error.`)}var Is=n(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)})),Ls=n(((e,t)=>{t.exports=(e,t)=>(t||=(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))})),Rs=n(((e,t)=>{var n=Ls(),r=class extends Error{constructor(e){super(e),this.name=`TimeoutError`}},i=(e,t,i)=>new Promise((a,o)=>{if(typeof t!=`number`||t<0)throw TypeError("Expected `milliseconds` to be a positive number");if(t===1/0){a(e);return}let s=setTimeout(()=>{if(typeof i==`function`){try{a(i())}catch(e){o(e)}return}let n=typeof i==`string`?i:`Promise timed out after ${t} milliseconds`,s=i instanceof Error?i:new r(n);typeof e.cancel==`function`&&e.cancel(),o(s)},t);n(e.then(a,o),()=>{clearTimeout(s)})});t.exports=i,t.exports.default=i,t.exports.TimeoutError=r})),zs=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e,t,n){let r=0,i=e.length;for(;i>0;){let a=i/2|0,o=r+a;n(e[o],t)<=0?(r=++o,i-=a+1):i=a}return r}e.default=t})),Bs=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t=zs();e.default=class{constructor(){this._queue=[]}enqueue(e,n){n=Object.assign({priority:0},n);let r={priority:n.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=n.priority){this._queue.push(r);return}let i=t.default(this._queue,r,(e,t)=>t.priority-e.priority);this._queue.splice(i,0,r)}dequeue(){return this._queue.shift()?.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this._queue.length}}})),Vs=e(n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t=Is(),n=Rs(),r=Bs(),i=()=>{},a=new n.TimeoutError;e.default=class extends t{constructor(e){if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=i,this._resolveIdle=i,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default},e),!(typeof e.intervalCap==`number`&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??``}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??``}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,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=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit(`next`)}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=i,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=i,this.emit(`idle`))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let t=this._intervalEnd-e;if(t<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return t?(this.emit(`active`),t(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e==`number`&&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,i)=>{this._queue.enqueue(async()=>{this._pendingCount++,this._intervalCount++;try{r(await(this._timeout===void 0&&t.timeout===void 0?e():n.default(Promise.resolve(e()),t.timeout===void 0?this._timeout:t.timeout,()=>{(t.throwOnTimeout===void 0?this._throwOnTimeout:t.throwOnTimeout)&&i(a)})))}catch(e){i(e)}this._next()},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):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))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}}}))(),1),Hs=[408,425,429,500,502,503,504],Us=class{constructor(e){Object.defineProperty(this,`maxConcurrency`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`maxRetries`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`maxQueueSizeBytes`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`queue`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`onFailedResponseHook`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`queueSizeBytes`,{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,`default`in Vs.default?this.queue=new Vs.default.default({concurrency:this.maxConcurrency}):this.queue=new Vs.default({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){return this.callWithOptions({},e,...t)}callWithOptions(e,t,...n){let r=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&r>0&&this.queueSizeBytes+r>this.maxQueueSizeBytes)return Promise.reject(Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${r} bytes.`));r>0&&(this.queueSizeBytes+=r);let i=this.onFailedResponseHook,a=this.queue.add(()=>Fs(()=>t(...n).catch(e=>{throw e instanceof Error?e:Error(e)}),{async onFailedAttempt({error:e}){if(typeof e!=`object`||!e)throw e;let t=`message`in e&&typeof e.message==`string`?e.message:void 0;if(t?.startsWith(`Cancel`)||t?.startsWith(`TimeoutError`)||t?.startsWith(`AbortError`)||`name`in e&&e.name===`TimeoutError`||`code`in e&&e.code===`ECONNABORTED`)throw e;let n=`response`in e?e.response:void 0;if(i&&await i(n))return;let r=n?.status??(`status`in e?e.status:void 0);if(r!=null&&(typeof r==`number`||typeof r==`string`)&&!Hs.includes(+r))throw e},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return r>0&&(a=a.finally(()=>{this.queueSizeBytes-=r})),e.signal?Promise.race([a,new Promise((t,n)=>{e.signal?.addEventListener(`abort`,()=>{n(Error(`AbortError`))})})]):a}};function Ws(e){return typeof e?._getType==`function`}function Gs(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}var Ks=n(((e,t)=>{var n=`2.0.0`,r=256;t.exports={MAX_LENGTH:r,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:r-6,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:n,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),qs=n(((e,t)=>{t.exports=typeof process==`object`&&{}.NODE_DEBUG&&/\bsemver\b/i.test({}.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),Js=n(((e,t)=>{var{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=Ks(),a=qs();e=t.exports={};var o=e.re=[],s=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={},d=0,f=`[a-zA-Z0-9-]`,p=[[`\\s`,1],[`\\d`,i],[f,r]],m=e=>{for(let[t,n]of p)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},h=(e,t,n)=>{let r=m(t),i=d++;a(e,i,t),u[e]=i,c[i]=t,l[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};h(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),h(`NUMERICIDENTIFIERLOOSE`,`\\d+`),h(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${f}*`),h(`MAINVERSION`,`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h(`MAINVERSIONLOOSE`,`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASEIDENTIFIER`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASE`,`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h(`PRERELEASELOOSE`,`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h(`BUILDIDENTIFIER`,`${f}+`),h(`BUILD`,`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h(`FULLPLAIN`,`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h(`FULL`,`^${c[u.FULLPLAIN]}$`),h(`LOOSEPLAIN`,`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h(`LOOSE`,`^${c[u.LOOSEPLAIN]}$`),h(`GTLT`,`((?:<|>)?=?)`),h(`XRANGEIDENTIFIERLOOSE`,`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h(`XRANGEIDENTIFIER`,`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h(`XRANGEPLAIN`,`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h(`XRANGEPLAINLOOSE`,`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h(`XRANGE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h(`XRANGELOOSE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h(`COERCE`,`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h(`COERCEFULL`,c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h(`COERCERTL`,c[u.COERCE],!0),h(`COERCERTLFULL`,c[u.COERCEFULL],!0),h(`LONETILDE`,`(?:~>?)`),h(`TILDETRIM`,`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,h(`TILDE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h(`TILDELOOSE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h(`LONECARET`,`(?:\\^)`),h(`CARETTRIM`,`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,h(`CARET`,`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h(`CARETLOOSE`,`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h(`COMPARATORLOOSE`,`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h(`COMPARATOR`,`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h(`COMPARATORTRIM`,`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,h(`HYPHENRANGE`,`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h(`HYPHENRANGELOOSE`,`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h(`STAR`,`(<|>)?=?\\s*\\*`),h(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),h(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),Ys=n(((e,t)=>{var n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),Xs=n(((e,t)=>{var n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),H=n(((e,t)=>{var n=qs(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=Ks(),{safeRe:a,t:o}=Js(),s=Ys(),{compareIdentifiers:c}=Xs();t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);l[4]?this.prerelease=l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:+(this.patch>t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=+!!Number(n);if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];n===!1&&(r=[t]),c(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),Zs=n(((e,t)=>{var n=H();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),Qs=n(((e,t)=>{var n=Zs();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),$s=n(((e,t)=>{var n=Zs();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),ec=n(((e,t)=>{var n=H();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),tc=n(((e,t)=>{var n=Zs();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),nc=n(((e,t)=>{var n=H();t.exports=(e,t)=>new n(e,t).major})),rc=n(((e,t)=>{var n=H();t.exports=(e,t)=>new n(e,t).minor})),ic=n(((e,t)=>{var n=H();t.exports=(e,t)=>new n(e,t).patch})),ac=n(((e,t)=>{var n=Zs();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),oc=n(((e,t)=>{var n=H();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),sc=n(((e,t)=>{var n=oc();t.exports=(e,t,r)=>n(t,e,r)})),cc=n(((e,t)=>{var n=oc();t.exports=(e,t)=>n(e,t,!0)})),lc=n(((e,t)=>{var n=H();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),uc=n(((e,t)=>{var n=lc();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),dc=n(((e,t)=>{var n=lc();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),fc=n(((e,t)=>{var n=oc();t.exports=(e,t,r)=>n(e,t,r)>0})),pc=n(((e,t)=>{var n=oc();t.exports=(e,t,r)=>n(e,t,r)<0})),mc=n(((e,t)=>{var n=oc();t.exports=(e,t,r)=>n(e,t,r)===0})),hc=n(((e,t)=>{var n=oc();t.exports=(e,t,r)=>n(e,t,r)!==0})),gc=n(((e,t)=>{var n=oc();t.exports=(e,t,r)=>n(e,t,r)>=0})),_c=n(((e,t)=>{var n=oc();t.exports=(e,t,r)=>n(e,t,r)<=0})),vc=n(((e,t)=>{var n=mc(),r=hc(),i=fc(),a=gc(),o=pc(),s=_c();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),yc=n(((e,t)=>{var n=H(),r=Zs(),{safeRe:i,t:a}=Js();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2];return r(`${s}.${o[3]||`0`}.${o[4]||`0`}${t.includePrerelease&&o[5]?`-${o[5]}`:``}${t.includePrerelease&&o[6]?`+${o[6]}`:``}`,t)}})),bc=n(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),xc=n(((e,t)=>{var n=/\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!h(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&g(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&p)|(this.options.loose&&m))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(s,ie(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[l.COMPARATORTRIM],u),o(`comparator trim`,e),e=e.replace(c[l.TILDETRIM],d),o(`tilde trim`,e),e=e.replace(c[l.CARETTRIM],f),o(`caret trim`,e);let g=e.split(` `).map(e=>v(e,this.options)).join(` `).split(/\s+/).map(e=>C(e,this.options));i&&(g=g.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[l.COMPARATORLOOSE])))),o(`range list`,g);let _=new Map,y=g.map(e=>new a(e,this.options));for(let e of y){if(h(e))return[e];_.set(e.value,e)}_.size>1&&_.has(``)&&_.delete(``);let b=[..._.values()];return r.set(t,b),b}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>_(e,n)&&t.set.some(t=>_(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(w(this.set[t],e,this.options))return!0;return!1}};var r=new(bc()),i=Ys(),a=Sc(),o=qs(),s=H(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=Js(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:m}=Ks(),h=e=>e.value===`<0.0.0-0`,g=e=>e.value===``,_=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},v=(e,t)=>(e=e.replace(c[l.BUILD],``),o(`comp`,e,t),e=te(e,t),o(`caret`,e),e=b(e,t),o(`tildes`,e),e=re(e,t),o(`xrange`,e),e=S(e,t),o(`stars`,e),e),y=e=>!e||e.toLowerCase()===`x`||e===`*`,b=(e,t)=>e.trim().split(/\s+/).map(e=>ee(e,t)).join(` `),ee=(e,t)=>{let n=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(n,(t,n,r,i,a)=>{o(`tilde`,e,t,n,r,i,a);let s;return y(n)?s=``:y(r)?s=`>=${n}.0.0 <${+n+1}.0.0-0`:y(i)?s=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:a?(o(`replaceTilde pr`,a),s=`>=${n}.${r}.${i}-${a} <${n}.${+r+1}.0-0`):s=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o(`tilde return`,s),s})},te=(e,t)=>e.trim().split(/\s+/).map(e=>ne(e,t)).join(` `),ne=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[l.CARETLOOSE]:c[l.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return y(n)?c=``:y(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:y(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a}${r} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},re=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>x(e,t)).join(` `)),x=(e,t)=>{e=e.trim();let n=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{o(`xRange`,e,n,r,i,a,s,c);let l=y(i),u=l||y(a),d=u||y(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},S=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[l.STAR],``)),C=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],``)),ie=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=y(r)?``:y(i)?`>=${r}.0.0${e?`-0`:``}`:y(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=y(l)?``:y(u)?`<${+l+1}.0.0-0`:y(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),w=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),Sc=n(((e,t)=>{var n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.semver===n?this.value=``:this.value=this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),r[2]?this.semver=new c(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``?!0:new l(t.value,n).test(this.value):t.operator===``?t.value===``?!0:new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};var r=Ys(),{safeRe:i,t:a}=Js(),o=vc(),s=qs(),c=H(),l=xc()})),Cc=n(((e,t)=>{var n=xc();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),wc=n(((e,t)=>{var n=xc();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),Tc=n(((e,t)=>{var n=H(),r=xc();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),Ec=n(((e,t)=>{var n=H(),r=xc();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),Dc=n(((e,t)=>{var n=H(),r=xc(),i=fc();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),Oc=n(((e,t)=>{var n=xc();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),kc=n(((e,t)=>{var n=H(),r=Sc(),{ANY:i}=r,a=xc(),o=Cc(),s=fc(),c=pc(),l=_c(),u=gc();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),Ac=n(((e,t)=>{var n=kc();t.exports=(e,t,r)=>n(e,t,`>`,r)})),jc=n(((e,t)=>{var n=kc();t.exports=(e,t,r)=>n(e,t,`<`,r)})),Mc=n(((e,t)=>{var n=xc();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),Nc=n(((e,t)=>{var n=Cc(),r=oc();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),Pc=n(((e,t)=>{var n=xc(),r=Sc(),{ANY:i}=r,a=Cc(),o=oc(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!a(s.semver,String(e),n))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!a(u.semver,String(e),n))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s}));n(((e,t)=>{var n=Js(),r=Ks(),i=H(),a=Xs();t.exports={parse:Zs(),valid:Qs(),clean:$s(),inc:ec(),diff:tc(),major:nc(),minor:rc(),patch:ic(),prerelease:ac(),compare:oc(),rcompare:sc(),compareLoose:cc(),compareBuild:lc(),sort:uc(),rsort:dc(),gt:fc(),lt:pc(),eq:mc(),neq:hc(),gte:gc(),lte:_c(),cmp:vc(),coerce:yc(),Comparator:Sc(),Range:xc(),satisfies:Cc(),toComparators:wc(),maxSatisfying:Tc(),minSatisfying:Ec(),minVersion:Dc(),validRange:Oc(),outside:kc(),gtr:Ac(),ltr:jc(),intersects:Mc(),simplifyRange:Nc(),subset:Pc(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}}))();function Fc(e){if(!e||e.split(`/`).length>2||e.startsWith(`/`)||e.endsWith(`/`)||e.split(`:`).length>2)throw Error(`Invalid identifier format: ${e}`);let[t,n]=e.split(`:`),r=n||`latest`;if(t.includes(`/`)){let[n,i]=t.split(`/`,2);if(!n||!i)throw Error(`Invalid identifier format: ${e}`);return[n,i,r]}else{if(!t)throw Error(`Invalid identifier format: ${e}`);return[`-`,t,r]}}var Ic=class 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}},Lc=class 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 Rc(e){return typeof e==`object`&&!!e&&`name`in e&&e?.name===`LangSmithNotFoundError`}async function U(e,t,n){let r;if(e.ok){n&&(r=await e.text());return}if(e.status===403)try{(await e.json())?.error===`org_scoped_key_requires_workspace`&&(r=`This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.`)}catch{let t=Error(`${e.status} ${e.statusText}`);throw t.status=e?.status,t}if(r===void 0)try{r=await e.text()}catch{r=``}let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${r}`;if(e.status===404)throw new Lc(i);if(e.status===409)throw new Ic(i);let a=Error(i);throw a.status=e.status,a}var zc=`ERR_CONFLICTING_ENDPOINTS`,Bc=class 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:zc}),this.name=`ConflictingEndpointsError`}};function Vc(e){return typeof e==`object`&&!!e&&e.code===zc}var Hc=`[...]`,Uc={result:`[Circular]`},Wc=[],Gc=[],Kc=new TextEncoder;function qc(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function Jc(e){return Kc.encode(e)}function Yc(e){if(e&&typeof e==`object`&&e){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e==`bigint`)return e.toString();return e}function Xc(e){return function(t,n){if(e){let r=e.call(this,t,n);if(r!==void 0)return r}return Yc(n)}}function Zc(e,t,n,r,i){try{return Jc(JSON.stringify(e,Xc(n),r))}catch(a){if(!a.message?.includes(`Converting circular structure to JSON`))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`\nContext: ${t}`:``}`),Jc(`[Unserializable]`);V(`SUPPRESS_CIRCULAR_JSON_WARNINGS`)!==`true`&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`\nContext: ${t}`:``}`),i===void 0&&(i=qc()),$c(e,``,0,[],void 0,0,i);let o;try{o=Gc.length===0?JSON.stringify(e,n,r):JSON.stringify(e,el(n),r)}catch{return Jc(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;Wc.length!==0;){let e=Wc.pop();e.length===4?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return Jc(o)}}function Qc(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,Wc.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),Wc.push([r,n,t,i])):Gc.push([t,n,e])}function $c(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){Qc(Uc,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){Qc(Hc,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){Qc(Hc,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)$c(e[s],s,s,r,e,a,o);else{e=Yc(e);var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];$c(e[l],l,s,r,e,a,o)}}r.pop()}}function el(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(Gc.length>0)for(var r=0;r<Gc.length;r++){var i=Gc[r];if(i[1]===t&&i[0]===n){n=i[2],Gc.splice(r,1);break}}return e.call(this,t,n)}}function tl(e,t,n){if(n)return e;let r=rs(),i=t??is(),a=e.extra??{},o=a.metadata;return e.extra={...a,runtime:{...r,...a?.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}:{},...o}},e}var nl=e=>{let t=e?.toString()??V(`TRACING_SAMPLING_RATE`);if(t===void 0)return;let n=parseFloat(t);if(n<0||n>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},rl=e=>{let t=e.replace(`http://`,``).replace(`https://`,``).split(`/`)[0].split(`:`)[0];return t===`localhost`||t===`127.0.0.1`||t===`::1`};async function il(e){let t=[];for await(let n of e)t.push(n);return t}function al(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,`$1`).replace(/^'(.*)'$/,`$1`)}var ol=async e=>{if(e?.status===429){let t=parseInt(e.headers.get(`retry-after`)??`10`,10)*1e3;if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};function sl(e){return typeof e==`number`?Number(e.toFixed(4)):e}var cl=1e4,ll=100,ul=`https://api.smith.langchain.com`,dl=class{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??1073741824}peek(){return this.items[0]}push(e){let t,n=new Promise(e=>{t=e}),r=Zc(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+r>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: ${r} bytes.`),t(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:n,size:r}),this.sizeBytes+=r,n)}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw Error(`Number of bytes to pop off may not be less than 1.`);let n=[],r=0;for(;r+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<t;){let e=this.items.shift();e&&(n.push(e),r+=e.size,this.sizeBytes-=e.size)}if(n.length===0&&this.items.length>0){let e=this.items.shift();n.push(e),r+=e.size,this.sizeBytes-=e.size}return[n.map(e=>({action:e.action,item:e.payload,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,size:e.size})),()=>n.forEach(e=>e.itemPromiseResolve())]}},fl=class e{get _fetch(){return this.fetchImplementation||Ra(this.debug)}constructor(t={}){Object.defineProperty(this,`apiKey`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`apiUrl`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`webUrl`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`workspaceId`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`caller`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`batchIngestCaller`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`timeout_ms`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`_tenantId`,{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,`hideInputs`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`hideOutputs`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`omitTracedRuntimeInfo`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`tracingSampleRate`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`filteredPostUuids`,{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,`autoBatchTracing`,{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,`autoBatchQueue`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`autoBatchTimeout`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`autoBatchAggregationDelayMs`,{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,`batchSizeBytesLimit`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`batchSizeLimit`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`fetchOptions`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`settings`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`blockOnRootRunFinalization`,{enumerable:!0,configurable:!0,writable:!0,value:os(`LANGSMITH_TRACING_BACKGROUND`)===`false`}),Object.defineProperty(this,`traceBatchConcurrency`,{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,`_serverInfo`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`_getServerInfoPromise`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`manualFlushMode`,{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,`langSmithToOTELTranslator`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`fetchImplementation`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`cachedLSEnvVarsForMetadata`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`_cache`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`multipartStreamingDisabled`,{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,`_multipartDisabled`,{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,`_runCompressionDisabled`,{enumerable:!0,configurable:!0,writable:!0,value:V(`DISABLE_RUN_COMPRESSION`)===`true`}),Object.defineProperty(this,`debug`,{enumerable:!0,configurable:!0,writable:!0,value:os(`LANGSMITH_DEBUG`)===`true`});let n=e.getDefaultClientConfig();if(this.tracingSampleRate=nl(t.tracingSamplingRate),this.apiUrl=al(t.apiUrl??n.apiUrl)??``,this.apiUrl.endsWith(`/`)&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=al(t.apiKey??n.apiKey),this.webUrl=al(t.webUrl??n.webUrl),this.webUrl?.endsWith(`/`)&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=al(t.workspaceId??V(`WORKSPACE_ID`)),this.timeout_ms=t.timeout_ms??9e4,this.caller=new Us({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error(`Trace batch concurrency must be positive.`);this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation;let r=t.maxIngestMemoryBytes??1073741824;this.batchIngestCaller=new Us({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:r,...t.callerOptions??{},onFailedResponseHook:ol,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??n.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??n.hideOutputs,this.omitTracedRuntimeInfo=t.omitTracedRuntimeInfo??!1,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new dl(r),this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,ls()&&(this.langSmithToOTELTranslator=new ws),this.cachedLSEnvVarsForMetadata=is(),t.cache===!0?this._cache=new qo:t.cache&&typeof t.cache==`object`?this._cache=t.cache:this._cache=void 0}static getDefaultClientConfig(){let e=V(`API_KEY`);return{apiUrl:V(`ENDPOINT`)??ul,apiKey:e,webUrl:void 0,hideInputs:V(`HIDE_INPUTS`)===`true`,hideOutputs:V(`HIDE_OUTPUTS`)===`true`}}getHostUrl(){return this.webUrl?this.webUrl:rl(this.apiUrl)?(this.webUrl=`http://localhost:3000`,this.webUrl):this.apiUrl.endsWith(`/api/v1`)?(this.webUrl=this.apiUrl.replace(`/api/v1`,``),this.webUrl):this.apiUrl.includes(`/api`)&&!this.apiUrl.split(`.`,1)[0].endsWith(`api`)?(this.webUrl=this.apiUrl.replace(`/api`,``),this.webUrl):this.apiUrl.split(`.`,1)[0].includes(`dev`)?(this.webUrl=`https://dev.smith.langchain.com`,this.webUrl):this.apiUrl.split(`.`,1)[0].includes(`eu`)?(this.webUrl=`https://eu.smith.langchain.com`,this.webUrl):this.apiUrl.split(`.`,1)[0].includes(`beta`)?(this.webUrl=`https://beta.smith.langchain.com`,this.webUrl):(this.webUrl=`https://smith.langchain.com`,this.webUrl)}get headers(){let e={"User-Agent":`langsmith-js/${Jo}`};return this.apiKey&&(e[`x-api-key`]=`${this.apiKey}`),this.workspaceId&&(e[`x-tenant-id`]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!==`/v1`&&this.apiUrl.slice(-4)!==`/v1/`?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs==`function`?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs==`function`?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){let t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){let n=t?.toString()??``,r=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let t=await this._fetch(r,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`fetch ${e}`),t})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,n){let r=Number(t.get(`offset`))||0,i=Number(t.get(`limit`))||100;for(;;){t.set(`offset`,String(r)),t.set(`limit`,String(i));let a=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{let t=await this._fetch(a,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`fetch ${e}`),t}),s=n?n(await o.json()):await o.json();if(s.length===0||(yield s,s.length<i))break;r+=s.length}}async*_getCursorPaginatedList(e,t=null,n=`POST`,r=`runs`){let i=t?{...t}:{};for(;;){let t=JSON.stringify(i),a=await(await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await U(r,`fetch ${e}`),r})).json();if(!a||!a[r])break;yield a[r];let o=a.cursors;if(!o||!o.next)break;i.cursor=o.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){let t=[];for(let n of e)this.filteredPostUuids.has(n.trace_id)?n.id===n.trace_id&&this.filteredPostUuids.delete(n.trace_id):t.push(n);return t}else{let t=[];for(let n of e){let e=n.trace_id??n.id;this.filteredPostUuids.has(e)||(n.id===e?this._shouldSample()?t.push(n):this.filteredPostUuids.add(e):t.push(n))}return t}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??25165824}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??ll}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[r,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!r.length){i();break}let a=r.reduce((e,t)=>{let n=t.apiUrl??this.apiUrl,r=t.apiKey??this.apiKey,i=t.apiKey===this.apiKey&&t.apiUrl===this.apiUrl?`default`:`${n}|${r}`;return e[i]||(e[i]=[]),e[i].push(t),e},{}),o=[];for(let[e,t]of Object.entries(a)){let n=this._processBatch(t,{apiUrl:e===`default`?void 0:e.split(`|`)[0],apiKey:e===`default`?void 0:e.split(`|`)[1]});o.push(n)}let s=Promise.all(o).finally(i);n.push(s)}return Promise.all(n)}async _processBatch(e,t){if(!e.length)return;let n=e.reduce((e,t)=>e+(t.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let r={runCreates:e.filter(e=>e.action===`create`).map(e=>e.item),runUpdates:e.filter(e=>e.action===`update`).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(r,{...t,useGzip:e,sizeBytes:n})}catch(e){if(Rc(e))this._multipartDisabled=!0,await this.batchIngestRuns(r,{...t,sizeBytes:n});else throw e}}else await this.batchIngestRuns(r,{...t,sizeBytes:n})}}catch(e){console.error(`Error exporting batch:`,e)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let t=new Map,n=[];for(let r of e)r.item.id&&r.otelContext&&(t.set(r.item.id,r.otelContext),r.action===`create`?n.push({operation:`post`,id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}):n.push({operation:`patch`,id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}));this.langSmithToOTELTranslator.exportBatch(n,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=tl(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;let n=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>r)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:r}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:r})},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){let e=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/info`,{method:`GET`,headers:{Accept:`application/json`},signal:AbortSignal.timeout(cl),...this.fetchOptions});return await U(e,`get server info`),e})).json();return this.debug&&console.log(`
9
+ === LangSmith Server Configuration ===
10
+ `+JSON.stringify(e,null,2)+`
11
+ `),e}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??`Unspecified status code`} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||=this._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=ys(),t=bs();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(t.active(),n)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;let n={...this.headers,"Content-Type":`application/json`},r=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let e=this._cloneCurrentOTELContext();this.processRunOperation({action:`create`,item:i,otelContext:e,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}let a=tl(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);t?.apiKey!==void 0&&(n[`x-api-key`]=t.apiKey),t?.workspaceId!==void 0&&(n[`x-tenant-id`]=t.workspaceId);let o=Zc(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{let e=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:`POST`,headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await U(e,`create run`,!0),e})}async batchIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;let r=await Promise.all(e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]),i=await Promise.all(t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]);if(r.length>0&&i.length>0){let e=r.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let n of i)n.id!==void 0&&e[n.id]?e[n.id]={...e[n.id],...n}:t.push(n);r=Object.values(e),i=t}let a={post:r,patch:i};if(!a.post.length&&!a.patch.length)return;let o={post:[],patch:[]};for(let e of[`post`,`patch`]){let t=e,n=a[t].reverse(),r=n.pop();for(;r!==void 0;)o[t].push(r),r=n.pop()}if(o.post.length>0||o.patch.length>0){let e=o.post.map(e=>e.id).concat(o.patch.map(e=>e.id)).join(`,`);await this._postBatchIngestRuns(Zc(o,`Ingesting runs with ids: ${e}`),n)}}async _postBatchIngestRuns(e,t){let n={...this.headers,"Content-Type":`application/json`,Accept:`application/json`};t?.apiKey!==void 0&&(n[`x-api-key`]=t.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:t?.sizeBytes},async()=>{let r=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:`POST`,headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await U(r,`batch create run`,!0),r})}async multipartIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;let r={},i=[];for(let t of e??[]){let e=await this.prepareRunCreateOrUpdateInputs(t);e.id!==void 0&&e.attachments!==void 0&&(r[e.id]=e.attachments),delete e.attachments,i.push(e)}let a=[];for(let e of t??[])a.push(await this.prepareRunCreateOrUpdateInputs(e));if(i.find(e=>e.trace_id===void 0||e.dotted_order===void 0)!==void 0)throw Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`);if(a.find(e=>e.trace_id===void 0||e.dotted_order===void 0)!==void 0)throw Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`);if(i.length>0&&a.length>0){let e=i.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let n of a)n.id!==void 0&&e[n.id]?e[n.id]={...e[n.id],...n}:t.push(n);i=Object.values(e),a=t}if(i.length===0&&a.length===0)return;let o=[],s=[];for(let[e,t]of[[`post`,i],[`patch`,a]])for(let n of t){let{inputs:t,outputs:i,events:a,extra:c,error:l,serialized:u,attachments:d,...f}=n,p={inputs:t,outputs:i,events:a,extra:c,error:l,serialized:u},m=Zc(f,`Serializing for multipart ingestion of run with id: ${f.id}`);s.push({name:`${e}.${f.id}`,payload:new Blob([m],{type:`application/json; length=${m.length}`})});for(let[t,n]of Object.entries(p)){if(n===void 0)continue;let r=Zc(n,`Serializing ${t} for multipart ingestion of run with id: ${f.id}`);s.push({name:`${e}.${f.id}.${t}`,payload:new Blob([r],{type:`application/json; length=${r.length}`})})}if(f.id!==void 0){let e=r[f.id];if(e){delete r[f.id];for(let[t,n]of Object.entries(e)){let e,r;if(Array.isArray(n)?[e,r]=n:(e=n.mimeType,r=n.data),t.includes(`.`)){console.warn(`Skipping attachment '${t}' for run ${f.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}s.push({name:`attachment.${f.id}.${t}`,payload:new Blob([r],{type:`${e}; length=${r.byteLength}`})})}}}o.push(`trace=${f.trace_id},id=${f.id}`)}await this._sendMultipartRequest(s,o.join(`; `),n)}async _createNodeFetchBody(e,t){let n=[];for(let r of e)n.push(new Blob([`--${t}\r\n`])),n.push(new Blob([`Content-Disposition: form-data; name="${r.name}"\r\n`,`Content-Type: ${r.payload.type}\r\n\r\n`])),n.push(r.payload),n.push(new Blob([`\r
12
+ `]));return n.push(new Blob([`--${t}--\r\n`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,t){let n=new TextEncoder;return new ReadableStream({async start(r){let i=async e=>{typeof e==`string`?r.enqueue(n.encode(e)):r.enqueue(e)};for(let n of e){await i(`--${t}\r\n`),await i(`Content-Disposition: form-data; name="${n.name}"\r\n`),await i(`Content-Type: ${n.payload.type}\r\n\r\n`);let e=n.payload.stream().getReader();try{let t;for(;!(t=await e.read()).done;)r.enqueue(t.value)}finally{e.releaseLock()}await i(`\r
13
+ `)}await i(`--${t}--\r\n`),r.close()}})}async _sendMultipartRequest(e,t,n){let r=`----LangSmithFormBoundary`+Math.random().toString(36).slice(2),i=La(),a=()=>this._createNodeFetchBody(e,r),o=()=>this._createMultipartStream(e,r),s=async e=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let t=await e(),i={...this.headers,"Content-Type":`multipart/form-data; boundary=${r}`};n?.apiKey!==void 0&&(i[`x-api-key`]=n.apiKey);let a=t;n?.useGzip&&typeof t==`object`&&`pipeThrough`in t&&(a=t.pipeThrough(new CompressionStream(`gzip`)),i[`Content-Encoding`]=`gzip`);let o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:`POST`,headers:i,body:a,duplex:`half`,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(o,`Failed to send multipart request`,!0),o});try{let e,r=!1;!i&&!this.multipartStreamingDisabled&&ts()!==`bun`?(r=!0,e=await s(o)):e=await s(a),(!this.multipartStreamingDisabled||r)&&e.status===422&&(n?.apiUrl??this.apiUrl)!==ul&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${t}".`),this.multipartStreamingDisabled=!0,e=await s(a))}catch(e){if(Rc(e))throw e;console.warn(`${e.message.trim()}\n\nContext: ${t}`)}}async updateRun(e,t,n){B(e),t.inputs&&=await this.processInputs(t.inputs),t.outputs&&=await this.processOutputs(t.outputs);let r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&r.trace_id!==void 0&&r.dotted_order!==void 0){let e=this._cloneCurrentOTELContext();if(t.end_time!==void 0&&r.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:`update`,item:r,otelContext:e,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:`update`,item:r,otelContext:e,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let i={...this.headers,"Content-Type":`application/json`};n?.apiKey!==void 0&&(i[`x-api-key`]=n.apiKey),n?.workspaceId!==void 0&&(i[`x-tenant-id`]=n.workspaceId);let a=Zc(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let t=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:`PATCH`,headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(t,`update run`,!0),t})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){B(e);let n=await this._get(`/runs/${e}`);return t&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:t,projectOpts:n}){if(t!==void 0){let e;e=t.session_id?t.session_id:n?.projectName?(await this.readProject({projectName:n?.projectName})).id:n?.projectId?n?.projectId:(await this.readProject({projectName:V(`PROJECT`)||`default`})).id;let r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${e}/r/${t.id}?poll=true`}else if(e!==void 0){let t=await this.readRun(e);if(!t.app_path)throw Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${t.app_path}`}else throw Error(`Must provide either runId or run`)}async _loadChildRuns(e){let t=await il(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},r={};t.sort((e,t)=>(e?.dotted_order??``).localeCompare(t?.dotted_order??``));for(let i of t){if(i.parent_run_id===null||i.parent_run_id===void 0)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 n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),r[i.id]=i)}e.child_runs=n[e.id]||[];for(let t in n)t!==e.id&&(r[t].child_runs=n[t]);return e}async*listRuns(e){let{projectId:t,projectName:n,parentRunId:r,traceId:i,referenceExampleId:a,startTime:o,executionOrder:s,isRoot:c,runType:l,error:u,id:d,query:f,filter:p,traceFilter:m,treeFilter:h,limit:g,select:_,order:v}=e,y=[];if(t&&(y=Array.isArray(t)?t:[t]),n){let e=Array.isArray(n)?n:[n],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));y.push(...t)}let b={session:y.length?y:null,run_type:l,reference_example:a,query:f,filter:p,trace_filter:m,tree_filter:h,execution_order:s,parent_run:r,start_time:o?o.toISOString():null,error:u,id:d,limit:g,trace:i,select:_||`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`.split(`.`),is_root:c,order:v};b.select.includes(`child_run_ids`)&&Va(`Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.`);let ee=0;for await(let e of this._getCursorPaginatedList(`/runs/query`,b))if(g){if(ee>=g)break;if(e.length+ee>g){yield*e.slice(0,g-ee);break}ee+=e.length,yield*e}else yield*e}async*listGroupRuns(e){let{projectId:t,projectName:n,groupBy:r,filter:i,startTime:a,endTime:o,limit:s,offset:c}=e,l={session_id:t||(await this.readProject({projectName:n})).id,group_by:r,filter:i,start_time:a?a.toISOString():null,end_time:o?o.toISOString():null,limit:Number(s)||100},u=Number(c)||0,d=`/runs/group`,f=`${this.apiUrl}${d}`;for(;;){let e={...l,offset:u},t=Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0)),n=JSON.stringify(t),{groups:r,total:i}=await(await this.caller.call(async()=>{let e=await this._fetch(f,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(e,`Failed to fetch ${d}`),e})).json();if(r.length===0)break;for(let e of r)yield e;if(u+=r.length,u>=i)break}}async getRunStats({id:e,trace:t,parentRun:n,runType:r,projectNames:i,projectIds:a,referenceExampleIds:o,startTime:s,endTime:c,error:l,query:u,filter:d,traceFilter:f,treeFilter:p,isRoot:m,dataSourceType:h}){let g=a||[];i&&(g=[...a||[],...await Promise.all(i.map(e=>this.readProject({projectName:e}).then(e=>e.id)))]);let _=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:n,run_type:r,session:g,reference_example:o,start_time:s,end_time:c,error:l,query:u,filter:d,trace_filter:f,tree_filter:p,is_root:m,data_source_type:h}).filter(([e,t])=>t!==void 0)),v=JSON.stringify(_);return await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/runs/stats`,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await U(e,`get run stats`),e})).json()}async shareRun(e,{shareId:t}={}){let n={run_id:e,share_token:t||Hi()};B(e);let r=JSON.stringify(n),i=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:`PUT`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await U(t,`share run`),t})).json();if(i===null||!(`share_token`in i))throw Error(`Invalid response from server`);return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){B(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:`DELETE`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`unshare run`,!0),t})}async readRunSharedLink(e){B(e);let t=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`read run shared link`),t})).json();if(!(t===null||!(`share_token`in t)))return`${this.getHostUrl()}/public/${t.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){let n=new URLSearchParams({share_token:e});if(t!==void 0)for(let e of t)n.append(`id`,e);return B(e),await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`list shared runs`),t})).json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw Error(`Either datasetId or datasetName must be given`);e||=(await this.readDataset({datasetName:t})).id,B(e);let n=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`read dataset shared schema`),t})).json();return n.url=`${this.getHostUrl()}/public/${n.share_token}/d`,n}async shareDataset(e,t){if(!e&&!t)throw Error(`Either datasetId or datasetName must be given`);e||=(await this.readDataset({datasetName:t})).id;let n={dataset_id:e};B(e);let r=JSON.stringify(n),i=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:`PUT`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await U(t,`share dataset`),t})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){B(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:`DELETE`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`unshare dataset`,!0),t})}async readSharedDataset(e){return B(e),await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`read shared dataset`),t})).json()}async listSharedExamples(e,t){let n={};t?.exampleIds&&(n.id=t.exampleIds);let r=new URLSearchParams;Object.entries(n).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>r.append(e,t)):r.append(e,t)});let i=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/examples?${r.toString()}`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`list shared examples`),t}),a=await i.json();if(!i.ok)throw`detail`in a?Error(`Failed to list shared examples.\nStatus: ${i.status}\nMessage: ${Array.isArray(a.detail)?a.detail.join(`
14
+ `):`Unspecified error`}`):Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(e=>({...e,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:n=null,upsert:r=!1,projectExtra:i=null,referenceDatasetId:a=null}){let o=r?`?upsert=true`:``,s=`${this.apiUrl}/sessions${o}`,c=i||{};n&&(c.metadata=n);let l={name:e,extra:c,description:t};a!==null&&(l.reference_dataset_id=a);let u=JSON.stringify(l);return await(await this.caller.call(async()=>{let e=await this._fetch(s,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(e,`create project`),e})).json()}async updateProject(e,{name:t=null,description:n=null,metadata:r=null,projectExtra:i=null,endTime:a=null}){let o=`${this.apiUrl}/sessions/${e}`,s=i;r&&(s={...s||{},metadata:r});let c=JSON.stringify({name:t,extra:s,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let e=await this._fetch(o,{method:`PATCH`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(e,`update project`),e})).json()}async hasProject({projectId:e,projectName:t}){let n=`/sessions`,r=new URLSearchParams;if(e!==void 0&&t!==void 0)throw Error(`Must provide either projectName or projectId, not both`);if(e!==void 0)B(e),n+=`/${e}`;else if(t!==void 0)r.append(`name`,t);else throw Error(`Must provide projectName or projectId`);let i=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${n}?${r}`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(e,`has project`),e});try{let e=await i.json();return i.ok?Array.isArray(e)?e.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:t,includeStats:n}){let r=`/sessions`,i=new URLSearchParams;if(e!==void 0&&t!==void 0)throw Error(`Must provide either projectName or projectId, not both`);if(e!==void 0)B(e),r+=`/${e}`;else if(t!==void 0)i.append(`name`,t);else throw Error(`Must provide projectName or projectId`);n!==void 0&&i.append(`include_stats`,n.toString());let a=await this._get(r,i),o;if(Array.isArray(a)){if(a.length===0)throw Error(`Project[id=${e}, name=${t}] not found`);o=a[0]}else o=a;return o}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw Error(`Must provide either projectName or projectId`);let n=await this.readProject({projectId:e,projectName:t}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw Error(`Must provide either datasetName or datasetId`);let n=await this.readDataset({datasetId:e,datasetName:t}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:`1`});for await(let t of this._getPaginated(`/sessions`,e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw Error(`No projects found to resolve tenant.`)}async*listProjects({projectIds:e,name:t,nameContains:n,referenceDatasetId:r,referenceDatasetName:i,includeStats:a,datasetVersion:o,referenceFree:s,metadata:c}={}){let l=new URLSearchParams;if(e!==void 0)for(let t of e)l.append(`id`,t);if(t!==void 0&&l.append(`name`,t),n!==void 0&&l.append(`name_contains`,n),r!==void 0)l.append(`reference_dataset`,r);else if(i!==void 0){let e=await this.readDataset({datasetName:i});l.append(`reference_dataset`,e.id)}a!==void 0&&l.append(`include_stats`,a.toString()),o!==void 0&&l.append(`dataset_version`,o),s!==void 0&&l.append(`reference_free`,s.toString()),c!==void 0&&l.append(`metadata`,JSON.stringify(c));for await(let e of this._getPaginated(`/sessions`,l))yield*e}async deleteProject({projectId:e,projectName:t}){let n;if(e===void 0&&t===void 0)throw Error(`Must provide projectName or projectId`);if(e!==void 0&&t!==void 0)throw Error(`Must provide either projectName or projectId, not both`);n=e===void 0?(await this.readProject({projectName:t})).id:e,B(n),await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:`DELETE`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(e,`delete session ${n} (${t})`,!0),e})}async uploadCsv({csvFile:e,fileName:t,inputKeys:n,outputKeys:r,description:i,dataType:a,name:o}){let s=`${this.apiUrl}/datasets/upload`,c=new FormData,l=new Blob([e],{type:`text/csv`});return c.append(`file`,l,t),n.forEach(e=>{c.append(`input_keys`,e)}),r.forEach(e=>{c.append(`output_keys`,e)}),i&&c.append(`description`,i),a&&c.append(`data_type`,a),o&&c.append(`name`,o),await(await this.caller.call(async()=>{let e=await this._fetch(s,{method:`POST`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(e,`upload CSV`),e})).json()}async createDataset(e,{description:t,dataType:n,inputsSchema:r,outputsSchema:i,metadata:a}={}){let o={name:e,description:t,extra:a?{metadata:a}:void 0};n&&(o.data_type=n),r&&(o.inputs_schema_definition=r),i&&(o.outputs_schema_definition=i);let s=JSON.stringify(o);return await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets`,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await U(e,`create dataset`),e})).json()}async readDataset({datasetId:e,datasetName:t}){let n=`/datasets`,r=new URLSearchParams({limit:`1`});if(e&&t)throw Error(`Must provide either datasetName or datasetId, not both`);if(e)B(e),n+=`/${e}`;else if(t)r.append(`name`,t);else throw Error(`Must provide datasetName or datasetId`);let i=await this._get(n,r),a;if(Array.isArray(i)){if(i.length===0)throw Error(`Dataset[id=${e}, name=${t}] not found`);a=i[0]}else a=i;return a}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes(`not found`))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:n,toVersion:r}){let i=e;if(i===void 0&&t===void 0)throw Error(`Must provide either datasetName or datasetId`);if(i!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);i===void 0&&(i=(await this.readDataset({datasetName:t})).id);let a=new URLSearchParams({from_version:typeof n==`string`?n:n.toISOString(),to_version:typeof r==`string`?r:r.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).id;else throw Error(`Must provide either datasetName or datasetId`);return(await(await this._getResponse(`/datasets/${e}/openai_ft`)).text()).trim().split(`
15
+ `).map(e=>JSON.parse(e))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:n,datasetName:r,datasetNameContains:i,metadata:a}={}){let o=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(n!==void 0)for(let e of n)o.append(`id`,e);r!==void 0&&o.append(`name`,r),i!==void 0&&o.append(`name_contains`,i),a!==void 0&&o.append(`metadata`,JSON.stringify(a));for await(let e of this._getPaginated(`/datasets`,o))yield*e}async updateDataset(e){let{datasetId:t,datasetName:n,...r}=e;if(!t&&!n)throw Error(`Must provide either datasetName or datasetId`);let i=t??(await this.readDataset({datasetName:n})).id;B(i);let a=JSON.stringify(r);return await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:`PATCH`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(e,`update dataset`),e})).json()}async updateDatasetTag(e){let{datasetId:t,datasetName:n,asOf:r,tag:i}=e;if(!t&&!n)throw Error(`Must provide either datasetName or datasetId`);let a=t??(await this.readDataset({datasetName:n})).id;B(a);let o=JSON.stringify({as_of:typeof r==`string`?r:r.toISOString(),tag:i});await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:`PUT`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await U(e,`update dataset tags`,!0),e})}async deleteDataset({datasetId:e,datasetName:t}){let n=`/datasets`,r=e;if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);if(t!==void 0&&(r=(await this.readDataset({datasetName:t})).id),r!==void 0)B(r),n+=`/${r}`;else throw Error(`Must provide datasetName or datasetId`);await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+n,{method:`DELETE`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(e,`delete ${n}`,!0),e})}async indexDataset({datasetId:e,datasetName:t,tag:n}){let r=e;if(!r&&!t)throw Error(`Must provide either datasetName or datasetId`);if(r&&t)throw Error(`Must provide either datasetName or datasetId, not both`);r||=(await this.readDataset({datasetName:t})).id,B(r);let i=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${r}/index`,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await U(e,`index dataset`),e})).json()}async similarExamples(e,t,n,{filter:r}={}){let i={limit:n,inputs:e};r!==void 0&&(i.filter=r),B(t);let a=JSON.stringify(i);return(await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${t}/search`,{headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:`POST`,body:a});return await U(e,`fetch similar examples`),e})).json()).examples}async createExample(e,t,n){if(pl(e)&&(t!==void 0||n!==void 0))throw Error(`Cannot provide outputs or options when using ExampleCreate object`);let r=t?n?.datasetId:e.dataset_id,i=t?n?.datasetName:e.dataset_name;if(r===void 0&&i===void 0)throw Error(`Must provide either datasetName or datasetId`);if(r!==void 0&&i!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);r===void 0&&(r=(await this.readDataset({datasetName:i})).id);let a=(t?n?.createdAt:e.created_at)||new Date,o;o=pl(e)?e:{inputs:e,outputs:t,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let s=await this._uploadExamplesMultipart(r,[o]);return await this.readExample(s.example_ids?.[0]??Hi())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let t=e,n=t[0].dataset_id,r=t[0].dataset_name;if(n===void 0&&r===void 0)throw Error(`Must provide either datasetName or datasetId`);if(n!==void 0&&r!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);n===void 0&&(n=(await this.readDataset({datasetName:r})).id);let i=await this._uploadExamplesMultipart(n,t);return await Promise.all(i.example_ids.map(e=>this.readExample(e)))}let{inputs:t,outputs:n,metadata:r,splits:i,sourceRunIds:a,useSourceRunIOs:o,useSourceRunAttachments:s,attachments:c,exampleIds:l,datasetId:u,datasetName:d}=e;if(t===void 0)throw Error(`Must provide inputs when using legacy parameters`);let f=u,p=d;if(f===void 0&&p===void 0)throw Error(`Must provide either datasetName or datasetId`);if(f!==void 0&&p!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);f===void 0&&(f=(await this.readDataset({datasetName:p})).id);let m=t.map((e,t)=>({dataset_id:f,inputs:e,outputs:n?.[t],metadata:r?.[t],split:i?.[t],id:l?.[t],attachments:c?.[t],source_run_id:a?.[t],use_source_run_io:o?.[t],use_source_run_attachments:s?.[t]})),h=await this._uploadExamplesMultipart(f,m);return await Promise.all(h.example_ids.map(e=>this.readExample(e)))}async createLLMExample(e,t,n){return this.createExample({input:e},{output:t},n)}async createChatExample(e,t,n){let r=e.map(e=>Ws(e)?Gs(e):e),i=Ws(t)?Gs(t):t;return this.createExample({input:r},{output:i},n)}async readExample(e){B(e);let t=`/examples/${e}`,{attachment_urls:n,...r}=await this._get(t),i=r;return n&&(i.attachments=Object.entries(n).reduce((e,[t,n])=>(e[t.slice(11)]={presigned_url:n.presigned_url,mime_type:n.mime_type},e),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:n,asOf:r,splits:i,inlineS3Urls:a,metadata:o,limit:s,offset:c,filter:l,includeAttachments:u}={}){let d;if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);if(e!==void 0)d=e;else if(t!==void 0)d=(await this.readDataset({datasetName:t})).id;else throw Error(`Must provide a datasetName or datasetId`);let f=new URLSearchParams({dataset:d}),p=r?typeof r==`string`?r:r?.toISOString():void 0;p&&f.append(`as_of`,p);let m=a??!0;if(f.append(`inline_s3_urls`,m.toString()),n!==void 0)for(let e of n)f.append(`id`,e);if(i!==void 0)for(let e of i)f.append(`splits`,e);if(o!==void 0){let e=JSON.stringify(o);f.append(`metadata`,e)}s!==void 0&&f.append(`limit`,s.toString()),c!==void 0&&f.append(`offset`,c.toString()),l!==void 0&&f.append(`filter`,l),u===!0&&[`attachment_urls`,`outputs`,`metadata`].forEach(e=>f.append(`select`,e));let h=0;for await(let e of this._getPaginated(`/examples`,f)){for(let t of e){let{attachment_urls:e,...n}=t,r=n;e&&(r.attachments=Object.entries(e).reduce((e,[t,n])=>(e[t.slice(11)]={presigned_url:n.presigned_url,mime_type:n.mime_type||void 0},e),{})),yield r,h++}if(s!==void 0&&h>=s)break}}async deleteExample(e){B(e);let t=`/examples/${e}`;await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+t,{method:`DELETE`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(e,`delete ${t}`,!0),e})}async deleteExamples(e,t){if(e.forEach(e=>B(e)),t?.hardDelete){let t=this._getPlatformEndpointPath(`datasets/examples/delete`);await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}${t}`,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,`hard delete examples`,!0),n})}else{let t=new URLSearchParams;e.forEach(e=>t.append(`example_ids`,e)),await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/examples?${t.toString()}`,{method:`DELETE`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(e,`delete examples`,!0),e})}}async updateExample(e,t){let n;n=t?e:e.id,B(n);let r;r=t?{id:n,...t}:e;let i;return i=r.dataset_id===void 0?(await this.readExample(n)).dataset_id:r.dataset_id,this._updateExamplesMultipart(i,[r])}async updateExamples(e){let t;return t=e[0].dataset_id===void 0?(await this.readExample(e[0].id)).dataset_id:e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:n,tag:r}){let i;if(i=e||(await this.readDataset({datasetName:t})).id,B(i),n&&r||!n&&!r)throw Error(`Exactly one of asOf and tag must be specified.`);let a=new URLSearchParams;return n!==void 0&&a.append(`as_of`,typeof n==`string`?n:n.toISOString()),r!==void 0&&a.append(`tag`,r),await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${a.toString()}`,{method:`GET`,headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(e,`read dataset version`),e})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:n}){let r;if(e===void 0&&t===void 0)throw Error(`Must provide dataset name or ID`);if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);r=e===void 0?(await this.readDataset({datasetName:t})).id:e,B(r);let i=new URLSearchParams,a=n?typeof n==`string`?n:n?.toISOString():void 0;return a&&i.append(`as_of`,a),await this._get(`/datasets/${r}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:n,exampleIds:r,remove:i=!1}){let a;if(e===void 0&&t===void 0)throw Error(`Must provide dataset name or ID`);if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);a=e===void 0?(await this.readDataset({datasetName:t})).id:e,B(a);let o={split_name:n,examples:r.map(e=>(B(e),e)),remove:i},s=JSON.stringify(o);await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${a}/splits`,{method:`PUT`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await U(e,`update dataset splits`,!0),e})}async createFeedback(e,t,{score:n,value:r,correction:i,comment:a,sourceInfo:o,feedbackSourceType:s=`api`,sourceRunId:c,feedbackId:l,feedbackConfig:u,projectId:d,comparativeExperimentId:f,sessionId:p,startTime:m}){if(!e&&!d)throw Error(`One of runId or projectId must be provided`);if(e&&d)throw Error(`Only one of runId or projectId can be provided`);let h={type:s??`api`,metadata:o??{}};c!==void 0&&h?.metadata!==void 0&&!h.metadata.__run&&(h.metadata.__run={run_id:c}),h?.metadata!==void 0&&h.metadata.__run?.run_id!==void 0&&B(h.metadata.__run.run_id);let g={id:l??Hi(),run_id:e,key:t,score:sl(n),value:r,correction:i,comment:a,feedback_source:h,comparative_experiment_id:f,feedbackConfig:u,session_id:p??d,start_time:m},_=JSON.stringify(g),v=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let e=await this._fetch(v,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await U(e,`create feedback`,!0),e}),g}async updateFeedback(e,{score:t,value:n,correction:r,comment:i}){let a={};t!=null&&(a.score=sl(t)),n!=null&&(a.value=n),r!=null&&(a.correction=r),i!=null&&(a.comment=i),B(e);let o=JSON.stringify(a);await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:`PATCH`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await U(t,`update feedback`,!0),t})}async readFeedback(e){B(e);let t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){B(e);let t=`/feedback/${e}`;await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+t,{method:`DELETE`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(e,`delete ${t}`,!0),e})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:n}={}){let r=new URLSearchParams;if(e)for(let t of e)B(t),r.append(`run`,t);if(t)for(let e of t)r.append(`key`,e);if(n)for(let e of n)r.append(`source`,e);for await(let e of this._getPaginated(`/feedback`,r))yield*e}async createPresignedFeedbackToken(e,t,{expiration:n,feedbackConfig:r}={}){let i={run_id:e,feedback_key:t,feedback_config:r};n?typeof n==`string`?i.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(i.expires_in=n):i.expires_in={hours:3};let a=JSON.stringify(i);return await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(e,`create presigned feedback token`),e})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:n,createdAt:r,description:i,metadata:a,id:o}){if(t.length===0)throw Error(`At least one experiment is required`);if(n||=(await this.readProject({projectId:t[0]})).reference_dataset_id,!n==null)throw Error(`A reference dataset is required`);let s={id:o,name:e,experiment_ids:t,reference_dataset_id:n,description:i,created_at:(r??new Date)?.toISOString(),extra:{}};a&&(s.extra.metadata=a);let c=JSON.stringify(s);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(e,`create comparative experiment`),e})).json()}async*listPresignedFeedbackTokens(e){B(e);let t=new URLSearchParams({run_id:e});for await(let e of this._getPaginated(`/feedback/tokens`,t))yield*e}_selectEvalResults(e){let t;return t=`results`in e?e.results:Array.isArray(e)?e:[e],t}async _logEvaluationFeedback(e,t,n){let r=this._selectEvalResults(e),i=[];for(let e of r){let r=n||{};e.evaluatorInfo&&(r={...e.evaluatorInfo,...r});let a=null;e.targetRunId?a=e.targetRunId:t&&(a=t.id),i.push(await this.createFeedback(a,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:r,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:`model`,sessionId:t?.session_id,startTime:t?.start_time}))}return[r,i]}async logEvaluationFeedback(e,t,n){let[r]=await this._logEvaluationFeedback(e,t,n);return r}async*listAnnotationQueues(e={}){let{queueIds:t,name:n,nameContains:r,limit:i}=e,a=new URLSearchParams;t&&t.forEach((e,t)=>{B(e,`queueIds[${t}]`),a.append(`ids`,e)}),n&&a.append(`name`,n),r&&a.append(`name_contains`,r),a.append(`limit`,(i===void 0?100:Math.min(i,100)).toString());let o=0;for await(let e of this._getPaginated(`/annotation-queues`,a))if(yield*e,o++,i!==void 0&&o>=i)break}async createAnnotationQueue(e){let{name:t,description:n,queueId:r,rubricInstructions:i}=e,a={name:t,description:n,id:r||Hi(),rubric_instructions:i},o=JSON.stringify(Object.fromEntries(Object.entries(a).filter(([e,t])=>t!==void 0)));return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await U(e,`create annotation queue`),e})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,`queueId`)}`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`read annotation queue`),t})).json()}async updateAnnotationQueue(e,t){let{name:n,description:r,rubricInstructions:i}=t,a=JSON.stringify({name:n,description:r,rubric_instructions:i});await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,`queueId`)}`,{method:`PATCH`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(t,`update annotation queue`,!0),t})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,`queueId`)}`,{method:`DELETE`,headers:{...this.headers,Accept:`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`delete annotation queue`,!0),t})}async addRunsToAnnotationQueue(e,t){let n=JSON.stringify(t.map((e,t)=>B(e,`runIds[${t}]`).toString()));await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,`queueId`)}/runs`,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(t,`add runs to annotation queue`,!0),t})}async getRunFromAnnotationQueue(e,t){let n=`/annotation-queues/${B(e,`queueId`)}/run`;return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${n}/${t}`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(e,`get run from annotation queue`),e})).json()}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,`queueId`)}/runs/${B(t,`queueRunId`)}`,{method:`DELETE`,headers:{...this.headers,Accept:`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,`delete run from annotation queue`,!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,`queueId`)}/size`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`get size from annotation queue`),t})).json()}async _currentTenantIsOwner(e){let t=await this._getSettings();return e==`-`||t.tenant_handle===e}async _ownerConflictError(e,t){let n=await this._getSettings();return Error(`Cannot ${e} for another tenant.\n
16
+ Current tenant: ${n.tenant_handle}\n
17
+ Requested tenant: ${t}`)}async _getLatestCommitHash(e){let t=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(t,`get latest commit hash`),t})).json();if(t.commits.length!==0)return t.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){let[n,r,i]=Fc(e),a=JSON.stringify({like:t});return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/likes/${n}/${r}`,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(e,`${t?`like`:`unlike`} prompt`),e})).json()}async _getPromptUrl(e){let[t,n,r]=Fc(e);if(await this._currentTenantIsOwner(t)){let e=await this._getSettings();return r===`latest`?`${this.getHostUrl()}/prompts/${n}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${n}/${r.substring(0,8)}?organizationId=${e.id}`}else return r===`latest`?`${this.getHostUrl()}/hub/${t}/${n}`:`${this.getHostUrl()}/hub/${t}/${n}/${r.substring(0,8)}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(let t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,e=>e.commits))yield*t}async*listPrompts(e){let t=new URLSearchParams;t.append(`sort_field`,e?.sortField??`updated_at`),t.append(`sort_direction`,`desc`),t.append(`is_archived`,(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append(`is_public`,e.isPublic.toString()),e?.query&&t.append(`query`,e.query);for await(let e of this._getPaginated(`/repos`,t,e=>e.repos))yield*e}async getPrompt(e){let[t,n,r]=Fc(e),i=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return e?.status===404?null:(await U(e,`get prompt`),e)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,t){let n=await this._getSettings();if(t?.isPublic&&!n.tenant_handle)throw Error(`Cannot create a public prompt without first
18
+
19
+ creating a LangChain Hub handle.
20
+ You can add a handle by creating a public prompt at:
21
+
22
+ https://smith.langchain.com/prompts`);let[r,i,a]=Fc(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError(`create a prompt`,r);let o={repo_handle:i,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},s=JSON.stringify(o),{repo:c}=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await U(e,`create prompt`),e})).json();return c}async createCommit(e,t,n){if(!await this.promptExists(e))throw Error(`Prompt does not exist, you must create it first.`);let[r,i,a]=Fc(e),o=n?.parentCommitHash===`latest`||!n?.parentCommitHash?await this._getLatestCommitHash(`${r}/${i}`):n?.parentCommitHash,s={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},c=JSON.stringify(s),l=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${r}/${i}`,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(e,`create commit`),e})).json();return this._getPromptUrl(`${r}/${i}${l.commit_hash?`:${l.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 n=new FormData;for(let e of t){let t=e.id,r=Zc({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}},`Serializing body for example with id: ${t}`),i=new Blob([r],{type:`application/json`});if(n.append(t,i),e.inputs){let r=Zc(e.inputs,`Serializing inputs for example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.inputs`,i)}if(e.outputs){let r=Zc(e.outputs,`Serializing outputs whle updating example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.outputs`,i)}if(e.attachments)for(let[r,i]of Object.entries(e.attachments)){let e,a;Array.isArray(i)?[e,a]=i:(e=i.mimeType,a=i.data);let o=new Blob([a],{type:`${e}; length=${a.byteLength}`});n.append(`${t}.attachment.${r}`,o)}if(e.attachments_operations){let r=Zc(e.attachments_operations,`Serializing attachments while updating example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.attachments_operations`,i)}}let r=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${r}/examples`)}`,{method:`PATCH`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(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 n=new FormData;for(let e of t){let t=(e.id??Hi()).toString(),r=Zc({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}`),i=new Blob([r],{type:`application/json`});if(n.append(t,i),e.inputs){let r=Zc(e.inputs,`Serializing inputs for uploaded example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.inputs`,i)}if(e.outputs){let r=Zc(e.outputs,`Serializing outputs for uploaded example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.outputs`,i)}if(e.attachments)for(let[r,i]of Object.entries(e.attachments)){let e,a;Array.isArray(i)?[e,a]=i:(e=i.mimeType,a=i.data);let o=new Blob([a],{type:`${e}; length=${a.byteLength}`});n.append(`${t}.attachment.${r}`,o)}}return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:`POST`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(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[n,r]=Fc(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError(`update a prompt`,n);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),Object.keys(i).length===0)throw Error(`No valid update options provided`);let a=JSON.stringify(i);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:`PATCH`,headers:{...this.headers,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(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,n,r]=Fc(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}/${n}`,{method:`DELETE`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(e,`delete prompt`),e})).json()}_getPromptCacheKey(e,t){return`${e}${t?`:with_model`:``}`}async _fetchPromptFromApi(e,t){let[n,r,i]=Fc(e),a=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${n}/${r}/${i}${t?.includeModel?`?include_model=true`:``}`,{method:`GET`,headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(e,`pull prompt commit`),e})).json();return{owner:n,repo:r,commit_hash:a.commit_hash,manifest:a.manifest,examples:a.examples}}async pullPromptCommit(e,t){if(!t?.skipCache&&this._cache){let n=this._getPromptCacheKey(e,t?.includeModel),r=this._cache.get(n);if(r)return r;let i=await this._fetchPromptFromApi(e,t);return this._cache.set(n,i),i}return this._fetchPromptFromApi(e,t)}async _pullPrompt(e,t){let n=await this.pullPromptCommit(e,{includeModel:t?.includeModel,skipCache:t?.skipCache});return JSON.stringify(n.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(e=>e!==`object`)&&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}):await this._getPromptUrl(e)}async clonePublicDataset(t,n={}){let{sourceApiUrl:r=this.apiUrl,datasetName:i}=n,[a,o]=this.parseTokenOrUrl(t,r),s=new e({apiUrl:a,apiKey:`placeholder`}),c=await s.readSharedDataset(o),l=i||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}let u=await s.listSharedExamples(o),d=await this.createDataset(l,{description:c.description,dataType:c.data_type||`kv`,inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(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,n=2,r=`dataset`){try{return B(e),[t,e]}catch{}try{let i=new URL(e).pathname.split(`/`).filter(e=>e!==``);if(i.length>=n)return[t,i[i.length-n]];throw Error(`Invalid public ${r} URL: ${e}`)}catch{throw Error(`Invalid public ${r} URL or token: ${e}`)}}get cache(){return this._cache}cleanup(){this._cache&&this._cache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await new Promise(e=>setTimeout(e,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await xs()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}};function pl(e){return`dataset_id`in e||`dataset_name`in e}var ml=e=>e===void 0?!![`TRACING_V2`,`TRACING`].find(e=>V(e)===`true`):e,hl=Symbol.for(`lc:context_variables`),gl=Symbol.for(`langsmith:replica_trace_roots`);function _l(e,t){if(hl in e)return e[hl][t]}function vl(e,t,n){let r=hl in e?e[hl]:{};r[t]=n,e[hl]=r}var yl=36,bl=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`;function xl(e){return Ki(Object.keys(e).sort().map(t=>`${t}:${e[t]??``}`).join(`|`),bl)}function Sl(e){return e.replace(/[-:.]/g,``)}function Cl(e,t=1){let n=t.toFixed(0).slice(0,3).padStart(3,`0`);return`${new Date(e).toISOString().slice(0,-1)}${n}Z`}function wl(e,t,n=1){let r=Cl(e,n);return{dottedOrder:Sl(r)+t,microsecondPrecisionDatestring:r}}var Tl=new Set([`projectName`,`updates`,`reroot`]);function El(e){let t={};for(let n of Object.keys(e))Tl.has(n)&&(t[n]=e[n]);return t}var Dl=class e{constructor(e,t,n,r){Object.defineProperty(this,`metadata`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`tags`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`project_name`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,`replicas`,{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=n,this.replicas=r}static fromHeader(t){let n=t.split(`,`),r={},i=[],a,o;for(let e of n){let[t,n]=e.split(`=`),s=decodeURIComponent(n);t===`langsmith-metadata`?r=JSON.parse(s):t===`langsmith-tags`?i=s.split(`,`):t===`langsmith-project`?a=s:t===`langsmith-replicas`&&(o=JSON.parse(s).map(e=>Array.isArray(e)?e:El(e)))}return new e(r,i,a,o)}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(`,`)}},Ol=class e{constructor(t){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}),kl(t)){Object.assign(this,{...t});return}let n=e.getDefaultConfig(),{metadata:r,...i}=t,a=i.client??e.getSharedClient(),o={...r,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:o},`id`in i&&i.id==null&&delete i.id,Object.assign(this,{...n,...i,client:a}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=Cl(this.start_time,this.execution_order)),this.id||=Lo(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=Fl(this.replicas),!this.dotted_order){let{dottedOrder:e}=wl(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:za(),child_runs:[],api_url:os(`LANGCHAIN_ENDPOINT`)??`http://localhost:1984`,api_key:os(`LANGCHAIN_API_KEY`),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return e.sharedClient||=new fl,e.sharedClient}createChild(t){let n=this.child_execution_order+1,r=this.replicas?.map(e=>{let{reroot:t,...n}=e;return n}),i=t.replicas??r,a=new e({...t,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n});hl in this&&(a[hl]=this[hl]);let o=Symbol.for(`lc:child_config`),s=t.extra?.[o]??this.extra[o];if(Nl(s)){let e={...s},t=Ml(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:a.id}),t.handlers?.find(Al)?.updateFromRunTree?.(a),e.callbacks=t),a.extra[o]=e}let c=new Set,l=this;for(;l!=null&&!c.has(l.id);)c.add(l.id),l.child_execution_order=Math.max(l.child_execution_order,n),l=l.parent_run;return this.child_runs.push(a),a}async end(e,t,n=Date.now(),r){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??n,r&&Object.keys(r).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...r}}:{metadata:r})}_convertToCreate(e,t,n=!0){let r=e.extra??{};if(r?.runtime?.library===void 0&&(r.runtime||={},t))for(let[e,n]of Object.entries(t))r.runtime[e]||(r.runtime[e]=n);let i,a;return n?(a=e.parent_run?.id??e.parent_run_id,i=[]):(i=e.child_runs.map(e=>this._convertToCreate(e,t,n)),a=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:r,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:i,parent_run_id:a,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 n=t.dotted_order.split(`.`),r=null;for(let t=0;t<n.length;t++)if(n[t].slice(-yl)===e){r=t;break}if(r!==null){let e=n.slice(r+1);t.dotted_order=e.join(`.`),e.length>0?t.trace_id=e[0].slice(-yl):t.trace_id=t.id}}t.parent_run_id===e&&(t.parent_run_id=void 0)}_setReplicaTraceRoot(e,t){let n=_l(this,gl)??{};n[e]=t,vl(this,gl,n);for(let n of this.child_runs)n._setReplicaTraceRoot(e,t)}_remapForProject(e){let{projectName:t,runtimeEnv:n,excludeChildRuns:r=!0,reroot:i=!1,distributedParentId:a,apiUrl:o,apiKey:s,workspaceId:c}=e,l=this._convertToCreate(this,n,r);if(t===this.project_name)return{...l,session_name:t};if(i){if(a)this._sliceParentId(a,l);else if(l.parent_run_id=void 0,l.dotted_order){let e=l.dotted_order.split(`.`);e.length>0&&(l.dotted_order=e[e.length-1],l.trace_id=l.id)}let e=xl({projectName:t,apiUrl:o,apiKey:s,workspaceId:c});this._setReplicaTraceRoot(e,l.id)}let u;if(!i&&(u=(_l(this,gl)??{})[xl({projectName:t,apiUrl:o,apiKey:s,workspaceId:c})],u&&(l.trace_id=u,l.dotted_order))){let e=l.dotted_order.split(`.`),t=null;for(let n=0;n<e.length;n++)if(e[n].slice(-yl)===u){t=n;break}t!==null&&(l.dotted_order=e.slice(t).join(`.`))}let d=l.id,f=Uo(d,t),p;p=l.trace_id?Uo(l.trace_id,t):f;let m;l.parent_run_id&&(m=Uo(l.parent_run_id,t));let h;return l.dotted_order&&(h=l.dotted_order.split(`.`).map(e=>{let n=Uo(e.slice(-yl),t);return e.slice(0,-yl)+n}).join(`.`)),{...l,id:f,trace_id:p,parent_run_id:m,dotted_order:h,session_name:t}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let t=rs();if(this.replicas&&this.replicas.length>0)for(let{projectName:e,apiKey:n,apiUrl:r,workspaceId:i,reroot:a}of this.replicas){let o=this._remapForProject({projectName:e??this.project_name,runtimeEnv:t,excludeChildRuns:!0,reroot:a,distributedParentId:this.distributedParentId,apiUrl:r,apiKey:n,workspaceId:i});await this.client.createRun(o,{apiKey:n,apiUrl:r,workspaceId:i})}else{let n=this._convertToCreate(this,t,e);await this.client.createRun(n)}if(!e){Va(`Posting with excludeChildRuns=false is deprecated and will be removed in a future version.`);for(let e of 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:n,apiUrl:r,workspaceId:i,updates:a,reroot:o}of this.replicas){let s=this._remapForProject({projectName:t??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:r,apiKey:n,workspaceId:i}),c={id:s.id,name:s.name,run_type:s.run_type,start_time:s.start_time,outputs:s.outputs,error:s.error,parent_run_id:s.parent_run_id,session_name:s.session_name,reference_example_id:s.reference_example_id,end_time:s.end_time,dotted_order:s.dotted_order,trace_id:s.trace_id,events:s.events,tags:s.tags,extra:s.extra,attachments:this.attachments,...a};e?.excludeInputs||(c.inputs=s.inputs),await this.client.updateRun(s.id,c,{apiKey:n,apiUrl:r,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||=[],typeof e==`string`?this.events.push({name:`event`,time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(t,n){let r=t?.callbacks,i,a,o,s=ml();if(r){let e=r?.getParentRunId?.()??``,t=r?.handlers?.find(e=>e?.name==`langchain_tracer`);i=t?.getRun?.(e),a=t?.projectName,o=t?.client,s||=!!t}return i?new e({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:o,tracingEnabled:s,project_name:a,tags:[...new Set((i?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...t?.metadata}}}).createChild(n):new e({...n,client:o,tracingEnabled:s,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(t,n){let r=`get`in t&&typeof t.get==`function`?{"langsmith-trace":t.get(`langsmith-trace`),baggage:t.get(`baggage`)}:t,i=r[`langsmith-trace`];if(!i||typeof i!=`string`)return;let a=i.trim(),o=a.split(`.`).map(e=>{let[t,n]=e.split(`Z`);return{strTime:t,time:Date.parse(t+`Z`),uuid:n}}),s=o[0].uuid,c={...n,name:n?.name??`parent`,run_type:n?.run_type??`chain`,start_time:n?.start_time??Date.now(),id:o.at(-1)?.uuid,trace_id:s,dotted_order:a};if(r.baggage&&typeof r.baggage==`string`){let e=Dl.fromHeader(r.baggage);c.metadata=e.metadata,c.tags=e.tags,c.project_name=e.project_name,c.replicas=e.replicas}let l=new e(c);return l.distributedParentId=l.id,l}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new Dl(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,r]of Object.entries(t))e.set(n,r);return t}};Object.defineProperty(Ol,`sharedClient`,{enumerable:!0,configurable:!0,writable:!0,value:null});function kl(e){return e!=null&&typeof e.createChild==`function`&&typeof e.postRun==`function`}function Al(e){return typeof e==`object`&&!!e&&typeof e.name==`string`&&e.name===`langchain_tracer`}function jl(e){return Array.isArray(e)&&e.some(e=>Al(e))}function Ml(e){return typeof e==`object`&&!!e&&Array.isArray(e.handlers)}function Nl(e){let t=e?.callbacks;return e!=null&&typeof t==`object`&&(jl(t?.handlers)||jl(t))}function Pl(){let e=os(`LANGSMITH_RUNS_ENDPOINTS`);if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t)){let e=[];for(let n of t){if(typeof n!=`object`||!n){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!=`string`){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!=`string`){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}e.push({apiUrl:n.api_url.replace(/\/$/,``),apiKey:n.api_key})}return e}else if(typeof t==`object`&&t){Il(t);let e=[];for(let[n,r]of Object.entries(t)){let t=n.replace(/\/$/,``);if(typeof r==`string`)e.push({apiUrl:t,apiKey:r});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof r}`);continue}}return e}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof t}`),[]}catch(e){if(Vc(e))throw e;return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey`),[]}}function Fl(e){return e?e.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Pl()}function Il(e){if(Object.keys(e).length>0&&V(`ENDPOINT`))throw new Bc}var Ll={};A(Ll,{BaseTracer:()=>Hl,isBaseTracer:()=>Vl});var Rl=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function zl(e,t){if(e)return new Ol({...e,start_time:e._serialized_start_time??e.start_time,parent_run:zl(t),child_runs:e.child_runs.map(e=>zl(e)).filter(e=>e!==void 0),extra:{...e.extra,runtime:Di()},tracingEnabled:!1})}function Bl(e,t){return e&&!Array.isArray(e)&&typeof e==`object`?e:{[t]:e}}function Vl(e){return typeof e._addRunToRunMap==`function`}var Hl=class extends ea{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?Rl(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`\n\n${e.stack}`:``):typeof e==`string`?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:t,microsecondPrecisionDatestring:n}=wl(new Date(e.start_time).getTime(),e.id,e.execution_order),r={...e},i=this.getRunById(r.parent_run_id);if(r.parent_run_id===void 0?(r.trace_id=r.id,r.dotted_order=t,r._serialized_start_time=n):i?(this._addChildRun(i,r),i.child_execution_order=Math.max(i.child_execution_order,r.child_execution_order),r.trace_id=i.trace_id,i.dotted_order!==void 0&&(r.dotted_order=[i.dotted_order,t].join(`.`),r._serialized_start_time=n)):r.parent_run_id=void 0,this.usesRunTreeMap){let e=zl(r,i);e!==void 0&&this.runTreeMap.set(r.id,e)}else this.runMap.set(r.id,r);return r}async _endTrace(e){let t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,r,i,a,o,s){let c=this._getExecutionOrder(r),l=Date.now(),u=o?{...i,metadata:o}:i,d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:`start`,time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:`llm`,extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForLLMStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,n,r,i,a,o,s){let c=this._getExecutionOrder(r),l=Date.now(),u=o?{...i,metadata:o}:i,d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:`start`,time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:`llm`,extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,n,r,i){let a=this.getRunById(t);if(!a||a?.run_type!==`llm`)throw Error(`No LLM run to end.`);return a.end_time=Date.now(),a.outputs=e,a.events.push({name:`end`,time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(e,t,n,r,i){let a=this.getRunById(t);if(!a||a?.run_type!==`llm`)throw Error(`No LLM run to end.`);return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:`error`,time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(e,t,n,r,i,a,o,s,c){let l=this._getExecutionOrder(r),u=Date.now(),d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:u,serialized:e,events:[{name:`start`,time:new Date(u).toISOString()}],inputs:t,execution_order:l,child_execution_order:l,run_type:o??`chain`,child_runs:[],extra:a?{...c,metadata:a}:{...c},tags:i||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForChainStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,n,r,i){let a=this.getRunById(t);if(!a)throw Error(`No chain run to end.`);return a.end_time=Date.now(),a.outputs=Bl(e,`output`),a.events.push({name:`end`,time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Bl(i.inputs,`input`)),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,t,n,r,i){let a=this.getRunById(t);if(!a)throw Error(`No chain run to end.`);return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:`error`,time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Bl(i.inputs,`input`)),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(e,t,n,r,i,a,o){let s=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:`start`,time:new Date(c).toISOString()}],inputs:{input:t},execution_order:s,child_execution_order:s,run_type:`tool`,child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,n,r,i,a,o){let s=this.getRunById(n)??this._createRunForToolStart(e,t,n,r,i,a,o);return await this.onRunCreate?.(s),await this.onToolStart?.(s),s}async handleToolEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`tool`)throw Error(`No tool run to end`);return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:`end`,time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`tool`)throw Error(`No tool run to end`);return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:`error`,time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`chain`)return;let r=n;r.actions=r.actions||[],r.actions.push(e),r.events.push({name:`agent_action`,time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(n)}async handleAgentEnd(e,t){let n=this.getRunById(t);!n||n?.run_type!==`chain`||(n.events.push({name:`agent_end`,time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(n))}_createRunForRetrieverStart(e,t,n,r,i,a,o){let s=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:`start`,time:new Date(c).toISOString()}],inputs:{query:t},execution_order:s,child_execution_order:s,run_type:`retriever`,child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,n,r,i,a,o){let s=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,r,i,a,o);return await this.onRunCreate?.(s),await this.onRetrieverStart?.(s),s}async handleRetrieverEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`retriever`)throw Error(`No retriever run to end`);return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:`end`,time:new Date(n.end_time).toISOString()}),await this.onRetrieverEnd?.(n),await this._endTrace(n),n}async handleRetrieverError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`retriever`)throw Error(`No retriever run to end`);return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:`error`,time:new Date(n.end_time).toISOString()}),await this.onRetrieverError?.(n),await this._endTrace(n),n}async handleText(e,t){let n=this.getRunById(t);!n||n?.run_type!==`chain`||(n.events.push({name:`text`,time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(n))}async handleLLMNewToken(e,t,n,r,i,a){let o=this.getRunById(n);if(!o||o?.run_type!==`llm`)throw Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`);return o.events.push({name:`new_token`,time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:a?.chunk}}),await this.onLLMNewToken?.(o,e,{chunk:a?.chunk}),o}},Ul=e(n(((e,t)=>{var n=10,r=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,i=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`;function a(){let e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[n,r]of Object.entries(t)){for(let[n,i]of Object.entries(r))t[n]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[n]=t[n],e.set(i[0],i[1]);Object.defineProperty(t,n,{value:r,enumerable:!1})}return Object.defineProperty(t,`codes`,{value:e,enumerable:!1}),t.color.close=`\x1B[39m`,t.bgColor.close=`\x1B[49m`,t.color.ansi256=r(),t.color.ansi16m=i(),t.bgColor.ansi256=r(n),t.bgColor.ansi16m=i(n),Object.defineProperties(t,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:n}=t.groups;n.length===3&&(n=n.split(``).map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>t.rgbToAnsi256(...t.hexToRgb(e)),enumerable:!1}}),t}Object.defineProperty(t,`exports`,{enumerable:!0,get:a})}))(),1),Wl={};A(Wl,{ConsoleCallbackHandler:()=>Xl});function Gl(e,t){return`${e.open}${t}${e.close}`}function Kl(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function ql(e){return typeof e==`string`?e.trim():e==null?e:Kl(e,e.toString())}function Jl(e){if(!e.end_time)return``;let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}var{color:Yl}=Ul.default,Xl=class extends Hl{name=`console_callback_handler`;persistRun(e){return Promise.resolve()}getParents(e){let t=[],n=e;for(;n.parent_run_id;){let e=this.runMap.get(n.parent_run_id);if(e)t.push(e),n=e;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((e,t,n)=>{let r=`${e.execution_order}:${e.run_type}:${e.name}`;return t===n.length-1?Gl(Ul.default.bold,r):r}).join(` > `);return Gl(Yl.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${Gl(Yl.green,`[chain/start]`)} [${t}] Entering Chain run with input: ${Kl(e.inputs,`[inputs]`)}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Gl(Yl.cyan,`[chain/end]`)} [${t}] [${Jl(e)}] Exiting Chain run with output: ${Kl(e.outputs,`[outputs]`)}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${Gl(Yl.red,`[chain/error]`)} [${t}] [${Jl(e)}] Chain run errored with error: ${Kl(e.error,`[error]`)}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),n=`prompts`in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${Gl(Yl.green,`[llm/start]`)} [${t}] Entering LLM run with input: ${Kl(n,`[inputs]`)}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Gl(Yl.cyan,`[llm/end]`)} [${t}] [${Jl(e)}] Exiting LLM run with output: ${Kl(e.outputs,`[response]`)}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${Gl(Yl.red,`[llm/error]`)} [${t}] [${Jl(e)}] LLM run errored with error: ${Kl(e.error,`[error]`)}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${Gl(Yl.green,`[tool/start]`)} [${t}] Entering Tool run with input: "${ql(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Gl(Yl.cyan,`[tool/end]`)} [${t}] [${Jl(e)}] Exiting Tool run with output: "${ql(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${Gl(Yl.red,`[tool/error]`)} [${t}] [${Jl(e)}] Tool run errored with error: ${Kl(e.error,`[error]`)}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${Gl(Yl.green,`[retriever/start]`)} [${t}] Entering Retriever run with input: ${Kl(e.inputs,`[inputs]`)}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Gl(Yl.cyan,`[retriever/end]`)} [${t}] [${Jl(e)}] Exiting Retriever run with output: ${Kl(e.outputs,`[outputs]`)}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${Gl(Yl.red,`[retriever/error]`)} [${t}] [${Jl(e)}] Retriever run errored with error: ${Kl(e.error,`[error]`)}`)}onAgentAction(e){let t=e,n=this.getBreadcrumbs(e);console.log(`${Gl(Yl.blue,`[agent/action]`)} [${n}] Agent selected action: ${Kl(t.actions[t.actions.length-1],`[action]`)}`)}},Zl,Ql=()=>(Zl===void 0&&(Zl=new fl(Oi(`LANGCHAIN_CALLBACKS_BACKGROUND`)===`false`?{blockOnRootRunFinalization:!0}:{})),Zl),$l=class{getStore(){}run(e,t){return t()}},eu=Symbol.for(`ls:tracing_async_local_storage`),tu=new $l,nu=new class{getInstance(){return globalThis[eu]??tu}initializeGlobalInstance(e){globalThis[eu]===void 0&&(globalThis[eu]=e)}};function ru(e=!1){let t=nu.getInstance().getStore();if(!e&&t===void 0)throw Error(`Could not get the current run tree.
23
+
24
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function iu(e){return typeof e==`function`&&`langsmith:traceable`in e}var au={};A(au,{LangChainTracer:()=>su});function ou(e){let t;for(let n of e)for(let e of n)$r.isInstance(e.message)&&e.message.usage_metadata!==void 0&&(t=tr(t,e.message.usage_metadata));return t}var su=class e extends Hl{name=`langchain_tracer`;projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);let{exampleId:n,projectName:r,client:i,replicas:a}=t;this.projectName=r??za(),this.replicas=a,this.exampleId=n,this.client=i??Ql();let o=e.getTraceableRunTree();o&&this.updateFromRunTree(o)}async persistRun(e){}async onRunCreate(e){e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(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 n=ou(t.generations);if(n!==void 0){e.extra=e.extra??{};let t=e.extra.metadata??{};t.usage_metadata=n,e.extra.metadata=t}}}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e,n=new Set;for(;t.parent_run&&!(n.has(t.id)||(n.add(t.id),!t.parent_run));)t=t.parent_run;n.clear();let r=[t];for(;r.length>0;){let e=r.shift();!e||n.has(e.id)||(n.add(e.id),this.runTreeMap.set(e.id,e),e.child_runs&&r.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}getRunTreeWithTracingConfig(e){let t=this.runTreeMap.get(e);if(t)return new Ol({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return ru(!0)}catch{return}}},cu;function lu(){return new(`default`in Vs.default?Vs.default.default:Vs.default)({autoStart:!0,concurrency:1})}function uu(){return cu===void 0&&(cu=lu()),cu}async function W(e,t){if(t===!0){let t=vi();t===void 0?await e():await t.run(void 0,async()=>e())}else cu=uu(),cu.add(async()=>{let t=vi();t===void 0?await e():await t.run(void 0,async()=>e())})}async function du(){let e=Ql();await Promise.allSettled([cu===void 0?Promise.resolve():cu.onIdle(),e.awaitPendingTraceBatches()])}var fu={};A(fu,{awaitAllCallbacks:()=>du,consumeCallback:()=>W});var pu=e=>e===void 0?!![`LANGSMITH_TRACING_V2`,`LANGCHAIN_TRACING_V2`,`LANGSMITH_TRACING`,`LANGCHAIN_TRACING`].find(e=>Oi(e)===`true`):e;function mu(e){let t=vi();if(t!==void 0)return t.getStore()?.[gi]?.[e]}var hu=Symbol(`lc:configure_hooks`),gu=()=>mu(hu)||[],_u={};A(_u,{BaseCallbackManager:()=>yu,BaseRunManager:()=>bu,CallbackManager:()=>Tu,CallbackManagerForChainRun:()=>Cu,CallbackManagerForLLMRun:()=>Su,CallbackManagerForRetrieverRun:()=>xu,CallbackManagerForToolRun:()=>wu,ensureHandler:()=>Eu,parseCallbackConfigArg:()=>vu});function vu(e){return e?Array.isArray(e)||`name`in e?{callbacks:e}:e:{}}var yu=class{setHandler(e){return this.setHandlers([e])}},bu=class{constructor(e,t,n,r,i,a,o,s){this.runId=e,this.handlers=t,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=i,this.metadata=a,this.inheritableMetadata=o,this._parentRunId=s}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>W(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,n,r,i){await Promise.all(this.handlers.map(n=>W(async()=>{try{await n.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleCustomEvent: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}},xu=class extends bu{getChild(e){let t=new Tu(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=>W(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=>W(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${n}`),t.raiseError)throw e}},t.awaitHandlers)))}},Su=class extends bu{async handleLLMNewToken(e,t,n,r,i,a){await Promise.all(this.handlers.map(n=>W(async()=>{if(!n.ignoreLLM)try{await n.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMNewToken: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}async handleLLMError(e,t,n,r,i){await Promise.all(this.handlers.map(t=>W(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,n,r,i){await Promise.all(this.handlers.map(t=>W(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)))}},Cu=class extends bu{getChild(e){let t=new Tu(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,n,r,i){await Promise.all(this.handlers.map(t=>W(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,n,r,i){await Promise.all(this.handlers.map(t=>W(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=>W(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=>W(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)))}},wu=class extends bu{getChild(e){let t=new Tu(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=>W(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 handleToolEnd(e){await Promise.all(this.handlers.map(t=>W(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)))}},Tu=class e extends yu{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,n=void 0,r=void 0,i=void 0,a=void 0,o=void 0,s=void 0){return Promise.all(t.map(async(t,r)=>{let a=r===0&&n?n:Xi();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return Vl(n)&&n._createRunForLLMStart(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s),W(async()=>{try{await n.handleLLMStart?.(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new Su(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,n=void 0,r=void 0,i=void 0,a=void 0,o=void 0,s=void 0){return Promise.all(t.map(async(t,r)=>{let a=r===0&&n?n:Xi();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return Vl(n)&&n._createRunForChatModelStart(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s),W(async()=>{try{if(n.handleChatModelStart)await n.handleChatModelStart?.(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s);else if(n.handleLLMStart){let r=ci(t);await n.handleLLMStart?.(e,[r],a,this._parentRunId,i,this.tags,this.metadata,s)}}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new Su(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,n=Xi(),r=void 0,i=void 0,a=void 0,o=void 0,s=void 0,c=void 0){return await Promise.all(this.handlers.map(i=>{if(!i.ignoreChain)return Vl(i)&&i._createRunForChainStart(e,t,n,this._parentRunId,this.tags,this.metadata,r,o,c),W(async()=>{try{await i.handleChainStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,r,o,c)}catch(e){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainStart: ${e}`),i.raiseError)throw e}},i.awaitHandlers)})),new Cu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,n=Xi(),r=void 0,i=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreAgent)return Vl(r)&&r._createRunForToolStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),W(async()=>{try{await r.handleToolStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleToolStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new wu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,n=Xi(),r=void 0,i=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreRetriever)return Vl(r)&&r._createRunForRetrieverStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),W(async()=>{try{await r.handleRetrieverStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleRetrieverStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new xu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,n,r,i){await Promise.all(this.handlers.map(r=>W(async()=>{if(!r.ignoreCustomEvent)try{await r.handleCustomEvent?.(e,t,n,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)))}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){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,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=[],n=!0){let r=new e(this._parentRunId);for(let e of this.handlers){let t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(let e of this.tags){let t=this.inheritableTags.includes(e);r.addTags([e],t)}for(let e of Object.keys(this.metadata)){let t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(let e of t)r.handlers.filter(e=>e.name===`console_callback_handler`).some(t=>t.name===e.name)||r.addHandler(e,n);return r}static fromHandlers(e){class t extends ea{name=Xi();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new t),n}static configure(e,t,n,r,i,a,o){return this._configureSync(e,t,n,r,i,a,o)}static _configureSync(t,n,r,i,a,o,s){let c;(t||n)&&(Array.isArray(t)||!t?(c=new e,c.setHandlers(t?.map(Eu)??[],!0)):c=t,c=c.copy(Array.isArray(n)?n.map(Eu):n?.handlers,!1));let l=Oi(`LANGCHAIN_VERBOSE`)===`true`||s?.verbose,u=su.getTraceableRunTree()?.tracingEnabled??pu(),d=u||(Oi(`LANGCHAIN_TRACING`)??!1);if(l||d){if(c||=new e,l&&!c.handlers.some(e=>e.name===Xl.prototype.name)){let e=new Xl;c.addHandler(e,!0)}if(d&&!c.handlers.some(e=>e.name===`langchain_tracer`)&&u){let e=new su;c.addHandler(e,!0)}if(u){let e=su.getTraceableRunTree();e&&c._parentRunId===void 0&&(c._parentRunId=e.id,c.handlers.find(e=>e.name===`langchain_tracer`)?.updateFromRunTree(e))}}for(let{contextVar:t,inheritable:n=!0,handlerClass:r,envVar:i}of gu()){let a=i&&Oi(i)===`true`&&r,o,s=t===void 0?void 0:mu(t);s&&ta(s)?o=s:a&&(o=new r({})),o!==void 0&&(c||=new e,c.handlers.some(e=>e.name===o.name)||c.addHandler(o,n))}return(r||i)&&c&&(c.addTags(r??[]),c.addTags(i??[],!1)),(a||o)&&c&&(c.addMetadata(a??{}),c.addMetadata(o??{},!1)),c}};function Eu(e){return`name`in e?e:ea.fromMethods(e)}var Du=class{getStore(){}run(e,t){return t()}enterWith(e){}},Ou=new Du,ku=Symbol.for(`lc:child_config`),Au=new class{getInstance(){return vi()??Ou}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[ku]}runWithConfig(e,t,n){let r=Tu._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),a=i.getStore(),o=r?.getParentRunId(),s=r?.handlers?.find(e=>e?.name===`langchain_tracer`),c;return s&&o?c=s.getRunTreeWithTracingConfig(o):n||(c=new Ol({name:`<runnable_lambda>`,tracingEnabled:!1})),c&&(c.extra={...c.extra,[ku]:e}),a!==void 0&&a[gi]!==void 0&&(c===void 0&&(c={}),c[gi]=a[gi]),i.run(c,t)}initializeGlobalInstance(e){vi()===void 0&&_i(e)}},ju={};A(ju,{AsyncLocalStorageProviderSingleton:()=>Au,MockAsyncLocalStorage:()=>Du,_CONTEXT_VARIABLES_KEY:()=>gi});async function Mu(e){return Tu._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function Nu(...e){let t={};for(let n of e.filter(e=>!!e))for(let e of Object.keys(n))if(e===`metadata`)t[e]={...t[e],...n[e]};else if(e===`tags`){let r=t[e]??[];t[e]=[...new Set(r.concat(n[e]??[]))]}else if(e===`configurable`)t[e]={...t[e],...n[e]};else if(e===`timeout`)t.timeout===void 0?t.timeout=n.timeout:n.timeout!==void 0&&(t.timeout=Math.min(t.timeout,n.timeout));else if(e===`signal`)t.signal===void 0?t.signal=n.signal:n.signal!==void 0&&(`any`in AbortSignal?t.signal=AbortSignal.any([t.signal,n.signal]):t.signal=n.signal);else if(e===`callbacks`){let e=t.callbacks,r=n.callbacks;if(Array.isArray(r))if(!e)t.callbacks=r;else if(Array.isArray(e))t.callbacks=e.concat(r);else{let n=e.copy();for(let e of r)n.addHandler(Eu(e),!0);t.callbacks=n}else if(r)if(!e)t.callbacks=r;else if(Array.isArray(e)){let n=r.copy();for(let t of e)n.addHandler(Eu(t),!0);t.callbacks=n}else t.callbacks=new Tu(r._parentRunId,{handlers:e.handlers.concat(r.handlers),inheritableHandlers:e.inheritableHandlers.concat(r.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(r.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(r.inheritableTags))),metadata:{...e.metadata,...r.metadata}})}else{let r=e;t[r]=n[r]??t[r]}return t}var Pu=new Set([`string`,`number`,`boolean`]);function G(e){let t=Au.getRunnableConfig(),n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:e,runName:r,...i}=t;n=Object.entries(i).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),n)}if(e&&(n=Object.entries(e).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),n)),n?.configurable)for(let e of Object.keys(n.configurable))Pu.has(typeof n.configurable[e])&&!n.metadata?.[e]&&(n.metadata||={},n.metadata[e]=n.configurable[e]);if(n.timeout!==void 0){if(n.timeout<=0)throw Error(`Timeout must be a positive number`);let e=n.timeout,t=AbortSignal.timeout(e);n.metadata||={},n.metadata.timeoutMs===void 0&&(n.metadata.timeoutMs=e),n.signal===void 0?n.signal=t:`any`in AbortSignal&&(n.signal=AbortSignal.any([n.signal,t])),delete n.timeout}return n}function K(e={},{callbacks:t,maxConcurrency:n,recursionLimit:r,runName:i,configurable:a,runId:o}={}){let s=G(e);return t!==void 0&&(delete s.runName,s.callbacks=t),r!==void 0&&(s.recursionLimit=r),n!==void 0&&(s.maxConcurrency=n),i!==void 0&&(s.runName=i),a!==void 0&&(s.configurable={...s.configurable,...a}),o!==void 0&&delete s.runId,s}function Fu(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 Iu(e,t){if(t===void 0)return e;let n;return Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,r)=>{n=()=>{r(Lu(t))},t.addEventListener(`abort`,n),t.aborted&&r(Lu(t))})]).finally(()=>t.removeEventListener(`abort`,n))}function Lu(e){return e?.reason instanceof Error?e.reason:typeof e?.reason==`string`?Error(e.reason):Error(`Aborted`)}var Ru={};A(Ru,{AsyncGeneratorWithSetup:()=>Hu,IterableReadableStream:()=>zu,atee:()=>Bu,concat:()=>Vu,pipeGeneratorWithSetup:()=>Uu});var zu=class e extends ReadableStream{reader;ensureReader(){this.reader||=this.getReader()}async next(){this.ensureReader();try{let e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){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 n=t.getReader();return new e({start(e){return t();function t(){return n.read().then(({done:n,value:r})=>{if(n){e.close();return}return e.enqueue(r),t()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new e({async pull(e){let{value:n,done:r}=await t.next();r&&e.close(),e.enqueue(n)},async cancel(e){await t.return(e)}})}};function Bu(e,t=2){let n=Array.from({length:t},()=>[]);return n.map(async function*(t){for(;;)if(t.length===0){let t=await e.next();for(let e of n)e.push(t)}else if(t[0].done)return;else yield t.shift().value})}function Vu(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e==`string`&&typeof t==`string`||typeof e==`number`&&typeof t==`number`)return e+t;if(`concat`in e&&typeof e.concat==`function`)return e.concat(t);if(typeof e==`object`&&typeof t==`object`){let n={...e};for(let[e,r]of Object.entries(t))e in n&&!Array.isArray(n[e])?n[e]=Vu(n[e],r):n[e]=r;return n}else throw Error(`Cannot concat ${typeof e} and ${typeof t}`)}var Hu=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,n)=>{Au.runWithConfig(Fu(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(e=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Au.runWithConfig(Fu(this.config),this.signal?async()=>Iu(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 Uu(e,t,n,r,...i){let a=new Hu({generator:t,startSetup:n,signal:r}),o=await a.setup;return{output:e(a,o,...i),setup:o}}var Wu=Object.prototype.hasOwnProperty;function Gu(e,t){return Wu.call(e,t)}function Ku(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 n in e)Gu(e,n)&&t.push(n);return t}function qu(e){switch(typeof e){case`object`:return JSON.parse(JSON.stringify(e));case`undefined`:return null;default:return e}}function Ju(e){let t=0,n=e.length,r;for(;t<n;){if(r=e.charCodeAt(t),r>=48&&r<=57){t++;continue}return!1}return!0}function Yu(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Xu(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Zu(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Zu(e[t]))return!0}else if(typeof e==`object`){let n=Ku(e),r=n.length;for(var t=0;t<r;t++)if(Zu(e[n[t]]))return!0}}return!1}function Qu(e,t){let n=[e];for(let e in t){let r=typeof t[e]==`object`?JSON.stringify(t[e],null,2):t[e];r!==void 0&&n.push(`${e}: ${r}`)}return n.join(`
25
+ `)}var $u=class extends Error{constructor(e,t,n,r,i){super(Qu(e,{name:t,index:n,operation:r,tree:i})),this.name=t,this.index=n,this.operation=r,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=Qu(e,{name:t,index:n,operation:r,tree:i})}},ed={};A(ed,{JsonPatchError:()=>q,_areEquals:()=>dd,applyOperation:()=>od,applyPatch:()=>sd,applyReducer:()=>cd,deepClone:()=>td,getValueByPointer:()=>ad,validate:()=>ud,validator:()=>ld});var q=$u,td=qu;function nd(e){return Object.getOwnPropertyNames(Object.prototype).includes(e)}var rd={add:function(e,t,n){if(nd(t))throw TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){if(nd(t))throw TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){if(nd(t))throw TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){let r=ad(n,this.path);r&&=qu(r);let i=od(n,{op:`remove`,path:this.from}).removed;return od(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){let r=ad(n,this.from);return od(n,{op:`add`,path:this.path,value:qu(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:dd(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},id={add:function(e,t,n){return Ju(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:rd.move,copy:rd.copy,test:rd.test,_get:rd._get};function ad(e,t){if(t==``)return e;var n={op:`_get`,path:t};return od(e,n),n.value}function od(e,t,n=!1,r=!0,i=!0,a=0){if(n&&(typeof n==`function`?n(t,0,e,t.path):ld(t,0)),t.path===``){let r={newDocument:e};if(t.op===`add`)return r.newDocument=t.value,r;if(t.op===`replace`)return r.newDocument=t.value,r.removed=e,r;if(t.op===`move`||t.op===`copy`)return r.newDocument=ad(e,t.from),t.op===`move`&&(r.removed=e),r;if(t.op===`test`){if(r.test=dd(e,t.value),r.test===!1)throw new q(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r.newDocument=e,r}else if(t.op===`remove`)return r.removed=e,r.newDocument=null,r;else if(t.op===`_get`)return t.value=e,r;else if(n)throw new q("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);else return r}else{r||(e=qu(e));let o=(t.path||``).split(`/`),s=e,c=1,l=o.length,u,d,f;for(f=typeof n==`function`?n:ld;;){if(d=o[c],d&&d.indexOf(`~`)!=-1&&(d=Xu(d)),i&&(d==`__proto__`||d==`prototype`&&c>0&&o[c-1]==`constructor`))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&u===void 0&&(s[d]===void 0?u=o.slice(0,c).join(`/`):c==l-1&&(u=t.path),u!==void 0&&f(t,0,e,u)),c++,Array.isArray(s)){if(d===`-`)d=s.length;else if(n&&!Ju(d))throw new q(`Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index`,`OPERATION_PATH_ILLEGAL_ARRAY_INDEX`,a,t,e);else Ju(d)&&(d=~~d);if(c>=l){if(n&&t.op===`add`&&d>s.length)throw new q(`The specified index MUST NOT be greater than the number of elements in the array`,`OPERATION_VALUE_OUT_OF_BOUNDS`,a,t,e);let r=id[t.op].call(t,s,d,e);if(r.test===!1)throw new q(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r}}else if(c>=l){let n=rd[t.op].call(t,s,d,e);if(n.test===!1)throw new q(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return n}if(s=s[d],n&&c<l&&(!s||typeof s!=`object`))throw new q(`Cannot perform operation at the desired path`,`OPERATION_PATH_UNRESOLVABLE`,a,t,e)}}}function sd(e,t,n,r=!0,i=!0){if(n&&!Array.isArray(t))throw new q(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);r||(e=qu(e));let a=Array(t.length);for(let r=0,o=t.length;r<o;r++)a[r]=od(e,t[r],n,!0,i,r),e=a[r].newDocument;return a.newDocument=e,a}function cd(e,t,n){let r=od(e,t);if(r.test===!1)throw new q(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function ld(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new q(`Operation is not an object`,`OPERATION_NOT_AN_OBJECT`,t,e,n);if(!rd[e.op])throw new q("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,t,e,n);if(typeof e.path!=`string`)throw new q("Operation `path` property is not a string",`OPERATION_PATH_INVALID`,t,e,n);if(e.path.indexOf(`/`)!==0&&e.path.length>0)throw new q('Operation `path` property must start with "/"',`OPERATION_PATH_INVALID`,t,e,n);if((e.op===`move`||e.op===`copy`)&&typeof e.from!=`string`)throw new q("Operation `from` property is not present (applicable in `move` and `copy` operations)",`OPERATION_FROM_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&e.value===void 0)throw new q("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&Zu(e.value))throw new q("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED`,t,e,n);if(n){if(e.op==`add`){var i=e.path.split(`/`).length,a=r.split(`/`).length;if(i!==a+1&&i!==a)throw new q("Cannot perform an `add` operation at the desired path",`OPERATION_PATH_CANNOT_ADD`,t,e,n)}else if(e.op===`replace`||e.op===`remove`||e.op===`_get`){if(e.path!==r)throw new q(`Cannot perform the operation at a path that does not exist`,`OPERATION_PATH_UNRESOLVABLE`,t,e,n)}else if(e.op===`move`||e.op===`copy`){var o=ud([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new q(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function ud(e,t,n){try{if(!Array.isArray(e))throw new q(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)sd(qu(t),qu(e),n||!0);else{n||=ld;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(e){if(e instanceof q)return e;throw e}}function dd(e,t){if(e===t)return!0;if(e&&t&&typeof e==`object`&&typeof t==`object`){var n=Array.isArray(e),r=Array.isArray(t),i,a,o;if(n&&r){if(a=e.length,a!=t.length)return!1;for(i=a;i--!==0;)if(!dd(e[i],t[i]))return!1;return!0}if(n!=r)return!1;var s=Object.keys(e);if(a=s.length,a!==Object.keys(t).length)return!1;for(i=a;i--!==0;)if(!t.hasOwnProperty(s[i]))return!1;for(i=a;i--!==0;)if(o=s[i],!dd(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}function fd(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=Ku(t),o=Ku(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(Gu(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?fd(u,d,n,r+`/`+Yu(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+Yu(l),value:qu(u)}),n.push({op:`replace`,path:r+`/`+Yu(l),value:qu(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+Yu(l),value:qu(u)}),n.push({op:`remove`,path:r+`/`+Yu(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(!(!s&&a.length==o.length))for(var c=0;c<a.length;c++){var l=a[c];!Gu(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+Yu(l),value:qu(t[l])})}}}function pd(e,t,n=!1){var r=[];return fd(e,t,r,``,n),r}({...ed});var md={};A(md,{LogStreamCallbackHandler:()=>xd,RunLog:()=>gd,RunLogPatch:()=>hd,isLogStreamHandler:()=>_d});var hd=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),n=sd({},t);return new gd({ops:t,state:n[n.length-1].newDocument})}},gd=class e extends hd{state;constructor(e){super(e),this.state=e.state}concat(t){let n=this.ops.concat(t.ops),r=sd(this.state,t.ops);return new e({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(t){let n=sd({},t.ops);return new e({ops:t.ops,state:n[n.length-1].newDocument})}},_d=e=>e.name===`log_stream_tracer`;async function vd(e,t){if(t===`original`)throw Error(`Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.`);let{inputs:n}=e;if([`retriever`,`llm`,`prompt`].includes(e.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===``))return n.input}async function yd(e,t){let{outputs:n}=e;return t===`original`||[`retriever`,`llm`,`prompt`].includes(e.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function bd(e){return e!==void 0&&e.message!==void 0}var xd=class extends Hl{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=zu.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??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){for await(let n of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new hd({ops:[{op:`add`,path:`/logs/${t}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new hd({ops:[{op:`replace`,path:``,value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;let n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat===`streaming_events`&&(n.inputs=await vd(e,this._schemaFormat)),await this.writer.write(new hd({ops:[{op:`add`,path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let n=[];this._schemaFormat===`streaming_events`&&n.push({op:`replace`,path:`/logs/${t}/inputs`,value:await vd(e,this._schemaFormat)}),n.push({op:`add`,path:`/logs/${t}/final_output`,value:await yd(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:`add`,path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let r=new hd({ops:n});await this.writer.write(r)}finally{if(e.id===this.rootId){let t=new hd({ops:[{op:`replace`,path:`/final_output`,value:await yd(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){let r=this.keyMapByRunId[e.id];if(r===void 0)return;let i=e.inputs.messages!==void 0,a;a=i?bd(n?.chunk)?n?.chunk:new ni({id:`run-${e.id}`,content:t}):t;let o=new hd({ops:[{op:`add`,path:`/logs/${r}/streamed_output_str/-`,value:t},{op:`add`,path:`/logs/${r}/streamed_output/-`,value:a}]});await this.writer.write(o)}},Sd={};A(Sd,{ChatGenerationChunk:()=>Td,GenerationChunk:()=>wd,RUN_KEY:()=>Cd});var Cd=`__run`,wd=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}})}},Td=class e extends wd{message;constructor(e){super(e),this.message=e.message}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function Ed({name:e,serialized:t}){return e===void 0?t?.name===void 0?t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:`Unnamed`:t.name:e}var Dd=e=>e.name===`event_stream_tracer`,Od=class extends Hl{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=zu.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){let n=await t.next();if(n.done)return;let r=this.runInfoMap.get(e);if(r===void 0){yield n.value;return}function i(e,t){return e===`llm`&&typeof t==`string`?new wd({text:t}):t}let a=this.tappedPromises.get(e);if(a===void 0){let o;a=new Promise(e=>{o=e}),this.tappedPromises.set(e,a);try{let a={event:`on_${r.runType}_stream`,run_id:e,name:r.name,tags:r.tags,metadata:r.metadata,data:{}};await this.send({...a,data:{chunk:i(r.runType,n.value)}},r),yield n.value;for await(let e of t)r.runType!==`tool`&&r.runType!==`retriever`&&await this.send({...a,data:{chunk:i(r.runType,e)}},r),yield e}finally{o?.()}}else{yield n.value;for await(let e of t)yield e}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let n=this.tappedPromises.get(e.run_id);n===void 0?await this.send(e,t):n.then(()=>{this.send(e,t)})}async onLLMStart(e){let t=Ed(e),n=e.inputs.messages===void 0?`llm`:`chat_model`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,r);let i=`on_${n}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onLLMNewToken(e,t,n){let r=this.runInfoMap.get(e.id),i,a;if(r===void 0)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(r.runType===`chat_model`)a=`on_chat_model_stream`,i=n?.chunk===void 0?new ni({content:t,id:`run-${e.id}`}):n.chunk.message;else if(r.runType===`llm`)a=`on_llm_stream`,i=n?.chunk===void 0?new wd({text:t}):n.chunk;else throw Error(`Unexpected run type ${r.runType}`);await this.send({event:a,data:{chunk:i},run_id:e.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let r=e.outputs?.generations,i;if(t.runType===`chat_model`){for(let e of r??[]){if(i!==void 0)break;i=e[0]?.message}n=`on_chat_model_end`}else if(t.runType===`llm`)i={generations:r?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n=`on_llm_end`;else throw Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=Ed(e),n=e.run_type??`chain`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};e.inputs.input===``&&Object.keys(e.inputs).length===1?(i={},r.inputs={}):e.inputs.input===void 0?(i.input=e.inputs,r.inputs=e.inputs):(i.input=e.inputs.input,r.inputs=e.inputs.input),this.runInfoMap.set(e.id,r),await this.send({event:`on_${n}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let n=`on_${e.run_type}_end`,r=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:r};r.input&&Object.keys(r).length===1&&(i.input=r.input,t.inputs=r.input),await this.sendEndEvent({event:n,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=Ed(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`tool`,inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:`on_tool_start`,data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let n=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:`on_tool_end`,data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)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=Ed(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`retriever`,inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),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??{}},n)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)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,n){let r=this.runInfoMap.get(n);if(r===void 0)throw Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:`on_custom_event`,run_id:n,name:e,tags:r.tags,metadata:r.metadata,data:t},r)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},kd=Object.prototype.toString,Ad=e=>kd.call(e)===`[object Error]`,jd=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 Md(e){if(!(e&&Ad(e)&&e.name===`TypeError`&&typeof e.message==`string`))return!1;let{message:t,stack:n}=e;return t===`Load failed`?n===void 0||`__sentry_captured__`in e:t.startsWith(`error sending request for url`)?!0:jd.has(t)}function Nd(e){if(typeof e==`number`){if(e<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function Pd(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${r?` or Infinity`:``}.`);if(!r&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw TypeError(`Expected \`${e}\` to be \u2265 ${n}.`)}}var Fd=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){let n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1,i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}function Ld(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Rd({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){let a=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof Fd)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,s=i.maxRetryTime??1/0,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(c),Ld(r,s)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=Ld(r,s);if(u<=0||o<=0)throw a;if(a instanceof TypeError&&!Md(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=Id(n,i),f=Math.min(d,u);return f>0&&await new Promise((e,t)=>{let n=()=>{clearTimeout(r),i.signal?.removeEventListener(`abort`,n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},f);i.unref&&r.unref?.(),i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.throwIfAborted(),!0}async function zd(e,t={}){if(t={...t},Nd(t.retries),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,Pd(`factor`,t.factor,{min:0,allowInfinity:!1}),Pd(`minTimeout`,t.minTimeout,{min:0,allowInfinity:!1}),Pd(`maxTimeout`,t.maxTimeout,{min:0,allowInfinity:!0}),Pd(`maxRetryTime`,t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0,i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();let r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await Rd({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw Error(`Retry attempts exhausted without throwing an error.`)}var Bd={};A(Bd,{AsyncCaller:()=>Ud});var Vd=[400,401,402,403,404,405,406,407,409],Hd=e=>{if(typeof e!=`object`||!e)return;if(`message`in e&&typeof e.message==`string`&&(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`))||`name`in e&&typeof e.name==`string`&&e.name===`AbortError`||`code`in e&&typeof e.code==`string`&&e.code===`ECONNABORTED`)throw e;let t=`response`in e&&typeof e.response==`object`&&e.response!==null&&`status`in e.response&&typeof e.response.status==`number`?e.response.status:void 0,n=`status`in e&&typeof e.status==`number`?e.status:void 0,r=t??n;if(r&&Vd.includes(+r))throw e;if((`error`in e&&typeof e.error==`object`&&e.error!==null&&`code`in e.error&&typeof e.error.code==`string`?e.error.code:void 0)===`insufficient_quota`){let t=Error(`message`in e&&typeof e.message==`string`?e.message:`Insufficient quota`);throw t.name=`InsufficientQuotaError`,t}},Ud=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??Hd,this.queue=new(`default`in Vs.default?Vs.default.default:Vs.default)({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>zd(()=>e(...t).catch(e=>{throw e instanceof Error?e:Error(e)}),{onFailedAttempt:({error:e})=>this.onFailedAttempt?.(e),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){if(e.signal){let r;return Promise.race([this.call(t,...n),new Promise((t,n)=>{r=()=>{n(Lu(e.signal))},e.signal?.addEventListener(`abort`,r)})]).finally(()=>{e.signal&&r&&e.signal.removeEventListener(`abort`,r)})}return this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}},Wd=class extends Hl{name=`RootListenersTracer`;rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:n,onError:r}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=r}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 Gd(e){return e?e.lc_runnable:!1}var Kd=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,r=e.tags??[];return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(t)),this.includeTags!==void 0&&(n||=r.some(e=>this.includeTags?.includes(e))),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n&&=r.every(e=>!this.excludeTags?.includes(e))),n}},qd=e=>btoa(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``);function J(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_zod`in t))return!1;let n=t._zod;return typeof n==`object`&&!!n&&`def`in n}function Y(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_def`in t)||`_zod`in t)return!1;let n=t._def;return typeof n==`object`&&!!n&&`typeName`in n}function Jd(e){return J(e)&&console.warn(`[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior.`),Y(e)}function Yd(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:!!(J(e)||Y(e))}function Xd(e){return!!(typeof e==`object`&&e&&`_def`in e&&typeof e._def==`object`&&e._def!==null&&`typeName`in e._def&&e._def.typeName===`ZodLiteral`)}function Zd(e){return J(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`literal`):!1}function Qd(e){return!!(Xd(e)||Zd(e))}async function $d(e,t){if(J(e))try{return{success:!0,data:await s(e,t)}}catch(e){return{success:!1,error:e}}if(Y(e))return await e.safeParseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}async function ef(e,t){if(J(e))return await s(e,t);if(Y(e))return await e.parseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function tf(e,t){if(J(e))try{return{success:!0,data:c(e,t)}}catch(e){return{success:!1,error:e}}if(Y(e))return e.safeParse(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function nf(e,t){if(J(e))return c(e,t);if(Y(e))return e.parse(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function rf(e){if(J(e))return a.get(e)?.description;if(Y(e)||`description`in e&&typeof e.description==`string`)return e.description}function af(e){if(!Yd(e))return!1;if(Y(e)){let t=e._def;if(t.typeName===`ZodObject`){let t=e;return!t.shape||Object.keys(t.shape).length===0}if(t.typeName===`ZodRecord`)return!0}if(J(e)){let t=e._zod.def;if(t.type===`object`){let t=e;return!t.shape||Object.keys(t.shape).length===0}if(t.type===`record`)return!0}return!!(typeof e==`object`&&e&&!(`shape`in e))}function of(e){return Yd(e)?Y(e)?e._def.typeName===`ZodString`:J(e)?e._zod.def.type===`string`:!1:!1}function sf(e){return!!(typeof e==`object`&&e&&`_def`in e&&typeof e._def==`object`&&e._def!==null&&`typeName`in e._def&&e._def.typeName===`ZodObject`)}function cf(e){return J(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`object`):!1}function lf(e){return J(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`array`):!1}function uf(e){return J(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`optional`):!1}function df(e){return J(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`nullable`):!1}function ff(e){return!!(sf(e)||cf(e))}function pf(e){if(Y(e))return e.shape;if(J(e))return e._zod.def.shape;throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function mf(e,t){if(Y(e))return e.extend(t);if(J(e))return d(e,t);throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function hf(e){if(Y(e))return e.partial();if(J(e))return p(m,e,void 0);throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function gf(e,t=!1){if(Y(e))return e.strict();if(cf(e)){let n=e._zod.def.shape;if(t)for(let[r,i]of Object.entries(e._zod.def.shape)){if(cf(i))n[r]=gf(i,t);else if(lf(i)){let e=i._zod.def.element;cf(e)&&(e=gf(e,t)),n[r]=f(i,{...i._zod.def,element:e})}else n[r]=i;let e=a.get(i);e&&a.add(n[r],e)}let r=f(e,{...e._zod.def,shape:n,catchall:l(u)}),i=a.get(e);return i&&a.add(r,i),r}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function _f(e,t=!1){if(sf(e))return e.passthrough();if(cf(e)){let n=e._zod.def.shape;if(t)for(let[r,i]of Object.entries(e._zod.def.shape)){if(cf(i))n[r]=_f(i,t);else if(lf(i)){let e=i._zod.def.element;cf(e)&&(e=_f(e,t)),n[r]=f(i,{...i._zod.def,element:e})}else n[r]=i;let e=a.get(i);e&&a.add(n[r],e)}let o=f(e,{...e._zod.def,shape:n,catchall:r(i)}),s=a.get(e);return s&&a.add(o,s),o}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function vf(e){if(Y(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(J(e))try{let t=c(e,void 0);return()=>t}catch{return}}function yf(e){return Y(e)&&`typeName`in e._def&&e._def.typeName===`ZodEffects`}function bf(e){return J(e)&&e._zod.def.type===`pipe`}function xf(e,t,n){let r=n.get(e);if(r!==void 0)return r;if(Y(e))return yf(e)?xf(e._def.schema,t,n):e;if(J(e)){let r=e;if(bf(e)&&(r=xf(e._zod.def.in,t,n)),t){if(cf(r)){let e={};for(let[i,a]of Object.entries(r._zod.def.shape))e[i]=xf(a,t,n);r=f(r,{...r._zod.def,shape:e})}else if(lf(r)){let e=xf(r._zod.def.element,t,n);r=f(r,{...r._zod.def,element:e})}else if(uf(r)){let e=xf(r._zod.def.innerType,t,n);r=f(r,{...r._zod.def,innerType:e})}else if(df(r)){let e=xf(r._zod.def.innerType,t,n);r=f(r,{...r._zod.def,innerType:e})}}let i=a.get(e);return i&&a.add(r,i),n.set(e,r),r}throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function Sf(e,t=!1){return xf(e,t,new WeakMap)}function Cf(e,t){if(Y(e)){let n=pf(e),r={};for(let[e,i]of Object.entries(n))t(e,i)?r[e]=i.optional():r[e]=i;return e.extend(r)}if(J(e)){let n=pf(e),r={...e._zod.def.shape};for(let[e,i]of Object.entries(n))t(e,i)&&(r[e]=new m({type:`optional`,innerType:i}));let i=f(e,{...e._zod.def,shape:r}),o=a.get(e);return o&&a.add(i,o),i}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function wf(e){return e instanceof Error&&(e.constructor.name===`ZodError`||e.constructor.name===`$ZodError`)}function Tf(e){return e.replace(/[^a-zA-Z-_0-9]/g,`_`)}var Ef=[`*`,`_`,"`"];function Df(e){let t=``;for(let[n,r]of Object.entries(e))t+=`\tclassDef ${n} ${r};\n`;return t}function Of(e,t,n){let{firstNode:r,lastNode:i,nodeColors:a,withStyles:o=!0,curveStyle:s=`linear`,wrapLabelNWords:c=9}=n??{},l=o?`%%{init: {'flowchart': {'curve': '${s}'}}}%%\ngraph TD;\n`:`graph TD;
26
+ `;if(o){let t=`default`,n={[t]:`{0}({1})`};r!==void 0&&(n[r]=`{0}([{1}]):::first`),i!==void 0&&(n[i]=`{0}([{1}]):::last`);for(let[r,i]of Object.entries(e)){let e=i.name.split(`:`).pop()??``,a=Ef.some(t=>e.startsWith(t)&&e.endsWith(t))?`<p>${e}</p>`:e;Object.keys(i.metadata??{}).length&&(a+=`<hr/><small><em>${Object.entries(i.metadata??{}).map(([e,t])=>`${e} = ${t}`).join(`
27
+ `)}</em></small>`);let o=(n[r]??n[t]).replace(`{0}`,Tf(r)).replace(`{1}`,a);l+=`\t${o}\n`}}let u={};for(let e of t){let t=e.source.split(`:`),n=e.target.split(`:`),r=t.filter((e,t)=>e===n[t]).join(`:`);u[r]||(u[r]=[]),u[r].push(e)}let d=new Set;function f(e){return[...e].sort((e,t)=>e.split(`:`).length-t.split(`:`).length)}function p(e,t){let n=e.length===1&&e[0].source===e[0].target;if(t&&!n){let e=t.split(`:`).pop();if(d.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.`);d.add(t),l+=`\tsubgraph ${e}\n`}let r=f(Object.keys(u).filter(e=>e.startsWith(`${t}:`)&&e!==t&&e.split(`:`).length===t.split(`:`).length+1));for(let e of r)p(u[e],e);for(let t of e){let{source:e,target:n,data:r,conditional:i}=t,a=``;if(r!==void 0){let e=r,t=e.split(` `);t.length>c&&(e=Array.from({length:Math.ceil(t.length/c)},(e,n)=>t.slice(n*c,(n+1)*c).join(` `)).join(`&nbsp;<br>&nbsp;`)),a=i?` -. &nbsp;${e}&nbsp; .-> `:` -- &nbsp;${e}&nbsp; --> `}else a=i?` -.-> `:` --> `;l+=`\t${Tf(e)}${a}${Tf(n)};\n`}t&&!n&&(l+=` end
28
+ `)}p(u[``]??[],``);for(let e in u)!e.includes(`:`)&&e!==``&&p(u[e],e);return o&&(l+=Df(a??{})),l}async function kf(e,t){let n=t?.backgroundColor??`white`,r=t?.imageType??`png`,i=qd(e);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));let a=`https://mermaid.ink/img/${i}?bgColor=${n}&type=${r}`,o=await fetch(a);if(!o.ok)throw Error([`Failed to render the graph using the Mermaid.INK API.`,`Status code: ${o.status}`,`Status text: ${o.statusText}`].join(`
29
+ `));return await o.blob()}var Af=Symbol(`Let zodToJsonSchema decide on which parser to use`),jf={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`},Mf=e=>typeof e==`string`?{...jf,name:e}:{...jf,...e},Nf=e=>{let t=Mf(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Pf=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function Ff(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?Pf(t,e.currentPath):t.join(`/`)}}function If(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function X(e,t,n,r,i){e[t]=n,If(e,t,r,i)}function Lf(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==k.ZodAny&&(n.items=Z(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&X(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&X(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(X(n,`minItems`,e.exactLength.value,e.exactLength.message,t),X(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Rf(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?X(n,`minimum`,r.value,r.message,t):X(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),X(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?X(n,`maximum`,r.value,r.message,t):X(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),X(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:X(n,`multipleOf`,r.value,r.message,t);break}return n}function zf(){return{type:`boolean`}}function Bf(e,t){return Z(e.type._def,t)}var Vf=(e,t)=>Z(e.innerType._def,t);function Hf(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(n=>Hf(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Uf(e,t)}}var Uf=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:X(n,`minimum`,r.value,r.message,t);break;case`max`:X(n,`maximum`,r.value,r.message,t);break}return n};function Wf(e,t){return{...Z(e.innerType._def,t),default:e.defaultValue()}}function Gf(e,t){return t.effectStrategy===`input`?Z(e.schema._def,t):Ff(t)}function Kf(e){return{type:`string`,enum:Array.from(e.values)}}var qf=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Jf(e,t){let n=[Z(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Z(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(qf(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Yf(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var Xf=void 0,Zf={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Xf===void 0&&(Xf=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Xf),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Qf(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:X(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:X(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:np(n,`email`,r.message,t);break;case`format:idn-email`:np(n,`idn-email`,r.message,t);break;case`pattern:zod`:rp(n,Zf.email,r.message,t);break}break;case`url`:np(n,`uri`,r.message,t);break;case`uuid`:np(n,`uuid`,r.message,t);break;case`regex`:rp(n,r.regex,r.message,t);break;case`cuid`:rp(n,Zf.cuid,r.message,t);break;case`cuid2`:rp(n,Zf.cuid2,r.message,t);break;case`startsWith`:rp(n,RegExp(`^${$f(r.value,t)}`),r.message,t);break;case`endsWith`:rp(n,RegExp(`${$f(r.value,t)}$`),r.message,t);break;case`datetime`:np(n,`date-time`,r.message,t);break;case`date`:np(n,`date`,r.message,t);break;case`time`:np(n,`time`,r.message,t);break;case`duration`:np(n,`duration`,r.message,t);break;case`length`:X(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),X(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:rp(n,RegExp($f(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&np(n,`ipv4`,r.message,t),r.version!==`v4`&&np(n,`ipv6`,r.message,t);break;case`base64url`:rp(n,Zf.base64url,r.message,t);break;case`jwt`:rp(n,Zf.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&rp(n,Zf.ipv4Cidr,r.message,t),r.version!==`v4`&&rp(n,Zf.ipv6Cidr,r.message,t);break;case`emoji`:rp(n,Zf.emoji(),r.message,t);break;case`ulid`:rp(n,Zf.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:np(n,`binary`,r.message,t);break;case`contentEncoding:base64`:X(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:rp(n,Zf.base64,r.message,t);break}break;case`nanoid`:rp(n,Zf.nanoid,r.message,t);break;case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function $f(e,t){return t.patternStrategy===`escape`?tp(e):e}var ep=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function tp(e){let t=``;for(let n=0;n<e.length;n++)ep.has(e[n])||(t+=`\\`),t+=e[n];return t}function np(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):X(e,`format`,t,n,r)}function rp(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:ip(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):X(e,`pattern`,ip(t,r),n,r)}function ip(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
30
+ ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
31
+ ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!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 ap(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===k.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??Ff(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===k.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Qf(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===k.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===k.ZodBranded&&e.keyType._def.type._def.typeName===k.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Bf(e.keyType._def,t);return{...n,propertyNames:i}}return n}function op(e,t){return t.mapStrategy===`record`?ap(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Z(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Ff(t),Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Ff(t)],minItems:2,maxItems:2}}}function sp(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function cp(e){return e.target===`openAi`?void 0:{not:Ff({...e,currentPath:[...e.currentPath,`not`]})}}function lp(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var up={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function dp(e,t){if(t.target===`openApi3`)return fp(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in up&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=up[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:return t._def.value===null?[...e,`null`]:e;default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return fp(e,t)}var fp=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function pp(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:up[e.innerType._def.typeName],nullable:!0}:{type:[up[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function mp(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,If(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?X(n,`minimum`,r.value,r.message,t):X(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),X(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?X(n,`maximum`,r.value,r.message,t):X(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),X(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:X(n,`multipleOf`,r.value,r.message,t);break}return n}function hp(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=_p(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=Z(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=gp(e,t);return o!==void 0&&(r.additionalProperties=o),r}function gp(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Z(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function _p(e){try{return e.isOptional()}catch{return!0}}var vp=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Z(e.innerType._def,t);let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:Ff(t)},n]}:Ff(t)},yp=(e,t)=>{if(t.pipeStrategy===`input`)return Z(e.in._def,t);if(t.pipeStrategy===`output`)return Z(e.out._def,t);let n=Z(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Z(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function bp(e,t){return Z(e.type._def,t)}function xp(e,t){let n={type:`array`,uniqueItems:!0,items:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&X(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&X(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Sp(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Z(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Cp(e){return{not:Ff(e)}}function wp(e){return Ff(e)}var Tp=(e,t)=>Z(e.innerType._def,t),Ep=(e,t,n)=>{switch(t){case k.ZodString:return Qf(e,n);case k.ZodNumber:return mp(e,n);case k.ZodObject:return hp(e,n);case k.ZodBigInt:return Rf(e,n);case k.ZodBoolean:return zf();case k.ZodDate:return Hf(e,n);case k.ZodUndefined:return Cp(n);case k.ZodNull:return lp(n);case k.ZodArray:return Lf(e,n);case k.ZodUnion:case k.ZodDiscriminatedUnion:return dp(e,n);case k.ZodIntersection:return Jf(e,n);case k.ZodTuple:return Sp(e,n);case k.ZodRecord:return ap(e,n);case k.ZodLiteral:return Yf(e,n);case k.ZodEnum:return Kf(e);case k.ZodNativeEnum:return sp(e);case k.ZodNullable:return pp(e,n);case k.ZodOptional:return vp(e,n);case k.ZodMap:return op(e,n);case k.ZodSet:return xp(e,n);case k.ZodLazy:return()=>e.getter()._def;case k.ZodPromise:return bp(e,n);case k.ZodNaN:case k.ZodNever:return cp(n);case k.ZodEffects:return Gf(e,n);case k.ZodAny:return Ff(n);case k.ZodUnknown:return wp(n);case k.ZodDefault:return Wf(e,n);case k.ZodBranded:return Bf(e,n);case k.ZodReadonly:return Tp(e,n);case k.ZodCatch:return Vf(e,n);case k.ZodPipeline:return yp(e,n);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(e=>void 0)(t)}};function Z(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Af)return i}if(r&&!n){let e=Dp(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=Ep(e,e.typeName,t),o=typeof a==`function`?Z(a(),t):a;if(o&&Op(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Dp=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:Pf(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),Ff(t)):t.$refStrategy===`seen`?Ff(t):void 0}},Op=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),kp=(e,t)=>{let n=Nf(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Z(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Ff(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Z(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Ff(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function Ap(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!Ap(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Ap(e[r],t[r]))return!1;return!0}return e===t}function jp(e){return encodeURI(Mp(e))}function Mp(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var Np={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Pp={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Fp={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Ip=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`);function Lp(e,t=Object.create(null),n=Ip,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:Lp(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,`__absolute_uri__`,{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_ref__`,{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_recursive_ref__`,{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(Fp[i])continue;let a=`${r}/${jp(i)}`,o=e[i];if(Array.isArray(o)){if(Np[i]){let e=o.length;for(let r=0;r<e;r++)Lp(o[r],t,n,`${a}/${r}`)}}else if(Pp[i])for(let e in o)Lp(o[e],t,n,`${a}/${jp(e)}`);else Lp(o,t,n,a)}return t}var Rp=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,zp=[0,31,28,31,30,31,30,31,31,30,31,30,31],Bp=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Vp=/^(?=.{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,Hp=/^(?:[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,Up=/^(?:(?:[^\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,Wp=/^(?:(?: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,Gp=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Kp=/^(?:\/(?:[^~/]|~0|~1)*)*$/,qp=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Jp=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Yp=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},Xp=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Zp=/^((([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,Qp=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function $p(e){return e.test.bind(e)}var em={date:nm,time:rm.bind(void 0,!1),"date-time":am,duration:Qp,uri:cm,"uri-reference":$p(Hp),"uri-template":$p(Up),url:$p(Wp),email:Yp,hostname:$p(Vp),ipv4:$p(Xp),ipv6:$p(Zp),regex:um,uuid:$p(Gp),"json-pointer":$p(Kp),"json-pointer-uri-fragment":$p(qp),"relative-json-pointer":$p(Jp)};function tm(e){return e%4==0&&(e%100!=0||e%400==0)}function nm(e){let t=e.match(Rp);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&tm(n)?29:zp[r])}function rm(e,t){let n=t.match(Bp);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}var im=/t|\s/i;function am(e){let t=e.split(im);return t.length==2&&nm(t[0])&&rm(!0,t[1])}var om=/\/|:/,sm=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function cm(e){return om.test(e)&&sm.test(e)}var lm=/[^\\]\\Z/;function um(e){if(lm.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function dm(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function Q(e,t,n=`2019-09`,r=Lp(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:ee,if:te,then:ne,else:re,format:x,properties:S,patternProperties:C,additionalProperties:ie,unevaluatedProperties:w,minProperties:ae,maxProperties:oe,propertyNames:se,dependentRequired:ce,dependentSchemas:T,dependencies:le,prefixItems:ue,items:E,additionalItems:D,unevaluatedItems:de,contains:fe,minContains:pe,maxContains:me,minItems:he,maxItems:ge,uniqueItems:_e,minimum:ve,maximum:ye,exclusiveMinimum:be,exclusiveMaximum:xe,multipleOf:Se,minLength:Ce,maxLength:we,pattern:Te,__absolute_ref__:Ee,__absolute_recursive_ref__:De}=t,O=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[De]:a,u=`${s}/$recursiveRef`,d=Q(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||O.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[Ee||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw Ee&&Ee!==d&&(e+=` Absolute URI "${Ee}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
32
+ - `)}`,Error(e)}let l=`${s}/$ref`,u=Q(e,t,n,r,i,a,o,l,c);if(u.valid||O.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:O.length===0,errors:O}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||O.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&O.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&O.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?Ap(e,h)||O.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&O.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>Ap(e,t))||O.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||O.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;Q(e,v,n,r,i,a,o,t).valid&&O.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Oe=[];if(y!==void 0){let t=`${s}/anyOf`,l=O.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=Q(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);O.push(...f.errors),u||=f.valid,f.valid&&Oe.push(d)}u?O.length=l:O.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${s}/allOf`,l=O.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=Q(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);O.push(...f.errors),u&&=f.valid,f.valid&&Oe.push(d)}u?O.length=l:O.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(ee!==void 0){let t=`${s}/oneOf`,l=O.length,u=ee.filter((s,l)=>{let u=Object.create(c),d=Q(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return O.push(...d.errors),d.valid&&Oe.push(u),d.valid}).length;u===1?O.length=l:O.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Oe),te!==void 0){let t=`${s}/if`;if(Q(e,te,n,r,i,a,o,t,c).valid){if(ne!==void 0){let l=Q(e,ne,n,r,i,a,o,`${s}/then`,c);l.valid||O.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(re!==void 0){let l=Q(e,re,n,r,i,a,o,`${s}/else`,c);l.valid||O.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||O.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(ae!==void 0&&t.length<ae&&O.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${ae} properties.`}),oe!==void 0&&t.length>oe&&O.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${oe} properties.`}),se!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${jp(s)}`,c=Q(s,se,n,r,i,a,e,t);c.valid||O.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(ce!==void 0){let t=`${s}/dependantRequired`;for(let n in ce)if(n in e){let r=ce[n];for(let i of r)i in e||O.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(T!==void 0)for(let t in T){let l=`${s}/dependentSchemas`;if(t in e){let s=Q(e,T[t],n,r,i,a,o,`${l}/${jp(t)}`,c);s.valid||O.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(le!==void 0){let t=`${s}/dependencies`;for(let s in le)if(s in e){let c=le[s];if(Array.isArray(c))for(let n of c)n in e||O.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=Q(e,c,n,r,i,a,o,`${t}/${jp(s)}`);l.valid||O.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(S!==void 0){let t=`${s}/properties`;for(let s in S){if(!(s in e))continue;let d=`${o}/${jp(s)}`,f=Q(e[s],S[s],n,r,i,a,d,`${t}/${jp(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,O.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&C!==void 0){let t=`${s}/patternProperties`;for(let s in C){let d=new RegExp(s,`u`),f=C[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${jp(p)}`,h=Q(e[p],f,n,r,i,a,m,`${t}/${jp(s)}`);h.valid?c[p]=l[p]=!0:(u=i,O.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&ie!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${jp(s)}`,f=Q(e[s],ie,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,O.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&w!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${jp(s)}`,u=Q(e[s],w,n,r,i,a,l,t);u.valid?c[s]=!0:O.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){ge!==void 0&&e.length>ge&&O.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${ge}).`}),he!==void 0&&e.length<he&&O.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${he}).`});let t=e.length,l=0,u=!1;if(ue!==void 0){let d=`${s}/prefixItems`,f=Math.min(ue.length,t);for(;l<f;l++){let t=Q(e[l],ue[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,O.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(E!==void 0){let d=`${s}/items`;if(Array.isArray(E)){let s=Math.min(E.length,t);for(;l<s;l++){let t=Q(e[l],E[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,O.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=Q(e[l],E,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,O.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&D!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=Q(e[l],D,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,O.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(fe!==void 0)if(t===0&&pe===void 0)O.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(pe!==void 0&&t<pe)O.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${pe}).`});else{let l=`${s}/contains`,u=O.length,d=0;for(let s=0;s<t;s++){let t=Q(e[s],fe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):O.push(...t.errors)}d>=(pe||0)&&(O.length=u),pe===void 0&&me===void 0&&d===0?O.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):pe!==void 0&&d<pe?O.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${pe} items matching schema. Only ${d} items were found.`}):me!==void 0&&d>me&&O.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${me} items matching schema. ${d} items were found.`})}if(!u&&de!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=Q(e[l],de,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||O.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(_e)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&Ap(r,t))&&(O.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(ve!==void 0&&(be===!0&&e<=ve||e<ve)&&O.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${be?`or equal to `:``} ${ve}.`}),ye!==void 0&&(xe===!0&&e>=ye||e>ye)&&O.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${xe?`or equal to `:``} ${ye}.`})):(ve!==void 0&&e<ve&&O.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${ve}.`}),ye!==void 0&&e>ye&&O.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${ye}.`}),be!==void 0&&e<=be&&O.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${be}.`}),xe!==void 0&&e>=xe&&O.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${xe}.`})),Se!==void 0){let t=e%Se;Math.abs(0-t)>=1.1920929e-7&&Math.abs(Se-t)>=1.1920929e-7&&O.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${Se}.`})}}else if(u===`string`){let t=Ce===void 0&&we===void 0?0:dm(e);Ce!==void 0&&t<Ce&&O.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${Ce}).`}),we!==void 0&&t>we&&O.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${we}).`}),Te!==void 0&&!new RegExp(Te,`u`).test(e)&&O.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),x!==void 0&&em[x]&&!em[x](e)&&O.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${x}".`})}return{valid:O.length===0,errors:O}}var fm=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Lp(e)}validate(e){return Q(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Lp(e,this.lookup)}},pm={};A(pm,{Validator:()=>fm,deepCompareStrict:()=>Ap,toJsonSchema:()=>mm,validatesOnlyStrings:()=>hm});function mm(e,t){if(J(e)){let n=Sf(e,!0);return cf(n)?o(gf(n,!0),t):o(e,t)}return Y(e)?kp(e):e}function hm(e){if(!e||typeof e!=`object`||Object.keys(e).length===0||Array.isArray(e))return!1;if(`type`in e)return typeof e.type==`string`?e.type===`string`:Array.isArray(e.type)?e.type.every(e=>e===`string`):!1;if(`enum`in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(e=>typeof e==`string`);if(`const`in e)return typeof e.const==`string`;if(`allOf`in e&&Array.isArray(e.allOf))return e.allOf.some(e=>hm(e));if(`anyOf`in e&&Array.isArray(e.anyOf)||`oneOf`in e&&Array.isArray(e.oneOf)){let t=`anyOf`in e?e.anyOf:e.oneOf;return t.length>0&&t.every(e=>hm(e))}if(`not`in e)return!1;if(`$ref`in e&&typeof e.$ref==`string`){let t=e.$ref,n=Lp(e);return n[t]?hm(n[t]):!1}return!1}var gm={};A(gm,{Graph:()=>ym});function _m(e,t){if(e!==void 0&&!Ai(e))return e;if(Gd(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}function vm(e){return Gd(e.data)?{type:`runnable`,data:{id:e.data.lc_id,name:e.data.getName()}}:{type:`schema`,data:{...mm(e.data.schema),title:e.data.name}}}var ym=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,n)=>{e[t.id]=Ai(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...vm(t)})),edges:this.edges.map(t=>{let n={source:e[t.source],target:e[t.target]};return t.data!==void 0&&(n.data=t.data),t.conditional!==void 0&&(n.conditional=t.conditional),n})}}addNode(e,t,n){if(t!==void 0&&this.nodes[t]!==void 0)throw Error(`Node with id ${t} already exists`);let r=t??Hi(),i={id:r,data:e,name:_m(t,e),metadata:n};return this.nodes[r]=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,n,r){if(this.nodes[e.id]===void 0)throw Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw Error(`Target node ${t.id} not in graph`);let i={source:e.id,target:t.id,data:n,conditional:r};return this.edges.push(i),i}firstNode(){return bm(this)}lastNode(){return xm(this)}extend(e,t=``){let n=t;Object.values(e.nodes).map(e=>e.id).every(Ai)&&(n=``);let r=e=>n?`${n}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[r(e)]={...t,id:r(e)}});let i=e.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}));this.edges=[...this.edges,...i];let a=e.firstNode(),o=e.lastNode();return[a?{id:r(a.id),data:a.data}:void 0,o?{id:r(o.id),data:o.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&bm(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&xm(this,[e.id])&&this.removeNode(e)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),n=new Map;Object.values(t).forEach(e=>{n.set(e,(n.get(e)||0)+1)});let r=e=>{let r=t[e];return Ai(e)&&n.get(r)===1?r:e};return new e({nodes:Object.fromEntries(Object.entries(this.nodes).map(([e,t])=>[r(e),{...t,id:r(e)}])),edges:this.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}))})}drawMermaid(e){let{withStyles:t,curveStyle:n,nodeColors:r={default:`fill:#f2f0ff,line-height:1.2`,first:`fill-opacity:0`,last:`fill:#bfb6fc`},wrapLabelNWords:i}=e??{},a=this.reid(),o=a.firstNode(),s=a.lastNode();return Of(a.nodes,a.edges,{firstNode:o?.id,lastNode:s?.id,withStyles:t,curveStyle:n,nodeColors:r,wrapLabelNWords:i})}async drawMermaidPng(e){return kf(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function bm(e,t=[]){let n=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),r=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!n.has(i.id)&&r.push(i);return r.length===1?r[0]:void 0}function xm(e,t=[]){let n=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),r=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!n.has(i.id)&&r.push(i);return r.length===1?r[0]:void 0}function Sm(e){let t=new TextEncoder,n=new ReadableStream({async start(n){for await(let r of e)n.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(r)}\n\n`));n.enqueue(t.encode(`event: end
33
+
34
+ `)),n.close()}});return zu.fromReadableStream(n)}function Cm(e){return typeof e==`object`&&!!e&&typeof e[Symbol.iterator]==`function`&&typeof e.next==`function`}var wm=e=>typeof e==`object`&&!!e&&`next`in e&&typeof e.next==`function`;function Tm(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}function*Em(e,t){for(;;){let{value:n,done:r}=Au.runWithConfig(Fu(e),t.next.bind(t),!0);if(r)break;yield n}}async function*Dm(e,t){let n=t[Symbol.asyncIterator]();for(;;){let{value:r,done:i}=await Au.runWithConfig(Fu(e),n.next.bind(t),!0);if(i)break;yield r}}function $(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}var Om=class extends pn{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 jm({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new km({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new Rm({runnable:this,fallbacks:t})}_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(G);if(t>1&&!Array.isArray(e)&&e.runId){console.warn(`Provided runId will be used only for the first element of the batch.`);let n=Object.fromEntries(Object.entries(e).filter(([e])=>e!==`runId`));return Array.from({length:t},(t,r)=>G(r===0?e:n))}return Array.from({length:t},()=>G(e))}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=new Ud({maxConcurrency:r[0]?.maxConcurrency??n?.maxConcurrency,onFailedAttempt:e=>{throw e}}),a=e.map((e,t)=>i.call(async()=>{try{return await this.invoke(e,r[t])}catch(e){if(n?.returnExceptions)return e;throw e}}));return Promise.all(a)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let n=G(t),r=new Hu({generator:this._streamIterator(e,n),config:n});return await r.setup,zu.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;t=G(e===void 0?e:{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 n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){let r=G(n),i=await(await Mu(r))?.handleChainStart(this.toJSON(),$(t,`input`),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName());delete r.runId;let a;try{a=await Iu(e.call(this,t,r,i),n?.signal)}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd($(a,`output`)),a}async _batchWithConfig(e,t,n,r){let i=this._getOptionsList(n??{},t.length),a=await Promise.all(i.map(Mu)),o=await Promise.all(a.map(async(e,n)=>{let r=await e?.handleChainStart(this.toJSON(),$(t[n],`input`),i[n].runId,i[n].runType,void 0,void 0,i[n].runName??this.getName());return delete i[n].runId,r})),s;try{s=await Iu(e.call(this,t,i,o,r),i?.[0]?.signal)}catch(e){throw await Promise.all(o.map(t=>t?.handleChainError(e))),e}return await Promise.all(o.map(e=>e?.handleChainEnd($(s,`output`)))),s}_concatOutputChunks(e,t){return Vu(e,t)}async*_transformStreamWithConfig(e,t,n){let r,i=!0,a,o=!0,s=G(n),c=await Mu(s),l=this;async function*u(){for await(let t of e){if(i)if(r===void 0)r=t;else try{r=l._concatOutputChunks(r,t)}catch{r=void 0,i=!1}yield t}}let d;try{let e=await Uu(t.bind(this),u(),async()=>c?.handleChainStart(this.toJSON(),{input:``},s.runId,s.runType,void 0,void 0,s.runName??this.getName(),void 0,{lc_defers_inputs:!0}),n?.signal,s);delete s.runId,d=e.setup;let r=d?.handlers.find(Dd),i=e.output;r!==void 0&&d!==void 0&&(i=r.tapOutputIterable(d.runId,i));let l=d?.handlers.find(_d);l!==void 0&&d!==void 0&&(i=l.tapOutputIterable(d.runId,i));for await(let e of i)if(yield e,o)if(a===void 0)a=e;else try{a=this._concatOutputChunks(a,e)}catch{a=void 0,o=!1}}catch(e){throw await d?.handleChainError(e,void 0,void 0,void 0,{inputs:$(r,`input`)}),e}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:$(r,`input`)})}getGraph(e){let t=new ym,n=t.addNode({name:`${this.getName()}Input`,schema:Dt()}),r=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:Dt()});return t.addEdge(n,r),t.addEdge(r,i),t}pipe(e){return new Mm({first:this,last:zm(e)})}pick(e){return this.pipe(new Vm(e))}assign(e){return this.pipe(new Bm(new Nm({steps:e})))}async*transform(e,t){let n;for await(let t of e)n=n===void 0?t:this._concatOutputChunks(n,t);yield*this._streamIterator(n,G(t))}async*streamLog(e,t,n){let r=new xd({...n,autoClose:!1,_schemaFormat:`original`}),i=G(t);yield*this._streamLog(e,r,i)}async*_streamLog(e,t,n){let{callbacks:r}=n;if(r===void 0)n.callbacks=[t];else if(Array.isArray(r))n.callbacks=r.concat([t]);else{let e=r.copy();e.addHandler(t,!0),n.callbacks=e}let i=this.stream(e,n);async function a(){try{let e=await i;for await(let n of e){let e=new hd({ops:[{op:`add`,path:`/streamed_output/-`,value:n}]});await t.writer.write(e)}}finally{await t.writer.close()}}let o=a();try{for await(let e of t)yield e}finally{await o}}streamEvents(e,t,n){let r;if(t.version===`v1`)r=this._streamEventsV1(e,t,n);else if(t.version===`v2`)r=this._streamEventsV2(e,t,n);else throw Error(`Only versions "v1" and "v2" of the schema are currently supported.`);return t.encoding===`text/event-stream`?Sm(r):zu.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){let r=new Od({...n,autoClose:!1}),i=G(t),a=i.runId??Hi();i.runId=a;let o=i.callbacks;if(o===void 0)i.callbacks=[r];else if(Array.isArray(o))i.callbacks=o.concat(r);else{let e=o.copy();e.addHandler(r,!0),i.callbacks=e}let s=new AbortController,c=this;async function l(){let n,o=null;try{t?.signal?`any`in AbortSignal?n=AbortSignal.any([s.signal,t.signal]):(n=t.signal,o=()=>{s.abort()},t.signal.addEventListener(`abort`,o,{once:!0})):n=s.signal;let l=await c.stream(e,{...i,signal:n}),u=r.tapOutputIterable(a,l);for await(let e of u)if(s.signal.aborted)break}finally{await r.finish(),n&&o&&n.removeEventListener(`abort`,o)}}let u=l(),d=!1,f;try{for await(let t of r){if(!d){t.data.input=e,d=!0,f=t.run_id,yield t;continue}t.run_id===f&&t.event.endsWith(`_end`)&&t.data?.input&&delete t.data.input,yield t}}finally{s.abort(),await u}}async*_streamEventsV1(e,t,n){let r,i=!1,a=G(t),o=a.tags??[],s=a.metadata??{},c=a.runName??this.getName(),l=new xd({...n,autoClose:!1,_schemaFormat:`streaming_events`}),u=new Kd({...n}),d=this._streamLog(e,l,a);for await(let t of d){if(r=r?r.concat(t):gd.fromRunLogPatch(t),r.state===void 0)throw Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`);if(!i){i=!0;let t={...r.state},n={run_id:t.id,event:`on_${t.type}_start`,name:c,tags:o,metadata:s,data:{input:e}};u.includeEvent(n,t.type)&&(yield n)}let n=t.ops.filter(e=>e.path.startsWith(`/logs/`)).map(e=>e.path.split(`/`)[2]),a=[...new Set(n)];for(let e of a){let t,n={},i=r.state.logs[e];if(t=i.end_time===void 0?i.streamed_output.length>0?`stream`:`start`:`end`,t===`start`)i.inputs!==void 0&&(n.input=i.inputs);else if(t===`end`)i.inputs!==void 0&&(n.input=i.inputs),n.output=i.final_output;else if(t===`stream`){let e=i.streamed_output.length;if(e!==1)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);n={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:n}}let{state:l}=r;if(l.streamed_output.length>0){let e=l.streamed_output.length;if(e!==1)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${l.name}"`);let t={chunk:l.streamed_output[0]};l.streamed_output=[];let n={event:`on_${l.type}_stream`,run_id:l.id,tags:o,metadata:s,name:c,data:t};u.includeEvent(n,l.type)&&(yield n)}}let f=r?.state;if(f!==void 0){let e={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:o,metadata:s,data:{output:f.final_output}};u.includeEvent(e,f.type)&&(yield e)}}static isRunnable(e){return Gd(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new km({bound:this,config:{},configFactories:[r=>({callbacks:[new Wd({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return Um(this,e)}},km=class e extends Om{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=Nu(this.config,...e);return Nu(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 jm({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,n){let r=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig(G(e),this.kwargs))):await this._mergeConfig(G(t),this.kwargs);return this.bound.batch(e,r,n)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(G(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(G(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(G(t),this.kwargs))}streamEvents(e,t,n){let r=this;return zu.fromAsyncGenerator(async function*(){yield*r.bound.streamEvents(e,{...await r._mergeConfig(G(t),r.kwargs),version:t.version},n)}())}static isRunnableBinding(e){return e.bound&&Om.isRunnable(e.bound)}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[e=>({callbacks:[new Wd({config:e,onStart:t,onEnd:n,onError:r})]})]})}},Am=class e extends Om{static lc_name(){return`RunnableEach`}lc_serializable=!0;lc_namespace=[`langchain_core`,`runnables`];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,n){return this.bound.batch(e,K(t,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:r})})}},jm=class extends km{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,n){let r=e>1?`retry:attempt:${e}`:void 0;return K(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return zd(r=>super.invoke(e,this._patchConfigForRetry(r,t,n)),{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,n,r){let i={};try{await zd(async a=>{let o=e.map((e,t)=>t).filter(e=>i[e.toString()]===void 0||i[e.toString()]instanceof Error),s=o.map(t=>e[t]),c=o.map(e=>this._patchConfigForRetry(a,t?.[e],n?.[e])),l=await super.batch(s,c,{...r,returnExceptions:!0}),u;for(let e=0;e<l.length;e+=1){let t=l[e],n=o[e];t instanceof Error&&u===void 0&&(u=t,u.input=s[e]),i[n.toString()]=t}if(u)throw u;return l},{onFailedAttempt:({error:e})=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(r?.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,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},Mm=class e extends Om{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 n=G(t),r=await(await Mu(n))?.handleChainStart(this.toJSON(),$(e,`input`),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i=e,a;try{let e=[this.first,...this.middle];for(let a=0;a<e.length;a+=1)i=await Iu(e[a].invoke(i,K(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${a+1}`)})),t?.signal);if(t?.signal?.aborted)throw Lu(t.signal);a=await this.last.invoke(i,K(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await r?.handleChainError(e),e}return await r?.handleChainEnd($(a,`output`)),a}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(Mu)),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),$(e[n],`input`),r[n].runId,void 0,void 0,void 0,r[n].runName);return delete r[n].runId,i})),o=e;try{for(let e=0;e<this.steps.length;e+=1)o=await Iu(this.steps[e].batch(o,a.map((t,n)=>{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return K(r[n],{callbacks:i})}),n),r[0]?.signal)}catch(e){throw await Promise.all(a.map(t=>t?.handleChainError(e))),e}return await Promise.all(a.map(e=>e?.handleChainEnd($(o,`output`)))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){let n=await Mu(t),{runId:r,...i}=t??{},a=await n?.handleChainStart(this.toJSON(),$(e,`input`),r,void 0,void 0,void 0,i?.runName),o=[this.first,...this.middle,this.last],s=!0,c;async function*l(){yield e}try{let e=o[0].transform(l(),K(i,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:1`)}));for(let t=1;t<o.length;t+=1)e=await o[t].transform(e,K(i,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)}));for await(let n of e)if(t?.signal?.throwIfAborted(),yield n,s)if(c===void 0)c=n;else try{c=this._concatOutputChunks(c,n)}catch{c=void 0,s=!1}}catch(e){throw await a?.handleChainError(e),e}await a?.handleChainEnd($(c,`output`))}getGraph(e){let t=new ym,n=null;return this.steps.forEach((r,i)=>{let a=r.getGraph(e);i!==0&&a.trimFirstNode(),i!==this.steps.length-1&&a.trimLastNode(),t.extend(a);let o=a.firstNode();if(!o)throw Error(`Runnable ${r} has no first node`);n&&t.addEdge(n,o),n=a.lastNode()}),t}pipe(t){return e.isRunnableSequence(t)?new e({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new e({first:this.first,middle:[...this.middle,this.last],last:zm(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Om.isRunnable(e)}static from([t,...n],r){let i={};return typeof r==`string`?i.name=r:r!==void 0&&(i=r),new e({...i,first:zm(t),middle:n.slice(0,-1).map(zm),last:zm(n[n.length-1])})}},Nm=class e extends Om{static lc_name(){return`RunnableMap`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(let[t,n]of Object.entries(e.steps))this.steps[t]=zm(n)}static from(t){return new e({steps:t})}async invoke(e,t){let n=G(t),r=await(await Mu(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i={};try{let a=Object.entries(this.steps).map(async([t,a])=>{i[t]=await a.invoke(e,K(n,{callbacks:r?.getChild(`map:key:${t}`)}))});await Iu(Promise.all(a),t?.signal)}catch(e){throw await r?.handleChainError(e),e}return await r?.handleChainEnd(i),i}async*_transform(e,t,n){let r={...this.steps},i=Bu(e,Object.keys(r).length),a=new Map(Object.entries(r).map(([e,r],a)=>{let o=r.transform(i[a],K(n,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,o.next().then(t=>({key:e,gen:o,result:t}))]}));for(;a.size;){let{key:e,result:t,gen:r}=await Iu(Promise.race(a.values()),n?.signal);a.delete(e),t.done||(yield{[e]:t.value},a.set(e,r.next().then(t=>({key:e,gen:r,result:t}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=G(t),i=new Hu({generator:this.transform(n(),r),config:r});return await i.setup,zu.fromAsyncGenerator(i)}},Pm=class e extends Om{lc_serializable=!1;lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(super(e),!iu(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[n]=this._getOptionsList(t??{},1),r=await Mu(n);return Iu(this.func(K(n,{callbacks:r}),e),n?.signal)}async*_streamIterator(e,t){let[n]=this._getOptionsList(t??{},1),r=await this.invoke(e,t);if(Tm(r)){for await(let e of r)n?.signal?.throwIfAborted(),yield e;return}if(wm(r)){for(;;){n?.signal?.throwIfAborted();let e=r.next();if(e.done)break;yield e.value}return}yield r}static from(t){return new e({func:t})}};function Fm(e){if(iu(e))throw Error(`RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.`)}var Im=class e extends Om{static lc_name(){return`RunnableLambda`}lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(iu(e.func))return Pm.from(e.func);super(e),Fm(e.func),this.func=e.func}static from(t){return new e({func:t})}async _invoke(e,t,n){return new Promise((r,i)=>{let a=K(t,{callbacks:n?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});Au.runWithConfig(Fu(a),async()=>{try{let n=await this.func(e,{...a});if(n&&Om.isRunnable(n)){if(t?.recursionLimit===0)throw Error(`Recursion limit reached.`);n=await n.invoke(e,{...a,recursionLimit:(a.recursionLimit??25)-1})}else if(Tm(n)){let e;for await(let r of Dm(a,n))if(t?.signal?.throwIfAborted(),e===void 0)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}else if(Cm(n)){let e;for(let r of Em(a,n))if(t?.signal?.throwIfAborted(),e===void 0)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}r(n)}catch(e){i(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,n){let r;for await(let t of e)if(r===void 0)r=t;else try{r=this._concatOutputChunks(r,t)}catch{r=t}let i=K(n,{callbacks:t?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),a=await new Promise((e,t)=>{Au.runWithConfig(Fu(i),async()=>{try{e(await this.func(r,{...i,config:i}))}catch(e){t(e)}})});if(a&&Om.isRunnable(a)){if(n?.recursionLimit===0)throw Error(`Recursion limit reached.`);let e=await a.stream(r,i);for await(let t of e)yield t}else if(Tm(a))for await(let e of Dm(i,a))n?.signal?.throwIfAborted(),yield e;else if(Cm(a))for(let e of Em(i,a))n?.signal?.throwIfAborted(),yield e;else yield a}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=G(t),i=new Hu({generator:this.transform(n(),r),config:r});return await i.setup,zu.fromAsyncGenerator(i)}},Lm=class extends Nm{},Rm=class extends Om{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(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,t){let n=G(t),r=await Mu(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),$(e,`input`),i,void 0,void 0,void 0,a?.runName),s=K(a,{callbacks:o?.getChild()});return await Au.runWithConfig(s,async()=>{let t;for(let r of this.runnables()){n?.signal?.throwIfAborted();try{let t=await r.invoke(e,s);return await o?.handleChainEnd($(t,`output`)),t}catch(e){t===void 0&&(t=e)}}throw t===void 0?Error(`No error stored at end of fallback.`):(await o?.handleChainError(t),t)})}async*_streamIterator(e,t){let n=G(t),r=await Mu(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),$(e,`input`),i,void 0,void 0,void 0,a?.runName),s,c;for(let t of this.runnables()){n?.signal?.throwIfAborted();let r=K(a,{callbacks:o?.getChild()});try{c=Dm(r,await t.stream(e,r));break}catch(e){s===void 0&&(s=e)}}if(c===void 0){let e=s??Error(`No error stored at end of fallback.`);throw await o?.handleChainError(e),e}let l;try{for await(let e of c){yield e;try{l=l===void 0?l:this._concatOutputChunks(l,e)}catch{l=void 0}}}catch(e){throw await o?.handleChainError(e),e}await o?.handleChainEnd($(l,`output`))}async batch(e,t,n){if(n?.returnExceptions)throw Error(`Not implemented.`);let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(e=>Mu(e))),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),$(e[n],`input`),r[n].runId,void 0,void 0,void 0,r[n].runName);return delete r[n].runId,i})),o;for(let t of this.runnables()){r[0].signal?.throwIfAborted();try{let i=await t.batch(e,a.map((e,t)=>K(r[t],{callbacks:e?.getChild()})),n);return await Promise.all(a.map((e,t)=>e?.handleChainEnd($(i[t],`output`)))),i}catch(e){o===void 0&&(o=e)}}throw o?(await Promise.all(a.map(e=>e?.handleChainError(o))),o):Error(`No error stored at end of fallbacks.`)}};function zm(e){if(typeof e==`function`)return new Im({func:e});if(Om.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=zm(r);return new Nm({steps:t})}else throw Error(`Expected a Runnable, function or object.
35
+ Instead got an unsupported type.`)}var Bm=class extends Om{static lc_name(){return`RunnableAssign`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;mapper;constructor(e){e instanceof Nm&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){let n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){let r=this.mapper.getStepsKeys(),[i,a]=Bu(e),o=this.mapper.transform(a,K(n,{callbacks:t?.getChild()})),s=o.next();for await(let e of i){if(typeof e!=`object`||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])=>!r.includes(e)));Object.keys(t).length>0&&(yield t)}yield(await s).value;for await(let e of o)yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=G(t),i=new Hu({generator:this.transform(n(),r),config:r});return await i.setup,zu.fromAsyncGenerator(i)}},Vm=class extends Om{static lc_name(){return`RunnablePick`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;keys;constructor(e){(typeof e==`string`||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys==`string`)return e[this.keys];{let t=this.keys.map(t=>[t,e[t]]).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(let t of e){let e=await this._pick(t);e!==void 0&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=G(t),i=new Hu({generator:this.transform(n(),r),config:r});return await i.setup,zu.fromAsyncGenerator(i)}},Hm=class extends km{name;description;schema;constructor(e){let t=Mm.from([Im.from(async e=>{let t;if(kr(e))try{t=await ef(this.schema,e.args)}catch{throw new jr(`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});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return`RunnableToolLike`}};function Um(e,t){let n=t.name??e.getName(),r=t.description??rf(t.schema);return of(t.schema)?new Hm({name:n,description:r,schema:kt({input:wt()}).transform(e=>e.input),bound:e}):new Hm({name:n,description:r,schema:t.schema,bound:e})}var Wm=(e,t)=>{let n=[...new Set(t?.map(e=>{if(typeof e==`string`)return e;let t=new e({});if(!(`getType`in t)||typeof t.getType!=`function`)throw Error(`Invalid type provided.`);return t.getType()}))],r=e.getType();return n.some(e=>e===r)};function Gm(e,t){return Array.isArray(e)?Km(e,t):Im.from(t=>Km(t,e))}function Km(e,t={}){let{includeNames:n,excludeNames:r,includeTypes:i,excludeTypes:a,includeIds:o,excludeIds:s}=t,c=[];for(let t of e)r&&t.name&&r.includes(t.name)||a&&Wm(t,a)||s&&t.id&&s.includes(t.id)||(i||o||n?(n&&t.name&&n.some(e=>e===t.name)||i&&Wm(t,i)||o&&t.id&&o.some(e=>e===t.id))&&c.push(t):c.push(t));return c}function qm(e){return Array.isArray(e)?Jm(e):Im.from(Jm)}function Jm(e){if(!e.length)return[];let t=[];for(let n of e){let e=n,r=t.pop();if(!r)t.push(e);else if(e.getType()===`tool`||e.getType()!==r.getType())t.push(r,e);else{let n=pi(r),i=pi(e),a=n.concat(i);typeof n.content==`string`&&typeof i.content==`string`&&(a.content=`${n.content}\n${i.content}`),t.push(th(a))}}return t}function Ym(e,t){if(Array.isArray(e)){let n=e;if(!t)throw Error(`Options parameter is required when providing messages.`);return Xm(n,t)}else{let t=e;return Im.from(e=>Xm(e,t)).withConfig({runName:`trim_messages`})}}async function Xm(e,t){let{maxTokens:n,tokenCounter:r,strategy:i=`last`,allowPartial:a=!1,endOn:o,startOn:s,includeSystem:c=!1,textSplitter:l}=t;if(s&&i===`first`)throw Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&i===`first`)throw Error("`includeSystem` should only be specified if `strategy` is 'last'.");let u;u=`getNumTokens`in r?async e=>(await Promise.all(e.map(e=>r.getNumTokens(e.content)))).reduce((e,t)=>e+t,0):async e=>r(e);let d=nh;if(l&&(d=`splitText`in l?l.splitText:async e=>l(e)),i===`first`)return Zm(e,{maxTokens:n,tokenCounter:u,textSplitter:d,partialStrategy:a?`first`:void 0,endOn:o});if(i===`last`)return Qm(e,{maxTokens:n,tokenCounter:u,textSplitter:d,allowPartial:a,includeSystem:c,startOn:s,endOn:o});throw Error(`Unrecognized strategy: '${i}'. Must be one of 'first' or 'last'.`)}async function Zm(e,t){let{maxTokens:n,tokenCounter:r,textSplitter:i,partialStrategy:a,endOn:o}=t,s=[...e],c=0;for(let e=0;e<s.length;e+=1)if(await r(e>0?s.slice(0,-e):s)<=n){c=s.length-e;break}if(c<s.length&&a){let e=!1;if(Array.isArray(s[c].content)){let t=s[c];if(typeof t.content==`string`)throw Error(`Expected content to be an array.`);let i=t.content.length,o=a===`last`?[...t.content].reverse():t.content;for(let l=1;l<=i;l+=1){let i=a===`first`?o.slice(0,l):o.slice(-l),u=Object.fromEntries(Object.entries(t).filter(([e])=>e!==`type`&&!e.startsWith(`lc_`))),d=eh(t.getType(),{...u,content:i}),f=[...s.slice(0,c),d];if(await r(f)<=n)s=f,c+=1,e=!0;else break}e&&a===`last`&&(t.content=[...o].reverse())}if(!e){let e=s[c],t;if(Array.isArray(e.content)&&e.content.some(e=>typeof e==`string`||e.type===`text`)?t=e.content.find(e=>e.type===`text`&&e.text)?.text:typeof e.content==`string`&&(t=e.content),t){let o=await i(t),l=o.length;a===`last`&&o.reverse();for(let t=0;t<l-1;t+=1)if(o.pop(),e.content=o.join(``),await r([...s.slice(0,c),e])<=n){a===`last`&&(e.content=[...o].reverse().join(``)),s=[...s.slice(0,c),e],c+=1;break}}}}if(o){let e=Array.isArray(o)?o:[o];for(;c>0&&!Wm(s[c-1],e);)--c}return s.slice(0,c)}async function Qm(e,t){let{allowPartial:n=!1,includeSystem:r=!1,endOn:i,startOn:a,...o}=t,s=e.map(e=>{let t=Object.fromEntries(Object.entries(e).filter(([e])=>e!==`type`&&!e.startsWith(`lc_`)));return eh(e.getType(),t,Xn(e))});if(i){let e=Array.isArray(i)?i:[i];for(;s.length>0&&!Wm(s[s.length-1],e);)s=s.slice(0,-1)}let c=r&&s[0]?.getType()===`system`,l=c?s.slice(0,1).concat(s.slice(1).reverse()):s.reverse();return l=await Zm(l,{...o,partialStrategy:n?`last`:void 0,endOn:a}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}var $m={human:{message:_r,messageChunk:vr},ai:{message:$r,messageChunk:ni},system:{message:Sr,messageChunk:Cr},developer:{message:Sr,messageChunk:Cr},tool:{message:ir,messageChunk:ar},function:{message:pr,messageChunk:mr},generic:{message:lr,messageChunk:ur},remove:{message:xr,messageChunk:xr}};function eh(e,t,n){let r,i;switch(e){case`human`:n?r=new vr(t):i=new _r(t);break;case`ai`:if(n){let e={...t};`tool_calls`in e&&(e={...e,tool_call_chunks:e.tool_calls?.map(e=>({...e,type:`tool_call_chunk`,index:void 0,args:JSON.stringify(e.args)}))}),r=new ni(e)}else i=new $r(t);break;case`system`:n?r=new Cr(t):i=new Sr(t);break;case`developer`:n?r=new Cr({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:`developer`}}):i=new Sr({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:`developer`}});break;case`tool`:if(`tool_call_id`in t)n?r=new ar(t):i=new ir(t);else throw Error(`Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.`);break;case`function`:if(n)r=new mr(t);else{if(!t.name)throw Error(`FunctionMessage must have a 'name' field`);i=new pr(t)}break;case`generic`:if(`role`in t)n?r=new ur(t):i=new lr(t);else throw Error(`Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.`);break;default:throw Error(`Unrecognized message type ${e}`)}if(n&&r)return r;if(i)return i;throw Error(`Unrecognized message type ${e}`)}function th(e){let t=e.getType(),n,r=Object.fromEntries(Object.entries(e).filter(([e])=>![`type`,`tool_call_chunks`].includes(e)&&!e.startsWith(`lc_`)));if(t in $m&&(n=eh(t,r)),!n)throw Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys($m)}`);return n}function nh(e){let t=e.split(`
36
+ `);return Promise.resolve([...t.slice(0,-1).map(e=>`${e}\n`),t[t.length-1]])}var rh=[`tool_call`,`tool_call_chunk`,`invalid_tool_call`,`server_tool_call`,`server_tool_call_chunk`,`server_tool_call_result`],ih=[`image`,`video`,`audio`,`text-plain`,`file`],ah=[`text`,`reasoning`,...rh,...ih],oh=t({AIMessage:()=>$r,AIMessageChunk:()=>ni,BaseMessage:()=>Hn,BaseMessageChunk:()=>qn,ChatMessage:()=>lr,ChatMessageChunk:()=>ur,DEFAULT_MERGE_IGNORE_KEYS:()=>Wn,FunctionMessage:()=>pr,FunctionMessageChunk:()=>mr,HumanMessage:()=>_r,HumanMessageChunk:()=>vr,KNOWN_BLOCK_TYPES:()=>ah,RemoveMessage:()=>xr,SystemMessage:()=>Sr,SystemMessageChunk:()=>Cr,ToolMessage:()=>ir,ToolMessageChunk:()=>ar,_isMessageFieldWithRole:()=>Jn,_mergeDicts:()=>P,_mergeLists:()=>Gn,_mergeObj:()=>Kn,_mergeStatus:()=>Bn,coerceMessageLikeToMessage:()=>si,collapseToolCallChunks:()=>mi,convertToChunk:()=>pi,convertToOpenAIImageBlock:()=>Ht,convertToProviderContentBlock:()=>Gt,defaultTextSplitter:()=>nh,defaultToolCallParser:()=>or,filterMessages:()=>Gm,getBufferString:()=>ci,iife:()=>ri,isAIMessage:()=>ei,isAIMessageChunk:()=>ti,isBase64ContentBlock:()=>zt,isBaseMessage:()=>Yn,isBaseMessageChunk:()=>Xn,isChatMessage:()=>dr,isChatMessageChunk:()=>fr,isDataContentBlock:()=>Lt,isDirectToolOutput:()=>rr,isFunctionMessage:()=>hr,isFunctionMessageChunk:()=>gr,isHumanMessage:()=>yr,isHumanMessageChunk:()=>br,isIDContentBlock:()=>Vt,isMessage:()=>Kt,isOpenAIToolCallArray:()=>Un,isPlainTextContentBlock:()=>Bt,isSystemMessage:()=>wr,isSystemMessageChunk:()=>Tr,isToolMessage:()=>sr,isToolMessageChunk:()=>cr,isURLContentBlock:()=>Rt,mapChatMessagesToStoredMessages:()=>fi,mapStoredMessageToChatMessage:()=>ui,mapStoredMessagesToChatMessages:()=>di,mergeContent:()=>zn,mergeMessageRuns:()=>qm,mergeResponseMetadata:()=>Zn,mergeUsageMetadata:()=>tr,messages_exports:()=>sh,parseBase64DataUrl:()=>Wt,parseMimeType:()=>Ut,trimMessages:()=>Ym}),sh={};A(sh,{AIMessage:()=>$r,AIMessageChunk:()=>ni,BaseMessage:()=>Hn,BaseMessageChunk:()=>qn,ChatMessage:()=>lr,ChatMessageChunk:()=>ur,DEFAULT_MERGE_IGNORE_KEYS:()=>Wn,FunctionMessage:()=>pr,FunctionMessageChunk:()=>mr,HumanMessage:()=>_r,HumanMessageChunk:()=>vr,KNOWN_BLOCK_TYPES:()=>ah,RemoveMessage:()=>xr,SystemMessage:()=>Sr,SystemMessageChunk:()=>Cr,ToolMessage:()=>ir,ToolMessageChunk:()=>ar,_isMessageFieldWithRole:()=>Jn,_mergeDicts:()=>P,_mergeLists:()=>Gn,_mergeObj:()=>Kn,_mergeStatus:()=>Bn,coerceMessageLikeToMessage:()=>si,collapseToolCallChunks:()=>mi,convertToChunk:()=>pi,convertToOpenAIImageBlock:()=>Ht,convertToProviderContentBlock:()=>Gt,defaultTextSplitter:()=>nh,defaultToolCallParser:()=>or,filterMessages:()=>Gm,getBufferString:()=>ci,iife:()=>ri,isAIMessage:()=>ei,isAIMessageChunk:()=>ti,isBase64ContentBlock:()=>zt,isBaseMessage:()=>Yn,isBaseMessageChunk:()=>Xn,isChatMessage:()=>dr,isChatMessageChunk:()=>fr,isDataContentBlock:()=>Lt,isDirectToolOutput:()=>rr,isFunctionMessage:()=>hr,isFunctionMessageChunk:()=>gr,isHumanMessage:()=>yr,isHumanMessageChunk:()=>br,isIDContentBlock:()=>Vt,isMessage:()=>Kt,isOpenAIToolCallArray:()=>Un,isPlainTextContentBlock:()=>Bt,isSystemMessage:()=>wr,isSystemMessageChunk:()=>Tr,isToolMessage:()=>sr,isToolMessageChunk:()=>cr,isURLContentBlock:()=>Rt,mapChatMessagesToStoredMessages:()=>fi,mapStoredMessageToChatMessage:()=>ui,mapStoredMessagesToChatMessages:()=>di,mergeContent:()=>zn,mergeMessageRuns:()=>qm,mergeResponseMetadata:()=>Zn,mergeUsageMetadata:()=>tr,parseBase64DataUrl:()=>Wt,parseMimeType:()=>Ut,trimMessages:()=>Ym});export{Jd as $,jt as $n,ti as $t,rf as A,Qt as An,Hl as At,wf as B,k as Bn,ji as Bt,hm as C,Yn as Cn,Au as Ct,mf as D,ln as Dn,fu as Dt,Ap as E,fn as En,vu as Et,Cf as F,Lt as Fn,$i as Ft,of as G,St as Gn,si as Gt,ff as H,Dt as Hn,yi as Ht,hf as I,Rt as In,Ki as It,Zd as J,Ct as Jn,ri as Jt,lf as K,Pt as Kn,pi as Kt,_f as L,Wt as Ln,Hi as Lt,ef as M,Ht as Mn,fl as Mt,tf as N,Gt as Nn,ea as Nt,vf as O,rn as On,au as Ot,$d as P,zt as Pn,Zi as Pt,uf as Q,Ft as Qn,ei as Qt,gf as R,Ut as Rn,Ii as Rt,mm as S,qn as Sn,ju as St,Q as T,pn as Tn,_u as Tt,Yd as U,Ot as Un,Ti as Ut,Qd as V,D as Vn,Ai as Vt,af as W,Et as Wn,Oi as Wt,sf as X,Tt as Xn,$r as Xt,df as Y,Nt as Yn,ui as Yt,cf as Z,kt as Zn,ni as Zt,$ as _,ar as _n,G as _t,Om as a,Or as an,wd as at,gm as b,nr as bn,K as bt,Am as c,Sr as cn,md as ct,Lm as d,_r as dn,Hu as dt,Mr as en,wt as er,Y as et,Vm as f,vr as fn,zu as ft,Rm as g,ir as gn,Iu as gt,Hm as h,ur as hn,Lu as ht,Ym as i,kr as in,Td as it,nf as j,$t as jn,Ll as jt,pf as k,cn as kn,Wl as kt,Im as l,Cr as ln,pd as lt,Mm as m,lr as mn,Ru as mt,oh as n,jr as nn,Ud as nt,Bm as o,Dr as on,Cd as ot,jm as p,mr as pn,Vu as pt,Xd as q,Mt as qn,ci as qt,Gm as r,Ar as rn,Bd as rt,km as s,Er as sn,Sd as st,sh as t,Pr as tn,At as tr,J as tt,Nm as u,xr as un,sd as ut,zm as v,rr as vn,Mu as vt,fm as w,Xn as wn,Tu as wt,pm as x,Hn as xn,Fu as xt,ym as y,sr as yn,Nu as yt,Sf as z,A as zn,Ni as zt};