@mcp-use/inspector 0.22.1 → 0.22.2

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 (236) hide show
  1. package/dist/cdn/inspector.css +1 -1
  2. package/dist/cdn/inspector.js +26547 -26379
  3. package/dist/cli.js +6 -2
  4. package/dist/client/components/ChatTab.d.ts.map +1 -1
  5. package/dist/client/components/MCPAppsRenderer.d.ts.map +1 -1
  6. package/dist/client/components/OpenAIComponentRenderer.d.ts.map +1 -1
  7. package/dist/client/components/chat/ChatInput.d.ts +5 -1
  8. package/dist/client/components/chat/ChatInput.d.ts.map +1 -1
  9. package/dist/client/components/chat/ChatInputArea.d.ts +5 -1
  10. package/dist/client/components/chat/ChatInputArea.d.ts.map +1 -1
  11. package/dist/client/components/chat/ChatLandingForm.d.ts +5 -1
  12. package/dist/client/components/chat/ChatLandingForm.d.ts.map +1 -1
  13. package/dist/client/components/chat/ToolSelector.d.ts +13 -0
  14. package/dist/client/components/chat/ToolSelector.d.ts.map +1 -0
  15. package/dist/client/components/chat/useChatMessagesClientSide.d.ts +2 -1
  16. package/dist/client/components/chat/useChatMessagesClientSide.d.ts.map +1 -1
  17. package/dist/client/index.js +591 -402
  18. package/dist/server/{chunk-HOSWJXPT.js → chunk-IZPEEN7F.js} +6 -2
  19. package/dist/server/{chunk-CE5BNX35.js → chunk-JNAYXSVD.js} +1 -1
  20. package/dist/server/{chunk-N6DUXBZK.js → chunk-YF6BUSE7.js} +1 -1
  21. package/dist/server/cli.js +2 -2
  22. package/dist/server/index.js +3 -3
  23. package/dist/server/middleware.js +3 -3
  24. package/dist/server/server.js +2 -2
  25. package/dist/server/shared-routes.js +2 -2
  26. package/dist/server/shared-utils.d.ts.map +1 -1
  27. package/dist/server/shared-utils.js +1 -1
  28. package/dist/web/assets/{1c-CuB6KJny.js → 1c-DdyTu-k_.js} +1 -1
  29. package/dist/web/assets/{abnf-331NRzq6.js → abnf-C2DLuWsJ.js} +1 -1
  30. package/dist/web/assets/{accesslog-DPZ1SVBF.js → accesslog-BcPmBnek.js} +1 -1
  31. package/dist/web/assets/{actionscript-CuGZR-oV.js → actionscript-BX-T-H0r.js} +1 -1
  32. package/dist/web/assets/{ada-DRqvTj3B.js → ada-bFUa8rWB.js} +1 -1
  33. package/dist/web/assets/{angelscript-CP2_ypHm.js → angelscript--QyowWyi.js} +1 -1
  34. package/dist/web/assets/{apache-DP5S1Xwo.js → apache-CSPxjWTM.js} +1 -1
  35. package/dist/web/assets/{applescript-CLh7Bl5g.js → applescript-Beh8nYPj.js} +1 -1
  36. package/dist/web/assets/{arcade-L7ZIK7Vg.js → arcade-7vaiax_h.js} +1 -1
  37. package/dist/web/assets/{arduino-D38C-BRe.js → arduino-D67F76RP.js} +1 -1
  38. package/dist/web/assets/{armasm-BL0z-zkV.js → armasm-DWQZh6t7.js} +1 -1
  39. package/dist/web/assets/{asciidoc-BwOqzYyI.js → asciidoc-DCLwNk1M.js} +1 -1
  40. package/dist/web/assets/{aspectj-CsfF5uHW.js → aspectj-C7zkyhZG.js} +1 -1
  41. package/dist/web/assets/{autohotkey-BnfF2slP.js → autohotkey-D67jHa54.js} +1 -1
  42. package/dist/web/assets/{autoit-BUNufrnh.js → autoit-YshTFaZR.js} +1 -1
  43. package/dist/web/assets/{avrasm-BUwC6GGa.js → avrasm-QFQOAcRR.js} +1 -1
  44. package/dist/web/assets/{awk-BAn6DoRI.js → awk-h3G4tOxj.js} +1 -1
  45. package/dist/web/assets/{axapta-C5EQhsWz.js → axapta-Ck2tuXpL.js} +1 -1
  46. package/dist/web/assets/{bash-CXJ0QYm_.js → bash-SNro2FI9.js} +1 -1
  47. package/dist/web/assets/{basic-8InlTbNb.js → basic-CdFIzr_S.js} +1 -1
  48. package/dist/web/assets/{bnf-zpEK5Wju.js → bnf-CoDF7W_1.js} +1 -1
  49. package/dist/web/assets/{brainfuck-BhgAAx-v.js → brainfuck-Bt-q8Sif.js} +1 -1
  50. package/dist/web/assets/{c-CDPkc2Ya.js → c-CSy1LJEc.js} +1 -1
  51. package/dist/web/assets/{c-like-Ds21bDLY.js → c-like-CgJH8TzM.js} +1 -1
  52. package/dist/web/assets/{cal-DWpElLgG.js → cal-BN4ZaGC3.js} +1 -1
  53. package/dist/web/assets/{capnproto-96me6T8-.js → capnproto-DtQwy4ia.js} +1 -1
  54. package/dist/web/assets/{ceylon-Eu9VMqL5.js → ceylon-rt4387UK.js} +1 -1
  55. package/dist/web/assets/{clean-Bw3NaeUf.js → clean-Cyb94-bm.js} +1 -1
  56. package/dist/web/assets/{client-Dqtz8Ili.js → client-hyRgVCty.js} +3 -3
  57. package/dist/web/assets/{clojure-CcB35oPu.js → clojure-CLewI5lA.js} +1 -1
  58. package/dist/web/assets/{clojure-repl-UmCtFENG.js → clojure-repl-BtzgAt1p.js} +1 -1
  59. package/dist/web/assets/{cmake-BNsFX7mM.js → cmake-DWrK9r_0.js} +1 -1
  60. package/dist/web/assets/{coffeescript-BO-bY-7g.js → coffeescript-dC8dxgju.js} +1 -1
  61. package/dist/web/assets/{coq-DxEbCmAp.js → coq-Dx-VjjMG.js} +1 -1
  62. package/dist/web/assets/{core-Ca6TmLdX.js → core-l5FbiT9y.js} +1 -1
  63. package/dist/web/assets/{cos-D7p4YQ1F.js → cos-8hM_upPC.js} +1 -1
  64. package/dist/web/assets/{cpp-BfXjKrw-.js → cpp-C9q7oMVc.js} +1 -1
  65. package/dist/web/assets/{crmsh-Cu_wHzWI.js → crmsh-CM-iDW78.js} +1 -1
  66. package/dist/web/assets/{crystal-B4ffFRgA.js → crystal-B89CGmJl.js} +1 -1
  67. package/dist/web/assets/{csharp-F3YLadH3.js → csharp-BML5bF5U.js} +1 -1
  68. package/dist/web/assets/{csp-BLkoFjJ1.js → csp-BFgIYW7p.js} +1 -1
  69. package/dist/web/assets/{css-CBlOEu5y.js → css-Bmr2MmHJ.js} +1 -1
  70. package/dist/web/assets/{d-B8LLg7Ap.js → d-Bl1waUG7.js} +1 -1
  71. package/dist/web/assets/{dart-Bg7_Weak.js → dart-7WM1pTL7.js} +1 -1
  72. package/dist/web/assets/{delphi-CUFJtF08.js → delphi-BATb_6La.js} +1 -1
  73. package/dist/web/assets/{diff-D6IyExXS.js → diff-DQixhTxV.js} +1 -1
  74. package/dist/web/assets/{display-A5IEINAP-CalMK9h7.js → display-A5IEINAP-CIPa27wl.js} +2 -2
  75. package/dist/web/assets/{django-B-UTY01C.js → django-BaiMyL7a.js} +1 -1
  76. package/dist/web/assets/{dns-DfGDf7is.js → dns-B9LMXwq0.js} +1 -1
  77. package/dist/web/assets/{dockerfile-BYeQ3jyi.js → dockerfile-CgRRyc7d.js} +1 -1
  78. package/dist/web/assets/{dos-B_5-_6xr.js → dos-CUi0wmYe.js} +1 -1
  79. package/dist/web/assets/{dsconfig-uyDAQQAU.js → dsconfig-CtHPMV_z.js} +1 -1
  80. package/dist/web/assets/{dts-D75DwEM4.js → dts-Da6KiRGb.js} +1 -1
  81. package/dist/web/assets/{dust-JsNLCukW.js → dust-CtSB5RuR.js} +1 -1
  82. package/dist/web/assets/{ebnf-BP6c5l4a.js → ebnf-Civ7z3Sl.js} +1 -1
  83. package/dist/web/assets/{elixir-CUhtoXbR.js → elixir-BRz9w0Jz.js} +1 -1
  84. package/dist/web/assets/{elm-CKMhE8ah.js → elm-BLvIF2ZJ.js} +1 -1
  85. package/dist/web/assets/{embeddings-LX6aYruq.js → embeddings-DgQZkbYX.js} +1 -1
  86. package/dist/web/assets/{erb-CIx8MUO5.js → erb-yf3e-otT.js} +1 -1
  87. package/dist/web/assets/{erlang-repl-k7jT--Ou.js → erlang-repl-ygAXsKis.js} +1 -1
  88. package/dist/web/assets/{erlang-CkXPsz4M.js → erlang-u1gFvkzN.js} +1 -1
  89. package/dist/web/assets/{excel-C5SkgBGz.js → excel-Dr1VKgu5.js} +1 -1
  90. package/dist/web/assets/{fix-_4ZjoSTH.js → fix-CQ9USTvQ.js} +1 -1
  91. package/dist/web/assets/{flix-DnrR-dRx.js → flix-CK8VWwdt.js} +1 -1
  92. package/dist/web/assets/{fortran-CD6uDQX4.js → fortran-ChxBIVaA.js} +1 -1
  93. package/dist/web/assets/{fsharp-DTtzfUsx.js → fsharp-C2VB7uZ8.js} +1 -1
  94. package/dist/web/assets/{gams-CQk2cq7o.js → gams-cNOVPE3r.js} +1 -1
  95. package/dist/web/assets/{gauss-CtDmpxAf.js → gauss-Bqbzwh3H.js} +1 -1
  96. package/dist/web/assets/{gcode-B_EYK0Vg.js → gcode-CCf3GJpC.js} +1 -1
  97. package/dist/web/assets/{gherkin-DVcj5Cvn.js → gherkin-zMG7sQxB.js} +1 -1
  98. package/dist/web/assets/{glsl-BoRlfwJN.js → glsl-ChXPtZtn.js} +1 -1
  99. package/dist/web/assets/{gml-DwXf4s-K.js → gml-Dkbq2p7u.js} +1 -1
  100. package/dist/web/assets/{go-jKSz3kk6.js → go-C_rm61mN.js} +1 -1
  101. package/dist/web/assets/{golo-Dz5XOjjS.js → golo-BHw2HzNW.js} +1 -1
  102. package/dist/web/assets/{gradle-CG3C4PH5.js → gradle-dmNWlxt5.js} +1 -1
  103. package/dist/web/assets/{groovy-SRcDLXTF.js → groovy-BYRQ-Iq8.js} +1 -1
  104. package/dist/web/assets/{haml-CJsy3-F-.js → haml-CUGq_1r0.js} +1 -1
  105. package/dist/web/assets/{handlebars-LN8E0NSL.js → handlebars-ClqAsR9Y.js} +1 -1
  106. package/dist/web/assets/{haskell-ZP5N77Rb.js → haskell-D1EUHyyy.js} +1 -1
  107. package/dist/web/assets/{haxe-S_8gGOoI.js → haxe-D5_584-N.js} +1 -1
  108. package/dist/web/assets/{hsp-KqF2E7-o.js → hsp-CxOObZJt.js} +1 -1
  109. package/dist/web/assets/{htmlbars-Bw_UyB1p.js → htmlbars-BcxYs9JO.js} +1 -1
  110. package/dist/web/assets/{http-BI5U1FE3.js → http-IoGXsslz.js} +1 -1
  111. package/dist/web/assets/{hy-BAOLWsZC.js → hy-DOezFVYJ.js} +1 -1
  112. package/dist/web/assets/{index-ChIi2Veb.js → index-58vKJ_rW.js} +1 -1
  113. package/dist/web/assets/{index-BJOEo8tI.js → index-BQMLPync.js} +1 -1
  114. package/dist/web/assets/{index-DtyH_PEF.js → index-BWHJKdRK.js} +1 -1
  115. package/dist/web/assets/index-Br5Lp-nB.css +1 -0
  116. package/dist/web/assets/{index-Bmd2u1yJ.js → index-Brj1Oahm.js} +1 -1
  117. package/dist/web/assets/{index-Cz7z8sOR.js → index-BzCXH-MY.js} +1 -1
  118. package/dist/web/assets/{index-YcAOTRMN.js → index-CeFusmJF.js} +155 -155
  119. package/dist/web/assets/{index-DUSfaXA6.js → index-Df6PS_lJ.js} +1 -1
  120. package/dist/web/assets/{inform7-DgEbiTHe.js → inform7-4DkSrciU.js} +1 -1
  121. package/dist/web/assets/{ini-VsC63Yhp.js → ini-BAOejxzX.js} +1 -1
  122. package/dist/web/assets/{irpf90-BPXrE0Br.js → irpf90-CPhvVsrR.js} +1 -1
  123. package/dist/web/assets/{isbl-Dz4HkKrY.js → isbl-B9cEpNQ2.js} +1 -1
  124. package/dist/web/assets/{java-C5QDkp3s.js → java-B4D9vUuB.js} +1 -1
  125. package/dist/web/assets/{javascript-Qw1A7HIi.js → javascript-BUcy5JSl.js} +1 -1
  126. package/dist/web/assets/{jboss-cli-DjxxWoe7.js → jboss-cli-rk3boy7C.js} +1 -1
  127. package/dist/web/assets/{json-DwXmVB99.js → json-DMjBKfEa.js} +1 -1
  128. package/dist/web/assets/{julia-_UEF-d-n.js → julia-ByXC6uTj.js} +1 -1
  129. package/dist/web/assets/{julia-repl-BmGjKqDN.js → julia-repl-BRG6tLsN.js} +1 -1
  130. package/dist/web/assets/{kotlin-BGX09JNe.js → kotlin-LVfLRQA6.js} +1 -1
  131. package/dist/web/assets/{langfuse-U2OEF7K7-oUFfuCA2.js → langfuse-U2OEF7K7-BHNkft2N.js} +28 -28
  132. package/dist/web/assets/{lasso-CMKn1wD1.js → lasso-BcDeHYYs.js} +1 -1
  133. package/dist/web/assets/{latex-CSuZLxub.js → latex-BQLu7e0M.js} +1 -1
  134. package/dist/web/assets/{ldif-DtYZcb6_.js → ldif-MoWOvygf.js} +1 -1
  135. package/dist/web/assets/{leaf-Dm7kHn1u.js → leaf-Dc_ryT_U.js} +1 -1
  136. package/dist/web/assets/{less-BduOo7w1.js → less-xL-2sUOW.js} +1 -1
  137. package/dist/web/assets/{lisp-CTN_y443.js → lisp-CQgkxiVN.js} +1 -1
  138. package/dist/web/assets/{livecodeserver-Bt_3a5Le.js → livecodeserver-CnHs8DDk.js} +1 -1
  139. package/dist/web/assets/{livescript-fany4WHq.js → livescript-Bq3GcA8X.js} +1 -1
  140. package/dist/web/assets/{llms-CaZsx5qn.js → llms-DJAqua6W.js} +1 -1
  141. package/dist/web/assets/{llvm-BPeNPow9.js → llvm-g2SZAh5n.js} +1 -1
  142. package/dist/web/assets/{lsl-CUkRosfV.js → lsl-duYC8WGZ.js} +1 -1
  143. package/dist/web/assets/{lua-BYvWg4jg.js → lua-BKi5mh_G.js} +1 -1
  144. package/dist/web/assets/{makefile-oS53Vg0z.js → makefile-BqeicODu.js} +1 -1
  145. package/dist/web/assets/{markdown-D_B0fAXx.js → markdown-BG4LCYiF.js} +1 -1
  146. package/dist/web/assets/{mathematica-DKe-IuUK.js → mathematica-abL0r-fQ.js} +1 -1
  147. package/dist/web/assets/{matlab-D_21Tl-L.js → matlab-UvEnHOa4.js} +1 -1
  148. package/dist/web/assets/{maxima-DUtL1egA.js → maxima-WaftEzY-.js} +1 -1
  149. package/dist/web/assets/{mel-LAIz87bj.js → mel-B2MSGRGp.js} +1 -1
  150. package/dist/web/assets/{mercury-zYnf0BJA.js → mercury-D-B5OKnw.js} +1 -1
  151. package/dist/web/assets/{mipsasm-By1nFx6c.js → mipsasm-BN0bNdeJ.js} +1 -1
  152. package/dist/web/assets/{mizar-Bzhf-tV1.js → mizar-B9qd-OhV.js} +1 -1
  153. package/dist/web/assets/{mojolicious-B8QJxbI8.js → mojolicious-DojZjej7.js} +1 -1
  154. package/dist/web/assets/{monkey-Z_CyDrLh.js → monkey-DTUG_uUK.js} +1 -1
  155. package/dist/web/assets/{moonscript-CoDseIDC.js → moonscript-BxxoAw0w.js} +1 -1
  156. package/dist/web/assets/{n1ql-BEBUEhhE.js → n1ql-DoMSEnVI.js} +1 -1
  157. package/dist/web/assets/{nginx-BGCHEvnU.js → nginx-Ce5-hgf7.js} +1 -1
  158. package/dist/web/assets/{nim-Ctrpw--E.js → nim--cUhot81.js} +1 -1
  159. package/dist/web/assets/{nix-Caa5UC27.js → nix-CFzICQwT.js} +1 -1
  160. package/dist/web/assets/{node-repl-sr3s7jQZ.js → node-repl-8uW0BP3C.js} +1 -1
  161. package/dist/web/assets/{nsis-CzkCLfi2.js → nsis-D85QEHck.js} +1 -1
  162. package/dist/web/assets/{objectivec-jvD65_0I.js → objectivec-CO4ZKM1N.js} +1 -1
  163. package/dist/web/assets/{ocaml-DhDYdcp2.js → ocaml-MdZmIFP9.js} +1 -1
  164. package/dist/web/assets/{openscad-BqnRwGZd.js → openscad-Dd_k-u5o.js} +1 -1
  165. package/dist/web/assets/{oxygene-Cd0jRim3.js → oxygene-C9_JJ-Tz.js} +1 -1
  166. package/dist/web/assets/{parser3-BETxqEki.js → parser3--hakx1TP.js} +1 -1
  167. package/dist/web/assets/{perl-knvs0MzJ.js → perl-Bryi0MIt.js} +1 -1
  168. package/dist/web/assets/{pf-DiXaovgm.js → pf-ZaeD0XU8.js} +1 -1
  169. package/dist/web/assets/{pgsql-BWEvOXP5.js → pgsql-9scnk6gR.js} +1 -1
  170. package/dist/web/assets/{php-fyvUpIS6.js → php-Fdiy0MkS.js} +1 -1
  171. package/dist/web/assets/{php-template-Bvb-N_hu.js → php-template-BYeCSEy4.js} +1 -1
  172. package/dist/web/assets/{plaintext-Dwt8jzyJ.js → plaintext-FbFisAWv.js} +1 -1
  173. package/dist/web/assets/{pony-Cfelzwqf.js → pony-B0HARvcw.js} +1 -1
  174. package/dist/web/assets/{powershell-2b2YR7rM.js → powershell-DUssROtG.js} +1 -1
  175. package/dist/web/assets/{processing-CgyyQkLr.js → processing-BQZO45D3.js} +1 -1
  176. package/dist/web/assets/{profile-CHSonwOR.js → profile-CcGplmcc.js} +1 -1
  177. package/dist/web/assets/{prolog-CArpL4nb.js → prolog-B0NhCbAQ.js} +1 -1
  178. package/dist/web/assets/{properties-B7x5j4f3.js → properties-CWjoVJ5W.js} +1 -1
  179. package/dist/web/assets/{protobuf-DbZMyS9y.js → protobuf-D58gQeRM.js} +1 -1
  180. package/dist/web/assets/{puppet-CyK4RmCj.js → puppet-Ba9doIt2.js} +1 -1
  181. package/dist/web/assets/{purebasic-Bu9BNLQf.js → purebasic-BrH-D46w.js} +1 -1
  182. package/dist/web/assets/{python-DpcgEz0v.js → python-CjvAeSv8.js} +1 -1
  183. package/dist/web/assets/{python-repl-BAoj7DrU.js → python-repl-Jgv_SkQ0.js} +1 -1
  184. package/dist/web/assets/{q-aLpDzBqb.js → q-DgYB_ewM.js} +1 -1
  185. package/dist/web/assets/{qml-CF8YT9EP.js → qml-C7I-vh-W.js} +1 -1
  186. package/dist/web/assets/{r-DJifPsK_.js → r-DUpFDXxH.js} +1 -1
  187. package/dist/web/assets/{reasonml-DYlZCQtf.js → reasonml-Dxs-bF-2.js} +1 -1
  188. package/dist/web/assets/{rib-BWlooZzU.js → rib-CQL270qQ.js} +1 -1
  189. package/dist/web/assets/{roboconf-B3mKPOxb.js → roboconf-krxtbKe1.js} +1 -1
  190. package/dist/web/assets/{routeros-Ri82AIpo.js → routeros-BGBHdfxg.js} +1 -1
  191. package/dist/web/assets/{rsl-YFzXeAfb.js → rsl-CxAtY_02.js} +1 -1
  192. package/dist/web/assets/{ruby-CjV_PTlL.js → ruby-DJm1xcVx.js} +1 -1
  193. package/dist/web/assets/{ruleslanguage-DJCtPhmJ.js → ruleslanguage-BnhvTD6g.js} +1 -1
  194. package/dist/web/assets/{rust-T_ZZbr83.js → rust-DQe5T9WQ.js} +1 -1
  195. package/dist/web/assets/{sas-DnThN-QA.js → sas-6xbHPzOh.js} +1 -1
  196. package/dist/web/assets/{scala-CiCGCGBM.js → scala-DZlwYVr9.js} +1 -1
  197. package/dist/web/assets/{scheme-C81ecRNU.js → scheme-DXL_Buip.js} +1 -1
  198. package/dist/web/assets/{scilab-yIe92bs8.js → scilab-CKRl_kfB.js} +1 -1
  199. package/dist/web/assets/{scss-BGCT6i58.js → scss-jr09pBlW.js} +1 -1
  200. package/dist/web/assets/{shell-CtJaW7qj.js → shell-CxU4VQpG.js} +1 -1
  201. package/dist/web/assets/{smali-D9JxR6Ok.js → smali-BsXFpLll.js} +1 -1
  202. package/dist/web/assets/{smalltalk-Cc681-eJ.js → smalltalk-D2nr_49h.js} +1 -1
  203. package/dist/web/assets/{sml-CTRWATz0.js → sml-B16pEEUV.js} +1 -1
  204. package/dist/web/assets/{sqf-DSWEsa4V.js → sqf-BRaN4nE_.js} +1 -1
  205. package/dist/web/assets/{sql-CDB6g9ay.js → sql-CeIac2_e.js} +1 -1
  206. package/dist/web/assets/{sql_more-CpMC6pU4.js → sql_more-ZIMlJNGg.js} +1 -1
  207. package/dist/web/assets/{stan-BHnXBW_m.js → stan-DmpIhD_z.js} +1 -1
  208. package/dist/web/assets/{stata-84iUAWPp.js → stata-0ytqR1Ib.js} +1 -1
  209. package/dist/web/assets/{stdio-ZJFIZK2F-DAa98oll.js → stdio-PVTCK7WZ-C_E3pv0k.js} +1 -1
  210. package/dist/web/assets/{step21-DDfRrzcc.js → step21-C5gS7qwT.js} +1 -1
  211. package/dist/web/assets/{stylus-6UGB2DbU.js → stylus-DUzDJYfR.js} +1 -1
  212. package/dist/web/assets/{subunit-CI6BjWYM.js → subunit-BgugsJpP.js} +1 -1
  213. package/dist/web/assets/{swift-gZKjqZzX.js → swift-Cq31xV9A.js} +1 -1
  214. package/dist/web/assets/{taggerscript-4a4rpAZe.js → taggerscript-D6rUQ5Ju.js} +1 -1
  215. package/dist/web/assets/{tap-1yGDzo5T.js → tap-DkraFPBQ.js} +1 -1
  216. package/dist/web/assets/{tcl-Blqm3M6H.js → tcl-87kkAxdg.js} +1 -1
  217. package/dist/web/assets/{thrift-SCSYAnoo.js → thrift-CHkbhRQC.js} +1 -1
  218. package/dist/web/assets/{tp-CJiYvF2Z.js → tp-D5drOrfs.js} +1 -1
  219. package/dist/web/assets/{twig-CwKcbSAY.js → twig-JUSSxmsN.js} +1 -1
  220. package/dist/web/assets/{typescript-Dfq7Dw6S.js → typescript-DxY7tpO6.js} +1 -1
  221. package/dist/web/assets/{vala-CwjTTkCe.js → vala-BKhreswN.js} +1 -1
  222. package/dist/web/assets/{vbnet-DkyZUDFs.js → vbnet-BHYN5PHo.js} +1 -1
  223. package/dist/web/assets/{vbscript-D7mSa0kc.js → vbscript-eErGIKc5.js} +1 -1
  224. package/dist/web/assets/{vbscript-html-4muOpfOP.js → vbscript-html-BVPWl6WP.js} +1 -1
  225. package/dist/web/assets/{verilog-CTx73zAb.js → verilog-DbaUNZdo.js} +1 -1
  226. package/dist/web/assets/{vhdl-bNkZElSZ.js → vhdl-UR-HSHjG.js} +1 -1
  227. package/dist/web/assets/{vim-BEHLt-ak.js → vim-Dk1XUiA7.js} +1 -1
  228. package/dist/web/assets/{x86asm-LPghO6jq.js → x86asm-B9c_N4c6.js} +1 -1
  229. package/dist/web/assets/{xl-C1a1l7dp.js → xl-swOLfPCO.js} +1 -1
  230. package/dist/web/assets/{xml-DkVcEWrP.js → xml-BpZLXHyv.js} +1 -1
  231. package/dist/web/assets/{xquery-BC8Ygt24.js → xquery-RWTIln5p.js} +1 -1
  232. package/dist/web/assets/{yaml-dlNOCKmh.js → yaml-k20kwc4p.js} +1 -1
  233. package/dist/web/assets/{zephir-Bif85EPV.js → zephir-7ED-2Mm2.js} +1 -1
  234. package/dist/web/index.html +3 -3
  235. package/package.json +2 -2
  236. package/dist/web/assets/index-B53yBrEF.css +0 -1
@@ -1,26 +1,26 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-Dqtz8Ili.js","assets/index-YcAOTRMN.js","assets/index-B53yBrEF.css","assets/display-A5IEINAP-CalMK9h7.js"])))=>i.map(i=>d[i]);
2
- import{bq as $c,br as eo,bs as jc,t as R,bt as Wr,b7 as Gr,bu as ve,b4 as Lc,bp as Dc,b9 as Tn,b2 as re,bb as Fc,b3 as Uc,bv as Vc,K as y,aQ as Re,e as mn,bw as Bc,bx as En,A as He,by as Ss,n as X,aC as hn,aA as se,U as P,ab as ae,j as zc,C as Hc,bz as Wc,z as Do,aY as Ii,bA as oe,aE as xn,bB as _n,X as Pi,S as Ue,bC as to,Q as Me,V as Cs,W as Qt,aJ as yr,bD as Gc,bE as Kc,bF as Jc,bG as qc,bH as Yc,bI as Xc,bJ as Zc,bK as Qc,bL as eu,bM as tu,bN as nu,bO as ru,bP as su,bQ as ou,bR as iu,bS as au,bT as lu,bU as cu,bV as uu,bW as hu,a1 as du,bX as fu,bY as pu,bZ as mu,p as vn,m as $e,a2 as it,aN as en,b_ as gu,Y as yu,aZ as Fo,aO as wu,b$ as Uo,c0 as Vo,c1 as wr,c2 as bt,b5 as no,ax as ks,aw as Ts,az as bu,ad as _u,as as ro,ay as so,an as te,av as nt,o as K,c3 as Le,c4 as Oi,b as oo,l as j,c5 as vu,c6 as Su,c7 as Cu,ac as Ni,at as ku,x as Tu,aR as Eu,T as xu,c8 as Dn,c9 as De,s as ie,ca as Ri,cb as tn,cc as Mn,cd as Mu,ce as Ke,cf as _t,cg as z,au as Au,f as io,aB as Iu,a as Pu,ch as $i,ci as Fn,cj as gt,ck as Ou,bl as Nu,bj as Ru,bi as $u,cl as ju,H as ji,cm as Xn,cn as Bo,u as nn,bg as Zn,E as Lu,co as Du,J as zo,cp as Fu,cq as Uu,cr as Vu,O as Bu,cs as zu,ct as Hu,cu as Ho}from"./index-YcAOTRMN.js";import{a as Qn,S as jr,b as Wu,t as Li,T as Gu,D as Ku}from"./index-Cz7z8sOR.js";import{h as Un,s as Di,g as Fi,d as Ju,l as qu,m as Yu,I as Xu,C as Zu,n as Qu,t as eh,o as th,p as nh,q as rh,r as sh,u as oh,v as ih,w as ah,x as lh,y as ch,z as uh,R as hh,A as Wo,e as dh}from"./index-DUSfaXA6.js";import{E as Ui,a as fh,e as ph}from"./embeddings-LX6aYruq.js";import{L as Vi,o as mh,l as gh}from"./llms-CaZsx5qn.js";var Kr,Hn,Jr=0,qr=0;function yh(t,e,n){var r=0,s=e||new Array(16);t=t||{};var o=t.node,i=t.clockseq;if(t._v6||(o||(o=Kr),i==null&&(i=Hn)),o==null||i==null){var a=t.random||(t.rng||$c)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Kr&&!t._v6&&(o[0]|=1,Kr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Hn===void 0&&!t._v6&&(Hn=i))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:qr+1,u=l-Jr+(c-qr)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||l>Jr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Jr=l,qr=c,Hn=i,l+=122192928e5;var d=((l&268435455)*1e4+c)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var h=l/4294967296*1e4&268435455;s[r++]=h>>>8&255,s[r++]=h&255,s[r++]=h>>>24&15|16,s[r++]=h>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var f=0;f<6;++f)s[r+f]=o[f];return e||eo(s)}function wh(t){var e=typeof t=="string"?jc(t):t,n=bh(e);return typeof t=="string"?eo(n):n}function bh(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function Go(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function Ko(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Go(Object(n),!0).forEach(function(r){_h(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Go(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function _h(t,e,n){return(e=vh(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vh(t){var e=Sh(t,"string");return typeof e=="symbol"?e:e+""}function Sh(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ch(t={},e,n=0){var r=yh(Ko(Ko({},t),{},{_v6:!0}),new Uint8Array(16));return r=wh(r),eo(r)}async function*Bi(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}R(Bi,"streamEventsToAISDK");function zi(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}R(zi,"createReadableStreamFromGenerator");async function*Hi(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-hyRgVCty.js","assets/index-CeFusmJF.js","assets/index-Br5Lp-nB.css","assets/display-A5IEINAP-CIPa27wl.js"])))=>i.map(i=>d[i]);
2
+ import{bq as $c,br as eo,bs as jc,t as R,bt as Wr,b7 as Gr,bu as ve,b4 as Lc,bp as Dc,b9 as kn,b2 as re,bb as Fc,b3 as Uc,bv as Vc,K as y,aQ as Re,e as mn,bw as Bc,bx as En,A as He,by as Ss,n as X,aC as hn,aA as se,U as P,ab as ae,j as zc,C as Hc,bz as Wc,z as Do,aY as Ii,bA as oe,aE as xn,bB as _n,X as Pi,S as Ue,bC as to,Q as Me,V as Cs,W as Qt,aJ as yr,bD as Gc,bE as Kc,bF as Jc,bG as qc,bH as Yc,bI as Xc,bJ as Zc,bK as Qc,bL as eu,bM as tu,bN as nu,bO as ru,bP as su,bQ as ou,bR as iu,bS as au,bT as lu,bU as cu,bV as uu,bW as hu,a1 as du,bX as fu,bY as pu,bZ as mu,p as vn,m as $e,a2 as it,aN as en,b_ as gu,Y as yu,aZ as Fo,aO as wu,b$ as Uo,c0 as Vo,c1 as wr,c2 as bt,b5 as no,ax as Ts,aw as ks,az as bu,ad as _u,as as ro,ay as so,an as te,av as nt,o as K,c3 as Le,c4 as Oi,b as oo,l as j,c5 as vu,c6 as Su,c7 as Cu,ac as Ni,at as Tu,x as ku,aR as Eu,T as xu,c8 as Dn,c9 as De,s as ie,ca as Ri,cb as tn,cc as Mn,cd as Mu,ce as Ke,cf as _t,cg as z,au as Au,f as io,aB as Iu,a as Pu,ch as $i,ci as Fn,cj as gt,ck as Ou,bl as Nu,bj as Ru,bi as $u,cl as ju,H as ji,cm as Xn,cn as Bo,u as nn,bg as Zn,E as Lu,co as Du,J as zo,cp as Fu,cq as Uu,cr as Vu,O as Bu,cs as zu,ct as Hu,cu as Ho}from"./index-CeFusmJF.js";import{a as Qn,S as jr,b as Wu,t as Li,T as Gu,D as Ku}from"./index-BzCXH-MY.js";import{h as Un,s as Di,g as Fi,d as Ju,l as qu,m as Yu,I as Xu,C as Zu,n as Qu,t as eh,o as th,p as nh,q as rh,r as sh,u as oh,v as ih,w as ah,x as lh,y as ch,z as uh,R as hh,A as Wo,e as dh}from"./index-Df6PS_lJ.js";import{E as Ui,a as fh,e as ph}from"./embeddings-DgQZkbYX.js";import{L as Vi,o as mh,l as gh}from"./llms-DJAqua6W.js";var Kr,Hn,Jr=0,qr=0;function yh(t,e,n){var r=0,s=e||new Array(16);t=t||{};var o=t.node,i=t.clockseq;if(t._v6||(o||(o=Kr),i==null&&(i=Hn)),o==null||i==null){var a=t.random||(t.rng||$c)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Kr&&!t._v6&&(o[0]|=1,Kr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Hn===void 0&&!t._v6&&(Hn=i))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:qr+1,u=l-Jr+(c-qr)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||l>Jr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Jr=l,qr=c,Hn=i,l+=122192928e5;var d=((l&268435455)*1e4+c)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var h=l/4294967296*1e4&268435455;s[r++]=h>>>8&255,s[r++]=h&255,s[r++]=h>>>24&15|16,s[r++]=h>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var f=0;f<6;++f)s[r+f]=o[f];return e||eo(s)}function wh(t){var e=typeof t=="string"?jc(t):t,n=bh(e);return typeof t=="string"?eo(n):n}function bh(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function Go(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function Ko(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Go(Object(n),!0).forEach(function(r){_h(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Go(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function _h(t,e,n){return(e=vh(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vh(t){var e=Sh(t,"string");return typeof e=="symbol"?e:e+""}function Sh(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ch(t={},e,n=0){var r=yh(Ko(Ko({},t),{},{_v6:!0}),new Uint8Array(16));return r=wh(r),eo(r)}async function*Bi(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}R(Bi,"streamEventsToAISDK");function zi(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}R(zi,"createReadableStreamFromGenerator");async function*Hi(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
3
3
  🔧 Using tool: ${e.name}
4
4
  `;break;case"on_tool_end":yield`
5
5
  ✅ Tool completed: ${e.name}
6
- `;break}}R(Hi,"streamEventsToAISDKWithTools");var Ut,kh=(Ut=class{static convert(e){return this.parseSchema(e)}static matchesCondition(e,n){if(!n.properties)return!0;if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;for(const[s,o]of Object.entries(n.properties)){if(!(s in r)){if("const"in o)return!1;continue}const i=r[s];if("const"in o&&i!==o.const||"minimum"in o&&typeof i=="number"&&i<o.minimum||"maximum"in o&&typeof i=="number"&&i>o.maximum)return!1}return!0}static validateConditionalSchema(e,n,r){this.validateRequiredProperties(e,n,r),this.validatePropertyPatterns(e,n,r),this.validateNestedConditions(e,n,r)}static validateRequiredProperties(e,n,r){if(n.required){if(typeof e!="object"||e===null){for(const s of n.required)r.addIssue({code:Wr.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:Wr.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(e,n,r){if(!n.properties||typeof e!="object"||e===null||Array.isArray(e))return;const s=e;for(const[o,i]of Object.entries(n.properties)){if(!(o in s))continue;const a=s[o];i.pattern&&typeof a=="string"&&(new RegExp(i.pattern).test(a)||r.addIssue({code:Wr.custom,message:`String '${a}' does not match pattern '${i.pattern}'`,path:[o]}))}}static validateNestedConditions(e,n,r){if(!n.if||!n.then)return;this.matchesCondition(e,n.if)?this.validateConditionalSchema(e,n.then,r):n.else&&this.validateConditionalSchema(e,n.else,r)}static parseSchema(e){let n;return Array.isArray(e.type)?n=this.handleTypeArray(e):e.oneOf||e.anyOf||e.allOf?n=this.parseCombinator(e):e.if&&e.then?n=this.parseObject(e):e.properties&&(!e.type||e.type==="object")?n=this.parseObject(e):n=this.handleSingleType(e),e.description&&typeof n.describe=="function"&&(n=n.describe(e.description)),n}static handleTypeArray(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");return e.type.includes("null")?this.handleNullableType(e):this.createUnionFromTypes(e.type,e)}static handleNullableType(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");const n={...e};return n.type=e.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...e,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(e,n){const r=e.map(s=>{const o={...n,type:s};return this.parseSchema(o)});return Gr(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):ve();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return Lc();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Fc();let r=n;return r=this.applyNumberBounds(n,e),r=this.applyNumberMultipleOf(n,e),r=this.applyNumberEnum(n,e),r=this.applyIntegerConstraint(n,e),r}static applyNumberBounds(e,n){let r=e;return n.minimum!==void 0&&(r=n.exclusiveMinimum?r.gt(n.minimum):r.gte(n.minimum)),n.maximum!==void 0&&(r=n.exclusiveMaximum?r.lt(n.maximum):r.lte(n.maximum)),r}static applyNumberMultipleOf(e,n){return n.multipleOf===void 0?e:e.refine(r=>r%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(e,n){if(!n.enum)return e;const r=n.enum.filter(s=>typeof s=="number");return r.length===0?e:e.refine(s=>r.includes(s),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(e,n){return n.type!=="integer"?e:e.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(e){const n=Tn();let r=n;return e.format?this.applyStringFormat(n,e):(r=this.applyStringPattern(n,e),r=this.applyStringLength(n,e),r=this.applyStringEnum(n,e),r)}static applyStringFormat(e,n){if(!n.format)return e;switch(n.format){case"email":return e.email();case"date-time":return e.datetime();case"uri":return e.url();case"uuid":return e.uuid();case"date":return e.date();default:return e}}static applyStringPattern(e,n){if(!n.pattern)return e;const r=new RegExp(n.pattern);return e.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(e,n){const r=e;return n.minLength!==void 0&&(e=e.min(n.minLength)),n.maxLength!==void 0&&(e=e.max(n.maxLength)),r}static applyStringEnum(e,n){return n.enum?e.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):e}static parseArray(e){if(Array.isArray(e.items)){const o=e.items.map(i=>this.parseSchema(i));return Gr(o)}const n=e.items?this.parseSchema(e.items):ve(),r=Uc(n);let s=r;return s=this.applyArrayConstraints(r,e),s}static applyArrayConstraints(e,n){return n.minItems!==void 0&&(e=e.min(n.minItems)),n.maxItems!==void 0&&(e=e.max(n.maxItems)),n.uniqueItems?e.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);if(!e.properties&&e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return Dc(Tn(),r)}const n={};return this.processObjectProperties(e,n),this.processAdditionalProperties(e,re(n))}static processObjectProperties(e,n){const r=new Set(e.required||[]);if(e.properties)for(const[s,o]of Object.entries(e.properties)){const i=this.parseSchema(o);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(e,n){if(e.additionalProperties===!0)return n.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(e){const n=this.createBaseObjectSchema(e),r=e.if,s=e.then,o=e.else;return n.superRefine((i,a)=>{const l=this.applyDefaultValues(i,e);this.matchesCondition(l,r)?this.validateConditionalSchema(l,s,a):o&&this.validateConditionalSchema(l,o,a)})}static createBaseObjectSchema(e){const n={},r=new Set(e.required||[]);for(const[o,i]of Object.entries(e.properties||{})){const a=this.parseSchema(i);n[o]=r.has(o)?a:a.optional()}const s=re(n);return this.processAdditionalProperties(e,s)}static applyDefaultValues(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return e;const s={...e};if(!n.properties)return s;for(const[o,i]of Object.entries(n.properties))!(o in s)&&"default"in i&&(s[o]=i.default);return s}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw new Error("Unsupported schema type")}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return ve();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(Vc()):n.push(this.parseSchema(r));return n.length>=2?Gr(n):n.length===1?n[0]:ve()}static parseAllOf(e){if(e.length===0)return ve();if(e.length===1)return this.parseSchema(e[0]);const n=e.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(e,n){const r={...e,...n};if(e.properties&&n.properties){const s={...e.properties,...n.properties};r.properties=s}if(e.required&&n.required){const s=[...new Set([...e.required,...n.required])];r.required=s}return r}},R(Ut,"JSONSchemaToZod"),Ut),Vt,Wi=(Vt=class{disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,n){const r=new this(n);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(y.info("No active sessions found, creating new ones..."),await e.createAllSessions());const s=e.getAllActiveSessions(),o=Object.values(s).map(i=>i.connector);return r.createToolsFromConnectors(o)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const s=this.connectorToolMap.get(e);return y.debug(`Returning ${s.length} existing tools for connector`),s}const n=[];if(!await this.ensureConnectorInitialized(e))return[];for(const s of e.tools){const o=this.convertTool(s,e);o&&n.push(o)}return this.connectorToolMap.set(e,n),y.debug(`Loaded ${n.length} new tools for connector: ${n.map(s=>s?.name??String(s)).join(", ")}`),n}async createToolsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadToolsForConnector(r);n.push(...s)}return y.debug(`Available tools: ${n.length}`),n}async loadResourcesForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listAllResources())?.resources||[];if(this.convertResource)for(const i of o){const a=this.convertResource(i,e);a&&n.push(a)}y.debug(`Loaded ${n.length} new resources for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){y.warn(`Error loading resources for connector: ${s}`)}return n}async loadPromptsForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(const i of o){const a=this.convertPrompt(i,e);a&&n.push(a)}y.debug(`Loaded ${n.length} new prompts for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){y.warn(`Error loading prompts for connector: ${s}`)}return n}async createResourcesFromConnectors(e){const n=[];for(const r of e){const s=await this.loadResourcesForConnector(r);n.push(...s)}return y.debug(`Available resources: ${n.length}`),n}async createPromptsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadPromptsForConnector(r);n.push(...s)}return y.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){y.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return y.error(`Error initializing connector: ${n}`),!1}}return!0}},R(Vt,"BaseAdapter"),Vt);function Gi(t){try{return kh.convert(t)}catch(e){return y.warn(`Failed to convert JSON schema to Zod: ${e}`),ve()}}R(Gi,"schemaToZod");var Bt,xt=(Bt=class extends Wi{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?Gi(e.inputSchema):re({}).optional();return new Qn({name:e.name??"NO NAME",description:e.description??"",schema:r,func:R(async o=>{y.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(o)}`);try{const i=await n.callTool(e.name,o);return JSON.stringify(i)}catch(i){return y.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,n){const s=R(a=>a.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),o=e.uri;return new Qn({name:s,description:e.description||`Return the content of the resource located at URI ${o}.`,schema:re({}).optional(),func:R(async()=>{y.debug(`Resource tool: "${s}" called`);try{const a=await n.readResource(o);return a.contents&&a.contents.length>0?a.contents.map(l=>typeof l=="string"?l:l.text?l.text:l.uri?l.uri:JSON.stringify(l)).join(`
7
- `):"Resource is empty or unavailable"}catch(a){return y.error(`Error reading resource: ${a.message}`),`Error reading resource: ${String(a)}`}},"func")})}convertPrompt(e,n){let r=re({}).optional();if(e.arguments&&e.arguments.length>0){const o={};for(const i of e.arguments){const a=Tn();i.required!==!1?o[i.name]=a:o[i.name]=a.optional()}r=Object.keys(o).length>0?re(o):re({}).optional()}return new Qn({name:e.name,description:e.description||"",schema:r,func:R(async o=>{y.debug(`Prompt tool: "${e.name}" called with args: ${JSON.stringify(o)}`);try{const i=await n.getPrompt(e.name,o);return i.messages&&i.messages.length>0?i.messages.map(a=>typeof a=="string"?a:a.content?typeof a.content=="string"?a.content:JSON.stringify(a.content):JSON.stringify(a)).join(`
8
- `):"Prompt returned no messages"}catch(i){return y.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},R(Bt,"LangChainAdapter"),Bt),Th=Object.defineProperty,Ki=(t,e)=>{for(var n in e)Th(t,n,{get:e[n],enumerable:!0})},Eh={};Ki(Eh,{ConfigurableModel:()=>Es,MODEL_PROVIDER_CONFIG:()=>Lr,_inferModelProvider:()=>Yi,getChatModelByClassName:()=>qi,initChatModel:()=>lt});const Lr={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},fireworks:{package:"@langchain/community/chat_models/fireworks",className:"ChatFireworks",hasCircularDependency:!0},together:{package:"@langchain/community/chat_models/togetherai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/community/chat_models/perplexity",className:"ChatPerplexity",hasCircularDependency:!0}},Ji=Object.keys(Lr);async function qi(t){const e=Object.entries(Lr).find(([,r])=>r.className===t);if(!e)return;const[,n]=e;try{return(await import(n.package))[n.className]}catch(r){const s=r;if("code"in s&&s.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in s&&typeof s.message=="string"){const i=(s.message.startsWith("Error: ")?s.message.slice(7):s.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${i}. Please install with \`npm install ${i}\` or \`pnpm install ${i}\``)}throw r}}async function xh(t,e,n={}){const r=e||Yi(t);if(!r)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);const s=Lr[r];if(!s){const l=Ji.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
6
+ `;break}}R(Hi,"streamEventsToAISDKWithTools");var Ut,Th=(Ut=class{static convert(e){return this.parseSchema(e)}static matchesCondition(e,n){if(!n.properties)return!0;if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;for(const[s,o]of Object.entries(n.properties)){if(!(s in r)){if("const"in o)return!1;continue}const i=r[s];if("const"in o&&i!==o.const||"minimum"in o&&typeof i=="number"&&i<o.minimum||"maximum"in o&&typeof i=="number"&&i>o.maximum)return!1}return!0}static validateConditionalSchema(e,n,r){this.validateRequiredProperties(e,n,r),this.validatePropertyPatterns(e,n,r),this.validateNestedConditions(e,n,r)}static validateRequiredProperties(e,n,r){if(n.required){if(typeof e!="object"||e===null){for(const s of n.required)r.addIssue({code:Wr.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:Wr.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(e,n,r){if(!n.properties||typeof e!="object"||e===null||Array.isArray(e))return;const s=e;for(const[o,i]of Object.entries(n.properties)){if(!(o in s))continue;const a=s[o];i.pattern&&typeof a=="string"&&(new RegExp(i.pattern).test(a)||r.addIssue({code:Wr.custom,message:`String '${a}' does not match pattern '${i.pattern}'`,path:[o]}))}}static validateNestedConditions(e,n,r){if(!n.if||!n.then)return;this.matchesCondition(e,n.if)?this.validateConditionalSchema(e,n.then,r):n.else&&this.validateConditionalSchema(e,n.else,r)}static parseSchema(e){let n;return Array.isArray(e.type)?n=this.handleTypeArray(e):e.oneOf||e.anyOf||e.allOf?n=this.parseCombinator(e):e.if&&e.then?n=this.parseObject(e):e.properties&&(!e.type||e.type==="object")?n=this.parseObject(e):n=this.handleSingleType(e),e.description&&typeof n.describe=="function"&&(n=n.describe(e.description)),n}static handleTypeArray(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");return e.type.includes("null")?this.handleNullableType(e):this.createUnionFromTypes(e.type,e)}static handleNullableType(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");const n={...e};return n.type=e.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...e,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(e,n){const r=e.map(s=>{const o={...n,type:s};return this.parseSchema(o)});return Gr(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):ve();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return Lc();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Fc();let r=n;return r=this.applyNumberBounds(n,e),r=this.applyNumberMultipleOf(n,e),r=this.applyNumberEnum(n,e),r=this.applyIntegerConstraint(n,e),r}static applyNumberBounds(e,n){let r=e;return n.minimum!==void 0&&(r=n.exclusiveMinimum?r.gt(n.minimum):r.gte(n.minimum)),n.maximum!==void 0&&(r=n.exclusiveMaximum?r.lt(n.maximum):r.lte(n.maximum)),r}static applyNumberMultipleOf(e,n){return n.multipleOf===void 0?e:e.refine(r=>r%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(e,n){if(!n.enum)return e;const r=n.enum.filter(s=>typeof s=="number");return r.length===0?e:e.refine(s=>r.includes(s),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(e,n){return n.type!=="integer"?e:e.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(e){const n=kn();let r=n;return e.format?this.applyStringFormat(n,e):(r=this.applyStringPattern(n,e),r=this.applyStringLength(n,e),r=this.applyStringEnum(n,e),r)}static applyStringFormat(e,n){if(!n.format)return e;switch(n.format){case"email":return e.email();case"date-time":return e.datetime();case"uri":return e.url();case"uuid":return e.uuid();case"date":return e.date();default:return e}}static applyStringPattern(e,n){if(!n.pattern)return e;const r=new RegExp(n.pattern);return e.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(e,n){const r=e;return n.minLength!==void 0&&(e=e.min(n.minLength)),n.maxLength!==void 0&&(e=e.max(n.maxLength)),r}static applyStringEnum(e,n){return n.enum?e.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):e}static parseArray(e){if(Array.isArray(e.items)){const o=e.items.map(i=>this.parseSchema(i));return Gr(o)}const n=e.items?this.parseSchema(e.items):ve(),r=Uc(n);let s=r;return s=this.applyArrayConstraints(r,e),s}static applyArrayConstraints(e,n){return n.minItems!==void 0&&(e=e.min(n.minItems)),n.maxItems!==void 0&&(e=e.max(n.maxItems)),n.uniqueItems?e.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);if(!e.properties&&e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return Dc(kn(),r)}const n={};return this.processObjectProperties(e,n),this.processAdditionalProperties(e,re(n))}static processObjectProperties(e,n){const r=new Set(e.required||[]);if(e.properties)for(const[s,o]of Object.entries(e.properties)){const i=this.parseSchema(o);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(e,n){if(e.additionalProperties===!0)return n.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(e){const n=this.createBaseObjectSchema(e),r=e.if,s=e.then,o=e.else;return n.superRefine((i,a)=>{const l=this.applyDefaultValues(i,e);this.matchesCondition(l,r)?this.validateConditionalSchema(l,s,a):o&&this.validateConditionalSchema(l,o,a)})}static createBaseObjectSchema(e){const n={},r=new Set(e.required||[]);for(const[o,i]of Object.entries(e.properties||{})){const a=this.parseSchema(i);n[o]=r.has(o)?a:a.optional()}const s=re(n);return this.processAdditionalProperties(e,s)}static applyDefaultValues(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return e;const s={...e};if(!n.properties)return s;for(const[o,i]of Object.entries(n.properties))!(o in s)&&"default"in i&&(s[o]=i.default);return s}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw new Error("Unsupported schema type")}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return ve();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(Vc()):n.push(this.parseSchema(r));return n.length>=2?Gr(n):n.length===1?n[0]:ve()}static parseAllOf(e){if(e.length===0)return ve();if(e.length===1)return this.parseSchema(e[0]);const n=e.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(e,n){const r={...e,...n};if(e.properties&&n.properties){const s={...e.properties,...n.properties};r.properties=s}if(e.required&&n.required){const s=[...new Set([...e.required,...n.required])];r.required=s}return r}},R(Ut,"JSONSchemaToZod"),Ut),Vt,Wi=(Vt=class{disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,n){const r=new this(n);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(y.info("No active sessions found, creating new ones..."),await e.createAllSessions());const s=e.getAllActiveSessions(),o=Object.values(s).map(i=>i.connector);return r.createToolsFromConnectors(o)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const s=this.connectorToolMap.get(e);return y.debug(`Returning ${s.length} existing tools for connector`),s}const n=[];if(!await this.ensureConnectorInitialized(e))return[];for(const s of e.tools){const o=this.convertTool(s,e);o&&n.push(o)}return this.connectorToolMap.set(e,n),y.debug(`Loaded ${n.length} new tools for connector: ${n.map(s=>s?.name??String(s)).join(", ")}`),n}async createToolsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadToolsForConnector(r);n.push(...s)}return y.debug(`Available tools: ${n.length}`),n}async loadResourcesForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listAllResources())?.resources||[];if(this.convertResource)for(const i of o){const a=this.convertResource(i,e);a&&n.push(a)}y.debug(`Loaded ${n.length} new resources for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){y.warn(`Error loading resources for connector: ${s}`)}return n}async loadPromptsForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(const i of o){const a=this.convertPrompt(i,e);a&&n.push(a)}y.debug(`Loaded ${n.length} new prompts for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){y.warn(`Error loading prompts for connector: ${s}`)}return n}async createResourcesFromConnectors(e){const n=[];for(const r of e){const s=await this.loadResourcesForConnector(r);n.push(...s)}return y.debug(`Available resources: ${n.length}`),n}async createPromptsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadPromptsForConnector(r);n.push(...s)}return y.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){y.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return y.error(`Error initializing connector: ${n}`),!1}}return!0}},R(Vt,"BaseAdapter"),Vt);function Gi(t){try{return Th.convert(t)}catch(e){return y.warn(`Failed to convert JSON schema to Zod: ${e}`),ve()}}R(Gi,"schemaToZod");var Bt,xt=(Bt=class extends Wi{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?Gi(e.inputSchema):re({}).optional();return new Qn({name:e.name??"NO NAME",description:e.description??"",schema:r,func:R(async o=>{y.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(o)}`);try{const i=await n.callTool(e.name,o);return JSON.stringify(i)}catch(i){return y.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,n){const s=R(a=>a.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),o=e.uri;return new Qn({name:s,description:e.description||`Return the content of the resource located at URI ${o}.`,schema:re({}).optional(),func:R(async()=>{y.debug(`Resource tool: "${s}" called`);try{const a=await n.readResource(o);return a.contents&&a.contents.length>0?a.contents.map(l=>typeof l=="string"?l:l.text?l.text:l.uri?l.uri:JSON.stringify(l)).join(`
7
+ `):"Resource is empty or unavailable"}catch(a){return y.error(`Error reading resource: ${a.message}`),`Error reading resource: ${String(a)}`}},"func")})}convertPrompt(e,n){let r=re({}).optional();if(e.arguments&&e.arguments.length>0){const o={};for(const i of e.arguments){const a=kn();i.required!==!1?o[i.name]=a:o[i.name]=a.optional()}r=Object.keys(o).length>0?re(o):re({}).optional()}return new Qn({name:e.name,description:e.description||"",schema:r,func:R(async o=>{y.debug(`Prompt tool: "${e.name}" called with args: ${JSON.stringify(o)}`);try{const i=await n.getPrompt(e.name,o);return i.messages&&i.messages.length>0?i.messages.map(a=>typeof a=="string"?a:a.content?typeof a.content=="string"?a.content:JSON.stringify(a.content):JSON.stringify(a)).join(`
8
+ `):"Prompt returned no messages"}catch(i){return y.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},R(Bt,"LangChainAdapter"),Bt),kh=Object.defineProperty,Ki=(t,e)=>{for(var n in e)kh(t,n,{get:e[n],enumerable:!0})},Eh={};Ki(Eh,{ConfigurableModel:()=>Es,MODEL_PROVIDER_CONFIG:()=>Lr,_inferModelProvider:()=>Yi,getChatModelByClassName:()=>qi,initChatModel:()=>lt});const Lr={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},fireworks:{package:"@langchain/community/chat_models/fireworks",className:"ChatFireworks",hasCircularDependency:!0},together:{package:"@langchain/community/chat_models/togetherai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/community/chat_models/perplexity",className:"ChatPerplexity",hasCircularDependency:!0}},Ji=Object.keys(Lr);async function qi(t){const e=Object.entries(Lr).find(([,r])=>r.className===t);if(!e)return;const[,n]=e;try{return(await import(n.package))[n.className]}catch(r){const s=r;if("code"in s&&s.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in s&&typeof s.message=="string"){const i=(s.message.startsWith("Error: ")?s.message.slice(7):s.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${i}. Please install with \`npm install ${i}\` or \`pnpm install ${i}\``)}throw r}}async function xh(t,e,n={}){const r=e||Yi(t);if(!r)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);const s=Lr[r];if(!s){const l=Ji.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
9
9
 
10
10
  Supported model providers are: ${l}`)}const{modelProvider:o,...i}=n,a=await qi(s.className);return new a({model:t,...i})}function Yi(t){return t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("gpt-5")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?"openai":t.startsWith("claude")?"anthropic":t.startsWith("command")?"cohere":t.startsWith("accounts/fireworks")?"fireworks":t.startsWith("gemini")?"google-vertexai":t.startsWith("amazon.")?"bedrock":t.startsWith("mistral")?"mistralai":t.startsWith("sonar")||t.startsWith("pplx")?"perplexity":void 0}var Es=class er extends Un{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields==="any"?this._configurableFields="any":this._configurableFields=e.configurableFields??["model","modelProvider"],e.configPrefix?this._configPrefix=e.configPrefix.endsWith("_")?e.configPrefix:`${e.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0}async _getModelInstance(e){const n=this._getCacheKey(e),r=this._modelInstanceCache.get(n);if(r)return r;const s={...this._defaultConfig,...this._modelParams(e)};let o=await xh(s.model,s.modelProvider,s);for(const[i,a]of Object.entries(this._queuedMethodOperations))i in o&&typeof o[i]=="function"&&(o=await o[i](...a));return this._modelInstanceCache.set(n,o),o}async _generate(e,n,r){return(await this._getModelInstance(n))._generate(e,n??{},r)}bindTools(e,n){const r={...this._queuedMethodOperations};return r.bindTools=[e,n],new er({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(e,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[e,...n],new er({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})};_modelParams(e){const n=e?.configurable??{};let r={};for(const[s,o]of Object.entries(n))if(s.startsWith(this._configPrefix)){const i=this._removePrefix(s,this._configPrefix);r[i]=o}return this._configurableFields!=="any"&&(r=Object.fromEntries(Object.entries(r).filter(([s])=>this._configurableFields.includes(s)))),r}_removePrefix(e,n){return e.startsWith(n)?e.slice(n.length):e}withConfig(e){const n={...e||{}},r=this._modelParams(n),s=Object.fromEntries(Object.entries(n).filter(([i])=>i!=="configurable"));s.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([i])=>this._configPrefix&&!Object.keys(r).includes(this._removePrefix(i,this._configPrefix))));const o=new er({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new Re({config:n,bound:o})}async invoke(e,n){const r=await this._getModelInstance(n),s=mn(n);return r.invoke(e,s)}async stream(e,n){const r=await this._getModelInstance(n),s=new Bc({generator:await r.stream(e,n),config:n});return await s.setup,En.fromAsyncGenerator(s)}async batch(e,n,r){return super.batch(e,n,r)}async*transform(e,n){const r=await this._getModelInstance(n),s=mn(n);yield*r.transform(e,s)}async*streamLog(e,n,r){const s=await this._getModelInstance(n),o=mn(n);yield*s.streamLog(e,o,{...r,_schemaFormat:"original",includeNames:r?.includeNames,includeTypes:r?.includeTypes,includeTags:r?.includeTags,excludeNames:r?.excludeNames,excludeTypes:r?.excludeTypes,excludeTags:r?.excludeTags})}streamEvents(e,n,r){const s=this;async function*o(){const i=await s._getModelInstance(n),a=mn(n),l=i.streamEvents(e,a,r);for await(const c of l)yield c}return En.fromAsyncGenerator(o())}get profile(){if(this._profile)return this._profile;const e=this._getCacheKey({});return this._modelInstanceCache.get(e)?.profile??{}}_getCacheKey(e){let n=e??{};if(n.configurable){const{configurable:r}=n,s={};for(const[o,i]of Object.entries(r))o.startsWith("__pregel_")||(s[o]=i);n={...n,configurable:s}}return JSON.stringify(n)}};async function lt(t,e){let{configurableFields:n,configPrefix:r,modelProvider:s,profile:o,...i}={configPrefix:"",...e??{}};if(s===void 0&&t?.includes(":")){const[u,...d]=t.split(":"),h=d.length===0?[u]:[u,d.join(":")];Ji.includes(h[0])&&([s,t]=h)}let a=Array.isArray(n)?[...n]:n;!t&&a===void 0&&(a=["model","modelProvider"]),r&&a===void 0&&console.warn(`{ configPrefix: ${r} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);const l={...i};let c;return a===void 0?c=new Es({defaultConfig:{...l,model:t,modelProvider:s},configPrefix:r,profile:o}):(t&&(l.model=t),s&&(l.modelProvider=s),c=new Es({defaultConfig:l,configPrefix:r,configurableFields:a,profile:o})),await c._getModelInstance(),c}class Mh{constructor(){this.store=void 0}getStore(){return this.store}run(e,n,...r){this.store=e;try{return n(...r)}finally{this.store=void 0}}exit(e,...n){const r=this.store;this.store=void 0;try{return e(...n)}finally{this.store=r}}enterWith(e){this.store=e}disable(){this.store=void 0}}function Ah(){He.initializeGlobalInstance(new Mh)}var ct=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
11
11
 
12
12
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${e.lc_error_code}/
13
- `),super(n),this.lc_error_code=e?.lc_error_code}},Xi=class extends ct{get is_bubble_up(){return!0}},Ih=class extends ct{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},tr=class extends ct{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},Lt=class extends Xi{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},Zi=class extends Lt{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Qi=class extends Xi{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function Ph(t){return t!==void 0&&t.name===Qi.unminifiable_name}function Sn(t){return t!==void 0&&t.is_bubble_up===!0}function yt(t){return t!==void 0&&[Lt.unminifiable_name,Zi.unminifiable_name].includes(t.name)}var Jo=class extends ct{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},ee=class extends ct{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},B=class extends ct{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},Oh=class extends ct{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}},Yr=class extends ct{constructor(t,e){super(t,e),this.name="StateGraphInputError",this.message="Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."}static get unminifiable_name(){return"StateGraphInputError"}};function ea(t){return Ch({clockseq:t})}function Nt(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return Ss(t,new Uint8Array(n))}const Nh="__error__",nr="__scheduled__",Rh="__interrupt__",$h="__resume__";var qo="[...]",jh="[Circular]",br=[],Rt=[];function Lh(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Dh(t,e,n,r){typeof r>"u"&&(r=Lh()),xs(t,"",0,[],void 0,0,r);var s;try{Rt.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,Fh(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;br.length!==0;){var o=br.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return s}function Xr(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),br.push([r,n,e,s])):Rt.push([e,n,t]):(r[n]=t,br.push([r,n,e]))}function xs(t,e,n,r,s,o,i){o+=1;var a;if(typeof t=="object"&&t!==null){for(a=0;a<r.length;a++)if(r[a]===t){Xr(jh,t,e,s);return}if(typeof i.depthLimit<"u"&&o>i.depthLimit){Xr(qo,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){Xr(qo,t,e,s);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)xs(t[a],a,a,r,t,o,i);else{var l=Object.keys(t);for(a=0;a<l.length;a++){var c=l[a];xs(t[c],c,a,r,t,o,i)}}r.pop()}}function Fh(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(Rt.length>0)for(var r=0;r<Rt.length;r++){var s=Rt[r];if(s[1]===e&&s[0]===n){n=s[2],Rt.splice(r,1);break}}return t.call(this,e,n)}}const Uh=[];var Vh={},ta={};X(ta,{BaseChatMessageHistory:()=>na,BaseListChatMessageHistory:()=>ao,InMemoryChatMessageHistory:()=>Bh});var na=class extends hn{async addMessages(t){for(const e of t)await this.addMessage(e)}},ao=class extends hn{addUserMessage(t){return this.addMessage(new se(t))}addAIMessage(t){return this.addMessage(new P(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},Bh=class extends ao{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(t){super(...arguments),this.messages=t??[]}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async clear(){this.messages=[]}},zh={},ra={};X(ra,{BaseMemory:()=>Hh,getInputValue:()=>Wh,getOutputValue:()=>Gh,getPromptInputKey:()=>Kh});var Hh=class{};const sa=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},Wh=(t,e)=>{const n=sa(t,e);if(!n){const r=Object.keys(t);throw new Error(`input values have ${r.length} keys, you must specify an input key or pass only 1 key as input`)}return n},Gh=(t,e)=>{const n=sa(t,e);if(!n&&n!==""){const r=Object.keys(t);throw new Error(`output values have ${r.length} keys, you must specify an output key or pass only 1 key as output`)}return n};function Kh(t,e){const n=Object.keys(t).filter(r=>!e.includes(r)&&r!=="stop");if(n.length!==1)throw new Error(`One input key expected, but got ${n.length}`);return n[0]}var oa={};X(oa,{BaseStore:()=>ia,InMemoryStore:()=>aa});var ia=class extends hn{},aa=class extends ia{lc_namespace=["langchain","storage"];store={};async mget(t){return t.map(e=>this.store[e])}async mset(t){for(const[e,n]of t)this.store[e]=n}async mdelete(t){for(const e of t)delete this.store[e]}async*yieldKeys(t){const e=Object.keys(this.store);for(const n of e)(t===void 0||n.startsWith(t))&&(yield n)}},la={};X(la,{BaseRetriever:()=>lo});var lo=class extends ae{callbacks;tags;metadata;verbose;constructor(t){super(t),this.callbacks=t?.callbacks,this.tags=t?.tags??[],this.metadata=t?.metadata??{},this.verbose=t?.verbose??!1}_getRelevantDocuments(t,e){throw new Error("Not implemented!")}async invoke(t,e){const n=mn(zc(e)),s=await(await Hc.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),t,n.runId,void 0,void 0,void 0,n.runName);try{const o=await this._getRelevantDocuments(t,s);return await s?.handleRetrieverEnd(o),o}catch(o){throw await s?.handleRetrieverError(o),o}}},ca={};X(ca,{SaveableVectorStore:()=>Jh,VectorStore:()=>co,VectorStoreRetriever:()=>rr});var rr=class extends lo{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}vectorStore;k=4;searchType="similarity";searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(t){super(t),this.vectorStore=t.vectorStore,this.k=t.k??this.k,this.searchType=t.searchType??this.searchType,this.filter=t.filter,t.searchType==="mmr"&&(this.searchKwargs=t.searchKwargs)}async _getRelevantDocuments(t,e){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(t,{k:this.k,filter:this.filter,...this.searchKwargs},e?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(t,this.k,this.filter,e?.getChild("vectorstore"))}async addDocuments(t,e){return this.vectorStore.addDocuments(t,e)}},co=class extends hn{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(t,e){super(e),this.embeddings=t}async delete(t){throw new Error("Not implemented.")}async similaritySearch(t,e=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)).map(o=>o[0])}async similaritySearchWithScore(t,e=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)}static fromTexts(t,e,n,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(t,e,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(t,e,n,r,s,o){if(typeof t=="number")return new rr({vectorStore:this,k:t,filter:e,tags:[...r??[],this._vectorstoreType()],metadata:s,verbose:o,callbacks:n});{const i={vectorStore:this,k:t?.k,filter:t?.filter,tags:[...t?.tags??[],this._vectorstoreType()],metadata:t?.metadata,verbose:t?.verbose,callbacks:t?.callbacks,searchType:t?.searchType};return t?.searchType==="mmr"?new rr({...i,searchKwargs:t.searchKwargs}):new rr({...i})}}},Jh=class extends co{static load(t,e){throw new Error("Not implemented")}},ua={};X(ua,{BaseDocumentLoader:()=>ha});var ha=class{},da={};X(da,{LangSmithLoader:()=>qh});var qh=class extends ha{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(t){if(super(),t.client&&t.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=t.client??new Wc(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??Yh,this.datasetId=t.datasetId,this.datasetName=t.datasetName,this.exampleIds=t.exampleIds,this.asOf=t.asOf,this.splits=t.splits,this.inlineS3Urls=t.inlineS3Urls,this.offset=t.offset,this.limit=t.limit,this.metadata=t.metadata,this.filter=t.filter}async load(){const t=[];for await(const e of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=e.inputs;for(const o of this.contentKey)n=n[o];const r=this.formatContent(n),s=e;["created_at","modified_at"].forEach(o=>{o in s&&typeof s[o]=="object"&&(s[o]=s[o].toString())}),t.push({pageContent:r,metadata:s})}return t}};function Yh(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var We=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},fa=class extends ae{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},Xh=class extends fa{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},pa={};X(pa,{BaseDocumentTransformer:()=>fa,Document:()=>We,MappingDocumentTransformer:()=>Xh});var uo=class extends hn{lc_namespace=["langchain_core","example_selectors","base"]},ma=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},Zh=class extends ma{defaultPrompt;conditionals;constructor(t,e=[]){super(),this.defaultPrompt=t,this.conditionals=e}getPrompt(t){for(const[e,n]of this.conditionals)if(e(t))return n;return this.defaultPrompt}};function Qh(t){return t._modelType()==="base_llm"}function ed(t){return t._modelType()==="base_chat_model"}function Yo(t){return t.split(/\n| /).length}var td=class ga extends uo{examples=[];examplePrompt;getTextLength=Yo;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Yo}async addExample(e){this.examples.push(e);const n=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(n))}async calculateExampleTextLengths(e,n){if(e.length>0)return e;const{examples:r,examplePrompt:s}=n;return(await Promise.all(r.map(i=>s.format(i)))).map(i=>this.getTextLength(i))}async selectExamples(e){const n=Object.values(e).join(" ");let r=this.maxLength-this.getTextLength(n),s=0;const o=[];for(;r>0&&s<this.examples.length;){const i=r-this.exampleTextLengths[s];if(i<0)break;o.push(this.examples[s]),r=i,s+=1}return o}static async fromExamples(e,n){const r=new ga(n);return await Promise.all(e.map(s=>r.addExample(s))),r}};function Zr(t){return Object.keys(t).sort().map(e=>t[e])}var nd=class ya extends uo{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(e){const n=this.inputKeys??Object.keys(e),r=Zr(n.reduce((s,o)=>({...s,[o]:e[o]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new We({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=Zr(n.reduce((i,a)=>({...i,[a]:e[a]}),{})).join(" "),o=(await this.vectorStoreRetriever.invoke(r)).map(i=>i.metadata);return this.exampleKeys?o.map(i=>this.exampleKeys.reduce((a,l)=>({...a,[l]:i[l]}),{})):o}static async fromExamples(e,n,r,s={}){const o=s.inputKeys??null,i=e.map(l=>Zr(o?o.reduce((c,u)=>({...c,[u]:l[u]}),{}):l).join(" ")),a=await r.fromTexts(i,e,n,s);return new ya({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},wa={};X(wa,{BaseExampleSelector:()=>uo,BasePromptSelector:()=>ma,ConditionalPromptSelector:()=>Zh,LengthBasedExampleSelector:()=>td,SemanticSimilarityExampleSelector:()=>nd,isChatModel:()=>ed,isLLM:()=>Qh});const Ms="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var rd=class extends hn{lc_namespace=["langchain","recordmanagers"]},ba=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Di;constructor(t){this.uid=t.uid,this.pageContent=t.pageContent,this.metadata=t.metadata}makeDefaultKeyEncoder(t){this.keyEncoder=t}calculateHashes(){const t=["hash_","content_hash","metadata_hash"];for(const n of t)if(n in this.metadata)throw new Error(`Metadata cannot contain key ${n} as it is reserved for internal use. Restricted keys: [${t.join(", ")}]`);const e=this._hashStringToUUID(this.pageContent);try{const n=this._hashNestedDictToUUID(this.metadata);this.contentHash=e,this.metadataHash=n}catch(n){throw new Error(`Failed to hash metadata: ${n}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||(this.uid=this.hash_)}toDocument(){return new We({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(t,e){const n=new this({pageContent:t.pageContent,metadata:t.metadata,uid:e||t.uid});return n.calculateHashes(),n}_hashStringToUUID(t){const e=this.keyEncoder(t);return Ss(e,Ms)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return Ss(n,Ms)}};function _a(t,e){const n=[];let r=[];return e.forEach(s=>{r.push(s),r.length>=t&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function va(t){const e=new Set,n=[];for(const r of t){if(!r.hash_)throw new Error("Hashed document does not have a hash");e.has(r.hash_)||(e.add(r.hash_),n.push(r))}return n}function Sa(t){if(t===null)return e=>null;if(typeof t=="string")return e=>e.metadata[t];if(typeof t=="function")return t;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof t}`)}const Ca=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function sd(t){const{docsSource:e,recordManager:n,vectorStore:r,options:s}=t,{batchSize:o=100,cleanup:i,sourceIdKey:a,cleanupBatchSize:l=1e3,forceUpdate:c=!1}=s??{};if(i==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const u=Ca(e)?await e.load():e,d=Sa(a??null),h=await n.getTime();let f=0,m=0,p=0,C=0;const k=_a(o??100,u);for(const T of k){const _=va(T.map(S=>ba.fromDocument(S))),g=_.map(S=>d(S));i==="incremental"&&_.forEach((S,x)=>{if(g[x]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const v=await n.exists(_.map(S=>S.uid)),M=[],w=[],b=[],E=new Set;if(_.forEach((S,x)=>{if(v[x])if(c)E.add(S.uid);else{b.push(S.uid);return}M.push(S.uid),w.push(S.toDocument())}),b.length>0&&(await n.update(b,{timeAtLeast:h}),C+=b.length),w.length>0&&(await r.addDocuments(w,{ids:M}),f+=w.length-E.size,p+=E.size),await n.update(_.map(S=>S.uid),{timeAtLeast:h,groupIds:g}),i==="incremental"){g.forEach(x=>{if(!x)throw new Error("Source id cannot be null")});const S=await n.listKeys({before:h,groupIds:g});S.length>0&&(await r.delete({ids:S}),await n.deleteKeys(S),m+=S.length)}}if(i==="full"){let T=await n.listKeys({before:h,limit:l});for(;T.length>0;)await r.delete({ids:T}),await n.deleteKeys(T),m+=T.length,T=await n.listKeys({before:h,limit:l})}return{numAdded:f,numDeleted:m,numUpdated:p,numSkipped:C}}var ka={};X(ka,{RecordManager:()=>rd,UUIDV5_NAMESPACE:()=>Ms,_HashedDocument:()=>ba,_batch:()=>_a,_deduplicateInOrder:()=>va,_getSourceIdAssigner:()=>Sa,_isBaseDocumentLoader:()=>Ca,index:()=>sd});var od={},Ta=class extends Fi{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(t){super(),this.argsOnly=t?.argsOnly??this.argsOnly}async parseResult(t){if("message"in t[0]){const n=t[0].message.additional_kwargs.function_call;if(!n)throw new Error(`No function_call in message ${JSON.stringify(t)}`);if(!n.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(t)}`);return this.argsOnly?n.arguments:JSON.stringify(n)}else throw new Error(`No message in generations ${JSON.stringify(t)}`)}},Ea=class extends Ju{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(t){super(t),this.argsOnly=t?.argsOnly??this.argsOnly,this.outputParser=new Ta(t)}_diff(t,e){return e?qu(t??{},e):void 0}async parsePartialResult(t){const e=t[0];if(!e.message)return;const{message:n}=e,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?Do(r.arguments):{...r,arguments:Do(r.arguments)}}async parseResult(t){const e=await this.outputParser.parseResult(t);if(!e)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(t)}`);return this.parse(e)}async parse(t){const e=JSON.parse(t);return this.argsOnly||(e.arguments=JSON.parse(e.arguments)),e}getFormatInstructions(){return""}},id=class extends Fi{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new Ea;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(t){super(t),this.attrName=t.attrName}async parseResult(t){return(await this.outputParser.parseResult(t))[this.attrName]}},xa={};X(xa,{JsonKeyOutputFunctionsParser:()=>id,JsonOutputFunctionsParser:()=>Ea,OutputFunctionsParser:()=>Ta});var Vn=class extends ae{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(t){super(t);const{inputVariables:e}=t;if(e.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,t)}async mergePartialAndUserVariables(t){const e=this.partialVariables??{},n={};for(const[s,o]of Object.entries(e))typeof o=="string"?n[s]=o:n[s]=await o();return{...n,...t}}async invoke(t,e){const n={...this.metadata,...e?.metadata},r=[...this.tags??[],...e?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),t,{...e,tags:r,metadata:n,runType:"prompt"})}},An=class extends Vn{async formatPromptValue(t){const e=await this.format(t);return new Yu(e)}};var ad=Object.prototype.toString,dn=Array.isArray||function(e){return ad.call(e)==="[object Array]"};function ho(t){return typeof t=="function"}function ld(t){return dn(t)?"array":typeof t}function Qr(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Xo(t,e){return t!=null&&typeof t=="object"&&e in t}function cd(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var ud=RegExp.prototype.test;function hd(t,e){return ud.call(t,e)}var dd=/\S/;function fd(t){return!hd(dd,t)}var pd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function md(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return pd[n]})}var gd=/\s*/,yd=/\s+/,Zo=/\s*=/,wd=/\s*\}/,bd=/#|\^|\/|>|\{|&|=|!/;function _d(t,e){if(!t)return[];var n=!1,r=[],s=[],o=[],i=!1,a=!1,l="",c=0;function u(){if(i&&!a)for(;o.length;)delete s[o.pop()];else o=[];i=!1,a=!1}var d,h,f;function m(b){if(typeof b=="string"&&(b=b.split(yd,2)),!dn(b)||b.length!==2)throw new Error("Invalid tags: "+b);d=new RegExp(Qr(b[0])+"\\s*"),h=new RegExp("\\s*"+Qr(b[1])),f=new RegExp("\\s*"+Qr("}"+b[1]))}m(e||ge.tags);for(var p=new Bn(t),C,k,T,_,g,v;!p.eos();){if(C=p.pos,T=p.scanUntil(d),T)for(var M=0,w=T.length;M<w;++M)_=T.charAt(M),fd(_)?(o.push(s.length),l+=_):(a=!0,n=!0,l+=" "),s.push(["text",_,C,C+1]),C+=1,_===`
14
- `&&(u(),l="",c=0,n=!1);if(!p.scan(d))break;if(i=!0,k=p.scan(bd)||"name",p.scan(gd),k==="="?(T=p.scanUntil(Zo),p.scan(Zo),p.scanUntil(h)):k==="{"?(T=p.scanUntil(f),p.scan(wd),p.scanUntil(h),k="&"):T=p.scanUntil(h),!p.scan(h))throw new Error("Unclosed tag at "+p.pos);if(k==">"?g=[k,T,C,p.pos,l,c,n]:g=[k,T,C,p.pos],c++,s.push(g),k==="#"||k==="^")r.push(g);else if(k==="/"){if(v=r.pop(),!v)throw new Error('Unopened section "'+T+'" at '+C);if(v[1]!==T)throw new Error('Unclosed section "'+v[1]+'" at '+C)}else k==="name"||k==="{"||k==="&"?a=!0:k==="="&&m(T)}if(u(),v=r.pop(),v)throw new Error('Unclosed section "'+v[1]+'" at '+p.pos);return Sd(vd(s))}function vd(t){for(var e=[],n,r,s=0,o=t.length;s<o;++s)n=t[s],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(e.push(n),r=n));return e}function Sd(t){for(var e=[],n=e,r=[],s,o,i=0,a=t.length;i<a;++i)switch(s=t[i],s[0]){case"#":case"^":n.push(s),r.push(s),n=s[4]=[];break;case"/":o=r.pop(),o[5]=s[2],n=r.length>0?r[r.length-1][4]:e;break;default:n.push(s)}return e}function Bn(t){this.string=t,this.tail=t,this.pos=0}Bn.prototype.eos=function(){return this.tail===""};Bn.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};Bn.prototype.scanUntil=function(e){var n=this.tail.search(e),r;switch(n){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=r.length,r};function rn(t,e){this.view=t,this.cache={".":this.view},this.parent=e}rn.prototype.push=function(e){return new rn(e,this)};rn.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var s=this,o,i,a,l=!1;s;){if(e.indexOf(".")>0)for(o=s.view,i=e.split("."),a=0;o!=null&&a<i.length;)a===i.length-1&&(l=Xo(o,i[a])||cd(o,i[a])),o=o[i[a++]];else o=s.view[e],l=Xo(s.view,e);if(l){r=o;break}s=s.parent}n[e]=r}return ho(r)&&(r=r.call(this.view)),r};function fe(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}fe.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};fe.prototype.parse=function(e,n){var r=this.templateCache,s=e+":"+(n||ge.tags).join(":"),o=typeof r<"u",i=o?r.get(s):void 0;return i==null&&(i=_d(e,n),o&&r.set(s,i)),i};fe.prototype.render=function(e,n,r,s){var o=this.getConfigTags(s),i=this.parse(e,o),a=n instanceof rn?n:new rn(n,void 0);return this.renderTokens(i,a,r,e,s)};fe.prototype.renderTokens=function(e,n,r,s,o){for(var i="",a,l,c,u=0,d=e.length;u<d;++u)c=void 0,a=e[u],l=a[0],l==="#"?c=this.renderSection(a,n,r,s,o):l==="^"?c=this.renderInverted(a,n,r,s,o):l===">"?c=this.renderPartial(a,n,r,o):l==="&"?c=this.unescapedValue(a,n):l==="name"?c=this.escapedValue(a,n,o):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(i+=c);return i};fe.prototype.renderSection=function(e,n,r,s,o){var i=this,a="",l=n.lookup(e[1]);function c(h){return i.render(h,n,r,o)}if(l){if(dn(l))for(var u=0,d=l.length;u<d;++u)a+=this.renderTokens(e[4],n.push(l[u]),r,s,o);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(e[4],n.push(l),r,s,o);else if(ho(l)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(n.view,s.slice(e[3],e[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(e[4],n,r,s,o);return a}};fe.prototype.renderInverted=function(e,n,r,s,o){var i=n.lookup(e[1]);if(!i||dn(i)&&i.length===0)return this.renderTokens(e[4],n,r,s,o)};fe.prototype.indentPartial=function(e,n,r){for(var s=n.replace(/[^ \t]/g,""),o=e.split(`
13
+ `),super(n),this.lc_error_code=e?.lc_error_code}},Xi=class extends ct{get is_bubble_up(){return!0}},Ih=class extends ct{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},tr=class extends ct{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},Lt=class extends Xi{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},Zi=class extends Lt{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Qi=class extends Xi{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function Ph(t){return t!==void 0&&t.name===Qi.unminifiable_name}function Sn(t){return t!==void 0&&t.is_bubble_up===!0}function yt(t){return t!==void 0&&[Lt.unminifiable_name,Zi.unminifiable_name].includes(t.name)}var Jo=class extends ct{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},ee=class extends ct{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},B=class extends ct{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},Oh=class extends ct{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}},Yr=class extends ct{constructor(t,e){super(t,e),this.name="StateGraphInputError",this.message="Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."}static get unminifiable_name(){return"StateGraphInputError"}};function ea(t){return Ch({clockseq:t})}function Nt(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return Ss(t,new Uint8Array(n))}const Nh="__error__",nr="__scheduled__",Rh="__interrupt__",$h="__resume__";var qo="[...]",jh="[Circular]",br=[],Rt=[];function Lh(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Dh(t,e,n,r){typeof r>"u"&&(r=Lh()),xs(t,"",0,[],void 0,0,r);var s;try{Rt.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,Fh(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;br.length!==0;){var o=br.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return s}function Xr(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),br.push([r,n,e,s])):Rt.push([e,n,t]):(r[n]=t,br.push([r,n,e]))}function xs(t,e,n,r,s,o,i){o+=1;var a;if(typeof t=="object"&&t!==null){for(a=0;a<r.length;a++)if(r[a]===t){Xr(jh,t,e,s);return}if(typeof i.depthLimit<"u"&&o>i.depthLimit){Xr(qo,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){Xr(qo,t,e,s);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)xs(t[a],a,a,r,t,o,i);else{var l=Object.keys(t);for(a=0;a<l.length;a++){var c=l[a];xs(t[c],c,a,r,t,o,i)}}r.pop()}}function Fh(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(Rt.length>0)for(var r=0;r<Rt.length;r++){var s=Rt[r];if(s[1]===e&&s[0]===n){n=s[2],Rt.splice(r,1);break}}return t.call(this,e,n)}}const Uh=[];var Vh={},ta={};X(ta,{BaseChatMessageHistory:()=>na,BaseListChatMessageHistory:()=>ao,InMemoryChatMessageHistory:()=>Bh});var na=class extends hn{async addMessages(t){for(const e of t)await this.addMessage(e)}},ao=class extends hn{addUserMessage(t){return this.addMessage(new se(t))}addAIMessage(t){return this.addMessage(new P(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},Bh=class extends ao{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(t){super(...arguments),this.messages=t??[]}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async clear(){this.messages=[]}},zh={},ra={};X(ra,{BaseMemory:()=>Hh,getInputValue:()=>Wh,getOutputValue:()=>Gh,getPromptInputKey:()=>Kh});var Hh=class{};const sa=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},Wh=(t,e)=>{const n=sa(t,e);if(!n){const r=Object.keys(t);throw new Error(`input values have ${r.length} keys, you must specify an input key or pass only 1 key as input`)}return n},Gh=(t,e)=>{const n=sa(t,e);if(!n&&n!==""){const r=Object.keys(t);throw new Error(`output values have ${r.length} keys, you must specify an output key or pass only 1 key as output`)}return n};function Kh(t,e){const n=Object.keys(t).filter(r=>!e.includes(r)&&r!=="stop");if(n.length!==1)throw new Error(`One input key expected, but got ${n.length}`);return n[0]}var oa={};X(oa,{BaseStore:()=>ia,InMemoryStore:()=>aa});var ia=class extends hn{},aa=class extends ia{lc_namespace=["langchain","storage"];store={};async mget(t){return t.map(e=>this.store[e])}async mset(t){for(const[e,n]of t)this.store[e]=n}async mdelete(t){for(const e of t)delete this.store[e]}async*yieldKeys(t){const e=Object.keys(this.store);for(const n of e)(t===void 0||n.startsWith(t))&&(yield n)}},la={};X(la,{BaseRetriever:()=>lo});var lo=class extends ae{callbacks;tags;metadata;verbose;constructor(t){super(t),this.callbacks=t?.callbacks,this.tags=t?.tags??[],this.metadata=t?.metadata??{},this.verbose=t?.verbose??!1}_getRelevantDocuments(t,e){throw new Error("Not implemented!")}async invoke(t,e){const n=mn(zc(e)),s=await(await Hc.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),t,n.runId,void 0,void 0,void 0,n.runName);try{const o=await this._getRelevantDocuments(t,s);return await s?.handleRetrieverEnd(o),o}catch(o){throw await s?.handleRetrieverError(o),o}}},ca={};X(ca,{SaveableVectorStore:()=>Jh,VectorStore:()=>co,VectorStoreRetriever:()=>rr});var rr=class extends lo{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}vectorStore;k=4;searchType="similarity";searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(t){super(t),this.vectorStore=t.vectorStore,this.k=t.k??this.k,this.searchType=t.searchType??this.searchType,this.filter=t.filter,t.searchType==="mmr"&&(this.searchKwargs=t.searchKwargs)}async _getRelevantDocuments(t,e){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(t,{k:this.k,filter:this.filter,...this.searchKwargs},e?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(t,this.k,this.filter,e?.getChild("vectorstore"))}async addDocuments(t,e){return this.vectorStore.addDocuments(t,e)}},co=class extends hn{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(t,e){super(e),this.embeddings=t}async delete(t){throw new Error("Not implemented.")}async similaritySearch(t,e=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)).map(o=>o[0])}async similaritySearchWithScore(t,e=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)}static fromTexts(t,e,n,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(t,e,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(t,e,n,r,s,o){if(typeof t=="number")return new rr({vectorStore:this,k:t,filter:e,tags:[...r??[],this._vectorstoreType()],metadata:s,verbose:o,callbacks:n});{const i={vectorStore:this,k:t?.k,filter:t?.filter,tags:[...t?.tags??[],this._vectorstoreType()],metadata:t?.metadata,verbose:t?.verbose,callbacks:t?.callbacks,searchType:t?.searchType};return t?.searchType==="mmr"?new rr({...i,searchKwargs:t.searchKwargs}):new rr({...i})}}},Jh=class extends co{static load(t,e){throw new Error("Not implemented")}},ua={};X(ua,{BaseDocumentLoader:()=>ha});var ha=class{},da={};X(da,{LangSmithLoader:()=>qh});var qh=class extends ha{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(t){if(super(),t.client&&t.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=t.client??new Wc(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??Yh,this.datasetId=t.datasetId,this.datasetName=t.datasetName,this.exampleIds=t.exampleIds,this.asOf=t.asOf,this.splits=t.splits,this.inlineS3Urls=t.inlineS3Urls,this.offset=t.offset,this.limit=t.limit,this.metadata=t.metadata,this.filter=t.filter}async load(){const t=[];for await(const e of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=e.inputs;for(const o of this.contentKey)n=n[o];const r=this.formatContent(n),s=e;["created_at","modified_at"].forEach(o=>{o in s&&typeof s[o]=="object"&&(s[o]=s[o].toString())}),t.push({pageContent:r,metadata:s})}return t}};function Yh(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var We=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},fa=class extends ae{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},Xh=class extends fa{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},pa={};X(pa,{BaseDocumentTransformer:()=>fa,Document:()=>We,MappingDocumentTransformer:()=>Xh});var uo=class extends hn{lc_namespace=["langchain_core","example_selectors","base"]},ma=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},Zh=class extends ma{defaultPrompt;conditionals;constructor(t,e=[]){super(),this.defaultPrompt=t,this.conditionals=e}getPrompt(t){for(const[e,n]of this.conditionals)if(e(t))return n;return this.defaultPrompt}};function Qh(t){return t._modelType()==="base_llm"}function ed(t){return t._modelType()==="base_chat_model"}function Yo(t){return t.split(/\n| /).length}var td=class ga extends uo{examples=[];examplePrompt;getTextLength=Yo;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Yo}async addExample(e){this.examples.push(e);const n=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(n))}async calculateExampleTextLengths(e,n){if(e.length>0)return e;const{examples:r,examplePrompt:s}=n;return(await Promise.all(r.map(i=>s.format(i)))).map(i=>this.getTextLength(i))}async selectExamples(e){const n=Object.values(e).join(" ");let r=this.maxLength-this.getTextLength(n),s=0;const o=[];for(;r>0&&s<this.examples.length;){const i=r-this.exampleTextLengths[s];if(i<0)break;o.push(this.examples[s]),r=i,s+=1}return o}static async fromExamples(e,n){const r=new ga(n);return await Promise.all(e.map(s=>r.addExample(s))),r}};function Zr(t){return Object.keys(t).sort().map(e=>t[e])}var nd=class ya extends uo{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(e){const n=this.inputKeys??Object.keys(e),r=Zr(n.reduce((s,o)=>({...s,[o]:e[o]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new We({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=Zr(n.reduce((i,a)=>({...i,[a]:e[a]}),{})).join(" "),o=(await this.vectorStoreRetriever.invoke(r)).map(i=>i.metadata);return this.exampleKeys?o.map(i=>this.exampleKeys.reduce((a,l)=>({...a,[l]:i[l]}),{})):o}static async fromExamples(e,n,r,s={}){const o=s.inputKeys??null,i=e.map(l=>Zr(o?o.reduce((c,u)=>({...c,[u]:l[u]}),{}):l).join(" ")),a=await r.fromTexts(i,e,n,s);return new ya({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},wa={};X(wa,{BaseExampleSelector:()=>uo,BasePromptSelector:()=>ma,ConditionalPromptSelector:()=>Zh,LengthBasedExampleSelector:()=>td,SemanticSimilarityExampleSelector:()=>nd,isChatModel:()=>ed,isLLM:()=>Qh});const Ms="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var rd=class extends hn{lc_namespace=["langchain","recordmanagers"]},ba=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Di;constructor(t){this.uid=t.uid,this.pageContent=t.pageContent,this.metadata=t.metadata}makeDefaultKeyEncoder(t){this.keyEncoder=t}calculateHashes(){const t=["hash_","content_hash","metadata_hash"];for(const n of t)if(n in this.metadata)throw new Error(`Metadata cannot contain key ${n} as it is reserved for internal use. Restricted keys: [${t.join(", ")}]`);const e=this._hashStringToUUID(this.pageContent);try{const n=this._hashNestedDictToUUID(this.metadata);this.contentHash=e,this.metadataHash=n}catch(n){throw new Error(`Failed to hash metadata: ${n}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||(this.uid=this.hash_)}toDocument(){return new We({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(t,e){const n=new this({pageContent:t.pageContent,metadata:t.metadata,uid:e||t.uid});return n.calculateHashes(),n}_hashStringToUUID(t){const e=this.keyEncoder(t);return Ss(e,Ms)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return Ss(n,Ms)}};function _a(t,e){const n=[];let r=[];return e.forEach(s=>{r.push(s),r.length>=t&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function va(t){const e=new Set,n=[];for(const r of t){if(!r.hash_)throw new Error("Hashed document does not have a hash");e.has(r.hash_)||(e.add(r.hash_),n.push(r))}return n}function Sa(t){if(t===null)return e=>null;if(typeof t=="string")return e=>e.metadata[t];if(typeof t=="function")return t;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof t}`)}const Ca=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function sd(t){const{docsSource:e,recordManager:n,vectorStore:r,options:s}=t,{batchSize:o=100,cleanup:i,sourceIdKey:a,cleanupBatchSize:l=1e3,forceUpdate:c=!1}=s??{};if(i==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const u=Ca(e)?await e.load():e,d=Sa(a??null),h=await n.getTime();let f=0,m=0,p=0,C=0;const T=_a(o??100,u);for(const k of T){const _=va(k.map(S=>ba.fromDocument(S))),g=_.map(S=>d(S));i==="incremental"&&_.forEach((S,x)=>{if(g[x]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const v=await n.exists(_.map(S=>S.uid)),M=[],w=[],b=[],E=new Set;if(_.forEach((S,x)=>{if(v[x])if(c)E.add(S.uid);else{b.push(S.uid);return}M.push(S.uid),w.push(S.toDocument())}),b.length>0&&(await n.update(b,{timeAtLeast:h}),C+=b.length),w.length>0&&(await r.addDocuments(w,{ids:M}),f+=w.length-E.size,p+=E.size),await n.update(_.map(S=>S.uid),{timeAtLeast:h,groupIds:g}),i==="incremental"){g.forEach(x=>{if(!x)throw new Error("Source id cannot be null")});const S=await n.listKeys({before:h,groupIds:g});S.length>0&&(await r.delete({ids:S}),await n.deleteKeys(S),m+=S.length)}}if(i==="full"){let k=await n.listKeys({before:h,limit:l});for(;k.length>0;)await r.delete({ids:k}),await n.deleteKeys(k),m+=k.length,k=await n.listKeys({before:h,limit:l})}return{numAdded:f,numDeleted:m,numUpdated:p,numSkipped:C}}var Ta={};X(Ta,{RecordManager:()=>rd,UUIDV5_NAMESPACE:()=>Ms,_HashedDocument:()=>ba,_batch:()=>_a,_deduplicateInOrder:()=>va,_getSourceIdAssigner:()=>Sa,_isBaseDocumentLoader:()=>Ca,index:()=>sd});var od={},ka=class extends Fi{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(t){super(),this.argsOnly=t?.argsOnly??this.argsOnly}async parseResult(t){if("message"in t[0]){const n=t[0].message.additional_kwargs.function_call;if(!n)throw new Error(`No function_call in message ${JSON.stringify(t)}`);if(!n.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(t)}`);return this.argsOnly?n.arguments:JSON.stringify(n)}else throw new Error(`No message in generations ${JSON.stringify(t)}`)}},Ea=class extends Ju{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(t){super(t),this.argsOnly=t?.argsOnly??this.argsOnly,this.outputParser=new ka(t)}_diff(t,e){return e?qu(t??{},e):void 0}async parsePartialResult(t){const e=t[0];if(!e.message)return;const{message:n}=e,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?Do(r.arguments):{...r,arguments:Do(r.arguments)}}async parseResult(t){const e=await this.outputParser.parseResult(t);if(!e)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(t)}`);return this.parse(e)}async parse(t){const e=JSON.parse(t);return this.argsOnly||(e.arguments=JSON.parse(e.arguments)),e}getFormatInstructions(){return""}},id=class extends Fi{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new Ea;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(t){super(t),this.attrName=t.attrName}async parseResult(t){return(await this.outputParser.parseResult(t))[this.attrName]}},xa={};X(xa,{JsonKeyOutputFunctionsParser:()=>id,JsonOutputFunctionsParser:()=>Ea,OutputFunctionsParser:()=>ka});var Vn=class extends ae{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(t){super(t);const{inputVariables:e}=t;if(e.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,t)}async mergePartialAndUserVariables(t){const e=this.partialVariables??{},n={};for(const[s,o]of Object.entries(e))typeof o=="string"?n[s]=o:n[s]=await o();return{...n,...t}}async invoke(t,e){const n={...this.metadata,...e?.metadata},r=[...this.tags??[],...e?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),t,{...e,tags:r,metadata:n,runType:"prompt"})}},An=class extends Vn{async formatPromptValue(t){const e=await this.format(t);return new Yu(e)}};var ad=Object.prototype.toString,dn=Array.isArray||function(e){return ad.call(e)==="[object Array]"};function ho(t){return typeof t=="function"}function ld(t){return dn(t)?"array":typeof t}function Qr(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Xo(t,e){return t!=null&&typeof t=="object"&&e in t}function cd(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var ud=RegExp.prototype.test;function hd(t,e){return ud.call(t,e)}var dd=/\S/;function fd(t){return!hd(dd,t)}var pd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function md(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return pd[n]})}var gd=/\s*/,yd=/\s+/,Zo=/\s*=/,wd=/\s*\}/,bd=/#|\^|\/|>|\{|&|=|!/;function _d(t,e){if(!t)return[];var n=!1,r=[],s=[],o=[],i=!1,a=!1,l="",c=0;function u(){if(i&&!a)for(;o.length;)delete s[o.pop()];else o=[];i=!1,a=!1}var d,h,f;function m(b){if(typeof b=="string"&&(b=b.split(yd,2)),!dn(b)||b.length!==2)throw new Error("Invalid tags: "+b);d=new RegExp(Qr(b[0])+"\\s*"),h=new RegExp("\\s*"+Qr(b[1])),f=new RegExp("\\s*"+Qr("}"+b[1]))}m(e||ge.tags);for(var p=new Bn(t),C,T,k,_,g,v;!p.eos();){if(C=p.pos,k=p.scanUntil(d),k)for(var M=0,w=k.length;M<w;++M)_=k.charAt(M),fd(_)?(o.push(s.length),l+=_):(a=!0,n=!0,l+=" "),s.push(["text",_,C,C+1]),C+=1,_===`
14
+ `&&(u(),l="",c=0,n=!1);if(!p.scan(d))break;if(i=!0,T=p.scan(bd)||"name",p.scan(gd),T==="="?(k=p.scanUntil(Zo),p.scan(Zo),p.scanUntil(h)):T==="{"?(k=p.scanUntil(f),p.scan(wd),p.scanUntil(h),T="&"):k=p.scanUntil(h),!p.scan(h))throw new Error("Unclosed tag at "+p.pos);if(T==">"?g=[T,k,C,p.pos,l,c,n]:g=[T,k,C,p.pos],c++,s.push(g),T==="#"||T==="^")r.push(g);else if(T==="/"){if(v=r.pop(),!v)throw new Error('Unopened section "'+k+'" at '+C);if(v[1]!==k)throw new Error('Unclosed section "'+v[1]+'" at '+C)}else T==="name"||T==="{"||T==="&"?a=!0:T==="="&&m(k)}if(u(),v=r.pop(),v)throw new Error('Unclosed section "'+v[1]+'" at '+p.pos);return Sd(vd(s))}function vd(t){for(var e=[],n,r,s=0,o=t.length;s<o;++s)n=t[s],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(e.push(n),r=n));return e}function Sd(t){for(var e=[],n=e,r=[],s,o,i=0,a=t.length;i<a;++i)switch(s=t[i],s[0]){case"#":case"^":n.push(s),r.push(s),n=s[4]=[];break;case"/":o=r.pop(),o[5]=s[2],n=r.length>0?r[r.length-1][4]:e;break;default:n.push(s)}return e}function Bn(t){this.string=t,this.tail=t,this.pos=0}Bn.prototype.eos=function(){return this.tail===""};Bn.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};Bn.prototype.scanUntil=function(e){var n=this.tail.search(e),r;switch(n){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=r.length,r};function rn(t,e){this.view=t,this.cache={".":this.view},this.parent=e}rn.prototype.push=function(e){return new rn(e,this)};rn.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var s=this,o,i,a,l=!1;s;){if(e.indexOf(".")>0)for(o=s.view,i=e.split("."),a=0;o!=null&&a<i.length;)a===i.length-1&&(l=Xo(o,i[a])||cd(o,i[a])),o=o[i[a++]];else o=s.view[e],l=Xo(s.view,e);if(l){r=o;break}s=s.parent}n[e]=r}return ho(r)&&(r=r.call(this.view)),r};function fe(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}fe.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};fe.prototype.parse=function(e,n){var r=this.templateCache,s=e+":"+(n||ge.tags).join(":"),o=typeof r<"u",i=o?r.get(s):void 0;return i==null&&(i=_d(e,n),o&&r.set(s,i)),i};fe.prototype.render=function(e,n,r,s){var o=this.getConfigTags(s),i=this.parse(e,o),a=n instanceof rn?n:new rn(n,void 0);return this.renderTokens(i,a,r,e,s)};fe.prototype.renderTokens=function(e,n,r,s,o){for(var i="",a,l,c,u=0,d=e.length;u<d;++u)c=void 0,a=e[u],l=a[0],l==="#"?c=this.renderSection(a,n,r,s,o):l==="^"?c=this.renderInverted(a,n,r,s,o):l===">"?c=this.renderPartial(a,n,r,o):l==="&"?c=this.unescapedValue(a,n):l==="name"?c=this.escapedValue(a,n,o):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(i+=c);return i};fe.prototype.renderSection=function(e,n,r,s,o){var i=this,a="",l=n.lookup(e[1]);function c(h){return i.render(h,n,r,o)}if(l){if(dn(l))for(var u=0,d=l.length;u<d;++u)a+=this.renderTokens(e[4],n.push(l[u]),r,s,o);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(e[4],n.push(l),r,s,o);else if(ho(l)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(n.view,s.slice(e[3],e[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(e[4],n,r,s,o);return a}};fe.prototype.renderInverted=function(e,n,r,s,o){var i=n.lookup(e[1]);if(!i||dn(i)&&i.length===0)return this.renderTokens(e[4],n,r,s,o)};fe.prototype.indentPartial=function(e,n,r){for(var s=n.replace(/[^ \t]/g,""),o=e.split(`
15
15
  `),i=0;i<o.length;i++)o[i].length&&(i>0||!r)&&(o[i]=s+o[i]);return o.join(`
16
16
  `)};fe.prototype.renderPartial=function(e,n,r,s){if(r){var o=this.getConfigTags(s),i=ho(r)?r(e[1]):r[e[1]];if(i!=null){var a=e[6],l=e[5],c=e[4],u=i;l==0&&c&&(u=this.indentPartial(i,c,a));var d=this.parse(u,o);return this.renderTokens(d,n,r,u,s)}}};fe.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};fe.prototype.escapedValue=function(e,n,r){var s=this.getConfigEscape(r)||ge.escape,o=n.lookup(e[1]);if(o!=null)return typeof o=="number"&&s===ge.escape?String(o):s(o)};fe.prototype.rawValue=function(e){return e[1]};fe.prototype.getConfigTags=function(e){return dn(e)?e:e&&typeof e=="object"?e.tags:void 0};fe.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!dn(e))return e.escape};var ge={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){In.templateCache=t},get templateCache(){return In.templateCache}},In=new fe;ge.clearCache=function(){return In.clearCache()};ge.parse=function(e,n){return In.parse(e,n)};ge.render=function(e,n,r,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+ld(e)+'" was given as the first argument for mustache#render(template, view, partials)');return In.render(e,n,r,s)};ge.escape=md;ge.Scanner=Bn;ge.Context=rn;ge.Writer=fe;function Ma(){ge.escape=t=>t}const Pn=t=>{const e=t.split(""),n=[],r=(o,i)=>{for(let a=i;a<e.length;a+=1)if(o.includes(e[a]))return a;return-1};let s=0;for(;s<e.length;)if(e[s]==="{"&&s+1<e.length&&e[s+1]==="{")n.push({type:"literal",text:"{"}),s+=2;else if(e[s]==="}"&&s+1<e.length&&e[s+1]==="}")n.push({type:"literal",text:"}"}),s+=2;else if(e[s]==="{"){const o=r("}",s);if(o<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(s+1,o).join("")}),s=o+1}else{if(e[s]==="}")throw new Error("Single '}' in template.");{const o=r("{}",s),i=(o<0?e.slice(s):e.slice(s,o)).join("");n.push({type:"literal",text:i}),s=o<0?e.length:o}}return n},Aa=(t,e=[])=>{const n=[];for(const r of t)if(r[0]==="name"){const s=r[1].includes(".")?r[1].split(".")[0]:r[1];n.push({type:"variable",name:s})}else if(["#","&","^",">"].includes(r[0])){if(n.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){const s=[...e,r[1]],o=Aa(r[4],s);n.push(...o)}}else n.push({type:"literal",text:r[1]});return n},_r=t=>{Ma();const e=ge.parse(t);return Aa(e)},Ia=(t,e)=>Pn(t).reduce((n,r)=>{if(r.type==="variable"){if(r.name in e){const s=typeof e[r.name]=="string"?e[r.name]:JSON.stringify(e[r.name]);return n+s}throw new Error(`(f-string) Missing value for input ${r.name}`)}return n+r.text},""),Pa=(t,e)=>(Ma(),ge.render(t,e)),vr={"f-string":Ia,mustache:Pa},Oa={"f-string":Pn,mustache:_r},Ae=(t,e,n)=>{try{return vr[e](t,n)}catch(r){throw Ii(r,"INVALID_PROMPT_INPUT")}},Sr=(t,e)=>Oa[e](t),zn=(t,e,n)=>{if(!(e in vr)){const r=Object.keys(vr);throw new Error(`Invalid template format. Got \`${e}\`;
17
17
  should be one of ${r}`)}try{const r=Object.fromEntries(n.map(s=>[s,"foo"]));Array.isArray(t)?t.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")Ae(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")Ae(s.image_url,e,r);else if(typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"){const o=s.image_url.url;Ae(o,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):Ae(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var rt=class gn extends An{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),zn(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(e){const n=await this.mergePartialAndUserVariables(e);return Ae(this.template,this.templateFormat,n)}static fromExamples(e,n,r,s=`
18
18
 
19
19
  `,o=""){const i=[o,...e,n].join(s);return new gn({inputVariables:r,template:i})}static fromTemplate(e,n){const{templateFormat:r="f-string",...s}=n??{},o=new Set;return Sr(e,r).forEach(i=>{i.type==="variable"&&o.add(i.name)}),new gn({inputVariables:[...o],templateFormat:r,template:e,...s})}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new gn(s)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(e){if(!e.template)throw new Error("Prompt template must have a template");return new gn({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}},sr=class Na extends Vn{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),zn([{type:"image_url",image_url:this.template}],this.templateFormat,n)}}_getPromptType(){return"prompt"}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new Na(s)}async format(e){const n={};for(const[i,a]of Object.entries(this.template))typeof a=="string"?n[i]=Ae(a,this.templateFormat,e):n[i]=a;const r=e.url||n.url,s=e.detail||n.detail;if(!r)throw new Error("Must provide either an image URL.");if(typeof r!="string")throw new Error("url must be a string.");const o={url:r};return s&&(o.detail=s),o}async formatPromptValue(e){const n=await this.format(e);return new Xu(n)}},As=class extends ae{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(t){const e=t.templateFormat??"f-string",n=Is(t.template,e);super({inputVariables:n,...t}),this.template=t.template,this.templateFormat=e,this.inputVariables=n}async format(t){return Ps(this.template,t,this.templateFormat)}async invoke(t){return await this._callWithConfig(this.format.bind(this),t,{runType:"prompt"})}};function Is(t,e){const n=[];for(const r of Object.values(t))if(typeof r=="string")Sr(r,e).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?Sr(s,e).forEach(o=>{o.type==="variable"&&n.push(o.name)}):typeof s=="object"&&n.push(...Is(s,e));else typeof r=="object"&&r!==null&&n.push(...Is(r,e));return Array.from(new Set(n))}function Ps(t,e,n){const r={};for(const[s,o]of Object.entries(t))if(typeof o=="string")r[s]=Ae(o,n,e);else if(Array.isArray(o)){const i=[];for(const a of o)typeof a=="string"?i.push(Ae(a,n,e)):typeof a=="object"&&i.push(Ps(a,e,n));r[s]=i}else typeof o=="object"&&o!==null?r[s]=Ps(o,e,n):r[s]=o;return r}var Dr=class extends ae{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(t,e){return this._callWithConfig(n=>this.formatMessages(n),t,{...e,runType:"prompt"})}},Os=class extends Dr{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(t){typeof t=="string"&&(t={variableName:t}),super(t),this.variableName=t.variableName,this.optional=t.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(t){const e=t[this.variableName];if(this.optional&&!e)return[];if(!e){const r=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw r.name="InputFormatError",r}let n;try{Array.isArray(e)?n=e.map(xn):n=[xn(e)]}catch(r){const s=typeof e=="string"?e:JSON.stringify(e,null,2),o=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${s}`,`Additional message: ${r.message}`].join(`
20
20
 
21
- `));throw o.name="InputFormatError",o.lc_error_code=r.lc_error_code,o}return n}},Ra=class extends Dr{prompt;constructor(t){"prompt"in t||(t={prompt:t}),super(t),this.prompt=t.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(t){return[await this.format(t)]}},fo=class extends Vn{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new Zu(e)}},$a=class extends Ra{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(t,e){"prompt"in t||(t={prompt:t,role:e}),super(t),this.role=t.role}async format(t){return new Pi(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(rt.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function Cd(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function kd(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}var po=class extends Dr{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(t,e){if("prompt"in t||(t={prompt:t}),super(t),this.prompt=t.prompt,Array.isArray(this.prompt)){let n=[];this.prompt.forEach(r=>{"inputVariables"in r&&(n=n.concat(r.inputVariables))}),this.inputVariables=n}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=e??this.additionalOptions}createMessage(t){const e=this.constructor;if(e._messageClass()){const n=e._messageClass();return new n({content:t})}else if(e.chatMessageClass){const n=e.chatMessageClass();return new n({content:t,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(t){switch(t){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(t,e){if(typeof t=="string")return new this(rt.fromTemplate(t,e));const n=[];for(const r of t)if(typeof r=="string")n.push(rt.fromTemplate(r,e));else if(r!==null)if(Cd(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const o={...e,additionalContentFields:r};n.push(rt.fromTemplate(s,o))}else if(kd(r)){let s=r.image_url??"",o,i=[];if(typeof s=="string"){let a;e?.templateFormat==="mustache"?a=_r(s):a=Pn(s);const l=a.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
21
+ `));throw o.name="InputFormatError",o.lc_error_code=r.lc_error_code,o}return n}},Ra=class extends Dr{prompt;constructor(t){"prompt"in t||(t={prompt:t}),super(t),this.prompt=t.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(t){return[await this.format(t)]}},fo=class extends Vn{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new Zu(e)}},$a=class extends Ra{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(t,e){"prompt"in t||(t={prompt:t,role:e}),super(t),this.role=t.role}async format(t){return new Pi(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(rt.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function Cd(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function Td(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}var po=class extends Dr{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(t,e){if("prompt"in t||(t={prompt:t}),super(t),this.prompt=t.prompt,Array.isArray(this.prompt)){let n=[];this.prompt.forEach(r=>{"inputVariables"in r&&(n=n.concat(r.inputVariables))}),this.inputVariables=n}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=e??this.additionalOptions}createMessage(t){const e=this.constructor;if(e._messageClass()){const n=e._messageClass();return new n({content:t})}else if(e.chatMessageClass){const n=e.chatMessageClass();return new n({content:t,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(t){switch(t){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(t,e){if(typeof t=="string")return new this(rt.fromTemplate(t,e));const n=[];for(const r of t)if(typeof r=="string")n.push(rt.fromTemplate(r,e));else if(r!==null)if(Cd(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const o={...e,additionalContentFields:r};n.push(rt.fromTemplate(s,o))}else if(Td(r)){let s=r.image_url??"",o,i=[];if(typeof s=="string"){let a;e?.templateFormat==="mustache"?a=_r(s):a=Pn(s);const l=a.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
22
22
  Got: ${l}
23
- From: ${s}`);i=[l[0]]}else i=[];s={url:s},o=new sr({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let a;e?.templateFormat==="mustache"?a=_r(s.url):a=Pn(s.url),i=a.flatMap(l=>l.type==="variable"?[l.name]:[])}else i=[];o=new sr({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else throw new Error("Invalid image template");n.push(o)}else typeof r=="object"&&n.push(new As({template:r,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof An){const e=await this.prompt.format(t);return this.createMessage(e)}else{const e=[];for(const n of this.prompt){let r={};if(!("inputVariables"in n))throw new Error(`Prompt ${n} does not have inputVariables defined.`);for(const s of n.inputVariables)r||(r={[s]:t[s]}),r={...r,[s]:t[s]};if(n instanceof An){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),s!==""&&e.push({...o,type:"text",text:s})}else if(n instanceof sr){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),e.push({...o,type:"image_url",image_url:s})}else if(n instanceof As){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),e.push({...o,...s})}}return this.createMessage(e)}}async formatMessages(t){return[await this.format(t)]}},mo=class extends po{static _messageClass(){return se}static lc_name(){return"HumanMessagePromptTemplate"}},ja=class extends po{static _messageClass(){return P}static lc_name(){return"AIMessagePromptTemplate"}},La=class extends po{static _messageClass(){return oe}static lc_name(){return"SystemMessagePromptTemplate"}};function Td(t){return typeof t.formatMessages=="function"}function Ed(t,e){if(Td(t)||Ue(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){const s=t[1];if(e?.templateFormat==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}"){const o=s.slice(2,-2);return new Os({variableName:o,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const o=s.slice(1,-1);return new Os({variableName:o,optional:!0})}throw new Error(`Invalid placeholder template for format ${e?.templateFormat??'"f-string"'}: "${t[1]}". Expected a variable name surrounded by ${e?.templateFormat==="mustache"?"double":"single"} curly braces.`)}const n=xn(t);let r;if(typeof n.content=="string"?r=n.content:r=n.content.map(s=>"text"in s?{...s,text:s.text}:"image_url"in s?{...s,image_url:s.image_url}:s),n._getType()==="human")return mo.fromTemplate(r,e);if(n._getType()==="ai")return ja.fromTemplate(r,e);if(n._getType()==="system")return La.fromTemplate(r,e);if(Pi.isInstance(n))return $a.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function xd(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var go=class or extends fo{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(e){if(super(e),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){const n=new Set;for(const a of this.promptMessages)if(!(a instanceof _n))for(const l of a.inputVariables)n.add(l);const r=this.inputVariables,s=new Set(this.partialVariables?r.concat(Object.keys(this.partialVariables)):r),o=new Set([...s].filter(a=>!n.has(a)));if(o.size>0)throw new Error(`Input variables \`${[...o]}\` are not used in any of the prompt messages.`);const i=new Set([...n].filter(a=>!s.has(a)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,n){if(typeof e.content=="string")return e;const r=await Promise.all(e.content.map(async s=>{if(s.type!=="image_url")return s;let o="";typeof s.image_url=="string"?o=s.image_url:typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(o=s.image_url.url);const a=await rt.fromTemplate(o,{templateFormat:this.templateFormat}).format(n);return typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url?s.image_url.url=a:s.image_url=a,s}));return e.content=r,e}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let r=[];for(const s of this.promptMessages)if(s instanceof _n)r.push(await this._parseImagePrompts(s,n));else{let o;this.templateFormat==="mustache"?o={...n}:o=s.inputVariables.reduce((a,l)=>{if(!(l in n)&&!(xd(s)&&s.optional))throw Ii(new Error(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");return a[l]=n[l],a},{});const i=await s.formatMessages(o);r=r.concat(i)}return r}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new or(s)}static fromTemplate(e,n){const r=rt.fromTemplate(e,n),s=new mo({prompt:r});return this.fromMessages([s])}static fromMessages(e,n){const r=e.reduce((i,a)=>i.concat(a instanceof or?a.promptMessages:[Ed(a,n)]),[]),s=e.reduce((i,a)=>a instanceof or?Object.assign(i,a.partialVariables):i,Object.create(null)),o=new Set;for(const i of r)if(!(i instanceof _n))for(const a of i.inputVariables)a in s||o.add(a);return new this({...n,inputVariables:[...o],promptMessages:r,partialVariables:s,templateFormat:n?.templateFormat})}},Md=class Ns extends An{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
23
+ From: ${s}`);i=[l[0]]}else i=[];s={url:s},o=new sr({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let a;e?.templateFormat==="mustache"?a=_r(s.url):a=Pn(s.url),i=a.flatMap(l=>l.type==="variable"?[l.name]:[])}else i=[];o=new sr({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else throw new Error("Invalid image template");n.push(o)}else typeof r=="object"&&n.push(new As({template:r,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof An){const e=await this.prompt.format(t);return this.createMessage(e)}else{const e=[];for(const n of this.prompt){let r={};if(!("inputVariables"in n))throw new Error(`Prompt ${n} does not have inputVariables defined.`);for(const s of n.inputVariables)r||(r={[s]:t[s]}),r={...r,[s]:t[s]};if(n instanceof An){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),s!==""&&e.push({...o,type:"text",text:s})}else if(n instanceof sr){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),e.push({...o,type:"image_url",image_url:s})}else if(n instanceof As){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),e.push({...o,...s})}}return this.createMessage(e)}}async formatMessages(t){return[await this.format(t)]}},mo=class extends po{static _messageClass(){return se}static lc_name(){return"HumanMessagePromptTemplate"}},ja=class extends po{static _messageClass(){return P}static lc_name(){return"AIMessagePromptTemplate"}},La=class extends po{static _messageClass(){return oe}static lc_name(){return"SystemMessagePromptTemplate"}};function kd(t){return typeof t.formatMessages=="function"}function Ed(t,e){if(kd(t)||Ue(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){const s=t[1];if(e?.templateFormat==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}"){const o=s.slice(2,-2);return new Os({variableName:o,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const o=s.slice(1,-1);return new Os({variableName:o,optional:!0})}throw new Error(`Invalid placeholder template for format ${e?.templateFormat??'"f-string"'}: "${t[1]}". Expected a variable name surrounded by ${e?.templateFormat==="mustache"?"double":"single"} curly braces.`)}const n=xn(t);let r;if(typeof n.content=="string"?r=n.content:r=n.content.map(s=>"text"in s?{...s,text:s.text}:"image_url"in s?{...s,image_url:s.image_url}:s),n._getType()==="human")return mo.fromTemplate(r,e);if(n._getType()==="ai")return ja.fromTemplate(r,e);if(n._getType()==="system")return La.fromTemplate(r,e);if(Pi.isInstance(n))return $a.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function xd(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var go=class or extends fo{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(e){if(super(e),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){const n=new Set;for(const a of this.promptMessages)if(!(a instanceof _n))for(const l of a.inputVariables)n.add(l);const r=this.inputVariables,s=new Set(this.partialVariables?r.concat(Object.keys(this.partialVariables)):r),o=new Set([...s].filter(a=>!n.has(a)));if(o.size>0)throw new Error(`Input variables \`${[...o]}\` are not used in any of the prompt messages.`);const i=new Set([...n].filter(a=>!s.has(a)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,n){if(typeof e.content=="string")return e;const r=await Promise.all(e.content.map(async s=>{if(s.type!=="image_url")return s;let o="";typeof s.image_url=="string"?o=s.image_url:typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(o=s.image_url.url);const a=await rt.fromTemplate(o,{templateFormat:this.templateFormat}).format(n);return typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url?s.image_url.url=a:s.image_url=a,s}));return e.content=r,e}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let r=[];for(const s of this.promptMessages)if(s instanceof _n)r.push(await this._parseImagePrompts(s,n));else{let o;this.templateFormat==="mustache"?o={...n}:o=s.inputVariables.reduce((a,l)=>{if(!(l in n)&&!(xd(s)&&s.optional))throw Ii(new Error(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");return a[l]=n[l],a},{});const i=await s.formatMessages(o);r=r.concat(i)}return r}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new or(s)}static fromTemplate(e,n){const r=rt.fromTemplate(e,n),s=new mo({prompt:r});return this.fromMessages([s])}static fromMessages(e,n){const r=e.reduce((i,a)=>i.concat(a instanceof or?a.promptMessages:[Ed(a,n)]),[]),s=e.reduce((i,a)=>a instanceof or?Object.assign(i,a.partialVariables):i,Object.create(null)),o=new Set;for(const i of r)if(!(i instanceof _n))for(const a of i.inputVariables)a in s||o.add(a);return new this({...n,inputVariables:[...o],promptMessages:r,partialVariables:s,templateFormat:n?.templateFormat})}},Md=class Ns extends An{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
24
24
 
25
25
  `;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(e){if(super(e),Object.assign(this,e),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),zn(this.prefix+this.suffix,this.templateFormat,n)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new Ns(s)}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),s=await Promise.all(r.map(i=>this.examplePrompt.format(i))),o=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return Ae(o,this.templateFormat,n)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){const{example_prompt:n}=e;if(!n)throw new Error("Missing example prompt");const r=await rt.deserialize(n);let s;if(Array.isArray(e.examples))s=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new Ns({inputVariables:e.input_variables,examplePrompt:r,examples:s,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},Ad=class Da extends fo{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
26
26
 
@@ -35,20 +35,20 @@ ${s}`)}return t}function Bd(t){const e=t.split(`
35
35
  `)}var Za={};X(Za,{EventStreamContentType:()=>zd,convertEventStreamToIterableReadableDataStream:()=>Wd,getBytes:()=>Qa,getLines:()=>el,getMessages:()=>tl});const zd="text/event-stream";async function Qa(t,e){if(t instanceof ReadableStream){const n=t.getReader();for(;;){const r=await n.read();if(r.done){e(new Uint8Array,!0);break}e(r.value)}}else try{for await(const n of t)e(new Uint8Array(n));e(new Uint8Array,!0)}catch(n){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${n.message}`].join(`
36
36
  `))}}var $t=(function(t){return t[t.NewLine=10]="NewLine",t[t.CarriageReturn=13]="CarriageReturn",t[t.Space=32]="Space",t[t.Colon=58]="Colon",t})($t||{});function el(t){let e,n,r,s=!1;return function(i,a){if(a){t(i,0,!0);return}e===void 0?(e=i,n=0,r=-1):e=Hd(e,i);const l=e.length;let c=0;for(;n<l;){s&&(e[n]===$t.NewLine&&(c=++n),s=!1);let u=-1;for(;n<l&&u===-1;++n)switch(e[n]){case $t.Colon:r===-1&&(r=n-c);break;case $t.CarriageReturn:s=!0;case $t.NewLine:u=n;break}if(u===-1)break;t(e.subarray(c,u),r),c=n,r=-1}c===l?e=void 0:c!==0&&(e=e.subarray(c),n-=c)}}function tl(t,e,n){let r=es();const s=new TextDecoder;return function(i,a,l){if(l){Gd(r)||(t?.(r),r=es());return}if(i.length===0)t?.(r),r=es();else if(a>0){const c=s.decode(i.subarray(0,a)),u=a+(i[a+1]===$t.Space?2:1),d=s.decode(i.subarray(u));switch(c){case"data":r.data=r.data?r.data+`
37
37
  `+d:d;break;case"event":r.event=d;break;case"id":e?.(r.id=d);break;case"retry":{const h=parseInt(d,10);Number.isNaN(h)||n?.(r.retry=h);break}}}}}function Hd(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function es(){return{data:"",event:"",id:"",retry:void 0}}function Wd(t,e){const n=new ReadableStream({async start(r){const s=tl(i=>{if(i.event==="error")throw new Error(i.data??"Unspecified event streaming error.");i.event==="metadata"?e?.(i):i.data&&r.enqueue(i.data)});await Qa(t,el((i,a,l)=>{s(i,a,l),l&&r.close()}))}});return En.fromReadableStream(n)}function Gd(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var Kd={};function nl(t,e){let n=0,r=0,s=0;for(let o=0;o<t.length;o++)n+=t[o]*e[o],r+=t[o]*t[o],s+=e[o]*e[o];return n/(Math.sqrt(r)*Math.sqrt(s))}function Jd(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function qd(t,e){let n=0;for(let r=0;r<t.length;r++)n+=(t[r]-e[r])*(t[r]-e[r]);return n}function Yd(t,e){return Math.sqrt(qd(t,e))}var rl={};X(rl,{cosineSimilarity:()=>Rs,euclideanDistance:()=>Qd,innerProduct:()=>Zd,matrixFunc:()=>Fr,maximalMarginalRelevance:()=>ef,normalize:()=>Xd});function Fr(t,e,n){if(t.length===0||t[0].length===0||e.length===0||e[0].length===0)return[[]];if(t[0].length!==e[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[t.length,t[0].length]} and Y has shape ${[e.length,e[0].length]}.`);return t.map(r=>e.map(s=>n(r,s)).map(s=>Number.isNaN(s)?0:s))}function Xd(t,e=!1){const n=tf(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function Rs(t,e){return Fr(t,e,nl)}function Zd(t,e){return Fr(t,e,Jd)}function Qd(t,e){return Fr(t,e,Yd)}function ef(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(t[0])?t:[t],o=Rs(s,e)[0],i=sl(o).maxIndex,a=[e[i]],l=[i];for(;l.length<Math.min(r,e.length);){let c=-1/0,u=-1;const d=Rs(e,a);o.forEach((h,f)=>{if(l.includes(f))return;const m=Math.max(...d[f]),p=n*h-(1-n)*m;p>c&&(c=p,u=f)}),a.push(e[u]),l.push(u)}return l}function sl(t){if(t.length===0)return{maxIndex:-1,maxValue:NaN};let e=t[0],n=0;for(let r=1;r<t.length;r+=1)t[r]>e&&(n=r,e=t[r]);return{maxIndex:n,maxValue:e}}function tf(t){return t.reduce((e,n)=>Math.max(e,sl(n).maxValue),0)}var nf=class extends Un{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){if(e?.stop?.length)return{generations:[{message:new P(e.stop[0]),text:e.stop[0]}]};const r=t.map(s=>typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2)).join(`
38
- `);return await n?.handleLLMNewToken(r),{generations:[{message:new P(r),text:r}],llmOutput:{}}}},rf=class ol extends Un{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:e=50,responses:n=[],chunks:r=[],toolStyle:s="openai",thrownErrorString:o,...i}){super(i),this.sleep=e,this.responses=n,this.chunks=r,this.toolStyle=s,this.thrownErrorString=o}_llmType(){return"fake"}bindTools(e){const n=[...this.tools,...e],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:Me(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:Me(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:Me(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:Me(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new ol({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return o.tools=n,o.withConfig({tools:s})}async _generate(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=this.responses?.[0]?.content??e[0].content??"";return{generations:[{text:"",message:new P({content:s,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const i of this.chunks){const a=new Cs({message:new Qt({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});if(n.signal?.aborted)break;yield a,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:a})}return}const s=this.responses?.[0]??new P(typeof e[0].content=="string"?e[0].content:""),o=typeof s.content=="string"?s.content:"";for(const i of o){await new Promise(l=>setTimeout(l,this.sleep));const a=new Cs({message:new Qt({content:i}),text:i});if(n.signal?.aborted)break;yield a,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:a})}}},sf=class il extends Un{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(e){super(e);const{responses:n,sleep:r,emitCustomEvent:s,generationInfo:o}=e;this.responses=n,this.sleep=r,this.emitCustomEvent=s??this.emitCustomEvent,this.generationInfo=o}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(e,n,r){if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);if(this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0}),n?.stop?.length)return{generations:[this._formatGeneration(n.stop[0])]};{const s=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(s)],llmOutput:{}}}}_formatGeneration(e){return{message:new P(e),text:e}}async*_streamResponseChunks(e,n,r){const s=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0});const o=[...s];for(let i=0;i<o.length;i++){const a=o[i],l=i===o.length-1;if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);const c=this._createResponseChunk(a,l?this.generationInfo:void 0);if(n.signal?.aborted)break;yield c,r?.handleLLMNewToken(a)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,n){return new Cs({message:new Qt({content:e}),text:e,generationInfo:n})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(e){const n=[...this.tools,...e],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:Me(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:Me(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:Me(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:Me(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new il({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return o.tools=n,o.toolStyle=this.toolStyle,o.i=this.i,o.withConfig({tools:s})}withStructuredOutput(e,n){return yr.from(async r=>{const s=await this.invoke(r);if(s.tool_calls?.[0]?.args)return s.tool_calls[0].args;if(typeof s.content=="string")return JSON.parse(s.content);throw new Error("No structured output found")})}},of=class extends Ui{vectorSize;constructor(t){super(t??{}),this.vectorSize=t?.vectorSize??4}async embedDocuments(t){return Promise.all(t.map(e=>this.embedQuery(e)))}async embedQuery(t){let e=t;e=e.toLowerCase().replaceAll(/[^a-z ]/g,"");const n=e.length%this.vectorSize,r=n===0?0:this.vectorSize-n,s=e.length+r;e=e.padEnd(s," ");const o=e.length/this.vectorSize,i=[];for(let l=0;l<e.length;l+=o)i.push(e.slice(l,l+o));return i.map(l=>{let c=0;for(let d=0;d<l.length;d+=1)c+=l===" "?0:l.charCodeAt(d);return c%26/26})}},af=class extends Ui{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},lf=class extends Vi{response;thrownErrorString;constructor(t){super(t),this.response=t.response,this.thrownErrorString=t.thrownErrorString}_llmType(){return"fake"}async _call(t,e,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.response??t;return await n?.handleLLMNewToken(r),r}},cf=class extends Vi{sleep=50;responses;thrownErrorString;constructor(t){super(t),this.sleep=t.sleep??this.sleep,this.responses=t.responses,this.thrownErrorString=t.thrownErrorString}_llmType(){return"fake"}async _call(t){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const e=this.responses?.[0];return this.responses=this.responses?.slice(1),e??t}async*_streamResponseChunks(t,e,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.responses?.[0];this.responses=this.responses?.slice(1);for(const s of r??t)await new Promise(o=>setTimeout(o,this.sleep)),yield{text:s,generationInfo:{}},await n?.handleLLMNewToken(s)}},uf=class extends na{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async addUserMessage(t){this.messages.push(new se(t))}async addAIMessage(t){this.messages.push(new P(t))}async clear(){this.messages=[]}},hf=class extends ao{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},df=class extends to{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},ff=class extends Qu{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},pf=class extends lo{lc_namespace=["test","fake"];output=[new We({pageContent:"foo"}),new We({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},mf=class extends ae{lc_namespace=["tests","fake"];returnOptions;constructor(t){super(t),this.returnOptions=t.returnOptions}async invoke(t,e){return this.returnOptions?e??{}:{input:t}}},gf=class extends jr{name;description;schema;constructor(t){super(t),this.name=t.name,this.description=t.description,this.schema=t.schema}async _call(t,e){return JSON.stringify(t)}},yf=class extends to{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(t=>{this.runPromiseResolver=t})}async persistRun(t){this.runPromiseResolver(t)}async extract(){return this.runPromise}},wf=class al extends co{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??nl}async addDocuments(e){const n=e.map(({pageContent:r})=>r);return this.addVectors(await this.embeddings.embedDocuments(n),e)}async addVectors(e,n){const r=e.map((s,o)=>({content:n[o].pageContent,embedding:s,metadata:n[o].metadata}));this.memoryVectors=this.memoryVectors.concat(r)}async similaritySearchVectorWithScore(e,n,r){const s=l=>{if(!r)return!0;const c=new We({metadata:l.metadata,pageContent:l.content});return r(c)},o=this.memoryVectors.filter(s);return o.map((l,c)=>({similarity:this.similarity(e,l.embedding),index:c})).sort((l,c)=>l.similarity>c.similarity?-1:0).slice(0,n).map(l=>[new We({metadata:o[l.index].metadata,pageContent:o[l.index].content}),l.similarity])}static async fromTexts(e,n,r,s){const o=[];for(let i=0;i<e.length;i+=1){const a=Array.isArray(n)?n[i]:n,l=new We({pageContent:e[i],metadata:a});o.push(l)}return al.fromDocuments(o,r,s)}static async fromDocuments(e,n,r){const s=new this(n,r);return await s.addDocuments(e),s}static async fromExistingIndex(e,n){return new this(e,n)}},ll={};X(ll,{FakeChatMessageHistory:()=>uf,FakeChatModel:()=>nf,FakeEmbeddings:()=>af,FakeLLM:()=>lf,FakeListChatMessageHistory:()=>hf,FakeListChatModel:()=>sf,FakeRetriever:()=>pf,FakeRunnable:()=>mf,FakeSplitIntoListParser:()=>ff,FakeStreamingChatModel:()=>rf,FakeStreamingLLM:()=>cf,FakeTool:()=>gf,FakeTracer:()=>df,FakeVectorStore:()=>wf,SingleRunExtractor:()=>yf,SyntheticEmbeddings:()=>of});var cl={};X(cl,{agents:()=>Vh,caches:()=>uh,callbacks__base:()=>cu,callbacks__manager:()=>lu,callbacks__promises:()=>au,chat_history:()=>ta,document_loaders__base:()=>ua,document_loaders__langsmith:()=>da,documents:()=>pa,embeddings:()=>ph,errors:()=>iu,example_selectors:()=>wa,index:()=>zh,indexing:()=>ka,language_models__base:()=>ch,language_models__chat_models:()=>lh,language_models__llms:()=>gh,language_models__profile:()=>od,load__serializable:()=>ou,memory:()=>ra,messages:()=>su,messages__tool:()=>ru,output_parsers:()=>ah,output_parsers__openai_functions:()=>xa,output_parsers__openai_tools:()=>mh,outputs:()=>nu,prompt_values:()=>ih,prompts:()=>Ua,retrievers:()=>la,retrievers__document_compressors:()=>Va,runnables:()=>oh,runnables__graph:()=>tu,singletons:()=>eu,stores:()=>oa,structured_query:()=>Ja,tools:()=>Wu,tracers__base:()=>Qc,tracers__console:()=>Zc,tracers__log_stream:()=>Xc,tracers__run_collector:()=>qa,tracers__tracer_langchain:()=>Yc,types__stream:()=>Ud,utils__async_caller:()=>qc,utils__chunk_array:()=>fh,utils__context:()=>Ya,utils__env:()=>Jc,utils__event_source_parse:()=>Za,utils__format:()=>Kd,utils__function_calling:()=>sh,utils__hash:()=>rh,utils__json_patch:()=>nh,utils__json_schema:()=>Kc,utils__math:()=>rl,utils__stream:()=>Gc,utils__testing:()=>ll,utils__tiktoken:()=>th,utils__types:()=>eh,vectorstores:()=>ca});const bf=50;function _f(t){const e={};for(let n=t;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(e,Reflect.get(n.prototype,"lc_aliases"));return Object.entries(e).reduce((n,[r,s])=>(n[s]=r,n),{})}async function ar(t){const{optionalImportsMap:e,optionalImportEntrypoints:n,importMap:r,secretsMap:s,secretsFromEnv:o,path:i,depth:a,maxDepth:l}=this,c=i.join(".");if(a>l)throw new Error(`Maximum recursion depth (${l}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof t!="object"||t==null)return t;if(Array.isArray(t))return Promise.all(t.map((h,f)=>ar.call({...this,path:[...i,`${f}`],depth:a+1},h)));const u=t;if(uu(u))return hu(u);if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="secret"){const h=u,[f]=h.id;if(f in s)return s[f];if(o){const m=du(f);if(m)return m}throw new Error(`Missing secret "${f}" at ${c}`)}if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="not_implemented"){const f=JSON.stringify(u);throw new Error(`Trying to load an object that doesn't implement serialization: ${c} -> ${f}`)}if("lc"in u&&"type"in u&&"id"in u&&"kwargs"in u&&u.lc===1&&u.type==="constructor"){const h=u,f=JSON.stringify(h),[m,...p]=h.id.slice().reverse(),C=p.reverse(),k={langchain_core:cl,langchain:r};let T=null;const _=[C.join("/")];C[0]==="langchain_community"&&_.push(["langchain",...C.slice(1)].join("/"));const g=_.find(b=>b in e);if(Uh.concat(n).includes(C.join("/"))||g)if(g!==void 0)T=await e[g];else throw new Error(`Missing key "${C.join("/")}" for ${c} in load(optionalImportsMap={})`);else{let b;if(C[0]==="langchain"||C[0]==="langchain_core")b=k[C[0]],C.shift();else throw new Error(`Invalid namespace: ${c} -> ${f}`);if(C.length===0)throw new Error(`Invalid namespace: ${c} -> ${f}`);let E;do{if(E=C.join("__"),E in b)break;C.pop()}while(C.length>0);E in b&&(T=b[E])}if(typeof T!="object"||T===null)throw new Error(`Invalid namespace: ${c} -> ${f}`);const v=T[m]??Object.values(T).find(b=>typeof b=="function"&&fu(b)===m);if(typeof v!="function")throw new Error(`Invalid identifer: ${c} -> ${f}`);const M=await ar.call({...this,path:[...i,"kwargs"],depth:a+1},h.kwargs),w=new v(pu(M,mu,_f(v)));return Object.defineProperty(w.constructor,"name",{value:m}),w}const d={};for(const[h,f]of Object.entries(u))d[h]=await ar.call({...this,path:[...i,h],depth:a+1},f);return d}async function vf(t,e){const n=JSON.parse(t),r={optionalImportsMap:{},optionalImportEntrypoints:[],secretsMap:{},secretsFromEnv:!1,importMap:{},path:["$"],depth:0,maxDepth:bf};return ar.call(r,n)}function Sf(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function $s(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>$s(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await $s(r);if(e.lc===2&&e.type==="undefined")return;if(e.lc===2&&e.type==="constructor"&&Array.isArray(e.id))try{const n=e.id[e.id.length-1];let r;switch(n){case"Set":r=Set;break;case"Map":r=Map;break;case"RegExp":r=RegExp;break;case"Error":r=Error;break;default:return e}return e.method?r[e.method](...e.args||[]):new r(...e.args||[])}catch{return e}else if(Sf(e))return vf(JSON.stringify(e));return e}}return t}function ts(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function Cf(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?ts(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?ts(RegExp,void 0,[t.source,t.flags]):t instanceof Error?ts(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t}var kf=class{_dumps(t){return new TextEncoder().encode(Dh(t,(n,r)=>Cf(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return $s(e)}async loadsTyped(t,e){if(t==="bytes")return typeof e=="string"?new TextEncoder().encode(e):e;if(t==="json")return this._loads(typeof e=="string"?e:new TextDecoder().decode(e));throw new Error(`Unknown serialization type: ${t}`)}};function ul(t){if(typeof t!="object"||t===null)return t;const e=Array.isArray(t)?[]:{};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=ul(t[n]));return e}function hl(){return{v:4,id:ea(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function Cr(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:ul(t.versions_seen)}}function dl(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function Tf(...t){return t.reduce((e,n,r)=>r===0?n:dl(e,n)>=0?e:n)}const Ef={[Nh]:-1,[nr]:-2,[Rh]:-3,[$h]:-4};var pn=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function xf(t){if(t.length===0)throw new pn("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new pn(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new pn(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new pn(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new pn(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var Mf=class{async get(t,e){return(await this.batch([{namespace:t,key:e}]))[0]}async search(t,e={}){const{filter:n,limit:r=10,offset:s=0,query:o}=e;return(await this.batch([{namespacePrefix:t,filter:n,limit:r,offset:s,query:o}]))[0]}async put(t,e,n,r){xf(t),await this.batch([{namespace:t,key:e,value:n,index:r}])}async delete(t,e){await this.batch([{namespace:t,key:e,value:null}])}async listNamespaces(t={}){const{prefix:e,suffix:n,maxDepth:r,limit:s=100,offset:o=0}=t,i=[];return e&&i.push({matchType:"prefix",path:e}),n&&i.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:i.length?i:void 0,maxDepth:r,limit:s,offset:o}]))[0]}start(){}stop(){}};const Af=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var If=class extends Mf{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=Af(t)}get isRunning(){return this.running}async batch(t){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(t,e){return this.enqueueOperation({namespace:t,key:e})}async search(t,e){const{filter:n,limit:r=10,offset:s=0,query:o}=e||{};return this.enqueueOperation({namespacePrefix:t,filter:n,limit:r,offset:s,query:o})}async put(t,e,n){return this.enqueueOperation({namespace:t,key:e,value:n})}async delete(t,e){return this.enqueueOperation({namespace:t,key:e,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(t){return new Promise((e,n)=>{const r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:t,resolve:e,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;const t=new Map(this.queue);this.queue.clear();try{const e=Array.from(t.values()).map(({operation:r})=>r),n=await this.store.batch(e);t.forEach(({resolve:r},s)=>{const o=Array.from(t.keys()).indexOf(s);r(n[o])})}catch(e){t.forEach(({reject:n})=>{n(e)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},Pf=class{serde=new kf;constructor(t){this.serde=t||this.serde}};function fl(t){return t!=null&&t.lg_is_channel===!0}var ut=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===ee.unminifiable_name)return!1;throw t}}equals(t){return this===t}};const js=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function vo(t){if(t[js]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];fl(r)&&(e[n]=r)}return Object.assign(e,{[js]:!0}),e}function kr(t,e){const n=vo(t),r={};for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=e.channel_values[s];r[s]=n[s].fromCheckpoint(o)}return Object.assign(r,{[js]:!0}),r}function pt(t,e,n,r){let s;if(e===void 0)s=t.channel_values;else{s={};for(const o in e)if(Object.prototype.hasOwnProperty.call(e,o))try{s[o]=e[o].checkpoint()}catch(i){if(i.name!==ee.unminifiable_name)throw i}}return{v:4,id:r?.id??ea(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}const Of=t=>t!=null&&t.lc_graph_name==="BinaryOperatorAggregate";var Tr=class pl extends ut{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(e,n){super(),this.operator=e,this.initialValueFactory=n,this.value=n?.()}fromCheckpoint(e){const n=new pl(this.operator,this.initialValueFactory);return typeof e<"u"&&(n.value=e),n}update(e){let n=e;if(!n.length)return!1;this.value===void 0&&([this.value]=n,n=n.slice(1));for(const r of n)this.value!==void 0&&(this.value=this.operator(this.value,r));return!0}get(){if(this.value===void 0)throw new ee;return this.value}checkpoint(){if(this.value===void 0)throw new ee;return this.value}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:Of(e)?this.operator===e.operator:!1}},Ur=class ml extends ut{lc_graph_name="LastValue";value=[];constructor(e){super(),this.initialValueFactory=e,e&&(this.value=[e()])}fromCheckpoint(e){const n=new ml(this.initialValueFactory);return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new B("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new ee;return this.value[0]}checkpoint(){if(this.value.length===0)throw new ee;return this.value[0]}isAvailable(){return this.value.length!==0}},Nf=class gl extends ut{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new gl;if(typeof e<"u"){const[r,s]=e;n.value=[r],n.finished=s}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new ee;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},Ls=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}static isInstance(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}};const Ds=function(t){return t?Fs(t):new Ur};Ds.Root=t=>new Ls(t);function Fs(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new Tr(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new Tr(t.value,t.default):new Ur}const U="__start__",N="__end__",Ve="__input__",Rf="__copy__",pe="__error__",ns="__pregel_ns_writes",st="__pregel_send",So="__pregel_call",vt="__pregel_read",J="__pregel_checkpointer",Ye="__pregel_resuming",Cn="__pregel_task_id",Er="__pregel_stream",$f="__pregel_resume_value",lr="__pregel_resume_map",ot="__pregel_scratchpad",cr="__pregel_previous",yl="__pregel_durability",Us="checkpoint_id",Ne="checkpoint_ns",jf="__pregel_node_finished",Ce="checkpoint_map",ei="__pregel_abort_signals",D="__interrupt__",me="__resume__",Co="__no_writes__",sn="__return__",rs="__previous__",Y="langsmith:hidden",Lf="langsmith:nostream",ti="__self__",Se="__pregel_tasks",_e="__pregel_push",ur="__pregel_pull",ke="00000000-0000-0000-0000-000000000000",Df=[Y,Ve,D,me,pe,Co,st,vt,J,yl,Er,Ye,Cn,So,$f,ot,cr,Ce,Ne,Us],Z="|",Ge=":",ni=Symbol.for("langgraph.command");var Ff=class{[ni];constructor(t){this[ni]=t}};function Vs(t){const e=t;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var he=class{lg_name="Send";node;args;constructor(t,e){this.node=t,this.args=On(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function ye(t){return t instanceof he}function wl(t){return!t||typeof t!="object"||!(D in t)?!1:Array.isArray(t[D])}var G=class extends Ff{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(t){super(t),this.resume=t.resume,this.graph=t.graph,this.update=t.update,t.goto&&(this.goto=Array.isArray(t.goto)?On(t.goto):[On(t.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let t;return typeof this.goto=="string"?t=this.goto:ye(this.goto)?t=this.goto.toJSON():t=this.goto?.map(e=>typeof e=="string"?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:t}}};function q(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function On(t,e=new Map){if(t!=null&&typeof t=="object"){if(e.has(t))return e.get(t);let n;if(Array.isArray(t))n=[],e.set(t,n),t.forEach((r,s)=>{n[s]=On(r,e)});else if(q(t)&&!(t instanceof G))n=new G(t),e.set(t,n);else if(Vs(t)&&!(t instanceof he))n=new he(t.node,t.args),e.set(t,n);else if(q(t)||ye(t))n=t,e.set(t,n);else if("lc_serializable"in t&&t.lc_serializable)n=t,e.set(t,n);else{n={},e.set(t,n);for(const[r,s]of Object.entries(t))n[r]=On(s,e)}return n}return t}const Uf=["tags","metadata","callbacks","configurable"],Vf=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],Bf=25;function bl(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:Bf,configurable:{}},n=He.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(Uf.includes(r)){let o;Array.isArray(s)?o=[...s]:typeof s=="object"?r==="callbacks"&&"copy"in s&&typeof s.copy=="function"?o=s.copy():o={...s}:o=s,e[r]=o}else e[r]=s}for(const r of t)if(r!==void 0)for(const[s,o]of Object.entries(r))o!==void 0&&Vf.includes(s)&&(e[s]=o);for(const[r,s]of Object.entries(e.configurable))e.metadata=e.metadata??{},!r.startsWith("__")&&(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&!(r in e.metadata)&&(e.metadata[r]=s);return e}function zf(){return He.getRunnableConfig()}function ss(t){return t.split(Z).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(Ge)[0]).join(Z)}function Hf(t){const e=t.split(Z);for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join(Z)}const A=t=>BigInt(t),V=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),_l=A("0x9E3779B1"),vl=A("0x85EBCA77"),Wf=A("0xC2B2AE3D"),at=A("0x9E3779B185EBCA87"),Ct=A("0xC2B2AE3D27D4EB4F"),Sl=A("0x165667B19E3779F9"),ko=A("0x85EBCA77C2B2AE63"),Gf=A("0x27D4EB2F165667C5"),Kf=A("0x165667919E3779F9"),Jf=A("0x9FB21C651E98DF25"),qf=t=>{const e=t.length;if(e%2!==0)throw new Error("String should have an even number of characters");const n=e/2,r=new Uint8Array(n);let s=0,o=0;for(;o<n;){const i=t.slice(s,s+=2);r[o]=Number.parseInt(i,16),o+=1}return V(r)},Oe=qf("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Dt=(A(1)<<A(128))-A(1),$=(A(1)<<A(64))-A(1),xr=(A(1)<<A(32))-A(1),Be=64,Cl=Be/8,Yf=8,Wn=4;function on(t){if(!t)throw new Error("Assert failed")}function Xf(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Zf(t){let e=t;return e=(e&A(65535))<<A(16)|(e&A(4294901760))>>A(16),e=(e&A(16711935))<<A(8)|(e&A(4278255360))>>A(8),e}function Qf(t,e){return(t&xr)*(e&xr)&$}function ep(t,e){return(t<<e|t>>A(32)-e)&xr}function kl(t,e,n){for(let r=0;r<Cl;r+=1){const s=e.getBigUint64(r*8,!0),o=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Qf(o,o>>A(32))}return t}function ri(t,e,n,r){for(let s=0;s<r;s+=1)kl(t,V(e,s*Be),V(n,s*8));return t}function tp(t,e){for(let n=0;n<Cl;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=Bs(s,A(47)),s^=r,s*=_l,t[n]=s&$}return t}function Gn(t,e){return Tl(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(Yf,!0))}function si(t,e,n){let r=n;return r+=Gn(t.slice(0),V(e,0*Wn)),r+=Gn(t.slice(2),V(e,4*Wn)),r+=Gn(t.slice(4),V(e,8*Wn)),r+=Gn(t.slice(6),V(e,12*Wn)),je(r&$)}function np(t,e,n,r,s){let o=t;const i=Math.floor((n.byteLength-Be)/8),a=Be*i,l=Math.floor((e.byteLength-1)/a);for(let c=0;c<l;c+=1)o=ri(o,V(e,c*a),n,i),o=s(o,V(n,n.byteLength-Be));{const c=Math.floor((e.byteLength-1-a*l)/Be);o=ri(o,V(e,l*a),n,c),o=r(o,V(e,e.byteLength-Be),V(n,n.byteLength-Be-7))}return o}function rp(t,e){let n=new BigUint64Array([Wf,at,Ct,Sl,ko,vl,Gf,_l]);on(t.byteLength>128),n=np(n,t,e,kl,tp),on(n.length*8===64);{const r=si(n,V(e,11),A(t.byteLength)*at&$);return si(n,V(e,e.byteLength-Be-11),~(A(t.byteLength)*Ct)&$)<<A(64)|r}}function Tl(t,e){const n=t*e&Dt;return n&$^n>>A(64)}function oi(t,e,n){return Tl((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&$,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&$)}function hr(t,e,n,r,s){let o=t&$,i=t>>A(64)&$;return o+=oi(e,r,s),o^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),o&=$,i+=oi(n,V(r,16),s),i^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),i&=$,i<<A(64)|o}function je(t){let e=t;return e^=e>>A(37),e*=Kf,e&=$,e^=e>>A(32),e}function Mr(t){let e=t;return e^=e>>A(33),e*=Ct,e&=$,e^=e>>A(29),e*=Sl,e&=$,e^=e>>A(32),e}function sp(t,e,n){const r=t.byteLength;on(r>0&&r<=3);const s=A(t.getUint8(r-1))|A(r<<8)|A(t.getUint8(0)<<16)|A(t.getUint8(r>>1)<<24),o=(s^(A(e.getUint32(0,!0))^A(e.getUint32(4,!0)))+n)&$,i=(A(e.getUint32(8,!0))^A(e.getUint32(12,!0)))-n;return(Mr((ep(Zf(s),A(13))^i)&$)&$)<<A(64)|Mr(o)}function Bs(t,e){return t^t>>e}function op(t,e,n){const r=t.byteLength;on(r>=4&&r<=8);{const s=t.getUint32(0,!0),o=t.getUint32(r-4,!0);let i=((A(s)|A(o)<<A(32))^(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&$)*(at+(A(r)<<A(2)))&Dt;return i+=(i&$)<<A(65),i&=Dt,i^=i>>A(67),Bs(Bs(i&$,A(35))*Jf&$,A(28))|je(i>>A(64))<<A(64)}}function ip(t,e,n){const r=t.byteLength;on(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&$,o=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&$,i=t.getBigUint64(0,!0);let a=t.getBigUint64(r-8,!0),l=(i^a^s)*at;const c=(l&$)+(A(r-1)<<A(54));l=l&(Dt^$)|c,a^=o,l+=a+(a&xr)*(vl-A(1))<<A(64),l&=Dt,l^=Xf(l>>A(64));let u=(l&$)*Ct;return u+=(l>>A(64))*Ct<<A(64),u&=Dt,je(u&$)|je(u>>A(64))<<A(64)}}function ap(t,e){const n=t.byteLength;return on(n<=16),n>8?ip(t,Oe,e):n>=4?op(t,Oe,e):n>0?sp(t,Oe,e):Mr(e^Oe.getBigUint64(64,!0)^Oe.getBigUint64(72,!0))|Mr(e^Oe.getBigUint64(80,!0)^Oe.getBigUint64(88,!0))<<A(64)}function zs(t){return~t+A(1)&$}function lp(t,e,n){let r=A(t.byteLength)*at&$,s=A(t.byteLength-1)/A(32);for(;s>=0;){const a=Number(s);r=hr(r,V(t,16*a),V(t,t.byteLength-16*(a+1)),V(e,32*a),n),s-=A(1)}let o=r+(r>>A(64))&$;o=je(o);let i=(r&$)*at+(r>>A(64))*ko+(A(t.byteLength)-n&$)*Ct;return i&=$,i=zs(je(i)),o|i<<A(64)}function cp(t,e,n){let r=A(t.byteLength)*at&$;for(let i=32;i<160;i+=32)r=hr(r,V(t,i-32),V(t,i-16),V(e,i-32),n);r=je(r&$)|je(r>>A(64))<<A(64);for(let i=160;i<=t.byteLength;i+=32)r=hr(r,V(t,i-32),V(t,i-16),V(e,3+i-160),n);r=hr(r,V(t,t.byteLength-16),V(t,t.byteLength-32),V(e,103),zs(n));let s=r+(r>>A(64))&$;s=je(s);let o=(r&$)*at+(r>>A(64))*ko+(A(t.byteLength)-n&$)*Ct;return o&=$,o=zs(je(o)),s|o<<A(64)}function ft(t,e=A(0)){const n=new TextEncoder,r=V(typeof t=="string"?n.encode(t):t),s=r.byteLength,o=i=>i.toString(16).padStart(32,"0");return s<=16?o(ap(r,e)):s<=128?o(lp(r,Oe,e)):s<=240?o(cp(r,Oe,e)):o(rp(r,Oe))}function El(t){return/^[0-9a-f]{32}$/.test(t)}function xl(t){const e=He.getRunnableConfig();if(!e)throw new Error("Called interrupt() outside the context of a graph.");const n=e.configurable;if(!n)throw new Error("No configurable found in config");if(!n[J])throw new tr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=n[ot];r.interruptCounter+=1;const s=r.interruptCounter;if(r.resume.length>0&&s<r.resume.length)return n[st]?.([[me,r.resume]]),r.resume[s];if(r.nullResume!==void 0){if(r.resume.length!==s)throw new Error(`Resume length mismatch: ${r.resume.length} !== ${s}`);const i=r.consumeNullResume();return r.resume.push(i),n[st]?.([[me,r.resume]]),i}const o=n[Ne]?.split(Z);throw new Lt([{id:o?ft(o.join(Z)):void 0,value:t}])}var Et=class extends ae{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,n,r){return new Promise((s,o)=>{const i=vn(n,{callbacks:r?.getChild()});He.runWithConfig(i,async()=>{try{s(await this.func(e,i))}catch(a){o(a)}})})}async invoke(e,n){let r;const s=bl(n),o=$e(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,o):r=await He.runWithConfig(o,async()=>this.func(e,o)),ae.isRunnable(r)&&this.recurse?await He.runWithConfig(o,async()=>r.invoke(e,o)):r}};function*qe(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function Ze(t){const e=[];for await(const n of await t)e.push(n);return e}function yn(t){const e=[];for(const n of t)e.push(n);return e}function Mt(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function up(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const St={[Symbol.for("LG_PASSTHROUGH")]:!0};function Kn(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const os=Symbol("IS_WRITER");var de=class Hs extends Et{writes;constructor(e,n){const r=`ChannelWrite<${e.map(s=>ye(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:e,name:r,tags:n,func:async(s,o)=>this._write(s,o??{})}),this.writes=e}async _write(e,n){const r=this.writes.map(s=>is(s)&&Kn(s.value)?{mapper:s.mapper,value:e}:dr(s)&&Kn(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await Hs.doWrite(n,r),e}static async doWrite(e,n){for(const o of n){if(dr(o)){if(o.channel===Se)throw new B("Cannot write to the reserved channel TASKS");if(Kn(o.value))throw new B("PASSTHROUGH value must be replaced")}if(is(o)&&Kn(o.value))throw new B("PASSTHROUGH value must be replaced")}const r=[];for(const o of n)if(ye(o))r.push([Se,o]);else if(is(o)){const i=await o.mapper.invoke(o.value,e);i!=null&&i.length>0&&r.push(...i)}else if(dr(o)){const i=o.mapper!==void 0?await o.mapper.invoke(o.value,e):o.value;if(up(i)||o.skipNone&&i===void 0)continue;r.push([o.channel,i])}else throw new Error(`Invalid write entry: ${JSON.stringify(o)}`);const s=e.configurable?.[st];s(r)}static isWriter(e){return e instanceof Hs||os in e&&!!e[os]}static registerWriter(e){return Object.defineProperty(e,os,{value:!0})}};function dr(t){return t!==void 0&&typeof t.channel=="string"}function is(t){return t!==void 0&&!dr(t)&&ae.isRunnable(t.mapper)}var hp=class Ml extends Et{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,o)=>Ml.doRead(o,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=e,this.name=Array.isArray(e)?`ChannelRead<${e.join(",")}>`:`ChannelRead<${e}>`}static doRead(e,n,r,s){const o=e.configurable?.[vt];if(!o)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return s?s(o(n,r)):o(n,r)}};const At=new hh;var Nn=class wn extends Re{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=At;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){const{channels:n,triggers:r,mapper:s,writers:o,bound:i,kwargs:a,metadata:l,retryPolicy:c,cachePolicy:u,tags:d,subgraphs:h,ends:f}=e,m=[...e.config?.tags?e.config.tags:[],...d??[]];super({...e,bound:e.bound??At,config:{...e.config?e.config:{},tags:m}}),this.channels=n,this.triggers=r,this.mapper=s,this.writers=o??this.writers,this.bound=i??this.bound,this.kwargs=a??this.kwargs,this.metadata=l??this.metadata,this.tags=m,this.retryPolicy=c,this.cachePolicy=u,this.subgraphs=h,this.ends=f}getWriters(){const e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof de&&e[e.length-2]instanceof de;){const n=e.slice(-2),r=n[0].writes.concat(n[1].writes);e[e.length-2]=new de(r,n[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();if(!(this.bound===At&&e.length===0))return this.bound===At&&e.length===1?e[0]:this.bound===At?new it({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new it({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(e){if(!Array.isArray(e))throw new Error("channels must be a list");if(typeof this.channels!="object")throw new Error("all channels must be named when using .join()");return new wn({channels:{...this.channels,...Object.fromEntries(e.map(n=>[n,n]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(e){return de.isWriter(e)?new wn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,e],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===At?new wn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:en(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new wn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function dp(t){return"steps"in t&&Array.isArray(t.steps)}function To(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function Al(t){const e=[t];for(const n of e){if(To(n))return n;dp(n)&&e.push(...n.steps)}}function Ft(t,e,n=!0,r=!1){try{return t[e].get()}catch(s){if(s.name===ee.unminifiable_name){if(r)return s;if(n)return null}throw s}}function kt(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=Ft(t,s,!n)}catch(o){if(o.name===ee.unminifiable_name)continue}return r}else return Ft(t,e)}function*fp(t,e){if(t.graph===G.PARENT)throw new B("There is no parent graph.");if(t.goto){let n;Array.isArray(t.goto)?n=t.goto:n=[t.goto];for(const r of n)if(ye(r))yield[ke,Se,r];else if(typeof r=="string")yield[ke,`branch:to:${r}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof r}`)}if(t.resume)if(typeof t.resume=="object"&&Object.keys(t.resume).length&&Object.keys(t.resume).every(El))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(o=>o[0]===n&&o[1]===me).map(o=>o[2]).slice(0,1)??[];s.push(r),yield[n,me,s]}else yield[ke,me,t.resume];if(t.update){if(typeof t.update!="object"||!t.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(t.update))for(const[n,r]of t.update)yield[ke,n,r];else for(const[n,r]of Object.entries(t.update))yield[ke,n,r]}}function*Il(t,e){if(e!=null)if(Array.isArray(t)&&typeof e=="object"&&!Array.isArray(e))for(const n in e)t.includes(n)&&(yield[n,e[n]]);else{if(Array.isArray(t))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[t,e]}}function*as(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield kt(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield Ft(n,t))}function*pp(t,e,n){const r=e.filter(([a,l])=>(a.config===void 0||!a.config.tags?.includes(Y))&&l[0][0]!==pe&&l[0][0]!==D);if(!r.length)return;let s;r.some(([a])=>a.writes.some(([l,c])=>l===sn))?s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===sn).map(([l,c])=>[a.name,c])):Array.isArray(t)?s=r.flatMap(([a])=>{const{writes:l}=a,c={};for(const[u]of l)t.includes(u)&&(c[u]=(c[u]||0)+1);return Object.values(c).some(u=>u>1)?l.filter(([u])=>t.includes(u)).map(([u,d])=>[a.name,{[u]:d}]):[[a.name,Object.fromEntries(l.filter(([u])=>t.includes(u)))]]}):s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===t).map(([l,c])=>[a.name,c]));const o={};for(const[a,l]of s)a in o||(o[a]=[]),o[a].push(l);const i={};for(const a in o)if(o[a].length===1){const[l]=o[a];i[a]=l}else i[a]=o[a];n&&(i.__metadata__={cached:n}),yield i}function Eo(t){const e=typeof t[U];if(e==="number")return 0;if(e==="string")return"";for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=typeof t[n];if(r==="number")return 0;if(r==="string")return"";break}}function fr(t,e){if(Object.keys(t).length>0){const n=Eo(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function mp(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Ee(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function dt(t,e){const n=e?.parents??{};return Object.keys(n).length>0?Ee(t,{[Ce]:{...n,[t.configurable?.checkpoint_ns??""]:t.configurable?.checkpoint_id}}):t}function Ar(...t){const e=[...new Set(t.filter(Boolean))];if(e.length===0)return{signal:void 0,dispose:void 0};if(e.length===1)return{signal:e[0],dispose:void 0};const n=new AbortController,r=()=>{const o=e.find(i=>i.aborted)?.reason;n.abort(o),e.forEach(i=>i.removeEventListener("abort",r))};e.forEach(o=>o.addEventListener("abort",r,{once:!0}));const s=e.find(o=>o.aborted);return s&&n.abort(s.reason),{signal:n.signal,dispose:()=>{e.forEach(o=>o.removeEventListener("abort",r))}}}const gp=(t,e)=>{if(!(!t&&!e))return t?e?Array.isArray(t)&&Array.isArray(e)?[...t,...e]:Array.isArray(t)?[...t,e]:Array.isArray(e)?[t,...e]:[t,e]:t:e};var yp=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:t,name:e,input:n,retry:r,cache:s,callbacks:o}){this.func=t,this.name=e,this.input=n,this.retry=r,this.cache=s,this.callbacks=o}};function wp(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function bp(t,e){return new it({name:t,first:new Et({func:n=>e(...n),name:t,trace:!1,recurse:!1}),last:new de([{channel:sn,value:St}],[Y])})}const _p=t=>t!==void 0?t+1:1;function vp(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function Sp(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=Tf(e,t[n]));return e}function Jn(t,e,n){const r=Eo(t.channel_versions),s=t.versions_seen[D]??{};let o=!1;if((t.channel_versions[U]??r)>(s[U]??r))o=!0;else for(const a in t.channel_versions)if(Object.prototype.hasOwnProperty.call(t.channel_versions,a)&&t.channel_versions[a]>(s[a]??r)){o=!0;break}const i=n.some(a=>e==="*"?!a.config?.tags?.includes(Y):e.includes(a.name));return o&&i}function pr(t,e,n,r,s=!1){let o=new Set;if(Array.isArray(r))o=new Set(r.filter(a=>n.writes.some(([l,c])=>l===a)));else{for(const[a]of n.writes)if(a===r){o=new Set([a]);break}o=o||new Set}let i;if(s&&o.size>0){const a=Object.fromEntries(Object.entries(e).filter(([u,d])=>o.has(u))),l=pt(t,a,-1),c=kr(a,l);be(Cr(l),c,[n],void 0,void 0),i=kt({...e,...c},r)}else i=kt(e,r);return i}function ls(t,e,n){for(const[r,s]of n)if([_e,Se].includes(r)&&s!=null){if(!ye(s))throw new B(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in e))throw new B(`Invalid node name "${s.node}" in Send packet`)}t(n)}const Cp=new Set([Co,_e,me,D,sn,pe]);function be(t,e,n,r,s){n.sort((h,f)=>{const m=h.path?.slice(0,3)||[],p=f.path?.slice(0,3)||[];for(let C=0;C<Math.min(m.length,p.length);C+=1){if(m[C]<p[C])return-1;if(m[C]>p[C])return 1}return m.length-p.length});const o=n.some(h=>h.triggers.length>0),i=vo(e);for(const h of n){t.versions_seen[h.name]??={};for(const f of h.triggers)f in t.channel_versions&&(t.versions_seen[h.name][f]=t.channel_versions[f])}let a=Sp(t.channel_versions);const l=new Set(n.flatMap(h=>h.triggers).filter(h=>!Df.includes(h)));let c=!1;for(const h of l)h in i&&i[h].consume()&&r!==void 0&&(t.channel_versions[h]=r(a),c=!0);const u={};for(const h of n)for(const[f,m]of h.writes)Cp.has(f)||f in i&&(u[f]??=[],u[f].push(m));a!=null&&r!=null&&(a=c?r(a):a);const d=new Set;for(const[h,f]of Object.entries(u))if(h in i){const m=i[h];let p;try{p=m.update(f)}catch(C){if(C.name===B.unminifiable_name){const k=new B(`Invalid update for channel "${h}" with values ${JSON.stringify(f)}: ${C.message}`);throw k.lc_error_code=C.lc_error_code,k}else throw C}p&&r!==void 0&&(t.channel_versions[h]=r(a),m.isAvailable()&&d.add(h))}if(o)for(const h in i){if(!Object.prototype.hasOwnProperty.call(i,h))continue;const f=i[h];f.isAvailable()&&!d.has(h)&&f.update([])&&r!==void 0&&(t.channel_versions[h]=r(a),f.isAvailable()&&d.add(h))}if(o&&!vp(d,s))for(const h in i){if(!Object.prototype.hasOwnProperty.call(i,h))continue;const f=i[h];f.finish()&&r!==void 0&&(t.channel_versions[h]=r(a),f.isAvailable()&&d.add(h))}return d}function*kp(t,e,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){const r=new Set;for(const s of n.updatedChannels){const o=n.triggerToNodes[s];for(const i of o??[])r.add(i)}yield*[...r].sort();return}if(!(()=>{for(const r in t.channel_versions)if(t.channel_versions[r]!==null)return!1;return!0})())for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(yield r)}function jt(t,e,n,r,s,o,i){const a={},l=r[Se];if(l?.isAvailable()){const c=l.get().length;for(let u=0;u<c;u+=1){const d=Ws([_e,u],t,e,n,r,s,o,i);d!==void 0&&(a[d.id]=d)}}for(const c of kp(t,n,i)){const u=Ws([ur,c],t,e,n,r,s,o,i);u!==void 0&&(a[u.id]=u)}return a}function Ws(t,e,n,r,s,o,i,a){const{step:l,checkpointer:c,manager:u}=a,d=o.configurable??{},h=d.checkpoint_ns??"";if(t[0]===_e&&wp(t[t.length-1])){const f=t[t.length-1],m=bp(f.name,f.func),p=[_e],C=h===""?f.name:`${h}${Z}${f.name}`,k=Nt(JSON.stringify([C,l.toString(),f.name,_e,t[1],t[2]]),e.id),T=`${C}${Ge}${k}`,_=[...t.slice(0,3),!0],g={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:p,langgraph_path:_,langgraph_checkpoint_ns:T};if(i){const v=[];return{name:f.name,input:f.input,proc:m,writes:v,config:vn($e(o,{metadata:g,store:a.store??o.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[Cn]:k,[st]:M=>ls(w=>v.push(...w),r,M),[vt]:(M,w=!1)=>pr(e,s,{name:f.name,writes:v,triggers:p,path:_},M,w),[J]:c??d[J],[Ce]:{...d[Ce],[h]:e.id},[ot]:cs({pendingWrites:n??[],taskId:k,currentTaskInput:f.input,resumeMap:o.configurable?.[lr],namespaceHash:ft(T)}),[cr]:e.channel_values[rs],checkpoint_id:void 0,checkpoint_ns:T}}),triggers:p,retry_policy:f.retry,cache_key:f.cache?{key:ft((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[ns,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:k,path:_,writers:[]}}else return{id:k,name:f.name,interrupts:[],path:_}}else if(t[0]===_e){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!s[Se]?.isAvailable())return;const m=s[Se].get();if(f<0||f>=m.length)return;const p=Vs(m[f])&&!ye(m[f])?new he(m[f].node,m[f].args):m[f];if(!Vs(p)){console.warn(`Ignoring invalid packet ${JSON.stringify(p)} in pending sends.`);return}if(!(p.node in r)){console.warn(`Ignoring unknown node name ${p.node} in pending sends.`);return}const C=[_e],k=h===""?p.node:`${h}${Z}${p.node}`,T=Nt(JSON.stringify([k,l.toString(),p.node,_e,f.toString()]),e.id),_=`${k}${Ge}${T}`;let g={langgraph_step:l,langgraph_node:p.node,langgraph_triggers:C,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:_};if(i){const v=r[p.node],M=v.getNode();if(M!==void 0){v.metadata!==void 0&&(g={...g,...v.metadata});const w=[];return{name:p.node,input:p.args,proc:M,subgraphs:v.subgraphs,writes:w,config:vn($e(o,{metadata:g,tags:v.tags,store:a.store??o.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[Cn]:T,[st]:b=>ls(E=>w.push(...E),r,b),[vt]:(b,E=!1)=>pr(e,s,{name:p.node,writes:w,triggers:C,path:t},b,E),[J]:c??d[J],[Ce]:{...d[Ce],[h]:e.id},[ot]:cs({pendingWrites:n??[],taskId:T,currentTaskInput:p.args,resumeMap:o.configurable?.[lr],namespaceHash:ft(_)}),[cr]:e.channel_values[rs],checkpoint_id:void 0,checkpoint_ns:_}}),triggers:C,retry_policy:v.retryPolicy,cache_key:v.cachePolicy?{key:ft((v.cachePolicy.keyFunc??JSON.stringify)([p.args])),ns:[ns,v.name??"__dynamic__",p.node],ttl:v.cachePolicy.ttl}:void 0,id:T,path:t,writers:v.getWriters()}}}else return{id:T,name:p.node,interrupts:[],path:t}}else if(t[0]===ur){const f=t[1].toString(),m=r[f];if(m===void 0)return;if(n?.length){const T=h===""?f:`${h}${Z}${f}`,_=Nt(JSON.stringify([T,l.toString(),f,ur,f]),e.id);if(n.some(g=>g[0]===_&&g[1]!==pe))return}const p=Eo(e.channel_versions);if(p===void 0)return;const C=e.versions_seen[f]??{},k=m.triggers.find(T=>s[T].isAvailable()?(e.channel_versions[T]??p)>(C[T]??p):!1);if(k!==void 0){const T=Tp(m,s,i);if(T===void 0)return;const _=h===""?f:`${h}${Z}${f}`,g=Nt(JSON.stringify([_,l.toString(),f,ur,[k]]),e.id),v=`${_}${Ge}${g}`;let M={langgraph_step:l,langgraph_node:f,langgraph_triggers:[k],langgraph_path:t,langgraph_checkpoint_ns:v};if(i){const w=m.getNode();if(w!==void 0){m.metadata!==void 0&&(M={...M,...m.metadata});const b=[];return{name:f,input:T,proc:w,subgraphs:m.subgraphs,writes:b,config:vn($e(o,{metadata:M,tags:m.tags,store:a.store??o.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[Cn]:g,[st]:E=>ls(S=>{b.push(...S)},r,E),[vt]:(E,S=!1)=>pr(e,s,{name:f,writes:b,triggers:[k],path:t},E,S),[J]:c??d[J],[Ce]:{...d[Ce],[h]:e.id},[ot]:cs({pendingWrites:n??[],taskId:g,currentTaskInput:T,resumeMap:o.configurable?.[lr],namespaceHash:ft(v)}),[cr]:e.channel_values[rs],checkpoint_id:void 0,checkpoint_ns:v}}),triggers:[k],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:ft((m.cachePolicy.keyFunc??JSON.stringify)([T])),ns:[ns,m.name??"__dynamic__",f],ttl:m.cachePolicy.ttl}:void 0,id:g,path:t,writers:m.getWriters()}}}else return{id:g,name:f,interrupts:[],path:t}}}}function Tp(t,e,n){let r;if(typeof t.channels=="object"&&!Array.isArray(t.channels)){r={};for(const[s,o]of Object.entries(t.channels))if(t.triggers.includes(o))try{r[s]=Ft(e,o,!1)}catch(i){if(i.name===ee.unminifiable_name)return;throw i}else if(o in e)try{r[s]=Ft(e,o,!1)}catch(i){if(i.name===ee.unminifiable_name)continue;throw i}}else if(Array.isArray(t.channels)){let s=!1;for(const o of t.channels)try{r=Ft(e,o,!1),s=!0;break}catch(i){if(i.name===ee.unminifiable_name)continue;throw i}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);return n&&t.mapper!==void 0&&(r=t.mapper(r)),r}function Ep(t,e){if(typeof t.args!="object"||t.args===null)return t;const n={};for(const[r,s]of Object.entries(t.args)){const o=e[r];(!o||o.lc_graph_name!=="UntrackedValue")&&(n[r]=s)}return new he(t.node,n)}function cs({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const o=t.find(([a,l])=>a===ke&&l===me)?.[2],i={callCounter:0,interruptCounter:-1,resume:(()=>{const a=t.filter(([l,c])=>l===e&&c===me).flatMap(([l,c,u])=>u);if(r!=null&&s in r){const l=r[s];a.push(l)}return a})(),nullResume:o,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(i.nullResume)return delete i.nullResume,t.splice(t.findIndex(([a,l])=>a===ke&&l===me),1),o}};return i}const Rn={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},$n=(t,e)=>`${t.start}${e}${t.end}`;function*ii(t){for(const{id:e,name:n,input:r,config:s,triggers:o,writes:i}of t)s?.tags?.includes(Y)||(yield{id:e,name:n,input:r,triggers:o,interrupts:i.filter(([a,l])=>a===e&&l===D).map(([,a])=>a)})}function xp(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Pl(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const o=xp(e[s])?e[s].$writes:[e[s]];o.push(r),e[s]={$writes:o}}else e[s]=r}return e}function*Mp(t,e){for(const[{id:n,name:r,config:s},o]of t)s?.tags?.includes(Y)||(yield{id:n,name:r,result:Pl(o.filter(([i])=>Array.isArray(e)?e.includes(i):i===e)),interrupts:o.filter(i=>i[0]===D).map(i=>i[1])})}function*Ap(t,e,n,r,s,o,i,a){function l(d){const h={};return d.callbacks!=null&&(h.callbacks=d.callbacks),d.configurable!=null&&(h.configurable=d.configurable),d.maxConcurrency!=null&&(h.max_concurrency=d.maxConcurrency),d.metadata!=null&&(h.metadata=d.metadata),d.recursionLimit!=null&&(h.recursion_limit=d.recursionLimit),d.runId!=null&&(h.run_id=d.runId),d.runName!=null&&(h.run_name=d.runName),d.tags!=null&&(h.tags=d.tags),h}const c=t.configurable?.checkpoint_ns,u={};for(const d of s){if(!(d.subgraphs?.length?d.subgraphs:[d.proc]).find(Al))continue;let h=`${d.name}:${d.id}`;c&&(h=`${c}|${h}`),u[d.id]={configurable:{thread_id:t.configurable?.thread_id,checkpoint_ns:h}}}yield{config:l(t),values:kt(e,n),metadata:r,next:s.map(d=>d.name),tasks:Ol(s,o,u,a),parentConfig:i?l(i):void 0}}function Ol(t,e,n,r){return t.map(s=>{const o=e.find(([c,u])=>c===s.id&&u===pe)?.[2],i=e.filter(([c,u])=>c===s.id&&u===D).map(([,,c])=>c),a=(()=>{if(o||i.length||!e.length)return;const c=e.findIndex(([u,d])=>u===s.id&&d===sn);if(c>=0)return e[c][2];if(typeof r=="string")return e.find(([u,d])=>u===s.id&&d===r)?.[2];if(Array.isArray(r)){const u=e.filter(([d,h])=>d===s.id&&r.includes(h)).map(([,d,h])=>[d,h]);return u.length?Pl(u):void 0}})();if(o)return{id:s.id,name:s.name,path:s.path,error:o,interrupts:i,result:a};const l=n?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:i,...l!==void 0?{state:l}:{},result:a}})}function Ip(t,e,n){console.log([`${$n(Rn.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
39
- `,JSON.stringify(kt(e,n),null,2)].join(""))}function Nl(t,e){const n=e.length;console.log([`${$n(Rn.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
38
+ `);return await n?.handleLLMNewToken(r),{generations:[{message:new P(r),text:r}],llmOutput:{}}}},rf=class ol extends Un{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:e=50,responses:n=[],chunks:r=[],toolStyle:s="openai",thrownErrorString:o,...i}){super(i),this.sleep=e,this.responses=n,this.chunks=r,this.toolStyle=s,this.thrownErrorString=o}_llmType(){return"fake"}bindTools(e){const n=[...this.tools,...e],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:Me(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:Me(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:Me(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:Me(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new ol({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return o.tools=n,o.withConfig({tools:s})}async _generate(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=this.responses?.[0]?.content??e[0].content??"";return{generations:[{text:"",message:new P({content:s,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const i of this.chunks){const a=new Cs({message:new Qt({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});if(n.signal?.aborted)break;yield a,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:a})}return}const s=this.responses?.[0]??new P(typeof e[0].content=="string"?e[0].content:""),o=typeof s.content=="string"?s.content:"";for(const i of o){await new Promise(l=>setTimeout(l,this.sleep));const a=new Cs({message:new Qt({content:i}),text:i});if(n.signal?.aborted)break;yield a,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:a})}}},sf=class il extends Un{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(e){super(e);const{responses:n,sleep:r,emitCustomEvent:s,generationInfo:o}=e;this.responses=n,this.sleep=r,this.emitCustomEvent=s??this.emitCustomEvent,this.generationInfo=o}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(e,n,r){if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);if(this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0}),n?.stop?.length)return{generations:[this._formatGeneration(n.stop[0])]};{const s=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(s)],llmOutput:{}}}}_formatGeneration(e){return{message:new P(e),text:e}}async*_streamResponseChunks(e,n,r){const s=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0});const o=[...s];for(let i=0;i<o.length;i++){const a=o[i],l=i===o.length-1;if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);const c=this._createResponseChunk(a,l?this.generationInfo:void 0);if(n.signal?.aborted)break;yield c,r?.handleLLMNewToken(a)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,n){return new Cs({message:new Qt({content:e}),text:e,generationInfo:n})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(e){const n=[...this.tools,...e],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:Me(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:Me(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:Me(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:Me(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new il({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return o.tools=n,o.toolStyle=this.toolStyle,o.i=this.i,o.withConfig({tools:s})}withStructuredOutput(e,n){return yr.from(async r=>{const s=await this.invoke(r);if(s.tool_calls?.[0]?.args)return s.tool_calls[0].args;if(typeof s.content=="string")return JSON.parse(s.content);throw new Error("No structured output found")})}},of=class extends Ui{vectorSize;constructor(t){super(t??{}),this.vectorSize=t?.vectorSize??4}async embedDocuments(t){return Promise.all(t.map(e=>this.embedQuery(e)))}async embedQuery(t){let e=t;e=e.toLowerCase().replaceAll(/[^a-z ]/g,"");const n=e.length%this.vectorSize,r=n===0?0:this.vectorSize-n,s=e.length+r;e=e.padEnd(s," ");const o=e.length/this.vectorSize,i=[];for(let l=0;l<e.length;l+=o)i.push(e.slice(l,l+o));return i.map(l=>{let c=0;for(let d=0;d<l.length;d+=1)c+=l===" "?0:l.charCodeAt(d);return c%26/26})}},af=class extends Ui{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},lf=class extends Vi{response;thrownErrorString;constructor(t){super(t),this.response=t.response,this.thrownErrorString=t.thrownErrorString}_llmType(){return"fake"}async _call(t,e,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.response??t;return await n?.handleLLMNewToken(r),r}},cf=class extends Vi{sleep=50;responses;thrownErrorString;constructor(t){super(t),this.sleep=t.sleep??this.sleep,this.responses=t.responses,this.thrownErrorString=t.thrownErrorString}_llmType(){return"fake"}async _call(t){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const e=this.responses?.[0];return this.responses=this.responses?.slice(1),e??t}async*_streamResponseChunks(t,e,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.responses?.[0];this.responses=this.responses?.slice(1);for(const s of r??t)await new Promise(o=>setTimeout(o,this.sleep)),yield{text:s,generationInfo:{}},await n?.handleLLMNewToken(s)}},uf=class extends na{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async addUserMessage(t){this.messages.push(new se(t))}async addAIMessage(t){this.messages.push(new P(t))}async clear(){this.messages=[]}},hf=class extends ao{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},df=class extends to{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},ff=class extends Qu{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},pf=class extends lo{lc_namespace=["test","fake"];output=[new We({pageContent:"foo"}),new We({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},mf=class extends ae{lc_namespace=["tests","fake"];returnOptions;constructor(t){super(t),this.returnOptions=t.returnOptions}async invoke(t,e){return this.returnOptions?e??{}:{input:t}}},gf=class extends jr{name;description;schema;constructor(t){super(t),this.name=t.name,this.description=t.description,this.schema=t.schema}async _call(t,e){return JSON.stringify(t)}},yf=class extends to{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(t=>{this.runPromiseResolver=t})}async persistRun(t){this.runPromiseResolver(t)}async extract(){return this.runPromise}},wf=class al extends co{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??nl}async addDocuments(e){const n=e.map(({pageContent:r})=>r);return this.addVectors(await this.embeddings.embedDocuments(n),e)}async addVectors(e,n){const r=e.map((s,o)=>({content:n[o].pageContent,embedding:s,metadata:n[o].metadata}));this.memoryVectors=this.memoryVectors.concat(r)}async similaritySearchVectorWithScore(e,n,r){const s=l=>{if(!r)return!0;const c=new We({metadata:l.metadata,pageContent:l.content});return r(c)},o=this.memoryVectors.filter(s);return o.map((l,c)=>({similarity:this.similarity(e,l.embedding),index:c})).sort((l,c)=>l.similarity>c.similarity?-1:0).slice(0,n).map(l=>[new We({metadata:o[l.index].metadata,pageContent:o[l.index].content}),l.similarity])}static async fromTexts(e,n,r,s){const o=[];for(let i=0;i<e.length;i+=1){const a=Array.isArray(n)?n[i]:n,l=new We({pageContent:e[i],metadata:a});o.push(l)}return al.fromDocuments(o,r,s)}static async fromDocuments(e,n,r){const s=new this(n,r);return await s.addDocuments(e),s}static async fromExistingIndex(e,n){return new this(e,n)}},ll={};X(ll,{FakeChatMessageHistory:()=>uf,FakeChatModel:()=>nf,FakeEmbeddings:()=>af,FakeLLM:()=>lf,FakeListChatMessageHistory:()=>hf,FakeListChatModel:()=>sf,FakeRetriever:()=>pf,FakeRunnable:()=>mf,FakeSplitIntoListParser:()=>ff,FakeStreamingChatModel:()=>rf,FakeStreamingLLM:()=>cf,FakeTool:()=>gf,FakeTracer:()=>df,FakeVectorStore:()=>wf,SingleRunExtractor:()=>yf,SyntheticEmbeddings:()=>of});var cl={};X(cl,{agents:()=>Vh,caches:()=>uh,callbacks__base:()=>cu,callbacks__manager:()=>lu,callbacks__promises:()=>au,chat_history:()=>ta,document_loaders__base:()=>ua,document_loaders__langsmith:()=>da,documents:()=>pa,embeddings:()=>ph,errors:()=>iu,example_selectors:()=>wa,index:()=>zh,indexing:()=>Ta,language_models__base:()=>ch,language_models__chat_models:()=>lh,language_models__llms:()=>gh,language_models__profile:()=>od,load__serializable:()=>ou,memory:()=>ra,messages:()=>su,messages__tool:()=>ru,output_parsers:()=>ah,output_parsers__openai_functions:()=>xa,output_parsers__openai_tools:()=>mh,outputs:()=>nu,prompt_values:()=>ih,prompts:()=>Ua,retrievers:()=>la,retrievers__document_compressors:()=>Va,runnables:()=>oh,runnables__graph:()=>tu,singletons:()=>eu,stores:()=>oa,structured_query:()=>Ja,tools:()=>Wu,tracers__base:()=>Qc,tracers__console:()=>Zc,tracers__log_stream:()=>Xc,tracers__run_collector:()=>qa,tracers__tracer_langchain:()=>Yc,types__stream:()=>Ud,utils__async_caller:()=>qc,utils__chunk_array:()=>fh,utils__context:()=>Ya,utils__env:()=>Jc,utils__event_source_parse:()=>Za,utils__format:()=>Kd,utils__function_calling:()=>sh,utils__hash:()=>rh,utils__json_patch:()=>nh,utils__json_schema:()=>Kc,utils__math:()=>rl,utils__stream:()=>Gc,utils__testing:()=>ll,utils__tiktoken:()=>th,utils__types:()=>eh,vectorstores:()=>ca});const bf=50;function _f(t){const e={};for(let n=t;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(e,Reflect.get(n.prototype,"lc_aliases"));return Object.entries(e).reduce((n,[r,s])=>(n[s]=r,n),{})}async function ar(t){const{optionalImportsMap:e,optionalImportEntrypoints:n,importMap:r,secretsMap:s,secretsFromEnv:o,path:i,depth:a,maxDepth:l}=this,c=i.join(".");if(a>l)throw new Error(`Maximum recursion depth (${l}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof t!="object"||t==null)return t;if(Array.isArray(t))return Promise.all(t.map((h,f)=>ar.call({...this,path:[...i,`${f}`],depth:a+1},h)));const u=t;if(uu(u))return hu(u);if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="secret"){const h=u,[f]=h.id;if(f in s)return s[f];if(o){const m=du(f);if(m)return m}throw new Error(`Missing secret "${f}" at ${c}`)}if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="not_implemented"){const f=JSON.stringify(u);throw new Error(`Trying to load an object that doesn't implement serialization: ${c} -> ${f}`)}if("lc"in u&&"type"in u&&"id"in u&&"kwargs"in u&&u.lc===1&&u.type==="constructor"){const h=u,f=JSON.stringify(h),[m,...p]=h.id.slice().reverse(),C=p.reverse(),T={langchain_core:cl,langchain:r};let k=null;const _=[C.join("/")];C[0]==="langchain_community"&&_.push(["langchain",...C.slice(1)].join("/"));const g=_.find(b=>b in e);if(Uh.concat(n).includes(C.join("/"))||g)if(g!==void 0)k=await e[g];else throw new Error(`Missing key "${C.join("/")}" for ${c} in load(optionalImportsMap={})`);else{let b;if(C[0]==="langchain"||C[0]==="langchain_core")b=T[C[0]],C.shift();else throw new Error(`Invalid namespace: ${c} -> ${f}`);if(C.length===0)throw new Error(`Invalid namespace: ${c} -> ${f}`);let E;do{if(E=C.join("__"),E in b)break;C.pop()}while(C.length>0);E in b&&(k=b[E])}if(typeof k!="object"||k===null)throw new Error(`Invalid namespace: ${c} -> ${f}`);const v=k[m]??Object.values(k).find(b=>typeof b=="function"&&fu(b)===m);if(typeof v!="function")throw new Error(`Invalid identifer: ${c} -> ${f}`);const M=await ar.call({...this,path:[...i,"kwargs"],depth:a+1},h.kwargs),w=new v(pu(M,mu,_f(v)));return Object.defineProperty(w.constructor,"name",{value:m}),w}const d={};for(const[h,f]of Object.entries(u))d[h]=await ar.call({...this,path:[...i,h],depth:a+1},f);return d}async function vf(t,e){const n=JSON.parse(t),r={optionalImportsMap:{},optionalImportEntrypoints:[],secretsMap:{},secretsFromEnv:!1,importMap:{},path:["$"],depth:0,maxDepth:bf};return ar.call(r,n)}function Sf(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function $s(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>$s(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await $s(r);if(e.lc===2&&e.type==="undefined")return;if(e.lc===2&&e.type==="constructor"&&Array.isArray(e.id))try{const n=e.id[e.id.length-1];let r;switch(n){case"Set":r=Set;break;case"Map":r=Map;break;case"RegExp":r=RegExp;break;case"Error":r=Error;break;default:return e}return e.method?r[e.method](...e.args||[]):new r(...e.args||[])}catch{return e}else if(Sf(e))return vf(JSON.stringify(e));return e}}return t}function ts(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function Cf(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?ts(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?ts(RegExp,void 0,[t.source,t.flags]):t instanceof Error?ts(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t}var Tf=class{_dumps(t){return new TextEncoder().encode(Dh(t,(n,r)=>Cf(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return $s(e)}async loadsTyped(t,e){if(t==="bytes")return typeof e=="string"?new TextEncoder().encode(e):e;if(t==="json")return this._loads(typeof e=="string"?e:new TextDecoder().decode(e));throw new Error(`Unknown serialization type: ${t}`)}};function ul(t){if(typeof t!="object"||t===null)return t;const e=Array.isArray(t)?[]:{};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=ul(t[n]));return e}function hl(){return{v:4,id:ea(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function Cr(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:ul(t.versions_seen)}}function dl(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function kf(...t){return t.reduce((e,n,r)=>r===0?n:dl(e,n)>=0?e:n)}const Ef={[Nh]:-1,[nr]:-2,[Rh]:-3,[$h]:-4};var pn=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function xf(t){if(t.length===0)throw new pn("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new pn(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new pn(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new pn(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new pn(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var Mf=class{async get(t,e){return(await this.batch([{namespace:t,key:e}]))[0]}async search(t,e={}){const{filter:n,limit:r=10,offset:s=0,query:o}=e;return(await this.batch([{namespacePrefix:t,filter:n,limit:r,offset:s,query:o}]))[0]}async put(t,e,n,r){xf(t),await this.batch([{namespace:t,key:e,value:n,index:r}])}async delete(t,e){await this.batch([{namespace:t,key:e,value:null}])}async listNamespaces(t={}){const{prefix:e,suffix:n,maxDepth:r,limit:s=100,offset:o=0}=t,i=[];return e&&i.push({matchType:"prefix",path:e}),n&&i.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:i.length?i:void 0,maxDepth:r,limit:s,offset:o}]))[0]}start(){}stop(){}};const Af=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var If=class extends Mf{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=Af(t)}get isRunning(){return this.running}async batch(t){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(t,e){return this.enqueueOperation({namespace:t,key:e})}async search(t,e){const{filter:n,limit:r=10,offset:s=0,query:o}=e||{};return this.enqueueOperation({namespacePrefix:t,filter:n,limit:r,offset:s,query:o})}async put(t,e,n){return this.enqueueOperation({namespace:t,key:e,value:n})}async delete(t,e){return this.enqueueOperation({namespace:t,key:e,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(t){return new Promise((e,n)=>{const r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:t,resolve:e,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;const t=new Map(this.queue);this.queue.clear();try{const e=Array.from(t.values()).map(({operation:r})=>r),n=await this.store.batch(e);t.forEach(({resolve:r},s)=>{const o=Array.from(t.keys()).indexOf(s);r(n[o])})}catch(e){t.forEach(({reject:n})=>{n(e)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},Pf=class{serde=new Tf;constructor(t){this.serde=t||this.serde}};function fl(t){return t!=null&&t.lg_is_channel===!0}var ut=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===ee.unminifiable_name)return!1;throw t}}equals(t){return this===t}};const js=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function vo(t){if(t[js]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];fl(r)&&(e[n]=r)}return Object.assign(e,{[js]:!0}),e}function Tr(t,e){const n=vo(t),r={};for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=e.channel_values[s];r[s]=n[s].fromCheckpoint(o)}return Object.assign(r,{[js]:!0}),r}function pt(t,e,n,r){let s;if(e===void 0)s=t.channel_values;else{s={};for(const o in e)if(Object.prototype.hasOwnProperty.call(e,o))try{s[o]=e[o].checkpoint()}catch(i){if(i.name!==ee.unminifiable_name)throw i}}return{v:4,id:r?.id??ea(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}const Of=t=>t!=null&&t.lc_graph_name==="BinaryOperatorAggregate";var kr=class pl extends ut{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(e,n){super(),this.operator=e,this.initialValueFactory=n,this.value=n?.()}fromCheckpoint(e){const n=new pl(this.operator,this.initialValueFactory);return typeof e<"u"&&(n.value=e),n}update(e){let n=e;if(!n.length)return!1;this.value===void 0&&([this.value]=n,n=n.slice(1));for(const r of n)this.value!==void 0&&(this.value=this.operator(this.value,r));return!0}get(){if(this.value===void 0)throw new ee;return this.value}checkpoint(){if(this.value===void 0)throw new ee;return this.value}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:Of(e)?this.operator===e.operator:!1}},Ur=class ml extends ut{lc_graph_name="LastValue";value=[];constructor(e){super(),this.initialValueFactory=e,e&&(this.value=[e()])}fromCheckpoint(e){const n=new ml(this.initialValueFactory);return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new B("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new ee;return this.value[0]}checkpoint(){if(this.value.length===0)throw new ee;return this.value[0]}isAvailable(){return this.value.length!==0}},Nf=class gl extends ut{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new gl;if(typeof e<"u"){const[r,s]=e;n.value=[r],n.finished=s}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new ee;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},Ls=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}static isInstance(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}};const Ds=function(t){return t?Fs(t):new Ur};Ds.Root=t=>new Ls(t);function Fs(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new kr(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new kr(t.value,t.default):new Ur}const U="__start__",N="__end__",Ve="__input__",Rf="__copy__",pe="__error__",ns="__pregel_ns_writes",st="__pregel_send",So="__pregel_call",vt="__pregel_read",J="__pregel_checkpointer",Ye="__pregel_resuming",Cn="__pregel_task_id",Er="__pregel_stream",$f="__pregel_resume_value",lr="__pregel_resume_map",ot="__pregel_scratchpad",cr="__pregel_previous",yl="__pregel_durability",Us="checkpoint_id",Ne="checkpoint_ns",jf="__pregel_node_finished",Ce="checkpoint_map",ei="__pregel_abort_signals",D="__interrupt__",me="__resume__",Co="__no_writes__",sn="__return__",rs="__previous__",Y="langsmith:hidden",Lf="langsmith:nostream",ti="__self__",Se="__pregel_tasks",_e="__pregel_push",ur="__pregel_pull",Te="00000000-0000-0000-0000-000000000000",Df=[Y,Ve,D,me,pe,Co,st,vt,J,yl,Er,Ye,Cn,So,$f,ot,cr,Ce,Ne,Us],Z="|",Ge=":",ni=Symbol.for("langgraph.command");var Ff=class{[ni];constructor(t){this[ni]=t}};function Vs(t){const e=t;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var he=class{lg_name="Send";node;args;constructor(t,e){this.node=t,this.args=On(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function ye(t){return t instanceof he}function wl(t){return!t||typeof t!="object"||!(D in t)?!1:Array.isArray(t[D])}var G=class extends Ff{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(t){super(t),this.resume=t.resume,this.graph=t.graph,this.update=t.update,t.goto&&(this.goto=Array.isArray(t.goto)?On(t.goto):[On(t.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let t;return typeof this.goto=="string"?t=this.goto:ye(this.goto)?t=this.goto.toJSON():t=this.goto?.map(e=>typeof e=="string"?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:t}}};function q(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function On(t,e=new Map){if(t!=null&&typeof t=="object"){if(e.has(t))return e.get(t);let n;if(Array.isArray(t))n=[],e.set(t,n),t.forEach((r,s)=>{n[s]=On(r,e)});else if(q(t)&&!(t instanceof G))n=new G(t),e.set(t,n);else if(Vs(t)&&!(t instanceof he))n=new he(t.node,t.args),e.set(t,n);else if(q(t)||ye(t))n=t,e.set(t,n);else if("lc_serializable"in t&&t.lc_serializable)n=t,e.set(t,n);else{n={},e.set(t,n);for(const[r,s]of Object.entries(t))n[r]=On(s,e)}return n}return t}const Uf=["tags","metadata","callbacks","configurable"],Vf=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],Bf=25;function bl(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:Bf,configurable:{}},n=He.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(Uf.includes(r)){let o;Array.isArray(s)?o=[...s]:typeof s=="object"?r==="callbacks"&&"copy"in s&&typeof s.copy=="function"?o=s.copy():o={...s}:o=s,e[r]=o}else e[r]=s}for(const r of t)if(r!==void 0)for(const[s,o]of Object.entries(r))o!==void 0&&Vf.includes(s)&&(e[s]=o);for(const[r,s]of Object.entries(e.configurable))e.metadata=e.metadata??{},!r.startsWith("__")&&(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&!(r in e.metadata)&&(e.metadata[r]=s);return e}function zf(){return He.getRunnableConfig()}function ss(t){return t.split(Z).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(Ge)[0]).join(Z)}function Hf(t){const e=t.split(Z);for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join(Z)}const A=t=>BigInt(t),V=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),_l=A("0x9E3779B1"),vl=A("0x85EBCA77"),Wf=A("0xC2B2AE3D"),at=A("0x9E3779B185EBCA87"),Ct=A("0xC2B2AE3D27D4EB4F"),Sl=A("0x165667B19E3779F9"),To=A("0x85EBCA77C2B2AE63"),Gf=A("0x27D4EB2F165667C5"),Kf=A("0x165667919E3779F9"),Jf=A("0x9FB21C651E98DF25"),qf=t=>{const e=t.length;if(e%2!==0)throw new Error("String should have an even number of characters");const n=e/2,r=new Uint8Array(n);let s=0,o=0;for(;o<n;){const i=t.slice(s,s+=2);r[o]=Number.parseInt(i,16),o+=1}return V(r)},Oe=qf("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Dt=(A(1)<<A(128))-A(1),$=(A(1)<<A(64))-A(1),xr=(A(1)<<A(32))-A(1),Be=64,Cl=Be/8,Yf=8,Wn=4;function on(t){if(!t)throw new Error("Assert failed")}function Xf(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Zf(t){let e=t;return e=(e&A(65535))<<A(16)|(e&A(4294901760))>>A(16),e=(e&A(16711935))<<A(8)|(e&A(4278255360))>>A(8),e}function Qf(t,e){return(t&xr)*(e&xr)&$}function ep(t,e){return(t<<e|t>>A(32)-e)&xr}function Tl(t,e,n){for(let r=0;r<Cl;r+=1){const s=e.getBigUint64(r*8,!0),o=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Qf(o,o>>A(32))}return t}function ri(t,e,n,r){for(let s=0;s<r;s+=1)Tl(t,V(e,s*Be),V(n,s*8));return t}function tp(t,e){for(let n=0;n<Cl;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=Bs(s,A(47)),s^=r,s*=_l,t[n]=s&$}return t}function Gn(t,e){return kl(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(Yf,!0))}function si(t,e,n){let r=n;return r+=Gn(t.slice(0),V(e,0*Wn)),r+=Gn(t.slice(2),V(e,4*Wn)),r+=Gn(t.slice(4),V(e,8*Wn)),r+=Gn(t.slice(6),V(e,12*Wn)),je(r&$)}function np(t,e,n,r,s){let o=t;const i=Math.floor((n.byteLength-Be)/8),a=Be*i,l=Math.floor((e.byteLength-1)/a);for(let c=0;c<l;c+=1)o=ri(o,V(e,c*a),n,i),o=s(o,V(n,n.byteLength-Be));{const c=Math.floor((e.byteLength-1-a*l)/Be);o=ri(o,V(e,l*a),n,c),o=r(o,V(e,e.byteLength-Be),V(n,n.byteLength-Be-7))}return o}function rp(t,e){let n=new BigUint64Array([Wf,at,Ct,Sl,To,vl,Gf,_l]);on(t.byteLength>128),n=np(n,t,e,Tl,tp),on(n.length*8===64);{const r=si(n,V(e,11),A(t.byteLength)*at&$);return si(n,V(e,e.byteLength-Be-11),~(A(t.byteLength)*Ct)&$)<<A(64)|r}}function kl(t,e){const n=t*e&Dt;return n&$^n>>A(64)}function oi(t,e,n){return kl((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&$,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&$)}function hr(t,e,n,r,s){let o=t&$,i=t>>A(64)&$;return o+=oi(e,r,s),o^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),o&=$,i+=oi(n,V(r,16),s),i^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),i&=$,i<<A(64)|o}function je(t){let e=t;return e^=e>>A(37),e*=Kf,e&=$,e^=e>>A(32),e}function Mr(t){let e=t;return e^=e>>A(33),e*=Ct,e&=$,e^=e>>A(29),e*=Sl,e&=$,e^=e>>A(32),e}function sp(t,e,n){const r=t.byteLength;on(r>0&&r<=3);const s=A(t.getUint8(r-1))|A(r<<8)|A(t.getUint8(0)<<16)|A(t.getUint8(r>>1)<<24),o=(s^(A(e.getUint32(0,!0))^A(e.getUint32(4,!0)))+n)&$,i=(A(e.getUint32(8,!0))^A(e.getUint32(12,!0)))-n;return(Mr((ep(Zf(s),A(13))^i)&$)&$)<<A(64)|Mr(o)}function Bs(t,e){return t^t>>e}function op(t,e,n){const r=t.byteLength;on(r>=4&&r<=8);{const s=t.getUint32(0,!0),o=t.getUint32(r-4,!0);let i=((A(s)|A(o)<<A(32))^(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&$)*(at+(A(r)<<A(2)))&Dt;return i+=(i&$)<<A(65),i&=Dt,i^=i>>A(67),Bs(Bs(i&$,A(35))*Jf&$,A(28))|je(i>>A(64))<<A(64)}}function ip(t,e,n){const r=t.byteLength;on(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&$,o=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&$,i=t.getBigUint64(0,!0);let a=t.getBigUint64(r-8,!0),l=(i^a^s)*at;const c=(l&$)+(A(r-1)<<A(54));l=l&(Dt^$)|c,a^=o,l+=a+(a&xr)*(vl-A(1))<<A(64),l&=Dt,l^=Xf(l>>A(64));let u=(l&$)*Ct;return u+=(l>>A(64))*Ct<<A(64),u&=Dt,je(u&$)|je(u>>A(64))<<A(64)}}function ap(t,e){const n=t.byteLength;return on(n<=16),n>8?ip(t,Oe,e):n>=4?op(t,Oe,e):n>0?sp(t,Oe,e):Mr(e^Oe.getBigUint64(64,!0)^Oe.getBigUint64(72,!0))|Mr(e^Oe.getBigUint64(80,!0)^Oe.getBigUint64(88,!0))<<A(64)}function zs(t){return~t+A(1)&$}function lp(t,e,n){let r=A(t.byteLength)*at&$,s=A(t.byteLength-1)/A(32);for(;s>=0;){const a=Number(s);r=hr(r,V(t,16*a),V(t,t.byteLength-16*(a+1)),V(e,32*a),n),s-=A(1)}let o=r+(r>>A(64))&$;o=je(o);let i=(r&$)*at+(r>>A(64))*To+(A(t.byteLength)-n&$)*Ct;return i&=$,i=zs(je(i)),o|i<<A(64)}function cp(t,e,n){let r=A(t.byteLength)*at&$;for(let i=32;i<160;i+=32)r=hr(r,V(t,i-32),V(t,i-16),V(e,i-32),n);r=je(r&$)|je(r>>A(64))<<A(64);for(let i=160;i<=t.byteLength;i+=32)r=hr(r,V(t,i-32),V(t,i-16),V(e,3+i-160),n);r=hr(r,V(t,t.byteLength-16),V(t,t.byteLength-32),V(e,103),zs(n));let s=r+(r>>A(64))&$;s=je(s);let o=(r&$)*at+(r>>A(64))*To+(A(t.byteLength)-n&$)*Ct;return o&=$,o=zs(je(o)),s|o<<A(64)}function ft(t,e=A(0)){const n=new TextEncoder,r=V(typeof t=="string"?n.encode(t):t),s=r.byteLength,o=i=>i.toString(16).padStart(32,"0");return s<=16?o(ap(r,e)):s<=128?o(lp(r,Oe,e)):s<=240?o(cp(r,Oe,e)):o(rp(r,Oe))}function El(t){return/^[0-9a-f]{32}$/.test(t)}function xl(t){const e=He.getRunnableConfig();if(!e)throw new Error("Called interrupt() outside the context of a graph.");const n=e.configurable;if(!n)throw new Error("No configurable found in config");if(!n[J])throw new tr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=n[ot];r.interruptCounter+=1;const s=r.interruptCounter;if(r.resume.length>0&&s<r.resume.length)return n[st]?.([[me,r.resume]]),r.resume[s];if(r.nullResume!==void 0){if(r.resume.length!==s)throw new Error(`Resume length mismatch: ${r.resume.length} !== ${s}`);const i=r.consumeNullResume();return r.resume.push(i),n[st]?.([[me,r.resume]]),i}const o=n[Ne]?.split(Z);throw new Lt([{id:o?ft(o.join(Z)):void 0,value:t}])}var Et=class extends ae{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,n,r){return new Promise((s,o)=>{const i=vn(n,{callbacks:r?.getChild()});He.runWithConfig(i,async()=>{try{s(await this.func(e,i))}catch(a){o(a)}})})}async invoke(e,n){let r;const s=bl(n),o=$e(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,o):r=await He.runWithConfig(o,async()=>this.func(e,o)),ae.isRunnable(r)&&this.recurse?await He.runWithConfig(o,async()=>r.invoke(e,o)):r}};function*qe(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function Ze(t){const e=[];for await(const n of await t)e.push(n);return e}function yn(t){const e=[];for(const n of t)e.push(n);return e}function Mt(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function up(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const St={[Symbol.for("LG_PASSTHROUGH")]:!0};function Kn(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const os=Symbol("IS_WRITER");var de=class Hs extends Et{writes;constructor(e,n){const r=`ChannelWrite<${e.map(s=>ye(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:e,name:r,tags:n,func:async(s,o)=>this._write(s,o??{})}),this.writes=e}async _write(e,n){const r=this.writes.map(s=>is(s)&&Kn(s.value)?{mapper:s.mapper,value:e}:dr(s)&&Kn(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await Hs.doWrite(n,r),e}static async doWrite(e,n){for(const o of n){if(dr(o)){if(o.channel===Se)throw new B("Cannot write to the reserved channel TASKS");if(Kn(o.value))throw new B("PASSTHROUGH value must be replaced")}if(is(o)&&Kn(o.value))throw new B("PASSTHROUGH value must be replaced")}const r=[];for(const o of n)if(ye(o))r.push([Se,o]);else if(is(o)){const i=await o.mapper.invoke(o.value,e);i!=null&&i.length>0&&r.push(...i)}else if(dr(o)){const i=o.mapper!==void 0?await o.mapper.invoke(o.value,e):o.value;if(up(i)||o.skipNone&&i===void 0)continue;r.push([o.channel,i])}else throw new Error(`Invalid write entry: ${JSON.stringify(o)}`);const s=e.configurable?.[st];s(r)}static isWriter(e){return e instanceof Hs||os in e&&!!e[os]}static registerWriter(e){return Object.defineProperty(e,os,{value:!0})}};function dr(t){return t!==void 0&&typeof t.channel=="string"}function is(t){return t!==void 0&&!dr(t)&&ae.isRunnable(t.mapper)}var hp=class Ml extends Et{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,o)=>Ml.doRead(o,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=e,this.name=Array.isArray(e)?`ChannelRead<${e.join(",")}>`:`ChannelRead<${e}>`}static doRead(e,n,r,s){const o=e.configurable?.[vt];if(!o)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return s?s(o(n,r)):o(n,r)}};const At=new hh;var Nn=class wn extends Re{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=At;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){const{channels:n,triggers:r,mapper:s,writers:o,bound:i,kwargs:a,metadata:l,retryPolicy:c,cachePolicy:u,tags:d,subgraphs:h,ends:f}=e,m=[...e.config?.tags?e.config.tags:[],...d??[]];super({...e,bound:e.bound??At,config:{...e.config?e.config:{},tags:m}}),this.channels=n,this.triggers=r,this.mapper=s,this.writers=o??this.writers,this.bound=i??this.bound,this.kwargs=a??this.kwargs,this.metadata=l??this.metadata,this.tags=m,this.retryPolicy=c,this.cachePolicy=u,this.subgraphs=h,this.ends=f}getWriters(){const e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof de&&e[e.length-2]instanceof de;){const n=e.slice(-2),r=n[0].writes.concat(n[1].writes);e[e.length-2]=new de(r,n[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();if(!(this.bound===At&&e.length===0))return this.bound===At&&e.length===1?e[0]:this.bound===At?new it({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new it({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(e){if(!Array.isArray(e))throw new Error("channels must be a list");if(typeof this.channels!="object")throw new Error("all channels must be named when using .join()");return new wn({channels:{...this.channels,...Object.fromEntries(e.map(n=>[n,n]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(e){return de.isWriter(e)?new wn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,e],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===At?new wn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:en(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new wn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function dp(t){return"steps"in t&&Array.isArray(t.steps)}function ko(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function Al(t){const e=[t];for(const n of e){if(ko(n))return n;dp(n)&&e.push(...n.steps)}}function Ft(t,e,n=!0,r=!1){try{return t[e].get()}catch(s){if(s.name===ee.unminifiable_name){if(r)return s;if(n)return null}throw s}}function Tt(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=Ft(t,s,!n)}catch(o){if(o.name===ee.unminifiable_name)continue}return r}else return Ft(t,e)}function*fp(t,e){if(t.graph===G.PARENT)throw new B("There is no parent graph.");if(t.goto){let n;Array.isArray(t.goto)?n=t.goto:n=[t.goto];for(const r of n)if(ye(r))yield[Te,Se,r];else if(typeof r=="string")yield[Te,`branch:to:${r}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof r}`)}if(t.resume)if(typeof t.resume=="object"&&Object.keys(t.resume).length&&Object.keys(t.resume).every(El))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(o=>o[0]===n&&o[1]===me).map(o=>o[2]).slice(0,1)??[];s.push(r),yield[n,me,s]}else yield[Te,me,t.resume];if(t.update){if(typeof t.update!="object"||!t.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(t.update))for(const[n,r]of t.update)yield[Te,n,r];else for(const[n,r]of Object.entries(t.update))yield[Te,n,r]}}function*Il(t,e){if(e!=null)if(Array.isArray(t)&&typeof e=="object"&&!Array.isArray(e))for(const n in e)t.includes(n)&&(yield[n,e[n]]);else{if(Array.isArray(t))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[t,e]}}function*as(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield Tt(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield Ft(n,t))}function*pp(t,e,n){const r=e.filter(([a,l])=>(a.config===void 0||!a.config.tags?.includes(Y))&&l[0][0]!==pe&&l[0][0]!==D);if(!r.length)return;let s;r.some(([a])=>a.writes.some(([l,c])=>l===sn))?s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===sn).map(([l,c])=>[a.name,c])):Array.isArray(t)?s=r.flatMap(([a])=>{const{writes:l}=a,c={};for(const[u]of l)t.includes(u)&&(c[u]=(c[u]||0)+1);return Object.values(c).some(u=>u>1)?l.filter(([u])=>t.includes(u)).map(([u,d])=>[a.name,{[u]:d}]):[[a.name,Object.fromEntries(l.filter(([u])=>t.includes(u)))]]}):s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===t).map(([l,c])=>[a.name,c]));const o={};for(const[a,l]of s)a in o||(o[a]=[]),o[a].push(l);const i={};for(const a in o)if(o[a].length===1){const[l]=o[a];i[a]=l}else i[a]=o[a];n&&(i.__metadata__={cached:n}),yield i}function Eo(t){const e=typeof t[U];if(e==="number")return 0;if(e==="string")return"";for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=typeof t[n];if(r==="number")return 0;if(r==="string")return"";break}}function fr(t,e){if(Object.keys(t).length>0){const n=Eo(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function mp(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Ee(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function dt(t,e){const n=e?.parents??{};return Object.keys(n).length>0?Ee(t,{[Ce]:{...n,[t.configurable?.checkpoint_ns??""]:t.configurable?.checkpoint_id}}):t}function Ar(...t){const e=[...new Set(t.filter(Boolean))];if(e.length===0)return{signal:void 0,dispose:void 0};if(e.length===1)return{signal:e[0],dispose:void 0};const n=new AbortController,r=()=>{const o=e.find(i=>i.aborted)?.reason;n.abort(o),e.forEach(i=>i.removeEventListener("abort",r))};e.forEach(o=>o.addEventListener("abort",r,{once:!0}));const s=e.find(o=>o.aborted);return s&&n.abort(s.reason),{signal:n.signal,dispose:()=>{e.forEach(o=>o.removeEventListener("abort",r))}}}const gp=(t,e)=>{if(!(!t&&!e))return t?e?Array.isArray(t)&&Array.isArray(e)?[...t,...e]:Array.isArray(t)?[...t,e]:Array.isArray(e)?[t,...e]:[t,e]:t:e};var yp=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:t,name:e,input:n,retry:r,cache:s,callbacks:o}){this.func=t,this.name=e,this.input=n,this.retry=r,this.cache=s,this.callbacks=o}};function wp(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function bp(t,e){return new it({name:t,first:new Et({func:n=>e(...n),name:t,trace:!1,recurse:!1}),last:new de([{channel:sn,value:St}],[Y])})}const _p=t=>t!==void 0?t+1:1;function vp(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function Sp(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=kf(e,t[n]));return e}function Jn(t,e,n){const r=Eo(t.channel_versions),s=t.versions_seen[D]??{};let o=!1;if((t.channel_versions[U]??r)>(s[U]??r))o=!0;else for(const a in t.channel_versions)if(Object.prototype.hasOwnProperty.call(t.channel_versions,a)&&t.channel_versions[a]>(s[a]??r)){o=!0;break}const i=n.some(a=>e==="*"?!a.config?.tags?.includes(Y):e.includes(a.name));return o&&i}function pr(t,e,n,r,s=!1){let o=new Set;if(Array.isArray(r))o=new Set(r.filter(a=>n.writes.some(([l,c])=>l===a)));else{for(const[a]of n.writes)if(a===r){o=new Set([a]);break}o=o||new Set}let i;if(s&&o.size>0){const a=Object.fromEntries(Object.entries(e).filter(([u,d])=>o.has(u))),l=pt(t,a,-1),c=Tr(a,l);be(Cr(l),c,[n],void 0,void 0),i=Tt({...e,...c},r)}else i=Tt(e,r);return i}function ls(t,e,n){for(const[r,s]of n)if([_e,Se].includes(r)&&s!=null){if(!ye(s))throw new B(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in e))throw new B(`Invalid node name "${s.node}" in Send packet`)}t(n)}const Cp=new Set([Co,_e,me,D,sn,pe]);function be(t,e,n,r,s){n.sort((h,f)=>{const m=h.path?.slice(0,3)||[],p=f.path?.slice(0,3)||[];for(let C=0;C<Math.min(m.length,p.length);C+=1){if(m[C]<p[C])return-1;if(m[C]>p[C])return 1}return m.length-p.length});const o=n.some(h=>h.triggers.length>0),i=vo(e);for(const h of n){t.versions_seen[h.name]??={};for(const f of h.triggers)f in t.channel_versions&&(t.versions_seen[h.name][f]=t.channel_versions[f])}let a=Sp(t.channel_versions);const l=new Set(n.flatMap(h=>h.triggers).filter(h=>!Df.includes(h)));let c=!1;for(const h of l)h in i&&i[h].consume()&&r!==void 0&&(t.channel_versions[h]=r(a),c=!0);const u={};for(const h of n)for(const[f,m]of h.writes)Cp.has(f)||f in i&&(u[f]??=[],u[f].push(m));a!=null&&r!=null&&(a=c?r(a):a);const d=new Set;for(const[h,f]of Object.entries(u))if(h in i){const m=i[h];let p;try{p=m.update(f)}catch(C){if(C.name===B.unminifiable_name){const T=new B(`Invalid update for channel "${h}" with values ${JSON.stringify(f)}: ${C.message}`);throw T.lc_error_code=C.lc_error_code,T}else throw C}p&&r!==void 0&&(t.channel_versions[h]=r(a),m.isAvailable()&&d.add(h))}if(o)for(const h in i){if(!Object.prototype.hasOwnProperty.call(i,h))continue;const f=i[h];f.isAvailable()&&!d.has(h)&&f.update([])&&r!==void 0&&(t.channel_versions[h]=r(a),f.isAvailable()&&d.add(h))}if(o&&!vp(d,s))for(const h in i){if(!Object.prototype.hasOwnProperty.call(i,h))continue;const f=i[h];f.finish()&&r!==void 0&&(t.channel_versions[h]=r(a),f.isAvailable()&&d.add(h))}return d}function*Tp(t,e,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){const r=new Set;for(const s of n.updatedChannels){const o=n.triggerToNodes[s];for(const i of o??[])r.add(i)}yield*[...r].sort();return}if(!(()=>{for(const r in t.channel_versions)if(t.channel_versions[r]!==null)return!1;return!0})())for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(yield r)}function jt(t,e,n,r,s,o,i){const a={},l=r[Se];if(l?.isAvailable()){const c=l.get().length;for(let u=0;u<c;u+=1){const d=Ws([_e,u],t,e,n,r,s,o,i);d!==void 0&&(a[d.id]=d)}}for(const c of Tp(t,n,i)){const u=Ws([ur,c],t,e,n,r,s,o,i);u!==void 0&&(a[u.id]=u)}return a}function Ws(t,e,n,r,s,o,i,a){const{step:l,checkpointer:c,manager:u}=a,d=o.configurable??{},h=d.checkpoint_ns??"";if(t[0]===_e&&wp(t[t.length-1])){const f=t[t.length-1],m=bp(f.name,f.func),p=[_e],C=h===""?f.name:`${h}${Z}${f.name}`,T=Nt(JSON.stringify([C,l.toString(),f.name,_e,t[1],t[2]]),e.id),k=`${C}${Ge}${T}`,_=[...t.slice(0,3),!0],g={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:p,langgraph_path:_,langgraph_checkpoint_ns:k};if(i){const v=[];return{name:f.name,input:f.input,proc:m,writes:v,config:vn($e(o,{metadata:g,store:a.store??o.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[Cn]:T,[st]:M=>ls(w=>v.push(...w),r,M),[vt]:(M,w=!1)=>pr(e,s,{name:f.name,writes:v,triggers:p,path:_},M,w),[J]:c??d[J],[Ce]:{...d[Ce],[h]:e.id},[ot]:cs({pendingWrites:n??[],taskId:T,currentTaskInput:f.input,resumeMap:o.configurable?.[lr],namespaceHash:ft(k)}),[cr]:e.channel_values[rs],checkpoint_id:void 0,checkpoint_ns:k}}),triggers:p,retry_policy:f.retry,cache_key:f.cache?{key:ft((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[ns,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:T,path:_,writers:[]}}else return{id:T,name:f.name,interrupts:[],path:_}}else if(t[0]===_e){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!s[Se]?.isAvailable())return;const m=s[Se].get();if(f<0||f>=m.length)return;const p=Vs(m[f])&&!ye(m[f])?new he(m[f].node,m[f].args):m[f];if(!Vs(p)){console.warn(`Ignoring invalid packet ${JSON.stringify(p)} in pending sends.`);return}if(!(p.node in r)){console.warn(`Ignoring unknown node name ${p.node} in pending sends.`);return}const C=[_e],T=h===""?p.node:`${h}${Z}${p.node}`,k=Nt(JSON.stringify([T,l.toString(),p.node,_e,f.toString()]),e.id),_=`${T}${Ge}${k}`;let g={langgraph_step:l,langgraph_node:p.node,langgraph_triggers:C,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:_};if(i){const v=r[p.node],M=v.getNode();if(M!==void 0){v.metadata!==void 0&&(g={...g,...v.metadata});const w=[];return{name:p.node,input:p.args,proc:M,subgraphs:v.subgraphs,writes:w,config:vn($e(o,{metadata:g,tags:v.tags,store:a.store??o.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[Cn]:k,[st]:b=>ls(E=>w.push(...E),r,b),[vt]:(b,E=!1)=>pr(e,s,{name:p.node,writes:w,triggers:C,path:t},b,E),[J]:c??d[J],[Ce]:{...d[Ce],[h]:e.id},[ot]:cs({pendingWrites:n??[],taskId:k,currentTaskInput:p.args,resumeMap:o.configurable?.[lr],namespaceHash:ft(_)}),[cr]:e.channel_values[rs],checkpoint_id:void 0,checkpoint_ns:_}}),triggers:C,retry_policy:v.retryPolicy,cache_key:v.cachePolicy?{key:ft((v.cachePolicy.keyFunc??JSON.stringify)([p.args])),ns:[ns,v.name??"__dynamic__",p.node],ttl:v.cachePolicy.ttl}:void 0,id:k,path:t,writers:v.getWriters()}}}else return{id:k,name:p.node,interrupts:[],path:t}}else if(t[0]===ur){const f=t[1].toString(),m=r[f];if(m===void 0)return;if(n?.length){const k=h===""?f:`${h}${Z}${f}`,_=Nt(JSON.stringify([k,l.toString(),f,ur,f]),e.id);if(n.some(g=>g[0]===_&&g[1]!==pe))return}const p=Eo(e.channel_versions);if(p===void 0)return;const C=e.versions_seen[f]??{},T=m.triggers.find(k=>s[k].isAvailable()?(e.channel_versions[k]??p)>(C[k]??p):!1);if(T!==void 0){const k=kp(m,s,i);if(k===void 0)return;const _=h===""?f:`${h}${Z}${f}`,g=Nt(JSON.stringify([_,l.toString(),f,ur,[T]]),e.id),v=`${_}${Ge}${g}`;let M={langgraph_step:l,langgraph_node:f,langgraph_triggers:[T],langgraph_path:t,langgraph_checkpoint_ns:v};if(i){const w=m.getNode();if(w!==void 0){m.metadata!==void 0&&(M={...M,...m.metadata});const b=[];return{name:f,input:k,proc:w,subgraphs:m.subgraphs,writes:b,config:vn($e(o,{metadata:M,tags:m.tags,store:a.store??o.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[Cn]:g,[st]:E=>ls(S=>{b.push(...S)},r,E),[vt]:(E,S=!1)=>pr(e,s,{name:f,writes:b,triggers:[T],path:t},E,S),[J]:c??d[J],[Ce]:{...d[Ce],[h]:e.id},[ot]:cs({pendingWrites:n??[],taskId:g,currentTaskInput:k,resumeMap:o.configurable?.[lr],namespaceHash:ft(v)}),[cr]:e.channel_values[rs],checkpoint_id:void 0,checkpoint_ns:v}}),triggers:[T],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:ft((m.cachePolicy.keyFunc??JSON.stringify)([k])),ns:[ns,m.name??"__dynamic__",f],ttl:m.cachePolicy.ttl}:void 0,id:g,path:t,writers:m.getWriters()}}}else return{id:g,name:f,interrupts:[],path:t}}}}function kp(t,e,n){let r;if(typeof t.channels=="object"&&!Array.isArray(t.channels)){r={};for(const[s,o]of Object.entries(t.channels))if(t.triggers.includes(o))try{r[s]=Ft(e,o,!1)}catch(i){if(i.name===ee.unminifiable_name)return;throw i}else if(o in e)try{r[s]=Ft(e,o,!1)}catch(i){if(i.name===ee.unminifiable_name)continue;throw i}}else if(Array.isArray(t.channels)){let s=!1;for(const o of t.channels)try{r=Ft(e,o,!1),s=!0;break}catch(i){if(i.name===ee.unminifiable_name)continue;throw i}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);return n&&t.mapper!==void 0&&(r=t.mapper(r)),r}function Ep(t,e){if(typeof t.args!="object"||t.args===null)return t;const n={};for(const[r,s]of Object.entries(t.args)){const o=e[r];(!o||o.lc_graph_name!=="UntrackedValue")&&(n[r]=s)}return new he(t.node,n)}function cs({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const o=t.find(([a,l])=>a===Te&&l===me)?.[2],i={callCounter:0,interruptCounter:-1,resume:(()=>{const a=t.filter(([l,c])=>l===e&&c===me).flatMap(([l,c,u])=>u);if(r!=null&&s in r){const l=r[s];a.push(l)}return a})(),nullResume:o,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(i.nullResume)return delete i.nullResume,t.splice(t.findIndex(([a,l])=>a===Te&&l===me),1),o}};return i}const Rn={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},$n=(t,e)=>`${t.start}${e}${t.end}`;function*ii(t){for(const{id:e,name:n,input:r,config:s,triggers:o,writes:i}of t)s?.tags?.includes(Y)||(yield{id:e,name:n,input:r,triggers:o,interrupts:i.filter(([a,l])=>a===e&&l===D).map(([,a])=>a)})}function xp(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Pl(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const o=xp(e[s])?e[s].$writes:[e[s]];o.push(r),e[s]={$writes:o}}else e[s]=r}return e}function*Mp(t,e){for(const[{id:n,name:r,config:s},o]of t)s?.tags?.includes(Y)||(yield{id:n,name:r,result:Pl(o.filter(([i])=>Array.isArray(e)?e.includes(i):i===e)),interrupts:o.filter(i=>i[0]===D).map(i=>i[1])})}function*Ap(t,e,n,r,s,o,i,a){function l(d){const h={};return d.callbacks!=null&&(h.callbacks=d.callbacks),d.configurable!=null&&(h.configurable=d.configurable),d.maxConcurrency!=null&&(h.max_concurrency=d.maxConcurrency),d.metadata!=null&&(h.metadata=d.metadata),d.recursionLimit!=null&&(h.recursion_limit=d.recursionLimit),d.runId!=null&&(h.run_id=d.runId),d.runName!=null&&(h.run_name=d.runName),d.tags!=null&&(h.tags=d.tags),h}const c=t.configurable?.checkpoint_ns,u={};for(const d of s){if(!(d.subgraphs?.length?d.subgraphs:[d.proc]).find(Al))continue;let h=`${d.name}:${d.id}`;c&&(h=`${c}|${h}`),u[d.id]={configurable:{thread_id:t.configurable?.thread_id,checkpoint_ns:h}}}yield{config:l(t),values:Tt(e,n),metadata:r,next:s.map(d=>d.name),tasks:Ol(s,o,u,a),parentConfig:i?l(i):void 0}}function Ol(t,e,n,r){return t.map(s=>{const o=e.find(([c,u])=>c===s.id&&u===pe)?.[2],i=e.filter(([c,u])=>c===s.id&&u===D).map(([,,c])=>c),a=(()=>{if(o||i.length||!e.length)return;const c=e.findIndex(([u,d])=>u===s.id&&d===sn);if(c>=0)return e[c][2];if(typeof r=="string")return e.find(([u,d])=>u===s.id&&d===r)?.[2];if(Array.isArray(r)){const u=e.filter(([d,h])=>d===s.id&&r.includes(h)).map(([,d,h])=>[d,h]);return u.length?Pl(u):void 0}})();if(o)return{id:s.id,name:s.name,path:s.path,error:o,interrupts:i,result:a};const l=n?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:i,...l!==void 0?{state:l}:{},result:a}})}function Ip(t,e,n){console.log([`${$n(Rn.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
39
+ `,JSON.stringify(Tt(e,n),null,2)].join(""))}function Nl(t,e){const n=e.length;console.log([`${$n(Rn.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
40
40
  `,e.map(r=>`- ${$n(Rn.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
41
41
  `)].join(""))}function Pp(t,e,n){const r={};for(const[s,o]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(o));console.log([`${$n(Rn.blue,`[${t}:writes]`)}`,`\x1B[1m Finished step ${t} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
42
42
  `,Object.entries(r).map(([s,o])=>`- ${$n(Rn.yellow,s)} -> ${o.map(i=>JSON.stringify(i)).join(", ")}`).join(`
43
43
  `)].join(""))}var ai=class extends En{_abortController;_innerReader;constructor(t,e){const n=t.getReader(),r=e??new AbortController;super({start(s){return o();function o(){return n.read().then(({done:i,value:a})=>{if(i){s.close();return}return s.enqueue(a),o()})}}}),this._abortController=r,this._innerReader=n}async cancel(t){this._abortController.abort(t),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},Rl=class extends En{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(t){let e;const n=new Promise(r=>{e=r});super({start:r=>{e(r)}}),n.then(r=>{this.controller=r}),this.passthroughFn=t.passthroughFn,this.modes=t.modes}push(t){this.passthroughFn?.(t),this.controller.enqueue(t)}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(t){this.controller.error(t)}};function Op(t){return JSON.stringify(t,function(e,n){const r=this[e];if(r!=null&&typeof r=="object"&&"toDict"in r&&typeof r.toDict=="function"){const{type:s,data:o}=r.toDict();return{...o,type:s}}return n})}function Np(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function xo(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function us(t){return!xo(t)||!t.configurable.thread_id?null:{thread_id:t.configurable.thread_id,checkpoint_ns:t.configurable.checkpoint_ns||"",checkpoint_id:t.configurable.checkpoint_id||null,checkpoint_map:t.configurable.checkpoint_map||null}}function li(t){if(xo(t)){const e=Object.fromEntries(Object.entries(t.configurable).filter(([r])=>!r.startsWith("__"))),n={...t,configurable:e};return delete n.callbacks,n}return t}function ci(t){const e={...t,checkpoint:us(t.config),parent_checkpoint:us(t.parentConfig),config:li(t.config),parent_config:li(t.parentConfig),tasks:t.tasks.map(n=>{if(xo(n.state)){const r=us(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function Rp(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
44
44
  data: ${Op(s.data)}
45
45
 
46
- `))};try{for await(const s of t){const[o,i,a]=s;let l=a;if(i==="debug"){const c=a;c.type==="checkpoint"&&(l={...c,payload:ci(c.payload)})}i==="checkpoints"&&(l=ci(a)),r({event:o?.length?`${i}|${o.join("|")}`:i,data:l})}}catch(s){r({event:"error",data:Np(s)})}n.close()}})}const qn=Symbol.for("INPUT_DONE"),hs=Symbol.for("INPUT_RESUMING"),$p=25;function jp(...t){return new Rl({passthroughFn:e=>{for(const n of t)n.modes.has(e[1])&&n.push(e)},modes:new Set(t.flatMap(e=>Array.from(e.modes)))})}var Lp=class extends Pf{cache;queue=Promise.resolve();constructor(t){super(),this.cache=t}async get(t){return this.enqueueOperation("get",t)}async set(t){return this.enqueueOperation("set",t)}async clear(t){return this.enqueueOperation("clear",t)}async stop(){await this.queue}enqueueOperation(t,...e){const n=this.queue.then(()=>this.cache[t](...e));return this.queue=n.then(()=>{},()=>{}),n}},Dp=class $l{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";tasks={};stream;checkpointerPromises=[];isNested;_checkpointerChainedPromise=Promise.resolve();store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let e=!1;if(U in this.checkpoint.channel_versions)e=!0;else for(const a in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,a)){e=!0;break}const n=this.config.configurable?.[Ye]!==void 0&&this.config.configurable?.[Ye],r=this.input===null||this.input===void 0,s=q(this.input)&&this.input.resume!=null,o=this.input===hs,i=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return e&&(n||r||s||o||i)}constructor(e){this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=_p,this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.manager=e.manager,this.outputKeys=e.outputKeys,this.streamKeys=e.streamKeys,this.nodes=e.nodes,this.skipDoneTasks=e.skipDoneTasks,this.store=e.store,this.cache=e.cache?new Lp(e.cache):void 0,this.stream=e.stream,this.checkpointNamespace=e.checkpointNamespace,this.prevCheckpointConfig=e.prevCheckpointConfig,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.durability=e.durability,this.debug=e.debug,this.triggerToNodes=e.triggerToNodes}static async initialize(e){let{config:n,stream:r}=e;r!==void 0&&n.configurable?.[Er]!==void 0&&(r=jp(r,n.configurable[Er]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,o=n.configurable?.[ot];n.configurable&&o&&(o.subgraphCounter>0&&(n=Ee(n,{[Ne]:[n.configurable[Ne],o.subgraphCounter.toString()].join(Z)})),o.subgraphCounter+=1);const i=vt in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Ee(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[Ce]!==void 0&&n.configurable?.[Ce]?.[n.configurable?.checkpoint_ns]&&(a=Ee(n,{checkpoint_id:n.configurable[Ce][n.configurable?.checkpoint_ns]}));const l=n.configurable?.checkpoint_ns?.split(Z)??[],c=await e.checkpointer?.getTuple(a)??{config:n,checkpoint:hl(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...n,...c.config,configurable:{checkpoint_ns:"",...n.configurable,...c.config.configurable}};const u=c.parentConfig,d=Cr(c.checkpoint),h={...c.metadata},f=c.pendingWrites??[],m=kr(e.channelSpecs,d),p=(h.step??0)+1,C=p+(n.recursionLimit??$p)+1,k={...d.channel_versions},T=e.store?new If(e.store):void 0;return T&&await T.start(),new $l({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:d,checkpointMetadata:h,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:l,channels:m,isNested:i,manager:e.manager,skipDoneTasks:s,step:p,stop:C,checkpointPreviousVersions:k,checkpointPendingWrites:f,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:T,cache:e.cache,interruptAfter:e.interruptAfter,interruptBefore:e.interruptBefore,durability:e.durability,debug:e.debug,triggerToNodes:e.triggerToNodes})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(e,n){let r=n;if(r.length===0)return;r.every(([l])=>l in Ef)&&(r=Array.from(new Map(r.map(l=>[l[0],l])).values()));let s=!1;for(const l in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,l)&&this.channels[l].lc_graph_name==="UntrackedValue"){s=!0;break}let o=r;s&&(o=r.filter(([l])=>{const c=this.channels[l];return!c||c.lc_graph_name!=="UntrackedValue"}).map(([l,c])=>l===Se&&ye(c)?[l,Ep(c,this.channels)]:[l,c])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(l=>l[0]!==e);for(const[l,c]of o)this.checkpointPendingWrites.push([e,l,c]);const i=Ee(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??"",[Us]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(i,o,e)),this.tasks&&this._outputWrites(e,r),!n.length||!this.cache||!this.tasks)return;const a=this.tasks[e];a==null||a.cache_key==null||n[0][0]===pe||n[0][0]===D||this.cache.set([{key:[a.cache_key.ns,a.cache_key.key],value:a.writes,ttl:a.cache_key.ttl}])}_outputWrites(e,n,r=!1){const s=this.tasks[e];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes(Y))return;if(n.length>0)if(n[0][0]===D){if(s.path?.[0]===_e&&s.path?.[s.path.length-1]===!0)return;const o=n.filter(i=>i[0]===D).flatMap(i=>i[1]);this._emit([["updates",{[D]:o}],["values",{[D]:o}]])}else n[0][0]!==pe&&this._emit(yn(qe(pp(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(yn(qe(Mp([[s,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const e=[],n=([i,a])=>`ns:${i.join(",")}|key:${a}`,r=[],s={};for(const i of Object.values(this.tasks))i.cache_key!=null&&!i.writes.length&&(r.push([i.cache_key.ns,i.cache_key.key]),s[n([i.cache_key.ns,i.cache_key.key])]=i);if(r.length===0)return[];const o=await this.cache.get(r);for(const{key:i,value:a}of o){const l=s[n(i)];l!=null&&(l.writes.push(...a),e.push({task:l,result:a}))}return e}async tick(e){this.store&&!this.store.isRunning&&await this.store?.start();const{inputKeys:n=[]}=e;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![qn,hs].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new Lt;if(Object.values(this.tasks).every(s=>s.writes.length>0)){const s=Object.values(this.tasks).flatMap(i=>i.writes);this.updatedChannels=be(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const o=await Ze(qe(as(this.outputKeys,s,this.channels),"values"));if(this._emit(o),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),Jn(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new Lt;this.config.configurable?.[Ye]!==void 0&&delete this.config.configurable?.[Ye]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;if(this.tasks=jt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels}),this.checkpointer&&this._emit(await Ze(qe(Ap(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[s,o,i]of this.checkpointPendingWrites){if(o===pe||o===D||o===me)continue;const a=Object.values(this.tasks).find(l=>l.id===s);a&&a.writes.push([o,i])}for(const s of Object.values(this.tasks))s.writes.length>0&&this._outputWrites(s.id,s.writes,!0)}if(Object.values(this.tasks).every(s=>s.writes.length>0))return this.tick({inputKeys:n});if(Jn(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new Lt;const r=await Ze(qe(ii(Object.values(this.tasks)),"tasks"));return this._emit(r),!0}async finishAndHandleError(e){this.durability==="exit"&&(!this.isNested||typeof e<"u"||this.checkpointNamespace.every(r=>!r.includes(Ge)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=kt(this.channels,this.outputKeys)),n&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(r=>r.writes.length>0)&&(this.updatedChannels=be(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(yn(qe(as(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),yt(e)&&!e.interrupts.length&&this._emit([["updates",{[D]:[]}],["values",{[D]:[]}]])),n}async acceptPush(e,n,r){if(this.interruptAfter?.length>0&&Jn(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=Ws([_e,e.path??[],n,e.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!s)return;if(this.interruptBefore?.length>0&&Jn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(yn(qe(ii([s]),"tasks"))),this.debug&&Nl(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});const o=await this._matchCachedWrites();for(const{task:i}of o)this._outputWrites(i.id,i.writes,!0);return s}_suppressInterrupt(e){return yt(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,r=n?.[ot];if(r&&r.nullResume!==void 0&&this.putWrites(ke,[[me,r.nullResume]]),q(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(El)&&(this.config.configurable??={},this.config.configurable[lr]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of fp(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new Jo("Received empty Command input");for(const[l,c]of Object.entries(a))this.putWrites(l,c)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===ke).map(i=>i.slice(1));s.length>0&&be(this.checkpoint,this.channels,[{name:Ve,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const o=q(this.input)&&s.length>0;if(this.isResuming||o){for(const a in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,a)&&this.checkpoint.channel_versions[a]!==void 0){const l=this.checkpoint.channel_versions[a];this.checkpoint.versions_seen[D]={...this.checkpoint.versions_seen[D],[a]:l}}const i=await Ze(qe(as(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=hs;else if(o)await this._putCheckpoint({source:"input"}),this.input=qn;else{const i=await Ze(Il(e,this.input));if(i.length>0){const a=jt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=be(this.checkpoint,this.channels,Object.values(a).concat([{name:Ve,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=qn}else if(Ye in(this.config.configurable??{}))this.input=qn;else throw new Jo(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=Ee(this.config,{[Ye]:this.isResuming}))}_emit(e){for(const[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){const s=n==="checkpoints"?this.step-1:this.step,o=new Date().toISOString(),i=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:i,timestamp:o,payload:r}])}}_putCheckpoint(e){const n=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=o=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Ee(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},a=fr(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:Cr(o),metadata:{...this.checkpointMetadata},newVersions:a}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};n||(this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.[Ce]??{}}),this.checkpoint=pt(this.checkpoint,r?this.channels:void 0,this.step,n?{id:this.checkpoint.id}:void 0),r&&s(this.checkpoint),n||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;const e=Ee(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??"",[Us]:this.checkpoint.id}),n={};for(const[r,s,o]of this.checkpointPendingWrites)n[r]??=[],n[r].push([s,o]);for(const[r,s]of Object.entries(n))this.checkpointerPromises.push(this.checkpointer.putWrites(e,s,r))}_matchWrites(e){for(const[n,r,s]of this.checkpointPendingWrites){if(r===pe||r===D||r===me)continue;const o=Object.values(e).find(i=>i.id===n);o&&o.writes.push([r,s])}for(const n of Object.values(e))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}};function Fp(t){return Ue(t?.message)}var Up=class extends gu{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(t){super(),this.streamFn=t}_emit(t,e,n,r=!1){if(r&&e.id!==void 0&&this.seen[e.id]!==void 0)return;let s=e.id;n!=null&&(yu(e)?s??=`run-${n}-tool-${e.tool_call_id}`:((s==null||s===`run-${n}`)&&(s=this.stableMessageIdMap[n]??s??`run-${n}`),this.stableMessageIdMap[n]??=s)),s!==e.id&&(e.id=s,e.lc_kwargs.id=s),e.id!=null&&(this.seen[e.id]=e),this.streamFn([t[0],"messages",[e,t[1]]])}handleChatModelStart(t,e,n,r,s,o,i,a){i&&(!o||!o.includes(Lf)&&!o.includes("nostream"))&&(this.metadatas[n]=[i.langgraph_checkpoint_ns.split("|"),{tags:o,name:a,...i}])}handleLLMNewToken(t,e,n,r,s,o){const i=o?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(Fp(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new Qt({content:t}),n))}handleLLMEnd(t,e){if(this.metadatas[e]!==void 0){if(!this.emittedChatModelRunIds[e]){const n=t.generations?.[0]?.[0];Ue(n?.message)&&this._emit(this.metadatas[e],n?.message,e,!0),delete this.emittedChatModelRunIds[e]}delete this.metadatas[e],delete this.stableMessageIdMap[e]}}handleLLMError(t,e){delete this.metadatas[e]}handleChainStart(t,e,n,r,s,o,i,a){if(o!==void 0&&a===o.langgraph_node&&(s===void 0||!s.includes(Y))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...o}],typeof e=="object")){for(const l of Object.values(e))if((Ue(l)||Fo(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(Ue(c)||Fo(c))&&c.id!==void 0&&(this.seen[c.id]=c)}}handleChainEnd(t,e){const n=this.metadatas[e];if(delete this.metadatas[e],n!==void 0){if(Ue(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)Ue(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(Ue(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)Ue(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const Vp=500,Bp=2,zp=128e3,Hp=3,Wp=[400,401,402,403,404,405,406,407,409],Gp=t=>{if(t.message.startsWith("Cancel")||t.message.startsWith("AbortError")||t.name==="AbortError"||t.name==="GraphValueError"||t?.code==="ECONNABORTED")return!1;const e=t?.response?.status??t?.status;return!(e&&Wp.includes(+e)||t?.error?.code==="insufficient_quota")};async function jl(t,e,n,r){const s=t.retry_policy??e;let o=s!==void 0?s.initialInterval??Vp:0,i=0,a,l,{config:c}=t;for(n&&(c=Ee(c,n)),c={...c,signal:r};!r?.aborted;){t.writes.splice(0,t.writes.length),a=void 0;try{l=await t.proc.invoke(t.input,c);break}catch(u){if(a=u,a.pregelTaskId=t.id,Ph(a)){const f=c?.configurable?.checkpoint_ns,m=a.command;if(m.graph===f){for(const p of t.writers)await p.invoke(m,c);a=void 0;break}else if(m.graph===G.PARENT){const p=Hf(f);a.command=new G({...a.command,graph:p})}}if(Sn(a)||s===void 0||(i+=1,i>=(s.maxAttempts??Hp))||!(s.retryOn??Gp)(a))break;o=Math.min(s.maxInterval??zp,o*(s.backoffFactor??Bp));const d=s.jitter?Math.floor(o+Math.random()*1e3):o;await new Promise(f=>setTimeout(f,d));const h=a.name??a.constructor.unminifiable_name??a.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(t.name)}" after ${o.toFixed(2)}ms (attempt ${i}) after ${h}: ${a}`),c=Ee(c,{[Ye]:!0})}}return{task:t,result:l,error:a,signalAborted:r?.aborted}}const Gs=Symbol.for("promiseAdded");function Kp(){const t={next:()=>{},wait:Promise.resolve(Gs)};function e(n){t.next=()=>{t.wait=new Promise(e),n(Gs)}}return t.wait=new Promise(e),t}var Jp=class{nodeFinished;loop;constructor({loop:t,nodeFinished:e}){this.loop=t,this.nodeFinished=e}async tick(t={}){const{timeout:e,retryPolicy:n,onStepWrite:r,maxConcurrency:s}=t,o=new Set;let i;const a=new AbortController,l=a.signal,c=e?AbortSignal.timeout(e):void 0,u=Object.values(this.loop.tasks).filter(m=>m.writes.length===0),{signals:d,disposeCombinedSignal:h}=this._initializeAbortSignals({exceptionSignal:l,stepTimeoutSignal:c,signal:t.signal}),f=this._executeTasksWithRetry(u,{signals:d,retryPolicy:n,maxConcurrency:s});for await(const{task:m,error:p,signalAborted:C}of f)this._commit(m,p),yt(p)||Sn(p)&&!yt(i)?i=p:p&&(o.size===0||!C)&&(a.abort(),o.add(p));if(h?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(m=>m.writes).flat()),o.size===1)throw Array.from(o)[0];if(o.size>1)throw new AggregateError(Array.from(o),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(yt(i)||Sn(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[ei]??{},s=r.externalAbortSignal??n,o=e??r.timeoutAbortSignal,{signal:i,dispose:a}=Ar(s,o,t),l={externalAbortSignal:s,timeoutAbortSignal:o,composedAbortSignal:i};return this.loop.config=Ee(this.loop.config,{[ei]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},o=Kp(),i={},a={executingTasksMap:i,barrier:o,retryPolicy:n,scheduleTask:async(h,f,m)=>this.loop.acceptPush(h,f,m)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let l=0,c;const u=Ar(s?.externalAbortSignal,s?.timeoutAbortSignal),d=u.signal?new Promise((h,f)=>{c=()=>f(new Error("Abort")),u.signal?.addEventListener("abort",c,{once:!0})}):void 0;for(;(l===0||Object.keys(i).length>0)&&t.length;){for(;Object.values(i).length<(r??t.length)&&l<t.length;l+=1){const f=t[l];i[f.id]=jl(f,n,{[So]:Ll?.bind(a,this,f)},s?.composedAbortSignal).catch(m=>({task:f,error:m,signalAborted:s?.composedAbortSignal?.aborted}))}const h=await Promise.race([...Object.values(i),...d?[d]:[],o.wait]);h!==Gs&&(yield h,c!=null&&(u.signal?.removeEventListener("abort",c),u.dispose?.()),delete i[h.task.id])}}_commit(t,e){if(e!==void 0)if(yt(e)){if(e.interrupts.length){const n=e.interrupts.map(s=>[D,s]),r=t.writes.filter(s=>s[0]===me);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else Sn(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[pe,{message:e.message,name:e.name}]]);else this.nodeFinished&&(t.config?.tags==null||!t.config.tags.includes(Y))&&this.nodeFinished(String(t.name)),t.writes.length===0&&t.writes.push([Co,null]),this.loop.putWrites(t.id,t.writes)}};async function Ll(t,e,n,r,s,o={}){const i=e.config?.configurable?.[ot];if(!i)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const a=i.callCounter;i.callCounter+=1;const l=new yp({func:n,name:r,input:s,cache:o.cache,retry:o.retry,callbacks:o.callbacks}),c=await this.scheduleTask(e,a,l);if(!c)return;const u=this.executingTasksMap[c.id];if(u!==void 0)return u;if(c.writes.length>0){const d=c.writes.filter(([f])=>f===sn),h=c.writes.filter(([f])=>f===pe);if(d.length>0){if(d.length===1)return Promise.resolve(d[0][1]);throw new Error(`BUG: multiple returns found for task ${c.name}__${c.id}`)}if(h.length>0){if(h.length===1){const f=h[0][1],m=f instanceof Error?f:new Error(String(f));return Promise.reject(m)}throw new Error(`BUG: multiple errors found for task ${c.name}__${c.id}`)}return}else{const d=jl(c,o.retry,{[So]:Ll.bind(this,t,c)});return this.executingTasksMap[c.id]=d,this.barrier.next(),d.then(({result:h,error:f})=>f?Promise.reject(f):h)}}var Fe=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function qp({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:o,interruptBeforeNodes:i}){if(!e)throw new Fe("Channels not provided");const a=new Set,l=new Set;for(const[c,u]of Object.entries(t)){if(c===D)throw new Fe(`"Node name ${D} is reserved"`);if(u.constructor===Nn)u.triggers.forEach(d=>a.add(d));else throw new Fe(`Invalid node type ${typeof u}, expected PregelNode`)}for(const c of a)if(!(c in e))throw new Fe(`Subscribed channel '${String(c)}' not in channels`);if(Array.isArray(n)){if(n.every(c=>!a.has(c)))throw new Fe(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new Fe(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(c=>l.add(c)):l.add(r),s&&!Array.isArray(s)?l.add(s):Array.isArray(s)&&s.forEach(c=>l.add(c));for(const c of l)if(!(c in e))throw new Fe(`Output channel '${String(c)}' not in channels`);if(o&&o!=="*"){for(const c of o)if(!(c in t))throw new Fe(`Node ${String(c)} not in nodes`)}if(i&&i!=="*"){for(const c of i)if(!(c in t))throw new Fe(`Node ${String(c)} not in nodes`)}}function ui(t,e){if(Array.isArray(t)){for(const n of t)if(!(n in e))throw new Error(`Key ${String(n)} not found in channels`)}else if(!(t in e))throw new Error(`Key ${String(t)} not found in channels`)}var Yp=class Dl extends ut{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(e){super(),this.unique=e?.unique??this.unique,this.accumulate=e?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(e){const n=new Dl({unique:this.unique,accumulate:this.accumulate});return typeof e<"u"&&(n.seen=new Set(e[0]),n.values=e[1]),n}update(e){let n=!1;this.accumulate||(n=this.values.length>0,this.values=[]);const r=e.flat();if(r.length>0)if(this.unique)for(const s of r)this.seen.has(s)||(n=!0,this.seen.add(s),this.values.push(s));else n=!0,this.values.push(...r);return n}get(){if(this.values.length===0)throw new ee;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},Xp=class{static subscribeTo(t,e){const{key:n,tags:r}={key:void 0,tags:void 0,...e??{}};if(Array.isArray(t)&&n!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;return typeof t=="string"?n?s={[n]:t}:s=[t]:s=Object.fromEntries(t.map(o=>[o,o])),new Nn({channels:s,triggers:Array.isArray(t)?t:[t],tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:St,skipNone:!1});for(const[r,s]of Object.entries(e??{}))ae.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:St,skipNone:!0,mapper:en(s)}):n.push({channel:r,value:s,skipNone:!1});return new de(n)}},Zp=class extends ae{lc_namespace=["langgraph","pregel"];invoke(t,e){throw new Error("Not implemented")}withConfig(t){return super.withConfig(t)}stream(t,e){return super.stream(t,e)}},Qp=class extends Zp{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(t){super(t);let{streamMode:e}=t;if(e!=null&&!Array.isArray(e)&&(e=[e]),this.nodes=t.nodes,this.channels=t.channels,Se in this.channels&&"lc_graph_name"in this.channels[Se]&&this.channels[Se].lc_graph_name!=="Topic")throw new Error(`Channel '${Se}' is reserved and cannot be used in the graph.`);this.channels[Se]=new Yp({accumulate:!1}),this.autoValidate=t.autoValidate??this.autoValidate,this.streamMode=e??this.streamMode,this.inputChannels=t.inputChannels,this.outputChannels=t.outputChannels,this.streamChannels=t.streamChannels??this.streamChannels,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.stepTimeout=t.stepTimeout??this.stepTimeout,this.debug=t.debug??this.debug,this.checkpointer=t.checkpointer,this.retryPolicy=t.retryPolicy,this.config=t.config,this.store=t.store,this.cache=t.cache,this.name=t.name,this.triggerToNodes=t.triggerToNodes??this.triggerToNodes,this.userInterrupt=t.userInterrupt,this.autoValidate&&this.validate()}withConfig(t){const e=$e(this.config,t);return new this.constructor({...this,config:e})}validate(){qp({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(const[t,e]of Object.entries(this.nodes))for(const n of e.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(t);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(t){return this.getGraph(t)}*getSubgraphs(t,e){for(const[n,r]of Object.entries(this.nodes)){if(t!==void 0&&!t.startsWith(n))continue;const s=r.subgraphs?.length?r.subgraphs:[r.bound];for(const o of s){const i=Al(o);if(i!==void 0){if(n===t){yield[n,i];return}if(t===void 0&&(yield[n,i]),e){let a=t;t!==void 0&&(a=t.slice(n.length+1));for(const[l,c]of i.getSubgraphs(a,e))yield[`${n}${Z}${l}`,c]}}}}}async*getSubgraphsAsync(t,e){yield*this.getSubgraphs(t,e)}async _prepareStateSnapshot({config:t,saved:e,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(e===void 0)return{values:{},next:[],config:t,tasks:[]};const s=kr(this.channels,e.checkpoint);if(e.pendingWrites?.length){const d=e.pendingWrites.filter(([h,f])=>h===ke).map(([h,f,m])=>[String(f),m]);d.length>0&&be(e.checkpoint,s,[{name:Ve,writes:d,triggers:[]}],void 0,this.triggerToNodes)}const o=Object.values(jt(e.checkpoint,e.pendingWrites,this.nodes,s,e.config,!0,{step:(e.metadata?.step??-1)+1,store:this.store})),i=await Ze(this.getSubgraphsAsync()),a=e.config.configurable?.checkpoint_ns??"",l={};for(const d of o){const h=i.find(([m])=>m===d.name);if(!h)continue;let f=`${String(d.name)}${Ge}${d.id}`;if(a&&(f=`${a}${Z}${f}`),n===void 0){const m={configurable:{thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}};l[d.id]=m}else{const m={configurable:{[J]:n,thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}},p=h[1];l[d.id]=await p.getState(m,{subgraphs:!0})}}if(r&&e.pendingWrites?.length){const d=Object.fromEntries(o.map(f=>[f.id,f]));for(const[f,m,p]of e.pendingWrites)[pe,D,nr].includes(m)||f in d&&d[f].writes.push([String(m),p]);const h=o.filter(f=>f.writes.length>0);h.length>0&&be(e.checkpoint,s,h,void 0,this.triggerToNodes)}let c=e?.metadata;c&&e?.config?.configurable?.thread_id&&(c={...c,thread_id:e.config.configurable.thread_id});const u=o.filter(d=>d.writes.length===0).map(d=>d.name);return{values:kt(s,this.streamChannelsAsIs),next:u,tasks:Ol(o,e?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:c,config:dt(e.config,e.metadata),createdAt:e.checkpoint.ts,parentConfig:e.parentConfig}}async getState(t,e){const n=t.configurable?.[J]??this.checkpointer;if(!n)throw new tr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[J]===void 0){const i=ss(r);for await(const[a,l]of this.getSubgraphsAsync(i,!0))if(a===i)return await l.getState(Mt(t,{[J]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${i}" not found.`)}const s=$e(this.config,t),o=await n.getTuple(t);return await this._prepareStateSnapshot({config:s,saved:o,subgraphCheckpointer:e?.subgraphs?n:void 0,applyPendingWrites:!t.configurable?.checkpoint_id})}async*getStateHistory(t,e){const n=t.configurable?.[J]??this.checkpointer;if(!n)throw new tr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[J]===void 0){const o=ss(r);for await(const[i,a]of this.getSubgraphsAsync(o,!0))if(i===o){yield*a.getStateHistory(Mt(t,{[J]:n}),e);return}throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=$e(this.config,t,{configurable:{checkpoint_ns:r}});for await(const o of n.list(s,e))yield this._prepareStateSnapshot({config:o.config,saved:o})}async bulkUpdateState(t,e){const n=t.configurable?.[J]??this.checkpointer;if(!n)throw new tr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(e.length===0)throw new Error("No supersteps provided");if(e.some(i=>i.updates.length===0))throw new Error("No updates provided");const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[J]===void 0){const i=ss(r);for await(const[,a]of this.getSubgraphsAsync(i,!0))return await a.bulkUpdateState(Mt(t,{[J]:n}),e);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,a)=>{const l=this.config?$e(this.config,i):i,c=await n.getTuple(l),u=c!==void 0?Cr(c.checkpoint):hl(),d={...c?.checkpoint.channel_versions},h=c?.metadata?.step??-1;let f=Mt(l,{checkpoint_ns:l.configurable?.checkpoint_ns??""}),m=l.metadata??{};c?.config.configurable&&(f=Mt(l,c.config.configurable),m={...c.metadata,...m});const{values:p,asNode:C}=a[0];if(p==null&&C===void 0){if(a.length>1)throw new B("Cannot create empty checkpoint with multiple updates");return dt(await n.put(f,pt(u,void 0,h),{source:"update",step:h+1,parents:c?.metadata?.parents??{}},{}),c?c.metadata:void 0)}const k=kr(this.channels,u);if(p===null&&C===N){if(a.length>1)throw new B("Cannot apply multiple updates when clearing state");if(c){const w=jt(u,c.pendingWrites||[],this.nodes,k,c.config,!0,{step:(c.metadata?.step??-1)+1,checkpointer:n,store:this.store}),b=(c.pendingWrites||[]).filter(E=>E[0]===ke).map(E=>E.slice(1));b.length>0&&be(u,k,[{name:Ve,writes:b,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[E,S,x]of c.pendingWrites||[])[pe,D,nr].includes(S)||E in w&&w[E].writes.push([S,x]);be(u,k,Object.values(w),n.getNextVersion.bind(n),this.triggerToNodes)}return dt(await n.put(f,pt(u,k,h),{...m,source:"update",step:h+1,parents:c?.metadata?.parents??{}},fr(d,u.channel_versions)),c?c.metadata:void 0)}if(C===Rf){if(a.length>1)throw new B("Cannot copy checkpoint with multiple updates");if(c==null)throw new B("Cannot copy a non-existent checkpoint");const w=S=>!Array.isArray(S)||S.length===0?!1:S.every(x=>Array.isArray(x)&&x.length===2),b=pt(u,void 0,h),E=await n.put(c.parentConfig??Mt(c.config,{checkpoint_id:void 0}),b,{source:"fork",step:h+1,parents:c.metadata?.parents??{}},{});if(w(p)){const S=jt(b,c.pendingWrites,this.nodes,k,E,!1,{step:h+2}),x=Object.values(S).reduce((O,{name:F,id:ce})=>(O[F]??=[],O[F].push({id:ce}),O),{}),I=p.reduce((O,F)=>{const[ce,Ie]=F;O[Ie]??=[];const we=O[Ie].length,ht=x[Ie]?.[we]?.id;return O[Ie].push({values:ce,asNode:Ie,taskId:ht}),O},{});return s(dt(E,c.metadata),Object.values(I).flat())}return dt(E,c.metadata)}if(C===Ve){if(a.length>1)throw new B("Cannot apply multiple updates when updating as input");const w=await Ze(Il(this.inputChannels,p));if(w.length===0)throw new B(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);be(u,k,[{name:Ve,writes:w,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const b=c?.metadata?.step!=null?c.metadata.step+1:-1,E=await n.put(f,pt(u,k,b),{source:"input",step:b,parents:c?.metadata?.parents??{}},fr(d,u.channel_versions));return await n.putWrites(E,w,Nt(Ve,u.id)),dt(E,c?c.metadata:void 0)}if(l.configurable?.checkpoint_id===void 0&&c?.pendingWrites!==void 0&&c.pendingWrites.length>0){const w=jt(u,c.pendingWrites,this.nodes,k,c.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(c.metadata?.step??-1)+1}),b=(c.pendingWrites??[]).filter(S=>S[0]===ke).map(S=>S.slice(1));b.length>0&&be(c.checkpoint,k,[{name:Ve,writes:b,triggers:[]}],void 0,this.triggerToNodes);for(const[S,x,I]of c.pendingWrites)[pe,D,nr].includes(x)||w[S]===void 0||w[S].writes.push([x,I]);const E=Object.values(w).filter(S=>S.writes.length>0);E.length>0&&be(u,k,E,void 0,this.triggerToNodes)}const T=Object.values(u.versions_seen).map(w=>Object.values(w)).flat().find(w=>!!w),_=[];if(a.length===1){let{values:w,asNode:b,taskId:E}=a[0];if(b===void 0&&Object.keys(this.nodes).length===1)[b]=Object.keys(this.nodes);else if(b===void 0&&T===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(b=this.inputChannels);else if(b===void 0){const S=Object.entries(u.versions_seen).map(([x,I])=>Object.values(I).map(O=>[O,x])).flat().filter(([x,I])=>I!==D).sort(([x],[I])=>dl(x,I));S&&(S.length===1?b=S[0][1]:S[S.length-1][0]!==S[S.length-2][0]&&(b=S[S.length-1][1]))}if(b===void 0)throw new B('Ambiguous update, specify "asNode"');_.push({values:w,asNode:b,taskId:E})}else for(const{asNode:w,values:b,taskId:E}of a){if(w==null)throw new B('"asNode" is required when applying multiple updates');_.push({values:b,asNode:w,taskId:E})}const g=[];for(const{asNode:w,values:b,taskId:E}of _){if(this.nodes[w]===void 0)throw new B(`Node "${w.toString()}" does not exist`);const S=this.nodes[w].getWriters();if(!S.length)throw new B(`No writers found for node "${w.toString()}"`);g.push({name:w,input:b,proc:S.length>1?it.from(S,{omitSequenceTags:!0}):S[0],writes:[],triggers:[D],id:E??Nt(D,u.id),writers:[]})}for(const w of g)await w.proc.invoke(w.input,vn({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[st]:b=>w.writes.push(...b),[vt]:(b,E=!1)=>pr(u,k,w,b,E)}}));for(const w of g){const b=w.writes.filter(E=>E[0]!==_e);c!==void 0&&b.length>0&&await n.putWrites(f,b,w.id)}be(u,k,g,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const v=fr(d,u.channel_versions),M=await n.put(f,pt(u,k,h+1),{source:"update",step:h+1,parents:c?.metadata?.parents??{}},v);for(const w of g){const b=w.writes.filter(E=>E[0]===_e);b.length>0&&await n.putWrites(M,b,w.id)}return dt(M,c?c.metadata:void 0)};let o=t;for(const{updates:i}of e)o=await s(o,i);return o}async updateState(t,e,n){return this.bulkUpdateState(t,[{updates:[{values:e,asNode:n}]}])}_defaults(t){const{debug:e,streamMode:n,inputKeys:r,outputKeys:s,interruptAfter:o,interruptBefore:i,...a}=t;let l=!0;const c=e!==void 0?e:this.debug;let u=s;u===void 0?u=this.streamChannelsAsIs:ui(u,this.channels);let d=r;d===void 0?d=this.inputChannels:ui(d,this.channels);const h=i??this.interruptBefore??[],f=o??this.interruptAfter??[];let m;n!==void 0?(m=Array.isArray(n)?n:[n],l=typeof n=="string"):(t.configurable?.[Cn]!==void 0?m=["values"]:m=this.streamMode,l=!0);let p;if(this.checkpointer===!1)p=void 0;else if(t!==void 0&&t.configurable?.[J]!==void 0)p=t.configurable[J];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");p=this.checkpointer}const C=t.store??this.store,k=t.cache??this.cache;if(t.durability!=null&&t.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");const T=(()=>{if(t.checkpointDuring!=null)return t.checkpointDuring===!1?"exit":"async"})(),_=t.durability??T??t?.configurable?.[yl]??"async";return[c,m,d,u,a,h,f,p,C,l,k,_]}async stream(t,e){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...e,signal:Ar(e?.signal,n.signal).signal},s=await super.stream(t,r);return new ai(e?.encoding==="text/event-stream"?Rp(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:gp(this.config?.callbacks,e?.callbacks),signal:Ar(e?.signal,r.signal).signal};return new ai(super.streamEvents(t,s,n),r)}async _validateInput(t){return t}async _validateContext(t){return t}async*_streamIterator(t,e){const n="version"in(e??{})?void 0:e?.encoding??void 0,r=e?.subgraphs,s=bl(this.config,e);if(s.recursionLimit===void 0||s.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&s.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const o=await this._validateInput(t),{runId:i,...a}=s,[l,c,,u,d,h,f,m,p,C,k,T]=this._defaults(a);typeof d.context<"u"?d.context=await this._validateContext(d.context):d.configurable=await this._validateContext(d.configurable);const _=new Rl({modes:new Set(c)});if(this.checkpointer===!0){d.configurable??={};const S=d.configurable[Ne]??"";d.configurable[Ne]=S.split(Z).map(x=>x.split(Ge)[0]).join(Z)}if(c.includes("messages")){const S=new Up(I=>_.push(I)),{callbacks:x}=d;if(x===void 0)d.callbacks=[S];else if(Array.isArray(x))d.callbacks=x.concat(S);else{const I=x.copy();I.addHandler(S,!0),d.callbacks=I}}d.writer??=S=>{if(!c.includes("custom"))return;const x=zf()?.configurable?.[Ne]?.split(Z).slice(0,-1);_.push([x??[],"custom",S])},d.interrupt??=this.userInterrupt??xl;const g=await(await wu(d))?.handleChainStart(this.toJSON(),mp(t,"input"),i,void 0,void 0,void 0,d?.runName??this.getName()),v=vo(this.channels);let M,w;const E=(async()=>{try{M=await Dp.initialize({input:o,config:d,checkpointer:m,nodes:this.nodes,channelSpecs:v,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:p,cache:k,stream:_,interruptAfter:f,interruptBefore:h,manager:g,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:T});const S=new Jp({loop:M,nodeFinished:d.configurable?.[jf]});e?.subgraphs&&(M.config.configurable={...M.config.configurable,[Er]:M.stream}),await this._runLoop({loop:M,runner:S,debug:l,config:d}),T==="sync"&&await Promise.all(M?.checkpointerPromises??[])}catch(S){w=S}finally{try{M&&(await M.store?.stop(),await M.cache?.stop()),await Promise.all(M?.checkpointerPromises??[])}catch(S){w=w??S}w?_.error(w):_.close()}})();try{for await(const S of _){if(S===void 0)throw new Error("Data structure error.");const[x,I,O]=S;if(c.includes(I)){if(n==="text/event-stream"){r?yield[x,I,O]:yield[null,I,O];continue}r&&!C?yield[x,I,O]:C?r?yield[x,O]:yield O:yield[I,O]}}}catch(S){throw await g?.handleChainError(w),S}finally{await E}await g?.handleChainEnd(M?.output??{},i,void 0,void 0,void 0)}async invoke(t,e){const n=e?.streamMode??"values",r={...e,outputKeys:e?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},s=[],o=await this.stream(t,r),i=[];let a;for await(const l of o)n==="values"?wl(l)?i.push(l[D]):a=l:s.push(l);if(n==="values"){if(i.length>0){const l=i.flat(1);if(a==null)return{[D]:l};if(typeof a=="object")return{...a,[D]:l}}return a}return s}async _runLoop(t){const{loop:e,runner:n,debug:r,config:s}=t;let o;try{for(;await e.tick({inputKeys:this.inputChannels});){for(const{task:i}of await e._matchCachedWrites())e._outputWrites(i.id,i.writes,!0);r&&Ip(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&Nl(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,a)=>{r&&Pp(i,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new Ih([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(i){if(o=i,!await e.finishAndHandleError(o))throw i}finally{o===void 0&&await e.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},an=class Fl extends ut{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new Fl(this.guard);return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0){const n=this.value.length>0;return this.value=[],n}if(e.length!==1&&this.guard)throw new B("EphemeralValue can only receive one value per step.");return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new ee;return this.value[0]}checkpoint(){if(this.value.length===0)throw new ee;return this.value[0]}isAvailable(){return this.value.length!==0}},Ul=class{path;ends;constructor(t){ae.isRunnable(t.path)?this.path=t.path:this.path=en(t.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(t.pathMap)?t.pathMap.reduce((e,n)=>(e[n]=n,e),{}):t.pathMap}run(t,e){return de.registerWriter(new Et({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===Zi.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
47
- NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(t,e,n,r){let s=await this.path.invoke(r?r(e):t,e);Array.isArray(s)||(s=[s]);let o;if(this.ends?o=s.map(i=>ye(i)?i:this.ends[i]):o=s,o.some(i=>!i))throw new Error("Branch condition returned unknown or null destination");if(o.filter(ye).some(i=>i.node===N))throw new B("Cannot send a packet to the END node");return await n(o,e)??t}},em=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(t){this.compiled&&console.warn(t)}get allEdges(){return this.edges}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,o]of n){for(const a of[Z,Ge])if(r.includes(a))throw new Error(`"${a}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===N)throw new Error(`Node \`${r}\` is reserved.`);const i=en(s);this.nodes[r]={runnable:i,metadata:o?.metadata,subgraphs:To(i)?[i]:o?.subgraphs,ends:o?.ends}}return this}addEdge(t,e){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),t===N)throw new Error("END cannot be a start node");if(e===U)throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([n])=>n===t)&&!("channels"in this))throw new Error(`Already found path for ${t}. For multiple edges, use StateGraph.`);return this.edges.add([t,e]),this}addConditionalEdges(t,e,n){const r=typeof t=="object"?t:{source:t,path:e,pathMap:n};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!ae.isRunnable(r.path)){const o=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=en(r.path).withConfig({runName:`Branch<${r.source}${o!==""?`,${o}`:""}>`.slice(0,63)})}const s=r.path.getName()==="RunnableLambda"?"condition":r.path.getName();if(this.branches[r.source]&&this.branches[r.source][s])throw new Error(`Condition \`${s}\` already present for node \`${t}\``);return this.branches[r.source]??={},this.branches[r.source][s]=new Ul(r),this}setEntryPoint(t){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(U,t)}setFinishPoint(t){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(t,N)}compile({checkpointer:t,interruptBefore:e,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(e)?e:[],...Array.isArray(n)?n:[]]);const s=new Vl({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[U]:new an,[N]:new an},inputChannels:U,outputChannels:N,streamChannels:[],streamMode:"values",name:r});for(const[o,i]of Object.entries(this.nodes))s.attachNode(o,i);for(const[o,i]of this.edges)s.attachEdge(o,i);for(const[o,i]of Object.entries(this.branches))for(const[a,l]of Object.entries(i))s.attachBranch(o,a,l);return s.validate()}validate(t){const e=new Set([...this.allEdges].map(([r,s])=>r));for(const[r]of Object.entries(this.branches))e.add(r);for(const r of e)if(r!==U&&!(r in this.nodes))throw new Error(`Found edge starting at unknown node \`${r}\``);const n=new Set([...this.allEdges].map(([r,s])=>s));for(const[r,s]of Object.entries(this.branches))for(const o of Object.values(s))if(o.ends!=null)for(const i of Object.values(o.ends))n.add(i);else{n.add(N);for(const i of Object.keys(this.nodes))i!==r&&n.add(i)}for(const r of Object.values(this.nodes))for(const s of r.ends??[])n.add(s);for(const r of Object.keys(this.nodes))if(!n.has(r))throw new Oh([`Node \`${r}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join(`
48
- `),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!==N&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(t){for(const r of t)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},Vl=class extends Qp{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new an,this.nodes[t]=new Nn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new de([{channel:t,value:St}],[Y])),this.streamChannels.push(t)}attachEdge(t,e){if(e===N){if(t===U)throw new Error("Cannot have an edge from START to END");this.nodes[t].writers.push(new de([{channel:N,value:St}],[Y]))}else this.nodes[e].triggers.push(t),this.nodes[e].channels.push(t)}attachBranch(t,e,n){t===U&&!this.nodes[U]&&(this.nodes[U]=Xp.subscribeTo(U,{tags:[Y]})),this.nodes[t].pipe(n.run(s=>new de(s.map(o=>ye(o)?o:{channel:o===N?N:`branch:${t}:${e}:${o}`,value:St}),[Y])));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==N){const o=`branch:${t}:${e}:${s}`;this.channels[o]=new an,this.nodes[s].triggers.push(o),this.nodes[s].channels.push(o)}}async getGraphAsync(t){const e=t?.xray,n=new Uo,r={[U]:n.addNode({schema:ve()},U)},s={};let o={};e&&(o=Object.fromEntries((await Ze(this.getSubgraphsAsync())).filter(l=>hi(l[1]))));function i(l,c,u,d=!1){if(c===N&&s[N]===void 0&&(s[N]=n.addNode({schema:ve()},N)),r[l]!==void 0){if(s[c]===void 0)throw new Error(`End node ${c} not found!`);return n.addEdge(r[l],s[c],u!==c?u:void 0,d)}}for(const[l,c]of Object.entries(this.builder.nodes)){const u=ue(l),d=c.runnable,h=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?h.__interrupt="before,after":this.interruptBefore?.includes(l)?h.__interrupt="before":this.interruptAfter?.includes(l)&&(h.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,m=o[l]!==void 0?await o[l].getGraphAsync({...t,xray:f}):d.getGraph(t);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let k=function(_){return _?_.lc_runnable:!1},T=function(_,g){if(_!==void 0&&!Vo(_))return _;if(k(g))try{let v=g.getName();return v=v.startsWith("Runnable")?v.slice(8):v,v}catch{return g.getName()}else return g.name??"UnknownSchema"};const[p,C]=n.extend(m,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);C!==void 0&&(r[u]={name:T(C.id,C.data),...C}),s[u]={name:T(p.id,p.data),...p}}else{const p=n.addNode(d,u,h);r[u]=p,s[u]=p}}else{const f=n.addNode(d,u,h);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(ue(l),ue(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==l).map(d=>[ue(d),ue(d)])),[N]:N};for(const d of Object.values(c)){let h;d.ends!==void 0?h=d.ends:h=u;for(const[f,m]of Object.entries(h))i(ue(l),ue(m),f,!0)}}for(const[l,c]of Object.entries(this.builder.nodes))if(c.ends!==void 0)for(const u of c.ends)i(ue(l),ue(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new Uo,r={[U]:n.addNode({schema:ve()},U)},s={};let o={};e&&(o=Object.fromEntries(yn(this.getSubgraphs()).filter(l=>hi(l[1]))));function i(l,c,u,d=!1){return c===N&&s[N]===void 0&&(s[N]=n.addNode({schema:ve()},N)),n.addEdge(r[l],s[c],u!==c?u:void 0,d)}for(const[l,c]of Object.entries(this.builder.nodes)){const u=ue(l),d=c.runnable,h=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?h.__interrupt="before,after":this.interruptBefore?.includes(l)?h.__interrupt="before":this.interruptAfter?.includes(l)&&(h.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,m=o[l]!==void 0?o[l].getGraph({...t,xray:f}):d.getGraph(t);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let k=function(_){return _?_.lc_runnable:!1},T=function(_,g){if(_!==void 0&&!Vo(_))return _;if(k(g))try{let v=g.getName();return v=v.startsWith("Runnable")?v.slice(8):v,v}catch{return g.getName()}else return g.name??"UnknownSchema"};const[p,C]=n.extend(m,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);C!==void 0&&(r[u]={name:T(C.id,C.data),...C}),s[u]={name:T(p.id,p.data),...p}}else{const p=n.addNode(d,u,h);r[u]=p,s[u]=p}}else{const f=n.addNode(d,u,h);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(ue(l),ue(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==l).map(d=>[ue(d),ue(d)])),[N]:N};for(const d of Object.values(c)){let h;d.ends!==void 0?h=d.ends:h=u;for(const[f,m]of Object.entries(h))i(ue(l),ue(m),f,!0)}}return n}};function hi(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function ue(t){return t==="subgraph"?`"${t}"`:t}function bn(t){return typeof t=="object"&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"validate"in t["~standard"]}function tm(t){return typeof t=="object"&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"jsonSchema"in t["~standard"]}function It(t){if(tm(t))try{return t["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function Pt(t){if(t!=null&&bn(t))try{const e=t["~standard"].validate(void 0);if(e&&typeof e=="object"&&!("then"in e&&typeof e.then=="function")){const n=e;if(!n.issues){const r=n.value;return()=>r}}}catch{}}const ds=Symbol.for("langgraph.channel.missing");var nm=class Bl extends ut{lc_graph_name="UntrackedValue";guard;_value=ds;initialValueFactory;constructor(e){super(),this.guard=e?.guard??!0,this.initialValueFactory=e?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(e){return new Bl({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(e){if(e.length===0)return!1;if(e.length!==1&&this.guard)throw new B("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this._value=e[e.length-1],!0}get(){if(this._value===ds)throw new ee;return this._value}checkpoint(){}isAvailable(){return this._value!==ds}};const fs=Symbol.for("langgraph.state.reduced_value");var Te=class{[fs]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(t,e){this.reducer=e.reducer,this.jsonSchemaExtra=e.jsonSchemaExtra,this.valueSchema=t,this.inputSchema="inputSchema"in e?e.inputSchema:t,this.jsonSchemaExtra=e.jsonSchemaExtra}static isInstance(t){return typeof t=="object"&&t!==null&&fs in t&&t[fs]===!0}};const di=Symbol.for("langgraph.state.untracked_value");var mt=class{[di]=!0;schema;guard;constructor(t,e){this.schema=t,this.guard=e?.guard??!0}static isInstance(t){return typeof t=="object"&&t!==null&&di in t}};const wt=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var rm=class zl extends ut{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new zl(this.names);return typeof e<"u"&&(n.seen=new Set(e)),n}update(e){let n=!1;for(const r of e)if(this.names.has(r))this.seen.has(r)||(this.seen.add(r),n=!0);else throw new B(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!wt(this.names,this.seen))throw new ee}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&wt(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&wt(this.names,this.seen)}},sm=class Hl extends ut{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(e){super(),this.names=e,this.seen=new Set,this.finished=!1}fromCheckpoint(e){const n=new Hl(this.names);if(typeof e<"u"){const[r,s]=e;n.seen=new Set(r),n.finished=s}return n}update(e){let n=!1;for(const r of e)if(this.names.has(r)&&!this.seen.has(r))this.seen.add(r),n=!0;else if(!this.names.has(r))throw new B(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!wt(this.names,this.seen))throw new ee}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&wt(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&wt(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&wt(this.names,this.seen)}};const ps=Symbol.for("langgraph.state.state_schema");var ne=class{[ps]=!0;constructor(t){this.fields=t}getChannels(){const t={};for(const[e,n]of Object.entries(this.fields))if(Te.isInstance(n)){const r=Pt(n.valueSchema);t[e]=new Tr(n.reducer,r)}else if(mt.isInstance(n)){const r=n.schema?Pt(n.schema):void 0;t[e]=new nm({guard:n.guard,initialValueFactory:r})}else if(bn(n))t[e]=new Ur(Pt(n));else throw new Error(`Invalid state field "${e}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return t}getJsonSchema(){const t={},e=[];for(const[n,r]of Object.entries(this.fields)){let s;if(Te.isInstance(r)?(s=It(r.valueSchema),r.jsonSchemaExtra&&(s={...s??{},...r.jsonSchemaExtra})):mt.isInstance(r)?s=r.schema?It(r.schema):void 0:bn(r)&&(s=It(r)),s){t[n]=s;let o=!1;Te.isInstance(r)?o=Pt(r.valueSchema)!==void 0:mt.isInstance(r)?o=r.schema?Pt(r.schema)!==void 0:!1:o=Pt(r)!==void 0,o||e.push(n)}}return{type:"object",properties:t,required:e.length>0?e:void 0}}getInputJsonSchema(){const t={};for(const[e,n]of Object.entries(this.fields)){let r;Te.isInstance(n)?r=It(n.inputSchema):mt.isInstance(n)?r=n.schema?It(n.schema):void 0:bn(n)&&(r=It(n)),r&&(t[e]=r)}return{type:"object",properties:t}}getChannelKeys(){return Object.entries(this.fields).map(([t])=>t)}getAllKeys(){return Object.keys(this.fields)}async validateInput(t){if(t==null||typeof t!="object")return t;const e={};for(const[n,r]of Object.entries(t)){const s=this.fields[n];if(s===void 0){e[n]=r;continue}let o;if(Te.isInstance(s)?o=s.inputSchema:mt.isInstance(s)?o=s.schema:bn(s)&&(o=s),o){const i=await o["~standard"].validate(r);if(i.issues)throw new Error(`Validation failed for field "${n}": ${JSON.stringify(i.issues)}`);e[n]=i.value}else e[n]=r}return e}static isInstance(t){return typeof t=="object"&&t!==null&&ps in t&&t[ps]===!0}};const Wl="__remove_all__";function Mo(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(xn),o=r.map(xn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=wr(),u.lc_kwargs.id=u.id);let i;for(let u=0;u<o.length;u+=1){const d=o[u];(d.id===null||d.id===void 0)&&(d.id=wr(),d.lc_kwargs.id=d.id),bt.isInstance(d)&&d.id===Wl&&(i=u)}if(i!=null)return o.slice(i+1);const a=[...s],l=new Map(a.map((u,d)=>[u.id,d])),c=new Set;for(const u of o){const d=l.get(u.id);if(d!==void 0)bt.isInstance(u)?c.add(u.id):(c.delete(u.id),a[d]=u);else{if(bt.isInstance(u))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);l.set(u.id,a.length),a.push(u)}}return a.filter(u=>!c.has(u.id))}const om=no().default(()=>[]),im=no(),ms=new Te(om,{inputSchema:im,reducer:Mo,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}}),am="lg:";var lm=class{_map=new Map;_extensionCache=new Map;get(t){return this._map.get(t)}extend(t,e){const n=this.get(t);this._map.set(t,e(n))}remove(t){return this._map.delete(t),this}has(t){return this._map.has(t)}getChannelsForSchema(t){const e={},n=ks(t);for(const[r,s]of Object.entries(n)){const o=this.get(s);o?.reducer?e[r]=new Tr(o.reducer.fn,o.default):e[r]=new Ur(o?.default)}return e}getExtendedChannelSchemas(t,e){if(Object.keys(e).length===0)return t;const n=Object.entries(e).filter(([,o])=>o===!0).sort(([o],[i])=>o.localeCompare(i)).map(([o,i])=>`${o}:${i}`).join("|"),r=this._extensionCache.get(n)??new Map;if(r.has(t))return r.get(t);let s=t;if(e.withReducerSchema||e.withJsonSchemaExtrasAsDescription){const o=Object.entries(ks(t)).map(([i,a])=>{const l=this.get(a);let c=e.withReducerSchema?l?.reducer?.schema??a:a;if(e.withJsonSchemaExtrasAsDescription&&l?.jsonSchemaExtra){const u=Ts(c)??Ts(a),d=JSON.stringify({...l.jsonSchemaExtra,description:u});c=c.describe(`${am}${d}`)}return[i,c]});s=bu(t,Object.fromEntries(o)),_u(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=ro(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const ln=new lm;function Ks(t,e){if(e.reducer&&!e.default){const n=so(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return ln.extend(n,()=>e),n}else return ln.extend(t,()=>e),t}function Ot(t){return t==null?!1:!!(ne.isInstance(t)||te(t)||typeof t=="object"&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||fl(e)))}function cm(t){if(typeof t!="object"||t==null)return!1;const e=t,n="state"in e&&Ot(e.state),r="stateSchema"in e&&Ot(e.stateSchema),s="input"in e&&Ot(e.input);return!(!n&&!r&&!s||"input"in e&&e.input!=null&&!Ot(e.input)||"output"in e&&e.output!=null&&!Ot(e.output))}const ze="__root__",Ir=Symbol.for("langgraph.state.partial");var um=class extends em{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=ln;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){super();const n=this._normalizeToStateGraphInit(t,e),r=n.state??n.stateSchema??n.input;if(!r)throw new Yr;const s=this._getChannelsFromSchema(r);this._schemaDefinition=s,ne.isInstance(r)?this._schemaRuntimeDefinition=r:te(r)&&(this._schemaRuntimeDefinition=r),n.input?ne.isInstance(n.input)?this._inputRuntimeDefinition=n.input:te(n.input)?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=Ir:this._inputRuntimeDefinition=Ir,n.output?ne.isInstance(n.output)?this._outputRuntimeDefinition=n.output:te(n.output)?this._outputRuntimeDefinition=n.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;const o=n.input?this._getChannelsFromSchema(n.input):s,i=n.output?this._getChannelsFromSchema(n.output):s;this._inputDefinition=o,this._outputDefinition=i,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),n.context&&te(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.writer}_normalizeToStateGraphInit(t,e){if(cm(t)){if(te(e)||Ls.isInstance(e))return{...t,context:e};const n=e;return{...t,input:t.input??n?.input,output:t.output??n?.output,context:t.context??n?.context,interrupt:t.interrupt??n?.interrupt,writer:t.writer??n?.writer,nodes:t.nodes??n?.nodes}}if(Ot(t)){if(te(e)||Ls.isInstance(e))return{state:t,context:e};const n=e;return{state:t,input:n?.input,output:n?.output,context:n?.context,interrupt:n?.interrupt,writer:n?.writer,nodes:n?.nodes}}if(fm(t))return{state:hm(t.channels)};throw new Yr}_getChannelsFromSchema(t){if(ne.isInstance(t))return t.getChannels();if(te(t))return this._metaRegistry.getChannelsForSchema(t);if(typeof t=="object"&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot")return t.spec;if(typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)return t;throw new Yr("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([t,e])=>t.map(n=>[n,e]))])}_addSchema(t){if(!this._schemaDefinitions.has(t)){this._schemaDefinitions.set(t,t);for(const[e,n]of Object.entries(t)){let r;if(typeof n=="function"?r=n():r=n,this.channels[e]!==void 0){if(!this.channels[e].equals(r)&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${e}" already exists with a different type.`)}else this.channels[e]=r}}}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]).map(([r,s])=>[r,s]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,o]of n){if(r in this.channels)throw new Error(`${r} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const u of[Z,Ge])if(r.includes(u))throw new Error(`"${u}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===N||r===U)throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;o?.input!==void 0&&(i=this._getChannelsFromSchema(o.input)),this._addSchema(i);let a;ae.isRunnable(s)?a=s:typeof s=="function"?a=new Et({func:s,name:r,trace:!1}):a=en(s);let l=o?.cachePolicy;typeof l=="boolean"&&(l=l?{}:void 0);const c={runnable:a,retryPolicy:o?.retryPolicy,cachePolicy:l,metadata:o?.metadata,input:i??this._schemaDefinition,subgraphs:To(a)?[a]:o?.subgraphs,ends:o?.ends,defer:o?.defer};this.nodes[r]=c}return this}addEdge(t,e){if(typeof t=="string")return super.addEdge(t,e);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const n of t){if(n===N)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(r=>r===n))throw new Error(`Need to add a node named "${n}" first`)}if(e===N)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(n=>n===e))throw new Error(`Need to add a node named "${e}" first`);return this.waitingEdges.add([t,e]),this}addSequence(t){const e=Array.isArray(t)?t:Object.entries(t);if(e.length===0)throw new Error("Sequence requires at least one node.");let n;for(const[r,s,o]of e){if(r in this.nodes)throw new Error(`Node names must be unique: node with the name "${r}" already exists.`);const i=r;this.addNode(i,s,o),n!=null&&this.addEdge(n,i),n=i}return this}compile({checkpointer:t,store:e,cache:n,interruptBefore:r,interruptAfter:s,name:o,description:i}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(s)?s:[]]);const a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),l=a.length===1&&a[0]===ze?ze:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===ze?ze:c,d=this._interrupt,h=new dm({builder:this,checkpointer:t,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[U]:new an},inputChannels:U,outputChannels:l,streamChannels:u,streamMode:"updates",store:e,cache:n,name:o,description:i,userInterrupt:d});h.attachNode(U);for(const[f,m]of Object.entries(this.nodes))h.attachNode(f,m);h.attachBranch(U,ti,fi(),{withReader:!1});for(const[f]of Object.entries(this.nodes))h.attachBranch(f,ti,fi(),{withReader:!1});for(const[f,m]of this.edges)h.attachEdge(f,m);for(const[f,m]of this.waitingEdges)h.attachEdge(f,m);for(const[f,m]of Object.entries(this.branches))for(const[p,C]of Object.entries(m))h.attachBranch(f,p,C);return h.validate()}};function hm(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Fs(r);return e}var dm=class extends Vl{description;_metaRegistry=ln;constructor({description:t,...e}){super(e),this.description=t}attachNode(t,e){let n;t===U?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):n=Object.keys(this.builder.channels);function r(a){if(q(a))return a.graph===G.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(l=>q(l))){const l=[];for(const c of a)if(q(c)){if(c.graph===G.PARENT)continue;l.push(...c._updateAsTuples())}else l.push([ze,c]);return l}else if(a!=null)return[[ze,a]];return null}const s=t;function o(a){if(a){if(q(a))return a.graph===G.PARENT?null:a._updateAsTuples().filter(([l])=>n.includes(l));if(Array.isArray(a)&&a.length>0&&a.some(q)){const l=[];for(const c of a)if(q(c)){if(c.graph===G.PARENT)continue;l.push(...c._updateAsTuples().filter(([u])=>n.includes(u)))}else{const u=o(c);u&&l.push(...u??[])}return l}else{if(typeof a=="object"&&!Array.isArray(a))return Object.entries(a).filter(([l])=>n.includes(l));{const l=Array.isArray(a)?"array":typeof a;throw new B(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${l}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const i=[{value:St,mapper:new Et({func:n.length&&n[0]===ze?r:o,trace:!1,recurse:!1})}];if(t===U)this.nodes[t]=new Nn({tags:[Y],triggers:[U],channels:[U],writers:[new de(i,[Y])]});else{const a=e?.input??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(a)).map(d=>[d,d])),c=Object.keys(l).length===1&&ze in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new Nf:new an(!1),this.nodes[t]=new Nn({triggers:[u],channels:c?Object.keys(l):l,writers:[new de(i,[Y])],mapper:c?void 0:d=>Object.fromEntries(Object.entries(d).filter(([h])=>h in l)),bound:e?.runnable,metadata:e?.metadata,retryPolicy:e?.retryPolicy,cachePolicy:e?.cachePolicy,subgraphs:e?.subgraphs,ends:e?.ends})}}attachEdge(t,e){if(e!==N){if(typeof t=="string")this.nodes[t].writers.push(new de([{channel:`branch:to:${e}`,value:null}],[Y]));else if(Array.isArray(t)){const n=`join:${t.join("+")}:${e}`;this.channels[n]=this.builder.nodes[e].defer?new sm(new Set(t)):new rm(new Set(t)),this.nodes[e].triggers.push(n);for(const r of t)this.nodes[r].writers.push(new de([{channel:n,value:r}],[Y]))}}}attachBranch(t,e,n,r={withReader:!0}){const s=async(o,i)=>{const a=o.filter(c=>c!==N);if(!a.length)return;const l=a.map(c=>ye(c)?c:{channel:c===N?c:`branch:to:${c}`,value:t});await de.doWrite({...i,tags:(i.tags??[]).concat([Y])},l)};this.nodes[t].writers.push(n.run(s,r.withReader?o=>hp.doRead(o,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(t){if(t==null)return t;const e=this.builder._inputRuntimeDefinition,n=this.builder._schemaRuntimeDefinition;if(ne.isInstance(e)){if(q(t)){const s=t;return t.update&&(s.update=await e.validateInput(Array.isArray(t.update)?Object.fromEntries(t.update):t.update)),s}return await e.validateInput(t)}if(e===Ir&&ne.isInstance(n)){if(q(t)){const s=t;return t.update&&(s.update=await n.validateInput(Array.isArray(t.update)?Object.fromEntries(t.update):t.update)),s}return await n.validateInput(t)}const r=(()=>{const s=o=>{if(o!=null)return this._metaRegistry.getExtendedChannelSchemas(o,{withReducerSchema:!0})};if(te(e))return s(e);if(e===Ir)return te(n)?ro(s(n)):void 0})();if(q(t)){const s=t;return t.update&&r!=null&&(s.update=nt(r,t.update)),s}return r!=null?nt(r,t):t}isInterrupted(t){return wl(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return te(e)&&nt(e,t),t}};function fm(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function pm(t){if(ye(t))return[t];const e=[];q(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(q));const n=[];for(const r of e){if(r.graph===G.PARENT)throw new Qi(r);ye(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function fi(){return new Ul({path:new Et({func:pm,tags:[Y],trace:!1,recurse:!1,name:"<control_branch>"})})}Ds.Root({messages:Ds({reducer:Mo,default:()=>[]})});const mm={reducer:{fn:Mo},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};K({messages:Ks(Le(),mm)});Ah();var Js=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},qs=class extends Error{toolNames;constructor(t){super(`The model has called multiple tools: ${t.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=t}},Gl=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(n=>`
46
+ `))};try{for await(const s of t){const[o,i,a]=s;let l=a;if(i==="debug"){const c=a;c.type==="checkpoint"&&(l={...c,payload:ci(c.payload)})}i==="checkpoints"&&(l=ci(a)),r({event:o?.length?`${i}|${o.join("|")}`:i,data:l})}}catch(s){r({event:"error",data:Np(s)})}n.close()}})}const qn=Symbol.for("INPUT_DONE"),hs=Symbol.for("INPUT_RESUMING"),$p=25;function jp(...t){return new Rl({passthroughFn:e=>{for(const n of t)n.modes.has(e[1])&&n.push(e)},modes:new Set(t.flatMap(e=>Array.from(e.modes)))})}var Lp=class extends Pf{cache;queue=Promise.resolve();constructor(t){super(),this.cache=t}async get(t){return this.enqueueOperation("get",t)}async set(t){return this.enqueueOperation("set",t)}async clear(t){return this.enqueueOperation("clear",t)}async stop(){await this.queue}enqueueOperation(t,...e){const n=this.queue.then(()=>this.cache[t](...e));return this.queue=n.then(()=>{},()=>{}),n}},Dp=class $l{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";tasks={};stream;checkpointerPromises=[];isNested;_checkpointerChainedPromise=Promise.resolve();store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let e=!1;if(U in this.checkpoint.channel_versions)e=!0;else for(const a in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,a)){e=!0;break}const n=this.config.configurable?.[Ye]!==void 0&&this.config.configurable?.[Ye],r=this.input===null||this.input===void 0,s=q(this.input)&&this.input.resume!=null,o=this.input===hs,i=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return e&&(n||r||s||o||i)}constructor(e){this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=_p,this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.manager=e.manager,this.outputKeys=e.outputKeys,this.streamKeys=e.streamKeys,this.nodes=e.nodes,this.skipDoneTasks=e.skipDoneTasks,this.store=e.store,this.cache=e.cache?new Lp(e.cache):void 0,this.stream=e.stream,this.checkpointNamespace=e.checkpointNamespace,this.prevCheckpointConfig=e.prevCheckpointConfig,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.durability=e.durability,this.debug=e.debug,this.triggerToNodes=e.triggerToNodes}static async initialize(e){let{config:n,stream:r}=e;r!==void 0&&n.configurable?.[Er]!==void 0&&(r=jp(r,n.configurable[Er]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,o=n.configurable?.[ot];n.configurable&&o&&(o.subgraphCounter>0&&(n=Ee(n,{[Ne]:[n.configurable[Ne],o.subgraphCounter.toString()].join(Z)})),o.subgraphCounter+=1);const i=vt in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Ee(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[Ce]!==void 0&&n.configurable?.[Ce]?.[n.configurable?.checkpoint_ns]&&(a=Ee(n,{checkpoint_id:n.configurable[Ce][n.configurable?.checkpoint_ns]}));const l=n.configurable?.checkpoint_ns?.split(Z)??[],c=await e.checkpointer?.getTuple(a)??{config:n,checkpoint:hl(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...n,...c.config,configurable:{checkpoint_ns:"",...n.configurable,...c.config.configurable}};const u=c.parentConfig,d=Cr(c.checkpoint),h={...c.metadata},f=c.pendingWrites??[],m=Tr(e.channelSpecs,d),p=(h.step??0)+1,C=p+(n.recursionLimit??$p)+1,T={...d.channel_versions},k=e.store?new If(e.store):void 0;return k&&await k.start(),new $l({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:d,checkpointMetadata:h,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:l,channels:m,isNested:i,manager:e.manager,skipDoneTasks:s,step:p,stop:C,checkpointPreviousVersions:T,checkpointPendingWrites:f,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:k,cache:e.cache,interruptAfter:e.interruptAfter,interruptBefore:e.interruptBefore,durability:e.durability,debug:e.debug,triggerToNodes:e.triggerToNodes})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(e,n){let r=n;if(r.length===0)return;r.every(([l])=>l in Ef)&&(r=Array.from(new Map(r.map(l=>[l[0],l])).values()));let s=!1;for(const l in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,l)&&this.channels[l].lc_graph_name==="UntrackedValue"){s=!0;break}let o=r;s&&(o=r.filter(([l])=>{const c=this.channels[l];return!c||c.lc_graph_name!=="UntrackedValue"}).map(([l,c])=>l===Se&&ye(c)?[l,Ep(c,this.channels)]:[l,c])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(l=>l[0]!==e);for(const[l,c]of o)this.checkpointPendingWrites.push([e,l,c]);const i=Ee(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??"",[Us]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(i,o,e)),this.tasks&&this._outputWrites(e,r),!n.length||!this.cache||!this.tasks)return;const a=this.tasks[e];a==null||a.cache_key==null||n[0][0]===pe||n[0][0]===D||this.cache.set([{key:[a.cache_key.ns,a.cache_key.key],value:a.writes,ttl:a.cache_key.ttl}])}_outputWrites(e,n,r=!1){const s=this.tasks[e];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes(Y))return;if(n.length>0)if(n[0][0]===D){if(s.path?.[0]===_e&&s.path?.[s.path.length-1]===!0)return;const o=n.filter(i=>i[0]===D).flatMap(i=>i[1]);this._emit([["updates",{[D]:o}],["values",{[D]:o}]])}else n[0][0]!==pe&&this._emit(yn(qe(pp(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(yn(qe(Mp([[s,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const e=[],n=([i,a])=>`ns:${i.join(",")}|key:${a}`,r=[],s={};for(const i of Object.values(this.tasks))i.cache_key!=null&&!i.writes.length&&(r.push([i.cache_key.ns,i.cache_key.key]),s[n([i.cache_key.ns,i.cache_key.key])]=i);if(r.length===0)return[];const o=await this.cache.get(r);for(const{key:i,value:a}of o){const l=s[n(i)];l!=null&&(l.writes.push(...a),e.push({task:l,result:a}))}return e}async tick(e){this.store&&!this.store.isRunning&&await this.store?.start();const{inputKeys:n=[]}=e;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![qn,hs].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new Lt;if(Object.values(this.tasks).every(s=>s.writes.length>0)){const s=Object.values(this.tasks).flatMap(i=>i.writes);this.updatedChannels=be(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const o=await Ze(qe(as(this.outputKeys,s,this.channels),"values"));if(this._emit(o),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),Jn(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new Lt;this.config.configurable?.[Ye]!==void 0&&delete this.config.configurable?.[Ye]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;if(this.tasks=jt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels}),this.checkpointer&&this._emit(await Ze(qe(Ap(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[s,o,i]of this.checkpointPendingWrites){if(o===pe||o===D||o===me)continue;const a=Object.values(this.tasks).find(l=>l.id===s);a&&a.writes.push([o,i])}for(const s of Object.values(this.tasks))s.writes.length>0&&this._outputWrites(s.id,s.writes,!0)}if(Object.values(this.tasks).every(s=>s.writes.length>0))return this.tick({inputKeys:n});if(Jn(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new Lt;const r=await Ze(qe(ii(Object.values(this.tasks)),"tasks"));return this._emit(r),!0}async finishAndHandleError(e){this.durability==="exit"&&(!this.isNested||typeof e<"u"||this.checkpointNamespace.every(r=>!r.includes(Ge)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=Tt(this.channels,this.outputKeys)),n&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(r=>r.writes.length>0)&&(this.updatedChannels=be(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(yn(qe(as(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),yt(e)&&!e.interrupts.length&&this._emit([["updates",{[D]:[]}],["values",{[D]:[]}]])),n}async acceptPush(e,n,r){if(this.interruptAfter?.length>0&&Jn(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=Ws([_e,e.path??[],n,e.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!s)return;if(this.interruptBefore?.length>0&&Jn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(yn(qe(ii([s]),"tasks"))),this.debug&&Nl(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});const o=await this._matchCachedWrites();for(const{task:i}of o)this._outputWrites(i.id,i.writes,!0);return s}_suppressInterrupt(e){return yt(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,r=n?.[ot];if(r&&r.nullResume!==void 0&&this.putWrites(Te,[[me,r.nullResume]]),q(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(El)&&(this.config.configurable??={},this.config.configurable[lr]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of fp(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new Jo("Received empty Command input");for(const[l,c]of Object.entries(a))this.putWrites(l,c)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===Te).map(i=>i.slice(1));s.length>0&&be(this.checkpoint,this.channels,[{name:Ve,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const o=q(this.input)&&s.length>0;if(this.isResuming||o){for(const a in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,a)&&this.checkpoint.channel_versions[a]!==void 0){const l=this.checkpoint.channel_versions[a];this.checkpoint.versions_seen[D]={...this.checkpoint.versions_seen[D],[a]:l}}const i=await Ze(qe(as(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=hs;else if(o)await this._putCheckpoint({source:"input"}),this.input=qn;else{const i=await Ze(Il(e,this.input));if(i.length>0){const a=jt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=be(this.checkpoint,this.channels,Object.values(a).concat([{name:Ve,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=qn}else if(Ye in(this.config.configurable??{}))this.input=qn;else throw new Jo(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=Ee(this.config,{[Ye]:this.isResuming}))}_emit(e){for(const[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){const s=n==="checkpoints"?this.step-1:this.step,o=new Date().toISOString(),i=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:i,timestamp:o,payload:r}])}}_putCheckpoint(e){const n=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=o=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Ee(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},a=fr(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:Cr(o),metadata:{...this.checkpointMetadata},newVersions:a}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};n||(this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.[Ce]??{}}),this.checkpoint=pt(this.checkpoint,r?this.channels:void 0,this.step,n?{id:this.checkpoint.id}:void 0),r&&s(this.checkpoint),n||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;const e=Ee(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??"",[Us]:this.checkpoint.id}),n={};for(const[r,s,o]of this.checkpointPendingWrites)n[r]??=[],n[r].push([s,o]);for(const[r,s]of Object.entries(n))this.checkpointerPromises.push(this.checkpointer.putWrites(e,s,r))}_matchWrites(e){for(const[n,r,s]of this.checkpointPendingWrites){if(r===pe||r===D||r===me)continue;const o=Object.values(e).find(i=>i.id===n);o&&o.writes.push([r,s])}for(const n of Object.values(e))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}};function Fp(t){return Ue(t?.message)}var Up=class extends gu{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(t){super(),this.streamFn=t}_emit(t,e,n,r=!1){if(r&&e.id!==void 0&&this.seen[e.id]!==void 0)return;let s=e.id;n!=null&&(yu(e)?s??=`run-${n}-tool-${e.tool_call_id}`:((s==null||s===`run-${n}`)&&(s=this.stableMessageIdMap[n]??s??`run-${n}`),this.stableMessageIdMap[n]??=s)),s!==e.id&&(e.id=s,e.lc_kwargs.id=s),e.id!=null&&(this.seen[e.id]=e),this.streamFn([t[0],"messages",[e,t[1]]])}handleChatModelStart(t,e,n,r,s,o,i,a){i&&(!o||!o.includes(Lf)&&!o.includes("nostream"))&&(this.metadatas[n]=[i.langgraph_checkpoint_ns.split("|"),{tags:o,name:a,...i}])}handleLLMNewToken(t,e,n,r,s,o){const i=o?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(Fp(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new Qt({content:t}),n))}handleLLMEnd(t,e){if(this.metadatas[e]!==void 0){if(!this.emittedChatModelRunIds[e]){const n=t.generations?.[0]?.[0];Ue(n?.message)&&this._emit(this.metadatas[e],n?.message,e,!0),delete this.emittedChatModelRunIds[e]}delete this.metadatas[e],delete this.stableMessageIdMap[e]}}handleLLMError(t,e){delete this.metadatas[e]}handleChainStart(t,e,n,r,s,o,i,a){if(o!==void 0&&a===o.langgraph_node&&(s===void 0||!s.includes(Y))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...o}],typeof e=="object")){for(const l of Object.values(e))if((Ue(l)||Fo(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(Ue(c)||Fo(c))&&c.id!==void 0&&(this.seen[c.id]=c)}}handleChainEnd(t,e){const n=this.metadatas[e];if(delete this.metadatas[e],n!==void 0){if(Ue(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)Ue(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(Ue(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)Ue(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const Vp=500,Bp=2,zp=128e3,Hp=3,Wp=[400,401,402,403,404,405,406,407,409],Gp=t=>{if(t.message.startsWith("Cancel")||t.message.startsWith("AbortError")||t.name==="AbortError"||t.name==="GraphValueError"||t?.code==="ECONNABORTED")return!1;const e=t?.response?.status??t?.status;return!(e&&Wp.includes(+e)||t?.error?.code==="insufficient_quota")};async function jl(t,e,n,r){const s=t.retry_policy??e;let o=s!==void 0?s.initialInterval??Vp:0,i=0,a,l,{config:c}=t;for(n&&(c=Ee(c,n)),c={...c,signal:r};!r?.aborted;){t.writes.splice(0,t.writes.length),a=void 0;try{l=await t.proc.invoke(t.input,c);break}catch(u){if(a=u,a.pregelTaskId=t.id,Ph(a)){const f=c?.configurable?.checkpoint_ns,m=a.command;if(m.graph===f){for(const p of t.writers)await p.invoke(m,c);a=void 0;break}else if(m.graph===G.PARENT){const p=Hf(f);a.command=new G({...a.command,graph:p})}}if(Sn(a)||s===void 0||(i+=1,i>=(s.maxAttempts??Hp))||!(s.retryOn??Gp)(a))break;o=Math.min(s.maxInterval??zp,o*(s.backoffFactor??Bp));const d=s.jitter?Math.floor(o+Math.random()*1e3):o;await new Promise(f=>setTimeout(f,d));const h=a.name??a.constructor.unminifiable_name??a.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(t.name)}" after ${o.toFixed(2)}ms (attempt ${i}) after ${h}: ${a}`),c=Ee(c,{[Ye]:!0})}}return{task:t,result:l,error:a,signalAborted:r?.aborted}}const Gs=Symbol.for("promiseAdded");function Kp(){const t={next:()=>{},wait:Promise.resolve(Gs)};function e(n){t.next=()=>{t.wait=new Promise(e),n(Gs)}}return t.wait=new Promise(e),t}var Jp=class{nodeFinished;loop;constructor({loop:t,nodeFinished:e}){this.loop=t,this.nodeFinished=e}async tick(t={}){const{timeout:e,retryPolicy:n,onStepWrite:r,maxConcurrency:s}=t,o=new Set;let i;const a=new AbortController,l=a.signal,c=e?AbortSignal.timeout(e):void 0,u=Object.values(this.loop.tasks).filter(m=>m.writes.length===0),{signals:d,disposeCombinedSignal:h}=this._initializeAbortSignals({exceptionSignal:l,stepTimeoutSignal:c,signal:t.signal}),f=this._executeTasksWithRetry(u,{signals:d,retryPolicy:n,maxConcurrency:s});for await(const{task:m,error:p,signalAborted:C}of f)this._commit(m,p),yt(p)||Sn(p)&&!yt(i)?i=p:p&&(o.size===0||!C)&&(a.abort(),o.add(p));if(h?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(m=>m.writes).flat()),o.size===1)throw Array.from(o)[0];if(o.size>1)throw new AggregateError(Array.from(o),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(yt(i)||Sn(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[ei]??{},s=r.externalAbortSignal??n,o=e??r.timeoutAbortSignal,{signal:i,dispose:a}=Ar(s,o,t),l={externalAbortSignal:s,timeoutAbortSignal:o,composedAbortSignal:i};return this.loop.config=Ee(this.loop.config,{[ei]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},o=Kp(),i={},a={executingTasksMap:i,barrier:o,retryPolicy:n,scheduleTask:async(h,f,m)=>this.loop.acceptPush(h,f,m)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let l=0,c;const u=Ar(s?.externalAbortSignal,s?.timeoutAbortSignal),d=u.signal?new Promise((h,f)=>{c=()=>f(new Error("Abort")),u.signal?.addEventListener("abort",c,{once:!0})}):void 0;for(;(l===0||Object.keys(i).length>0)&&t.length;){for(;Object.values(i).length<(r??t.length)&&l<t.length;l+=1){const f=t[l];i[f.id]=jl(f,n,{[So]:Ll?.bind(a,this,f)},s?.composedAbortSignal).catch(m=>({task:f,error:m,signalAborted:s?.composedAbortSignal?.aborted}))}const h=await Promise.race([...Object.values(i),...d?[d]:[],o.wait]);h!==Gs&&(yield h,c!=null&&(u.signal?.removeEventListener("abort",c),u.dispose?.()),delete i[h.task.id])}}_commit(t,e){if(e!==void 0)if(yt(e)){if(e.interrupts.length){const n=e.interrupts.map(s=>[D,s]),r=t.writes.filter(s=>s[0]===me);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else Sn(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[pe,{message:e.message,name:e.name}]]);else this.nodeFinished&&(t.config?.tags==null||!t.config.tags.includes(Y))&&this.nodeFinished(String(t.name)),t.writes.length===0&&t.writes.push([Co,null]),this.loop.putWrites(t.id,t.writes)}};async function Ll(t,e,n,r,s,o={}){const i=e.config?.configurable?.[ot];if(!i)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const a=i.callCounter;i.callCounter+=1;const l=new yp({func:n,name:r,input:s,cache:o.cache,retry:o.retry,callbacks:o.callbacks}),c=await this.scheduleTask(e,a,l);if(!c)return;const u=this.executingTasksMap[c.id];if(u!==void 0)return u;if(c.writes.length>0){const d=c.writes.filter(([f])=>f===sn),h=c.writes.filter(([f])=>f===pe);if(d.length>0){if(d.length===1)return Promise.resolve(d[0][1]);throw new Error(`BUG: multiple returns found for task ${c.name}__${c.id}`)}if(h.length>0){if(h.length===1){const f=h[0][1],m=f instanceof Error?f:new Error(String(f));return Promise.reject(m)}throw new Error(`BUG: multiple errors found for task ${c.name}__${c.id}`)}return}else{const d=jl(c,o.retry,{[So]:Ll.bind(this,t,c)});return this.executingTasksMap[c.id]=d,this.barrier.next(),d.then(({result:h,error:f})=>f?Promise.reject(f):h)}}var Fe=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function qp({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:o,interruptBeforeNodes:i}){if(!e)throw new Fe("Channels not provided");const a=new Set,l=new Set;for(const[c,u]of Object.entries(t)){if(c===D)throw new Fe(`"Node name ${D} is reserved"`);if(u.constructor===Nn)u.triggers.forEach(d=>a.add(d));else throw new Fe(`Invalid node type ${typeof u}, expected PregelNode`)}for(const c of a)if(!(c in e))throw new Fe(`Subscribed channel '${String(c)}' not in channels`);if(Array.isArray(n)){if(n.every(c=>!a.has(c)))throw new Fe(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new Fe(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(c=>l.add(c)):l.add(r),s&&!Array.isArray(s)?l.add(s):Array.isArray(s)&&s.forEach(c=>l.add(c));for(const c of l)if(!(c in e))throw new Fe(`Output channel '${String(c)}' not in channels`);if(o&&o!=="*"){for(const c of o)if(!(c in t))throw new Fe(`Node ${String(c)} not in nodes`)}if(i&&i!=="*"){for(const c of i)if(!(c in t))throw new Fe(`Node ${String(c)} not in nodes`)}}function ui(t,e){if(Array.isArray(t)){for(const n of t)if(!(n in e))throw new Error(`Key ${String(n)} not found in channels`)}else if(!(t in e))throw new Error(`Key ${String(t)} not found in channels`)}var Yp=class Dl extends ut{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(e){super(),this.unique=e?.unique??this.unique,this.accumulate=e?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(e){const n=new Dl({unique:this.unique,accumulate:this.accumulate});return typeof e<"u"&&(n.seen=new Set(e[0]),n.values=e[1]),n}update(e){let n=!1;this.accumulate||(n=this.values.length>0,this.values=[]);const r=e.flat();if(r.length>0)if(this.unique)for(const s of r)this.seen.has(s)||(n=!0,this.seen.add(s),this.values.push(s));else n=!0,this.values.push(...r);return n}get(){if(this.values.length===0)throw new ee;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},Xp=class{static subscribeTo(t,e){const{key:n,tags:r}={key:void 0,tags:void 0,...e??{}};if(Array.isArray(t)&&n!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;return typeof t=="string"?n?s={[n]:t}:s=[t]:s=Object.fromEntries(t.map(o=>[o,o])),new Nn({channels:s,triggers:Array.isArray(t)?t:[t],tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:St,skipNone:!1});for(const[r,s]of Object.entries(e??{}))ae.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:St,skipNone:!0,mapper:en(s)}):n.push({channel:r,value:s,skipNone:!1});return new de(n)}},Zp=class extends ae{lc_namespace=["langgraph","pregel"];invoke(t,e){throw new Error("Not implemented")}withConfig(t){return super.withConfig(t)}stream(t,e){return super.stream(t,e)}},Qp=class extends Zp{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(t){super(t);let{streamMode:e}=t;if(e!=null&&!Array.isArray(e)&&(e=[e]),this.nodes=t.nodes,this.channels=t.channels,Se in this.channels&&"lc_graph_name"in this.channels[Se]&&this.channels[Se].lc_graph_name!=="Topic")throw new Error(`Channel '${Se}' is reserved and cannot be used in the graph.`);this.channels[Se]=new Yp({accumulate:!1}),this.autoValidate=t.autoValidate??this.autoValidate,this.streamMode=e??this.streamMode,this.inputChannels=t.inputChannels,this.outputChannels=t.outputChannels,this.streamChannels=t.streamChannels??this.streamChannels,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.stepTimeout=t.stepTimeout??this.stepTimeout,this.debug=t.debug??this.debug,this.checkpointer=t.checkpointer,this.retryPolicy=t.retryPolicy,this.config=t.config,this.store=t.store,this.cache=t.cache,this.name=t.name,this.triggerToNodes=t.triggerToNodes??this.triggerToNodes,this.userInterrupt=t.userInterrupt,this.autoValidate&&this.validate()}withConfig(t){const e=$e(this.config,t);return new this.constructor({...this,config:e})}validate(){qp({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(const[t,e]of Object.entries(this.nodes))for(const n of e.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(t);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(t){return this.getGraph(t)}*getSubgraphs(t,e){for(const[n,r]of Object.entries(this.nodes)){if(t!==void 0&&!t.startsWith(n))continue;const s=r.subgraphs?.length?r.subgraphs:[r.bound];for(const o of s){const i=Al(o);if(i!==void 0){if(n===t){yield[n,i];return}if(t===void 0&&(yield[n,i]),e){let a=t;t!==void 0&&(a=t.slice(n.length+1));for(const[l,c]of i.getSubgraphs(a,e))yield[`${n}${Z}${l}`,c]}}}}}async*getSubgraphsAsync(t,e){yield*this.getSubgraphs(t,e)}async _prepareStateSnapshot({config:t,saved:e,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(e===void 0)return{values:{},next:[],config:t,tasks:[]};const s=Tr(this.channels,e.checkpoint);if(e.pendingWrites?.length){const d=e.pendingWrites.filter(([h,f])=>h===Te).map(([h,f,m])=>[String(f),m]);d.length>0&&be(e.checkpoint,s,[{name:Ve,writes:d,triggers:[]}],void 0,this.triggerToNodes)}const o=Object.values(jt(e.checkpoint,e.pendingWrites,this.nodes,s,e.config,!0,{step:(e.metadata?.step??-1)+1,store:this.store})),i=await Ze(this.getSubgraphsAsync()),a=e.config.configurable?.checkpoint_ns??"",l={};for(const d of o){const h=i.find(([m])=>m===d.name);if(!h)continue;let f=`${String(d.name)}${Ge}${d.id}`;if(a&&(f=`${a}${Z}${f}`),n===void 0){const m={configurable:{thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}};l[d.id]=m}else{const m={configurable:{[J]:n,thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}},p=h[1];l[d.id]=await p.getState(m,{subgraphs:!0})}}if(r&&e.pendingWrites?.length){const d=Object.fromEntries(o.map(f=>[f.id,f]));for(const[f,m,p]of e.pendingWrites)[pe,D,nr].includes(m)||f in d&&d[f].writes.push([String(m),p]);const h=o.filter(f=>f.writes.length>0);h.length>0&&be(e.checkpoint,s,h,void 0,this.triggerToNodes)}let c=e?.metadata;c&&e?.config?.configurable?.thread_id&&(c={...c,thread_id:e.config.configurable.thread_id});const u=o.filter(d=>d.writes.length===0).map(d=>d.name);return{values:Tt(s,this.streamChannelsAsIs),next:u,tasks:Ol(o,e?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:c,config:dt(e.config,e.metadata),createdAt:e.checkpoint.ts,parentConfig:e.parentConfig}}async getState(t,e){const n=t.configurable?.[J]??this.checkpointer;if(!n)throw new tr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[J]===void 0){const i=ss(r);for await(const[a,l]of this.getSubgraphsAsync(i,!0))if(a===i)return await l.getState(Mt(t,{[J]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${i}" not found.`)}const s=$e(this.config,t),o=await n.getTuple(t);return await this._prepareStateSnapshot({config:s,saved:o,subgraphCheckpointer:e?.subgraphs?n:void 0,applyPendingWrites:!t.configurable?.checkpoint_id})}async*getStateHistory(t,e){const n=t.configurable?.[J]??this.checkpointer;if(!n)throw new tr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[J]===void 0){const o=ss(r);for await(const[i,a]of this.getSubgraphsAsync(o,!0))if(i===o){yield*a.getStateHistory(Mt(t,{[J]:n}),e);return}throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=$e(this.config,t,{configurable:{checkpoint_ns:r}});for await(const o of n.list(s,e))yield this._prepareStateSnapshot({config:o.config,saved:o})}async bulkUpdateState(t,e){const n=t.configurable?.[J]??this.checkpointer;if(!n)throw new tr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(e.length===0)throw new Error("No supersteps provided");if(e.some(i=>i.updates.length===0))throw new Error("No updates provided");const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[J]===void 0){const i=ss(r);for await(const[,a]of this.getSubgraphsAsync(i,!0))return await a.bulkUpdateState(Mt(t,{[J]:n}),e);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,a)=>{const l=this.config?$e(this.config,i):i,c=await n.getTuple(l),u=c!==void 0?Cr(c.checkpoint):hl(),d={...c?.checkpoint.channel_versions},h=c?.metadata?.step??-1;let f=Mt(l,{checkpoint_ns:l.configurable?.checkpoint_ns??""}),m=l.metadata??{};c?.config.configurable&&(f=Mt(l,c.config.configurable),m={...c.metadata,...m});const{values:p,asNode:C}=a[0];if(p==null&&C===void 0){if(a.length>1)throw new B("Cannot create empty checkpoint with multiple updates");return dt(await n.put(f,pt(u,void 0,h),{source:"update",step:h+1,parents:c?.metadata?.parents??{}},{}),c?c.metadata:void 0)}const T=Tr(this.channels,u);if(p===null&&C===N){if(a.length>1)throw new B("Cannot apply multiple updates when clearing state");if(c){const w=jt(u,c.pendingWrites||[],this.nodes,T,c.config,!0,{step:(c.metadata?.step??-1)+1,checkpointer:n,store:this.store}),b=(c.pendingWrites||[]).filter(E=>E[0]===Te).map(E=>E.slice(1));b.length>0&&be(u,T,[{name:Ve,writes:b,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[E,S,x]of c.pendingWrites||[])[pe,D,nr].includes(S)||E in w&&w[E].writes.push([S,x]);be(u,T,Object.values(w),n.getNextVersion.bind(n),this.triggerToNodes)}return dt(await n.put(f,pt(u,T,h),{...m,source:"update",step:h+1,parents:c?.metadata?.parents??{}},fr(d,u.channel_versions)),c?c.metadata:void 0)}if(C===Rf){if(a.length>1)throw new B("Cannot copy checkpoint with multiple updates");if(c==null)throw new B("Cannot copy a non-existent checkpoint");const w=S=>!Array.isArray(S)||S.length===0?!1:S.every(x=>Array.isArray(x)&&x.length===2),b=pt(u,void 0,h),E=await n.put(c.parentConfig??Mt(c.config,{checkpoint_id:void 0}),b,{source:"fork",step:h+1,parents:c.metadata?.parents??{}},{});if(w(p)){const S=jt(b,c.pendingWrites,this.nodes,T,E,!1,{step:h+2}),x=Object.values(S).reduce((O,{name:F,id:ce})=>(O[F]??=[],O[F].push({id:ce}),O),{}),I=p.reduce((O,F)=>{const[ce,Ie]=F;O[Ie]??=[];const we=O[Ie].length,ht=x[Ie]?.[we]?.id;return O[Ie].push({values:ce,asNode:Ie,taskId:ht}),O},{});return s(dt(E,c.metadata),Object.values(I).flat())}return dt(E,c.metadata)}if(C===Ve){if(a.length>1)throw new B("Cannot apply multiple updates when updating as input");const w=await Ze(Il(this.inputChannels,p));if(w.length===0)throw new B(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);be(u,T,[{name:Ve,writes:w,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const b=c?.metadata?.step!=null?c.metadata.step+1:-1,E=await n.put(f,pt(u,T,b),{source:"input",step:b,parents:c?.metadata?.parents??{}},fr(d,u.channel_versions));return await n.putWrites(E,w,Nt(Ve,u.id)),dt(E,c?c.metadata:void 0)}if(l.configurable?.checkpoint_id===void 0&&c?.pendingWrites!==void 0&&c.pendingWrites.length>0){const w=jt(u,c.pendingWrites,this.nodes,T,c.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(c.metadata?.step??-1)+1}),b=(c.pendingWrites??[]).filter(S=>S[0]===Te).map(S=>S.slice(1));b.length>0&&be(c.checkpoint,T,[{name:Ve,writes:b,triggers:[]}],void 0,this.triggerToNodes);for(const[S,x,I]of c.pendingWrites)[pe,D,nr].includes(x)||w[S]===void 0||w[S].writes.push([x,I]);const E=Object.values(w).filter(S=>S.writes.length>0);E.length>0&&be(u,T,E,void 0,this.triggerToNodes)}const k=Object.values(u.versions_seen).map(w=>Object.values(w)).flat().find(w=>!!w),_=[];if(a.length===1){let{values:w,asNode:b,taskId:E}=a[0];if(b===void 0&&Object.keys(this.nodes).length===1)[b]=Object.keys(this.nodes);else if(b===void 0&&k===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(b=this.inputChannels);else if(b===void 0){const S=Object.entries(u.versions_seen).map(([x,I])=>Object.values(I).map(O=>[O,x])).flat().filter(([x,I])=>I!==D).sort(([x],[I])=>dl(x,I));S&&(S.length===1?b=S[0][1]:S[S.length-1][0]!==S[S.length-2][0]&&(b=S[S.length-1][1]))}if(b===void 0)throw new B('Ambiguous update, specify "asNode"');_.push({values:w,asNode:b,taskId:E})}else for(const{asNode:w,values:b,taskId:E}of a){if(w==null)throw new B('"asNode" is required when applying multiple updates');_.push({values:b,asNode:w,taskId:E})}const g=[];for(const{asNode:w,values:b,taskId:E}of _){if(this.nodes[w]===void 0)throw new B(`Node "${w.toString()}" does not exist`);const S=this.nodes[w].getWriters();if(!S.length)throw new B(`No writers found for node "${w.toString()}"`);g.push({name:w,input:b,proc:S.length>1?it.from(S,{omitSequenceTags:!0}):S[0],writes:[],triggers:[D],id:E??Nt(D,u.id),writers:[]})}for(const w of g)await w.proc.invoke(w.input,vn({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[st]:b=>w.writes.push(...b),[vt]:(b,E=!1)=>pr(u,T,w,b,E)}}));for(const w of g){const b=w.writes.filter(E=>E[0]!==_e);c!==void 0&&b.length>0&&await n.putWrites(f,b,w.id)}be(u,T,g,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const v=fr(d,u.channel_versions),M=await n.put(f,pt(u,T,h+1),{source:"update",step:h+1,parents:c?.metadata?.parents??{}},v);for(const w of g){const b=w.writes.filter(E=>E[0]===_e);b.length>0&&await n.putWrites(M,b,w.id)}return dt(M,c?c.metadata:void 0)};let o=t;for(const{updates:i}of e)o=await s(o,i);return o}async updateState(t,e,n){return this.bulkUpdateState(t,[{updates:[{values:e,asNode:n}]}])}_defaults(t){const{debug:e,streamMode:n,inputKeys:r,outputKeys:s,interruptAfter:o,interruptBefore:i,...a}=t;let l=!0;const c=e!==void 0?e:this.debug;let u=s;u===void 0?u=this.streamChannelsAsIs:ui(u,this.channels);let d=r;d===void 0?d=this.inputChannels:ui(d,this.channels);const h=i??this.interruptBefore??[],f=o??this.interruptAfter??[];let m;n!==void 0?(m=Array.isArray(n)?n:[n],l=typeof n=="string"):(t.configurable?.[Cn]!==void 0?m=["values"]:m=this.streamMode,l=!0);let p;if(this.checkpointer===!1)p=void 0;else if(t!==void 0&&t.configurable?.[J]!==void 0)p=t.configurable[J];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");p=this.checkpointer}const C=t.store??this.store,T=t.cache??this.cache;if(t.durability!=null&&t.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");const k=(()=>{if(t.checkpointDuring!=null)return t.checkpointDuring===!1?"exit":"async"})(),_=t.durability??k??t?.configurable?.[yl]??"async";return[c,m,d,u,a,h,f,p,C,l,T,_]}async stream(t,e){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...e,signal:Ar(e?.signal,n.signal).signal},s=await super.stream(t,r);return new ai(e?.encoding==="text/event-stream"?Rp(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:gp(this.config?.callbacks,e?.callbacks),signal:Ar(e?.signal,r.signal).signal};return new ai(super.streamEvents(t,s,n),r)}async _validateInput(t){return t}async _validateContext(t){return t}async*_streamIterator(t,e){const n="version"in(e??{})?void 0:e?.encoding??void 0,r=e?.subgraphs,s=bl(this.config,e);if(s.recursionLimit===void 0||s.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&s.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const o=await this._validateInput(t),{runId:i,...a}=s,[l,c,,u,d,h,f,m,p,C,T,k]=this._defaults(a);typeof d.context<"u"?d.context=await this._validateContext(d.context):d.configurable=await this._validateContext(d.configurable);const _=new Rl({modes:new Set(c)});if(this.checkpointer===!0){d.configurable??={};const S=d.configurable[Ne]??"";d.configurable[Ne]=S.split(Z).map(x=>x.split(Ge)[0]).join(Z)}if(c.includes("messages")){const S=new Up(I=>_.push(I)),{callbacks:x}=d;if(x===void 0)d.callbacks=[S];else if(Array.isArray(x))d.callbacks=x.concat(S);else{const I=x.copy();I.addHandler(S,!0),d.callbacks=I}}d.writer??=S=>{if(!c.includes("custom"))return;const x=zf()?.configurable?.[Ne]?.split(Z).slice(0,-1);_.push([x??[],"custom",S])},d.interrupt??=this.userInterrupt??xl;const g=await(await wu(d))?.handleChainStart(this.toJSON(),mp(t,"input"),i,void 0,void 0,void 0,d?.runName??this.getName()),v=vo(this.channels);let M,w;const E=(async()=>{try{M=await Dp.initialize({input:o,config:d,checkpointer:m,nodes:this.nodes,channelSpecs:v,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:p,cache:T,stream:_,interruptAfter:f,interruptBefore:h,manager:g,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:k});const S=new Jp({loop:M,nodeFinished:d.configurable?.[jf]});e?.subgraphs&&(M.config.configurable={...M.config.configurable,[Er]:M.stream}),await this._runLoop({loop:M,runner:S,debug:l,config:d}),k==="sync"&&await Promise.all(M?.checkpointerPromises??[])}catch(S){w=S}finally{try{M&&(await M.store?.stop(),await M.cache?.stop()),await Promise.all(M?.checkpointerPromises??[])}catch(S){w=w??S}w?_.error(w):_.close()}})();try{for await(const S of _){if(S===void 0)throw new Error("Data structure error.");const[x,I,O]=S;if(c.includes(I)){if(n==="text/event-stream"){r?yield[x,I,O]:yield[null,I,O];continue}r&&!C?yield[x,I,O]:C?r?yield[x,O]:yield O:yield[I,O]}}}catch(S){throw await g?.handleChainError(w),S}finally{await E}await g?.handleChainEnd(M?.output??{},i,void 0,void 0,void 0)}async invoke(t,e){const n=e?.streamMode??"values",r={...e,outputKeys:e?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},s=[],o=await this.stream(t,r),i=[];let a;for await(const l of o)n==="values"?wl(l)?i.push(l[D]):a=l:s.push(l);if(n==="values"){if(i.length>0){const l=i.flat(1);if(a==null)return{[D]:l};if(typeof a=="object")return{...a,[D]:l}}return a}return s}async _runLoop(t){const{loop:e,runner:n,debug:r,config:s}=t;let o;try{for(;await e.tick({inputKeys:this.inputChannels});){for(const{task:i}of await e._matchCachedWrites())e._outputWrites(i.id,i.writes,!0);r&&Ip(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&Nl(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,a)=>{r&&Pp(i,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new Ih([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(i){if(o=i,!await e.finishAndHandleError(o))throw i}finally{o===void 0&&await e.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},an=class Fl extends ut{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new Fl(this.guard);return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0){const n=this.value.length>0;return this.value=[],n}if(e.length!==1&&this.guard)throw new B("EphemeralValue can only receive one value per step.");return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new ee;return this.value[0]}checkpoint(){if(this.value.length===0)throw new ee;return this.value[0]}isAvailable(){return this.value.length!==0}},Ul=class{path;ends;constructor(t){ae.isRunnable(t.path)?this.path=t.path:this.path=en(t.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(t.pathMap)?t.pathMap.reduce((e,n)=>(e[n]=n,e),{}):t.pathMap}run(t,e){return de.registerWriter(new Et({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===Zi.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
47
+ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(t,e,n,r){let s=await this.path.invoke(r?r(e):t,e);Array.isArray(s)||(s=[s]);let o;if(this.ends?o=s.map(i=>ye(i)?i:this.ends[i]):o=s,o.some(i=>!i))throw new Error("Branch condition returned unknown or null destination");if(o.filter(ye).some(i=>i.node===N))throw new B("Cannot send a packet to the END node");return await n(o,e)??t}},em=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(t){this.compiled&&console.warn(t)}get allEdges(){return this.edges}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,o]of n){for(const a of[Z,Ge])if(r.includes(a))throw new Error(`"${a}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===N)throw new Error(`Node \`${r}\` is reserved.`);const i=en(s);this.nodes[r]={runnable:i,metadata:o?.metadata,subgraphs:ko(i)?[i]:o?.subgraphs,ends:o?.ends}}return this}addEdge(t,e){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),t===N)throw new Error("END cannot be a start node");if(e===U)throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([n])=>n===t)&&!("channels"in this))throw new Error(`Already found path for ${t}. For multiple edges, use StateGraph.`);return this.edges.add([t,e]),this}addConditionalEdges(t,e,n){const r=typeof t=="object"?t:{source:t,path:e,pathMap:n};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!ae.isRunnable(r.path)){const o=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=en(r.path).withConfig({runName:`Branch<${r.source}${o!==""?`,${o}`:""}>`.slice(0,63)})}const s=r.path.getName()==="RunnableLambda"?"condition":r.path.getName();if(this.branches[r.source]&&this.branches[r.source][s])throw new Error(`Condition \`${s}\` already present for node \`${t}\``);return this.branches[r.source]??={},this.branches[r.source][s]=new Ul(r),this}setEntryPoint(t){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(U,t)}setFinishPoint(t){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(t,N)}compile({checkpointer:t,interruptBefore:e,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(e)?e:[],...Array.isArray(n)?n:[]]);const s=new Vl({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[U]:new an,[N]:new an},inputChannels:U,outputChannels:N,streamChannels:[],streamMode:"values",name:r});for(const[o,i]of Object.entries(this.nodes))s.attachNode(o,i);for(const[o,i]of this.edges)s.attachEdge(o,i);for(const[o,i]of Object.entries(this.branches))for(const[a,l]of Object.entries(i))s.attachBranch(o,a,l);return s.validate()}validate(t){const e=new Set([...this.allEdges].map(([r,s])=>r));for(const[r]of Object.entries(this.branches))e.add(r);for(const r of e)if(r!==U&&!(r in this.nodes))throw new Error(`Found edge starting at unknown node \`${r}\``);const n=new Set([...this.allEdges].map(([r,s])=>s));for(const[r,s]of Object.entries(this.branches))for(const o of Object.values(s))if(o.ends!=null)for(const i of Object.values(o.ends))n.add(i);else{n.add(N);for(const i of Object.keys(this.nodes))i!==r&&n.add(i)}for(const r of Object.values(this.nodes))for(const s of r.ends??[])n.add(s);for(const r of Object.keys(this.nodes))if(!n.has(r))throw new Oh([`Node \`${r}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join(`
48
+ `),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!==N&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(t){for(const r of t)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},Vl=class extends Qp{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new an,this.nodes[t]=new Nn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new de([{channel:t,value:St}],[Y])),this.streamChannels.push(t)}attachEdge(t,e){if(e===N){if(t===U)throw new Error("Cannot have an edge from START to END");this.nodes[t].writers.push(new de([{channel:N,value:St}],[Y]))}else this.nodes[e].triggers.push(t),this.nodes[e].channels.push(t)}attachBranch(t,e,n){t===U&&!this.nodes[U]&&(this.nodes[U]=Xp.subscribeTo(U,{tags:[Y]})),this.nodes[t].pipe(n.run(s=>new de(s.map(o=>ye(o)?o:{channel:o===N?N:`branch:${t}:${e}:${o}`,value:St}),[Y])));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==N){const o=`branch:${t}:${e}:${s}`;this.channels[o]=new an,this.nodes[s].triggers.push(o),this.nodes[s].channels.push(o)}}async getGraphAsync(t){const e=t?.xray,n=new Uo,r={[U]:n.addNode({schema:ve()},U)},s={};let o={};e&&(o=Object.fromEntries((await Ze(this.getSubgraphsAsync())).filter(l=>hi(l[1]))));function i(l,c,u,d=!1){if(c===N&&s[N]===void 0&&(s[N]=n.addNode({schema:ve()},N)),r[l]!==void 0){if(s[c]===void 0)throw new Error(`End node ${c} not found!`);return n.addEdge(r[l],s[c],u!==c?u:void 0,d)}}for(const[l,c]of Object.entries(this.builder.nodes)){const u=ue(l),d=c.runnable,h=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?h.__interrupt="before,after":this.interruptBefore?.includes(l)?h.__interrupt="before":this.interruptAfter?.includes(l)&&(h.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,m=o[l]!==void 0?await o[l].getGraphAsync({...t,xray:f}):d.getGraph(t);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let T=function(_){return _?_.lc_runnable:!1},k=function(_,g){if(_!==void 0&&!Vo(_))return _;if(T(g))try{let v=g.getName();return v=v.startsWith("Runnable")?v.slice(8):v,v}catch{return g.getName()}else return g.name??"UnknownSchema"};const[p,C]=n.extend(m,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);C!==void 0&&(r[u]={name:k(C.id,C.data),...C}),s[u]={name:k(p.id,p.data),...p}}else{const p=n.addNode(d,u,h);r[u]=p,s[u]=p}}else{const f=n.addNode(d,u,h);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(ue(l),ue(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==l).map(d=>[ue(d),ue(d)])),[N]:N};for(const d of Object.values(c)){let h;d.ends!==void 0?h=d.ends:h=u;for(const[f,m]of Object.entries(h))i(ue(l),ue(m),f,!0)}}for(const[l,c]of Object.entries(this.builder.nodes))if(c.ends!==void 0)for(const u of c.ends)i(ue(l),ue(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new Uo,r={[U]:n.addNode({schema:ve()},U)},s={};let o={};e&&(o=Object.fromEntries(yn(this.getSubgraphs()).filter(l=>hi(l[1]))));function i(l,c,u,d=!1){return c===N&&s[N]===void 0&&(s[N]=n.addNode({schema:ve()},N)),n.addEdge(r[l],s[c],u!==c?u:void 0,d)}for(const[l,c]of Object.entries(this.builder.nodes)){const u=ue(l),d=c.runnable,h=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?h.__interrupt="before,after":this.interruptBefore?.includes(l)?h.__interrupt="before":this.interruptAfter?.includes(l)&&(h.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,m=o[l]!==void 0?o[l].getGraph({...t,xray:f}):d.getGraph(t);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let T=function(_){return _?_.lc_runnable:!1},k=function(_,g){if(_!==void 0&&!Vo(_))return _;if(T(g))try{let v=g.getName();return v=v.startsWith("Runnable")?v.slice(8):v,v}catch{return g.getName()}else return g.name??"UnknownSchema"};const[p,C]=n.extend(m,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);C!==void 0&&(r[u]={name:k(C.id,C.data),...C}),s[u]={name:k(p.id,p.data),...p}}else{const p=n.addNode(d,u,h);r[u]=p,s[u]=p}}else{const f=n.addNode(d,u,h);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(ue(l),ue(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==l).map(d=>[ue(d),ue(d)])),[N]:N};for(const d of Object.values(c)){let h;d.ends!==void 0?h=d.ends:h=u;for(const[f,m]of Object.entries(h))i(ue(l),ue(m),f,!0)}}return n}};function hi(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function ue(t){return t==="subgraph"?`"${t}"`:t}function bn(t){return typeof t=="object"&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"validate"in t["~standard"]}function tm(t){return typeof t=="object"&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"jsonSchema"in t["~standard"]}function It(t){if(tm(t))try{return t["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function Pt(t){if(t!=null&&bn(t))try{const e=t["~standard"].validate(void 0);if(e&&typeof e=="object"&&!("then"in e&&typeof e.then=="function")){const n=e;if(!n.issues){const r=n.value;return()=>r}}}catch{}}const ds=Symbol.for("langgraph.channel.missing");var nm=class Bl extends ut{lc_graph_name="UntrackedValue";guard;_value=ds;initialValueFactory;constructor(e){super(),this.guard=e?.guard??!0,this.initialValueFactory=e?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(e){return new Bl({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(e){if(e.length===0)return!1;if(e.length!==1&&this.guard)throw new B("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this._value=e[e.length-1],!0}get(){if(this._value===ds)throw new ee;return this._value}checkpoint(){}isAvailable(){return this._value!==ds}};const fs=Symbol.for("langgraph.state.reduced_value");var ke=class{[fs]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(t,e){this.reducer=e.reducer,this.jsonSchemaExtra=e.jsonSchemaExtra,this.valueSchema=t,this.inputSchema="inputSchema"in e?e.inputSchema:t,this.jsonSchemaExtra=e.jsonSchemaExtra}static isInstance(t){return typeof t=="object"&&t!==null&&fs in t&&t[fs]===!0}};const di=Symbol.for("langgraph.state.untracked_value");var mt=class{[di]=!0;schema;guard;constructor(t,e){this.schema=t,this.guard=e?.guard??!0}static isInstance(t){return typeof t=="object"&&t!==null&&di in t}};const wt=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var rm=class zl extends ut{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new zl(this.names);return typeof e<"u"&&(n.seen=new Set(e)),n}update(e){let n=!1;for(const r of e)if(this.names.has(r))this.seen.has(r)||(this.seen.add(r),n=!0);else throw new B(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!wt(this.names,this.seen))throw new ee}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&wt(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&wt(this.names,this.seen)}},sm=class Hl extends ut{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(e){super(),this.names=e,this.seen=new Set,this.finished=!1}fromCheckpoint(e){const n=new Hl(this.names);if(typeof e<"u"){const[r,s]=e;n.seen=new Set(r),n.finished=s}return n}update(e){let n=!1;for(const r of e)if(this.names.has(r)&&!this.seen.has(r))this.seen.add(r),n=!0;else if(!this.names.has(r))throw new B(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!wt(this.names,this.seen))throw new ee}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&wt(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&wt(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&wt(this.names,this.seen)}};const ps=Symbol.for("langgraph.state.state_schema");var ne=class{[ps]=!0;constructor(t){this.fields=t}getChannels(){const t={};for(const[e,n]of Object.entries(this.fields))if(ke.isInstance(n)){const r=Pt(n.valueSchema);t[e]=new kr(n.reducer,r)}else if(mt.isInstance(n)){const r=n.schema?Pt(n.schema):void 0;t[e]=new nm({guard:n.guard,initialValueFactory:r})}else if(bn(n))t[e]=new Ur(Pt(n));else throw new Error(`Invalid state field "${e}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return t}getJsonSchema(){const t={},e=[];for(const[n,r]of Object.entries(this.fields)){let s;if(ke.isInstance(r)?(s=It(r.valueSchema),r.jsonSchemaExtra&&(s={...s??{},...r.jsonSchemaExtra})):mt.isInstance(r)?s=r.schema?It(r.schema):void 0:bn(r)&&(s=It(r)),s){t[n]=s;let o=!1;ke.isInstance(r)?o=Pt(r.valueSchema)!==void 0:mt.isInstance(r)?o=r.schema?Pt(r.schema)!==void 0:!1:o=Pt(r)!==void 0,o||e.push(n)}}return{type:"object",properties:t,required:e.length>0?e:void 0}}getInputJsonSchema(){const t={};for(const[e,n]of Object.entries(this.fields)){let r;ke.isInstance(n)?r=It(n.inputSchema):mt.isInstance(n)?r=n.schema?It(n.schema):void 0:bn(n)&&(r=It(n)),r&&(t[e]=r)}return{type:"object",properties:t}}getChannelKeys(){return Object.entries(this.fields).map(([t])=>t)}getAllKeys(){return Object.keys(this.fields)}async validateInput(t){if(t==null||typeof t!="object")return t;const e={};for(const[n,r]of Object.entries(t)){const s=this.fields[n];if(s===void 0){e[n]=r;continue}let o;if(ke.isInstance(s)?o=s.inputSchema:mt.isInstance(s)?o=s.schema:bn(s)&&(o=s),o){const i=await o["~standard"].validate(r);if(i.issues)throw new Error(`Validation failed for field "${n}": ${JSON.stringify(i.issues)}`);e[n]=i.value}else e[n]=r}return e}static isInstance(t){return typeof t=="object"&&t!==null&&ps in t&&t[ps]===!0}};const Wl="__remove_all__";function Mo(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(xn),o=r.map(xn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=wr(),u.lc_kwargs.id=u.id);let i;for(let u=0;u<o.length;u+=1){const d=o[u];(d.id===null||d.id===void 0)&&(d.id=wr(),d.lc_kwargs.id=d.id),bt.isInstance(d)&&d.id===Wl&&(i=u)}if(i!=null)return o.slice(i+1);const a=[...s],l=new Map(a.map((u,d)=>[u.id,d])),c=new Set;for(const u of o){const d=l.get(u.id);if(d!==void 0)bt.isInstance(u)?c.add(u.id):(c.delete(u.id),a[d]=u);else{if(bt.isInstance(u))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);l.set(u.id,a.length),a.push(u)}}return a.filter(u=>!c.has(u.id))}const om=no().default(()=>[]),im=no(),ms=new ke(om,{inputSchema:im,reducer:Mo,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}}),am="lg:";var lm=class{_map=new Map;_extensionCache=new Map;get(t){return this._map.get(t)}extend(t,e){const n=this.get(t);this._map.set(t,e(n))}remove(t){return this._map.delete(t),this}has(t){return this._map.has(t)}getChannelsForSchema(t){const e={},n=Ts(t);for(const[r,s]of Object.entries(n)){const o=this.get(s);o?.reducer?e[r]=new kr(o.reducer.fn,o.default):e[r]=new Ur(o?.default)}return e}getExtendedChannelSchemas(t,e){if(Object.keys(e).length===0)return t;const n=Object.entries(e).filter(([,o])=>o===!0).sort(([o],[i])=>o.localeCompare(i)).map(([o,i])=>`${o}:${i}`).join("|"),r=this._extensionCache.get(n)??new Map;if(r.has(t))return r.get(t);let s=t;if(e.withReducerSchema||e.withJsonSchemaExtrasAsDescription){const o=Object.entries(Ts(t)).map(([i,a])=>{const l=this.get(a);let c=e.withReducerSchema?l?.reducer?.schema??a:a;if(e.withJsonSchemaExtrasAsDescription&&l?.jsonSchemaExtra){const u=ks(c)??ks(a),d=JSON.stringify({...l.jsonSchemaExtra,description:u});c=c.describe(`${am}${d}`)}return[i,c]});s=bu(t,Object.fromEntries(o)),_u(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=ro(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const ln=new lm;function Ks(t,e){if(e.reducer&&!e.default){const n=so(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return ln.extend(n,()=>e),n}else return ln.extend(t,()=>e),t}function Ot(t){return t==null?!1:!!(ne.isInstance(t)||te(t)||typeof t=="object"&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||fl(e)))}function cm(t){if(typeof t!="object"||t==null)return!1;const e=t,n="state"in e&&Ot(e.state),r="stateSchema"in e&&Ot(e.stateSchema),s="input"in e&&Ot(e.input);return!(!n&&!r&&!s||"input"in e&&e.input!=null&&!Ot(e.input)||"output"in e&&e.output!=null&&!Ot(e.output))}const ze="__root__",Ir=Symbol.for("langgraph.state.partial");var um=class extends em{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=ln;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){super();const n=this._normalizeToStateGraphInit(t,e),r=n.state??n.stateSchema??n.input;if(!r)throw new Yr;const s=this._getChannelsFromSchema(r);this._schemaDefinition=s,ne.isInstance(r)?this._schemaRuntimeDefinition=r:te(r)&&(this._schemaRuntimeDefinition=r),n.input?ne.isInstance(n.input)?this._inputRuntimeDefinition=n.input:te(n.input)?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=Ir:this._inputRuntimeDefinition=Ir,n.output?ne.isInstance(n.output)?this._outputRuntimeDefinition=n.output:te(n.output)?this._outputRuntimeDefinition=n.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;const o=n.input?this._getChannelsFromSchema(n.input):s,i=n.output?this._getChannelsFromSchema(n.output):s;this._inputDefinition=o,this._outputDefinition=i,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),n.context&&te(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.writer}_normalizeToStateGraphInit(t,e){if(cm(t)){if(te(e)||Ls.isInstance(e))return{...t,context:e};const n=e;return{...t,input:t.input??n?.input,output:t.output??n?.output,context:t.context??n?.context,interrupt:t.interrupt??n?.interrupt,writer:t.writer??n?.writer,nodes:t.nodes??n?.nodes}}if(Ot(t)){if(te(e)||Ls.isInstance(e))return{state:t,context:e};const n=e;return{state:t,input:n?.input,output:n?.output,context:n?.context,interrupt:n?.interrupt,writer:n?.writer,nodes:n?.nodes}}if(fm(t))return{state:hm(t.channels)};throw new Yr}_getChannelsFromSchema(t){if(ne.isInstance(t))return t.getChannels();if(te(t))return this._metaRegistry.getChannelsForSchema(t);if(typeof t=="object"&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot")return t.spec;if(typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)return t;throw new Yr("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([t,e])=>t.map(n=>[n,e]))])}_addSchema(t){if(!this._schemaDefinitions.has(t)){this._schemaDefinitions.set(t,t);for(const[e,n]of Object.entries(t)){let r;if(typeof n=="function"?r=n():r=n,this.channels[e]!==void 0){if(!this.channels[e].equals(r)&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${e}" already exists with a different type.`)}else this.channels[e]=r}}}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]).map(([r,s])=>[r,s]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,o]of n){if(r in this.channels)throw new Error(`${r} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const u of[Z,Ge])if(r.includes(u))throw new Error(`"${u}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===N||r===U)throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;o?.input!==void 0&&(i=this._getChannelsFromSchema(o.input)),this._addSchema(i);let a;ae.isRunnable(s)?a=s:typeof s=="function"?a=new Et({func:s,name:r,trace:!1}):a=en(s);let l=o?.cachePolicy;typeof l=="boolean"&&(l=l?{}:void 0);const c={runnable:a,retryPolicy:o?.retryPolicy,cachePolicy:l,metadata:o?.metadata,input:i??this._schemaDefinition,subgraphs:ko(a)?[a]:o?.subgraphs,ends:o?.ends,defer:o?.defer};this.nodes[r]=c}return this}addEdge(t,e){if(typeof t=="string")return super.addEdge(t,e);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const n of t){if(n===N)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(r=>r===n))throw new Error(`Need to add a node named "${n}" first`)}if(e===N)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(n=>n===e))throw new Error(`Need to add a node named "${e}" first`);return this.waitingEdges.add([t,e]),this}addSequence(t){const e=Array.isArray(t)?t:Object.entries(t);if(e.length===0)throw new Error("Sequence requires at least one node.");let n;for(const[r,s,o]of e){if(r in this.nodes)throw new Error(`Node names must be unique: node with the name "${r}" already exists.`);const i=r;this.addNode(i,s,o),n!=null&&this.addEdge(n,i),n=i}return this}compile({checkpointer:t,store:e,cache:n,interruptBefore:r,interruptAfter:s,name:o,description:i}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(s)?s:[]]);const a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),l=a.length===1&&a[0]===ze?ze:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===ze?ze:c,d=this._interrupt,h=new dm({builder:this,checkpointer:t,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[U]:new an},inputChannels:U,outputChannels:l,streamChannels:u,streamMode:"updates",store:e,cache:n,name:o,description:i,userInterrupt:d});h.attachNode(U);for(const[f,m]of Object.entries(this.nodes))h.attachNode(f,m);h.attachBranch(U,ti,fi(),{withReader:!1});for(const[f]of Object.entries(this.nodes))h.attachBranch(f,ti,fi(),{withReader:!1});for(const[f,m]of this.edges)h.attachEdge(f,m);for(const[f,m]of this.waitingEdges)h.attachEdge(f,m);for(const[f,m]of Object.entries(this.branches))for(const[p,C]of Object.entries(m))h.attachBranch(f,p,C);return h.validate()}};function hm(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Fs(r);return e}var dm=class extends Vl{description;_metaRegistry=ln;constructor({description:t,...e}){super(e),this.description=t}attachNode(t,e){let n;t===U?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):n=Object.keys(this.builder.channels);function r(a){if(q(a))return a.graph===G.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(l=>q(l))){const l=[];for(const c of a)if(q(c)){if(c.graph===G.PARENT)continue;l.push(...c._updateAsTuples())}else l.push([ze,c]);return l}else if(a!=null)return[[ze,a]];return null}const s=t;function o(a){if(a){if(q(a))return a.graph===G.PARENT?null:a._updateAsTuples().filter(([l])=>n.includes(l));if(Array.isArray(a)&&a.length>0&&a.some(q)){const l=[];for(const c of a)if(q(c)){if(c.graph===G.PARENT)continue;l.push(...c._updateAsTuples().filter(([u])=>n.includes(u)))}else{const u=o(c);u&&l.push(...u??[])}return l}else{if(typeof a=="object"&&!Array.isArray(a))return Object.entries(a).filter(([l])=>n.includes(l));{const l=Array.isArray(a)?"array":typeof a;throw new B(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${l}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const i=[{value:St,mapper:new Et({func:n.length&&n[0]===ze?r:o,trace:!1,recurse:!1})}];if(t===U)this.nodes[t]=new Nn({tags:[Y],triggers:[U],channels:[U],writers:[new de(i,[Y])]});else{const a=e?.input??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(a)).map(d=>[d,d])),c=Object.keys(l).length===1&&ze in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new Nf:new an(!1),this.nodes[t]=new Nn({triggers:[u],channels:c?Object.keys(l):l,writers:[new de(i,[Y])],mapper:c?void 0:d=>Object.fromEntries(Object.entries(d).filter(([h])=>h in l)),bound:e?.runnable,metadata:e?.metadata,retryPolicy:e?.retryPolicy,cachePolicy:e?.cachePolicy,subgraphs:e?.subgraphs,ends:e?.ends})}}attachEdge(t,e){if(e!==N){if(typeof t=="string")this.nodes[t].writers.push(new de([{channel:`branch:to:${e}`,value:null}],[Y]));else if(Array.isArray(t)){const n=`join:${t.join("+")}:${e}`;this.channels[n]=this.builder.nodes[e].defer?new sm(new Set(t)):new rm(new Set(t)),this.nodes[e].triggers.push(n);for(const r of t)this.nodes[r].writers.push(new de([{channel:n,value:r}],[Y]))}}}attachBranch(t,e,n,r={withReader:!0}){const s=async(o,i)=>{const a=o.filter(c=>c!==N);if(!a.length)return;const l=a.map(c=>ye(c)?c:{channel:c===N?c:`branch:to:${c}`,value:t});await de.doWrite({...i,tags:(i.tags??[]).concat([Y])},l)};this.nodes[t].writers.push(n.run(s,r.withReader?o=>hp.doRead(o,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(t){if(t==null)return t;const e=this.builder._inputRuntimeDefinition,n=this.builder._schemaRuntimeDefinition;if(ne.isInstance(e)){if(q(t)){const s=t;return t.update&&(s.update=await e.validateInput(Array.isArray(t.update)?Object.fromEntries(t.update):t.update)),s}return await e.validateInput(t)}if(e===Ir&&ne.isInstance(n)){if(q(t)){const s=t;return t.update&&(s.update=await n.validateInput(Array.isArray(t.update)?Object.fromEntries(t.update):t.update)),s}return await n.validateInput(t)}const r=(()=>{const s=o=>{if(o!=null)return this._metaRegistry.getExtendedChannelSchemas(o,{withReducerSchema:!0})};if(te(e))return s(e);if(e===Ir)return te(n)?ro(s(n)):void 0})();if(q(t)){const s=t;return t.update&&r!=null&&(s.update=nt(r,t.update)),s}return r!=null?nt(r,t):t}isInterrupted(t){return wl(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return te(e)&&nt(e,t),t}};function fm(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function pm(t){if(ye(t))return[t];const e=[];q(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(q));const n=[];for(const r of e){if(r.graph===G.PARENT)throw new Qi(r);ye(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function fi(){return new Ul({path:new Et({func:pm,tags:[Y],trace:!1,recurse:!1,name:"<control_branch>"})})}Ds.Root({messages:Ds({reducer:Mo,default:()=>[]})});const mm={reducer:{fn:Mo},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};K({messages:Ks(Le(),mm)});Ah();var Js=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},qs=class extends Error{toolNames;constructor(t){super(`The model has called multiple tools: ${t.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=t}},Gl=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(n=>`
49
49
  - ${n}`).join("")}.`),this.toolName=t,this.errors=e}},Ao=class extends Error{toolCall;toolError;constructor(t,e){const n=t instanceof Error?t:new Error(String(t)),r=JSON.stringify(e.args);super(`Error invoking tool '${e.name}' with kwargs ${r} with error: ${n.stack}
50
50
  Please fix the error and try again.`),this.toolCall=e,this.toolError=n}},Io=class Kl extends Error{static"~brand"="MiddlewareError";constructor(e,n){const r=e instanceof Error?e.message:String(e);super(r),this.name=e instanceof Error?e.name:`${n[0].toUpperCase()+n.slice(1)}Error`,e instanceof Error&&(this.cause=e)}static wrap(e,n){return Sn(e)?e:new Kl(e,n)}static isInstance(e){return e instanceof Error&&"~brand"in e&&e["~brand"]==="MiddlewareError"}};function Po(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function Pr(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_getModelInstance"in t&&typeof t._getModelInstance=="function"}const pi=!0;let gm=0;var Xe=class Ys{constructor(e,n,r){this.schema=e,this.tool=n,this.options=r}get name(){return this.tool.function.name}static fromSchema(e,n){function r(a){return a??`extract-${++gm}`}if(oo(e)){const a=Me(e),l={type:"function",function:{name:r(a.title),strict:!1,description:a.description??"Tool for extracting structured output from the model's response.",parameters:a}};return new Ys(a,l,n)}let s;typeof e.name=="string"&&typeof e.parameters=="object"&&e.parameters!=null?s=e:s={name:r(e.title),description:e.description??"",parameters:e.schema||e};const o=Me(e),i={type:"function",function:s};return new Ys(o,i,n)}parse(e){const r=new Oi(this.schema).validate(e);if(!r.valid)throw new Gl(this.name,r.errors.map(s=>s.error));return e}},et=class Jl{_schemaType;schema;strict;constructor(e,n){if("schema"in e&&typeof e.schema=="object"&&e.schema!==null&&!("type"in e)){const r=e;this.schema=r.schema,this.strict=r.strict??pi}else this.schema=e,this.strict=n??pi}static fromSchema(e,n){const r=Me(e);return new Jl(r,n)}parse(e){let n;if(typeof e.content=="string")n=e.content;else if(Array.isArray(e.content)){for(const r of e.content)if(typeof r=="object"&&r!==null&&"type"in r&&r.type==="text"&&"text"in r&&typeof r.text=="string"){n=r.text;break}}if(!(!n||n===""))try{const r=JSON.parse(n);return new Oi(this.schema).validate(r).valid?r:void 0}catch{}}};function ql(t,e,n){if(!t)return[];if(typeof t=="object"&&t!==null&&"__responseFormatUndefined"in t)return[];if(Array.isArray(t)){if(t.every(s=>s instanceof Xe||s instanceof et))return t;if(t.every(s=>te(s)))return t.map(s=>Xe.fromSchema(s,e));if(t.every(s=>typeof s=="object"&&s!==null&&!te(s)))return t.map(s=>Xe.fromSchema(s,e));throw new Error(`Invalid response format: list contains mixed types.
51
- All items must be either InteropZodObject or plain JSON schema objects.`)}if(t instanceof Xe||t instanceof et)return[t];const r=Yl(n);if(te(t))return r?[et.fromSchema(t)]:[Xe.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[et.fromSchema(t)]:[Xe.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function ym(t,e){return ql(t,e)}function wm(t){if(typeof t=="object"&&t!==null&&"schema"in t&&!oo(t)&&!("type"in t)){const{schema:e,strict:n}=t;return et.fromSchema(e,n)}return et.fromSchema(t)}const bm=["ChatOpenAI","ChatXAI"],mi=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function Yl(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return mi.some(r=>n.includes(r))}if(Pr(t))return Yl(t._defaultConfig.model);if(!Po(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||bm.includes(e)&&("model"in t&&mi.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function Oo(t){let e=0;for(const n of t){let r;typeof n.content=="string"?r=n.content:Array.isArray(n.content)?r=n.content.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join(""):r="",P.isInstance(n)&&Array.isArray(n.tool_calls)&&n.tool_calls.length>0&&(r+=JSON.stringify(n.tool_calls)),j.isInstance(n)&&(r+=n.tool_call_id??""),e+=r.length}return Math.ceil(e/4)}function tt(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Vr(t){return typeof t=="function"?t:t.hook}function Xl(t){return new Promise(e=>setTimeout(e,t))}function Zl(t,e){const{backoffFactor:n,initialDelayMs:r,maxDelayMs:s,jitter:o}=t;let i;if(n===0?i=r:i=r*n**e,i=Math.min(i,s),o&&i>0){const a=i*.25;i=i+(Math.random()*2-1)*a,i=Math.max(0,i)}return i}const Ql=Symbol("AgentMiddleware");function le(t){return{[Ql]:!0,name:t.name,stateSchema:t.stateSchema,contextSchema:t.contextSchema,wrapToolCall:t.wrapToolCall,wrapModelCall:t.wrapModelCall,beforeAgent:t.beforeAgent,beforeModel:t.beforeModel,afterModel:t.afterModel,afterAgent:t.afterAgent,tools:t.tools}}var _m=class ec extends Un{toolCalls;toolStyle;indexRef;structuredResponse;tools=[];constructor({toolCalls:e=[],toolStyle:n="openai",index:r=0,structuredResponse:s,indexRef:o,...i}={}){super(i),this.toolCalls=e,this.toolStyle=n,this.indexRef=o??{current:r},this.structuredResponse=s}get index(){return this.indexRef.current}set index(e){this.indexRef.current=e}_llmType(){return"fake-tool-calling"}_combineLLMOutput(){return[]}bindTools(e){const n=new ec({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...e],n}withStructuredOutput(e){return new yr({func:async()=>this.structuredResponse})}async _generate(e,n,r){let o=e[e.length-1].content;e.length>1&&(o=e.map(d=>d.content).filter(Boolean).map(d=>typeof d=="string"?d:typeof d=="object"&&"text"in d?d.text:Array.isArray(d)?d.map(h=>typeof h=="string"?h:typeof h=="object"&&"text"in h?h.text:"").join("-"):JSON.stringify(d)).join("-")),(e.length===1||e.length===2&&e.every(se.isInstance))&&this.index!==0&&(this.index=0);const a=this.toolCalls[this.index]||[],l=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const c=new P({content:o,id:l,tool_calls:a.length>0?a.map(u=>({...u,type:"tool_call"})):void 0});return{generations:[{text:o,message:c}],llmOutput:{}}}};const Xs=Symbol.for("langgraph-zod");Xs in globalThis||(globalThis[Xs]=new WeakSet);function gi(t){const e=globalThis[Xs];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return Ks(n,{jsonSchemaExtra:r})},reducer(r,s){return Ks(n,{default:so(n),reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{gi(vu.prototype),gi(Su.prototype)}catch(t){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:t})}var vm=class extends Cu{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=so(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new vm(ln);function Sm(t=!0,e,n=[]){const r={jumpTo:new mt},s={},o={},i=a=>{if(ne.isInstance(a)){for(const[c,u]of Object.entries(a.fields))c.startsWith("_")||c in r||(r[c]=u,Te.isInstance(u)?(s[c]=u.inputSchema||u.valueSchema,o[c]=u.valueSchema):(s[c]=u,o[c]=u));return}const l=ks(a);for(const[c,u]of Object.entries(l))if(!c.startsWith("_")&&!(c in r)){if(Ni(u)){const d=ln.get(u);if(d?.reducer){d.reducer.schema?(r[c]=new Te(u,{inputSchema:d.reducer.schema,reducer:d.reducer.fn}),s[c]=d.reducer.schema,o[c]=u):(r[c]=new Te(u,{reducer:d.reducer.fn}),s[c]=u,o[c]=u);continue}}r[c]=u,s[c]=u,o[c]=u}};e&&(ne.isInstance(e)||te(e))&&i(e);for(const a of n)a.stateSchema&&(ne.isInstance(a.stateSchema)||te(a.stateSchema))&&i(a.stateSchema);return t&&(o.structuredResponse=new mt),{state:new ne({messages:ms,...r}),input:new ne({messages:ms,...s}),output:new ne({messages:ms,...o})}}const gs=/<name>(.*?)<\/name>/s,ys=/<content>(.*?)<\/content>/s;function Cm(t,e){if(ne.isInstance(t)){const n={};for(const r of Object.keys(t.fields))r in e&&(n[r]=e[r]);return n}if(oo(t))return nt(t,e);throw new Error(`Invalid state schema type: ${typeof t}`)}function km(t){if(!P.isInstance(t)||Qt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new P({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});const n=[];let r=0;for(const s of t.content)typeof s=="string"?(r+=1,n.push(`<name>${e}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,n.push({...s,text:`<name>${e}</name><content>${s.text}</content>`})):n.push(s);return r||n.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new P({...t.lc_kwargs,content:n,name:void 0})}function Tm(t){if(!P.isInstance(t)||!t.content)return t;let e=[],n;if(Array.isArray(t.content))e=t.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(gs),o=r.text.match(ys);return s&&(!o||o[1]==="")?(n=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(gs),o=r.text.match(ys);return!s||!o?r:(n=s[1],{...r,text:o[1]})}return r});else{const r=t.content,s=r.match(gs),o=r.match(ys);if(!s||!o)return t;n=s[1],e=o[1]}return new P({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function Or(t){return ae.isRunnable(t)}function yi(t){return Po(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const ws=(t,e,n={})=>{if(yi(t))return t.bindTools(e,n);if(Re.isRunnableBinding(t)&&yi(t.bound)){const r=t.bound.bindTools(e,n);return Re.isRunnableBinding(r)?new Re({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new Re({bound:r,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function tc(t){if(typeof t=="function")return;let e=t;if(it.isRunnableSequence(e)&&(e=e.steps.find(n=>Re.isRunnableBinding(n))||e),!Pr(e)){if(Re.isRunnableBinding(e)){const n=e.kwargs!=null&&typeof e.kwargs=="object"&&"tools"in e.kwargs&&Array.isArray(e.kwargs.tools)&&e.kwargs.tools.length>0,r=e.config!=null&&typeof e.config=="object"&&"tools"in e.config&&Array.isArray(e.config.tools)&&e.config.tools.length>0;if(n||r)throw new Js}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new Js}}function Nr(t){return!!(P.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Em(t){if(t==null)return new oe("");if(oe.isInstance(t))return t;if(typeof t=="string")return new oe({content:[{type:"text",text:t}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof t}`)}async function xm(t,e,n={}){const r=ws(t,e,n);if(r)return r;if(Pr(t)){const s=ws(await t._getModelInstance(),e,n);if(s)return s}if(it.isRunnableSequence(t)){const s=t.steps.findIndex(o=>Re.isRunnableBinding(o)||Po(o)||Pr(o));if(s>=0){const o=ws(t.steps[s],e,n);if(o){const i=t.steps.slice();return i.splice(s,1,o),it.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function Mm(t){if(t.length===0)return;if(t.length===1)return t[0];function e(r,s){return async(o,i)=>r(o,async l=>s(l,i))}let n=t[t.length-1];for(let r=t.length-2;r>=0;r--)n=e(t[r],n);return n}function Am(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return Mm(e.map(n=>{const r=n.wrapToolCall;return async(o,i)=>{const a=o.state,l=async c=>{const u={...a,...c.state};return i({...c,state:u})};try{const c=await r({...o,state:{messages:a.messages,...n.stateSchema?Cm(n.stateSchema,{...a}):{}}},l);if(!j.isInstance(c)&&!q(c))throw new Error(`Invalid response from "wrapToolCall" in middleware "${n.name}": expected ToolMessage or Command, got ${typeof c}`);return c}catch(c){throw Io.wrap(c,n.name)}}}))}async function Im(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;let s=r.stateSchema;if(ne.isInstance(r.stateSchema)){const l={};for(const[c,u]of Object.entries(r.stateSchema.fields))Te.isInstance(u)?l[c]=u.inputSchema||u.valueSchema:l[c]=u;s=re(l)}const o=ku(s,l=>l.startsWith("_")),i=await Tu(o,e);if(i.success){Object.assign(n,i.data);continue}const a=i.error.issues.filter(l=>l.code==="invalid_type").map(l=>` - ${l.path.join(".")}: Required`).join(`
51
+ All items must be either InteropZodObject or plain JSON schema objects.`)}if(t instanceof Xe||t instanceof et)return[t];const r=Yl(n);if(te(t))return r?[et.fromSchema(t)]:[Xe.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[et.fromSchema(t)]:[Xe.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function ym(t,e){return ql(t,e)}function wm(t){if(typeof t=="object"&&t!==null&&"schema"in t&&!oo(t)&&!("type"in t)){const{schema:e,strict:n}=t;return et.fromSchema(e,n)}return et.fromSchema(t)}const bm=["ChatOpenAI","ChatXAI"],mi=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function Yl(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return mi.some(r=>n.includes(r))}if(Pr(t))return Yl(t._defaultConfig.model);if(!Po(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||bm.includes(e)&&("model"in t&&mi.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function Oo(t){let e=0;for(const n of t){let r;typeof n.content=="string"?r=n.content:Array.isArray(n.content)?r=n.content.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join(""):r="",P.isInstance(n)&&Array.isArray(n.tool_calls)&&n.tool_calls.length>0&&(r+=JSON.stringify(n.tool_calls)),j.isInstance(n)&&(r+=n.tool_call_id??""),e+=r.length}return Math.ceil(e/4)}function tt(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Vr(t){return typeof t=="function"?t:t.hook}function Xl(t){return new Promise(e=>setTimeout(e,t))}function Zl(t,e){const{backoffFactor:n,initialDelayMs:r,maxDelayMs:s,jitter:o}=t;let i;if(n===0?i=r:i=r*n**e,i=Math.min(i,s),o&&i>0){const a=i*.25;i=i+(Math.random()*2-1)*a,i=Math.max(0,i)}return i}const Ql=Symbol("AgentMiddleware");function le(t){return{[Ql]:!0,name:t.name,stateSchema:t.stateSchema,contextSchema:t.contextSchema,wrapToolCall:t.wrapToolCall,wrapModelCall:t.wrapModelCall,beforeAgent:t.beforeAgent,beforeModel:t.beforeModel,afterModel:t.afterModel,afterAgent:t.afterAgent,tools:t.tools}}var _m=class ec extends Un{toolCalls;toolStyle;indexRef;structuredResponse;tools=[];constructor({toolCalls:e=[],toolStyle:n="openai",index:r=0,structuredResponse:s,indexRef:o,...i}={}){super(i),this.toolCalls=e,this.toolStyle=n,this.indexRef=o??{current:r},this.structuredResponse=s}get index(){return this.indexRef.current}set index(e){this.indexRef.current=e}_llmType(){return"fake-tool-calling"}_combineLLMOutput(){return[]}bindTools(e){const n=new ec({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...e],n}withStructuredOutput(e){return new yr({func:async()=>this.structuredResponse})}async _generate(e,n,r){let o=e[e.length-1].content;e.length>1&&(o=e.map(d=>d.content).filter(Boolean).map(d=>typeof d=="string"?d:typeof d=="object"&&"text"in d?d.text:Array.isArray(d)?d.map(h=>typeof h=="string"?h:typeof h=="object"&&"text"in h?h.text:"").join("-"):JSON.stringify(d)).join("-")),(e.length===1||e.length===2&&e.every(se.isInstance))&&this.index!==0&&(this.index=0);const a=this.toolCalls[this.index]||[],l=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const c=new P({content:o,id:l,tool_calls:a.length>0?a.map(u=>({...u,type:"tool_call"})):void 0});return{generations:[{text:o,message:c}],llmOutput:{}}}};const Xs=Symbol.for("langgraph-zod");Xs in globalThis||(globalThis[Xs]=new WeakSet);function gi(t){const e=globalThis[Xs];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return Ks(n,{jsonSchemaExtra:r})},reducer(r,s){return Ks(n,{default:so(n),reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{gi(vu.prototype),gi(Su.prototype)}catch(t){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:t})}var vm=class extends Cu{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=so(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new vm(ln);function Sm(t=!0,e,n=[]){const r={jumpTo:new mt},s={},o={},i=a=>{if(ne.isInstance(a)){for(const[c,u]of Object.entries(a.fields))c.startsWith("_")||c in r||(r[c]=u,ke.isInstance(u)?(s[c]=u.inputSchema||u.valueSchema,o[c]=u.valueSchema):(s[c]=u,o[c]=u));return}const l=Ts(a);for(const[c,u]of Object.entries(l))if(!c.startsWith("_")&&!(c in r)){if(Ni(u)){const d=ln.get(u);if(d?.reducer){d.reducer.schema?(r[c]=new ke(u,{inputSchema:d.reducer.schema,reducer:d.reducer.fn}),s[c]=d.reducer.schema,o[c]=u):(r[c]=new ke(u,{reducer:d.reducer.fn}),s[c]=u,o[c]=u);continue}}r[c]=u,s[c]=u,o[c]=u}};e&&(ne.isInstance(e)||te(e))&&i(e);for(const a of n)a.stateSchema&&(ne.isInstance(a.stateSchema)||te(a.stateSchema))&&i(a.stateSchema);return t&&(o.structuredResponse=new mt),{state:new ne({messages:ms,...r}),input:new ne({messages:ms,...s}),output:new ne({messages:ms,...o})}}const gs=/<name>(.*?)<\/name>/s,ys=/<content>(.*?)<\/content>/s;function Cm(t,e){if(ne.isInstance(t)){const n={};for(const r of Object.keys(t.fields))r in e&&(n[r]=e[r]);return n}if(oo(t))return nt(t,e);throw new Error(`Invalid state schema type: ${typeof t}`)}function Tm(t){if(!P.isInstance(t)||Qt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new P({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});const n=[];let r=0;for(const s of t.content)typeof s=="string"?(r+=1,n.push(`<name>${e}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,n.push({...s,text:`<name>${e}</name><content>${s.text}</content>`})):n.push(s);return r||n.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new P({...t.lc_kwargs,content:n,name:void 0})}function km(t){if(!P.isInstance(t)||!t.content)return t;let e=[],n;if(Array.isArray(t.content))e=t.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(gs),o=r.text.match(ys);return s&&(!o||o[1]==="")?(n=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(gs),o=r.text.match(ys);return!s||!o?r:(n=s[1],{...r,text:o[1]})}return r});else{const r=t.content,s=r.match(gs),o=r.match(ys);if(!s||!o)return t;n=s[1],e=o[1]}return new P({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function Or(t){return ae.isRunnable(t)}function yi(t){return Po(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const ws=(t,e,n={})=>{if(yi(t))return t.bindTools(e,n);if(Re.isRunnableBinding(t)&&yi(t.bound)){const r=t.bound.bindTools(e,n);return Re.isRunnableBinding(r)?new Re({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new Re({bound:r,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function tc(t){if(typeof t=="function")return;let e=t;if(it.isRunnableSequence(e)&&(e=e.steps.find(n=>Re.isRunnableBinding(n))||e),!Pr(e)){if(Re.isRunnableBinding(e)){const n=e.kwargs!=null&&typeof e.kwargs=="object"&&"tools"in e.kwargs&&Array.isArray(e.kwargs.tools)&&e.kwargs.tools.length>0,r=e.config!=null&&typeof e.config=="object"&&"tools"in e.config&&Array.isArray(e.config.tools)&&e.config.tools.length>0;if(n||r)throw new Js}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new Js}}function Nr(t){return!!(P.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Em(t){if(t==null)return new oe("");if(oe.isInstance(t))return t;if(typeof t=="string")return new oe({content:[{type:"text",text:t}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof t}`)}async function xm(t,e,n={}){const r=ws(t,e,n);if(r)return r;if(Pr(t)){const s=ws(await t._getModelInstance(),e,n);if(s)return s}if(it.isRunnableSequence(t)){const s=t.steps.findIndex(o=>Re.isRunnableBinding(o)||Po(o)||Pr(o));if(s>=0){const o=ws(t.steps[s],e,n);if(o){const i=t.steps.slice();return i.splice(s,1,o),it.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function Mm(t){if(t.length===0)return;if(t.length===1)return t[0];function e(r,s){return async(o,i)=>r(o,async l=>s(l,i))}let n=t[t.length-1];for(let r=t.length-2;r>=0;r--)n=e(t[r],n);return n}function Am(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return Mm(e.map(n=>{const r=n.wrapToolCall;return async(o,i)=>{const a=o.state,l=async c=>{const u={...a,...c.state};return i({...c,state:u})};try{const c=await r({...o,state:{messages:a.messages,...n.stateSchema?Cm(n.stateSchema,{...a}):{}}},l);if(!j.isInstance(c)&&!q(c))throw new Error(`Invalid response from "wrapToolCall" in middleware "${n.name}": expected ToolMessage or Command, got ${typeof c}`);return c}catch(c){throw Io.wrap(c,n.name)}}}))}async function Im(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;let s=r.stateSchema;if(ne.isInstance(r.stateSchema)){const l={};for(const[c,u]of Object.entries(r.stateSchema.fields))ke.isInstance(u)?l[c]=u.inputSchema||u.valueSchema:l[c]=u;s=re(l)}const o=Tu(s,l=>l.startsWith("_")),i=await ku(o,e);if(i.success){Object.assign(n,i.data);continue}const a=i.error.issues.filter(l=>l.code==="invalid_type").map(l=>` - ${l.path.join(".")}: Required`).join(`
52
52
  `);throw new Error(`Middleware "${r.name}" has required state fields that must be initialized:
53
53
  ${a}
54
54
 
@@ -67,12 +67,12 @@ To fix this, either:
67
67
  agent.invoke({
68
68
  messages: [...],
69
69
  ${i.error.issues[0]?.path.join(".")}: "value"
70
- })`)}return n}function Pm(t){const e={messages:no(()=>[]),structuredResponse:ve().optional()};if(!t)return re(e);let n;if(ne.isInstance(t)){n={};for(const[s,o]of Object.entries(t.fields))Te.isInstance(o)?n[s]=o.inputSchema||o.valueSchema:n[s]=o}else n=t.shape;const r={...e};for(const[s,o]of Object.entries(n))s.startsWith("_")?r[s]=o.optional():r[s]=o;return re(r)}function Om(t){if(te(t))return ro(t);if(ne.isInstance(t)){const e={};for(const[n,r]of Object.entries(t.fields)){let s;Te.isInstance(r)?s=r.inputSchema||r.valueSchema:s=r,e[n]=Ni(s)?s.optional():ve().optional()}return re(e)}return re({})}function Pe(t){if(t){if(["model_request","tools",N].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return N;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function nc(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var No=class extends ae{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.recurse=t.recurse??this.recurse}getState(){return this.#e}setState(t){this.#e={...this.#e,...t}}async invoke(t,e){const n=$e(this.config,e),r=await He.runWithConfig(n,async()=>this.func(t,n));return ae.isRunnable(r)&&this.recurse?await He.runWithConfig(n,async()=>r.invoke(t,n)):(this.#e=r,r)}};function Nm(t,e){let n,r;if(e==="inline")n=km,r=Tm;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(o){return o.map(n)}return it.from([yr.from(s),t,yr.from(r)])}function Rm(t){return P.isInstance(t)||typeof t=="object"&&t!==null&&"structuredResponse"in t&&"messages"in t}const W="model_request";var $m=class extends No{#e;#r;#t;constructor(t){super({name:t.name??"model",func:(e,n)=>this.#s(e,n)}),this.#e=t,this.#r=t.systemMessage}#n(t){if(!this.#e.responseFormat)return;const e=ql(this.#e.responseFormat,void 0,t);return e.every(r=>r instanceof et)?{type:"native",strategy:e[0]}:{type:"tool",tools:e.filter(r=>r instanceof Xe).reduce((r,s)=>(r[s.name]=s,r),{})}}async#s(t,e){const n=t.messages.at(-1);if(n&&j.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};const r=await this.#c(t,e);return"structuredResponse"in r?{messages:[...t.messages,...r.messages||[]],structuredResponse:r.structuredResponse}:r instanceof G?r:(r.name=this.name,r.lc_kwargs.name=this.name,this.#h(t,r)?{messages:[new P({content:"Sorry, need more steps to process this request.",name:this.name,id:r.id})]}:{messages:[r]})}#l(){if(typeof this.#e.model=="string")return lt(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#c(t,e,n={}){const r=await this.#l(),s=e,o=async c=>{tc(c.model);const u=this.#n(c.model),d=await this.#a(c.model,c,u),h=[...this.#t.text===""?[]:[this.#t],...c.messages],f=nc(this.#e.signal,e.signal),m=await Eu(d.invoke(h,{...e,signal:f}),f);if(u?.type==="native"){const T=u.strategy.parse(m);return T?{structuredResponse:T,messages:[m]}:m}if(!u||!m.tool_calls)return m;const p=m.tool_calls.filter(T=>T.name in u.tools);if(p.length===0)return m;if(p.length>1)return this.#u(m,p,u);const k=u.tools[p[0].name]?.options?.toolMessageContent;return this.#o(m,p[0],u,k??n.lastMessage)},i=this.#e.wrapModelCallHookMiddleware??[];let a=o;for(let c=i.length-1;c>=0;c--){const[u,d]=i[c];if(u.wrapModelCall){const h=a,f=u,m=d;a=async p=>{const C=f.contextSchema?nt(f.contextSchema,s?.context||{}):s?.context,k=Object.freeze({context:C,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),T={...p,state:{...u.stateSchema?nt(Om(u.stateSchema),t):{},...m(),messages:t.messages},runtime:k},_=async g=>{const v=g.tools??[],M=v.filter(x=>Or(x)&&!this.#e.toolClasses.some(I=>I.name===x.name));if(M.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${M.map(x=>x.name).join(", ")}. This is not supported.`);const w=v.filter(x=>Or(x)&&this.#e.toolClasses.every(I=>I!==x));if(w.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${w.map(x=>x.name).join(", ")}. This is not supported.`);let b=g;const E=g.systemPrompt!==this.#t.text,S=g.systemMessage!==this.#t;if(E&&S)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");return E&&(this.#t=new oe({content:[{type:"text",text:g.systemPrompt}]}),b={...g,systemPrompt:this.#t.text,systemMessage:this.#t}),S&&(this.#t=new oe({...g.systemMessage}),b={...g,systemPrompt:this.#t.text,systemMessage:this.#t}),h(b)};if(!f.wrapModelCall)return _(T);try{const g=await f.wrapModelCall(T,_);if(!Rm(g))throw new Error(`Invalid response from "wrapModelCall" in middleware "${f.name}": expected AIMessage, got ${typeof g}`);return g}catch(g){throw Io.wrap(g,f.name)}}}}this.#t=this.#r;const l={model:r,systemPrompt:this.#t?.text,systemMessage:this.#t,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:s?.context,writer:s.writer,interrupt:s.interrupt,signal:s.signal})};return a(l)}#u(t,e,n){const r=new qs(e.map(s=>s.name));return this.#i(r,t,e[0],n)}#o(t,e,n,r){const s=n.tools[e.name];try{const o=s.parse(e.args);return{structuredResponse:o,messages:[t,new j({tool_call_id:e.id??"",content:JSON.stringify(o),name:e.name}),new P(r??`Returning structured response: ${JSON.stringify(o)}`)]}}catch(o){return this.#i(o,t,e,n)}}async#i(t,e,n,r){const s=Object.values(r.tools).at(0)?.options?.handleError,o=n.id;if(!o)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(s===!1)throw t;if(s===void 0||typeof s=="boolean"&&s||Array.isArray(s)&&s.some(i=>i instanceof qs))return new G({update:{messages:[e,new j({content:t.message,tool_call_id:o})]},goto:W});if(typeof s=="string")return new G({update:{messages:[e,new j({content:s,tool_call_id:o})]},goto:W});if(typeof s=="function"){const i=await s(t);if(typeof i!="string")throw new Error("Error handler must return a string.");return new G({update:{messages:[e,new j({content:i,tool_call_id:o})]},goto:W})}return new G({update:{messages:[e,new j({content:t.message,tool_call_id:o})]},goto:W})}#h(t,e){const n=P.isInstance(e)&&e.tool_calls?.every(s=>this.#e.shouldReturnDirect.has(s.name)),r="remainingSteps"in t?t.remainingSteps:void 0;return!!(r&&(r<1&&n||r<2&&Nr(t.messages.at(-1))))}async#a(t,e,n){const r={},s=Object.values(n&&"tools"in n?n.tools:{}),o=[...e?.tools??this.#e.toolClasses,...s.map(c=>c.tool)],i=e?.toolChoice||(s.length>0?"any":void 0);if(n?.type==="native"){const c=e?.modelSettings?.strict??n?.strategy?.strict??!0,u={name:n.strategy.schema?.name??"extract",description:Ts(n.strategy.schema),schema:n.strategy.schema,strict:c};Object.assign(r,{response_format:{type:"json_schema",json_schema:u},output_format:{type:"json_schema",schema:n.strategy.schema},headers:{"anthropic-beta":"structured-outputs-2025-11-13"},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:n.strategy.schema},strict:c})}const a=await xm(t,o,{...r,...e?.modelSettings,tool_choice:i});return this.#e.includeAgentName==="inline"?Nm(a,this.#e.includeAgentName):a}getState(){const t=super.getState(),e=t&&!(t instanceof G)?t:{};return{messages:[],...e}}};const wi=(t,e)=>`Error: ${t} is not a valid tool, try one of [${e.join(", ")}].`,H="tools",rc=t=>Array.isArray(t)&&t.every(_n.isInstance),jm=t=>typeof t=="object"&&t!=null&&"messages"in t&&rc(t.messages),Lm=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function Dm(t,e){return t instanceof Ao?new j({content:t.message,tool_call_id:e.id,name:e.name}):new j({content:`${t}
70
+ })`)}return n}function Pm(t){const e={messages:no(()=>[]),structuredResponse:ve().optional()};if(!t)return re(e);let n;if(ne.isInstance(t)){n={};for(const[s,o]of Object.entries(t.fields))ke.isInstance(o)?n[s]=o.inputSchema||o.valueSchema:n[s]=o}else n=t.shape;const r={...e};for(const[s,o]of Object.entries(n))s.startsWith("_")?r[s]=o.optional():r[s]=o;return re(r)}function Om(t){if(te(t))return ro(t);if(ne.isInstance(t)){const e={};for(const[n,r]of Object.entries(t.fields)){let s;ke.isInstance(r)?s=r.inputSchema||r.valueSchema:s=r,e[n]=Ni(s)?s.optional():ve().optional()}return re(e)}return re({})}function Pe(t){if(t){if(["model_request","tools",N].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return N;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function nc(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var No=class extends ae{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.recurse=t.recurse??this.recurse}getState(){return this.#e}setState(t){this.#e={...this.#e,...t}}async invoke(t,e){const n=$e(this.config,e),r=await He.runWithConfig(n,async()=>this.func(t,n));return ae.isRunnable(r)&&this.recurse?await He.runWithConfig(n,async()=>r.invoke(t,n)):(this.#e=r,r)}};function Nm(t,e){let n,r;if(e==="inline")n=Tm,r=km;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(o){return o.map(n)}return it.from([yr.from(s),t,yr.from(r)])}function Rm(t){return P.isInstance(t)||typeof t=="object"&&t!==null&&"structuredResponse"in t&&"messages"in t}const W="model_request";var $m=class extends No{#e;#r;#t;constructor(t){super({name:t.name??"model",func:(e,n)=>this.#s(e,n)}),this.#e=t,this.#r=t.systemMessage}#n(t){if(!this.#e.responseFormat)return;const e=ql(this.#e.responseFormat,void 0,t);return e.every(r=>r instanceof et)?{type:"native",strategy:e[0]}:{type:"tool",tools:e.filter(r=>r instanceof Xe).reduce((r,s)=>(r[s.name]=s,r),{})}}async#s(t,e){const n=t.messages.at(-1);if(n&&j.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};const r=await this.#c(t,e);return"structuredResponse"in r?{messages:[...t.messages,...r.messages||[]],structuredResponse:r.structuredResponse}:r instanceof G?r:(r.name=this.name,r.lc_kwargs.name=this.name,this.#h(t,r)?{messages:[new P({content:"Sorry, need more steps to process this request.",name:this.name,id:r.id})]}:{messages:[r]})}#l(){if(typeof this.#e.model=="string")return lt(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#c(t,e,n={}){const r=await this.#l(),s=e,o=async c=>{tc(c.model);const u=this.#n(c.model),d=await this.#a(c.model,c,u),h=[...this.#t.text===""?[]:[this.#t],...c.messages],f=nc(this.#e.signal,e.signal),m=await Eu(d.invoke(h,{...e,signal:f}),f);if(u?.type==="native"){const k=u.strategy.parse(m);return k?{structuredResponse:k,messages:[m]}:m}if(!u||!m.tool_calls)return m;const p=m.tool_calls.filter(k=>k.name in u.tools);if(p.length===0)return m;if(p.length>1)return this.#u(m,p,u);const T=u.tools[p[0].name]?.options?.toolMessageContent;return this.#o(m,p[0],u,T??n.lastMessage)},i=this.#e.wrapModelCallHookMiddleware??[];let a=o;for(let c=i.length-1;c>=0;c--){const[u,d]=i[c];if(u.wrapModelCall){const h=a,f=u,m=d;a=async p=>{const C=f.contextSchema?nt(f.contextSchema,s?.context||{}):s?.context,T=Object.freeze({context:C,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),k={...p,state:{...u.stateSchema?nt(Om(u.stateSchema),t):{},...m(),messages:t.messages},runtime:T},_=async g=>{const v=g.tools??[],M=v.filter(x=>Or(x)&&!this.#e.toolClasses.some(I=>I.name===x.name));if(M.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${M.map(x=>x.name).join(", ")}. This is not supported.`);const w=v.filter(x=>Or(x)&&this.#e.toolClasses.every(I=>I!==x));if(w.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${w.map(x=>x.name).join(", ")}. This is not supported.`);let b=g;const E=g.systemPrompt!==this.#t.text,S=g.systemMessage!==this.#t;if(E&&S)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");return E&&(this.#t=new oe({content:[{type:"text",text:g.systemPrompt}]}),b={...g,systemPrompt:this.#t.text,systemMessage:this.#t}),S&&(this.#t=new oe({...g.systemMessage}),b={...g,systemPrompt:this.#t.text,systemMessage:this.#t}),h(b)};if(!f.wrapModelCall)return _(k);try{const g=await f.wrapModelCall(k,_);if(!Rm(g))throw new Error(`Invalid response from "wrapModelCall" in middleware "${f.name}": expected AIMessage, got ${typeof g}`);return g}catch(g){throw Io.wrap(g,f.name)}}}}this.#t=this.#r;const l={model:r,systemPrompt:this.#t?.text,systemMessage:this.#t,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:s?.context,writer:s.writer,interrupt:s.interrupt,signal:s.signal})};return a(l)}#u(t,e,n){const r=new qs(e.map(s=>s.name));return this.#i(r,t,e[0],n)}#o(t,e,n,r){const s=n.tools[e.name];try{const o=s.parse(e.args);return{structuredResponse:o,messages:[t,new j({tool_call_id:e.id??"",content:JSON.stringify(o),name:e.name}),new P(r??`Returning structured response: ${JSON.stringify(o)}`)]}}catch(o){return this.#i(o,t,e,n)}}async#i(t,e,n,r){const s=Object.values(r.tools).at(0)?.options?.handleError,o=n.id;if(!o)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(s===!1)throw t;if(s===void 0||typeof s=="boolean"&&s||Array.isArray(s)&&s.some(i=>i instanceof qs))return new G({update:{messages:[e,new j({content:t.message,tool_call_id:o})]},goto:W});if(typeof s=="string")return new G({update:{messages:[e,new j({content:s,tool_call_id:o})]},goto:W});if(typeof s=="function"){const i=await s(t);if(typeof i!="string")throw new Error("Error handler must return a string.");return new G({update:{messages:[e,new j({content:i,tool_call_id:o})]},goto:W})}return new G({update:{messages:[e,new j({content:t.message,tool_call_id:o})]},goto:W})}#h(t,e){const n=P.isInstance(e)&&e.tool_calls?.every(s=>this.#e.shouldReturnDirect.has(s.name)),r="remainingSteps"in t?t.remainingSteps:void 0;return!!(r&&(r<1&&n||r<2&&Nr(t.messages.at(-1))))}async#a(t,e,n){const r={},s=Object.values(n&&"tools"in n?n.tools:{}),o=[...e?.tools??this.#e.toolClasses,...s.map(c=>c.tool)],i=e?.toolChoice||(s.length>0?"any":void 0);if(n?.type==="native"){const c=e?.modelSettings?.strict??n?.strategy?.strict??!0,u={name:n.strategy.schema?.name??"extract",description:ks(n.strategy.schema),schema:n.strategy.schema,strict:c};Object.assign(r,{response_format:{type:"json_schema",json_schema:u},output_format:{type:"json_schema",schema:n.strategy.schema},headers:{"anthropic-beta":"structured-outputs-2025-11-13"},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:n.strategy.schema},strict:c})}const a=await xm(t,o,{...r,...e?.modelSettings,tool_choice:i});return this.#e.includeAgentName==="inline"?Nm(a,this.#e.includeAgentName):a}getState(){const t=super.getState(),e=t&&!(t instanceof G)?t:{};return{messages:[],...e}}};const wi=(t,e)=>`Error: ${t} is not a valid tool, try one of [${e.join(", ")}].`,H="tools",rc=t=>Array.isArray(t)&&t.every(_n.isInstance),jm=t=>typeof t=="object"&&t!=null&&"messages"in t&&rc(t.messages),Lm=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function Dm(t,e){return t instanceof Ao?new j({content:t.message,tool_call_id:e.id,name:e.name}):new j({content:`${t}
71
71
  Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var Fm=class extends No{tools;trace=!1;signal;handleToolErrors=Dm;wrapToolCall;constructor(t,e){const{name:n,tags:r,handleToolErrors:s,signal:o,wrapToolCall:i}=e??{};super({name:n,tags:r,func:(a,l)=>this.run(a,l)}),this.options=e,this.tools=t,this.handleToolErrors=s??this.handleToolErrors,this.signal=o,this.wrapToolCall=i}#e(t,e,n){if(yt(t)||this.signal?.aborted||n&&this.handleToolErrors!==!0||!this.handleToolErrors)throw t;if(typeof this.handleToolErrors=="function"){const r=this.handleToolErrors(t,e);if(r&&j.isInstance(r))return r;throw t}else if(this.handleToolErrors)return new j({name:e.name,content:`${t}
72
- Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,n){const r=e,s={context:r?.context,writer:r?.writer,interrupt:r?.interrupt,signal:r?.signal},o=this.tools.find(l=>l.name===t.name),i=async l=>{const{toolCall:c,tool:u}=l,d=u??this.tools.find(f=>f.name===c.name);if(d===void 0){const f=this.tools.map(m=>m.name);return new j({content:wi(c.name,f),tool_call_id:c.id,name:c.name,status:"error"})}const h=d;try{const f=await h.invoke({...c,type:"tool_call"},{...e,config:e,toolCallId:c.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:nc(this.signal,e.signal)});return j.isInstance(f)||q(f)?f:new j({name:h.name,content:typeof f=="string"?f:JSON.stringify(f),tool_call_id:c.id})}catch(f){throw f instanceof xu?new Ao(f,c):f}},a={toolCall:t,tool:o,state:n,runtime:s};if(this.wrapToolCall)try{return await this.wrapToolCall(a,i)}catch(l){return this.#e(l,t,!0)}if(!o){const l=this.tools.map(c=>c.name);return new j({content:wi(t.name,l),tool_call_id:t.id,name:t.name,status:"error"})}try{return await i(a)}catch(l){return this.#e(l,t,!1)}}async run(t,e){let n;if(Lm(t)){const{lg_tool_call:o,jumpTo:i,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let o;if(rc(t))o=t;else if(jm(t))o=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const i=new Set(o.filter(l=>l.getType()==="tool").map(l=>l.tool_call_id));let a;for(let l=o.length-1;l>=0;l-=1){const c=o[l];if(P.isInstance(c)){a=c;break}}if(!P.isInstance(a))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(a.tool_calls?.filter(l=>l.id==null||!i.has(l.id)).map(l=>this.runTool(l,e,t))??[])}if(!n.some(q))return Array.isArray(t)?n:{messages:n};const r=[];let s=null;for(const o of n)q(o)?o.graph===G.PARENT&&Array.isArray(o.goto)&&o.goto.every(i=>Um(i))?s?s.goto.push(...o.goto):s=new G({graph:G.PARENT,goto:o.goto}):r.push(o):r.push(Array.isArray(t)?[o]:{messages:[o]});return s&&r.push(s),r}};function Um(t){return t instanceof he}var Vm=class{},Bm=class{},Br=class extends No{#e;constructor(t,e){super(t),this.#e=e}async invokeMiddleware(t,e){let n={};if(this.middleware.contextSchema){const l=this.middleware.contextSchema?.shape;if(l){const c={},u=e?.context||{};for(const d of Object.keys(l))d in u&&(c[d]=u[d]);n=nt(this.middleware.contextSchema,c)}}const r={...this.#e.getState(),...t,messages:t.messages},s={context:n,writer:e?.writer,interrupt:e?.interrupt,signal:e?.signal},o=await this.runHook(r,Object.freeze(Object.assign(new Bm,{...s,context:Object.freeze(Object.assign(new Vm,n))})));if(!o)return{...r,jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=tt(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=tt(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=tt(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=tt(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof o.jumpTo=="string"&&!i?.includes(o.jumpTo)){const l=i&&i.length>0?`must be one of: ${i?.join(", ")}.`:a?`no ${a} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${o.jumpTo}, ${l}.`)}if(typeof o=="object"&&"type"in o){if(o.type==="terminate"){if(o.error)throw o.error;return{...r,...o.result||{},jumpTo:o.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(o)}`)}return{...r,...o,jumpTo:o.jumpTo}}get nodeOptions(){return{input:Pm(this.middleware.stateSchema)}}},zm=class extends Br{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t,e){super({name:`BeforeAgentNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Vr(this.middleware.beforeAgent)(t,e)}},Hm=class extends Br{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t,e){super({name:`BeforeModelNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Vr(this.middleware.beforeModel)(t,e)}},Wm=class extends Br{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t,e){super({name:`AfterModelNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Vr(this.middleware.afterModel)(t,e)}},Gm=class extends Br{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t,e){super({name:`AfterAgentNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Vr(this.middleware.afterAgent)(t,e)}},Km=class{#e=new Map;addNode(t,e){this.#e.set(t.name,[...this.#e.get(t.name)??[],e])}getState(t){const n=(this.#e.get(t)??[]).reduce((r,s)=>({...r,...s.getState()??{}}),{});return delete n.jumpTo,n}},Jm=class{#e;#r="v2";#t;#n=new Km;constructor(t){if(this.options=t,this.#r=t.version??this.#r,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&tc(t.model);const e=this.options.middleware?.filter(w=>w.tools).flatMap(w=>w.tools)??[],n=[...t.tools??[],...e],r=new Set(n.filter(Or).filter(w=>"returnDirect"in w&&w.returnDirect).map(w=>w.name)),{state:s,input:o,output:i}=Sm(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),l=new um(s,{input:o,output:i,context:this.options.contextSchema}),c=[],u=[],d=[],h=[],f=[];this.#t=new $m({model:this.options.model,systemMessage:Em(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:n,shouldReturnDirect:r,signal:this.options.signal,wrapModelCallHookMiddleware:f});const m=new Set,p=this.options.middleware??[];for(let w=0;w<p.length;w++){let b,E,S,x;const I=p[w];if(m.has(I.name))throw new Error(`Middleware ${I.name} is defined multiple times`);if(m.add(I.name),I.beforeAgent){b=new zm(I,{getState:()=>this.#n.getState(I.name)}),this.#n.addNode(I,b);const O=`${I.name}.before_agent`;c.push({index:w,name:O,allowed:tt(I.beforeAgent)}),l.addNode(O,b,b.nodeOptions)}if(I.beforeModel){E=new Hm(I,{getState:()=>this.#n.getState(I.name)}),this.#n.addNode(I,E);const O=`${I.name}.before_model`;u.push({index:w,name:O,allowed:tt(I.beforeModel)}),l.addNode(O,E,E.nodeOptions)}if(I.afterModel){S=new Wm(I,{getState:()=>this.#n.getState(I.name)}),this.#n.addNode(I,S);const O=`${I.name}.after_model`;d.push({index:w,name:O,allowed:tt(I.afterModel)}),l.addNode(O,S,S.nodeOptions)}if(I.afterAgent){x=new Gm(I,{getState:()=>this.#n.getState(I.name)}),this.#n.addNode(I,x);const O=`${I.name}.after_agent`;h.push({index:w,name:O,allowed:tt(I.afterAgent)}),l.addNode(O,x,x.nodeOptions)}I.wrapModelCall&&f.push([I,()=>this.#n.getState(I.name)])}l.addNode(W,this.#t);const C=p.some(w=>w.wrapToolCall),k=n.filter(Or);if(k.length>0||C){const w=new Fm(k,{signal:this.options.signal,wrapToolCall:Am(p)});l.addNode(H,w)}let T;c.length>0?T=c[0].name:u.length>0?T=u[0].name:T=W;const _=u.length>0?u[0].name:W,g=h.length>0?h[h.length-1].name:N;l.addEdge(U,T);const v=k.length>0||C;for(let w=0;w<c.length;w++){const b=c[w],E=b.name,x=w===c.length-1?_:c[w+1].name;if(b.allowed&&b.allowed.length>0){const I=b.allowed.map(F=>Pe(F)).filter(F=>F!==H||v),O=Array.from(new Set([x,...I.map(F=>F===N?g:F)]));l.addConditionalEdges(E,this.#i(k,x,g,v),O)}else l.addEdge(E,x)}for(let w=0;w<u.length;w++){const b=u[w],E=b.name,x=w===u.length-1?W:u[w+1].name;if(b.allowed&&b.allowed.length>0){const I=b.allowed.map(F=>Pe(F)).filter(F=>F!==H||v),O=Array.from(new Set([x,...I]));l.addConditionalEdges(E,this.#h(k,x,v),O)}else l.addEdge(E,x)}const M=d.at(-1);if(d.length>0&&M)l.addEdge(W,M.name);else{const b=this.#s(k,!1,v).map(E=>E===N?g:E);b.length===1?l.addEdge(W,b[0]):l.addConditionalEdges(W,this.#c(g),b)}for(let w=d.length-1;w>0;w--){const b=d[w],E=b.name,S=d[w-1].name;if(b.allowed&&b.allowed.length>0){const x=b.allowed.map(O=>Pe(O)).filter(O=>O!==H||v),I=Array.from(new Set([S,...x]));l.addConditionalEdges(E,this.#o(k,b.allowed,S,v),I)}else l.addEdge(E,S)}if(d.length>0){const w=d[0],b=w.name,E=this.#s(k,!0,v).filter(I=>I!==H||v),S=!!(w.allowed&&w.allowed.length>0),x=E.map(I=>I===N?g:I);l.addConditionalEdges(b,this.#u(k,S,g,v),x)}for(let w=h.length-1;w>0;w--){const b=h[w],E=b.name,S=h[w-1].name;if(b.allowed&&b.allowed.length>0){const x=b.allowed.map(O=>Pe(O)).filter(O=>O!==H||v),I=Array.from(new Set([S,...x]));l.addConditionalEdges(E,this.#o(k,b.allowed,S,v),I)}else l.addEdge(E,S)}if(h.length>0){const w=h[0],b=w.name;if(w.allowed&&w.allowed.length>0){const E=w.allowed.map(x=>Pe(x)).filter(x=>x!==H||v),S=Array.from(new Set([N,...E]));l.addConditionalEdges(b,this.#o(k,w.allowed,N,v),S)}else l.addEdge(b,N)}if(v){const w=_;r.size>0?l.addConditionalEdges(H,this.#l(r,g),[w,g]):l.addEdge(H,w)}this.#e=l.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#s(t,e=!1,n=t.length>0){const r=[];return n&&r.push(H),e&&r.push(W),r.push(N),r}#l(t,e){return n=>{const s=n.messages,o=s[s.length-1];return j.isInstance(o)&&o.name&&t.has(o.name)?this.options.responseFormat?W:e:W}}#c(t=N){return e=>{const s=e.messages.at(-1);if(!P.isInstance(s)||!s.tool_calls||s.tool_calls.length===0||s.tool_calls.every(a=>a.name.startsWith("extract-")))return t;if(this.#r==="v1")return H;const i=s.tool_calls.filter(a=>!a.name.startsWith("extract-"));return i.length===0?t:i.map(a=>new he(H,{...e,lg_tool_call:a}))}}#u(t,e,n,r=t.length>0){const s=!!this.options.responseFormat;return o=>{const i=o,a=i.messages,l=a.at(-1);if(P.isInstance(l)&&(!l.tool_calls||l.tool_calls.length===0))return n;if(e&&i.jumpTo){const p=Pe(i.jumpTo);return p===N?n:p===H?r?new he(H,{...o,jumpTo:void 0}):n:new he(W,{...o,jumpTo:void 0})}const c=a.filter(j.isInstance),u=a.filter(P.isInstance).at(-1),d=u?.tool_calls?.filter(p=>!c.some(C=>C.tool_call_id===p.id));if(d&&d.length>0)return d.map(p=>new he(H,{...o,lg_tool_call:p}));const h=u?.tool_calls?.some(p=>p.name.startsWith("extract-"));if(d&&d.length===0&&!h&&s)return W;if(!P.isInstance(l)||!l.tool_calls||l.tool_calls.length===0)return n;const f=l.tool_calls.every(p=>p.name.startsWith("extract-")),m=l.tool_calls.some(p=>!p.name.startsWith("extract-"));return f||!m?n:H}}#o(t,e,n,r=t.length>0){const s=new Set(e.map(o=>Pe(o)));return o=>{const i=o;if(i.jumpTo){const a=Pe(i.jumpTo);if(a===N&&s.has(N))return N;if(a===H&&s.has(H))return r?new he(H,{...o,jumpTo:void 0}):N;if(a===W&&s.has(W))return new he(W,{...o,jumpTo:void 0})}return n}}#i(t,e,n,r=t.length>0){return s=>{const o=s;if(!o.jumpTo)return e;const i=Pe(o.jumpTo);return i===N?n:i===H?r?new he(H,{...s,jumpTo:void 0}):n:new he(W,{...s,jumpTo:void 0})}}#h(t,e,n=t.length>0){return r=>{const s=r;if(!s.jumpTo)return e;const o=Pe(s.jumpTo);return o===N?N:o===H?n?new he(H,{...r,jumpTo:void 0}):N:new he(W,{...r,jumpTo:void 0})}}async#a(t,e){if(!this.options.middleware||this.options.middleware.length===0||t instanceof G||!t)return t;const n=await Im(this.options.middleware,t),s={...(await this.#e.getState(e).catch(()=>({values:{}}))).values,...t};if(!s)return s;for(const[o,i]of Object.entries(n))o in s||(s[o]=i);return s}async invoke(t,e){const n=await this.#a(t,e);return this.#e.invoke(n,e)}async stream(t,e){const n=await this.#a(t,e);return this.#e.stream(n,e)}async drawMermaidPng(t){const r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(t){return(await this.#e.getGraphAsync()).drawMermaid(t)}streamEvents(t,e,n){return this.#e.streamEvents(t,{...e,version:e?.version??"v2"},n)}getGraphAsync(t){return this.#e.getGraphAsync(t)}getState(t,e){return this.#e.getState(t,e)}getStateHistory(t,e){return this.#e.getStateHistory(t,e)}getSubgraphs(t,e){return this.#e.getSubgraphs(t,e)}getSubgraphAsync(t,e){return this.#e.getSubgraphsAsync(t,e)}updateState(t,e,n){return this.#e.updateState(t,e,n)}get builder(){return this.#e.builder}};function sc(t){return new Jm(t)}const qm=Dn().args(Le(),Le(),Le()).returns(De([ie(),Ri(ie())])),oc=["approve","edit","reject"],Ym=tn(oc),Xm=K({allowedDecisions:Ke(Ym),description:De([ie(),qm]).optional(),argsSchema:Mn(Mu()).optional()}),bi=K({interruptOn:Mn(De([_t(),Xm])).optional(),descriptionPrefix:ie().default("Tool execution requires approval")});function Zm(t){const e=async(r,s,o,i)=>{const a=r.name,l=r.args,c=s.description;let u;typeof c=="function"?u=await c(r,o,i):c!==void 0?u=c:u=`${t.descriptionPrefix??"Tool execution requires approval"}
72
+ Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,n){const r=e,s={context:r?.context,writer:r?.writer,interrupt:r?.interrupt,signal:r?.signal},o=this.tools.find(l=>l.name===t.name),i=async l=>{const{toolCall:c,tool:u}=l,d=u??this.tools.find(f=>f.name===c.name);if(d===void 0){const f=this.tools.map(m=>m.name);return new j({content:wi(c.name,f),tool_call_id:c.id,name:c.name,status:"error"})}const h=d;try{const f=await h.invoke({...c,type:"tool_call"},{...e,config:e,toolCallId:c.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:nc(this.signal,e.signal)});return j.isInstance(f)||q(f)?f:new j({name:h.name,content:typeof f=="string"?f:JSON.stringify(f),tool_call_id:c.id})}catch(f){throw f instanceof xu?new Ao(f,c):f}},a={toolCall:t,tool:o,state:n,runtime:s};if(this.wrapToolCall)try{return await this.wrapToolCall(a,i)}catch(l){return this.#e(l,t,!0)}if(!o){const l=this.tools.map(c=>c.name);return new j({content:wi(t.name,l),tool_call_id:t.id,name:t.name,status:"error"})}try{return await i(a)}catch(l){return this.#e(l,t,!1)}}async run(t,e){let n;if(Lm(t)){const{lg_tool_call:o,jumpTo:i,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let o;if(rc(t))o=t;else if(jm(t))o=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const i=new Set(o.filter(l=>l.getType()==="tool").map(l=>l.tool_call_id));let a;for(let l=o.length-1;l>=0;l-=1){const c=o[l];if(P.isInstance(c)){a=c;break}}if(!P.isInstance(a))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(a.tool_calls?.filter(l=>l.id==null||!i.has(l.id)).map(l=>this.runTool(l,e,t))??[])}if(!n.some(q))return Array.isArray(t)?n:{messages:n};const r=[];let s=null;for(const o of n)q(o)?o.graph===G.PARENT&&Array.isArray(o.goto)&&o.goto.every(i=>Um(i))?s?s.goto.push(...o.goto):s=new G({graph:G.PARENT,goto:o.goto}):r.push(o):r.push(Array.isArray(t)?[o]:{messages:[o]});return s&&r.push(s),r}};function Um(t){return t instanceof he}var Vm=class{},Bm=class{},Br=class extends No{#e;constructor(t,e){super(t),this.#e=e}async invokeMiddleware(t,e){let n={};if(this.middleware.contextSchema){const l=this.middleware.contextSchema?.shape;if(l){const c={},u=e?.context||{};for(const d of Object.keys(l))d in u&&(c[d]=u[d]);n=nt(this.middleware.contextSchema,c)}}const r={...this.#e.getState(),...t,messages:t.messages},s={context:n,writer:e?.writer,interrupt:e?.interrupt,signal:e?.signal},o=await this.runHook(r,Object.freeze(Object.assign(new Bm,{...s,context:Object.freeze(Object.assign(new Vm,n))})));if(!o)return{...r,jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=tt(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=tt(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=tt(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=tt(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof o.jumpTo=="string"&&!i?.includes(o.jumpTo)){const l=i&&i.length>0?`must be one of: ${i?.join(", ")}.`:a?`no ${a} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${o.jumpTo}, ${l}.`)}if(typeof o=="object"&&"type"in o){if(o.type==="terminate"){if(o.error)throw o.error;return{...r,...o.result||{},jumpTo:o.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(o)}`)}return{...r,...o,jumpTo:o.jumpTo}}get nodeOptions(){return{input:Pm(this.middleware.stateSchema)}}},zm=class extends Br{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t,e){super({name:`BeforeAgentNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Vr(this.middleware.beforeAgent)(t,e)}},Hm=class extends Br{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t,e){super({name:`BeforeModelNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Vr(this.middleware.beforeModel)(t,e)}},Wm=class extends Br{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t,e){super({name:`AfterModelNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Vr(this.middleware.afterModel)(t,e)}},Gm=class extends Br{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t,e){super({name:`AfterAgentNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Vr(this.middleware.afterAgent)(t,e)}},Km=class{#e=new Map;addNode(t,e){this.#e.set(t.name,[...this.#e.get(t.name)??[],e])}getState(t){const n=(this.#e.get(t)??[]).reduce((r,s)=>({...r,...s.getState()??{}}),{});return delete n.jumpTo,n}},Jm=class{#e;#r="v2";#t;#n=new Km;constructor(t){if(this.options=t,this.#r=t.version??this.#r,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&tc(t.model);const e=this.options.middleware?.filter(w=>w.tools).flatMap(w=>w.tools)??[],n=[...t.tools??[],...e],r=new Set(n.filter(Or).filter(w=>"returnDirect"in w&&w.returnDirect).map(w=>w.name)),{state:s,input:o,output:i}=Sm(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),l=new um(s,{input:o,output:i,context:this.options.contextSchema}),c=[],u=[],d=[],h=[],f=[];this.#t=new $m({model:this.options.model,systemMessage:Em(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:n,shouldReturnDirect:r,signal:this.options.signal,wrapModelCallHookMiddleware:f});const m=new Set,p=this.options.middleware??[];for(let w=0;w<p.length;w++){let b,E,S,x;const I=p[w];if(m.has(I.name))throw new Error(`Middleware ${I.name} is defined multiple times`);if(m.add(I.name),I.beforeAgent){b=new zm(I,{getState:()=>this.#n.getState(I.name)}),this.#n.addNode(I,b);const O=`${I.name}.before_agent`;c.push({index:w,name:O,allowed:tt(I.beforeAgent)}),l.addNode(O,b,b.nodeOptions)}if(I.beforeModel){E=new Hm(I,{getState:()=>this.#n.getState(I.name)}),this.#n.addNode(I,E);const O=`${I.name}.before_model`;u.push({index:w,name:O,allowed:tt(I.beforeModel)}),l.addNode(O,E,E.nodeOptions)}if(I.afterModel){S=new Wm(I,{getState:()=>this.#n.getState(I.name)}),this.#n.addNode(I,S);const O=`${I.name}.after_model`;d.push({index:w,name:O,allowed:tt(I.afterModel)}),l.addNode(O,S,S.nodeOptions)}if(I.afterAgent){x=new Gm(I,{getState:()=>this.#n.getState(I.name)}),this.#n.addNode(I,x);const O=`${I.name}.after_agent`;h.push({index:w,name:O,allowed:tt(I.afterAgent)}),l.addNode(O,x,x.nodeOptions)}I.wrapModelCall&&f.push([I,()=>this.#n.getState(I.name)])}l.addNode(W,this.#t);const C=p.some(w=>w.wrapToolCall),T=n.filter(Or);if(T.length>0||C){const w=new Fm(T,{signal:this.options.signal,wrapToolCall:Am(p)});l.addNode(H,w)}let k;c.length>0?k=c[0].name:u.length>0?k=u[0].name:k=W;const _=u.length>0?u[0].name:W,g=h.length>0?h[h.length-1].name:N;l.addEdge(U,k);const v=T.length>0||C;for(let w=0;w<c.length;w++){const b=c[w],E=b.name,x=w===c.length-1?_:c[w+1].name;if(b.allowed&&b.allowed.length>0){const I=b.allowed.map(F=>Pe(F)).filter(F=>F!==H||v),O=Array.from(new Set([x,...I.map(F=>F===N?g:F)]));l.addConditionalEdges(E,this.#i(T,x,g,v),O)}else l.addEdge(E,x)}for(let w=0;w<u.length;w++){const b=u[w],E=b.name,x=w===u.length-1?W:u[w+1].name;if(b.allowed&&b.allowed.length>0){const I=b.allowed.map(F=>Pe(F)).filter(F=>F!==H||v),O=Array.from(new Set([x,...I]));l.addConditionalEdges(E,this.#h(T,x,v),O)}else l.addEdge(E,x)}const M=d.at(-1);if(d.length>0&&M)l.addEdge(W,M.name);else{const b=this.#s(T,!1,v).map(E=>E===N?g:E);b.length===1?l.addEdge(W,b[0]):l.addConditionalEdges(W,this.#c(g),b)}for(let w=d.length-1;w>0;w--){const b=d[w],E=b.name,S=d[w-1].name;if(b.allowed&&b.allowed.length>0){const x=b.allowed.map(O=>Pe(O)).filter(O=>O!==H||v),I=Array.from(new Set([S,...x]));l.addConditionalEdges(E,this.#o(T,b.allowed,S,v),I)}else l.addEdge(E,S)}if(d.length>0){const w=d[0],b=w.name,E=this.#s(T,!0,v).filter(I=>I!==H||v),S=!!(w.allowed&&w.allowed.length>0),x=E.map(I=>I===N?g:I);l.addConditionalEdges(b,this.#u(T,S,g,v),x)}for(let w=h.length-1;w>0;w--){const b=h[w],E=b.name,S=h[w-1].name;if(b.allowed&&b.allowed.length>0){const x=b.allowed.map(O=>Pe(O)).filter(O=>O!==H||v),I=Array.from(new Set([S,...x]));l.addConditionalEdges(E,this.#o(T,b.allowed,S,v),I)}else l.addEdge(E,S)}if(h.length>0){const w=h[0],b=w.name;if(w.allowed&&w.allowed.length>0){const E=w.allowed.map(x=>Pe(x)).filter(x=>x!==H||v),S=Array.from(new Set([N,...E]));l.addConditionalEdges(b,this.#o(T,w.allowed,N,v),S)}else l.addEdge(b,N)}if(v){const w=_;r.size>0?l.addConditionalEdges(H,this.#l(r,g),[w,g]):l.addEdge(H,w)}this.#e=l.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#s(t,e=!1,n=t.length>0){const r=[];return n&&r.push(H),e&&r.push(W),r.push(N),r}#l(t,e){return n=>{const s=n.messages,o=s[s.length-1];return j.isInstance(o)&&o.name&&t.has(o.name)?this.options.responseFormat?W:e:W}}#c(t=N){return e=>{const s=e.messages.at(-1);if(!P.isInstance(s)||!s.tool_calls||s.tool_calls.length===0||s.tool_calls.every(a=>a.name.startsWith("extract-")))return t;if(this.#r==="v1")return H;const i=s.tool_calls.filter(a=>!a.name.startsWith("extract-"));return i.length===0?t:i.map(a=>new he(H,{...e,lg_tool_call:a}))}}#u(t,e,n,r=t.length>0){const s=!!this.options.responseFormat;return o=>{const i=o,a=i.messages,l=a.at(-1);if(P.isInstance(l)&&(!l.tool_calls||l.tool_calls.length===0))return n;if(e&&i.jumpTo){const p=Pe(i.jumpTo);return p===N?n:p===H?r?new he(H,{...o,jumpTo:void 0}):n:new he(W,{...o,jumpTo:void 0})}const c=a.filter(j.isInstance),u=a.filter(P.isInstance).at(-1),d=u?.tool_calls?.filter(p=>!c.some(C=>C.tool_call_id===p.id));if(d&&d.length>0)return d.map(p=>new he(H,{...o,lg_tool_call:p}));const h=u?.tool_calls?.some(p=>p.name.startsWith("extract-"));if(d&&d.length===0&&!h&&s)return W;if(!P.isInstance(l)||!l.tool_calls||l.tool_calls.length===0)return n;const f=l.tool_calls.every(p=>p.name.startsWith("extract-")),m=l.tool_calls.some(p=>!p.name.startsWith("extract-"));return f||!m?n:H}}#o(t,e,n,r=t.length>0){const s=new Set(e.map(o=>Pe(o)));return o=>{const i=o;if(i.jumpTo){const a=Pe(i.jumpTo);if(a===N&&s.has(N))return N;if(a===H&&s.has(H))return r?new he(H,{...o,jumpTo:void 0}):N;if(a===W&&s.has(W))return new he(W,{...o,jumpTo:void 0})}return n}}#i(t,e,n,r=t.length>0){return s=>{const o=s;if(!o.jumpTo)return e;const i=Pe(o.jumpTo);return i===N?n:i===H?r?new he(H,{...s,jumpTo:void 0}):n:new he(W,{...s,jumpTo:void 0})}}#h(t,e,n=t.length>0){return r=>{const s=r;if(!s.jumpTo)return e;const o=Pe(s.jumpTo);return o===N?N:o===H?n?new he(H,{...r,jumpTo:void 0}):N:new he(W,{...r,jumpTo:void 0})}}async#a(t,e){if(!this.options.middleware||this.options.middleware.length===0||t instanceof G||!t)return t;const n=await Im(this.options.middleware,t),s={...(await this.#e.getState(e).catch(()=>({values:{}}))).values,...t};if(!s)return s;for(const[o,i]of Object.entries(n))o in s||(s[o]=i);return s}async invoke(t,e){const n=await this.#a(t,e);return this.#e.invoke(n,e)}async stream(t,e){const n=await this.#a(t,e);return this.#e.stream(n,e)}async drawMermaidPng(t){const r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(t){return(await this.#e.getGraphAsync()).drawMermaid(t)}streamEvents(t,e,n){return this.#e.streamEvents(t,{...e,version:e?.version??"v2"},n)}getGraphAsync(t){return this.#e.getGraphAsync(t)}getState(t,e){return this.#e.getState(t,e)}getStateHistory(t,e){return this.#e.getStateHistory(t,e)}getSubgraphs(t,e){return this.#e.getSubgraphs(t,e)}getSubgraphAsync(t,e){return this.#e.getSubgraphsAsync(t,e)}updateState(t,e,n){return this.#e.updateState(t,e,n)}get builder(){return this.#e.builder}};function sc(t){return new Jm(t)}const qm=Dn().args(Le(),Le(),Le()).returns(De([ie(),Ri(ie())])),oc=["approve","edit","reject"],Ym=tn(oc),Xm=K({allowedDecisions:Ke(Ym),description:De([ie(),qm]).optional(),argsSchema:Mn(Mu()).optional()}),bi=K({interruptOn:Mn(De([_t(),Xm])).optional(),descriptionPrefix:ie().default("Tool execution requires approval")});function Zm(t){const e=async(r,s,o,i)=>{const a=r.name,l=r.args,c=s.description;let u;typeof c=="function"?u=await c(r,o,i):c!==void 0?u=c:u=`${t.descriptionPrefix??"Tool execution requires approval"}
73
73
 
74
74
  Tool: ${a}
75
- Args: ${JSON.stringify(l,null,2)}`;const d={name:a,args:l,description:u},h={actionName:a,allowedDecisions:s.allowedDecisions};return s.argsSchema&&(h.argsSchema=s.argsSchema),{actionRequest:d,reviewConfig:h}},n=(r,s,o)=>{const i=o.allowedDecisions;if(r.type==="approve"&&i.includes("approve"))return{revisedToolCall:s,toolMessage:null};if(r.type==="edit"&&i.includes("edit")){const l=r.editedAction;if(!l||typeof l.name!="string")throw new Error(`Invalid edited action for tool "${s.name}": name must be a string`);if(!l.args||typeof l.args!="object")throw new Error(`Invalid edited action for tool "${s.name}": args must be an object`);return{revisedToolCall:{type:"tool_call",name:l.name,args:l.args,id:s.id},toolMessage:null}}if(r.type==="reject"&&i.includes("reject")){if(r.message!==void 0&&typeof r.message!="string")throw new Error(`Tool call response for "${s.name}" must be a string, got ${typeof r.message}`);const l=r.message??`User rejected the tool call for \`${s.name}\` with id ${s.id}`,c=new j({content:l,name:s.name,tool_call_id:s.id,status:"error"});return{revisedToolCall:s,toolMessage:c}}const a=`Unexpected human decision: ${JSON.stringify(r)}. Decision type '${r.type}' is not allowed for tool '${s.name}'. Expected one of ${JSON.stringify(i)} based on the tool's configuration.`;throw new Error(a)};return le({name:"HumanInTheLoopMiddleware",contextSchema:bi,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const o=nt(bi,{...t,...s.context||{}});if(!o)return;const{messages:i}=r;if(!i.length)return;const a=[...i].reverse().find(g=>P.isInstance(g));if(!a||!a.tool_calls?.length||!o.interruptOn)return;const l={};for(const[g,v]of Object.entries(o.interruptOn))typeof v=="boolean"?v===!0&&(l[g]={allowedDecisions:[...oc]}):v.allowedDecisions&&(l[g]=v);const c=[],u=[];for(const g of a.tool_calls)g.name in l?c.push(g):u.push(g);if(!c.length)return;const d=[],h=[];for(const g of c){const v=l[g.name],{actionRequest:M,reviewConfig:w}=await e(g,v,r,s);d.push(M),h.push(w)}const p=(await xl({actionRequests:d,reviewConfigs:h})).decisions;if(!p||!Array.isArray(p))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(p.length!==c.length)throw new Error(`Number of human decisions (${p.length}) does not match number of hanging tool calls (${c.length}).`);const C=[...u],k=[],T=p.some(g=>g.type==="reject");for(let g=0;g<p.length;g++){const v=p[g],M=c[g],w=l[M.name],{revisedToolCall:b,toolMessage:E}=n(v,M,w);b&&(!T||v.type==="reject")&&C.push(b),E&&k.push(E)}P.isInstance(a)&&(a.tool_calls=C);const _=T?"model":void 0;return{messages:[a,...k],jumpTo:_}}}})}const mr=`<role>
75
+ Args: ${JSON.stringify(l,null,2)}`;const d={name:a,args:l,description:u},h={actionName:a,allowedDecisions:s.allowedDecisions};return s.argsSchema&&(h.argsSchema=s.argsSchema),{actionRequest:d,reviewConfig:h}},n=(r,s,o)=>{const i=o.allowedDecisions;if(r.type==="approve"&&i.includes("approve"))return{revisedToolCall:s,toolMessage:null};if(r.type==="edit"&&i.includes("edit")){const l=r.editedAction;if(!l||typeof l.name!="string")throw new Error(`Invalid edited action for tool "${s.name}": name must be a string`);if(!l.args||typeof l.args!="object")throw new Error(`Invalid edited action for tool "${s.name}": args must be an object`);return{revisedToolCall:{type:"tool_call",name:l.name,args:l.args,id:s.id},toolMessage:null}}if(r.type==="reject"&&i.includes("reject")){if(r.message!==void 0&&typeof r.message!="string")throw new Error(`Tool call response for "${s.name}" must be a string, got ${typeof r.message}`);const l=r.message??`User rejected the tool call for \`${s.name}\` with id ${s.id}`,c=new j({content:l,name:s.name,tool_call_id:s.id,status:"error"});return{revisedToolCall:s,toolMessage:c}}const a=`Unexpected human decision: ${JSON.stringify(r)}. Decision type '${r.type}' is not allowed for tool '${s.name}'. Expected one of ${JSON.stringify(i)} based on the tool's configuration.`;throw new Error(a)};return le({name:"HumanInTheLoopMiddleware",contextSchema:bi,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const o=nt(bi,{...t,...s.context||{}});if(!o)return;const{messages:i}=r;if(!i.length)return;const a=[...i].reverse().find(g=>P.isInstance(g));if(!a||!a.tool_calls?.length||!o.interruptOn)return;const l={};for(const[g,v]of Object.entries(o.interruptOn))typeof v=="boolean"?v===!0&&(l[g]={allowedDecisions:[...oc]}):v.allowedDecisions&&(l[g]=v);const c=[],u=[];for(const g of a.tool_calls)g.name in l?c.push(g):u.push(g);if(!c.length)return;const d=[],h=[];for(const g of c){const v=l[g.name],{actionRequest:M,reviewConfig:w}=await e(g,v,r,s);d.push(M),h.push(w)}const p=(await xl({actionRequests:d,reviewConfigs:h})).decisions;if(!p||!Array.isArray(p))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(p.length!==c.length)throw new Error(`Number of human decisions (${p.length}) does not match number of hanging tool calls (${c.length}).`);const C=[...u],T=[],k=p.some(g=>g.type==="reject");for(let g=0;g<p.length;g++){const v=p[g],M=c[g],w=l[M.name],{revisedToolCall:b,toolMessage:E}=n(v,M,w);b&&(!k||v.type==="reject")&&C.push(b),E&&T.push(E)}P.isInstance(a)&&(a.tool_calls=C);const _=k?"model":void 0;return{messages:[a,...T],jumpTo:_}}}})}const mr=`<role>
76
76
  Context Extraction Assistant
77
77
  </role>
78
78
 
@@ -98,10 +98,10 @@ Respond ONLY with the extracted context. Do not include any additional informati
98
98
  <messages>
99
99
  Messages to summarize:
100
100
  {messages}
101
- </messages>`,Qm="Here is a summary of the conversation to date:",Rr=20,eg=4e3,_i=5,tg=Dn().args(Ke(Le())).returns(De([z(),Ri(z())])),cn=K({fraction:z().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:z().positive("Tokens must be greater than 0").optional(),messages:z().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),Ro=K({fraction:z().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:z().min(0,"Tokens must be greater than or equal to 0").optional(),messages:z().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),vi=K({model:Le(),trigger:De([cn,Ke(cn)]).optional(),keep:Ro.optional(),tokenCounter:tg.optional(),summaryPrompt:ie().default(mr),trimTokensToSummarize:z().optional(),summaryPrefix:ie().optional(),maxTokensBeforeSummary:z().optional(),messagesToKeep:z().optional()});function jn(t){if("profile"in t&&typeof t.profile=="object"&&t.profile&&"maxInputTokens"in t.profile&&(typeof t.profile.maxInputTokens=="number"||t.profile.maxInputTokens==null))return t.profile.maxInputTokens??void 0;if("model"in t&&typeof t.model=="string")return Wo(t.model);if("modelName"in t&&typeof t.modelName=="string")return Wo(t.modelName)}function ng(t){const{data:e,error:n}=Au(vi,t);if(n)throw new Error(`Invalid summarization middleware options: ${io(n)}`);return le({name:"SummarizationMiddleware",contextSchema:vi.extend({model:Le().optional()}),beforeModel:async(r,s)=>{let o=e.trigger,i=e.keep;e.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),o===void 0&&(o={tokens:e.maxTokensBeforeSummary})),e.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!i||i&&"messages"in i&&i.messages===Rr)&&(i={messages:e.messagesToKeep}));const a=s.context?.trigger!==void 0?s.context.trigger:o,l=s.context?.keep!==void 0?s.context.keep:i??{messages:Rr},c=Ro.parse(l);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(S=>cn.parse(S)):u=[cn.parse(a)];const d=u.some(S=>"fraction"in S)||"fraction"in c,h=typeof e.model=="string"?await lt(e.model):e.model;if(d&&!jn(h))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=s.context?.summaryPrompt===mr?e.summaryPrompt??mr:s.context?.summaryPrompt??e.summaryPrompt??mr,m=s.context.summaryPrefix??e.summaryPrefix??Qm,p=s.context?.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:e.trimTokensToSummarize??eg;rg(r.messages);const C=s.context?.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??Oo,k=await C(r.messages);if(!await ig(r.messages,k,u,h))return;const{systemPrompt:_,conversationMessages:g}=sg(r.messages),v=await ag(g,c,C,h);if(v<=0)return;const{messagesToSummarize:M,preservedMessages:w}=og(_,g,v),b=await ug(M,h,f,C,p,s),E=new se({content:`${m}
101
+ </messages>`,Qm="Here is a summary of the conversation to date:",Rr=20,eg=4e3,_i=5,tg=Dn().args(Ke(Le())).returns(De([z(),Ri(z())])),cn=K({fraction:z().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:z().positive("Tokens must be greater than 0").optional(),messages:z().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),Ro=K({fraction:z().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:z().min(0,"Tokens must be greater than or equal to 0").optional(),messages:z().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),vi=K({model:Le(),trigger:De([cn,Ke(cn)]).optional(),keep:Ro.optional(),tokenCounter:tg.optional(),summaryPrompt:ie().default(mr),trimTokensToSummarize:z().optional(),summaryPrefix:ie().optional(),maxTokensBeforeSummary:z().optional(),messagesToKeep:z().optional()});function jn(t){if("profile"in t&&typeof t.profile=="object"&&t.profile&&"maxInputTokens"in t.profile&&(typeof t.profile.maxInputTokens=="number"||t.profile.maxInputTokens==null))return t.profile.maxInputTokens??void 0;if("model"in t&&typeof t.model=="string")return Wo(t.model);if("modelName"in t&&typeof t.modelName=="string")return Wo(t.modelName)}function ng(t){const{data:e,error:n}=Au(vi,t);if(n)throw new Error(`Invalid summarization middleware options: ${io(n)}`);return le({name:"SummarizationMiddleware",contextSchema:vi.extend({model:Le().optional()}),beforeModel:async(r,s)=>{let o=e.trigger,i=e.keep;e.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),o===void 0&&(o={tokens:e.maxTokensBeforeSummary})),e.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!i||i&&"messages"in i&&i.messages===Rr)&&(i={messages:e.messagesToKeep}));const a=s.context?.trigger!==void 0?s.context.trigger:o,l=s.context?.keep!==void 0?s.context.keep:i??{messages:Rr},c=Ro.parse(l);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(S=>cn.parse(S)):u=[cn.parse(a)];const d=u.some(S=>"fraction"in S)||"fraction"in c,h=typeof e.model=="string"?await lt(e.model):e.model;if(d&&!jn(h))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=s.context?.summaryPrompt===mr?e.summaryPrompt??mr:s.context?.summaryPrompt??e.summaryPrompt??mr,m=s.context.summaryPrefix??e.summaryPrefix??Qm,p=s.context?.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:e.trimTokensToSummarize??eg;rg(r.messages);const C=s.context?.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??Oo,T=await C(r.messages);if(!await ig(r.messages,T,u,h))return;const{systemPrompt:_,conversationMessages:g}=sg(r.messages),v=await ag(g,c,C,h);if(v<=0)return;const{messagesToSummarize:M,preservedMessages:w}=og(_,g,v),b=await ug(M,h,f,C,p,s),E=new se({content:`${m}
102
102
 
103
103
  ${b}`,id:wr(),additional_kwargs:{lc_source:"summarization"}});return{messages:[new bt({id:Wl}),E,...w]}}})}function rg(t){for(const e of t)e.id||(e.id=wr())}function sg(t){return t.length>0&&oe.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function og(t,e,n){const r=e.slice(0,n),s=e.slice(n);return t&&r.unshift(t),{messagesToSummarize:r,preservedMessages:s}}async function ig(t,e,n,r){if(n.length===0)return!1;for(const s of n){let o=!0,i=!1;if(s.messages!==void 0&&(i=!0,t.length<s.messages&&(o=!1)),s.tokens!==void 0&&(i=!0,e<s.tokens&&(o=!1)),s.fraction!==void 0){i=!0;const a=jn(r);if(typeof a=="number"){const l=Math.floor(a*s.fraction);e<l&&(o=!1)}else o=!1}if(i&&o)return!0}return!1}async function ag(t,e,n,r){if("tokens"in e||"fraction"in e){const s=await lg(t,e,n,r);return typeof s=="number"?s:Si(t,Rr)}return Si(t,e.messages??Rr)}async function lg(t,e,n,r){if(t.length===0)return 0;let s;if("fraction"in e&&e.fraction!==void 0){const d=jn(r);if(typeof d!="number")return;s=Math.floor(d*e.fraction)}else if("tokens"in e&&e.tokens!==void 0)s=Math.floor(e.tokens);else return;if(s<=0&&(s=1),await n(t)<=s)return 0;let i=0,a=t.length,l=t.length;const c=Math.floor(Math.log2(t.length))+1;for(let d=0;d<c&&!(i>=a);d++){const h=Math.floor((i+a)/2);await n(t.slice(h))<=s?(l=h,a=h):i=h+1}if(l===t.length&&(l=i),l>=t.length){if(t.length===1)return 0;l=t.length-1}const u=lc(t,l);if(u<=l)return u;for(let d=l;d>=0;d--)if(ic(t,d))return d;return 0}function Si(t,e){if(t.length<=e)return 0;const n=t.length-e,r=lc(t,n);if(r<=n)return r;for(let s=n;s>=0;s--)if(ic(t,s))return s;return 0}function ic(t,e){if(e>=t.length)return!0;if(e<t.length&&P.isInstance(t[e])&&Nr(t[e]))return!1;const n=Math.max(0,e-_i),r=Math.min(t.length,e+_i);for(let s=n;s<r;s++){if(!Nr(t[s]))continue;const o=ac(t[s]);if(cg(t,s,e,o))return!1}return!0}function ac(t){const e=new Set;if(t.tool_calls)for(const n of t.tool_calls){const r=typeof n=="object"&&"id"in n?n.id:null;r&&e.add(r)}return e}function lc(t,e){if(e>=t.length||!j.isInstance(t[e]))return e;const n=new Set;let r=e;for(;r<t.length&&j.isInstance(t[r]);){const s=t[r];s.tool_call_id&&n.add(s.tool_call_id),r++}for(let s=e-1;s>=0;s--){const o=t[s];if(P.isInstance(o)&&Nr(o)){const i=ac(o);for(const a of n)if(i.has(a))return s}}return r}function cg(t,e,n,r){for(let s=e+1;s<t.length;s++){const o=t[s];if(j.isInstance(o)&&r.has(o.tool_call_id)){const i=e<n,a=s<n;if(i!==a)return!0}}return!1}async function ug(t,e,n,r,s,o){if(!t.length)return"No previous conversation history.";const i=await hg(t,r,s);if(!i.length)return"Previous conversation was too long to summarize.";const a=Iu(i);try{const l=n.replace("{messages}",a),c=Pu(o)??{},u=$e(c,{metadata:{lc_source:"summarization"}}),h=(await e.invoke(l,u)).content;return typeof h=="string"?h.trim():Array.isArray(h)?h.map(m=>typeof m=="string"?m:typeof m=="object"&&m!==null&&"text"in m?m.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(l){return`Error generating summary: ${l}`}}async function hg(t,e,n){if(n===void 0)return t;try{return await $i(t,{maxTokens:n,tokenCounter:async r=>e(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}function dg(t){return le({name:"DynamicSystemPromptMiddleware",wrapModelCall:async(e,n)=>{const r=await t(e.state,e.runtime);if(!(typeof r=="string"||oe.isInstance(r)))throw new Error("dynamicSystemPromptMiddleware function must return a string or SystemMessage");return n({...e,systemMessage:e.systemMessage.concat(r)})}})}const fg="Your goal is to select the most relevant tools for answering the user's query.";function pg(t){if(!t||t.length===0)throw new Error("Invalid usage: tools must be non-empty");const e=t.map(r=>gt(r.name)),n=De(e);return K({tools:Ke(n).describe("Tools to use. Place the most relevant tools first.")})}const mg=K({model:ie().or(Fn(dh)).optional(),systemPrompt:ie().optional(),maxTools:z().optional(),alwaysInclude:Ke(ie()).optional()});function gg(t){return le({name:"LLMToolSelector",contextSchema:mg,async wrapModelCall(e,n){const r=await yg(e,t,e.runtime);if(!r)return n(e);const s=pg(r.availableTools),i=await(await r.model.withStructuredOutput?.(s))?.invoke([{role:"system",content:r.systemMessage},r.lastUserMessage]);if(!i||typeof i!="object"||!("tools"in i))throw new Error(`Expected object response with tools array, got ${typeof i}`);return n(wg(i,r.availableTools,r.validToolNames,e,t))}})}async function yg(t,e,n){const r=n.context.model??e.model,s=n.context.maxTools??e.maxTools,o=n.context.alwaysInclude??e.alwaysInclude??[],i=n.context.systemPrompt??e.systemPrompt??fg;if(!t.tools||t.tools.length===0)return;const a=t.tools.filter(f=>typeof f=="object"&&"name"in f&&"description"in f&&typeof f.name=="string");if(o.length>0){const f=new Set(a.map(p=>p.name)),m=o.filter(p=>!f.has(p));if(m.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${m.join(", ")}. Available tools: ${Array.from(f).sort().join(", ")}`)}const l=a.filter(f=>!o.includes(f.name));if(l.length===0)return;let c=i;s!==void 0&&(c+=`
104
- IMPORTANT: List the tool names in order of relevance, with the most relevant first. If you exceed the maximum number of tools, only the first ${s} will be used.`);let u;for(const f of t.messages)se.isInstance(f)&&(u=f);if(!u)throw new Error("No user message found in request messages");const d=r?typeof r=="string"?await lt(r):r:t.model,h=l.map(f=>f.name);return{availableTools:l,systemMessage:c,lastUserMessage:u,model:d,validToolNames:h}}function wg(t,e,n,r,s){const o=s.maxTools,i=s.alwaysInclude??[],a=[],l=[];for(const h of t.tools){if(!n.includes(h)){l.push(h);continue}!a.includes(h)&&(o===void 0||a.length<o)&&a.push(h)}if(l.length>0)throw new Error(`Model selected invalid tools: ${l.join(", ")}`);const c=e.filter(h=>a.includes(h.name)),u=(r.tools??[]).filter(h=>typeof h=="object"&&"name"in h&&typeof h.name=="string"&&i.includes(h.name));c.push(...u);const d=(r.tools??[]).filter(h=>!(typeof h=="object"&&"name"in h&&"description"in h&&typeof h.name=="string"));return{...r,tools:[...c,...d]}}var cc=class extends Error{constructor(t,e){super(`PII detected: ${t} found ${e.length} occurrence(s)`),this.piiType=t,this.matches=e,this.name="PIIDetectionError"}};const bg=/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,_g=/\b(?:\d{4}[-\s]?){3}\d{4}\b/g,vg=/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,Sg=/\b(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\b/g,Cg=/(?:https?:\/\/|www\.)[^\s<>"{}|\\^`[\]]+/gi;function kg(t){const e=t.replace(/\D/g,"");let n=0,r=!1;for(let s=e.length-1;s>=0;s--){let o=parseInt(e[s],10);r&&(o*=2,o>9&&(o-=9)),n+=o,r=!r}return n%10===0}function Tt(t){return{text:t[0],start:t.index??0,end:(t.index??0)+t[0].length}}function uc(t){const e=[],n=new RegExp(bg);let r;for(;(r=n.exec(t))!==null;)e.push(Tt(r));return e}function hc(t){const e=[],n=new RegExp(_g);let r;for(;(r=n.exec(t))!==null;){const s=r[0].replace(/\D/g,"");s.length>=13&&s.length<=19&&kg(s)&&e.push(Tt(r))}return e}function dc(t){const e=[],n=new RegExp(vg);let r;for(;(r=n.exec(t))!==null;){const o=r[0].split(".");o.length===4&&o.every(i=>{const a=parseInt(i,10);return a>=0&&a<=255})&&e.push(Tt(r))}return e}function fc(t){const e=[],n=new RegExp(Sg);let r;for(;(r=n.exec(t))!==null;)e.push(Tt(r));return e}function pc(t){const e=[],n=new RegExp(Cg);let r;for(;(r=n.exec(t))!==null;)e.push(Tt(r));return e}const bs={email:uc,credit_card:hc,ip:dc,mac_address:fc,url:pc};function mc(t){let e;if(t.detector)if(typeof t.detector=="string"){const n=new RegExp(t.detector,"g");e=r=>{const s=[];let o;const i=new RegExp(n);for(;(o=i.exec(r))!==null;)s.push(Tt(o));return s}}else t.detector instanceof RegExp?e=n=>{if(!(t.detector instanceof RegExp))throw new Error("Detector is required");const r=[];let s;for(;(s=t.detector.exec(n))!==null;)r.push(Tt(s));return r}:e=t.detector;else{const n=t.piiType;if(!bs[n])throw new Error(`Unknown PII type: ${t.piiType}. Must be one of: ${Object.keys(bs).join(", ")}, or provide a custom detector.`);e=bs[n]}return{piiType:t.piiType,strategy:t.strategy,detector:e}}function Tg(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=`[REDACTED_${n.toUpperCase()}]`;r=r.slice(0,o.start)+i+r.slice(o.end)}return r}function Eg(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=o.text;let a;if(n==="credit_card")a=`****-****-****-${i.replace(/\D/g,"").slice(-4)}`;else if(n==="email"){const[l,c]=i.split("@");l&&c?a=`${l[0]}***@${c}`:a="***"}else{const l=Math.min(4,i.length);a=`${"*".repeat(Math.max(0,i.length-l))}${i.slice(-l)}`}r=r.slice(0,o.start)+a+r.slice(o.end)}return r}function xg(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=Di(o.text).slice(0,8),a=`<${n}_hash:${i}>`;r=r.slice(0,o.start)+a+r.slice(o.end)}return r}function gc(t,e,n,r){if(e.length===0)return t;switch(n){case"block":throw new cc(r,e);case"redact":return Tg(t,e,r);case"mask":return Eg(t,e,r);case"hash":return xg(t,e,r);default:throw new Error(`Unknown strategy: ${n}`)}}const Mg=K({applyToInput:_t().optional(),applyToOutput:_t().optional(),applyToToolResults:_t().optional()});function _s(t,e){const n=e.detector(t);return n.length===0?{content:t,matches:[]}:{content:gc(t,n,e.strategy,e.piiType),matches:n}}function Ag(t,e={}){const{strategy:n="redact",detector:r}=e,s=mc({piiType:t,strategy:n,detector:r}),o=`PIIMiddleware[${s.piiType}]`;return le({name:o,contextSchema:Mg,beforeModel:async(i,a)=>{const l=a.context.applyToInput??e.applyToInput??!0,c=a.context.applyToToolResults??e.applyToToolResults??!1;if(!l&&!c)return;const u=i.messages;if(!u||u.length===0)return;const d=[...u];let h=!1;if(l){let f=null;for(let m=u.length-1;m>=0;m--)if(se.isInstance(u[m])){f=m;break}if(f!==null){const m=u[f];if(m&&m.content){const p=String(m.content),{content:C,matches:k}=_s(p,s);k.length>0&&(d[f]=new se({content:C,id:m.id,name:m.name}),h=!0)}}}if(c){let f=null;for(let m=u.length-1;m>=0;m--)if(P.isInstance(u[m])){f=m;break}if(f!==null)for(let m=f+1;m<u.length;m++){const p=u[m];if(j.isInstance(p)){if(!p.content)continue;const C=String(p.content),{content:k,matches:T}=_s(C,s);T.length>0&&(d[m]=new j({content:k,id:p.id,name:p.name,tool_call_id:p.tool_call_id}),h=!0)}}}if(h)return{messages:d}},afterModel:async(i,a)=>{if(!(a.context.applyToOutput??e.applyToOutput??!1))return;const c=i.messages;if(!c||c.length===0)return;let u=null,d=null;for(let k=c.length-1;k>=0;k--)if(P.isInstance(c[k])){d=c[k],u=k;break}if(u===null||!d||!d.content)return;const h=String(d.content),{content:f,matches:m}=_s(h,s);if(m.length===0)return;const p=new P({content:f,id:d.id,name:d.name,tool_calls:d.tool_calls}),C=[...c];return C[u]=p,{messages:C}}})}const Ig=K({rules:Mn(ie(),Fn(RegExp).describe("Regular expression pattern to match PII")).optional()});function Pg(){return Math.random().toString(36).substring(2,11)}function vs(t,e,n){let r=t;for(const[s,o]of Object.entries(e)){const i=s.toUpperCase().replace(/[^a-zA-Z0-9_-]/g,"");r=r.replace(o,a=>{const l=Pg();return n[l]=a,`[REDACTED_${i}_${l}]`})}return r}async function Og(t,e){if(se.isInstance(t)||j.isInstance(t)||oe.isInstance(t)){const n=t.content,r=await vs(n,e.rules,e.redactionMap);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return new s({...t,content:r})}return t}if(P.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=await vs(n,e.rules,e.redactionMap),o=await vs(r,e.rules,e.redactionMap);return s!==n||o!==r?new P({...t,content:typeof t.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(o)}):t}throw new Error(`Unsupported message type: ${t.type}`)}function kn(t,e){let n=t;const r=/\[REDACTED_[A-Z_]+_(\w+)\]/g;return n=n.replace(r,(s,o)=>e[o]?e[o]:s),n}function Ci(t,e){if(se.isInstance(t)||j.isInstance(t)||oe.isInstance(t)){const n=t.content,r=kn(n,e);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return{message:new s({...t,content:r}),changed:!0}}return{message:t,changed:!1}}if(P.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=kn(n,e),o=kn(r,e);return s!==n||o!==r?{message:new P({...t,content:typeof t.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(o)}),changed:!0}:{message:t,changed:!1}}throw new Error(`Unsupported message type: ${t.type}`)}function Ng(t={}){const e={};return console.warn("DEPRECATED: piiRedactionMiddleware is deprecated. Please use piiMiddleware instead, go to https://docs.langchain.com/oss/javascript/langchain/middleware/built-in#pii-detection for more information."),le({name:"PIIRedactionMiddleware",contextSchema:Ig,wrapModelCall:async(n,r)=>{const s=n.runtime.context.rules??t.rules??{};if(Object.keys(s).length===0)return r(n);const o=await Promise.all(n.state.messages.map(i=>Og(i,{rules:s,redactionMap:e})));return r({...n,messages:o})},afterModel:async n=>{if(Object.keys(e).length===0)return;const r=n.messages.at(-1);if(!P.isInstance(r))return;const s=n.messages.at(-2),{message:o,changed:i}=Ci(r,e);if(!i)return;let a;if(P.isInstance(r)&&r?.tool_calls?.length===0&&typeof r.content=="string"&&r.content.startsWith("{")&&r.content.endsWith("}"))try{a=JSON.parse(kn(r.content,e))}catch{}if(P.isInstance(s)&&s?.tool_calls?.length!==0&&s?.tool_calls?.some(c=>c.name.startsWith("extract-"))){const{message:c,changed:u}=Ci(s,e),d=s.tool_calls?.find(f=>f.name.startsWith("extract-"))?.args,h=d?JSON.parse(kn(JSON.stringify(d),e)):void 0;if(i||u)return{...n,...h?{structuredResponse:h}:{},messages:[new bt({id:s.id}),new bt({id:r.id}),c,o]}}return{...n,...a?{structuredResponse:a}:{},messages:[new bt({id:r.id}),o]}}})}const Rg="[cleared]",$g=1e5,Yn=3;var yc=class{#e;trigger;keep;clearToolInputs;excludeTools;placeholder;model;clearAtLeast;constructor(t={}){let e=t.trigger;t.triggerTokens!==void 0&&(console.warn("triggerTokens is deprecated. Use `trigger: { tokens: value }` instead."),e===void 0&&(e={tokens:t.triggerTokens}));let n=t.keep;if(t.keepMessages!==void 0&&(console.warn("keepMessages is deprecated. Use `keep: { messages: value }` instead."),n===void 0&&(n={messages:t.keepMessages})),e===void 0&&(e={tokens:$g}),n===void 0&&(n={messages:Yn}),Array.isArray(e))this.#e=e.map(s=>cn.parse(s)),this.trigger=this.#e;else{const s=cn.parse(e);this.#e=[s],this.trigger=s}const r=Ro.parse(n);this.keep=r,t.clearAtLeast!==void 0&&console.warn("clearAtLeast is deprecated and will be removed in a future version. It conflicts with the `keep` property. Use `keep: { tokens: value }` or `keep: { messages: value }` instead to control retention."),this.clearAtLeast=t.clearAtLeast??0,this.clearToolInputs=t.clearToolInputs??!1,this.excludeTools=new Set(t.excludeTools??[]),this.placeholder=t.placeholder??Rg}async apply(t){const{messages:e,model:n,countTokens:r}=t,s=await r(e),o=[];for(let h=0;h<e.length;h++){const f=e[h];if(j.isInstance(f)){const m=this.#n(e.slice(0,h),f.tool_call_id);m&&m.tool_calls?.find(C=>C.id===f.tool_call_id)||o.push(h)}}for(let h=o.length-1;h>=0;h--)e.splice(o[h],1);let i=s;if(o.length>0&&(i=await r(e)),!this.#r(e,i,n))return;const a=[];for(let h=0;h<e.length;h++){const f=e[h];j.isInstance(f)&&a.push({idx:h,msg:f})}if(a.length===0)return;const l=await this.#t(a,r,n),c=l>=a.length?[]:l>0?a.slice(0,-l):a;let u=0;const d=[...c];for(const{idx:h,msg:f}of d){if(f.response_metadata?.context_editing?.cleared)continue;const p=this.#n(e.slice(0,h),f.tool_call_id);if(!p)continue;const C=p.tool_calls?.find(_=>_.id===f.tool_call_id);if(!C)continue;const k=f.name||C.name;if(this.excludeTools.has(k))continue;if(e[h]=new j({tool_call_id:f.tool_call_id,content:this.placeholder,name:f.name,artifact:void 0,response_metadata:{...f.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const _=e.indexOf(p);_>=0&&(e[_]=this.#s(p,f.tool_call_id))}const T=await r(e);u=Math.max(0,i-T)}if(this.clearAtLeast>0&&u<this.clearAtLeast){const h=l>0&&l<a.length?a.slice(-l):[];for(let f=h.length-1;f>=0&&!(u>=this.clearAtLeast);f--){const{idx:m,msg:p}=h[f];if(p.response_metadata?.context_editing?.cleared)continue;const k=this.#n(e.slice(0,m),p.tool_call_id);if(!k)continue;const T=k.tool_calls?.find(v=>v.id===p.tool_call_id);if(!T)continue;const _=p.name||T.name;if(this.excludeTools.has(_))continue;if(e[m]=new j({tool_call_id:p.tool_call_id,content:this.placeholder,name:p.name,artifact:void 0,response_metadata:{...p.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const v=e.indexOf(k);v>=0&&(e[v]=this.#s(k,p.tool_call_id))}const g=await r(e);u=Math.max(0,i-g)}}}#r(t,e,n){for(const r of this.#e){let s=!0,o=!1;if(r.messages!==void 0&&(o=!0,t.length<r.messages&&(s=!1)),r.tokens!==void 0&&(o=!0,e<r.tokens&&(s=!1)),r.fraction!==void 0){if(o=!0,!n)continue;const i=jn(n);if(typeof i=="number"){const a=Math.floor(i*r.fraction);if(a<=0)continue;e<a&&(s=!1)}else continue}if(o&&s)return!0}return!1}async#t(t,e,n){if("messages"in this.keep&&this.keep.messages!==void 0)return this.keep.messages;if("tokens"in this.keep&&this.keep.tokens!==void 0){const r=this.keep.tokens;let s=0,o=0;for(let i=t.length-1;i>=0;i--){const a=t[i],l=await e([a.msg]);if(s+l<=r)s+=l,o++;else break}return o}if("fraction"in this.keep&&this.keep.fraction!==void 0){if(!n)return Yn;const r=jn(n);if(typeof r=="number"){const s=Math.floor(r*this.keep.fraction);if(s<=0)return Yn;let o=0,i=0;for(let a=t.length-1;a>=0;a--){const l=t[a],c=await e([l.msg]);if(o+c<=s)o+=c,i++;else break}return i}}return Yn}#n(t,e){for(let n=t.length-1;n>=0;n--){const r=t[n];if(P.isInstance(r)&&r.tool_calls?.some(o=>o.id===e))return r}return null}#s(t,e){const n=t.tool_calls?.map(i=>i.id===e?{...i,args:{}}:i),r={...t.response_metadata},s={...r.context_editing},o=new Set(s.cleared_tool_inputs);return o.add(e),s.cleared_tool_inputs=Array.from(o).sort(),r.context_editing=s,new P({content:t.content,tool_calls:n,response_metadata:r,id:t.id,name:t.name,additional_kwargs:t.additional_kwargs})}};function jg(t={}){const e=t.edits??[new yc],n=t.tokenCountMethod??"approx";return le({name:"ContextEditingMiddleware",wrapModelCall:async(r,s)=>{if(!r.messages||r.messages.length===0)return s(r);const o=r.systemPrompt?[new oe(r.systemPrompt)]:[],i=n==="approx"?Oo:async a=>{const l=[...o,...a];if("getNumTokensFromMessages"in r.model)return r.model.getNumTokensFromMessages(l).then(({totalCount:c})=>c);throw new Error(`Model "${r.model.getName()}" does not support token counting`)};for(const a of e)await a.apply({messages:r.messages,model:r.model,countTokens:i});return s(r)}})}function Lg(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const Dg=["continue","error","end"],wc="continue";function bc(t,e,n,r,s){const o=s?`'${s}' tool`:"Tool",i=[];n!==void 0&&t>n&&i.push(`thread limit exceeded (${t}/${n} calls)`),r!==void 0&&e>r&&i.push(`run limit exceeded (${e}/${r} calls)`);const a=i.join(" and ");return`${o} call limit reached: ${a}.`}const _c=tn(Dg).default(wc);var vc=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const o=bc(t,e,n,r,s);super(o),this.name="ToolCallLimitExceededError",this.threadCount=t,this.runCount=e,this.threadLimit=n,this.runLimit=r,this.toolName=s}};K({toolName:ie().optional(),threadLimit:z().optional(),runLimit:z().optional(),exitBehavior:_c});const Fg=K({threadToolCallCount:Mn(ie(),z()).default({}),runToolCallCount:Mn(ie(),z()).default({})}),Ug="__all__";function Vg(t){if(t.threadLimit===void 0&&t.runLimit===void 0)throw new Error("At least one limit must be specified (threadLimit or runLimit)");const e=t.exitBehavior??wc,n=_c.safeParse(e);if(!n.success)throw new Error(io(n.error).slice(2));if(t.threadLimit!==void 0&&t.runLimit!==void 0&&t.runLimit>t.threadLimit)throw new Error(`runLimit (${t.runLimit}) cannot exceed threadLimit (${t.threadLimit}). The run limit should be less than or equal to the thread limit.`);const r=t.toolName?`ToolCallLimitMiddleware[${t.toolName}]`:"ToolCallLimitMiddleware";return le({name:r,stateSchema:Fg,afterModel:{canJumpTo:["end"],hook:s=>{const o=[...s.messages].reverse().find(P.isInstance);if(!o||!o.tool_calls)return;const i=(g,v)=>t.threadLimit!==void 0&&g+1>t.threadLimit||t.runLimit!==void 0&&v+1>t.runLimit,a=g=>t.toolName===void 0||g.name===t.toolName,l=(g,v,M)=>{const w=[],b=[];let E=v,S=M;for(const x of g)a(x)&&(i(E,S)?b.push(x):(w.push(x),E+=1,S+=1));return{allowed:w,blocked:b,finalThreadCount:E,finalRunCount:S+b.length}},c=t.toolName??Ug,u={...s.threadToolCallCount??{}},d={...s.runToolCallCount??{}},h=u[c]??0,f=d[c]??0,{allowed:m,blocked:p,finalThreadCount:C,finalRunCount:k}=l(o.tool_calls,h,f);if(u[c]=C,d[c]=k,p.length===0)return m.length>0?{threadToolCallCount:u,runToolCallCount:d}:void 0;if(e==="error"){const g=C+p.length;throw new vc(g,k,t.threadLimit,t.runLimit,t.toolName)}const T=Lg(t.toolName),_=p.map(g=>new j({content:T,tool_call_id:g.id,name:g.name,status:"error"}));if(e==="end"){let g=[];if(t.toolName!==void 0?g=o.tool_calls.filter(w=>w.name!==t.toolName):new Set(o.tool_calls.map(b=>b.name).filter(Boolean)).size>1&&(g=m.length>0?m:o.tool_calls),g.length>0){const w=Array.from(new Set(g.map(b=>b.name).filter(Boolean))).join(", ");throw new Error(`Cannot end execution with other tool calls pending. Found calls to: ${w}. Use 'continue' or 'error' behavior instead.`)}const v=C+p.length,M=bc(v,k,t.threadLimit,t.runLimit,t.toolName);return _.push(new P(M)),{threadToolCallCount:u,runToolCallCount:d,jumpTo:"end",messages:_}}return{threadToolCallCount:u,runToolCallCount:d,messages:_}}},afterAgent:()=>({runToolCallCount:{}})})}const Bg=`Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
104
+ IMPORTANT: List the tool names in order of relevance, with the most relevant first. If you exceed the maximum number of tools, only the first ${s} will be used.`);let u;for(const f of t.messages)se.isInstance(f)&&(u=f);if(!u)throw new Error("No user message found in request messages");const d=r?typeof r=="string"?await lt(r):r:t.model,h=l.map(f=>f.name);return{availableTools:l,systemMessage:c,lastUserMessage:u,model:d,validToolNames:h}}function wg(t,e,n,r,s){const o=s.maxTools,i=s.alwaysInclude??[],a=[],l=[];for(const h of t.tools){if(!n.includes(h)){l.push(h);continue}!a.includes(h)&&(o===void 0||a.length<o)&&a.push(h)}if(l.length>0)throw new Error(`Model selected invalid tools: ${l.join(", ")}`);const c=e.filter(h=>a.includes(h.name)),u=(r.tools??[]).filter(h=>typeof h=="object"&&"name"in h&&typeof h.name=="string"&&i.includes(h.name));c.push(...u);const d=(r.tools??[]).filter(h=>!(typeof h=="object"&&"name"in h&&"description"in h&&typeof h.name=="string"));return{...r,tools:[...c,...d]}}var cc=class extends Error{constructor(t,e){super(`PII detected: ${t} found ${e.length} occurrence(s)`),this.piiType=t,this.matches=e,this.name="PIIDetectionError"}};const bg=/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,_g=/\b(?:\d{4}[-\s]?){3}\d{4}\b/g,vg=/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,Sg=/\b(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\b/g,Cg=/(?:https?:\/\/|www\.)[^\s<>"{}|\\^`[\]]+/gi;function Tg(t){const e=t.replace(/\D/g,"");let n=0,r=!1;for(let s=e.length-1;s>=0;s--){let o=parseInt(e[s],10);r&&(o*=2,o>9&&(o-=9)),n+=o,r=!r}return n%10===0}function kt(t){return{text:t[0],start:t.index??0,end:(t.index??0)+t[0].length}}function uc(t){const e=[],n=new RegExp(bg);let r;for(;(r=n.exec(t))!==null;)e.push(kt(r));return e}function hc(t){const e=[],n=new RegExp(_g);let r;for(;(r=n.exec(t))!==null;){const s=r[0].replace(/\D/g,"");s.length>=13&&s.length<=19&&Tg(s)&&e.push(kt(r))}return e}function dc(t){const e=[],n=new RegExp(vg);let r;for(;(r=n.exec(t))!==null;){const o=r[0].split(".");o.length===4&&o.every(i=>{const a=parseInt(i,10);return a>=0&&a<=255})&&e.push(kt(r))}return e}function fc(t){const e=[],n=new RegExp(Sg);let r;for(;(r=n.exec(t))!==null;)e.push(kt(r));return e}function pc(t){const e=[],n=new RegExp(Cg);let r;for(;(r=n.exec(t))!==null;)e.push(kt(r));return e}const bs={email:uc,credit_card:hc,ip:dc,mac_address:fc,url:pc};function mc(t){let e;if(t.detector)if(typeof t.detector=="string"){const n=new RegExp(t.detector,"g");e=r=>{const s=[];let o;const i=new RegExp(n);for(;(o=i.exec(r))!==null;)s.push(kt(o));return s}}else t.detector instanceof RegExp?e=n=>{if(!(t.detector instanceof RegExp))throw new Error("Detector is required");const r=[];let s;for(;(s=t.detector.exec(n))!==null;)r.push(kt(s));return r}:e=t.detector;else{const n=t.piiType;if(!bs[n])throw new Error(`Unknown PII type: ${t.piiType}. Must be one of: ${Object.keys(bs).join(", ")}, or provide a custom detector.`);e=bs[n]}return{piiType:t.piiType,strategy:t.strategy,detector:e}}function kg(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=`[REDACTED_${n.toUpperCase()}]`;r=r.slice(0,o.start)+i+r.slice(o.end)}return r}function Eg(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=o.text;let a;if(n==="credit_card")a=`****-****-****-${i.replace(/\D/g,"").slice(-4)}`;else if(n==="email"){const[l,c]=i.split("@");l&&c?a=`${l[0]}***@${c}`:a="***"}else{const l=Math.min(4,i.length);a=`${"*".repeat(Math.max(0,i.length-l))}${i.slice(-l)}`}r=r.slice(0,o.start)+a+r.slice(o.end)}return r}function xg(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=Di(o.text).slice(0,8),a=`<${n}_hash:${i}>`;r=r.slice(0,o.start)+a+r.slice(o.end)}return r}function gc(t,e,n,r){if(e.length===0)return t;switch(n){case"block":throw new cc(r,e);case"redact":return kg(t,e,r);case"mask":return Eg(t,e,r);case"hash":return xg(t,e,r);default:throw new Error(`Unknown strategy: ${n}`)}}const Mg=K({applyToInput:_t().optional(),applyToOutput:_t().optional(),applyToToolResults:_t().optional()});function _s(t,e){const n=e.detector(t);return n.length===0?{content:t,matches:[]}:{content:gc(t,n,e.strategy,e.piiType),matches:n}}function Ag(t,e={}){const{strategy:n="redact",detector:r}=e,s=mc({piiType:t,strategy:n,detector:r}),o=`PIIMiddleware[${s.piiType}]`;return le({name:o,contextSchema:Mg,beforeModel:async(i,a)=>{const l=a.context.applyToInput??e.applyToInput??!0,c=a.context.applyToToolResults??e.applyToToolResults??!1;if(!l&&!c)return;const u=i.messages;if(!u||u.length===0)return;const d=[...u];let h=!1;if(l){let f=null;for(let m=u.length-1;m>=0;m--)if(se.isInstance(u[m])){f=m;break}if(f!==null){const m=u[f];if(m&&m.content){const p=String(m.content),{content:C,matches:T}=_s(p,s);T.length>0&&(d[f]=new se({content:C,id:m.id,name:m.name}),h=!0)}}}if(c){let f=null;for(let m=u.length-1;m>=0;m--)if(P.isInstance(u[m])){f=m;break}if(f!==null)for(let m=f+1;m<u.length;m++){const p=u[m];if(j.isInstance(p)){if(!p.content)continue;const C=String(p.content),{content:T,matches:k}=_s(C,s);k.length>0&&(d[m]=new j({content:T,id:p.id,name:p.name,tool_call_id:p.tool_call_id}),h=!0)}}}if(h)return{messages:d}},afterModel:async(i,a)=>{if(!(a.context.applyToOutput??e.applyToOutput??!1))return;const c=i.messages;if(!c||c.length===0)return;let u=null,d=null;for(let T=c.length-1;T>=0;T--)if(P.isInstance(c[T])){d=c[T],u=T;break}if(u===null||!d||!d.content)return;const h=String(d.content),{content:f,matches:m}=_s(h,s);if(m.length===0)return;const p=new P({content:f,id:d.id,name:d.name,tool_calls:d.tool_calls}),C=[...c];return C[u]=p,{messages:C}}})}const Ig=K({rules:Mn(ie(),Fn(RegExp).describe("Regular expression pattern to match PII")).optional()});function Pg(){return Math.random().toString(36).substring(2,11)}function vs(t,e,n){let r=t;for(const[s,o]of Object.entries(e)){const i=s.toUpperCase().replace(/[^a-zA-Z0-9_-]/g,"");r=r.replace(o,a=>{const l=Pg();return n[l]=a,`[REDACTED_${i}_${l}]`})}return r}async function Og(t,e){if(se.isInstance(t)||j.isInstance(t)||oe.isInstance(t)){const n=t.content,r=await vs(n,e.rules,e.redactionMap);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return new s({...t,content:r})}return t}if(P.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=await vs(n,e.rules,e.redactionMap),o=await vs(r,e.rules,e.redactionMap);return s!==n||o!==r?new P({...t,content:typeof t.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(o)}):t}throw new Error(`Unsupported message type: ${t.type}`)}function Tn(t,e){let n=t;const r=/\[REDACTED_[A-Z_]+_(\w+)\]/g;return n=n.replace(r,(s,o)=>e[o]?e[o]:s),n}function Ci(t,e){if(se.isInstance(t)||j.isInstance(t)||oe.isInstance(t)){const n=t.content,r=Tn(n,e);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return{message:new s({...t,content:r}),changed:!0}}return{message:t,changed:!1}}if(P.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=Tn(n,e),o=Tn(r,e);return s!==n||o!==r?{message:new P({...t,content:typeof t.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(o)}),changed:!0}:{message:t,changed:!1}}throw new Error(`Unsupported message type: ${t.type}`)}function Ng(t={}){const e={};return console.warn("DEPRECATED: piiRedactionMiddleware is deprecated. Please use piiMiddleware instead, go to https://docs.langchain.com/oss/javascript/langchain/middleware/built-in#pii-detection for more information."),le({name:"PIIRedactionMiddleware",contextSchema:Ig,wrapModelCall:async(n,r)=>{const s=n.runtime.context.rules??t.rules??{};if(Object.keys(s).length===0)return r(n);const o=await Promise.all(n.state.messages.map(i=>Og(i,{rules:s,redactionMap:e})));return r({...n,messages:o})},afterModel:async n=>{if(Object.keys(e).length===0)return;const r=n.messages.at(-1);if(!P.isInstance(r))return;const s=n.messages.at(-2),{message:o,changed:i}=Ci(r,e);if(!i)return;let a;if(P.isInstance(r)&&r?.tool_calls?.length===0&&typeof r.content=="string"&&r.content.startsWith("{")&&r.content.endsWith("}"))try{a=JSON.parse(Tn(r.content,e))}catch{}if(P.isInstance(s)&&s?.tool_calls?.length!==0&&s?.tool_calls?.some(c=>c.name.startsWith("extract-"))){const{message:c,changed:u}=Ci(s,e),d=s.tool_calls?.find(f=>f.name.startsWith("extract-"))?.args,h=d?JSON.parse(Tn(JSON.stringify(d),e)):void 0;if(i||u)return{...n,...h?{structuredResponse:h}:{},messages:[new bt({id:s.id}),new bt({id:r.id}),c,o]}}return{...n,...a?{structuredResponse:a}:{},messages:[new bt({id:r.id}),o]}}})}const Rg="[cleared]",$g=1e5,Yn=3;var yc=class{#e;trigger;keep;clearToolInputs;excludeTools;placeholder;model;clearAtLeast;constructor(t={}){let e=t.trigger;t.triggerTokens!==void 0&&(console.warn("triggerTokens is deprecated. Use `trigger: { tokens: value }` instead."),e===void 0&&(e={tokens:t.triggerTokens}));let n=t.keep;if(t.keepMessages!==void 0&&(console.warn("keepMessages is deprecated. Use `keep: { messages: value }` instead."),n===void 0&&(n={messages:t.keepMessages})),e===void 0&&(e={tokens:$g}),n===void 0&&(n={messages:Yn}),Array.isArray(e))this.#e=e.map(s=>cn.parse(s)),this.trigger=this.#e;else{const s=cn.parse(e);this.#e=[s],this.trigger=s}const r=Ro.parse(n);this.keep=r,t.clearAtLeast!==void 0&&console.warn("clearAtLeast is deprecated and will be removed in a future version. It conflicts with the `keep` property. Use `keep: { tokens: value }` or `keep: { messages: value }` instead to control retention."),this.clearAtLeast=t.clearAtLeast??0,this.clearToolInputs=t.clearToolInputs??!1,this.excludeTools=new Set(t.excludeTools??[]),this.placeholder=t.placeholder??Rg}async apply(t){const{messages:e,model:n,countTokens:r}=t,s=await r(e),o=[];for(let h=0;h<e.length;h++){const f=e[h];if(j.isInstance(f)){const m=this.#n(e.slice(0,h),f.tool_call_id);m&&m.tool_calls?.find(C=>C.id===f.tool_call_id)||o.push(h)}}for(let h=o.length-1;h>=0;h--)e.splice(o[h],1);let i=s;if(o.length>0&&(i=await r(e)),!this.#r(e,i,n))return;const a=[];for(let h=0;h<e.length;h++){const f=e[h];j.isInstance(f)&&a.push({idx:h,msg:f})}if(a.length===0)return;const l=await this.#t(a,r,n),c=l>=a.length?[]:l>0?a.slice(0,-l):a;let u=0;const d=[...c];for(const{idx:h,msg:f}of d){if(f.response_metadata?.context_editing?.cleared)continue;const p=this.#n(e.slice(0,h),f.tool_call_id);if(!p)continue;const C=p.tool_calls?.find(_=>_.id===f.tool_call_id);if(!C)continue;const T=f.name||C.name;if(this.excludeTools.has(T))continue;if(e[h]=new j({tool_call_id:f.tool_call_id,content:this.placeholder,name:f.name,artifact:void 0,response_metadata:{...f.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const _=e.indexOf(p);_>=0&&(e[_]=this.#s(p,f.tool_call_id))}const k=await r(e);u=Math.max(0,i-k)}if(this.clearAtLeast>0&&u<this.clearAtLeast){const h=l>0&&l<a.length?a.slice(-l):[];for(let f=h.length-1;f>=0&&!(u>=this.clearAtLeast);f--){const{idx:m,msg:p}=h[f];if(p.response_metadata?.context_editing?.cleared)continue;const T=this.#n(e.slice(0,m),p.tool_call_id);if(!T)continue;const k=T.tool_calls?.find(v=>v.id===p.tool_call_id);if(!k)continue;const _=p.name||k.name;if(this.excludeTools.has(_))continue;if(e[m]=new j({tool_call_id:p.tool_call_id,content:this.placeholder,name:p.name,artifact:void 0,response_metadata:{...p.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const v=e.indexOf(T);v>=0&&(e[v]=this.#s(T,p.tool_call_id))}const g=await r(e);u=Math.max(0,i-g)}}}#r(t,e,n){for(const r of this.#e){let s=!0,o=!1;if(r.messages!==void 0&&(o=!0,t.length<r.messages&&(s=!1)),r.tokens!==void 0&&(o=!0,e<r.tokens&&(s=!1)),r.fraction!==void 0){if(o=!0,!n)continue;const i=jn(n);if(typeof i=="number"){const a=Math.floor(i*r.fraction);if(a<=0)continue;e<a&&(s=!1)}else continue}if(o&&s)return!0}return!1}async#t(t,e,n){if("messages"in this.keep&&this.keep.messages!==void 0)return this.keep.messages;if("tokens"in this.keep&&this.keep.tokens!==void 0){const r=this.keep.tokens;let s=0,o=0;for(let i=t.length-1;i>=0;i--){const a=t[i],l=await e([a.msg]);if(s+l<=r)s+=l,o++;else break}return o}if("fraction"in this.keep&&this.keep.fraction!==void 0){if(!n)return Yn;const r=jn(n);if(typeof r=="number"){const s=Math.floor(r*this.keep.fraction);if(s<=0)return Yn;let o=0,i=0;for(let a=t.length-1;a>=0;a--){const l=t[a],c=await e([l.msg]);if(o+c<=s)o+=c,i++;else break}return i}}return Yn}#n(t,e){for(let n=t.length-1;n>=0;n--){const r=t[n];if(P.isInstance(r)&&r.tool_calls?.some(o=>o.id===e))return r}return null}#s(t,e){const n=t.tool_calls?.map(i=>i.id===e?{...i,args:{}}:i),r={...t.response_metadata},s={...r.context_editing},o=new Set(s.cleared_tool_inputs);return o.add(e),s.cleared_tool_inputs=Array.from(o).sort(),r.context_editing=s,new P({content:t.content,tool_calls:n,response_metadata:r,id:t.id,name:t.name,additional_kwargs:t.additional_kwargs})}};function jg(t={}){const e=t.edits??[new yc],n=t.tokenCountMethod??"approx";return le({name:"ContextEditingMiddleware",wrapModelCall:async(r,s)=>{if(!r.messages||r.messages.length===0)return s(r);const o=r.systemPrompt?[new oe(r.systemPrompt)]:[],i=n==="approx"?Oo:async a=>{const l=[...o,...a];if("getNumTokensFromMessages"in r.model)return r.model.getNumTokensFromMessages(l).then(({totalCount:c})=>c);throw new Error(`Model "${r.model.getName()}" does not support token counting`)};for(const a of e)await a.apply({messages:r.messages,model:r.model,countTokens:i});return s(r)}})}function Lg(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const Dg=["continue","error","end"],wc="continue";function bc(t,e,n,r,s){const o=s?`'${s}' tool`:"Tool",i=[];n!==void 0&&t>n&&i.push(`thread limit exceeded (${t}/${n} calls)`),r!==void 0&&e>r&&i.push(`run limit exceeded (${e}/${r} calls)`);const a=i.join(" and ");return`${o} call limit reached: ${a}.`}const _c=tn(Dg).default(wc);var vc=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const o=bc(t,e,n,r,s);super(o),this.name="ToolCallLimitExceededError",this.threadCount=t,this.runCount=e,this.threadLimit=n,this.runLimit=r,this.toolName=s}};K({toolName:ie().optional(),threadLimit:z().optional(),runLimit:z().optional(),exitBehavior:_c});const Fg=K({threadToolCallCount:Mn(ie(),z()).default({}),runToolCallCount:Mn(ie(),z()).default({})}),Ug="__all__";function Vg(t){if(t.threadLimit===void 0&&t.runLimit===void 0)throw new Error("At least one limit must be specified (threadLimit or runLimit)");const e=t.exitBehavior??wc,n=_c.safeParse(e);if(!n.success)throw new Error(io(n.error).slice(2));if(t.threadLimit!==void 0&&t.runLimit!==void 0&&t.runLimit>t.threadLimit)throw new Error(`runLimit (${t.runLimit}) cannot exceed threadLimit (${t.threadLimit}). The run limit should be less than or equal to the thread limit.`);const r=t.toolName?`ToolCallLimitMiddleware[${t.toolName}]`:"ToolCallLimitMiddleware";return le({name:r,stateSchema:Fg,afterModel:{canJumpTo:["end"],hook:s=>{const o=[...s.messages].reverse().find(P.isInstance);if(!o||!o.tool_calls)return;const i=(g,v)=>t.threadLimit!==void 0&&g+1>t.threadLimit||t.runLimit!==void 0&&v+1>t.runLimit,a=g=>t.toolName===void 0||g.name===t.toolName,l=(g,v,M)=>{const w=[],b=[];let E=v,S=M;for(const x of g)a(x)&&(i(E,S)?b.push(x):(w.push(x),E+=1,S+=1));return{allowed:w,blocked:b,finalThreadCount:E,finalRunCount:S+b.length}},c=t.toolName??Ug,u={...s.threadToolCallCount??{}},d={...s.runToolCallCount??{}},h=u[c]??0,f=d[c]??0,{allowed:m,blocked:p,finalThreadCount:C,finalRunCount:T}=l(o.tool_calls,h,f);if(u[c]=C,d[c]=T,p.length===0)return m.length>0?{threadToolCallCount:u,runToolCallCount:d}:void 0;if(e==="error"){const g=C+p.length;throw new vc(g,T,t.threadLimit,t.runLimit,t.toolName)}const k=Lg(t.toolName),_=p.map(g=>new j({content:k,tool_call_id:g.id,name:g.name,status:"error"}));if(e==="end"){let g=[];if(t.toolName!==void 0?g=o.tool_calls.filter(w=>w.name!==t.toolName):new Set(o.tool_calls.map(b=>b.name).filter(Boolean)).size>1&&(g=m.length>0?m:o.tool_calls),g.length>0){const w=Array.from(new Set(g.map(b=>b.name).filter(Boolean))).join(", ");throw new Error(`Cannot end execution with other tool calls pending. Found calls to: ${w}. Use 'continue' or 'error' behavior instead.`)}const v=C+p.length,M=bc(v,T,t.threadLimit,t.runLimit,t.toolName);return _.push(new P(M)),{threadToolCallCount:u,runToolCallCount:d,jumpTo:"end",messages:_}}return{threadToolCallCount:u,runToolCallCount:d,messages:_}}},afterAgent:()=>({runToolCallCount:{}})})}const Bg=`Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
105
105
  It also helps the user understand the progress of the task and overall progress of their requests.
106
106
  Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the taks directly.
107
107
 
@@ -327,19 +327,19 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
327
327
  - The \`write_todos\` tool should never be called multiple times in parallel.
328
328
  - Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`,zg=tn(["pending","in_progress","completed"]).describe("Status of the todo"),Cc=K({content:ie().describe("Content of the todo item"),status:zg}),Hg=K({todos:Ke(Cc).default([])});function Wg(t){const e=Li(({todos:n},r)=>new G({update:{todos:n,messages:[new j({content:`Updated todo list to ${JSON.stringify(n)}`,tool_call_id:r.toolCall?.id})]}}),{name:"write_todos",description:t?.toolDescription??Bg,schema:K({todos:Ke(Cc).describe("List of todo items to update")})});return le({name:"todoListMiddleware",stateSchema:Hg,tools:[e],wrapModelCall:(n,r)=>r({...n,systemMessage:n.systemMessage.concat(`
329
329
 
330
- ${t?.systemPrompt??Sc}`)}),afterModel:n=>{const r=n.messages;if(!r||r.length===0)return;const s=[...r].reverse().find(i=>P.isInstance(i));if(!s||!s.tool_calls||s.tool_calls.length===0)return;const o=s.tool_calls.filter(i=>i.name===e.name);if(o.length>1)return{messages:o.map(a=>new j({content:"Error: The `write_todos` tool should never be called multiple times in parallel. Please call it only once per model invocation to update the todo list.",tool_call_id:a.id,status:"error"}))}}})}const Gg="end",Kg=K({threadLimit:z().optional(),runLimit:z().optional(),exitBehavior:tn(["error","end"]).optional()}),Jg=K({threadModelCallCount:z().default(0),runModelCallCount:z().default(0)});var ki=class extends Error{constructor({threadLimit:t,runLimit:e,threadCount:n,runCount:r}){const s=[];typeof t=="number"&&typeof n=="number"&&s.push(`thread level call limit reached with ${n} model calls`),typeof e=="number"&&typeof r=="number"&&s.push(`run level call limit reached with ${r} model calls`),super(`Model call limits exceeded${s.length>0?`: ${s.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function kc(t){return le({name:"ModelCallLimitMiddleware",contextSchema:Kg,stateSchema:Jg,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{let r=n.context.exitBehavior??t?.exitBehavior??Gg;r==="throw"&&(console.warn("The 'throw' exit behavior is deprecated. Please use 'error' instead."),r="error");const s=n.context.threadLimit??t?.threadLimit,o=n.context.runLimit??t?.runLimit,i=e.threadModelCallCount,a=e.runModelCallCount;if(typeof s=="number"&&s<=i){const l=new ki({threadLimit:s,threadCount:i});if(r==="end")return{jumpTo:"end",messages:[new P(l.message)]};throw l}if(typeof o=="number"&&o<=a){const l=new ki({runLimit:o,runCount:a});if(r==="end")return{jumpTo:"end",messages:[new P(l.message)]};throw l}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function qg(...t){return le({name:"modelFallbackMiddleware",wrapModelCall:async(e,n)=>{try{return await n(e)}catch(r){for(let s=0;s<t.length;s++)try{const o=t[s],i=typeof o=="string"?await lt(o):o;return await n({...e,model:i})}catch(o){if(s===t.length-1)throw o}throw r}}})}const Tc=K({maxRetries:z().min(0).default(2),retryOn:De([Dn().args(Fn(Error)).returns(_t()),Ke(Le())]).default(()=>()=>!0),backoffFactor:z().min(0).default(2),initialDelayMs:z().min(0).default(1e3),maxDelayMs:z().min(0).default(6e4),jitter:_t().default(!0)});var Ec=class extends Error{cause;constructor(t){const e=io(t).slice(2);super(e),this.name="InvalidRetryConfigError",this.cause=t}};const Ti=K({onFailure:De([gt("error"),gt("continue"),Dn().args(Fn(Error)).returns(ie())]).default("continue")}).merge(Tc);function Yg(t={}){const{success:e,error:n,data:r}=Ti.safeParse(t);if(!e)throw new Ec(n);const{maxRetries:s,retryOn:o,onFailure:i,backoffFactor:a,initialDelayMs:l,maxDelayMs:c,jitter:u}=r,d=p=>typeof o=="function"?o(p):o.some(C=>p.constructor===C),h={backoffFactor:a,initialDelayMs:l,maxDelayMs:c,jitter:u},f=(p,C)=>{const k=p.constructor.name;return`Model call failed after ${C} ${C===1?"attempt":"attempts"} with ${k}: ${p.message}`},m=(p,C)=>{if(i==="error")throw p;let k;return typeof i=="function"?k=i(p):k=f(p,C),new P({content:k})};return le({name:"modelRetryMiddleware",contextSchema:Ti,wrapModelCall:async(p,C)=>{for(let k=0;k<=s;k++)try{return await C(p)}catch(T){const _=k+1,g=T&&typeof T=="object"&&"message"in T?T:new Error(String(T));if(!d(g))return m(g,_);if(k<s){const v=Zl(h,k);v>0&&await Xl(v)}else return m(g,_)}throw new Error("Unexpected: retry loop completed without returning")}})}const Ei=K({tools:Ke(De([Le(),Le(),ie()])).optional(),onFailure:De([gt("error"),gt("continue"),gt("raise"),gt("return_message"),Dn().args(Fn(Error)).returns(ie())]).default("continue")}).merge(Tc);function Xg(t={}){const{success:e,error:n,data:r}=Ei.safeParse(t);if(!e)throw new Ec(n);const{maxRetries:s,tools:o,retryOn:i,onFailure:a,backoffFactor:l,initialDelayMs:c,maxDelayMs:u,jitter:d}=r;let h=a;a==="raise"?(console.warn("⚠️ `onFailure: 'raise'` is deprecated. Use `onFailure: 'error'` instead."),h="error"):a==="return_message"&&(console.warn("⚠️ `onFailure: 'return_message'` is deprecated. Use `onFailure: 'continue'` instead."),h="continue");const f=[];for(const _ of o??[])if(typeof _=="string")f.push(_);else if("name"in _&&typeof _.name=="string")f.push(_.name);else throw new TypeError("Expected a tool name string or tool instance to be passed to toolRetryMiddleware");const m=_=>f.length===0?!0:f.includes(_),p=_=>typeof i=="function"?i(_):i.some(g=>_ instanceof g),C={backoffFactor:l,initialDelayMs:c,maxDelayMs:u,jitter:d},k=(_,g,v)=>{const M=g.constructor.name;return`Tool '${_}' failed after ${v} ${v===1?"attempt":"attempts"} with ${M}`},T=(_,g,v,M)=>{if(h==="error")throw v;let w;return typeof h=="function"?w=h(v):w=k(_,v,M),new j({content:w,tool_call_id:g,name:_,status:"error"})};return le({name:"toolRetryMiddleware",contextSchema:Ei,wrapToolCall:async(_,g)=>{const v=_.tool?.name??_.toolCall.name;if(!m(v))return g(_);const M=_.toolCall.id??"";for(let w=0;w<=s;w++)try{return await g(_)}catch(b){const E=w+1,S=b&&typeof b=="object"&&"message"in b?b:new Error(String(b));if(!p(S))return T(v,M,S,E);if(w<s){const x=Zl(C,w);x>0&&await Xl(x)}else return T(v,M,S,E)}throw new Error("Unexpected: retry loop completed without returning")}})}function Zg(t={}){let e;const{tools:n,model:r}=t,s=!n||n.length===0,o=new Set;if(!s&&n)for(const l of n)if(typeof l=="string")o.add(l);else{const c=typeof l.name=="string"?l.name:String(l.name);o.add(c)}let i;const a=async()=>typeof r=="object"?r:typeof r=="string"?(i=i??await lt(r,{temperature:1}).catch(l=>(console.error("Error initializing emulator model, using agent model:",l),e)),i):e;return le({name:"ToolEmulatorMiddleware",wrapModelCall:async(l,c)=>(e=l.model,c(l)),wrapToolCall:async(l,c)=>{const u=l.toolCall.name;if(!(s||o.has(u)))return c(l);const h=l.toolCall.args,f=l.tool?.description||"No description available",m=typeof h=="string"?h:JSON.stringify(h),p=`You are emulating a tool call for testing purposes.
330
+ ${t?.systemPrompt??Sc}`)}),afterModel:n=>{const r=n.messages;if(!r||r.length===0)return;const s=[...r].reverse().find(i=>P.isInstance(i));if(!s||!s.tool_calls||s.tool_calls.length===0)return;const o=s.tool_calls.filter(i=>i.name===e.name);if(o.length>1)return{messages:o.map(a=>new j({content:"Error: The `write_todos` tool should never be called multiple times in parallel. Please call it only once per model invocation to update the todo list.",tool_call_id:a.id,status:"error"}))}}})}const Gg="end",Kg=K({threadLimit:z().optional(),runLimit:z().optional(),exitBehavior:tn(["error","end"]).optional()}),Jg=K({threadModelCallCount:z().default(0),runModelCallCount:z().default(0)});var Ti=class extends Error{constructor({threadLimit:t,runLimit:e,threadCount:n,runCount:r}){const s=[];typeof t=="number"&&typeof n=="number"&&s.push(`thread level call limit reached with ${n} model calls`),typeof e=="number"&&typeof r=="number"&&s.push(`run level call limit reached with ${r} model calls`),super(`Model call limits exceeded${s.length>0?`: ${s.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function Tc(t){return le({name:"ModelCallLimitMiddleware",contextSchema:Kg,stateSchema:Jg,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{let r=n.context.exitBehavior??t?.exitBehavior??Gg;r==="throw"&&(console.warn("The 'throw' exit behavior is deprecated. Please use 'error' instead."),r="error");const s=n.context.threadLimit??t?.threadLimit,o=n.context.runLimit??t?.runLimit,i=e.threadModelCallCount,a=e.runModelCallCount;if(typeof s=="number"&&s<=i){const l=new Ti({threadLimit:s,threadCount:i});if(r==="end")return{jumpTo:"end",messages:[new P(l.message)]};throw l}if(typeof o=="number"&&o<=a){const l=new Ti({runLimit:o,runCount:a});if(r==="end")return{jumpTo:"end",messages:[new P(l.message)]};throw l}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function qg(...t){return le({name:"modelFallbackMiddleware",wrapModelCall:async(e,n)=>{try{return await n(e)}catch(r){for(let s=0;s<t.length;s++)try{const o=t[s],i=typeof o=="string"?await lt(o):o;return await n({...e,model:i})}catch(o){if(s===t.length-1)throw o}throw r}}})}const kc=K({maxRetries:z().min(0).default(2),retryOn:De([Dn().args(Fn(Error)).returns(_t()),Ke(Le())]).default(()=>()=>!0),backoffFactor:z().min(0).default(2),initialDelayMs:z().min(0).default(1e3),maxDelayMs:z().min(0).default(6e4),jitter:_t().default(!0)});var Ec=class extends Error{cause;constructor(t){const e=io(t).slice(2);super(e),this.name="InvalidRetryConfigError",this.cause=t}};const ki=K({onFailure:De([gt("error"),gt("continue"),Dn().args(Fn(Error)).returns(ie())]).default("continue")}).merge(kc);function Yg(t={}){const{success:e,error:n,data:r}=ki.safeParse(t);if(!e)throw new Ec(n);const{maxRetries:s,retryOn:o,onFailure:i,backoffFactor:a,initialDelayMs:l,maxDelayMs:c,jitter:u}=r,d=p=>typeof o=="function"?o(p):o.some(C=>p.constructor===C),h={backoffFactor:a,initialDelayMs:l,maxDelayMs:c,jitter:u},f=(p,C)=>{const T=p.constructor.name;return`Model call failed after ${C} ${C===1?"attempt":"attempts"} with ${T}: ${p.message}`},m=(p,C)=>{if(i==="error")throw p;let T;return typeof i=="function"?T=i(p):T=f(p,C),new P({content:T})};return le({name:"modelRetryMiddleware",contextSchema:ki,wrapModelCall:async(p,C)=>{for(let T=0;T<=s;T++)try{return await C(p)}catch(k){const _=T+1,g=k&&typeof k=="object"&&"message"in k?k:new Error(String(k));if(!d(g))return m(g,_);if(T<s){const v=Zl(h,T);v>0&&await Xl(v)}else return m(g,_)}throw new Error("Unexpected: retry loop completed without returning")}})}const Ei=K({tools:Ke(De([Le(),Le(),ie()])).optional(),onFailure:De([gt("error"),gt("continue"),gt("raise"),gt("return_message"),Dn().args(Fn(Error)).returns(ie())]).default("continue")}).merge(kc);function Xg(t={}){const{success:e,error:n,data:r}=Ei.safeParse(t);if(!e)throw new Ec(n);const{maxRetries:s,tools:o,retryOn:i,onFailure:a,backoffFactor:l,initialDelayMs:c,maxDelayMs:u,jitter:d}=r;let h=a;a==="raise"?(console.warn("⚠️ `onFailure: 'raise'` is deprecated. Use `onFailure: 'error'` instead."),h="error"):a==="return_message"&&(console.warn("⚠️ `onFailure: 'return_message'` is deprecated. Use `onFailure: 'continue'` instead."),h="continue");const f=[];for(const _ of o??[])if(typeof _=="string")f.push(_);else if("name"in _&&typeof _.name=="string")f.push(_.name);else throw new TypeError("Expected a tool name string or tool instance to be passed to toolRetryMiddleware");const m=_=>f.length===0?!0:f.includes(_),p=_=>typeof i=="function"?i(_):i.some(g=>_ instanceof g),C={backoffFactor:l,initialDelayMs:c,maxDelayMs:u,jitter:d},T=(_,g,v)=>{const M=g.constructor.name;return`Tool '${_}' failed after ${v} ${v===1?"attempt":"attempts"} with ${M}`},k=(_,g,v,M)=>{if(h==="error")throw v;let w;return typeof h=="function"?w=h(v):w=T(_,v,M),new j({content:w,tool_call_id:g,name:_,status:"error"})};return le({name:"toolRetryMiddleware",contextSchema:Ei,wrapToolCall:async(_,g)=>{const v=_.tool?.name??_.toolCall.name;if(!m(v))return g(_);const M=_.toolCall.id??"";for(let w=0;w<=s;w++)try{return await g(_)}catch(b){const E=w+1,S=b&&typeof b=="object"&&"message"in b?b:new Error(String(b));if(!p(S))return k(v,M,S,E);if(w<s){const x=Zl(C,w);x>0&&await Xl(x)}else return k(v,M,S,E)}throw new Error("Unexpected: retry loop completed without returning")}})}function Zg(t={}){let e;const{tools:n,model:r}=t,s=!n||n.length===0,o=new Set;if(!s&&n)for(const l of n)if(typeof l=="string")o.add(l);else{const c=typeof l.name=="string"?l.name:String(l.name);o.add(c)}let i;const a=async()=>typeof r=="object"?r:typeof r=="string"?(i=i??await lt(r,{temperature:1}).catch(l=>(console.error("Error initializing emulator model, using agent model:",l),e)),i):e;return le({name:"ToolEmulatorMiddleware",wrapModelCall:async(l,c)=>(e=l.model,c(l)),wrapToolCall:async(l,c)=>{const u=l.toolCall.name;if(!(s||o.has(u)))return c(l);const h=l.toolCall.args,f=l.tool?.description||"No description available",m=typeof h=="string"?h:JSON.stringify(h),p=`You are emulating a tool call for testing purposes.
331
331
 
332
332
  Tool: ${u}
333
333
  Description: ${f}
334
334
  Arguments: ${m}
335
335
 
336
336
  Generate a realistic response that this tool would return given these arguments.
337
- Return ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`,k=await(await a()).invoke([new se(p)]),T=typeof k.content=="string"?k.content:JSON.stringify(k.content);return new j({content:T,tool_call_id:l.toolCall.id??"",name:u})}})}function Qg(t){return!t||typeof t!="object"||t===null||!("client"in t)||!("_getClientOptions"in t)||typeof t._getClientOptions!="function"?!1:(t._getClientOptions(),typeof t.client=="object"&&t.client!==null&&"moderations"in t.client&&typeof t.client.moderations=="object"&&t.client.moderations!==null&&"create"in t.client.moderations&&typeof t.client.moderations.create=="function")}const ey="I'm sorry, but I can't comply with that request. It was flagged for {categories}.";var ty=class extends Error{content;stage;result;originalMessage;constructor({content:t,stage:e,result:n,message:r}){super(r),this.name="OpenAIModerationError",this.content=t,this.stage=e,this.result=n,this.originalMessage=r}};function ny(t){const{model:e,moderationModel:n="omni-moderation-latest",checkInput:r=!0,checkOutput:s=!0,checkToolResults:o=!1,exitBehavior:i="end",violationMessage:a}=t;let l;const c=async()=>{if(l)return l;const _=typeof e=="string"?await lt(e):e;if(!_.getName().includes("ChatOpenAI"))throw new Error(`Model must be an OpenAI model to use moderation middleware. Got: ${_.getName()}`);if(!Qg(_))throw new Error("Model must support moderation to use moderation middleware.");return l=_,l},u=_=>_.content==null?null:_.text||null,d=(_,g)=>{for(let v=_.length-1;v>=0;v--)if(g.isInstance(_[v]))return v;return null},h=(_,g)=>{const v=[],M=g.categories;for(const[S,x]of Object.entries(M))x&&v.push(S.replace(/_/g," "));const w=v.length>0?v.join(", "):"OpenAI's safety policies",b=a||ey,E=JSON.stringify(g.category_scores,null,2);try{return b.replace("{categories}",w).replace("{category_scores}",E).replace("{original_content}",_)}catch{return b}};function f(_,g){const v=l?._getClientOptions?.(),M=g?.model??"omni-moderation-latest",w={input:_,model:M};return l.client.moderations.create(w,v)}const m=(_,g,v,M,w)=>{const b=h(M,w);if(i==="error")throw new ty({content:M,stage:v,result:w,message:b});if(i==="end")return{jumpTo:"end",messages:[new P({content:b})]};if(g==null)return;const E=[..._],S=E[g],x=Object.getPrototypeOf(S).constructor;return E[g]=new x({...S,content:b}),{messages:E}},p=async _=>{const g=d(_,se);if(g==null)return null;const v=_[g],M=u(v);if(!M)return null;await c();const b=(await f(M,{model:n})).results.find(E=>E.flagged);return b?m(_,g,"input",M,b):null},C=async _=>{const g=d(_,P);if(g==null)return null;const v=[..._];let M=!1;for(let w=g+1;w<v.length;w++){const b=v[w];if(!j.isInstance(b))continue;const E=u(b);if(!E)continue;await c();const x=(await f(E,{model:n})).results.find(O=>O.flagged);if(!x)continue;const I=m(v,w,"tool",E,x);if(I){if("jumpTo"in I)return I;"messages"in I&&(v.splice(0,v.length,...I.messages),M=!0)}}return M?{messages:v}:null},k=async _=>{const g=d(_,P);if(g==null)return null;const v=_[g],M=u(v);if(!M)return null;await c();const b=(await f(M,{model:n})).results.find(E=>E.flagged);return b?m(_,g,"output",M,b):null},T=async _=>{const g=[..._];let v=!1;if(o){const M=await C(g);if(M){if("jumpTo"in M)return M;"messages"in M&&(g.splice(0,g.length,...M.messages),v=!0)}}if(r){const M=await p(g);if(M){if("jumpTo"in M)return M;"messages"in M&&(g.splice(0,g.length,...M.messages),v=!0)}}return v?{messages:g}:null};return le({name:"OpenAIModerationMiddleware",beforeModel:{hook:async _=>{if(!r&&!o)return;const g=_.messages||[];if(g.length!==0)return await T(g)??void 0},canJumpTo:["end"]},afterModel:{hook:async _=>{if(!s)return;const g=_.messages||[];if(g.length!==0)return await k(g)??void 0},canJumpTo:["end"]}})}const ry=!0,sy="5m",oy=3,iy="warn",ay=K({enableCaching:_t().optional(),ttl:tn(["5m","1h"]).optional(),minMessagesToCache:z().optional(),unsupportedModelBehavior:tn(["ignore","warn","raise"]).optional()});var ly=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function cy(t){return le({name:"PromptCachingMiddleware",contextSchema:ay,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??ry,s=e.runtime.context.ttl??t?.ttl??sy,o=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??oy,i=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??iy;if(!r||!e.model)return n(e);if(!(e.model.getName()==="ChatAnthropic"||e.model.getName()==="ConfigurableModel"&&e.model._defaultConfig?.modelProvider==="anthropic")){const c=e.model.getName(),d=`Unsupported model '${e.model.getName()==="ConfigurableModel"?`${c} (${e.model._defaultConfig?.modelProvider})`:c}'. Prompt caching requires an Anthropic model`;if(i==="raise")throw new ly(`${d} (e.g., 'anthropic:claude-4-0-sonnet').`);return i==="warn"&&console.warn(`PromptCachingMiddleware: Skipping caching for ${c}. Consider switching to an Anthropic model for caching benefits.`),n(e)}return e.state.messages.length+(e.systemPrompt?1:0)<o?n(e):n({...e,modelSettings:{...e.modelSettings,cache_control:{type:"ephemeral",ttl:s}}})}})}var uy={};Ki(uy,{AIMessage:()=>P,AIMessageChunk:()=>Qt,BaseMessage:()=>_n,BaseMessageChunk:()=>ju,ClearToolUsesEdit:()=>yc,Document:()=>We,DynamicStructuredTool:()=>Qn,DynamicTool:()=>Ku,FakeToolCallingModel:()=>_m,HumanMessage:()=>se,HumanMessageChunk:()=>$u,InMemoryStore:()=>aa,MIDDLEWARE_BRAND:()=>Ql,MiddlewareError:()=>Io,MultipleStructuredOutputsError:()=>qs,MultipleToolsBoundError:()=>Js,PIIDetectionError:()=>cc,ProviderStrategy:()=>et,StructuredOutputParsingError:()=>Gl,StructuredTool:()=>jr,SystemMessage:()=>oe,SystemMessageChunk:()=>Ru,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>Sc,Tool:()=>Gu,ToolCallLimitExceededError:()=>vc,ToolInvocationError:()=>Ao,ToolMessage:()=>j,ToolMessageChunk:()=>Nu,ToolStrategy:()=>Xe,anthropicPromptCachingMiddleware:()=>cy,applyStrategy:()=>gc,context:()=>Xa,contextEditingMiddleware:()=>jg,countTokensApproximately:()=>Oo,createAgent:()=>sc,createMiddleware:()=>le,detectCreditCard:()=>hc,detectEmail:()=>uc,detectIP:()=>dc,detectMacAddress:()=>fc,detectUrl:()=>pc,dynamicSystemPromptMiddleware:()=>dg,filterMessages:()=>Ou,humanInTheLoopMiddleware:()=>Zm,initChatModel:()=>lt,llmToolSelectorMiddleware:()=>gg,modelCallLimitMiddleware:()=>kc,modelFallbackMiddleware:()=>qg,modelRetryMiddleware:()=>Yg,openAIModerationMiddleware:()=>ny,piiMiddleware:()=>Ag,piiRedactionMiddleware:()=>Ng,providerStrategy:()=>wm,resolveRedactionRule:()=>mc,summarizationMiddleware:()=>ng,todoListMiddleware:()=>Wg,tool:()=>Li,toolCallLimitMiddleware:()=>Vg,toolEmulatorMiddleware:()=>Zg,toolRetryMiddleware:()=>Xg,toolStrategy:()=>ym,trimMessages:()=>$i});var Zs={},zt,zr=(zt=class extends jr{name="mcp_server_tool";description="Base tool for MCP server operations.";schema;_manager;constructor(e){super(),this._manager=e}async _call(e,n,r){throw new Error("Method not implemented.")}get manager(){return this._manager}},R(zt,"MCPServerTool"),zt),hy=re({}),Ht,dy=(Ht=class extends zr{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=hy;constructor(e){super(e)}async _call(){return this.manager.activeServer?`Currently active MCP server: ${this.manager.activeServer}`:"No MCP server is currently active. Use connect_to_mcp_server to connect to a server."}},R(Ht,"AcquireActiveMCPServerTool"),Ht),Wt,fy=(Wt=class extends jr{name="add_mcp_server_from_config";description="Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";schema=re({serverName:Tn().describe("The name for the new MCP server."),serverConfig:ve().describe('The configuration object for the server. This should not include the top-level "mcpServers" key.')});manager;constructor(e){super(),this.manager=e}async _call({serverName:e,serverConfig:n}){try{this.manager.client.addServer(e,n);let r=`Server '${e}' added to the client.`;y.debug(`Connecting to new server '${e}' and discovering tools.`);const o=(await this.manager.client.createSession(e)).connector,i=await this.manager.adapter.createToolsFromConnectors([o]);this.manager.serverTools[e]=i,this.manager.initializedServers[e]=!0,this.manager.activeServer=e;const a=i.length;return r+=` Session created and connected. '${e}' is now the active server with ${a} tools available.`,r+=`
337
+ Return ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`,T=await(await a()).invoke([new se(p)]),k=typeof T.content=="string"?T.content:JSON.stringify(T.content);return new j({content:k,tool_call_id:l.toolCall.id??"",name:u})}})}function Qg(t){return!t||typeof t!="object"||t===null||!("client"in t)||!("_getClientOptions"in t)||typeof t._getClientOptions!="function"?!1:(t._getClientOptions(),typeof t.client=="object"&&t.client!==null&&"moderations"in t.client&&typeof t.client.moderations=="object"&&t.client.moderations!==null&&"create"in t.client.moderations&&typeof t.client.moderations.create=="function")}const ey="I'm sorry, but I can't comply with that request. It was flagged for {categories}.";var ty=class extends Error{content;stage;result;originalMessage;constructor({content:t,stage:e,result:n,message:r}){super(r),this.name="OpenAIModerationError",this.content=t,this.stage=e,this.result=n,this.originalMessage=r}};function ny(t){const{model:e,moderationModel:n="omni-moderation-latest",checkInput:r=!0,checkOutput:s=!0,checkToolResults:o=!1,exitBehavior:i="end",violationMessage:a}=t;let l;const c=async()=>{if(l)return l;const _=typeof e=="string"?await lt(e):e;if(!_.getName().includes("ChatOpenAI"))throw new Error(`Model must be an OpenAI model to use moderation middleware. Got: ${_.getName()}`);if(!Qg(_))throw new Error("Model must support moderation to use moderation middleware.");return l=_,l},u=_=>_.content==null?null:_.text||null,d=(_,g)=>{for(let v=_.length-1;v>=0;v--)if(g.isInstance(_[v]))return v;return null},h=(_,g)=>{const v=[],M=g.categories;for(const[S,x]of Object.entries(M))x&&v.push(S.replace(/_/g," "));const w=v.length>0?v.join(", "):"OpenAI's safety policies",b=a||ey,E=JSON.stringify(g.category_scores,null,2);try{return b.replace("{categories}",w).replace("{category_scores}",E).replace("{original_content}",_)}catch{return b}};function f(_,g){const v=l?._getClientOptions?.(),M=g?.model??"omni-moderation-latest",w={input:_,model:M};return l.client.moderations.create(w,v)}const m=(_,g,v,M,w)=>{const b=h(M,w);if(i==="error")throw new ty({content:M,stage:v,result:w,message:b});if(i==="end")return{jumpTo:"end",messages:[new P({content:b})]};if(g==null)return;const E=[..._],S=E[g],x=Object.getPrototypeOf(S).constructor;return E[g]=new x({...S,content:b}),{messages:E}},p=async _=>{const g=d(_,se);if(g==null)return null;const v=_[g],M=u(v);if(!M)return null;await c();const b=(await f(M,{model:n})).results.find(E=>E.flagged);return b?m(_,g,"input",M,b):null},C=async _=>{const g=d(_,P);if(g==null)return null;const v=[..._];let M=!1;for(let w=g+1;w<v.length;w++){const b=v[w];if(!j.isInstance(b))continue;const E=u(b);if(!E)continue;await c();const x=(await f(E,{model:n})).results.find(O=>O.flagged);if(!x)continue;const I=m(v,w,"tool",E,x);if(I){if("jumpTo"in I)return I;"messages"in I&&(v.splice(0,v.length,...I.messages),M=!0)}}return M?{messages:v}:null},T=async _=>{const g=d(_,P);if(g==null)return null;const v=_[g],M=u(v);if(!M)return null;await c();const b=(await f(M,{model:n})).results.find(E=>E.flagged);return b?m(_,g,"output",M,b):null},k=async _=>{const g=[..._];let v=!1;if(o){const M=await C(g);if(M){if("jumpTo"in M)return M;"messages"in M&&(g.splice(0,g.length,...M.messages),v=!0)}}if(r){const M=await p(g);if(M){if("jumpTo"in M)return M;"messages"in M&&(g.splice(0,g.length,...M.messages),v=!0)}}return v?{messages:g}:null};return le({name:"OpenAIModerationMiddleware",beforeModel:{hook:async _=>{if(!r&&!o)return;const g=_.messages||[];if(g.length!==0)return await k(g)??void 0},canJumpTo:["end"]},afterModel:{hook:async _=>{if(!s)return;const g=_.messages||[];if(g.length!==0)return await T(g)??void 0},canJumpTo:["end"]}})}const ry=!0,sy="5m",oy=3,iy="warn",ay=K({enableCaching:_t().optional(),ttl:tn(["5m","1h"]).optional(),minMessagesToCache:z().optional(),unsupportedModelBehavior:tn(["ignore","warn","raise"]).optional()});var ly=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function cy(t){return le({name:"PromptCachingMiddleware",contextSchema:ay,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??ry,s=e.runtime.context.ttl??t?.ttl??sy,o=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??oy,i=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??iy;if(!r||!e.model)return n(e);if(!(e.model.getName()==="ChatAnthropic"||e.model.getName()==="ConfigurableModel"&&e.model._defaultConfig?.modelProvider==="anthropic")){const c=e.model.getName(),d=`Unsupported model '${e.model.getName()==="ConfigurableModel"?`${c} (${e.model._defaultConfig?.modelProvider})`:c}'. Prompt caching requires an Anthropic model`;if(i==="raise")throw new ly(`${d} (e.g., 'anthropic:claude-4-0-sonnet').`);return i==="warn"&&console.warn(`PromptCachingMiddleware: Skipping caching for ${c}. Consider switching to an Anthropic model for caching benefits.`),n(e)}return e.state.messages.length+(e.systemPrompt?1:0)<o?n(e):n({...e,modelSettings:{...e.modelSettings,cache_control:{type:"ephemeral",ttl:s}}})}})}var uy={};Ki(uy,{AIMessage:()=>P,AIMessageChunk:()=>Qt,BaseMessage:()=>_n,BaseMessageChunk:()=>ju,ClearToolUsesEdit:()=>yc,Document:()=>We,DynamicStructuredTool:()=>Qn,DynamicTool:()=>Ku,FakeToolCallingModel:()=>_m,HumanMessage:()=>se,HumanMessageChunk:()=>$u,InMemoryStore:()=>aa,MIDDLEWARE_BRAND:()=>Ql,MiddlewareError:()=>Io,MultipleStructuredOutputsError:()=>qs,MultipleToolsBoundError:()=>Js,PIIDetectionError:()=>cc,ProviderStrategy:()=>et,StructuredOutputParsingError:()=>Gl,StructuredTool:()=>jr,SystemMessage:()=>oe,SystemMessageChunk:()=>Ru,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>Sc,Tool:()=>Gu,ToolCallLimitExceededError:()=>vc,ToolInvocationError:()=>Ao,ToolMessage:()=>j,ToolMessageChunk:()=>Nu,ToolStrategy:()=>Xe,anthropicPromptCachingMiddleware:()=>cy,applyStrategy:()=>gc,context:()=>Xa,contextEditingMiddleware:()=>jg,countTokensApproximately:()=>Oo,createAgent:()=>sc,createMiddleware:()=>le,detectCreditCard:()=>hc,detectEmail:()=>uc,detectIP:()=>dc,detectMacAddress:()=>fc,detectUrl:()=>pc,dynamicSystemPromptMiddleware:()=>dg,filterMessages:()=>Ou,humanInTheLoopMiddleware:()=>Zm,initChatModel:()=>lt,llmToolSelectorMiddleware:()=>gg,modelCallLimitMiddleware:()=>Tc,modelFallbackMiddleware:()=>qg,modelRetryMiddleware:()=>Yg,openAIModerationMiddleware:()=>ny,piiMiddleware:()=>Ag,piiRedactionMiddleware:()=>Ng,providerStrategy:()=>wm,resolveRedactionRule:()=>mc,summarizationMiddleware:()=>ng,todoListMiddleware:()=>Wg,tool:()=>Li,toolCallLimitMiddleware:()=>Vg,toolEmulatorMiddleware:()=>Zg,toolRetryMiddleware:()=>Xg,toolStrategy:()=>ym,trimMessages:()=>$i});var Zs={},zt,zr=(zt=class extends jr{name="mcp_server_tool";description="Base tool for MCP server operations.";schema;_manager;constructor(e){super(),this._manager=e}async _call(e,n,r){throw new Error("Method not implemented.")}get manager(){return this._manager}},R(zt,"MCPServerTool"),zt),hy=re({}),Ht,dy=(Ht=class extends zr{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=hy;constructor(e){super(e)}async _call(){return this.manager.activeServer?`Currently active MCP server: ${this.manager.activeServer}`:"No MCP server is currently active. Use connect_to_mcp_server to connect to a server."}},R(Ht,"AcquireActiveMCPServerTool"),Ht),Wt,fy=(Wt=class extends jr{name="add_mcp_server_from_config";description="Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";schema=re({serverName:kn().describe("The name for the new MCP server."),serverConfig:ve().describe('The configuration object for the server. This should not include the top-level "mcpServers" key.')});manager;constructor(e){super(),this.manager=e}async _call({serverName:e,serverConfig:n}){try{this.manager.client.addServer(e,n);let r=`Server '${e}' added to the client.`;y.debug(`Connecting to new server '${e}' and discovering tools.`);const o=(await this.manager.client.createSession(e)).connector,i=await this.manager.adapter.createToolsFromConnectors([o]);this.manager.serverTools[e]=i,this.manager.initializedServers[e]=!0,this.manager.activeServer=e;const a=i.length;return r+=` Session created and connected. '${e}' is now the active server with ${a} tools available.`,r+=`
338
338
 
339
339
  ${i.map(l=>l.name).join(`
340
- `)}`,y.info(r),r}catch(r){return y.error(`Failed to add or connect to server '${e}': ${r.message}`),`Failed to add or connect to server '${e}': ${r.message}`}}},R(Wt,"AddMCPServerFromConfigTool"),Wt),py=re({serverName:Tn().describe("The name of the MCP server.")}),Gt,my=(Gt=class extends zr{name="connect_to_mcp_server";description="Connect to a specific MCP (Model Context Protocol) server to use its tools. Use this tool to connect to a specific server and use its tools.";schema=py;constructor(e){super(e)}async _call({serverName:e}){const n=this.manager.client.getServerNames();if(!n.includes(e)){const r=n.length>0?n.join(", "):"none";return`Server '${e}' not found. Available servers: ${r}`}if(this.manager.activeServer===e)return`Already connected to MCP server '${e}'`;try{let r=this.manager.client.getSession(e);if(y.debug(`Using existing session for server '${e}'`),r||(y.debug(`Creating new session for server '${e}'`),r=await this.manager.client.createSession(e)),this.manager.activeServer=e,!this.manager.serverTools[e]){const i=r.connector,a=await this.manager.adapter.createToolsFromConnectors([i]),l=await this.manager.adapter.createResourcesFromConnectors([i]),c=await this.manager.adapter.createPromptsFromConnectors([i]),u=[...a,...l,...c];this.manager.serverTools[e]=u,this.manager.initializedServers[e]=!0,y.debug(`Loaded ${u.length} items for server '${e}': ${a.length} tools, ${l.length} resources, ${c.length} prompts`)}const o=(this.manager.serverTools[e]||[]).length;return`Connected to MCP server '${e}'. ${o} tools, resources, and prompts are now available.`}catch(r){return y.error(`Error connecting to server '${e}': ${String(r)}`),`Failed to connect to server '${e}': ${String(r)}`}}},R(Gt,"ConnectMCPServerTool"),Gt),gy=re({}),Kt,yy=(Kt=class extends zr{name="list_mcp_servers";description="Lists all available MCP (Model Context Protocol) servers that can be connected to, along with the tools available on each server. Use this tool to discover servers and see what functionalities they offer.";schema=gy;constructor(e){super(e)}async _call(){const e=this.manager.client.getServerNames();if(e.length===0)return"No MCP servers are currently defined.";const n=["Available MCP servers:"];for(const r of e){const o=r===this.manager.activeServer?" (ACTIVE)":"";n.push(`- ${r}${o}`);try{const i=this.manager.serverTools?.[r]??[],a=Array.isArray(i)?i.length:0;n.push(`${a} tools available for this server
340
+ `)}`,y.info(r),r}catch(r){return y.error(`Failed to add or connect to server '${e}': ${r.message}`),`Failed to add or connect to server '${e}': ${r.message}`}}},R(Wt,"AddMCPServerFromConfigTool"),Wt),py=re({serverName:kn().describe("The name of the MCP server.")}),Gt,my=(Gt=class extends zr{name="connect_to_mcp_server";description="Connect to a specific MCP (Model Context Protocol) server to use its tools. Use this tool to connect to a specific server and use its tools.";schema=py;constructor(e){super(e)}async _call({serverName:e}){const n=this.manager.client.getServerNames();if(!n.includes(e)){const r=n.length>0?n.join(", "):"none";return`Server '${e}' not found. Available servers: ${r}`}if(this.manager.activeServer===e)return`Already connected to MCP server '${e}'`;try{let r=this.manager.client.getSession(e);if(y.debug(`Using existing session for server '${e}'`),r||(y.debug(`Creating new session for server '${e}'`),r=await this.manager.client.createSession(e)),this.manager.activeServer=e,!this.manager.serverTools[e]){const i=r.connector,a=await this.manager.adapter.createToolsFromConnectors([i]),l=await this.manager.adapter.createResourcesFromConnectors([i]),c=await this.manager.adapter.createPromptsFromConnectors([i]),u=[...a,...l,...c];this.manager.serverTools[e]=u,this.manager.initializedServers[e]=!0,y.debug(`Loaded ${u.length} items for server '${e}': ${a.length} tools, ${l.length} resources, ${c.length} prompts`)}const o=(this.manager.serverTools[e]||[]).length;return`Connected to MCP server '${e}'. ${o} tools, resources, and prompts are now available.`}catch(r){return y.error(`Error connecting to server '${e}': ${String(r)}`),`Failed to connect to server '${e}': ${String(r)}`}}},R(Gt,"ConnectMCPServerTool"),Gt),gy=re({}),Kt,yy=(Kt=class extends zr{name="list_mcp_servers";description="Lists all available MCP (Model Context Protocol) servers that can be connected to, along with the tools available on each server. Use this tool to discover servers and see what functionalities they offer.";schema=gy;constructor(e){super(e)}async _call(){const e=this.manager.client.getServerNames();if(e.length===0)return"No MCP servers are currently defined.";const n=["Available MCP servers:"];for(const r of e){const o=r===this.manager.activeServer?" (ACTIVE)":"";n.push(`- ${r}${o}`);try{const i=this.manager.serverTools?.[r]??[],a=Array.isArray(i)?i.length:0;n.push(`${a} tools available for this server
341
341
  `)}catch(i){y.error(`Unexpected error listing tools for server '${r}': ${String(i)}`)}}return n.join(`
342
- `)}},R(Kt,"ListMCPServersTool"),Kt),wy=re({}),Jt,by=(Jt=class extends zr{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=wy;constructor(e){super(e)}async _call(){if(!this.manager.activeServer)return"No MCP server is currently active, so there's nothing to disconnect from.";const e=this.manager.activeServer;return this.manager.activeServer=null,`Successfully disconnected from MCP server '${e}'.`}},R(Jt,"ReleaseMCPServerConnectionTool"),Jt);function $r(t,e){if(t===e)return!0;if(t==null||e==null||typeof t!=typeof e)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)&&Array.isArray(e))return t.length!==e.length?!1:t.every((n,r)=>$r(n,e[r]));if(typeof t=="object"&&typeof e=="object"){const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>Object.prototype.hasOwnProperty.call(e,s)&&$r(t[s],e[s]))}return!1}R($r,"isEqual");var qt,xi=(qt=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(e,n,r){this.client=e,this.adapter=n,this.overrideManagementTools=r}setManagementTools(e){this.overrideManagementTools=e,y.info(`Overriding default management tools with a new set of ${e.length} tools.`)}logState(e){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){y.info("Server Manager State: No servers configured.");return}const s=n.map(o=>({"Server Name":o,Connected:r.includes(o)?"✅":"❌",Initialized:this.initializedServers[o]?"✅":"❌","Tool Count":this.serverTools[o]?.length??0,Active:this.activeServer===o?"✅":"❌"}));y.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&y.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const e=this.client.getServerNames();for(const n of e)try{let r=null;if(r=this.client.getSession(n),y.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(y.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),y.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let o=[],i=[],a=[];try{o=await this.adapter.createToolsFromConnectors([s]),i=await this.adapter.createResourcesFromConnectors([s]),a=await this.adapter.createPromptsFromConnectors([s])}catch(d){y.error(`Failed to create tools/resources/prompts from connector for server '${n}': ${d}`);continue}const l=[...o,...i,...a],c=this.serverTools[n];!c||!$r(c,l)?(this.serverTools[n]=l,this.initializedServers[n]=!0,y.debug(`Prefetched ${l.length} items for server '${n}': ${o.length} tools, ${i.length} resources, ${a.length} prompts.`)):y.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){y.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){y.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new fy(this),new yy(this),new my(this),new dy(this),new by(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return y.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},R(qt,"ServerManager"),qt),Yt,Qs=(Yt=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(e={}){this.customCallbacks=e.customCallbacks,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.agentId=e.agentId,this.metadata=e.metadata,this.metadataProvider=e.metadataProvider,this.tagsProvider=e.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:e,langfuseInitPromise:n}=await nn(async()=>{const{langfuseHandler:s,langfuseInitPromise:o}=await Promise.resolve().then(()=>Ai);return{langfuseHandler:s,langfuseInitPromise:o}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await nn(async()=>{const{initializeLangfuse:o}=await Promise.resolve().then(()=>Ai);return{initializeLangfuse:o}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),y.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=e();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),y.debug("ObservabilityManager: Langfuse handler available"))}catch{y.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(y.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?y.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):y.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(y.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(e=>e.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const e=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:n,metadata:r,tags:s}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),y.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],y.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const e=await this.getCallbacks();for(const n of e)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();y.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const e=await this.getCallbacks();for(const n of e)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();y.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},R(Yt,"ObservabilityManager"),Yt),_y="/api/v1/chats",vy="/api/v1/chats/{chat_id}/execute";function xc(t,e,n,r,s){if(typeof t=="object"&&t!==null){const o=t;return{query:o.prompt,maxSteps:o.maxSteps,manageConnector:o.manageConnector,externalHistory:o.externalHistory,outputSchema:o.schema}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s}}R(xc,"normalizeRemoteRunOptions");var Xt,Mc=(Xt=class{agentId;apiKey;baseUrl;chatId=null;constructor(e){this.agentId=e.agentId,this.baseUrl=e.baseUrl??"https://cloud.mcp-use.com";const n=e.apiKey??(typeof process<"u"&&Zs?.MCP_USE_API_KEY);if(!n)throw new Error("API key is required for remote execution. Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. You can get an API key from https://cloud.mcp-use.com");this.apiKey=n}pydanticToJsonSchema(e){return Zn(e)}parseStructuredResponse(e,n){let r;if(typeof e=="object"&&e!==null)if("result"in e){const s=e.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=e;else if(typeof e=="string")try{r=JSON.parse(e)}catch{r={content:e}}else r=e;try{return n.parse(r)}catch(s){y.warn(`Failed to parse structured output: ${s}`);const o=n._def?.shape();if(o&&"content"in o)return n.parse({content:String(r)});throw s}}async createChatSession(){const e={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},n={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${_y}`;y.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(e)});if(!s.ok){const a=await s.text(),l=s.status;throw l===404?new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`):new Error(`Failed to create chat session: ${l} - ${a}`)}const i=(await s.json()).id;return y.info(`✅ Chat session created: ${i}`),i}catch(s){throw s instanceof Error?new TypeError(`Failed to create chat session: ${s.message}`):new Error(`Failed to create chat session: ${String(s)}`)}}async run(e,n,r,s,o){const{query:i,maxSteps:a,externalHistory:l,outputSchema:c}=xc(e,n,r,s,o);l!==void 0&&y.warn("External history is not yet supported for remote execution");try{y.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const u=this.chatId,d={query:i,max_steps:a??10};c&&(d.output_schema=this.pydanticToJsonSchema(c),y.info("🔧 Using structured output with schema"));const h={"Content-Type":"application/json","x-api-key":this.apiKey},f=`${this.baseUrl}${vy.replace("{chat_id}",u)}`;y.info(`🚀 Executing agent in chat ${u}`);const m=await fetch(f,{method:"POST",headers:h,body:JSON.stringify(d),signal:AbortSignal.timeout(3e5)});if(!m.ok){const C=await m.text(),k=m.status;throw k===401?(y.error(`❌ Authentication failed: ${C}`),new Error("Authentication failed: Invalid or missing API key. Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.")):k===403?(y.error(`❌ Access forbidden: ${C}`),new Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. Check if the agent exists and you have the necessary permissions.`)):k===404?(y.error(`❌ Agent not found: ${C}`),new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`)):k===422?(y.error(`❌ Validation error: ${C}`),new Error(`Request validation failed: ${C}. Please check your query parameters and output schema format.`)):k===500?(y.error(`❌ Server error: ${C}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(y.error(`❌ Remote execution failed with status ${k}: ${C}`),new Error(`Remote agent execution failed: ${k} - ${C}`))}const p=await m.json();if(y.info(`🔧 Response: ${JSON.stringify(p)}`),y.info("✅ Remote execution completed successfully"),typeof p=="object"&&p!==null){if(p.status==="error"||p.error!==null){const C=p.error??String(p);throw y.error(`❌ Remote agent execution failed: ${C}`),new Error(`Remote agent execution failed: ${C}`)}if(String(p).includes("failed to initialize"))throw y.error(`❌ Agent initialization failed: ${p}`),new Error(`Agent initialization failed on remote server. This usually indicates:
342
+ `)}},R(Kt,"ListMCPServersTool"),Kt),wy=re({}),Jt,by=(Jt=class extends zr{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=wy;constructor(e){super(e)}async _call(){if(!this.manager.activeServer)return"No MCP server is currently active, so there's nothing to disconnect from.";const e=this.manager.activeServer;return this.manager.activeServer=null,`Successfully disconnected from MCP server '${e}'.`}},R(Jt,"ReleaseMCPServerConnectionTool"),Jt);function $r(t,e){if(t===e)return!0;if(t==null||e==null||typeof t!=typeof e)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)&&Array.isArray(e))return t.length!==e.length?!1:t.every((n,r)=>$r(n,e[r]));if(typeof t=="object"&&typeof e=="object"){const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>Object.prototype.hasOwnProperty.call(e,s)&&$r(t[s],e[s]))}return!1}R($r,"isEqual");var qt,xi=(qt=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(e,n,r){this.client=e,this.adapter=n,this.overrideManagementTools=r}setManagementTools(e){this.overrideManagementTools=e,y.info(`Overriding default management tools with a new set of ${e.length} tools.`)}logState(e){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){y.info("Server Manager State: No servers configured.");return}const s=n.map(o=>({"Server Name":o,Connected:r.includes(o)?"✅":"❌",Initialized:this.initializedServers[o]?"✅":"❌","Tool Count":this.serverTools[o]?.length??0,Active:this.activeServer===o?"✅":"❌"}));y.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&y.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const e=this.client.getServerNames();for(const n of e)try{let r=null;if(r=this.client.getSession(n),y.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(y.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),y.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let o=[],i=[],a=[];try{o=await this.adapter.createToolsFromConnectors([s]),i=await this.adapter.createResourcesFromConnectors([s]),a=await this.adapter.createPromptsFromConnectors([s])}catch(d){y.error(`Failed to create tools/resources/prompts from connector for server '${n}': ${d}`);continue}const l=[...o,...i,...a],c=this.serverTools[n];!c||!$r(c,l)?(this.serverTools[n]=l,this.initializedServers[n]=!0,y.debug(`Prefetched ${l.length} items for server '${n}': ${o.length} tools, ${i.length} resources, ${a.length} prompts.`)):y.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){y.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){y.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new fy(this),new yy(this),new my(this),new dy(this),new by(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return y.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},R(qt,"ServerManager"),qt),Yt,Qs=(Yt=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(e={}){this.customCallbacks=e.customCallbacks,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.agentId=e.agentId,this.metadata=e.metadata,this.metadataProvider=e.metadataProvider,this.tagsProvider=e.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:e,langfuseInitPromise:n}=await nn(async()=>{const{langfuseHandler:s,langfuseInitPromise:o}=await Promise.resolve().then(()=>Ai);return{langfuseHandler:s,langfuseInitPromise:o}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await nn(async()=>{const{initializeLangfuse:o}=await Promise.resolve().then(()=>Ai);return{initializeLangfuse:o}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),y.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=e();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),y.debug("ObservabilityManager: Langfuse handler available"))}catch{y.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(y.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?y.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):y.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(y.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(e=>e.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const e=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:n,metadata:r,tags:s}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),y.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],y.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const e=await this.getCallbacks();for(const n of e)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();y.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const e=await this.getCallbacks();for(const n of e)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();y.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},R(Yt,"ObservabilityManager"),Yt),_y="/api/v1/chats",vy="/api/v1/chats/{chat_id}/execute";function xc(t,e,n,r,s){if(typeof t=="object"&&t!==null){const o=t;return{query:o.prompt,maxSteps:o.maxSteps,manageConnector:o.manageConnector,externalHistory:o.externalHistory,outputSchema:o.schema}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s}}R(xc,"normalizeRemoteRunOptions");var Xt,Mc=(Xt=class{agentId;apiKey;baseUrl;chatId=null;constructor(e){this.agentId=e.agentId,this.baseUrl=e.baseUrl??"https://cloud.mcp-use.com";const n=e.apiKey??(typeof process<"u"&&Zs?.MCP_USE_API_KEY);if(!n)throw new Error("API key is required for remote execution. Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. You can get an API key from https://cloud.mcp-use.com");this.apiKey=n}pydanticToJsonSchema(e){return Zn(e)}parseStructuredResponse(e,n){let r;if(typeof e=="object"&&e!==null)if("result"in e){const s=e.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=e;else if(typeof e=="string")try{r=JSON.parse(e)}catch{r={content:e}}else r=e;try{return n.parse(r)}catch(s){y.warn(`Failed to parse structured output: ${s}`);const o=n._def?.shape();if(o&&"content"in o)return n.parse({content:String(r)});throw s}}async createChatSession(){const e={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},n={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${_y}`;y.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(e)});if(!s.ok){const a=await s.text(),l=s.status;throw l===404?new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`):new Error(`Failed to create chat session: ${l} - ${a}`)}const i=(await s.json()).id;return y.info(`✅ Chat session created: ${i}`),i}catch(s){throw s instanceof Error?new TypeError(`Failed to create chat session: ${s.message}`):new Error(`Failed to create chat session: ${String(s)}`)}}async run(e,n,r,s,o){const{query:i,maxSteps:a,externalHistory:l,outputSchema:c}=xc(e,n,r,s,o);l!==void 0&&y.warn("External history is not yet supported for remote execution");try{y.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const u=this.chatId,d={query:i,max_steps:a??10};c&&(d.output_schema=this.pydanticToJsonSchema(c),y.info("🔧 Using structured output with schema"));const h={"Content-Type":"application/json","x-api-key":this.apiKey},f=`${this.baseUrl}${vy.replace("{chat_id}",u)}`;y.info(`🚀 Executing agent in chat ${u}`);const m=await fetch(f,{method:"POST",headers:h,body:JSON.stringify(d),signal:AbortSignal.timeout(3e5)});if(!m.ok){const C=await m.text(),T=m.status;throw T===401?(y.error(`❌ Authentication failed: ${C}`),new Error("Authentication failed: Invalid or missing API key. Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.")):T===403?(y.error(`❌ Access forbidden: ${C}`),new Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. Check if the agent exists and you have the necessary permissions.`)):T===404?(y.error(`❌ Agent not found: ${C}`),new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`)):T===422?(y.error(`❌ Validation error: ${C}`),new Error(`Request validation failed: ${C}. Please check your query parameters and output schema format.`)):T===500?(y.error(`❌ Server error: ${C}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(y.error(`❌ Remote execution failed with status ${T}: ${C}`),new Error(`Remote agent execution failed: ${T} - ${C}`))}const p=await m.json();if(y.info(`🔧 Response: ${JSON.stringify(p)}`),y.info("✅ Remote execution completed successfully"),typeof p=="object"&&p!==null){if(p.status==="error"||p.error!==null){const C=p.error??String(p);throw y.error(`❌ Remote agent execution failed: ${C}`),new Error(`Remote agent execution failed: ${C}`)}if(String(p).includes("failed to initialize"))throw y.error(`❌ Agent initialization failed: ${p}`),new Error(`Agent initialization failed on remote server. This usually indicates:
343
343
  • Invalid agent configuration (LLM model, system prompt)
344
344
  • Missing or invalid MCP server configurations
345
345
  • Network connectivity issues with MCP servers
@@ -387,9 +387,9 @@ You can then use these server-specific tools in subsequent steps.
387
387
  Here are the tools *currently* available to you (this list includes server management tools and will
388
388
  change when you connect to a server):
389
389
  {tool_descriptions}
390
- `;function gr(t,e,n,r,s,o){if(typeof t=="object"&&t!==null){const i=t;return{query:i.prompt,maxSteps:i.maxSteps,manageConnector:i.manageConnector,externalHistory:i.externalHistory,outputSchema:i.schema,signal:i.signal}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s,signal:o}}R(gr,"normalizeRunOptions");var Zt,ky=(Zt=class{static getPackageVersion(){return ji()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Mc({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new xt,this.telemetry=Xn.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Qs({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],y.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.isSimplifiedMode)this.adapter=e.adapter??new xt(this.disallowedTools),this.telemetry=Xn.getInstance(),this.modelProvider="unknown",this.modelName="unknown";else{if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new xt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new xi(this.client,this.adapter)}else this.adapter=e.adapter??new xt(this.disallowedTools);if(this.telemetry=Xn.getInstance(),this.llm){const[r,s]=Bo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Qs({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:R(()=>this.getMetadata(),"metadataProvider"),tagsProvider:R(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:R(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:R(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:R(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(y.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(y.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){y.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await nn(async()=>{const{MCPClient:s}=await import("./client-Dqtz8Ili.js").then(o=>o.c);return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),y.info("✅ MCPClient created successfully")}if(this.llmString){y.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await $o(this.llmString,this.llmConfig),y.info("✅ LLM created successfully");const[r,s]=Bo(this.llm);this.modelProvider=r,this.modelName=s}catch(r){throw new Error(`Failed to create LLM from string '${this.llmString}': ${r?.message||r}`)}}if(this.useServerManager){if(!this.client)throw new Error("'client' must be available when 'useServerManager' is true.");this.serverManager=new xi(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),y.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),y.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=await this.adapter.createToolsFromConnectors(Object.values(this.sessions).map(a=>a.connector)),o=await this.adapter.createResourcesFromConnectors(Object.values(this.sessions).map(a=>a.connector)),i=await this.adapter.createPromptsFromConnectors(Object.values(this.sessions).map(a=>a.connector));this._tools=[...s,...o,...i],y.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{y.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),y.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}y.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Sy;this.systemMessage=Rc(e,n,Cy,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof oe))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(o=>o.name);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[kc({runLimit:this.maxSteps})],s=sc({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new oe(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof oe)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new xt(this.disallowedTools),this._initialized&&y.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},y.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],y.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){y.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(y.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){y.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else y.warn(`Unsupported metadata value type for key '${o}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){y.warn(`Failed to get config for server '${s}': ${o}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){y.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof P)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof se)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof j)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof P||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,o,i){const{query:a,maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:d,signal:h}=gr(e,n,r,s,o,i);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(a,l,c,u,d);const f=this.stream(a,l,c,u,d,h);return this._consumeAndReturn(f)}async*stream(e,n,r=!0,s,o,i){const{query:a,maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:d,signal:h}=gr(e,n,r,s,o,i);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(a,l,c,u,d);let f=!1;const m=Date.now();let p=!1,C=null,k=0;try{if(c&&!this._initialized?(await this.initialize(),f=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),f=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const b=this.serverManager.tools,E=new Set(b.map(x=>x.name)),S=new Set(this._tools.map(x=>x.name));(E.size!==S.size||[...E].some(x=>!S.has(x)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...E].join(", ")}`),this._tools=b,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const T=u??this.conversationHistory,_=[];for(const b of T)(this._isHumanMessageLike(b)||this._isAIMessageLike(b)||this._isToolMessageLike(b))&&_.push(b);const g=a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:a.replace(/\n/g," ");y.info(`💬 Received query: '${g}'`),y.info("🏁 Starting agent execution");const v=3;let M=0;const w=[..._,new se(a)];for(;M<=v;){const b={messages:w};let E=!1;const S=await this._agentExecutor.stream(b,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...h&&{signal:h}});for await(const x of S){if(h?.aborted)break;for(const[I,O]of Object.entries(x))if(y.debug(`📦 Node '${I}' output: ${JSON.stringify(O)}`),O&&typeof O=="object"&&"messages"in O){let F=O.messages;Array.isArray(F)||(F=[F]);for(const ce of F)w.includes(ce)||w.push(ce);for(const ce of F){if("tool_calls"in ce&&Array.isArray(ce.tool_calls)&&ce.tool_calls.length>0)for(const Ie of ce.tool_calls){const we=Ie.name||"unknown",ht=Ie.args||{};this.toolsUsedNames.push(we),k++;let Je=JSON.stringify(ht);Je.length>100&&(Je=`${Je.slice(0,97)}...`),y.info(`🔧 Tool call: ${we} with input: ${Je}`),yield{action:{tool:we,toolInput:ht,log:`Calling tool ${we}`},observation:""}}if(this._isToolMessageLike(ce)){const Ie=ce.content;let we=String(Ie);if(we.length>100&&(we=`${we.slice(0,97)}...`),we=we.replace(/\n/g," "),y.info(`📄 Tool result: ${we}`),this.useServerManager&&this.serverManager){const ht=this.serverManager.tools,Je=new Set(ht.map(fn=>fn.name)),Lo=new Set(this._tools.map(fn=>fn.name));if(Je.size!==Lo.size||[...Je].some(fn=>!Lo.has(fn))){y.info(`🔄 Tools changed during execution. New tools: ${[...Je].join(", ")}`),this._tools=ht,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),E=!0,M++,y.info(`🔃 Restarting execution with updated tools (restart ${M}/${v})`);break}}}this._isAIMessageLike(ce)&&!this._messageHasToolCalls(ce)&&(C=this._normalizeOutput(this._getMessageContent(ce)),y.info("✅ Agent finished with output"))}if(E)break}if(E)break}if(!E)break;if(M>v){y.warn(`⚠️ Max restarts (${v}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const b=w.slice(_.length);for(const E of b)this.addToHistory(E)}if(d&&C)try{y.info("🔧 Attempting structured output...");const b=await this._attemptStructuredOutput(C,this.llm,d);return this.memoryEnabled&&this.addToHistory(new P(`Structured result: ${JSON.stringify(b)}`)),y.info("✅ Structured output successful"),p=!0,b}catch(b){throw y.error(`❌ Structured output failed: ${b}`),new Error(`Failed to generate structured output: ${b instanceof Error?b.message:String(b)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-m)/1e3).toFixed(2)} seconds`),p=!0,C||"No output generated"}catch(T){throw y.error(`❌ Error running query: ${T}`),f&&c&&(y.info("🧹 Cleaning up resources after error"),await this.close()),T}finally{const T=Date.now()-m;let _=0;this.client?_=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(_=this.connectors.length);const g=this.memoryEnabled?this.conversationHistory.length:0,v=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:a,success:p,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:_,serverIdentifiers:this.connectors.map(M=>M.publicIdentifier),totalToolsAvailable:v.length,toolsAvailableNames:v.map(M=>M.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:c??!0,externalHistoryUsed:u!==void 0,stepsTaken:k,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:C||"",executionTimeMs:T,errorType:p?null:"execution_error",conversationHistoryLength:g}),c&&!this.client&&f&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(y.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(y.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new xt)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await nn(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-CalMK9h7.js");return{prettyStreamEvents:l}},__vite__mapDeps([3,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o,i){const a=gr(e,n,r,s,o,i);let{query:l}=a;const{maxSteps:c,manageConnector:u,externalHistory:d,outputSchema:h,signal:f}=a;let m=!1;const p=Date.now();let C=!1,k=0,T=0,_="";h&&(l=this._enhanceQueryWithSchema(l,h));try{u&&!this._initialized?(await this.initialize(),m=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),m=!0);const g=this._agentExecutor;if(!g)throw new Error("MCP agent failed to initialize");this.maxSteps=c??this.maxSteps;const v=typeof l=="string"&&l.length>50?`${l.slice(0,50).replace(/\n/g," ")}...`:typeof l=="string"?l.replace(/\n/g," "):String(l);y.info(`💬 Received query for streamEvents: '${v}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${v}`),this.addToHistory(new se({content:l})));const M=d??this.conversationHistory,w=[];for(const S of M)this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S)?w.push(S):y.info(`⚠️ Skipped message of type: ${S.constructor?.name||typeof S}`);const b=[...w,new se(l)];y.info("callbacks",this.callbacks);const E=g.streamEvents({messages:b},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...f&&{signal:f}});for await(const S of E){if(f?.aborted)break;if(k++,!(!S||typeof S!="object")){if(S.event==="on_chat_model_stream"&&S.data?.chunk?.content&&(T+=S.data.chunk.content.length),S.event==="on_chat_model_stream"&&S.data?.chunk){const x=S.data.chunk;if(x.content){_||(_="");const I=this._normalizeOutput(x.content);_+=I,y.debug(`📝 Accumulated response length: ${_.length}`)}}if(yield S,S.event==="on_chain_end"&&S.data?.output&&!_){const x=S.data.output;Array.isArray(x)&&x.length>0&&x[0]?.text?_=x[0].text:typeof x=="string"?_=x:x&&typeof x=="object"&&"output"in x&&(_=x.output)}}}if(h&&_){y.info("🔧 Attempting structured output conversion...");try{let S=!1,x=null,I=null;this._attemptStructuredOutput(_,this.llm,h).then(F=>(S=!0,x=F,F)).catch(F=>{throw S=!0,I=F,F});let O=0;for(;!S;)await new Promise(F=>setTimeout(F,2e3)),S||(O++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${O*2}s)`,elapsed:O*2}});if(I)throw I;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new P(`Structured result: ${JSON.stringify(x)}`)),y.info("✅ Structured output successful"))}catch(S){y.warn(`⚠️ Structured output failed: ${S}`),yield{event:"on_structured_output_error",data:{error:S instanceof Error?S.message:String(S)}}}}else this.memoryEnabled&&_&&this.addToHistory(new P(_));console.log(`
390
+ `;function gr(t,e,n,r,s,o){if(typeof t=="object"&&t!==null){const i=t;return{query:i.prompt,maxSteps:i.maxSteps,manageConnector:i.manageConnector,externalHistory:i.externalHistory,outputSchema:i.schema,signal:i.signal}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s,signal:o}}R(gr,"normalizeRunOptions");var Zt,Ty=(Zt=class{static getPackageVersion(){return ji()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];exposeResourcesAsTools=!0;exposePromptsAsTools=!0;useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Mc({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new xt,this.telemetry=Xn.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Qs({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],y.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.exposeResourcesAsTools=e.exposeResourcesAsTools??!0,this.exposePromptsAsTools=e.exposePromptsAsTools??!0,this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.isSimplifiedMode)this.adapter=e.adapter??new xt(this.disallowedTools),this.telemetry=Xn.getInstance(),this.modelProvider="unknown",this.modelName="unknown";else{if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new xt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new xi(this.client,this.adapter)}else this.adapter=e.adapter??new xt(this.disallowedTools);if(this.telemetry=Xn.getInstance(),this.llm){const[r,s]=Bo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Qs({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:R(()=>this.getMetadata(),"metadataProvider"),tagsProvider:R(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:R(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:R(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:R(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(y.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(y.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){y.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await nn(async()=>{const{MCPClient:s}=await import("./client-hyRgVCty.js").then(o=>o.c);return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),y.info("✅ MCPClient created successfully")}if(this.llmString){y.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await $o(this.llmString,this.llmConfig),y.info("✅ LLM created successfully");const[r,s]=Bo(this.llm);this.modelProvider=r,this.modelName=s}catch(r){throw new Error(`Failed to create LLM from string '${this.llmString}': ${r?.message||r}`)}}if(this.useServerManager){if(!this.client)throw new Error("'client' must be available when 'useServerManager' is true.");this.serverManager=new xi(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),y.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),y.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=Object.values(this.sessions).map(l=>l.connector),o=await this.adapter.createToolsFromConnectors(s),i=this.exposeResourcesAsTools?await this.adapter.createResourcesFromConnectors(s):[],a=this.exposePromptsAsTools?await this.adapter.createPromptsFromConnectors(s):[];this._tools=[...o,...i,...a],y.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${o.length} tools, ${i.length} resources, ${a.length} prompts`)}this._tools.push(...this.additionalTools)}else{y.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),y.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}y.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Sy;this.systemMessage=Rc(e,n,Cy,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof oe))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(o=>o.name);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Tc({runLimit:this.maxSteps})],s=sc({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new oe(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof oe)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new xt(this.disallowedTools),this._initialized&&y.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},y.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],y.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){y.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(y.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){y.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else y.warn(`Unsupported metadata value type for key '${o}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){y.warn(`Failed to get config for server '${s}': ${o}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){y.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof P)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof se)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof j)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof P||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,o,i){const{query:a,maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:d,signal:h}=gr(e,n,r,s,o,i);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(a,l,c,u,d);const f=this.stream(a,l,c,u,d,h);return this._consumeAndReturn(f)}async*stream(e,n,r=!0,s,o,i){const{query:a,maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:d,signal:h}=gr(e,n,r,s,o,i);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(a,l,c,u,d);let f=!1;const m=Date.now();let p=!1,C=null,T=0;try{if(c&&!this._initialized?(await this.initialize(),f=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),f=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const b=this.serverManager.tools,E=new Set(b.map(x=>x.name)),S=new Set(this._tools.map(x=>x.name));(E.size!==S.size||[...E].some(x=>!S.has(x)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...E].join(", ")}`),this._tools=b,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const k=u??this.conversationHistory,_=[];for(const b of k)(this._isHumanMessageLike(b)||this._isAIMessageLike(b)||this._isToolMessageLike(b))&&_.push(b);const g=a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:a.replace(/\n/g," ");y.info(`💬 Received query: '${g}'`),y.info("🏁 Starting agent execution");const v=3;let M=0;const w=[..._,new se(a)];for(;M<=v;){const b={messages:w};let E=!1;const S=await this._agentExecutor.stream(b,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...h&&{signal:h}});for await(const x of S){if(h?.aborted)break;for(const[I,O]of Object.entries(x))if(y.debug(`📦 Node '${I}' output: ${JSON.stringify(O)}`),O&&typeof O=="object"&&"messages"in O){let F=O.messages;Array.isArray(F)||(F=[F]);for(const ce of F)w.includes(ce)||w.push(ce);for(const ce of F){if("tool_calls"in ce&&Array.isArray(ce.tool_calls)&&ce.tool_calls.length>0)for(const Ie of ce.tool_calls){const we=Ie.name||"unknown",ht=Ie.args||{};this.toolsUsedNames.push(we),T++;let Je=JSON.stringify(ht);Je.length>100&&(Je=`${Je.slice(0,97)}...`),y.info(`🔧 Tool call: ${we} with input: ${Je}`),yield{action:{tool:we,toolInput:ht,log:`Calling tool ${we}`},observation:""}}if(this._isToolMessageLike(ce)){const Ie=ce.content;let we=String(Ie);if(we.length>100&&(we=`${we.slice(0,97)}...`),we=we.replace(/\n/g," "),y.info(`📄 Tool result: ${we}`),this.useServerManager&&this.serverManager){const ht=this.serverManager.tools,Je=new Set(ht.map(fn=>fn.name)),Lo=new Set(this._tools.map(fn=>fn.name));if(Je.size!==Lo.size||[...Je].some(fn=>!Lo.has(fn))){y.info(`🔄 Tools changed during execution. New tools: ${[...Je].join(", ")}`),this._tools=ht,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),E=!0,M++,y.info(`🔃 Restarting execution with updated tools (restart ${M}/${v})`);break}}}this._isAIMessageLike(ce)&&!this._messageHasToolCalls(ce)&&(C=this._normalizeOutput(this._getMessageContent(ce)),y.info("✅ Agent finished with output"))}if(E)break}if(E)break}if(!E)break;if(M>v){y.warn(`⚠️ Max restarts (${v}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const b=w.slice(_.length);for(const E of b)this.addToHistory(E)}if(d&&C)try{y.info("🔧 Attempting structured output...");const b=await this._attemptStructuredOutput(C,this.llm,d);return this.memoryEnabled&&this.addToHistory(new P(`Structured result: ${JSON.stringify(b)}`)),y.info("✅ Structured output successful"),p=!0,b}catch(b){throw y.error(`❌ Structured output failed: ${b}`),new Error(`Failed to generate structured output: ${b instanceof Error?b.message:String(b)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-m)/1e3).toFixed(2)} seconds`),p=!0,C||"No output generated"}catch(k){throw y.error(`❌ Error running query: ${k}`),f&&c&&(y.info("🧹 Cleaning up resources after error"),await this.close()),k}finally{const k=Date.now()-m;let _=0;this.client?_=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(_=this.connectors.length);const g=this.memoryEnabled?this.conversationHistory.length:0,v=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:a,success:p,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:_,serverIdentifiers:this.connectors.map(M=>M.publicIdentifier),totalToolsAvailable:v.length,toolsAvailableNames:v.map(M=>M.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:c??!0,externalHistoryUsed:u!==void 0,stepsTaken:T,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:C||"",executionTimeMs:k,errorType:p?null:"execution_error",conversationHistoryLength:g}),c&&!this.client&&f&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(y.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(y.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new xt)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await nn(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-CIPa27wl.js");return{prettyStreamEvents:l}},__vite__mapDeps([3,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o,i){const a=gr(e,n,r,s,o,i);let{query:l}=a;const{maxSteps:c,manageConnector:u,externalHistory:d,outputSchema:h,signal:f}=a;let m=!1;const p=Date.now();let C=!1,T=0,k=0,_="";h&&(l=this._enhanceQueryWithSchema(l,h));try{u&&!this._initialized?(await this.initialize(),m=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),m=!0);const g=this._agentExecutor;if(!g)throw new Error("MCP agent failed to initialize");this.maxSteps=c??this.maxSteps;const v=typeof l=="string"&&l.length>50?`${l.slice(0,50).replace(/\n/g," ")}...`:typeof l=="string"?l.replace(/\n/g," "):String(l);y.info(`💬 Received query for streamEvents: '${v}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${v}`),this.addToHistory(new se({content:l})));const M=d??this.conversationHistory,w=[];for(const S of M)this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S)?w.push(S):y.info(`⚠️ Skipped message of type: ${S.constructor?.name||typeof S}`);const b=[...w,new se(l)];y.info("callbacks",this.callbacks);const E=g.streamEvents({messages:b},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...f&&{signal:f}});for await(const S of E){if(f?.aborted)break;if(T++,!(!S||typeof S!="object")){if(S.event==="on_chat_model_stream"&&S.data?.chunk?.content&&(k+=S.data.chunk.content.length),S.event==="on_chat_model_stream"&&S.data?.chunk){const x=S.data.chunk;if(x.content){_||(_="");const I=this._normalizeOutput(x.content);_+=I,y.debug(`📝 Accumulated response length: ${_.length}`)}}if(yield S,S.event==="on_chain_end"&&S.data?.output&&!_){const x=S.data.output;Array.isArray(x)&&x.length>0&&x[0]?.text?_=x[0].text:typeof x=="string"?_=x:x&&typeof x=="object"&&"output"in x&&(_=x.output)}}}if(h&&_){y.info("🔧 Attempting structured output conversion...");try{let S=!1,x=null,I=null;this._attemptStructuredOutput(_,this.llm,h).then(F=>(S=!0,x=F,F)).catch(F=>{throw S=!0,I=F,F});let O=0;for(;!S;)await new Promise(F=>setTimeout(F,2e3)),S||(O++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${O*2}s)`,elapsed:O*2}});if(I)throw I;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new P(`Structured result: ${JSON.stringify(x)}`)),y.info("✅ Structured output successful"))}catch(S){y.warn(`⚠️ Structured output failed: ${S}`),yield{event:"on_structured_output_error",data:{error:S instanceof Error?S.message:String(S)}}}}else this.memoryEnabled&&_&&this.addToHistory(new P(_));console.log(`
391
391
 
392
- `),y.info(`🎉 StreamEvents complete - ${k} events emitted`),C=!0}catch(g){throw y.error(`❌ Error during streamEvents: ${g}`),m&&u&&(y.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),g}finally{const g=Date.now()-p;let v=0;this.client?v=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(v=this.connectors.length);const M=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:l,success:C,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:v,serverIdentifiers:this.connectors.map(w=>w.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(w=>w.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:u??!0,externalHistoryUsed:d!==void 0,response:`[STREAMED RESPONSE - ${T} chars]`,executionTimeMs:g,errorType:C?null:"streaming_error",conversationHistoryLength:M}),u&&!this.client&&m&&(y.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){y.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),y.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(y.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Zn(r),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")s=n.withStructuredOutput(r);else if(n)s=n;else throw new Error("LLM is required for structured output");const i=Zn(r),{$schema:a,additionalProperties:l,...c}=i;o=JSON.stringify(c,null,2),y.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),y.info("rawResult",e),u||(u=JSON.stringify(e));const d=3;let h="";for(let f=1;f<=d;f++){y.info(`🔄 Structured output attempt ${f}/${d}`);let m=`
392
+ `),y.info(`🎉 StreamEvents complete - ${T} events emitted`),C=!0}catch(g){throw y.error(`❌ Error during streamEvents: ${g}`),m&&u&&(y.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),g}finally{const g=Date.now()-p;let v=0;this.client?v=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(v=this.connectors.length);const M=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:l,success:C,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:v,serverIdentifiers:this.connectors.map(w=>w.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(w=>w.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:u??!0,externalHistoryUsed:d!==void 0,response:`[STREAMED RESPONSE - ${k} chars]`,executionTimeMs:g,errorType:C?null:"streaming_error",conversationHistoryLength:M}),u&&!this.client&&m&&(y.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){y.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),y.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(y.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Zn(r),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")s=n.withStructuredOutput(r);else if(n)s=n;else throw new Error("LLM is required for structured output");const i=Zn(r),{$schema:a,additionalProperties:l,...c}=i;o=JSON.stringify(c,null,2),y.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),y.info("rawResult",e),u||(u=JSON.stringify(e));const d=3;let h="";for(let f=1;f<=d;f++){y.info(`🔄 Structured output attempt ${f}/${d}`);let m=`
393
393
  Please format the following information according to the EXACT schema specified below.
394
394
  You must use the exact field names and types as shown in the schema.
395
395
 
@@ -411,7 +411,7 @@ Here are the tools *currently* available to you (this list includes server manag
411
411
  PREVIOUS ATTEMPT FAILED with error: ${h}
412
412
  Please fix the issues mentioned above and ensure the output matches the schema exactly.
413
413
  `);try{y.info(`🔄 Structured output attempt ${f} - using streaming approach`);const p=u.length>300?`${u.slice(0,300)}...`:u;y.info(`🔄 Content being formatted (${u.length} chars): ${p}`),y.info(`🔄 Full format prompt (${m.length} chars):
414
- ${m}`);const C=await s.stream(m);let k=null,T=0;for await(const g of C){if(T++,y.debug(`Chunk ${T}: ${JSON.stringify(g,null,2)}`),typeof g=="string")try{k=JSON.parse(g)}catch{y.warn(`🔄 Failed to parse string chunk as JSON: ${g}`)}else if(g&&typeof g=="object")k=g;else try{k=JSON.parse(String(g))}catch{y.warn(`🔄 Failed to parse chunk as JSON: ${g}`)}T%10===0&&y.debug(`🔄 Structured output streaming: ${T} chunks`)}if(y.info(`🔄 Structured result attempt ${f}: ${JSON.stringify(k,null,2)}`),!k)throw new Error("No structured result received from stream");const _=this._validateStructuredResult(k,r);return y.info(`✅ Structured output successful on attempt ${f}`),_}catch(p){if(h=p instanceof Error?p.message:String(p),y.warn(`⚠️ Structured output attempt ${f} failed: ${h}`),f===d)throw y.error(`❌ All ${d} structured output attempts failed`),new Error(`Failed to generate valid structured output after ${d} attempts. Last error: ${h}`);continue}}throw new Error("Unexpected error in structured output generation")}_validateStructuredResult(e,n){try{const r=n.parse(e),s=n;if(s._def&&s._def.shape)for(const[o,i]of Object.entries(s._def.shape)){const a=i,l=a.isOptional?.()??a._def?.typeName==="ZodOptional",c=a.isNullable?.()??a._def?.typeName==="ZodNullable";if(!l&&!c){const u=r[o];if(u==null||typeof u=="string"&&!u.trim()||Array.isArray(u)&&u.length===0)throw new Error(`Required field '${o}' is missing or empty`)}}return r}catch(r){throw y.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(e,n){try{const r=Zn(n),{$schema:s,additionalProperties:o,...i}=r,a=JSON.stringify(i,null,2);return`
414
+ ${m}`);const C=await s.stream(m);let T=null,k=0;for await(const g of C){if(k++,y.debug(`Chunk ${k}: ${JSON.stringify(g,null,2)}`),typeof g=="string")try{T=JSON.parse(g)}catch{y.warn(`🔄 Failed to parse string chunk as JSON: ${g}`)}else if(g&&typeof g=="object")T=g;else try{T=JSON.parse(String(g))}catch{y.warn(`🔄 Failed to parse chunk as JSON: ${g}`)}k%10===0&&y.debug(`🔄 Structured output streaming: ${k} chunks`)}if(y.info(`🔄 Structured result attempt ${f}: ${JSON.stringify(T,null,2)}`),!T)throw new Error("No structured result received from stream");const _=this._validateStructuredResult(T,r);return y.info(`✅ Structured output successful on attempt ${f}`),_}catch(p){if(h=p instanceof Error?p.message:String(p),y.warn(`⚠️ Structured output attempt ${f} failed: ${h}`),f===d)throw y.error(`❌ All ${d} structured output attempts failed`),new Error(`Failed to generate valid structured output after ${d} attempts. Last error: ${h}`);continue}}throw new Error("Unexpected error in structured output generation")}_validateStructuredResult(e,n){try{const r=n.parse(e),s=n;if(s._def&&s._def.shape)for(const[o,i]of Object.entries(s._def.shape)){const a=i,l=a.isOptional?.()??a._def?.typeName==="ZodOptional",c=a.isNullable?.()??a._def?.typeName==="ZodNullable";if(!l&&!c){const u=r[o];if(u==null||typeof u=="string"&&!u.trim()||Array.isArray(u)&&u.length===0)throw new Error(`Required field '${o}' is missing or empty`)}}return r}catch(r){throw y.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(e,n){try{const r=Zn(n),{$schema:s,additionalProperties:o,...i}=r,a=JSON.stringify(i,null,2);return`
415
415
  ${e}
416
416
 
417
417
  IMPORTANT: Your response must include sufficient information to populate the following structured output:
@@ -420,4 +420,4 @@ ${m}`);const C=await s.stream(m);let k=null,T=0;for await(const g of C){if(T++,y
420
420
 
421
421
  Make sure you gather ALL the required information during your task execution.
422
422
  If any required information is missing, continue working to find it.
423
- `}catch(r){return y.warn(`Could not extract schema details: ${r}`),e}}},R(Zt,"MCPAgent"),Zt),Mi={};function Q(t){if(typeof process<"u"&&Mi)return Mi[t]}R(Q,"getEnvVar");var Ty=Q("MCP_USE_LANGFUSE")?.toLowerCase()==="false",un={handler:null,client:null,initPromise:null};async function jo(t,e,n,r){try{const s=await nn(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){y.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:o}=s,u=class u extends o{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(h,f,m,p,C){super(h),this.agentId=f,this.metadata=m,this.metadataProvider=p,this.tagsProvider=C,this.verbose=h?.verbose??!1}async handleChainStart(h,f,m,p,C,k,T,_){y.debug("Langfuse: Chain start intercepted");const g=this.getCustomTags(),v=this.getMetadata(),M=[...C||[],...g],w={...k||{},...v};return this.verbose&&(y.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(M)}`),y.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(w)}`)),super.handleChainStart(h,f,m,p,M,w,T,_)}getCustomTags(){const h=[],f=this.getEnvironmentTag();if(f&&h.push(`env:${f}`),this.agentId&&h.push(`agent_id:${this.agentId}`),this.tagsProvider){const m=this.tagsProvider();m&&m.length>0&&h.push(...m)}return h}getMetadata(){const h={},f=this.getEnvironmentTag();if(f&&(h.env=f),this.agentId&&(h.agent_id=this.agentId),this.metadata&&Object.assign(h,this.metadata),this.metadataProvider){const m=this.metadataProvider();m&&Object.assign(h,m)}return h}getEnvironmentTag(){const h=Q("MCP_USE_AGENT_ENV");if(!h)return"unknown";const f=h.toLowerCase();return f==="local"||f==="development"?"local":f==="production"||f==="prod"?"production":f==="staging"||f==="stage"?"staging":f==="hosted"||f==="cloud"?"hosted":f.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...h){return y.debug("Langfuse: LLM start intercepted"),this.verbose&&y.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return y.debug("Langfuse: Tool start intercepted"),this.verbose&&y.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return y.debug("Langfuse: Retriever start intercepted"),this.verbose&&y.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return y.debug("Langfuse: Agent action intercepted"),this.verbose&&y.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return y.debug("Langfuse: Agent end intercepted"),this.verbose&&y.debug(`Langfuse: Agent end args: ${JSON.stringify(h)}`),super.handleAgentEnd(...h)}};R(u,"LoggingCallbackHandler");let i=u;const a=e||(n?n():{}),l=r?r():[],c={publicKey:Q("LANGFUSE_PUBLIC_KEY"),secretKey:Q("LANGFUSE_SECRET_KEY"),baseUrl:Q("LANGFUSE_HOST")||Q("LANGFUSE_BASEURL")||"https://cloud.langfuse.com",flushAt:Number.parseInt(Q("LANGFUSE_FLUSH_AT")||"15"),flushInterval:Number.parseInt(Q("LANGFUSE_FLUSH_INTERVAL")||"10000"),release:Q("LANGFUSE_RELEASE"),requestTimeout:Number.parseInt(Q("LANGFUSE_REQUEST_TIMEOUT")||"10000"),enabled:Q("LANGFUSE_ENABLED")!=="false",traceName:a.trace_name||Q("LANGFUSE_TRACE_NAME")||"mcp-use-agent",sessionId:a.session_id||void 0,userId:a.user_id||void 0,tags:l.length>0?l:void 0,metadata:a||void 0};y.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),un.handler=new i(c,t,e,n,r),y.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await nn(()=>import("langfuse"),[]).catch(()=>null);if(d){const{Langfuse:h}=d;un.client=new h({publicKey:Q("LANGFUSE_PUBLIC_KEY"),secretKey:Q("LANGFUSE_SECRET_KEY"),baseUrl:Q("LANGFUSE_HOST")||"https://cloud.langfuse.com"}),y.debug("Langfuse client initialized")}}catch(d){y.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){y.debug(`Langfuse initialization error: ${s}`)}}R(jo,"initializeLangfuse");Ty?y.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Q("LANGFUSE_PUBLIC_KEY")||!Q("LANGFUSE_SECRET_KEY")?y.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):un.initPromise=jo();var Ey=R(()=>un.handler,"langfuseHandler"),xy=R(()=>un.client,"langfuseClient"),My=R(()=>un.initPromise,"langfuseInitPromise");const jy=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:Wi,BaseConnector:Lu,BrowserOAuthClientProvider:Du,BrowserTelemetry:zo,HttpConnector:Fu,Logger:Uu,MCPAgent:ky,MCPClient:Vu,MCPSession:Bu,ObservabilityManager:Qs,RemoteAgent:Mc,Tel:zo,Telemetry:Xn,VERSION:zu,createLLMFromString:$o,createReadableStreamFromGenerator:zi,getPackageVersion:ji,getSupportedProviders:Pc,isValidLLMString:Ic,logger:y,onMcpAuthorization:Hu,parseLLMString:Hr,setBrowserTelemetrySource:Ho,setTelemetrySource:Ho,streamEventsToAISDK:Bi,streamEventsToAISDKWithTools:Hi},Symbol.toStringTag,{value:"Module"})),Ai=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:jo,langfuseClient:xy,langfuseHandler:Ey,langfuseInitPromise:My},Symbol.toStringTag,{value:"Module"}));export{kh as J,jy as b};
423
+ `}catch(r){return y.warn(`Could not extract schema details: ${r}`),e}}},R(Zt,"MCPAgent"),Zt),Mi={};function Q(t){if(typeof process<"u"&&Mi)return Mi[t]}R(Q,"getEnvVar");var ky=Q("MCP_USE_LANGFUSE")?.toLowerCase()==="false",un={handler:null,client:null,initPromise:null};async function jo(t,e,n,r){try{const s=await nn(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){y.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:o}=s,u=class u extends o{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(h,f,m,p,C){super(h),this.agentId=f,this.metadata=m,this.metadataProvider=p,this.tagsProvider=C,this.verbose=h?.verbose??!1}async handleChainStart(h,f,m,p,C,T,k,_){y.debug("Langfuse: Chain start intercepted");const g=this.getCustomTags(),v=this.getMetadata(),M=[...C||[],...g],w={...T||{},...v};return this.verbose&&(y.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(M)}`),y.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(w)}`)),super.handleChainStart(h,f,m,p,M,w,k,_)}getCustomTags(){const h=[],f=this.getEnvironmentTag();if(f&&h.push(`env:${f}`),this.agentId&&h.push(`agent_id:${this.agentId}`),this.tagsProvider){const m=this.tagsProvider();m&&m.length>0&&h.push(...m)}return h}getMetadata(){const h={},f=this.getEnvironmentTag();if(f&&(h.env=f),this.agentId&&(h.agent_id=this.agentId),this.metadata&&Object.assign(h,this.metadata),this.metadataProvider){const m=this.metadataProvider();m&&Object.assign(h,m)}return h}getEnvironmentTag(){const h=Q("MCP_USE_AGENT_ENV");if(!h)return"unknown";const f=h.toLowerCase();return f==="local"||f==="development"?"local":f==="production"||f==="prod"?"production":f==="staging"||f==="stage"?"staging":f==="hosted"||f==="cloud"?"hosted":f.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...h){return y.debug("Langfuse: LLM start intercepted"),this.verbose&&y.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return y.debug("Langfuse: Tool start intercepted"),this.verbose&&y.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return y.debug("Langfuse: Retriever start intercepted"),this.verbose&&y.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return y.debug("Langfuse: Agent action intercepted"),this.verbose&&y.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return y.debug("Langfuse: Agent end intercepted"),this.verbose&&y.debug(`Langfuse: Agent end args: ${JSON.stringify(h)}`),super.handleAgentEnd(...h)}};R(u,"LoggingCallbackHandler");let i=u;const a=e||(n?n():{}),l=r?r():[],c={publicKey:Q("LANGFUSE_PUBLIC_KEY"),secretKey:Q("LANGFUSE_SECRET_KEY"),baseUrl:Q("LANGFUSE_HOST")||Q("LANGFUSE_BASEURL")||"https://cloud.langfuse.com",flushAt:Number.parseInt(Q("LANGFUSE_FLUSH_AT")||"15"),flushInterval:Number.parseInt(Q("LANGFUSE_FLUSH_INTERVAL")||"10000"),release:Q("LANGFUSE_RELEASE"),requestTimeout:Number.parseInt(Q("LANGFUSE_REQUEST_TIMEOUT")||"10000"),enabled:Q("LANGFUSE_ENABLED")!=="false",traceName:a.trace_name||Q("LANGFUSE_TRACE_NAME")||"mcp-use-agent",sessionId:a.session_id||void 0,userId:a.user_id||void 0,tags:l.length>0?l:void 0,metadata:a||void 0};y.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),un.handler=new i(c,t,e,n,r),y.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await nn(()=>import("langfuse"),[]).catch(()=>null);if(d){const{Langfuse:h}=d;un.client=new h({publicKey:Q("LANGFUSE_PUBLIC_KEY"),secretKey:Q("LANGFUSE_SECRET_KEY"),baseUrl:Q("LANGFUSE_HOST")||"https://cloud.langfuse.com"}),y.debug("Langfuse client initialized")}}catch(d){y.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){y.debug(`Langfuse initialization error: ${s}`)}}R(jo,"initializeLangfuse");ky?y.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Q("LANGFUSE_PUBLIC_KEY")||!Q("LANGFUSE_SECRET_KEY")?y.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):un.initPromise=jo();var Ey=R(()=>un.handler,"langfuseHandler"),xy=R(()=>un.client,"langfuseClient"),My=R(()=>un.initPromise,"langfuseInitPromise");const jy=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:Wi,BaseConnector:Lu,BrowserOAuthClientProvider:Du,BrowserTelemetry:zo,HttpConnector:Fu,Logger:Uu,MCPAgent:Ty,MCPClient:Vu,MCPSession:Bu,ObservabilityManager:Qs,RemoteAgent:Mc,Tel:zo,Telemetry:Xn,VERSION:zu,createLLMFromString:$o,createReadableStreamFromGenerator:zi,getPackageVersion:ji,getSupportedProviders:Pc,isValidLLMString:Ic,logger:y,onMcpAuthorization:Hu,parseLLMString:Hr,setBrowserTelemetrySource:Ho,setTelemetrySource:Ho,streamEventsToAISDK:Bi,streamEventsToAISDKWithTools:Hi},Symbol.toStringTag,{value:"Module"})),Ai=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:jo,langfuseClient:xy,langfuseHandler:Ey,langfuseInitPromise:My},Symbol.toStringTag,{value:"Module"}));export{Th as J,jy as b};