@arcgis/portal-components 6.0.0-next.37 → 6.0.0-next.39

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 (218) hide show
  1. package/dist/cdn/2574FNAZ.js +2 -0
  2. package/dist/cdn/3DOZPC3W.js +2 -0
  3. package/dist/cdn/{R5LNWMD4.js → 3HZI6MKD.js} +1 -1
  4. package/dist/cdn/{ASLKTYLX.js → 3KGSWW6B.js} +1 -1
  5. package/dist/cdn/{VWV2LCNA.js → 3OL7A2UC.js} +1 -1
  6. package/dist/cdn/3Q7UJKKN.js +2 -0
  7. package/dist/cdn/43A74S72.js +2 -0
  8. package/dist/cdn/46HNNQAD.js +2 -0
  9. package/dist/cdn/46MYBPSS.js +2 -0
  10. package/dist/cdn/{H25PBZPU.js → 47DKAGRV.js} +1 -1
  11. package/dist/cdn/{5VFGR7LA.js → 4CBRO7JP.js} +1 -1
  12. package/dist/cdn/{NLFBHNSX.js → 5M25PCH2.js} +1 -1
  13. package/dist/cdn/5MLBK66O.js +2 -0
  14. package/dist/cdn/5RBH3LGK.js +2 -0
  15. package/dist/cdn/5ZHNRQOW.js +2 -0
  16. package/dist/cdn/62TL6V4N.js +2 -0
  17. package/dist/cdn/{IWQ5I2DD.js → 66VV7NHO.js} +1 -1
  18. package/dist/cdn/{US37IXWO.js → 6AHPTR2E.js} +1 -1
  19. package/dist/cdn/{ZQ6SGKLT.js → 6APPSZ7E.js} +1 -1
  20. package/dist/cdn/{XH6RD5BO.js → 6CUXEL27.js} +1 -1
  21. package/dist/cdn/{6HNKQNS5.js → 6QI7DAS2.js} +1 -1
  22. package/dist/cdn/{324F5URQ.js → 6ZJNZZPC.js} +1 -1
  23. package/dist/cdn/{5CEFJTG4.js → 75CT6IMW.js} +1 -1
  24. package/dist/cdn/{CJ4S56BE.js → 7J22VLBO.js} +1 -1
  25. package/dist/cdn/7VPB6Q55.js +63 -0
  26. package/dist/cdn/7ZU43BL6.js +2 -0
  27. package/dist/cdn/A5QLPZ57.js +2 -0
  28. package/dist/cdn/AZTAWZI5.js +2 -0
  29. package/dist/cdn/{WIUFH5SJ.js → BNWJUQDF.js} +1 -1
  30. package/dist/cdn/{UBPCKCW2.js → BUYOYUA2.js} +1 -1
  31. package/dist/cdn/BX7Q3V2Y.js +43 -0
  32. package/dist/cdn/BXPNB7VJ.js +2 -0
  33. package/dist/cdn/{4Y73LE7P.js → BZEKNJUA.js} +1 -1
  34. package/dist/cdn/{WCZJXBW3.js → C6RUWLEJ.js} +1 -1
  35. package/dist/cdn/C7SNE6YG.js +2 -0
  36. package/dist/cdn/DENQY4OE.js +2 -0
  37. package/dist/cdn/DT4HGMLS.js +2 -0
  38. package/dist/cdn/{NYBLHT3F.js → DTGPLVZF.js} +1 -1
  39. package/dist/cdn/DU2R3VC4.js +2 -0
  40. package/dist/cdn/{RJRTGF33.js → E5HCHRAI.js} +1 -1
  41. package/dist/cdn/{IX4WEZZ2.js → EBL7YSRM.js} +1 -1
  42. package/dist/cdn/EDGE3T36.js +2 -0
  43. package/dist/cdn/{HBO7XTIL.js → EFMYI4L2.js} +1 -1
  44. package/dist/cdn/{XOM3GLYF.js → FFL2L4X5.js} +1 -1
  45. package/dist/cdn/{PST62OKJ.js → FIAEPK5L.js} +1 -1
  46. package/dist/cdn/{L25GEXL6.js → FTKSVLDI.js} +1 -1
  47. package/dist/cdn/{QMIVFHQE.js → G272JPUS.js} +1 -1
  48. package/dist/cdn/{D52TYBRX.js → GFUKRB6D.js} +1 -1
  49. package/dist/cdn/{ZGSAH7Z7.js → GG6U75ZA.js} +1 -1
  50. package/dist/cdn/{O4YFPGD5.js → GZ4ONSFV.js} +1 -1
  51. package/dist/cdn/{YP7T6NKR.js → HOIZXTOD.js} +1 -1
  52. package/dist/cdn/{DV57AOBF.js → IAMPUXPT.js} +1 -1
  53. package/dist/cdn/{AUM2QTBQ.js → IAWL475A.js} +1 -1
  54. package/dist/cdn/IGLODZPX.js +2 -0
  55. package/dist/cdn/{KTWSNYYZ.js → IOF72CDU.js} +1 -1
  56. package/dist/cdn/ITRJGXFV.js +93 -0
  57. package/dist/cdn/{EDQSL2P3.js → ITWLFQI4.js} +1 -1
  58. package/dist/cdn/{B343BOVA.js → IYICIRGI.js} +1 -1
  59. package/dist/cdn/{OVAOMUO3.js → JFGXTJY4.js} +1 -1
  60. package/dist/cdn/{5E4EL6TF.js → JIU6MBGB.js} +1 -1
  61. package/dist/cdn/{5Y32T5IJ.js → JTA223NH.js} +1 -1
  62. package/dist/cdn/KA2MXQTR.js +2 -0
  63. package/dist/cdn/KAK6CNI7.js +2 -0
  64. package/dist/cdn/{5S4JV6IY.js → KPZGBBDG.js} +1 -1
  65. package/dist/cdn/{M664QA6J.js → KRO5XRZ7.js} +1 -1
  66. package/dist/cdn/KWL2D56D.js +3 -0
  67. package/dist/cdn/{BRWHEYLW.js → KXVXQYIB.js} +1 -1
  68. package/dist/cdn/L3YOPSRB.js +135 -0
  69. package/dist/cdn/{QF626JXP.js → LEESUFWE.js} +1 -1
  70. package/dist/cdn/{CMNTOT5D.js → LGKI24ZT.js} +1 -1
  71. package/dist/cdn/LTD5KLLE.js +2 -0
  72. package/dist/cdn/{VFECPSKA.js → MB32XRI5.js} +1 -1
  73. package/dist/cdn/{3T3QBPC3.js → MSL36HAR.js} +1 -1
  74. package/dist/cdn/{ARAHDT2O.js → N3WRMPM6.js} +1 -1
  75. package/dist/cdn/N47MW5HI.js +9 -0
  76. package/dist/cdn/{G7DJPREL.js → N7XYFVOI.js} +1 -1
  77. package/dist/cdn/{WZFGZEQI.js → NU4K2AV3.js} +1 -1
  78. package/dist/cdn/{ESKKH4DE.js → ONRTCGLU.js} +1 -1
  79. package/dist/cdn/{WSQLSDQY.js → OPI4P6VO.js} +1 -1
  80. package/dist/cdn/{YYKKXL62.js → OPMM7QH5.js} +1 -1
  81. package/dist/cdn/{PRBP4AP6.js → OXF2WDSW.js} +1 -1
  82. package/dist/cdn/P3FFM322.js +2 -0
  83. package/dist/cdn/QAXFE5DD.js +2 -0
  84. package/dist/cdn/{6EMK2BU6.js → QKRLO5CJ.js} +1 -1
  85. package/dist/cdn/{FVHP6PFG.js → R26RBXQW.js} +1 -1
  86. package/dist/cdn/R6KJVAX3.js +99 -0
  87. package/dist/cdn/RA2NMLMP.js +2 -0
  88. package/dist/cdn/{365ICWHN.js → RJXIU4GH.js} +1 -1
  89. package/dist/cdn/{6FFYU4NI.js → RKHNP3KL.js} +1 -1
  90. package/dist/cdn/RR56BOTV.js +2 -0
  91. package/dist/cdn/RTZ2TKM5.js +2 -0
  92. package/dist/cdn/RX64JXHI.js +170 -0
  93. package/dist/cdn/{26KZUWNM.js → RXMM6CFK.js} +1 -1
  94. package/dist/cdn/{JA3GGSJJ.js → S4N5QMSN.js} +1 -1
  95. package/dist/cdn/{3CXU5CCM.js → SCLYGIHM.js} +1 -1
  96. package/dist/cdn/{PJZZIITX.js → SLK7PV62.js} +1 -1
  97. package/dist/cdn/{SUA7ZZUH.js → SUN4MBT3.js} +1 -1
  98. package/dist/cdn/SYXCSFIA.js +2 -0
  99. package/dist/cdn/{3QWNGHAK.js → TBSNDRRE.js} +1 -1
  100. package/dist/cdn/TP7V25GT.js +2 -0
  101. package/dist/cdn/{FGDSHTJ5.js → UBMZBXT7.js} +1 -1
  102. package/dist/cdn/UIK6LPA7.js +2 -0
  103. package/dist/cdn/{7DAB2CEU.js → VQRMXBPQ.js} +1 -1
  104. package/dist/cdn/{AM3UTQWH.js → VWOBCSD6.js} +1 -1
  105. package/dist/cdn/{C3F24ZOM.js → W3JJBZYX.js} +1 -1
  106. package/dist/cdn/W6WVMRGQ.js +2 -0
  107. package/dist/cdn/{TO666HVV.js → WNXDXB3M.js} +1 -1
  108. package/dist/cdn/{XEVOU7SJ.js → WOSWA2VI.js} +1 -1
  109. package/dist/cdn/{DMS3R2W5.js → WTKLB3R6.js} +1 -1
  110. package/dist/cdn/{LR33CLTB.js → X7W4VJO7.js} +1 -1
  111. package/dist/cdn/{CIRCDM5E.js → XCOP6QHA.js} +1 -1
  112. package/dist/cdn/{C4GK263H.js → XVV75AX3.js} +1 -1
  113. package/dist/cdn/XYHIVGUK.js +2 -0
  114. package/dist/cdn/{2GZVUHL5.js → Y4JOEFBJ.js} +1 -1
  115. package/dist/cdn/{CNEJPW3I.js → Y7ZCEONL.js} +1 -1
  116. package/dist/cdn/YELHAJB3.js +2 -0
  117. package/dist/cdn/YH2OFXPU.js +2 -0
  118. package/dist/cdn/{HVQ7FKJ5.js → YYVLFAFT.js} +1 -1
  119. package/dist/cdn/{BX2LXI3N.js → ZDH4KVAV.js} +1 -1
  120. package/dist/cdn/{SO3IBFEU.js → ZECUXVTO.js} +1 -1
  121. package/dist/cdn/ZG7OW456.js +2 -0
  122. package/dist/cdn/{7BFTXD5J.js → ZLNBCJE4.js} +1 -1
  123. package/dist/cdn/{GC4BV7IZ.js → ZNNEU5QW.js} +1 -1
  124. package/dist/cdn/assets/portal-item-status-card/t9n/messages.en.json +1 -0
  125. package/dist/cdn/assets/portal-review-layer-sharing/t9n/messages.en.json +1 -0
  126. package/dist/cdn/index.js +1 -1
  127. package/dist/cdn/main.css +1 -1
  128. package/dist/chunks/constants.js +7 -0
  129. package/dist/chunks/contextUsage.js +208 -0
  130. package/dist/chunks/createPortalTool.js +8 -8
  131. package/dist/chunks/fieldAddDelete.js +1 -1
  132. package/dist/chunks/groups2.js +1 -1
  133. package/dist/chunks/help.js +22 -0
  134. package/dist/chunks/item.js +29 -25
  135. package/dist/chunks/item2.js +66 -30
  136. package/dist/chunks/itemThumbnail.js +1 -1
  137. package/dist/chunks/items.js +11 -11
  138. package/dist/chunks/layers.js +1 -1
  139. package/dist/chunks/portal-item-preview-sublayer.js +1 -1
  140. package/dist/chunks/portal-item-status-card.js +81 -0
  141. package/dist/chunks/portal.js +2 -2
  142. package/dist/chunks/portal2.js +1 -1
  143. package/dist/chunks/previewSessionController.js +33 -0
  144. package/dist/chunks/request.js +9 -9
  145. package/dist/chunks/services.js +1 -1
  146. package/dist/chunks/user.js +2 -2
  147. package/dist/chunks/utils2.js +4 -4
  148. package/dist/components/arcgis-portal-ai-assistant/customElement.js +241 -219
  149. package/dist/components/arcgis-portal-ai-assistant/index.js +1 -0
  150. package/dist/components/arcgis-portal-ai-assistant-diagnostics/contextUsage.d.ts +46 -0
  151. package/dist/components/arcgis-portal-ai-assistant-diagnostics/customElement.d.ts +26 -0
  152. package/dist/components/arcgis-portal-ai-assistant-diagnostics/customElement.js +46 -0
  153. package/dist/components/arcgis-portal-ai-assistant-diagnostics/index.d.ts +1 -0
  154. package/dist/components/arcgis-portal-ai-assistant-diagnostics/index.js +10 -0
  155. package/dist/components/arcgis-portal-delete-items/customElement.js +95 -110
  156. package/dist/components/arcgis-portal-entity-picker/customElement.js +1 -1
  157. package/dist/components/arcgis-portal-field-delete/customElement.js +1 -1
  158. package/dist/components/arcgis-portal-group-browser/customElement.js +62 -90
  159. package/dist/components/arcgis-portal-group-thumbnail/customElement.js +1 -1
  160. package/dist/components/arcgis-portal-item-share-summary/customElement.js +1 -1
  161. package/dist/components/arcgis-portal-item-status-card/customElement.d.ts +82 -0
  162. package/dist/components/arcgis-portal-item-status-card/customElement.js +12 -0
  163. package/dist/components/arcgis-portal-item-status-card/index.d.ts +1 -0
  164. package/dist/components/arcgis-portal-item-status-card/index.js +4 -0
  165. package/dist/components/arcgis-portal-navigation/customElement.js +1 -1
  166. package/dist/components/arcgis-portal-navigation/index.js +4 -4
  167. package/dist/components/arcgis-portal-review-layer-sharing/customElement.d.ts +139 -0
  168. package/dist/components/arcgis-portal-review-layer-sharing/customElement.js +593 -0
  169. package/dist/components/arcgis-portal-review-layer-sharing/index.d.ts +1 -0
  170. package/dist/components/arcgis-portal-review-layer-sharing/index.js +10 -0
  171. package/dist/components/arcgis-portal-review-layer-sharing/types.d.ts +27 -0
  172. package/dist/components/arcgis-portal-user-popup/customElement.js +1 -1
  173. package/dist/docs/api.json +1 -1
  174. package/dist/docs/docs.json +1 -1
  175. package/dist/docs/vscode.html-custom-data.json +1 -1
  176. package/dist/docs/web-types.json +1 -1
  177. package/dist/index.d.ts +24 -0
  178. package/dist/index.js +1 -1
  179. package/dist/loader.js +3 -0
  180. package/dist/types/item.d.ts +2 -0
  181. package/dist/types/lumina.d.ts +18 -0
  182. package/dist/types/preact.d.ts +21 -0
  183. package/dist/types/react.d.ts +24 -0
  184. package/dist/types/stencil.d.ts +18 -0
  185. package/package.json +10 -10
  186. package/dist/cdn/234TH32X.js +0 -106
  187. package/dist/cdn/25K5D5HL.js +0 -2
  188. package/dist/cdn/4KTRAA2J.js +0 -2
  189. package/dist/cdn/4X4EYM3Q.js +0 -2
  190. package/dist/cdn/4YJGTINX.js +0 -2
  191. package/dist/cdn/A3OUZJ44.js +0 -2
  192. package/dist/cdn/ASID6YW7.js +0 -135
  193. package/dist/cdn/AYESDOK5.js +0 -2
  194. package/dist/cdn/BOEGDK4D.js +0 -2
  195. package/dist/cdn/CBFFZMX4.js +0 -2
  196. package/dist/cdn/FACH2JTF.js +0 -2
  197. package/dist/cdn/FGRMURKX.js +0 -2
  198. package/dist/cdn/GBG25IJ2.js +0 -2
  199. package/dist/cdn/H6MGSC3Y.js +0 -2
  200. package/dist/cdn/IKRGN33H.js +0 -93
  201. package/dist/cdn/K3GAZFRI.js +0 -63
  202. package/dist/cdn/LBW47BJG.js +0 -2
  203. package/dist/cdn/LRL2RJID.js +0 -2
  204. package/dist/cdn/MHQ5BATZ.js +0 -2
  205. package/dist/cdn/NJB24AIV.js +0 -2
  206. package/dist/cdn/NQ2IAQKL.js +0 -41
  207. package/dist/cdn/OEG4XCKY.js +0 -2
  208. package/dist/cdn/OHAQPQAP.js +0 -2
  209. package/dist/cdn/OYTK2VF2.js +0 -2
  210. package/dist/cdn/QPBWKASC.js +0 -2
  211. package/dist/cdn/RJ3SU3EV.js +0 -2
  212. package/dist/cdn/U2HTYOBB.js +0 -150
  213. package/dist/cdn/VLD3MVSG.js +0 -2
  214. package/dist/cdn/WMKG3CBK.js +0 -2
  215. package/dist/cdn/X4R2NVDQ.js +0 -2
  216. package/dist/cdn/X7C4PAJY.js +0 -2
  217. package/dist/cdn/YGZICQBT.js +0 -2
  218. package/dist/cdn/YNGFN7AY.js +0 -2
@@ -0,0 +1,135 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
+ import{$ as qi,A as Qc,B as Zc,E as el,F as tl,G as zi,H as rl,I as nl,J as sl,L as il,P as ol,Q as al,U as cl,V as ps,W as ll,Y as ul,Z as Cr,_ as hl,a as ic,aa as pl,c as Tc,ca as fl,d as on,ea as dl,f as Ic,fa as ml,g as Ac,h as ls,ha as gl,i as Oc,ia as _l,j as Dc,k as Hi,ka as yl,l as G,m as us,n as Zt,o as hs,p as ot,q as Vc,r as Lc,s as Fc,t as Uc,u as Bc,v as Hc,w as Wc,x as Gc,y as Xc,z as Ki}from"./R6KJVAX3.js";import{A as yc,B as _r,Ba as it,Fa as wr,Ga as vr,L as Vi,La as Be,Ta as Sc,Ua as kc,Va as Ec,Wa as Cc,Xa as br,Y as ee,Ya as Fi,Za as ie,_a as xc,a as nc,ab as $e,b as mr,bb as cs,c as rn,ca as nn,cb as He,d as sc,ea as yt,f as Di,fa as Li,g as oc,h as ac,i as cc,ia as wc,j as lc,k as uc,ka as wt,l as hc,m as Ue,n as pc,na as vc,p as fc,pa as Z,q as dc,sa as yr,t as st,ta as sn,v as mc,x as gc,xa as bc,y as gr,z as _c}from"./RX64JXHI.js";import{E as Bi,F as $c,K as jc,L as We,b as Pc,d as Nc,k as Mt,l as Ui,t as ke,u as an,v as Rc,w as Sr,z as Mc}from"./N47MW5HI.js";import{a as T}from"./DU2R3VC4.js";import{b as kr,c as je,d as Wi,e as er,f as Er,g as Kc,h as zc,i as Gi,j as qc,k as vt,l as Jc,m as Yc,n as $t}from"./QAXFE5DD.js";function wl(e,t){if(e!=null){if(typeof e!="number"||Number.isNaN(e)||e<=0)throw new Error(`${t} must be greater than 0`);return e}}function jt(e){if(e==null)return;let t=typeof e=="number"?{runTimeout:e}:e,r=t.refreshOn??"auto";if(r!=="auto"&&r!=="heartbeat")throw new Error('refreshOn must be "auto" or "heartbeat"');let n=wl(t.runTimeout,"runTimeout"),s=wl(t.idleTimeout,"idleTimeout");if(!(n===void 0&&s===void 0))return{runTimeout:n,idleTimeout:s,refreshOn:r}}var z="__start__",Y="__end__",Ge="__input__";var Dt="__error__",ln="__error_source_node__",fs="__pregel_ns_writes";function vl(){let e=typeof process<"u"?process.env?.LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT:void 0;if(e!==void 0&&e!==""){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}return 5e3}var ge="__pregel_send",ct="__pregel_call",ve="__pregel_read",lt="__pregel_checkpointer",rr="__pregel_resuming",xr="__pregel_task_id",un="__pregel_stream",uf="__pregel_resume_value",nr="__pregel_resume_map";var pe="__pregel_scratchpad",Vt="__pregel_previous",hf="__pregel_durability",Lt="checkpoint_id",Pe="checkpoint_ns",bl="__pregel_node_finished",hn="__pregel_node_error",_e="checkpoint_map",ds="__pregel_replay_state",Sl="__pregel_abort_signals",B="__interrupt__",ye="__resume__",pn="__no_writes__";function fn(e){return e!=="__error__"&&e!=="__error_source_node__"&&e!=="__interrupt__"&&e!=="__resume__"}var dn="__snapshot_bumps__",Ft="__return__",Ut="__previous__",te="langsmith:hidden";var Yi="__self__",ut="__pregel_tasks",Ce="__pregel_push",ms="__pregel_pull",fe="00000000-0000-0000-0000-000000000000",kl="00000000-0000-0000-0000-000000000001",El=[te,Ge,B,ye,Dt,ln,pn,dn,ge,ve,lt,hf,un,rr,xr,ct,uf,pe,Vt,_e,Pe,Lt,ds],Ji=Symbol.for("langgraph.command"),Cl=class{[Ji];constructor(e){this[Ji]=e}};function gs(e){let t=e;return t!=null&&typeof t.node=="string"&&t.args!==void 0}var tr=class{lg_name="Send";node;args;timeout;constructor(e,t,r){this.node=e,this.args=cn(t),this.timeout=jt(r?.timeout)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args,timeout:this.timeout}}};function oe(e){return e instanceof tr}var at="__overwrite__",Xi=class{lg_name="Overwrite";[at];constructor(e){this[at]=e}get value(){return this[at]}toJSON(){return{[at]:this[at]}}static isInstance(e){return!e||typeof e!="object"?!1:"__overwrite__"in e||"lg_name"in e&&e.lg_name==="Overwrite"}};function xe(e){if(typeof e=="object"&&e!==null){if("__overwrite__"in e)return[!0,e[at]];let t=e;if(t.type==="__overwrite__"&&"value"in t)return[!0,t.value]}return[!1,void 0]}function bt(e){return xe(e)[0]}function sr(e){return!e||typeof e!="object"||!("__interrupt__"in e)?!1:Array.isArray(e[B])}var Ee=class extends Cl{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(e){super(e),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?cn(e.goto):[cn(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let e;return typeof this.goto=="string"?e=this.goto:oe(this.goto)?e=this.goto.toJSON():e=this.goto?.map(t=>typeof t=="string"?t:t.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}};function ae(e){return typeof e!="object"||e==null?!1:!xl(e)&&"lg_name"in e&&e.lg_name==="Command"}function xl(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function cn(e,t=new Map){if(e!=null&&typeof e=="object"){if(t.has(e))return t.get(e);let r;if(Array.isArray(e))r=[],t.set(e,r),e.forEach((n,s)=>{r[s]=cn(n,t)});else if(e instanceof Ee||e instanceof tr||!xl(e))r=e,t.set(e,r);else if("lg_name"in e&&e.lg_name==="Command")r=new Ee(e),t.set(e,r);else if(gs(e))r=new tr(e.node,e.args,e.timeout!==void 0?{timeout:e.timeout}:void 0),t.set(e,r);else if("lc_serializable"in e&&e.lc_serializable)r=e,t.set(e,r);else{r={},t.set(e,r);for(let[n,s]of Object.entries(e))r[n]=cn(s,t)}return r}return e}var Ne=class extends Error{lc_error_code;constructor(e,t){let r=e??"";t?.lc_error_code&&(r=`${r}
3
+
4
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/
5
+ `),super(r),this.lc_error_code=t?.lc_error_code}},_s=class extends Ne{get is_bubble_up(){return!0}},Qi=class extends Ne{constructor(e,t){super(e,t),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},mn=class extends Ne{constructor(e,t){super(e,t),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},ys=class extends _s{reason;constructor(e="shutdown",t){super(`Graph drained: ${e}`,t),this.name="GraphDrained",this.reason=e}static get unminifiable_name(){return"GraphDrained"}};function Tr(e){return e!==void 0&&e.name===ys.unminifiable_name}var Ke=class extends _s{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}},ws=class extends Ke{constructor(e,t){super([{value:e}],t),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},vs=class{node;error;constructor(e,t){this.node=e,this.error=t}static get unminifiable_name(){return"NodeError"}};function pf(e){return e!=null&&typeof e=="object"&&e.constructor!=null&&e.constructor.unminifiable_name===vs.unminifiable_name}var bs=class extends _s{command;constructor(e){super(),this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}};function Zi(e){return e!==void 0&&e.name===bs.unminifiable_name}function Bt(e){return e!==void 0&&e.is_bubble_up===!0}var Tl=Symbol.for("langgraph.invalid_resume");function eo(e){typeof e=="object"&&e!==null&&Object.defineProperty(e,Tl,{value:!0})}function to(e){let t=e;for(let r=0;r<10;r+=1){if(typeof t!="object"||t===null)return!1;if(t[Tl]===!0)return!0;t=t.cause}return!1}function De(e){return e!==void 0&&[Ke.unminifiable_name,ws.unminifiable_name].includes(e.name)}var Ss=class extends Ne{node;kind;timeout;elapsed;runTimeout;idleTimeout;constructor(e,t){let{node:r,elapsed:n,kind:s,runTimeout:i,idleTimeout:o}=e,a,c;if(s==="idle"){if(o===void 0)throw new Error("idleTimeout is required when kind='idle'");c=o,a=`Node "${r}" exceeded its idle timeout of ${o}ms without making progress (elapsed: ${n}ms).`}else{if(i===void 0)throw new Error("runTimeout is required when kind='run'");c=i,a=`Node "${r}" exceeded its run timeout of ${i}ms (elapsed: ${n}ms).`}super(a,t),this.name="NodeTimeoutError",this.node=r,this.kind=s,this.timeout=c,this.elapsed=n,this.runTimeout=i,this.idleTimeout=o}static get unminifiable_name(){return"NodeTimeoutError"}};function ff(e){return e!==void 0&&e.name===Ss.unminifiable_name}var ks=class extends Ne{constructor(e,t){super(e,t),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Ir=class extends Ne{reason;interruptIds;pendingIds;constructor(e,t){super(e,t),this.name="UnknownInterruptError",this.reason=t.reason,this.interruptIds=t.interruptIds??[],this.pendingIds=t.pendingIds??[]}static get unminifiable_name(){return"UnknownInterruptError"}};function df(e){return e!=null&&e.name===Ir.unminifiable_name}var V=class extends Ne{constructor(e,t){let r=Error.stackTraceLimit;Error.stackTraceLimit=0,super(e,t),Error.stackTraceLimit=r,this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},M=class extends Ne{constructor(e,t){super(e,t),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},mf=class extends Ne{constructor(e,t){super(e,t),this.name="MultipleSubgraphError"}static get unminifiable_name(){return"MultipleSubgraphError"}},ro=class extends Ne{constructor(e,t){super(e,t),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}},gf=class extends Ne{constructor(e,t){super(e,t),this.name="RemoteException"}static get unminifiable_name(){return"RemoteException"}},gn=class extends Ne{constructor(e,t){super(e,t),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"}},_f=()=>(globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]===void 0&&(globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]=new Set),globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]);var no=0,_n=0;function yn(e){let t=Date.now();return t<=no?(_n+=1,_n>=1e4&&(_n=0,t=no+1)):_n=0,no=t,sc({clockseq:e,msecs:t,nsecs:_n})}function Ve(e,t){let r=t.replace(/-/g,"").match(/.{2}/g).map(n=>parseInt(n,16));return rn(e,new Uint8Array(r))}var wn="__pregel_tasks",so="__error__",ir="__scheduled__",io="__interrupt__",oo="__resume__",Ar=class{lg_name="DeltaSnapshot";value;constructor(e){this.value=e}};function vn(e){return e!=null&&typeof e=="object"&&e.lg_name==="DeltaSnapshot"}var Il="[...]",yf="[Circular]",Es=[],Or=[];function wf(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Al(e,t,r,n){typeof n>"u"&&(n=wf()),co(e,"",0,[],void 0,0,n);var s;try{Or.length===0?s=JSON.stringify(e,t,r):s=JSON.stringify(e,vf(t),r)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Es.length!==0;){var i=Es.pop();i.length===4?Object.defineProperty(i[0],i[1],i[3]):i[0][i[1]]=i[2]}}return s}function ao(e,t,r,n){var s=Object.getOwnPropertyDescriptor(n,r);s.get!==void 0?s.configurable?(Object.defineProperty(n,r,{value:e}),Es.push([n,r,t,s])):Or.push([t,r,e]):(n[r]=e,Es.push([n,r,t]))}function co(e,t,r,n,s,i,o){i+=1;var a;if(typeof e=="object"&&e!==null){for(a=0;a<n.length;a++)if(n[a]===e){ao(yf,e,t,s);return}if(typeof o.depthLimit<"u"&&i>o.depthLimit){ao(Il,e,t,s);return}if(typeof o.edgesLimit<"u"&&r+1>o.edgesLimit){ao(Il,e,t,s);return}if(n.push(e),Array.isArray(e))for(a=0;a<e.length;a++)co(e[a],a,a,n,e,i,o);else{var c=Object.keys(e);for(a=0;a<c.length;a++){var l=c[a];co(e[l],l,a,n,e,i,o)}}n.pop()}}function vf(e){return e=typeof e<"u"?e:function(t,r){return r},function(t,r){if(Or.length>0)for(var n=0;n<Or.length;n++){var s=Or[n];if(s[1]===t&&s[0]===r){r=s[2],Or.splice(n,1);break}}return e.call(this,t,r)}}var Ol=[];var Pl=T({});var Nl=T({BaseChatMessageHistory:()=>lo,BaseListChatMessageHistory:()=>Cs,InMemoryChatMessageHistory:()=>bf}),lo=class extends Ue{async addMessages(e){for(let t of e)await this.addMessage(t)}},Cs=class extends Ue{addUserMessage(e){return this.addMessage(new it(e))}addAIMessage(e){return this.addMessage(new Z(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw new Error("Not implemented.")}},bf=class extends Cs{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};var or=Yc(),xs=zc([kr(),qc(kr(),or),Wi(or)]),Sf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bn(e){return Jc(Sf,"Expected an object.").transform((t,r)=>{let n=[];for(let[s,i]of Object.entries(t)){let o=e.safeParse(i);if(o.success)n.push([s,o.data]);else for(let a of o.error.issues)r.issues.push({code:"custom",message:a.message,input:i,path:[s,...a.path]})}return Object.fromEntries(n)})}var kf=Er({true:or.optional(),false:or.optional()}),Ef=Er({type:vt("noul"),instructions:xs,criteria:kf.nullish()}),Cf=Er({type:vt("choice"),criteria:bn(or).refine(e=>Object.keys(e).length>=1,"Choice question must have at least 1 option."),instructions:xs}),xf=Er({type:vt("score"),criteria:Wi(or).min(2,"Score question must have at least 2 ordered levels."),instructions:xs}),Tf=Er({type:vt("box"),instructions:xs}),If=Gi("type",[Ef,Cf,xf,Tf]),Ts=je().min(0).max(1),Af=er({type:vt("noul"),noul:Ts}),Of=er({type:vt("choice"),choice:kr(),probabilities:bn(je()),confidence:Ts}),Pf=er({type:vt("score"),score:je(),legend:bn(or),probabilities:bn(je()),confidence:Ts}),Nf=er({top:je(),bottom:je(),left:je(),right:je()}),Rf=er({type:vt("box"),box:Nf,confidence:Ts.nullish().transform(e=>e??void 0)}),Mf=Gi("type",[Af,Of,Pf,Rf]),$f=Kc({input_tokens:je().nullish(),output_tokens:je().nullish(),total_tokens:je().nullish()}).transform(e=>{let t=e.input_tokens??0,r=e.output_tokens??0;return{...e,input_tokens:t,output_tokens:r,total_tokens:e.total_tokens||t+r}}),jf=er({model:kr(),answers:bn(Mf),usage_metadata:$f.nullish().transform(e=>e??void 0),requestId:kr().nullish().transform(e=>e??void 0)});function Df(e){let t=(r,n)=>{Object.defineProperty(e,r,{enumerable:!1,configurable:!0,get(){return Object.fromEntries(Object.entries(e.answers).filter(([,s])=>s.type===n))}})};return t("nouls","noul"),t("choices","choice"),t("scores","score"),t("boxes","box"),e}function Rl(e){let t=e.path.map(String).join("."),r=e.code==="unrecognized_keys"?"Unrecognized key.":e.message;return t?`${t}: ${r}`:r}function Is(e){if(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length===0)throw new Error("Decision models require at least one question.");for(let[t,r]of Object.entries(e)){let n;try{n=If.safeParse(r)}catch{throw new Error(`Invalid question "${t}": content is too deeply nested or circular.`)}if(!n.success)throw new Error(`Invalid question "${t}": ${Rl(n.error.issues[0])}`)}return e}function Ml(e){let t=jf.safeParse(e);if(!t.success)throw new Error(`Invalid decision model response: ${Rl(t.error.issues[0])}`);let{usage_metadata:r,requestId:n,...s}=t.data;return Df({...s,...r===void 0?{}:{usage_metadata:r},...n===void 0?{}:{requestId:n}})}function Vf(e,t){for(let[r,n]of Object.entries(e)){let s=Object.hasOwn(t.answers,r)?t.answers[r]:void 0;if(s===void 0)throw new Error(`Decision model returned no answer for question "${r}".`);if(s.type!==n.type)throw new Error(`Decision model returned a ${s.type} answer for ${n.type} question "${r}".`);if(s.type==="choice"&&n.type==="choice"&&!Object.hasOwn(n.criteria,s.choice))throw new Error(`Decision model returned a choice for question "${r}" that is not one of its labels.`)}}var $l=class extends G{model;constructor(e){super(e),this.model=e.model}async invoke(e,t){let r=cs(t);return await this._callWithConfig(async(n,s,i)=>{let{runType:o,...a}=s??{},c=Is(n.questions),l=await this._classify(n.state,c,He(a,{callbacks:i?.getChild()}));return Vf(c,l),l},e,{...r,runType:"llm",metadata:{...r.metadata,ls_provider:this._provider,ls_model_name:this.model,ls_model_type:"chat"}})}};var jl=T({BaseDecisionModel:()=>$l,parseClassifierResponse:()=>Ml,parseQuestions:()=>Is});var Dl=T({BaseDocumentLoader:()=>uo}),uo=class{};var Vl=T({LangSmithLoader:()=>Lf}),Lf=class extends uo{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=e.client??new mc(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split("."):[],this.formatContent=e.formatContent??Ff,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t 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 r=t.inputs;for(let i of this.contentKey)r=r[i];let n=this.formatContent(r),s=t;["created_at","modified_at"].forEach(i=>{i in s&&typeof s[i]=="object"&&(s[i]=s[i].toString())}),e.push({pageContent:n,metadata:s})}return e}};function Ff(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var Re=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent!==void 0?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}};var ho=class extends G{lc_namespace=["langchain_core","documents","transformers"];invoke(e,t){return this.transformDocuments(e)}},Ll=class extends ho{async transformDocuments(e){let t=[];for(let r of e){let n=await this._transformDocument(r);t.push(n)}return t}};var Fl=T({BaseDocumentTransformer:()=>ho,Document:()=>Re,MappingDocumentTransformer:()=>Ll});var Pr=class extends Ue{lc_namespace=["langchain_core","example_selectors","base"]};var po=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},Ul=class extends po{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,r]of this.conditionals)if(t(e))return r;return this.defaultPrompt}};function Bl(e){return e._modelType()==="base_llm"}function Hl(e){return e._modelType()==="base_chat_model"}function Wl(e){return e.split(/\n| /).length}var Gl=class Kl extends Pr{examples=[];examplePrompt;getTextLength=Wl;maxLength=2048;exampleTextLengths=[];constructor(t){super(t),this.examplePrompt=t.examplePrompt,this.maxLength=t.maxLength??2048,this.getTextLength=t.getTextLength??Wl}async addExample(t){this.examples.push(t);let r=await this.examplePrompt.format(t);this.exampleTextLengths.push(this.getTextLength(r))}async calculateExampleTextLengths(t,r){if(t.length>0)return t;let{examples:n,examplePrompt:s}=r;return(await Promise.all(n.map(i=>s.format(i)))).map(i=>this.getTextLength(i))}async selectExamples(t){let r=Object.values(t).join(" "),n=this.maxLength-this.getTextLength(r),s=0,i=[];for(;n>0&&s<this.examples.length;){let o=n-this.exampleTextLengths[s];if(o<0)break;i.push(this.examples[s]),n=o,s+=1}return i}static async fromExamples(t,r){let n=new Kl(r);return await Promise.all(t.map(s=>n.addExample(s))),n}};function fo(e){return Object.keys(e).sort().map(t=>e[t])}var zl=class ql extends Pr{vectorStoreRetriever;exampleKeys;inputKeys;constructor(t){if(super(t),this.exampleKeys=t.exampleKeys,this.inputKeys=t.inputKeys,t.vectorStore!==void 0)this.vectorStoreRetriever=t.vectorStore.asRetriever({k:t.k??4,filter:t.filter});else if(t.vectorStoreRetriever)this.vectorStoreRetriever=t.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(t){let r=fo((this.inputKeys??Object.keys(t)).reduce((n,s)=>({...n,[s]:t[s]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new Re({pageContent:r,metadata:t})])}async selectExamples(t){let r=fo((this.inputKeys??Object.keys(t)).reduce((s,i)=>({...s,[i]:t[i]}),{})).join(" "),n=(await this.vectorStoreRetriever.invoke(r)).map(s=>s.metadata);return this.exampleKeys?n.map(s=>this.exampleKeys.reduce((i,o)=>({...i,[o]:s[o]}),{})):n}static async fromExamples(t,r,n,s={}){let i=s.inputKeys??null,o=t.map(c=>fo(i?i.reduce((l,u)=>({...l,[u]:c[u]}),{}):c).join(" ")),a=await n.fromTexts(o,t,r,s);return new ql({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}};var Jl=T({BaseExampleSelector:()=>Pr,BasePromptSelector:()=>po,ConditionalPromptSelector:()=>Ul,LengthBasedExampleSelector:()=>Gl,SemanticSimilarityExampleSelector:()=>zl,isChatModel:()=>Hl,isLLM:()=>Bl});var Yl=T({});var Sn="10f90ea3-90a4-4962-bf75-83a0f3c1c62a",Xl=class extends Ue{lc_namespace=["langchain","recordmanagers"]};var mo=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Hc;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=["hash_","content_hash","metadata_hash"];for(let r of e)if(r in this.metadata)throw new Error(`Metadata cannot contain key ${r} as it is reserved for internal use. Restricted keys: [${e.join(", ")}]`);let t=this._hashStringToUUID(this.pageContent);try{let r=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=r}catch(r){throw new Error(`Failed to hash metadata: ${r}. 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 Re({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let r=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return r.calculateHashes(),r}_hashStringToUUID(e){let t=this.keyEncoder(e);return rn(t,Sn)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort()),r=this.keyEncoder(t);return rn(r,Sn)}};function go(e,t){let r=[],n=[];return t.forEach(s=>{n.push(s),n.length>=e&&(r.push(n),n=[])}),n.length>0&&r.push(n),r}function _o(e){let t=new Set,r=[];for(let n of e){if(!n.hash_)throw new Error("Hashed document does not have a hash");t.has(n.hash_)||(t.add(n.hash_),r.push(n))}return r}function yo(e){if(e===null)return t=>null;if(typeof e=="string")return t=>t.metadata[e];if(typeof e=="function")return e;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var wo=e=>"load"in e&&typeof e.load=="function"&&"loadAndSplit"in e&&typeof e.loadAndSplit=="function";async function Ql(e){let{docsSource:t,recordManager:r,vectorStore:n,options:s}=e,{batchSize:i=100,cleanup:o,sourceIdKey:a,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=s??{};if(o==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");let u=wo(t)?await t.load():t,h=yo(a??null),p=await r.getTime(),d=0,f=0,m=0,_=0,y=go(i??100,u);for(let g of y){let w=_o(g.map(I=>mo.fromDocument(I))),S=w.map(I=>h(I));o==="incremental"&&w.forEach((I,D)=>{if(S[D]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});let k=await r.exists(w.map(I=>I.uid)),C=[],O=[],P=[],K=new Set;if(w.forEach((I,D)=>{if(k[D])if(l)K.add(I.uid);else{P.push(I.uid);return}C.push(I.uid),O.push(I.toDocument())}),P.length>0&&(await r.update(P,{timeAtLeast:p}),_+=P.length),O.length>0&&(await n.addDocuments(O,{ids:C}),d+=O.length-K.size,m+=K.size),await r.update(w.map(I=>I.uid),{timeAtLeast:p,groupIds:S}),o==="incremental"){S.forEach(D=>{if(!D)throw new Error("Source id cannot be null")});let I=await r.listKeys({before:p,groupIds:S});I.length>0&&(await n.delete({ids:I}),await r.deleteKeys(I),f+=I.length)}}if(o==="full"){let g=await r.listKeys({before:p,limit:c});for(;g.length>0;)await n.delete({ids:g}),await r.deleteKeys(g),f+=g.length,g=await r.listKeys({before:p,limit:c})}return{numAdded:d,numDeleted:f,numUpdated:m,numSkipped:_}}var Zl=T({RecordManager:()=>Xl,UUIDV5_NAMESPACE:()=>Sn,_HashedDocument:()=>mo,_batch:()=>go,_deduplicateInOrder:()=>_o,_getSourceIdAssigner:()=>yo,_isBaseDocumentLoader:()=>wo,index:()=>Ql});var eu=T({});var tu=T({});var ru=T({BaseMemory:()=>Uf,getInputValue:()=>Bf,getOutputValue:()=>Hf,getPromptInputKey:()=>Wf}),Uf=class{},nu=(e,t)=>{if(t!==void 0)return e[t];let r=Object.keys(e);if(r.length===1)return e[r[0]]},Bf=(e,t)=>{let r=nu(e,t);if(!r){let n=Object.keys(e);throw new Error(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}return r},Hf=(e,t)=>{let r=nu(e,t);if(!r&&r!==""){let n=Object.keys(e);throw new Error(`output values have ${n.length} keys, you must specify an output key or pass only 1 key as output`)}return r};function Wf(e,t){let r=Object.keys(e).filter(n=>!t.includes(n)&&n!=="stop");if(r.length!==1)throw new Error(`One input key expected, but got ${r.length}`);return r[0]}var vo=class extends zi{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if("message"in e[0]){let t=e[0].message.additional_kwargs.function_call;if(!t)throw new Error(`No function_call in message ${JSON.stringify(e)}`);if(!t.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?t.arguments:JSON.stringify(t)}else throw new Error(`No message in generations ${JSON.stringify(e)}`)}},bo=class extends nl{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new vo(e)}_diff(e,t){if(t)return ic(e??{},t)}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:r}=t,n=r.additional_kwargs.function_call;if(n)return this.argsOnly?Vi(n.arguments):{...n,arguments:Vi(n.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return""}},su=class extends zi{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new bo;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}};var iu=T({JsonKeyOutputFunctionsParser:()=>su,JsonOutputFunctionsParser:()=>bo,OutputFunctionsParser:()=>vo});var ht=class extends G{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},r={};for(let[n,s]of Object.entries(t))typeof s=="string"?r[n]=s:r[n]=await s();return{...r,...e}}async invoke(e,t){let r={...this.metadata,...t?.metadata},n=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),e,{...t,tags:n,metadata:r,runType:"prompt"})}};var St=class extends ht{async formatPromptValue(e){let t=await this.format(e);return new Fc(t)}};function kn(){return _r(new Error("Prompt template nesting exceeds maximum depth (256)."),"INVALID_PROMPT_INPUT")}var Gf=Object.prototype.toString,Rr=Array.isArray||function(t){return Gf.call(t)==="[object Array]"};function ko(e){return typeof e=="function"}function Kf(e){return Rr(e)?"array":typeof e}function So(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function ou(e,t){return e!=null&&typeof e=="object"&&t in e}function zf(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var qf=RegExp.prototype.test;function Jf(e,t){return qf.call(e,t)}var Yf=/\S/;function Xf(e){return!Jf(Yf,e)}var Qf={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Zf(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return Qf[r]})}var ed=/\s*/,td=/\s+/,au=/\s*=/,rd=/\s*\}/,nd=/#|\^|\/|>|\{|&|=|!/;function sd(e,t){if(!e)return[];var r=!1,n=[],s=[],i=[],o=!1,a=!1,c="",l=0;function u(){if(o&&!a)for(;i.length;)delete s[i.pop()];else i=[];o=!1,a=!1}var h,p,d;function f(P){if(typeof P=="string"&&(P=P.split(td,2)),!Rr(P)||P.length!==2)throw new Error("Invalid tags: "+P);h=new RegExp(So(P[0])+"\\s*"),p=new RegExp("\\s*"+So(P[1])),d=new RegExp("\\s*"+So("}"+P[1]))}f(t||Le.tags);for(var m=new Cn(e),_,y,g,w,S,k;!m.eos();){if(_=m.pos,g=m.scanUntil(h),g)for(var C=0,O=g.length;C<O;++C)w=g.charAt(C),Xf(w)?(i.push(s.length),c+=w):(a=!0,r=!0,c+=" "),s.push(["text",w,_,_+1]),_+=1,w===`
6
+ `&&(u(),c="",l=0,r=!1);if(!m.scan(h))break;if(o=!0,y=m.scan(nd)||"name",m.scan(ed),y==="="?(g=m.scanUntil(au),m.scan(au),m.scanUntil(p)):y==="{"?(g=m.scanUntil(d),m.scan(rd),m.scanUntil(p),y="&"):g=m.scanUntil(p),!m.scan(p))throw new Error("Unclosed tag at "+m.pos);if(y==">"?S=[y,g,_,m.pos,c,l,r]:S=[y,g,_,m.pos],l++,s.push(S),y==="#"||y==="^")n.push(S);else if(y==="/"){if(k=n.pop(),!k)throw new Error('Unopened section "'+g+'" at '+_);if(k[1]!==g)throw new Error('Unclosed section "'+k[1]+'" at '+_)}else y==="name"||y==="{"||y==="&"?a=!0:y==="="&&f(g)}if(u(),k=n.pop(),k)throw new Error('Unclosed section "'+k[1]+'" at '+m.pos);return od(id(s))}function id(e){for(var t=[],r,n,s=0,i=e.length;s<i;++s)r=e[s],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(t.push(r),n=r));return t}function od(e){for(var t=[],r=t,n=[],s,i,o=0,a=e.length;o<a;++o)switch(s=e[o],s[0]){case"#":case"^":r.push(s),n.push(s),r=s[4]=[];break;case"/":i=n.pop(),i[5]=s[2],r=n.length>0?n[n.length-1][4]:t;break;default:r.push(s)}return t}function Cn(e){this.string=e,this.tail=e,this.pos=0}Cn.prototype.eos=function(){return this.tail===""};Cn.prototype.scan=function(t){var r=this.tail.match(t);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};Cn.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};function Nr(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Nr.prototype.push=function(t){return new Nr(t,this)};Nr.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var s=this,i,o,a,c=!1;s;){if(t.indexOf(".")>0)for(i=s.view,o=t.split("."),a=0;i!=null&&a<o.length;)a===o.length-1&&(c=ou(i,o[a])||zf(i,o[a])),i=i[o[a++]];else i=s.view[t],c=ou(s.view,t);if(c){n=i;break}s=s.parent}r[t]=n}return ko(n)&&(n=n.call(this.view)),n};function be(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}be.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};be.prototype.parse=function(t,r){var n=this.templateCache,s=t+":"+(r||Le.tags).join(":"),i=typeof n<"u",o=i?n.get(s):void 0;return o==null&&(o=sd(t,r),i&&n.set(s,o)),o};be.prototype.render=function(t,r,n,s){var i=this.getConfigTags(s),o=this.parse(t,i),a=r instanceof Nr?r:new Nr(r,void 0);return this.renderTokens(o,a,n,t,s)};be.prototype.renderTokens=function(t,r,n,s,i){for(var o="",a,c,l,u=0,h=t.length;u<h;++u)l=void 0,a=t[u],c=a[0],c==="#"?l=this.renderSection(a,r,n,s,i):c==="^"?l=this.renderInverted(a,r,n,s,i):c===">"?l=this.renderPartial(a,r,n,i):c==="&"?l=this.unescapedValue(a,r):c==="name"?l=this.escapedValue(a,r,i):c==="text"&&(l=this.rawValue(a)),l!==void 0&&(o+=l);return o};be.prototype.renderSection=function(t,r,n,s,i){var o=this,a="",c=r.lookup(t[1]);function l(p){return o.render(p,r,n,i)}if(c){if(Rr(c))for(var u=0,h=c.length;u<h;++u)a+=this.renderTokens(t[4],r.push(c[u]),n,s,i);else if(typeof c=="object"||typeof c=="string"||typeof c=="number")a+=this.renderTokens(t[4],r.push(c),n,s,i);else if(ko(c)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");c=c.call(r.view,s.slice(t[3],t[5]),l),c!=null&&(a+=c)}else a+=this.renderTokens(t[4],r,n,s,i);return a}};be.prototype.renderInverted=function(t,r,n,s,i){var o=r.lookup(t[1]);if(!o||Rr(o)&&o.length===0)return this.renderTokens(t[4],r,n,s,i)};be.prototype.indentPartial=function(t,r,n){for(var s=r.replace(/[^ \t]/g,""),i=t.split(`
7
+ `),o=0;o<i.length;o++)i[o].length&&(o>0||!n)&&(i[o]=s+i[o]);return i.join(`
8
+ `)};be.prototype.renderPartial=function(t,r,n,s){if(n){var i=this.getConfigTags(s),o=ko(n)?n(t[1]):n[t[1]];if(o!=null){var a=t[6],c=t[5],l=t[4],u=o;c==0&&l&&(u=this.indentPartial(o,l,a));var h=this.parse(u,i);return this.renderTokens(h,r,n,u,s)}}};be.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};be.prototype.escapedValue=function(t,r,n){var s=this.getConfigEscape(n)||Le.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&s===Le.escape?String(i):s(i)};be.prototype.rawValue=function(t){return t[1]};be.prototype.getConfigTags=function(t){return Rr(t)?t:t&&typeof t=="object"?t.tags:void 0};be.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Rr(t))return t.escape};var Le={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(e){En.templateCache=e},get templateCache(){return En.templateCache}},En=new be;Le.clearCache=function(){return En.clearCache()};Le.parse=function(t,r){return En.parse(t,r)};Le.render=function(t,r,n,s){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Kf(t)+'" was given as the first argument for mustache#render(template, view, partials)');return En.render(t,r,n,s)};Le.escape=Zf;Le.Scanner=Cn;Le.Context=Nr;Le.Writer=be;var Eo=Le;var ad={escape:e=>e},ar=e=>{let t=e.split(""),r=[],n=(i,o)=>{for(let a=o;a<t.length;a+=1)if(i.includes(t[a]))return a;return-1},s=0;for(;s<t.length;)if(t[s]==="{"&&s+1<t.length&&t[s+1]==="{")r.push({type:"literal",text:"{"}),s+=2;else if(t[s]==="}"&&s+1<t.length&&t[s+1]==="}")r.push({type:"literal",text:"}"}),s+=2;else if(t[s]==="{"){let i=n("}",s);if(i<0)throw new Error("Unclosed '{' in template.");r.push({type:"variable",name:t.slice(s+1,i).join("")}),s=i+1}else{if(t[s]==="}")throw new Error("Single '}' in template.");{let i=n("{}",s),o=(i<0?t.slice(s):t.slice(s,i)).join("");r.push({type:"literal",text:o}),s=i<0?t.length:i}}return r},cu=(e,t=[],r=0)=>{if(r>=256)throw kn();let n=[];for(let s of e)if(s[0]==="name"){let i=s[1].includes(".")?s[1].split(".")[0]:s[1];n.push({type:"variable",name:i})}else if(["#","&","^",">"].includes(s[0])){if(n.push({type:"variable",name:s[1]}),s[0]==="#"&&s.length>4&&Array.isArray(s[4])){let i=[...t,s[1]],o=cu(s[4],i,r+1);n.push(...o)}}else n.push({type:"literal",text:s[1]});return n},Mr=e=>{let t=Eo.parse(e);return cu(t)},Co=(e,t)=>ar(e).reduce((r,n)=>{if(n.type==="variable"){if(n.name in t)return r+(typeof t[n.name]=="string"?t[n.name]:JSON.stringify(t[n.name]));throw new Error(`(f-string) Missing value for input ${n.name}`)}return r+n.text},""),xo=(e,t)=>Eo.render(e,t,void 0,ad),xn={"f-string":Co,mustache:xo},To={"f-string":ar,mustache:Mr},we=(e,t,r)=>{try{return xn[t](e,r)}catch(n){throw _r(n,"INVALID_PROMPT_INPUT")}},cr=(e,t)=>To[t](e),kt=(e,t,r)=>{if(!(t in xn)){let n=Object.keys(xn);throw new Error(`Invalid template format. Got \`${t}\`;
9
+ should be one of ${n}`)}try{let n=Object.fromEntries(r.map(s=>[s,"foo"]));Array.isArray(e)?e.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")we(s.text,t,n);else if(s.type==="image_url"){if(typeof s.image_url=="string")we(s.image_url,t,n);else if(typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"){let i=s.image_url.url;we(i,t,n)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):we(e,t,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}};var ze=class Tn extends St{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),kt(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(t){let r=await this.mergePartialAndUserVariables(t);return we(this.template,this.templateFormat,r)}static fromExamples(t,r,n,s=`
10
+
11
+ `,i=""){let o=[i,...t,r].join(s);return new Tn({inputVariables:n,template:o})}static fromTemplate(t,r){let{templateFormat:n="f-string",...s}=r??{},i=new Set;return cr(t,n).forEach(o=>{o.type==="variable"&&i.add(o.name)}),new Tn({inputVariables:[...i],templateFormat:n,template:t,...s})}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},s={...this,inputVariables:r,partialVariables:n};return new Tn(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(t){if(!t.template)throw new Error("Prompt template must have a template");return new Tn({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}};var $r=class lu extends ht{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),this.template=t.template,this.templateFormat=t.templateFormat??this.templateFormat,this.validateTemplate=t.validateTemplate??this.validateTemplate,this.additionalContentFields=t.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),kt([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}_getPromptType(){return"prompt"}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},s={...this,inputVariables:r,partialVariables:n};return new lu(s)}async format(t){let r={};for(let[o,a]of Object.entries(this.template))typeof a=="string"?r[o]=we(a,this.templateFormat,t):r[o]=a;let n=t.url||r.url,s=t.detail||r.detail;if(!n)throw new Error("Must provide either an image URL.");if(typeof n!="string")throw new Error("url must be a string.");let i={url:n};return s&&(i.detail=s),i}async formatPromptValue(t){let r=await this.format(t);return new Bc(r)}};var In=class extends G{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(e){let t=e.templateFormat??"f-string",r=Io(e.template,t);super({inputVariables:r,...e}),this.template=e.template,this.templateFormat=t,this.inputVariables=r}async format(e){return Ao(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}};function Io(e,t,r=0){if(r>=256)throw kn();let n=[];for(let s of Object.values(e))if(typeof s=="string")cr(s,t).forEach(i=>{i.type==="variable"&&n.push(i.name)});else if(Array.isArray(s))for(let i of s)typeof i=="string"?cr(i,t).forEach(o=>{o.type==="variable"&&n.push(o.name)}):typeof i=="object"&&n.push(...Io(i,t,r+1));else typeof s=="object"&&s!==null&&n.push(...Io(s,t,r+1));return Array.from(new Set(n))}function Ao(e,t,r,n=0){if(n>=256)throw kn();let s={};for(let[i,o]of Object.entries(e))if(typeof o=="string")s[i]=we(o,r,t);else if(Array.isArray(o)){let a=[];for(let c of o)typeof c=="string"?a.push(we(c,r,t)):typeof c=="object"&&a.push(Ao(c,t,r,n+1));s[i]=a}else typeof o=="object"&&o!==null?s[i]=Ao(o,t,r,n+1):s[i]=o;return s}var An=class extends G{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(e,t){return this._callWithConfig(r=>this.formatMessages(r),e,{...t,runType:"prompt"})}},Os=class extends An{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(e){typeof e=="string"&&(e={variableName:e}),super(e),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){let t=e[this.variableName];if(this.optional&&!t)return[];if(!t){let n=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw n.name="InputFormatError",n}let r;try{Array.isArray(t)?r=t.map(Be):r=[Be(t)]}catch(n){let s=typeof t=="string"?t:JSON.stringify(t,null,2),i=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: ${n.message}`].join(`
12
+
13
+ `));throw i.name="InputFormatError",i.lc_error_code=n.lc_error_code,i}return r}},Oo=class extends An{prompt;constructor(e){"prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},On=class extends ht{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){let t=await this.formatMessages(e);return new Uc(t)}},Po=class extends Oo{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(e,t){"prompt"in e||(e={prompt:e,role:t}),super(e),this.role=e.role}async format(e){return new sn(await this.prompt.format(e),this.role)}static fromTemplate(e,t,r){return new this(ze.fromTemplate(e,{templateFormat:r?.templateFormat}),t)}};function cd(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.keys(e).length===1&&"text"in e&&typeof e.text=="string"}function ld(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:"image_url"in e&&(typeof e.image_url=="string"||typeof e.image_url=="object"&&e.image_url!==null&&"url"in e.image_url&&typeof e.image_url.url=="string")}var No=class extends An{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(e,t){if("prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(n=>{"inputVariables"in n&&(r=r.concat(n.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){let t=this.constructor;if(t._messageClass())return new(t._messageClass())({content:e});if(t.chatMessageClass){let r=t.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){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(e,t){if(typeof e=="string")return new this(ze.fromTemplate(e,t));let r=[];for(let n of e)if(typeof n=="string")r.push(ze.fromTemplate(n,t));else if(n!==null)if(cd(n)){let s="";typeof n.text=="string"&&(s=n.text??"");let i={...t,additionalContentFields:n};r.push(ze.fromTemplate(s,i))}else if(ld(n)){let s=n.image_url??"",i,o=[];if(typeof s=="string"){let a;t?.templateFormat==="mustache"?a=Mr(s):a=ar(s);let c=a.flatMap(l=>l.type==="variable"?[l.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
14
+ Got: ${c}
15
+ From: ${s}`);o=[c[0]]}else o=[];s={url:s},i=new $r({template:s,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:n})}else if(typeof s=="object"){if("url"in s){let a;t?.templateFormat==="mustache"?a=Mr(s.url):a=ar(s.url),o=a.flatMap(c=>c.type==="variable"?[c.name]:[])}else o=[];i=new $r({template:s,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:n})}else throw new Error("Invalid image template");r.push(i)}else typeof n=="object"&&r.push(new In({template:n,templateFormat:t?.templateFormat}));return new this({prompt:r,additionalOptions:t})}async format(e){if(this.prompt instanceof St){let t=await this.prompt.format(e);return this.createMessage(t)}else{let t=[];for(let r of this.prompt){let n={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(let s of r.inputVariables)n||(n={[s]:e[s]}),n={...n,[s]:e[s]};if(r instanceof St){let s=await r.format(n),i;"additionalContentFields"in r&&(i=r.additionalContentFields),s!==""&&t.push({...i,type:"text",text:s})}else if(r instanceof $r){let s=await r.format(n),i;"additionalContentFields"in r&&(i=r.additionalContentFields),t.push({...i,type:"image_url",image_url:s})}else if(r instanceof In){let s=await r.format(n),i;"additionalContentFields"in r&&(i=r.additionalContentFields),t.push({...i,...s})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}},Ps=class extends No{static _messageClass(){return it}static lc_name(){return"HumanMessagePromptTemplate"}},Ro=class extends No{static _messageClass(){return Z}static lc_name(){return"AIMessagePromptTemplate"}},Mo=class extends No{static _messageClass(){return vr}static lc_name(){return"SystemMessagePromptTemplate"}};function ud(e){return typeof e.formatMessages=="function"}function hd(e,t){if(ud(e)||yt(e))return e;if(Array.isArray(e)&&e[0]==="placeholder"){let s=e[1];if(t?.templateFormat==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}")return new Os({variableName:s.slice(2,-2),optional:!0});if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}")return new Os({variableName:s.slice(1,-1),optional:!0});throw new Error(`Invalid placeholder template for format ${t?.templateFormat??'"f-string"'}: "${e[1]}". Expected a variable name surrounded by ${t?.templateFormat==="mustache"?"double":"single"} curly braces.`)}let r=Be(e),n;if(typeof r.content=="string"?n=r.content:n=r.content.map(s=>"text"in s?{...s,text:s.text}:"image_url"in s?{...s,image_url:s.image_url}:s),r._getType()==="human")return Ps.fromTemplate(n,t);if(r._getType()==="ai")return Ro.fromTemplate(n,t);if(r._getType()==="system")return Mo.fromTemplate(n,t);if(sn.isInstance(r))return Po.fromTemplate(r.content,r.role,t);throw new Error(`Could not coerce message prompt template from input. Received message type: "${r._getType()}".`)}function pd(e){return e.constructor.lc_name()==="MessagesPlaceholder"}var jr=class As extends On{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){let r=new Set;for(let a of this.promptMessages)if(!(a instanceof ee))for(let c of a.inputVariables)r.add(c);let n=this.inputVariables,s=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),i=new Set([...s].filter(a=>!r.has(a)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are not used in any of the prompt messages.`);let o=new Set([...r].filter(a=>!s.has(a)));if(o.size>0)throw new Error(`Input variables \`${[...o]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(t,r){return typeof t.content=="string"||(t.content=await Promise.all(t.content.map(async n=>{if(n.type!=="image_url")return n;let s="";typeof n.image_url=="string"?s=n.image_url:typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(s=n.image_url.url);let i=await ze.fromTemplate(s,{templateFormat:this.templateFormat}).format(r);return typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url?n.image_url.url=i:n.image_url=i,n}))),t}async formatMessages(t){let r=await this.mergePartialAndUserVariables(t),n=[];for(let s of this.promptMessages)if(s instanceof ee)n.push(await this._parseImagePrompts(s,r));else{let i;this.templateFormat==="mustache"?i={...r}:i=s.inputVariables.reduce((a,c)=>{if(!(c in r)&&!(pd(s)&&s.optional))throw _r(new Error(`Missing value for input variable \`${c.toString()}\``),"INVALID_PROMPT_INPUT");return a[c]=r[c],a},{});let o=await s.formatMessages(i);n=n.concat(o)}return n}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},s={...this,inputVariables:r,partialVariables:n};return new As(s)}static fromTemplate(t,r){let n=new Ps({prompt:ze.fromTemplate(t,r)});return this.fromMessages([n])}static fromMessages(t,r){let n=t.reduce((o,a)=>o.concat(a instanceof As?a.promptMessages:[hd(a,r)]),[]),s=t.reduce((o,a)=>a instanceof As?Object.assign(o,a.partialVariables):o,Object.create(null)),i=new Set;for(let o of n)if(!(o instanceof ee))for(let a of o.inputVariables)a in s||i.add(a);return new this({...r,inputVariables:[...i],promptMessages:n,partialVariables:s,templateFormat:r?.templateFormat})}};var uu=class $o extends St{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
16
+
17
+ `;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(t){if(super(t),Object.assign(this,t),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 r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),kt(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},s={...this,inputVariables:r,partialVariables:n};return new $o(s)}async format(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),s=await Promise.all(n.map(o=>this.examplePrompt.format(o))),i=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return we(i,this.templateFormat,r)}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(t){let{example_prompt:r}=t;if(!r)throw new Error("Missing example prompt");let n=await ze.deserialize(r),s;if(Array.isArray(t.examples))s=t.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new $o({inputVariables:t.input_variables,examplePrompt:n,examples:s,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},hu=class pu extends On{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
18
+
19
+ `;prefix="";templateFormat="f-string";validateTemplate=!0;_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(t){if(super(t),this.examples=t.examples,this.examplePrompt=t.examplePrompt,this.exampleSeparator=t.exampleSeparator??`
20
+
21
+ `,this.exampleSelector=t.exampleSelector,this.prefix=t.prefix??"",this.suffix=t.suffix??"",this.templateFormat=t.templateFormat??"f-string",this.validateTemplate=t.validateTemplate??!0,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 r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),kt(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r);n=n.map(i=>{let o={};return this.examplePrompt.inputVariables.forEach(a=>{o[a]=i[a]}),o});let s=[];for(let i of n){let o=await this.examplePrompt.formatMessages(i);s.push(...o)}return s}async format(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),s=(await Promise.all(n.map(o=>this.examplePrompt.formatMessages(o)))).flat().map(o=>o.content),i=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return we(i,this.templateFormat,r)}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},s={...this,inputVariables:r,partialVariables:n};return new pu(s)}};var fu=class Ns extends ht{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(t){super({...t,inputVariables:[]}),this.pipelinePrompts=t.pipelinePrompts,this.finalPrompt=t.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let t=this.pipelinePrompts.map(n=>n.name),r=this.pipelinePrompts.map(n=>n.prompt.inputVariables.filter(s=>!t.includes(s))).flat();return[...new Set(r)]}static extractRequiredInputValues(t,r){return r.reduce((n,s)=>(n[s]=t[s],n),{})}async formatPipelinePrompts(t){let r=await this.mergePartialAndUserVariables(t);for(let{name:n,prompt:s}of this.pipelinePrompts){let i=Ns.extractRequiredInputValues(r,s.inputVariables);s instanceof jr?r[n]=await s.formatMessages(i):r[n]=await s.format(i)}return Ns.extractRequiredInputValues(r,this.finalPrompt.inputVariables)}async formatPromptValue(t){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(t))}async format(t){return this.finalPrompt.format(await this.formatPipelinePrompts(t))}async partial(t){let r={...this};return r.inputVariables=this.inputVariables.filter(n=>!(n in t)),r.partialVariables={...this.partialVariables??{},...t},new Ns(r)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function du(e){return typeof e=="object"&&e!=null&&"withStructuredOutput"in e&&typeof e.withStructuredOutput=="function"}function fd(e){return typeof e=="object"&&e!=null&&"lc_id"in e&&Array.isArray(e.lc_id)&&e.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var mu=class gu extends jr{schema;method;lc_namespace=["langchain_core","prompts","structured"];get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(t){super(t),this.schema=t.schema,this.method=t.method}pipe(t){if(du(t))return super.pipe(t.withStructuredOutput(this.schema));if(fd(t)&&du(t.bound))return super.pipe(new us({bound:t.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:t.kwargs??{},config:t.config,configFactories:t.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(t,r,n){return gu.fromMessages(t,{schema:r,method:n})}};var _u=T({AIMessagePromptTemplate:()=>Ro,BaseChatPromptTemplate:()=>On,BaseMessagePromptTemplate:()=>An,BaseMessageStringPromptTemplate:()=>Oo,BasePromptTemplate:()=>ht,BaseStringPromptTemplate:()=>St,ChatMessagePromptTemplate:()=>Po,ChatPromptTemplate:()=>jr,DEFAULT_FORMATTER_MAPPING:()=>xn,DEFAULT_PARSER_MAPPING:()=>To,DictPromptTemplate:()=>In,FewShotChatMessagePromptTemplate:()=>hu,FewShotPromptTemplate:()=>uu,HumanMessagePromptTemplate:()=>Ps,ImagePromptTemplate:()=>$r,MessagesPlaceholder:()=>Os,PipelinePromptTemplate:()=>fu,PromptTemplate:()=>ze,StructuredPrompt:()=>mu,SystemMessagePromptTemplate:()=>Mo,checkValidTemplate:()=>kt,interpolateFString:()=>Co,interpolateMustache:()=>xo,parseFString:()=>ar,parseMustache:()=>Mr,parseTemplate:()=>cr,renderTemplate:()=>we});var yu=T({BaseDocumentCompressor:()=>dd}),dd=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}};var wu=T({BaseRetriever:()=>Pn}),Pn=class extends G{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){let r=cs(Cc(t)),n=await(await br.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName);try{let s=await this._getRelevantDocuments(e,n);return await n?.handleRetrieverEnd(s),s}catch(s){throw await n?.handleRetrieverError(s),s}}};var vu=T({BaseStore:()=>bu,InMemoryStore:()=>md}),bu=class extends Ue{},md=class extends bu{lc_namespace=["langchain","storage"];store={};async mget(e){return e.map(t=>this.store[t])}async mset(e){for(let[t,r]of e)this.store[t]=r}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let r of t)(e===void 0||r.startsWith(e))&&(yield r)}};var qe={and:"and",or:"or",not:"not"},j={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"},Rs=class{},Ms=class{accept(e){if(this.exprName==="Operation")return e.visitOperation(this);if(this.exprName==="Comparison")return e.visitComparison(this);if(this.exprName==="StructuredQuery")return e.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},$s=class extends Ms{},Su=class extends $s{comparator;attribute;value;exprName="Comparison";constructor(e,t,r){super(),this.comparator=e,this.attribute=t,this.value=r}},ku=class extends $s{operator;args;exprName="Operation";constructor(e,t){super(),this.operator=e,this.args=t}},Eu=class extends Ms{query;filter;exprName="StructuredQuery";constructor(e,t){super(),this.query=e,this.filter=t}};function jo(e){return e&&typeof e=="object"&&!Array.isArray(e)}function Te(e){return e?typeof e=="string"&&e.length>0||typeof e=="function"?!1:jo(e)&&Object.keys(e).length===0:!0}function Do(e){if(typeof e=="number")return e%1===0;if(typeof e=="string"){let t=parseInt(e,10);return!Number.isNaN(t)&&t%1===0&&t.toString()===e}return!1}function Vo(e){if(typeof e=="number")return e%1!==0;if(typeof e=="string"){let t=parseFloat(e);return!Number.isNaN(t)&&t%1!==0&&t.toString()===e}return!1}function Lo(e){return typeof e=="string"&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function Fo(e){return typeof e=="boolean"}function Dr(e){let t;if(Lo(e))t=e;else if(Do(e))t=parseInt(e,10);else if(Vo(e))t=parseFloat(e);else if(Fo(e))t=!!e;else throw new Error("Unsupported value type");return t}var Nn=class extends Rs{},Cu=class extends Nn{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[qe.and,qe.or],this.allowedComparators=e?.allowedComparators??[j.eq,j.ne,j.gt,j.gte,j.lt,j.lte]}formatFunction(e){if(e in j){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw new Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(e in qe){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw new Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${e}`}visitOperation(e){let t=e.args?.map(r=>r.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:Dr(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,r="and",n=!1){if(!(Te(e)&&Te(t))){if(Te(e)||r==="replace")return Te(t)?void 0:t;if(Te(t))return n?e:r==="and"?void 0:e;if(r==="and")return{$and:[e,t]};if(r==="or")return{$or:[e,t]};throw new Error("Unknown merge type")}}};var xu=class extends Nn{allowedOperators=[qe.and,qe.or];allowedComparators=[j.eq,j.ne,j.gt,j.gte,j.lt,j.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(e){switch(e){case"string":return[j.eq,j.ne,j.gt,j.gte,j.lt,j.lte];case"number":return[j.eq,j.ne,j.gt,j.gte,j.lt,j.lte];case"boolean":return[j.eq,j.ne];default:throw new Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case j.eq:return(t,r)=>t===r;case j.ne:return(t,r)=>t!==r;case j.gt:return(t,r)=>t>r;case j.gte:return(t,r)=>t>=r;case j.lt:return(t,r)=>t<r;case j.lte:return(t,r)=>t<=r;default:throw new Error("Unknown comparator")}}getOperatorFunction(e){switch(e){case qe.and:return(t,r)=>t&&r;case qe.or:return(t,r)=>t||r;default:throw new Error("Unknown operator")}}visitOperation(e){let{operator:t,args:r}=e;if(this.allowedOperators.includes(t)){let n=this.getOperatorFunction(t);return s=>r?r.reduce((i,o)=>{let a=o.accept(this);if(typeof a=="function")return n(i,a(s));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(e){let{comparator:t,attribute:r,value:n}=e,s=[j.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof n).includes(t))throw new Error(`'${t}' comparator not allowed to be used with ${typeof n}`);let i=this.getComparatorFunction(t);return o=>{let a=o.metadata[r];return a===void 0?!!s.includes(t):i(a,Dr(n))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(e){if(!e.filter)return{};let t=e.filter?.accept(this);if(typeof t!="function")throw new Error("Structured query filter is not a function");return{filter:t}}mergeFilters(e,t,r="and"){if(!(Te(e)&&Te(t))){if(Te(e)||r==="replace")return Te(t)?void 0:t;if(Te(t))return r==="and"?void 0:e;if(r==="and")return n=>e(n)&&t(n);if(r==="or")return n=>e(n)||t(n);throw new Error("Unknown merge type")}}};var Tu=T({BaseTranslator:()=>Nn,BasicTranslator:()=>Cu,Comparators:()=>j,Comparison:()=>Su,Expression:()=>Ms,FilterDirective:()=>$s,FunctionalTranslator:()=>xu,Operation:()=>ku,Operators:()=>qe,StructuredQuery:()=>Eu,Visitor:()=>Rs,castValue:()=>Dr,isBoolean:()=>Fo,isFilterEmpty:()=>Te,isFloat:()=>Vo,isInt:()=>Do,isObject:()=>jo,isString:()=>Lo});function Rn(e){if(e==null||typeof e!="object")return!1;let t=e;return typeof t.text<"u"&&typeof t.toolCalls<"u"&&typeof t.reasoning<"u"&&typeof t.usage<"u"&&typeof t.output<"u"&&typeof t[Symbol.asyncIterator]=="function"}function Iu(e,t,r){return e==null?!1:Object.entries(t).every(([n,s])=>r(e[n],s))}function Au(e,t,r){return e==null?!1:Iu(e,t,r)}function Ou(e){return e.content.find(t=>t.type==="text")?.text}function gd(e,t,r){if(t.id!==void 0&&e.id!==t.id||t.text!==void 0&&Ou(e)!==t.text)return!1;if(t.toolCalls!==void 0){let n=e.tool_calls??[];if(n.length!==t.toolCalls.length)return!1;for(let s=0;s<t.toolCalls.length;s++){let i=n[s],o=t.toolCalls[s];if(i?.name!==o.name||!r(i.args,o.args))return!1}}return!(t.usage!==void 0&&!Au(e.usage_metadata,t.usage,r)||t.responseMetadata!==void 0&&!Iu(e.response_metadata,t.responseMetadata,r))}function Mn(e,t,r){return{pass:!1,message:()=>`${r.matcherHint(t)}
22
+
23
+ Expected: ChatModelStream (return value of model.streamEvents("Hello"))
24
+ Received: ${r.printReceived(e)}`,actual:e,expected:"ChatModelStream"}}function $n(e,t){return t?!e:e}async function _d(e,t){let{isNot:r,utils:n}=this,s="toHaveStreamText";if(!Rn(e))return Mn(e,s,n);let i=await e.text;return{pass:$n(i===t,r),message:()=>`${n.matcherHint(s,void 0,void 0,{isNot:r})}
25
+
26
+ Expected stream text: ${r?"not ":""}${n.printExpected(t)}
27
+ Received stream text: ${n.printReceived(i)}`,actual:i,expected:t}}async function yd(e,t){let{isNot:r,utils:n}=this,s="toHaveStreamReasoning";if(!Rn(e))return Mn(e,s,n);let i=await e.reasoning;return{pass:$n(i===t,r),message:()=>`${n.matcherHint(s,void 0,void 0,{isNot:r})}
28
+
29
+ Expected stream reasoning: ${r?"not ":""}${n.printExpected(t)}
30
+ Received stream reasoning: ${n.printReceived(i)}`,actual:i,expected:t}}async function wd(e,t){let{isNot:r,utils:n}=this,s="toHaveStreamToolCalls";if(!Rn(e))return Mn(e,s,n);let i=await e.toolCalls,o=i.length===t.length&&t.every((a,c)=>{let l=i[c];return l?.name===a.name&&this.equals(l.args,a.args)});return o=$n(o,r),{pass:o,message:()=>`${n.matcherHint(s,void 0,void 0,{isNot:r})}
31
+
32
+ Expected stream tool calls: ${n.printExpected(t)}
33
+ Received stream tool calls: ${n.printReceived(i.map(a=>({name:a.name,args:a.args})))}`,actual:i.map(a=>({name:a.name,args:a.args})),expected:t}}async function vd(e,t){let{isNot:r,utils:n}=this,s="toHaveStreamUsage";if(!Rn(e))return Mn(e,s,n);let i=await e.usage;return{pass:$n(Au(i,t,this.equals),r),message:()=>`${n.matcherHint(s,void 0,void 0,{isNot:r})}
34
+
35
+ Expected stream usage: ${n.printExpected(t)}
36
+ Received stream usage: ${n.printReceived(i)}`,actual:i,expected:t}}async function bd(e,t){let{isNot:r,utils:n}=this,s="toHaveStreamOutput";if(!Rn(e))return Mn(e,s,n);let i=await e.output;return{pass:$n(gd(i,t,this.equals),r),message:()=>`${n.matcherHint(s,void 0,void 0,{isNot:r})}
37
+
38
+ Expected stream output: ${n.printExpected(t)}
39
+ Received stream output: ${n.printReceived({id:i.id,text:Ou(i),tool_calls:i.tool_calls?.map(o=>({name:o.name,args:o.args})),usage_metadata:i.usage_metadata,response_metadata:i.response_metadata})}`,actual:i,expected:t}}var Vr={toHaveStreamText:_d,toHaveStreamReasoning:yd,toHaveStreamToolCalls:wd,toHaveStreamUsage:vd,toHaveStreamOutput:bd};function jn(e){return ee.isInstance(e)?e.constructor.name||e.type:typeof e}function js(e,t){return function(r,n){let{isNot:s,utils:i}=this;if(!t(r))return{pass:!1,message:()=>`${i.matcherHint(`toBe${e}`,void 0,void 0)}
40
+
41
+ Expected: ${s?"not ":""}${e}
42
+ Received: ${jn(r)}`,actual:jn(r),expected:e};if(n===void 0)return{pass:!0,message:()=>`${i.matcherHint(`toBe${e}`,void 0,void 0)}
43
+
44
+ Expected: not ${e}
45
+ Received: ${e}`};let o=r;return typeof n=="string"?{pass:o.content===n,message:()=>`${i.matcherHint(`toBe${e}`,void 0,void 0)}
46
+
47
+ Expected: ${e} with content ${i.printExpected(n)}
48
+ Received: ${e} with content ${i.printReceived(o.content)}`,actual:o.content,expected:n}:{pass:Object.entries(n).every(([a,c])=>this.equals(o[a],c)),message:()=>{let a={};for(let c of Object.keys(n))a[c]=o[c];return`${i.matcherHint(`toBe${e}`,void 0,void 0)}
49
+
50
+ Expected: ${e} matching ${i.printExpected(n)}
51
+ Received: ${e} with ${i.printReceived(a)}`},actual:(()=>{let a={};for(let c of Object.keys(n))a[c]=o[c];return a})(),expected:n}}}var Uo=js("HumanMessage",it.isInstance),Bo=js("AIMessage",Z.isInstance),Ho=js("SystemMessage",vr.isInstance),Wo=js("ToolMessage",wt.isInstance);function Go(e,t){let{isNot:r,utils:n}=this;if(!Z.isInstance(e))return{pass:!1,message:()=>`${n.matcherHint("toHaveToolCalls")}
52
+
53
+ Expected: AIMessage
54
+ Received: ${jn(e)}`};let s=e.tool_calls??[];if(s.length!==t.length)return{pass:!1,message:()=>`${n.matcherHint("toHaveToolCalls")}
55
+
56
+ Expected ${r?"not ":""}${t.length} tool call(s), received ${s.length}`,actual:s.length,expected:t.length};let i=t.filter(o=>!s.some(a=>Object.entries(o).every(([c,l])=>this.equals(a[c],l))));return i.length>0?{pass:!1,message:()=>`${n.matcherHint("toHaveToolCalls")}
57
+
58
+ Could not find matching tool call(s) for:
59
+ ${n.printExpected(i)}
60
+ Received tool calls: ${n.printReceived(s.map(o=>({name:o.name,id:o.id,args:o.args})))}`,actual:s.map(o=>({name:o.name,id:o.id,args:o.args})),expected:t}:{pass:!0,message:()=>`${n.matcherHint("toHaveToolCalls")}
61
+
62
+ Expected AIMessage not to have matching tool calls`}}function Ko(e,t){let{isNot:r,utils:n}=this;if(!Z.isInstance(e))return{pass:!1,message:()=>`${n.matcherHint("toHaveToolCallCount")}
63
+
64
+ Expected: AIMessage
65
+ Received: ${jn(e)}`};let s=e.tool_calls?.length??0;return{pass:s===t,message:()=>`${n.matcherHint("toHaveToolCallCount")}
66
+
67
+ Expected ${r?"not ":""}${t} tool call(s)
68
+ Received: ${s}`,actual:s,expected:t}}function zo(e,t){let{isNot:r,utils:n}=this;if(!Z.isInstance(e))return{pass:!1,message:()=>`${n.matcherHint("toContainToolCall")}
69
+
70
+ Expected: AIMessage
71
+ Received: ${jn(e)}`};let s=e.tool_calls??[];return{pass:s.some(i=>Object.entries(t).every(([o,a])=>this.equals(i[o],a))),message:()=>`${n.matcherHint("toContainToolCall")}
72
+
73
+ Expected AIMessage ${r?"not ":""}to contain a tool call matching ${n.printExpected(t)}
74
+ Received tool calls: ${n.printReceived(s.map(i=>({name:i.name,id:i.id})))}`,actual:s.map(i=>({name:i.name,id:i.id})),expected:t}}function qo(e,t){let{isNot:r,utils:n}=this;if(!Array.isArray(e))return{pass:!1,message:()=>`${n.matcherHint("toHaveToolMessages")}
75
+
76
+ Expected an array of messages
77
+ Received: ${typeof e}`};let s=e.filter(wt.isInstance);if(s.length!==t.length)return{pass:!1,message:()=>`${n.matcherHint("toHaveToolMessages")}
78
+
79
+ Expected ${r?"not ":""}${t.length} tool message(s), found ${s.length}`,actual:s.length,expected:t.length};for(let i=0;i<t.length;i++)if(!Object.entries(t[i]).every(([o,a])=>this.equals(s[i][o],a)))return{pass:!1,message:()=>{let o={};for(let a of Object.keys(t[i]))o[a]=s[i][a];return`${n.matcherHint("toHaveToolMessages")}
80
+
81
+ Tool message at index ${i} did not match:
82
+ Expected: ${n.printExpected(t[i])}
83
+ Received: ${n.printReceived(o)}`},actual:s[i],expected:t[i]};return{pass:!0,message:()=>`${n.matcherHint("toHaveToolMessages")}
84
+
85
+ Expected messages not to contain matching tool messages`}}function Jo(e,t){let{isNot:r,utils:n}=this,s=e?.__interrupt__;if(!(Array.isArray(s)&&s.length>0))return{pass:!1,message:()=>`${n.matcherHint("toHaveBeenInterrupted")}
86
+
87
+ Expected result ${r?"not ":""}to have been interrupted
88
+ Received __interrupt__: ${n.printReceived(s)}`};if(t===void 0)return{pass:!0,message:()=>`${n.matcherHint("toHaveBeenInterrupted")}
89
+
90
+ Expected result not to have been interrupted
91
+ Received ${s.length} interrupt(s)`};let i=s[0]?.value;return{pass:this.equals(i,t),message:()=>`${n.matcherHint("toHaveBeenInterrupted")}
92
+
93
+ Expected interrupt value: ${n.printExpected(t)}
94
+ Received interrupt value: ${n.printReceived(i)}`,actual:i,expected:t}}function Yo(e,t){let{isNot:r,utils:n}=this,s=e?.structuredResponse;return s===void 0?{pass:!1,message:()=>`${n.matcherHint("toHaveStructuredResponse")}
95
+
96
+ Expected result ${r?"not ":""}to have a structured response
97
+ Received structuredResponse: undefined`}:t===void 0?{pass:!0,message:()=>`${n.matcherHint("toHaveStructuredResponse")}
98
+
99
+ Expected result not to have a structured response`}:{pass:Object.entries(t).every(([i,o])=>this.equals(s[i],o)),message:()=>`${n.matcherHint("toHaveStructuredResponse")}
100
+
101
+ Expected structured response: ${n.printExpected(t)}
102
+ Received structured response: ${n.printReceived(s)}`,actual:s,expected:t}}var Pu={toBeHumanMessage:Uo,toBeAIMessage:Bo,toBeSystemMessage:Ho,toBeToolMessage:Wo,toHaveToolCalls:Go,toHaveToolCallCount:Ko,toContainToolCall:zo,toHaveToolMessages:qo,toHaveBeenInterrupted:Jo,toHaveStructuredResponse:Yo,...Vr};function Sd(e){return e.map(t=>t.text).filter(Boolean).join("-")}var Nu=0;function kd(){return Nu+=1,`fake_tc_${Nu}`}var Xo=class Ru extends Cr{queue=[];_alwaysThrowError;_structuredResponseValue;_tools=[];_state={callIndex:0,calls:[]};get calls(){return this._state.calls}get callCount(){return this._state.calls.length}constructor(){super({})}_llmType(){return"fake-model-builder"}_combineLLMOutput(){return[]}respond(t){return typeof t=="function"?this.queue.push({kind:"factory",factory:t}):ee.isInstance(t)?this.queue.push({kind:"message",message:t}):this.queue.push({kind:"error",error:t}),this}respondWithTools(t){return this.queue.push({kind:"toolCalls",toolCalls:t.map(r=>({name:r.name,args:r.args,id:r.id??kd(),type:"tool_call"}))}),this}alwaysThrow(t){return this._alwaysThrowError=t,this}structuredResponse(t){return this._structuredResponseValue=t,this}bindTools(t){let r=[...this._tools,...t],n=new Ru;return n.queue=this.queue,n._alwaysThrowError=this._alwaysThrowError,n._structuredResponseValue=this._structuredResponseValue,n._tools=r,n._state=this._state,n.withConfig({})}withStructuredOutput(t,r){let{_structuredResponseValue:n}=this;return hs.from(async()=>n)}async _generate(t,r,n){this._state.calls.push({messages:[...t],options:r});let s=this._state.callIndex;if(this._state.callIndex+=1,this._alwaysThrowError)throw this._alwaysThrowError;let i=this.queue[s];if(!i)throw new Error(`FakeModel: no response queued for invocation ${s} (${this.queue.length} total queued).`);if(i.kind==="error")throw i.error;if(i.kind==="factory"){let a=i.factory(t);if(!ee.isInstance(a))throw a;return{generations:[{text:"",message:a}]}}if(i.kind==="message")return{generations:[{text:"",message:i.message}]};let o=Sd(t);return{generations:[{text:o,message:new Z({content:o,id:s.toString(),tool_calls:i.toolCalls.length>0?i.toolCalls.map(a=>({...a,type:"tool_call"})):void 0})}],llmOutput:{}}}};function Mu(){return new Xo}function Ds(e){return{async*[Symbol.asyncIterator](){for(let t of e)yield t}}}function Vs(e="test-model"){let t=Dn(e),r=t[t.length-1];return t[t.length-1]={...r,usage:{prompt_tokens:10,completion_tokens:2,total_tokens:12}},t}function Dn(e="test-model"){return[{id:"chatcmpl-text",model:e,choices:[{index:0,delta:{role:"assistant",content:"Hello"},finish_reason:null}]},{id:"chatcmpl-text",model:e,choices:[{index:0,delta:{content:" world"},finish_reason:null}]},{id:"chatcmpl-text",model:e,choices:[{index:0,delta:{},finish_reason:"stop"}]}]}function Ls(e="test-model"){return[{id:"chatcmpl-reason",model:e,choices:[{index:0,delta:{role:"assistant",reasoning_content:"Let me reason..."},finish_reason:null}]},{id:"chatcmpl-reason",model:e,choices:[{index:0,delta:{content:"Answer."},finish_reason:null}]},{id:"chatcmpl-reason",model:e,choices:[{index:0,delta:{},finish_reason:"stop"}]}]}function Fs(e="test-model"){return[{id:"chatcmpl-tools",model:e,choices:[{index:0,delta:{role:"assistant",content:"Let me search."},finish_reason:null}]},{id:"chatcmpl-tools",model:e,choices:[{index:0,delta:{tool_calls:[{index:0,id:"call_abc",type:"function",function:{name:"web_search",arguments:'{"query"'}}]},finish_reason:null}]},{id:"chatcmpl-tools",model:e,choices:[{index:0,delta:{tool_calls:[{index:0,function:{arguments:':"weather"}'}}]},finish_reason:null}]},{id:"chatcmpl-tools",model:e,choices:[{index:0,delta:{},finish_reason:"tool_calls"}]}]}function Us(e){let t=new TextEncoder;return new Response(new ReadableStream({start(r){for(let n of e)r.enqueue(t.encode(`data: ${JSON.stringify(n)}
103
+
104
+ `));r.close()}}),{status:200,headers:{"Content-Type":"text/event-stream"}})}var $u=T({FakeBuiltModel:()=>Xo,asAsyncIterable:()=>Ds,fakeModel:()=>Mu,langchainMatchers:()=>Pu,openAIReasoningTextChunks:()=>Ls,openAITextOnlyChunks:()=>Dn,openAITextOnlyChunksWithUsage:()=>Vs,openAIToolCallChunks:()=>Fs,sseResponseFromOpenAIChunks:()=>Us,streamMatchers:()=>Vr,toBeAIMessage:()=>Bo,toBeHumanMessage:()=>Uo,toBeSystemMessage:()=>Ho,toBeToolMessage:()=>Wo,toContainToolCall:()=>zo,toHaveBeenInterrupted:()=>Jo,toHaveStructuredResponse:()=>Yo,toHaveToolCallCount:()=>Ko,toHaveToolCalls:()=>Go,toHaveToolMessages:()=>qo});var ju=T({RunCollectorCallbackHandler:()=>Ed}),Ed=class extends gr{name="run_collector";exampleId;tracedRuns;constructor({exampleId:e}={}){super({_awaitHandler:!0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){let t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}};var Du=T({});var Vu=T({context:()=>Cd});function Cd(e,...t){let r=e.raw,n="";for(let s=0;s<r.length;s++){let i=r[s].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(n+=i,s<t.length){let o=xd(t[s],n);n+=typeof o=="string"?o:JSON.stringify(o)}}return n=Td(n),n=n.trim(),n=n.replace(/\\n/g,`
105
+ `),n}function xd(e,t){if(typeof e!="string"||!e.includes(`
106
+ `))return e;let r=t.slice(t.lastIndexOf(`
107
+ `)+1).match(/^(\s+)/);if(r){let n=r[1];return e.replace(/\n/g,`
108
+ ${n}`)}return e}function Td(e){let t=e.split(`
109
+ `),r=null;for(let n of t){let s=n.match(/^(\s+)\S+/);if(s){let i=s[1].length;r===null?r=i:r=Math.min(r,i)}}return r===null?e:t.map(n=>n[0]===" "||n[0]===" "?n.slice(r):n).join(`
110
+ `)}var Lu=T({EventStreamContentType:()=>Id,convertEventStreamToIterableReadableDataStream:()=>Od,getBytes:()=>Fu,getLines:()=>Uu,getMessages:()=>Bu}),Id="text/event-stream";async function Fu(e,t){if(e instanceof ReadableStream){let r=e.getReader();for(;;){let n=await r.read();if(n.done){t(new Uint8Array,!0);break}t(n.value)}}else try{for await(let r of e)t(new Uint8Array(r));t(new Uint8Array,!0)}catch(r){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${r.message}`].join(`
111
+ `))}}function Uu(e){let t,r,n,s=!1;return function(o,a){if(a){e(o,0,!0);return}t===void 0?(t=o,r=0,n=-1):t=Ad(t,o);let c=t.length,l=0;for(;r<c;){s&&(t[r]===10&&(l=++r),s=!1);let u=-1;for(;r<c&&u===-1;++r)switch(t[r]){case 58:n===-1&&(n=r-l);break;case 13:s=!0;case 10:u=r}if(u===-1)break;e(t.subarray(l,u),n),l=r,n=-1}l===c?t=void 0:l!==0&&(t=t.subarray(l),r-=l)}}function Bu(e,t,r){let n=Qo(),s=new TextDecoder;return function(o,a,c){if(c){Pd(n)||(e?.(n),n=Qo());return}if(o.length===0)e?.(n),n=Qo();else if(a>0){let l=s.decode(o.subarray(0,a)),u=a+(o[a+1]===32?2:1),h=s.decode(o.subarray(u));switch(l){case"data":n.data=n.data?n.data+`
112
+ `+h:h;break;case"event":n.event=h;break;case"id":t?.(n.id=h);break;case"retry":{let p=parseInt(h,10);Number.isNaN(p)||r?.(n.retry=p);break}}}}}function Ad(e,t){let r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function Qo(){return{data:"",event:"",id:"",retry:void 0}}function Od(e,t){let r=new ReadableStream({async start(n){let s=Bu(o=>{if(o.event==="error")throw new Error(o.data??"Unspecified event streaming error.");o.event==="metadata"?t?.(o):o.data&&n.enqueue(o.data)});await Fu(e,Uu((o,a,c)=>{s(o,a,c),c&&n.close()}))}});return on.fromReadableStream(r)}function Pd(e){return e.data===""&&e.event===""&&e.id===""&&e.retry===void 0}var Hu=T({});function Bs(e,t){let r=0,n=0,s=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i],n+=e[i]*e[i],s+=t[i]*t[i];return r/(Math.sqrt(n)*Math.sqrt(s))}function Wu(e,t){let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r}function Nd(e,t){let r=0;for(let n=0;n<e.length;n++)r+=(e[n]-t[n])*(e[n]-t[n]);return r}function Gu(e,t){return Math.sqrt(Nd(e,t))}var Ku=T({cosineSimilarity:()=>Zo,euclideanDistance:()=>$d,innerProduct:()=>Md,matrixFunc:()=>Hs,maximalMarginalRelevance:()=>jd,normalize:()=>Rd});function Hs(e,t,r){if(e.length===0||e[0].length===0||t.length===0||t[0].length===0)return[[]];if(e[0].length!==t[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(n=>t.map(s=>r(n,s)).map(s=>Number.isNaN(s)?0:s))}function Rd(e,t=!1){let r=Dd(e);return e.map(n=>n.map(s=>t?1-s/r:s/r))}function Zo(e,t){return Hs(e,t,Bs)}function Md(e,t){return Hs(e,t,Wu)}function $d(e,t){return Hs(e,t,Gu)}function jd(e,t,r=.5,n=4){if(Math.min(n,t.length)<=0)return[];let s=Zo(Array.isArray(e[0])?e:[e],t)[0],i=zu(s).maxIndex,o=[t[i]],a=[i];for(;a.length<Math.min(n,t.length);){let c=-1/0,l=-1,u=Zo(t,o);s.forEach((h,p)=>{if(a.includes(p))return;let d=Math.max(...u[p]),f=r*h-(1-r)*d;f>c&&(c=f,l=p)}),o.push(t[l]),a.push(l)}return a}function zu(e){if(e.length===0)return{maxIndex:-1,maxValue:NaN};let t=e[0],r=0;for(let n=1;n<e.length;n+=1)e[n]>t&&(r=n,t=e[n]);return{maxIndex:r,maxValue:t}}function Dd(e){return e.reduce((t,r)=>Math.max(t,zu(r).maxValue),0)}var qu=T({isCloudMetadata:()=>ea,isLocalhost:()=>ta,isPrivateIp:()=>Zu,isSafeUrl:()=>Gd,isSameOrigin:()=>Kd,validateSafeUrl:()=>eh}),Vd=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8","169.254.0.0/16","0.0.0.0/8","::1/128","fc00::/7","fe80::/10","ff00::/8"],Ld=["169.254.169.254","169.254.170.2","100.100.100.200"],Fd=["metadata.google.internal","metadata","instance-data"],Ud=["localhost","localhost.localdomain"],Bd=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function Ju(e){return Bd.test(e)}function Ws(e){return Qu(e)!==null}function Yu(e){return Ju(e)||Ws(e)}function Xu(e){if(Ju(e))return e.split(".").map(t=>parseInt(t,10));if(Ws(e)){let t=Qu(e);if(!t)return null;let r=t.split(":"),n=[];for(let s of r)n.push(parseInt(s,16));return n}return null}function Qu(e){if(!e||typeof e!="string"||!e.includes(":")||!/^[0-9a-fA-F:]+$/.test(e))return null;let t=e;if(t.includes("::")){let n=t.split("::");if(n.length>2)return null;let[s,i]=n,o=s?s.split(":"):[],a=i?i.split(":"):[],c=8-(o.length+a.length);if(c<0)return null;let l=Array(c).fill("0");t=[...o,...l,...a].filter(u=>u!=="").join(":")}let r=t.split(":");if(r.length!==8)return null;for(let n of r)if(n.length===0||n.length>4||!/^[0-9a-fA-F]+$/.test(n))return null;return r.map(n=>n.padStart(4,"0").toLowerCase()).join(":")}function Hd(e){let[t,r]=e.split("/");if(!t||!r)return null;let n=Xu(t);if(!n)return null;let s=parseInt(r,10);if(isNaN(s))return null;let i=Ws(t);return i&&s>128||!i&&s>32?null:{addr:n,prefixLen:s,isIpv6:i}}function Wd(e,t){let r=Xu(e);if(!r)return!1;let n=Hd(t);if(!n)return!1;let s=Ws(e);if(s!==n.isIpv6)return!1;let{addr:i,prefixLen:o}=n;if(s)for(let a=0;a<Math.ceil(o/16);a++){let c=65535<<16-Math.min(16,o-a*16)&65535;if((r[a]&c)!==(i[a]&c))return!1}else for(let a=0;a<Math.ceil(o/8);a++){let c=255<<8-Math.min(8,o-a*8)&255;if((r[a]&c)!==(i[a]&c))return!1}return!0}function Zu(e){if(!Yu(e))return!1;for(let t of Vd)if(Wd(e,t))return!0;return!1}function ea(e,t){if(Ld.includes(t||""))return!0;let r=e.toLowerCase();return!!Fd.includes(r)}function ta(e,t){if(t&&(t==="127.0.0.1"||t==="::1"||t==="0.0.0.0"||t.startsWith("127.")))return!0;let r=e.toLowerCase();return!!Ud.includes(r)}function eh(e,t){let r=t?.allowPrivate??!1,n=t?.allowHttp??!1;try{let s;try{s=new URL(e)}catch{throw new Error(`Invalid URL: ${e}`)}let i=s.hostname;if(!i)throw new Error("URL missing hostname.");if(ea(i))throw new Error(`URL points to cloud metadata endpoint: ${i}`);if(ta(i)){if(!r)throw new Error(`URL points to localhost: ${i}`);return e}let o=s.protocol;if(o!=="http:"&&o!=="https:")throw new Error(`Invalid URL scheme: ${o}. Only http and https are allowed.`);if(o==="http:"&&!n)throw new Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true.");if(Yu(i)){let a=i;if(ta(i,a)){if(!r)throw new Error(`URL points to localhost: ${i}`);return e}if(ea(i,a))throw new Error(`URL resolves to cloud metadata IP: ${a} (${i})`);if(Zu(a)&&!r)throw new Error(`URL resolves to private IP: ${a} (${i}). Set allowPrivate: true to allow.`);return e}return e}catch(s){throw s&&typeof s=="object"&&"message"in s?s:new Error(`URL validation failed: ${s}`)}}function Gd(e,t){try{return eh(e,t),!0}catch{return!1}}function Kd(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}var th=class extends Cr{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(e,t,r){if(t?.stop?.length)return{generations:[{message:new Z(t.stop[0]),text:t.stop[0]}]};let n=e.map(s=>typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2)).join(`
113
+ `);return await r?.handleLLMNewToken(n),{generations:[{message:new Z(n),text:n}],llmOutput:{}}}},rh=class nh extends Cr{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:t=50,responses:r=[],chunks:n=[],toolStyle:s="openai",thrownErrorString:i,...o}){super(o),this.sleep=t,this.responses=r,this.chunks=n,this.toolStyle=s,this.thrownErrorString=i}_llmType(){return"fake"}bindTools(t){let r=[...this.tools,...t],n=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:We(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:We(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:We(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:We(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:n}]:n,i=new nh({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return i.tools=r,i.withConfig({tools:s})}async _generate(t,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let s=this.responses?.[0]?.content??t[0].content??"";return{generations:[{text:"",message:new Z({content:s,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(t,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(let o of this.chunks){let a=new ls({message:new yr({content:o.content,tool_calls:o.tool_calls,additional_kwargs:o.additional_kwargs??{}}),text:o.content?.toString()??""});if(r.signal?.aborted)break;yield a,await n?.handleLLMNewToken(o.content,void 0,void 0,void 0,void 0,{chunk:a})}return}let s=this.responses?.[0]??new Z(typeof t[0].content=="string"?t[0].content:""),i=typeof s.content=="string"?s.content:"";for(let o of i){await new Promise(c=>setTimeout(c,this.sleep));let a=new ls({message:new yr({content:o}),text:o});if(r.signal?.aborted)break;yield a,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:a})}}},sh=class ih extends Cr{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(t){super(t);let{responses:r,sleep:n,emitCustomEvent:s,generationInfo:i}=t;this.responses=r,this.sleep=n,this.emitCustomEvent=s??this.emitCustomEvent,this.generationInfo=i}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(t,r,n){if(await this._sleepIfRequested(),r?.thrownErrorString)throw new Error(r.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0}),r?.stop?.length)return{generations:[this._formatGeneration(r.stop[0])]};{let s=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(s)],llmOutput:{}}}}_formatGeneration(t){return{message:new Z(t),text:t}}async*_streamResponseChunks(t,r,n){let s=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0});let i=[...s];for(let o=0;o<i.length;o++){let a=i[o],c=o===i.length-1;if(await this._sleepIfRequested(),r?.thrownErrorString)throw new Error(r.thrownErrorString);let l=this._createResponseChunk(a,c?this.generationInfo:void 0);if(r.signal?.aborted)break;yield l,n?.handleLLMNewToken(a)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(t=>{setTimeout(()=>t(),this.sleep)})}_createResponseChunk(t,r){return new ls({message:new yr({content:t}),text:t,generationInfo:r})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let r=[...this.tools,...t],n=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:We(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:We(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:We(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:We(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:n}]:n,i=new ih({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return i.tools=r,i.toolStyle=this.toolStyle,i.i=this.i,i.withConfig({tools:s})}withStructuredOutput(t,r){return hs.from(async n=>{let s=await this.invoke(n);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")})}};var oh=class extends Ki{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(t=>this.embedQuery(t)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");let r=t.length%this.vectorSize,n=r===0?0:this.vectorSize-r,s=t.length+n;t=t.padEnd(s," ");let i=t.length/this.vectorSize,o=[];for(let a=0;a<t.length;a+=i)o.push(t.slice(a,a+i));return o.map(a=>{let c=0;for(let l=0;l<a.length;l+=1)c+=a===" "?0:a.charCodeAt(l);return c%26/26})}},ah=class extends Ki{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}};var ch=class extends qi{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let n=this.response??e;return await r?.handleLLMNewToken(n),n}},lh=class extends qi{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let n=this.responses?.[0];this.responses=this.responses?.slice(1);for(let s of n??e)await new Promise(i=>setTimeout(i,this.sleep)),yield{text:s,generationInfo:{}},await r?.handleLLMNewToken(s)}};var uh=class extends lo{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new it(e))}async addAIMessage(e){this.messages.push(new Z(e))}async clear(){this.messages=[]}},hh=class extends Cs{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},ph=class extends gr{name="fake_tracer";runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}};var fh=class extends rl{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(e){return e.split(",").map(t=>t.trim())}};var dh=class extends Pn{lc_namespace=["test","fake"];output=[new Re({pageContent:"foo"}),new Re({pageContent:"bar"})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}};var mh=class extends G{lc_namespace=["tests","fake"];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}};var gh=class extends ml{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}};var _h=class extends gr{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}};var yh=T({SaveableVectorStore:()=>zd,VectorStore:()=>Ks,VectorStoreRetriever:()=>Gs}),Gs=class extends Pn{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(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){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(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},Ks=class extends Ue{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,r=void 0,n=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)).map(s=>s[0])}async similaritySearchWithScore(e,t=4,r=void 0,n=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)}static fromTexts(e,t,r,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,r,n,s,i){if(typeof e=="number")return new Gs({vectorStore:this,k:e,filter:t,tags:[...n??[],this._vectorstoreType()],metadata:s,verbose:i,callbacks:r});{let o={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType==="mmr"?new Gs({...o,searchKwargs:e.searchKwargs}):new Gs({...o})}}},zd=class extends Ks{static load(e,t){throw new Error("Not implemented")}};var wh=class vh extends Ks{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(t,{similarity:r,...n}={}){super(t,n),this.similarity=r??Bs}async addDocuments(t){let r=t.map(({pageContent:n})=>n);return this.addVectors(await this.embeddings.embedDocuments(r),t)}async addVectors(t,r){let n=t.map((s,i)=>({content:r[i].pageContent,embedding:s,metadata:r[i].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(t,r,n){let s=o=>n?n(new Re({metadata:o.metadata,pageContent:o.content})):!0,i=this.memoryVectors.filter(s);return i.map((o,a)=>({similarity:this.similarity(t,o.embedding),index:a})).sort((o,a)=>o.similarity>a.similarity?-1:0).slice(0,r).map(o=>[new Re({metadata:i[o.index].metadata,pageContent:i[o.index].content}),o.similarity])}static async fromTexts(t,r,n,s){let i=[];for(let o=0;o<t.length;o+=1){let a=Array.isArray(r)?r[o]:r,c=new Re({pageContent:t[o],metadata:a});i.push(c)}return vh.fromDocuments(i,n,s)}static async fromDocuments(t,r,n){let s=new this(r,n);return await s.addDocuments(t),s}static async fromExistingIndex(t,r){return new this(t,r)}};var bh=T({FakeChatMessageHistory:()=>uh,FakeChatModel:()=>th,FakeEmbeddings:()=>ah,FakeLLM:()=>ch,FakeListChatMessageHistory:()=>hh,FakeListChatModel:()=>sh,FakeRetriever:()=>dh,FakeRunnable:()=>mh,FakeSplitIntoListParser:()=>fh,FakeStreamingChatModel:()=>rh,FakeStreamingLLM:()=>lh,FakeTool:()=>gh,FakeTracer:()=>ph,FakeVectorStore:()=>wh,SingleRunExtractor:()=>_h,SyntheticEmbeddings:()=>oh,asAsyncIterable:()=>Ds,openAIReasoningTextChunks:()=>Ls,openAITextOnlyChunks:()=>Dn,openAITextOnlyChunksWithUsage:()=>Vs,openAIToolCallChunks:()=>Fs,sseResponseFromOpenAIChunks:()=>Us,streamMatchers:()=>Vr});var Sh=T({agents:()=>Pl,caches:()=>Gc,callbacks__base:()=>dc,callbacks__manager:()=>Ec,callbacks__promises:()=>kc,chat_history:()=>Nl,decisions:()=>jl,document_loaders__base:()=>Dl,document_loaders__langsmith:()=>Vl,documents:()=>Fl,embeddings:()=>Xc,errors:()=>yc,example_selectors:()=>Jl,index:()=>Yl,indexing:()=>Zl,language_models__base:()=>Zc,language_models__chat_models:()=>ul,language_models__compat:()=>ll,language_models__event:()=>eu,language_models__llms:()=>hl,language_models__openai_completions_stream:()=>pl,language_models__profile:()=>tu,language_models__stream:()=>cl,language_models__structured_output:()=>al,load__serializable:()=>uc,memory:()=>ru,messages:()=>Vc,messages__tool:()=>wc,output_parsers:()=>il,output_parsers__openai_functions:()=>iu,output_parsers__openai_tools:()=>fl,outputs:()=>Ac,prompt_values:()=>Lc,prompts:()=>_u,retrievers:()=>wu,retrievers__document_compressors:()=>yu,runnables:()=>tl,runnables__graph:()=>Dc,singletons:()=>xc,stores:()=>vu,structured_query:()=>Tu,testing:()=>$u,tools:()=>dl,tracers__base:()=>gc,tracers__console:()=>_c,tracers__log_stream:()=>Ic,tracers__run_collector:()=>ju,tracers__tracer_langchain:()=>Sc,types__stream:()=>Du,utils__async_caller:()=>Oc,utils__chunk_array:()=>gl,utils__context:()=>Vu,utils__env:()=>pc,utils__event_source_parse:()=>Lu,utils__format:()=>Hu,utils__function_calling:()=>_l,utils__gateway:()=>yl,utils__hash:()=>Wc,utils__json_patch:()=>sl,utils__json_schema:()=>jc,utils__math:()=>Ku,utils__ssrf:()=>qu,utils__standard_schema:()=>$c,utils__stream:()=>Tc,utils__testing:()=>bh,utils__tiktoken:()=>Qc,utils__types:()=>ol,utils__uuid:()=>nc,vectorstores:()=>yh});var qd=50;function Jd(e){let t={};for(let r=e;r&&r.prototype;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r.prototype,"lc_aliases"));return Object.entries(t).reduce((r,[n,s])=>(r[s]=n,r),{})}async function zs(e){let{optionalImportsMap:t,optionalImportEntrypoints:r,importMap:n,secretsMap:s,secretsFromEnv:i,path:o,depth:a,maxDepth:c}=this,l=o.join(".");if(a>c)throw new Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!="object"||e==null)return e;if(Array.isArray(e))return Promise.all(e.map((p,d)=>zs.call({...this,path:[...o,`${d}`],depth:a+1},p)));let u=e;if(cc(u))return lc(u);if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="secret"){let[p]=u.id;if(p in s)return s[p];if(i){let d=fc(p);if(d)return d}throw new Error(`Missing secret "${p}" at ${l}`)}if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="not_implemented"){let p=JSON.stringify(u);throw new Error(`Trying to load an object that doesn't implement serialization: ${l} -> ${p}`)}if("lc"in u&&"type"in u&&"id"in u&&"kwargs"in u&&u.lc===1&&u.type==="constructor"){let p=u,d=JSON.stringify(p),[f,...m]=p.id.slice().reverse(),_=m.reverse(),y={langchain_core:Sh,langchain:n},g=null,w=[_.join("/")];_[0]==="langchain_community"&&w.push(["langchain",..._.slice(1)].join("/"));let S=w.find(P=>P in t);if(Ol.concat(r).includes(_.join("/"))||S)if(S!==void 0)g=await t[S];else throw new Error(`Missing key "${_.join("/")}" for ${l} in load(optionalImportsMap={})`);else{let P;if(_[0]==="langchain"||_[0]==="langchain_core")P=y[_[0]],_.shift();else throw new Error(`Invalid namespace: ${l} -> ${d}`);if(_.length===0)throw new Error(`Invalid namespace: ${l} -> ${d}`);let K;do{if(K=_.join("__"),K in P)break;_.pop()}while(_.length>0);K in P&&(g=P[K])}if(typeof g!="object"||g===null)throw new Error(`Invalid namespace: ${l} -> ${d}`);let k=g[f]??Object.values(g).find(P=>typeof P=="function"&&hc(P)===f);if(typeof k!="function")throw new Error(`Invalid identifer: ${l} -> ${d}`);let C=await zs.call({...this,path:[...o,"kwargs"],depth:a+1},p.kwargs),O=new k(ac(C,oc,Jd(k)));return Object.defineProperty(O.constructor,"name",{value:f}),O}let h={};for(let[p,d]of Object.entries(u))h[p]=await zs.call({...this,path:[...o,p],depth:a+1},d);return h}async function kh(e,t){let r=JSON.parse(e),n={optionalImportsMap:t?.optionalImportsMap??{},optionalImportEntrypoints:t?.optionalImportEntrypoints??[],secretsMap:t?.secretsMap??{},secretsFromEnv:t?.secretsFromEnv??!1,importMap:t?.importMap??{},path:["$"],depth:0,maxDepth:t?.maxDepth??qd};return zs.call(n,r)}function Yd(e){return e!==null&&e.lc===1&&e.type==="constructor"&&Array.isArray(e.id)}function Xd(e){return e.lc===2&&e.type==="undefined"}function Qd(e){return e.lc===2&&e.type==="delta_snapshot"&&Object.prototype.hasOwnProperty.call(e,"value")}function Zd(e){return e.lc===2&&e.type==="constructor"}function Vn(e,t){return Array.isArray(e.id)&&e.id.length===1&&e.id[0]===t}function Ln(e){return e.method===void 0||e.method===null}function ra(e){return Array.isArray(e.args)&&e.args.length===1&&Array.isArray(e.args[0])}function em(e){return e.every(t=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=255)}function tm(e){if(Vn(e,"Set")&&Ln(e))return ra(e)?new Set(e.args[0]):void 0;if(Vn(e,"Map")&&Ln(e))return!ra(e)||!e.args[0].every(t=>Array.isArray(t)&&t.length===2)?void 0:new Map(e.args[0]);if(Vn(e,"RegExp")&&Ln(e)){if(!Array.isArray(e.args)||e.args.length!==2||typeof e.args[0]!="string"||typeof e.args[1]!="string")return;try{return new RegExp(e.args[0],e.args[1])}catch{return}}if(Vn(e,"Error")&&Ln(e))return!Array.isArray(e.args)||e.args.length!==1||typeof e.args[0]!="string"?void 0:new Error(e.args[0]);if(Vn(e,"Uint8Array")&&(Ln(e)||e.method==="from"))return!ra(e)||!em(e.args[0])?void 0:new Uint8Array(e.args[0])}async function na(e){if(e&&typeof e=="object"){if(Array.isArray(e))return await Promise.all(e.map(t=>na(t)));{let t={};for(let[r,n]of Object.entries(e))t[r]=await na(n);return Xd(t)?void 0:Qd(t)?new Ar(t.value):Zd(t)?tm(t)??t:Yd(t)?kh(JSON.stringify(t)):t}}return e}function qs(e,t,r,n){return{lc:2,type:"constructor",id:[e.name],method:t??null,args:r??[],kwargs:n??{}}}function rm(e){return e===void 0?{lc:2,type:"undefined"}:e instanceof Ar?{lc:2,type:"delta_snapshot",value:e.value}:e instanceof Set||e instanceof Map?qs(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?qs(RegExp,void 0,[e.source,e.flags]):e instanceof Error?qs(Error,void 0,[e.message]):e?.lg_name==="Send"?{node:e.node,args:e.args,...e.timeout!==void 0?{timeout:e.timeout}:{}}:e instanceof Uint8Array?qs(Uint8Array,"from",[Array.from(e)]):e}var Fn=class{_dumps(e){return new TextEncoder().encode(Al(e,(t,r)=>rm(r)))}async dumpsTyped(e){return e instanceof Uint8Array?["bytes",e]:["json",this._dumps(e)]}async _loads(e){return na(JSON.parse(e))}async loadsTyped(e,t){if(e==="bytes")return typeof t=="string"?new TextEncoder().encode(t):t;if(e==="json")return this._loads(typeof t=="string"?t:new TextDecoder().decode(t));throw new Error(`Unknown serialization type: ${e}`)}};function sa(e){if(typeof e!="object"||e===null)return e;let t=Array.isArray(e)?[]:{};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=sa(e[r]));return t}function lr(){return{v:4,id:yn(0),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function Je(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values??{}},channel_versions:{...e.channel_versions??{}},versions_seen:sa(e.versions_seen??{})}}function Un(e,t="",r=0){return[e,t,r]}function Bn(e,t){return e[0]!==t[0]?Eh(e[0],t[0]):e[1]!==t[1]?Eh(e[1],t[1]):e[2]<t[2]?-1:e[2]>t[2]?1:0}function Eh(e,t){let r=0,n=0;for(;r<e.length&&n<t.length;){let s=e.codePointAt(r),i=t.codePointAt(n);if(s!==i)return s<i?-1:1;r+=s>65535?2:1,n+=i>65535?2:1}return r>=e.length&&n>=t.length?0:r>=e.length?-1:1}var Js=class{serde=new Fn;constructor(e){this.serde=e||this.serde}toJSON(){return`[${this.constructor.name}]`}async get(e){let t=await this.getTuple(e);return t?t.checkpoint:void 0}async getDeltaChannelHistory(e){let{config:t,channels:r}=e;if(r.length===0)return{};let n={},s={},i=new Set(r);for(let c of r)n[c]=[];let o=(await this.getTuple(t))?.parentConfig;for(;o!=null&&i.size>0;){let c=await this.getTuple(o);if(c===void 0)break;if(c.pendingWrites&&c.pendingWrites.length>0){let l={};for(let u of c.pendingWrites){let h=u[1];i.has(h)&&(l[h]??=[]).push(u)}for(let u of Object.keys(l)){let h=l[u];for(let p=h.length-1;p>=0;p-=1)n[u].push(h[p])}}for(let l of Array.from(i))Object.prototype.hasOwnProperty.call(c.checkpoint.channel_values,l)&&(s[l]=c.checkpoint.channel_values[l],i.delete(l));o=c.parentConfig}let a={};for(let c of r){let l={writes:n[c].slice().reverse()};Object.prototype.hasOwnProperty.call(s,c)&&(l.seed=s[c]),a[c]=l}return a}getNextVersion(e){if(typeof e=="string")throw new Error("Please override this method to use string versions.");return e!==void 0&&typeof e=="number"?e+1:1}};function Ys(e,t){return typeof e=="number"&&typeof t=="number"?Math.sign(e-t):String(e).localeCompare(String(t))}function Hn(...e){return e.reduce((t,r,n)=>n===0?r:Ys(t,r)>=0?t:r)}var Wn={[so]:-1,[ir]:-2,[io]:-3,[oo]:-4},ia=new Set(["thread_id","checkpoint_id","checkpoint_ns","checkpoint_map","langgraph_step","langgraph_node","langgraph_triggers","langgraph_path","langgraph_checkpoint_ns"]);function Xs(e){return e.configurable?.checkpoint_id||e.configurable?.thread_ts||""}var nm=new Set(["__proto__","constructor","prototype"]);function de(e,t,r={}){let{allowEmpty:n=!1}=r;if(typeof t!="string"){let s=t===null?"null":t===void 0?"undefined":Array.isArray(t)?"array":typeof t;throw new Error(`Invalid configurable value for key "${e}": expected a string identifier (got ${s}). This guard protects MemorySaver from prototype pollution.`)}if(!n&&t==="")throw new Error(`Invalid configurable value for key "${e}": empty string is not permitted as an in-memory storage key.`);if(nm.has(t))throw new Error(`Invalid configurable value for key "${e}": value "${t}" is reserved (would mutate Object.prototype). This guard protects MemorySaver from prototype pollution.`)}function oa(e,t,r){return JSON.stringify([e,t,r])}function sm(e){let[t,r,n]=JSON.parse(e);return{threadId:t,checkpointNamespace:r,checkpointId:n}}var Ch=class extends Js{storage=Object.create(null);writes=Object.create(null);constructor(e){super(e)}async _migratePendingSends(e,t,r,n){let s=e,i=oa(t,r,n),o=await Promise.all(Object.values(this.writes[i]??{}).filter(([a,c])=>c===wn).map(async([a,c,l])=>await this.serde.loadsTyped("json",l)));s.channel_values??={},s.channel_values[wn]=o,s.channel_versions??={},s.channel_versions[wn]=Object.keys(s.channel_versions).length>0?Hn(...Object.values(s.channel_versions)):this.getNextVersion(void 0)}_orderedWrites(e,t,r){let n=e===void 0?void 0:this.writes[oa(e,t,r)];if(n===void 0)return[];let s=Object.entries(n).map(([i,o])=>{let a=i.lastIndexOf(","),c=i.slice(0,a),l=Number(i.slice(a+1));return{key:Un(o[3]??"",c,l),entry:[c,l,o]}});return s.sort((i,o)=>Bn(i.key,o.key)),s.map(({entry:i})=>i)}async _deserializeOrderedWrites(e){return Promise.all(e.map(async([,,[t,r,n]])=>[t,r,await this.serde.loadsTyped("json",n)]))}async getTuple(e){let t=e.configurable?.thread_id,r=e.configurable?.checkpoint_ns??"",n=Xs(e);if(t!==void 0&&de("thread_id",t),de("checkpoint_ns",r,{allowEmpty:!0}),n&&de("checkpoint_id",n),n){let s=this.storage[t]?.[r]?.[n];if(s!==void 0){let[i,o,a]=s,c=await this.serde.loadsTyped("json",i);c.v<4&&a!==void 0&&await this._migratePendingSends(c,t,r,a);let l=await this._deserializeOrderedWrites(this._orderedWrites(t,r,n)),u={config:e,checkpoint:c,metadata:await this.serde.loadsTyped("json",o),pendingWrites:l};return a!==void 0&&(u.parentConfig={configurable:{thread_id:t,checkpoint_ns:r,checkpoint_id:a}}),u}}else{let s=this.storage[t]?.[r];if(s!==void 0){n=Object.keys(s).sort().reverse()[0];let[i,o,a]=s[n],c=await this.serde.loadsTyped("json",i);c.v<4&&a!==void 0&&await this._migratePendingSends(c,t,r,a);let l=await this._deserializeOrderedWrites(this._orderedWrites(t,r,n)),u={config:{configurable:{thread_id:t,checkpoint_id:n,checkpoint_ns:r}},checkpoint:c,metadata:await this.serde.loadsTyped("json",o),pendingWrites:l};return a!==void 0&&(u.parentConfig={configurable:{thread_id:t,checkpoint_ns:r,checkpoint_id:a}}),u}}}async*list(e,t){let{before:r,limit:n,filter:s}=t??{};e.configurable?.thread_id!==void 0&&de("thread_id",e.configurable.thread_id),e.configurable?.checkpoint_ns!==void 0&&de("checkpoint_ns",e.configurable.checkpoint_ns,{allowEmpty:!0}),e.configurable?.checkpoint_id&&de("checkpoint_id",e.configurable.checkpoint_id),r?.configurable?.checkpoint_id&&de("checkpoint_id",r.configurable.checkpoint_id);let i=e.configurable?.thread_id?[e.configurable?.thread_id]:Object.keys(this.storage),o=e.configurable?.checkpoint_ns,a=e.configurable?.checkpoint_id;for(let c of i)for(let l of Object.keys(this.storage[c]??{})){if(o!==void 0&&l!==o)continue;let u=this.storage[c]?.[l]??{},h=Object.keys(u).sort().reverse().map(p=>[p,u[p]]);for(let[p,[d,f,m]]of h){if(a&&p!==a||r&&r.configurable?.checkpoint_id&&p>=r.configurable.checkpoint_id)continue;let _=await this.serde.loadsTyped("json",f);if(s&&!Object.entries(s).every(([S,k])=>_[S]===k))continue;if(n!==void 0){if(n<=0)break;n-=1}let y=await this._deserializeOrderedWrites(this._orderedWrites(c,l,p)),g=await this.serde.loadsTyped("json",d);g.v<4&&m!==void 0&&await this._migratePendingSends(g,c,l,m);let w={config:{configurable:{thread_id:c,checkpoint_ns:l,checkpoint_id:p}},checkpoint:g,metadata:_,pendingWrites:y};m!==void 0&&(w.parentConfig={configurable:{thread_id:c,checkpoint_ns:l,checkpoint_id:m}}),yield w}}}async put(e,t,r){let n=Je(t),s=e.configurable?.thread_id,i=e.configurable?.checkpoint_ns??"";if(s===void 0)throw new Error('Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })');de("thread_id",s),de("checkpoint_ns",i,{allowEmpty:!0}),de("checkpoint_id",t.id),this.storage[s]||(this.storage[s]=Object.create(null)),this.storage[s][i]||(this.storage[s][i]=Object.create(null));let[[,o],[,a]]=await Promise.all([this.serde.dumpsTyped(n),this.serde.dumpsTyped(r)]);return this.storage[s][i][t.id]=[o,a,e.configurable?.checkpoint_id],{configurable:{thread_id:s,checkpoint_ns:i,checkpoint_id:t.id}}}async putWrites(e,t,r,n){let s=e.configurable?.thread_id,i=e.configurable?.checkpoint_ns,o=e.configurable?.checkpoint_id;if(s===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })');if(o===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "checkpoint_id" field in its "configurable" property.');de("thread_id",s),de("checkpoint_ns",i,{allowEmpty:!0}),de("checkpoint_id",o),de("task_id",r);let a=oa(s,i,o),c=this.writes[a];this.writes[a]===void 0&&(this.writes[a]=Object.create(null)),await Promise.all(t.map(async([l,u],h)=>{let[,p]=await this.serde.dumpsTyped(u),d=[r,Wn[l]||h],f=`${d[0]},${d[1]}`;d[1]>=0&&c&&f in c||(this.writes[a][f]=[r,l,p,n??""])}))}async deleteThread(e){de("thread_id",e),delete this.storage[e];for(let t of Object.keys(this.writes))sm(t).threadId===e&&delete this.writes[t]}async getDeltaChannelHistory(e){let{config:t,channels:r}=e;if(r.length===0)return{};let n=t.configurable?.thread_id,s=t.configurable?.checkpoint_ns??"";n!==void 0&&de("thread_id",n),de("checkpoint_ns",s,{allowEmpty:!0});let i=this.storage[n]?.[s]??{},o=Xs(t)||Object.keys(i).sort().reverse()[0],a=[],c=(o?i[o]:void 0)?.[2];for(;c!==void 0;){let d=i[c];if(d===void 0)break;a.push(c),c=d[2]}let l={},u={},h=new Set(r);for(let d of r)l[d]=[];for(let d of a){if(h.size===0)break;let f=i[d],m=f!==void 0?await this.serde.loadsTyped("json",f[0]):void 0,_={},y=new Set;if(m!==void 0)for(let w of h)Object.prototype.hasOwnProperty.call(m.channel_values,w)&&m.channel_values[w]!==void 0&&(_[w]=m.channel_values[w],y.add(w));let g=this._orderedWrites(n,s,d);for(let w=g.length-1;w>=0;w-=1){let[S,k,C]=g[w][2];h.has(k)&&l[k].push([S,k,await this.serde.loadsTyped("json",C)])}for(let w of y)u[w]=_[w],h.delete(w)}let p={};for(let d of r){let f={writes:l[d].slice().reverse()};Object.prototype.hasOwnProperty.call(u,d)&&(f.seed=u[d]),p[d]=f}return p}};var pt=class extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}};function Ie(e,t={}){if(e.length===0){if(t.allowEmpty)return;throw new pt("Namespace cannot be empty.")}for(let r of e){if(typeof r!="string")throw new pt(`Invalid namespace label '${r}' found in ${e}. Namespace labels must be strings, but got ${typeof r}.`);if(r.includes("."))throw new pt(`Invalid namespace label '${r}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(r.includes(":"))throw new pt(`Invalid namespace label '${r}'. Namespace labels cannot contain colons (':').`);if(r.includes("\0"))throw new pt("Namespace labels cannot contain NUL bytes.");if(r==="")throw new pt(`Namespace labels cannot be empty strings. Got ${r} in ${e}`)}if(e[0]==="langgraph"&&!t.allowReservedRoot)throw new pt(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var Lr=class{async get(e,t){return Ie(e,{allowEmpty:!0,allowReservedRoot:!0}),(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){Ie(e,{allowEmpty:!0,allowReservedRoot:!0});let{filter:r,limit:n=10,offset:s=0,query:i}=t;return(await this.batch([{namespacePrefix:e,filter:r,limit:n,offset:s,query:i}]))[0]}async put(e,t,r,n){Ie(e),await this.batch([{namespace:e,key:t,value:r,index:n}])}async delete(e,t){Ie(e,{allowEmpty:!0,allowReservedRoot:!0}),await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:r,maxDepth:n,limit:s=100,offset:i=0}=e,o=[];return t&&(Ie(t,{allowEmpty:!0,allowReservedRoot:!0}),o.push({matchType:"prefix",path:t})),r&&(Ie(r,{allowEmpty:!0,allowReservedRoot:!0}),o.push({matchType:"suffix",path:r})),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:n,limit:s,offset:i}]))[0]}start(){}stop(){}};var im=e=>"lg_name"in e&&e.lg_name==="AsyncBatchedStore"?e.store:e,Qs=class extends Lr{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=im(e)}get isRunning(){return this.running}async batch(e){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(e,t){return Ie(e,{allowEmpty:!0,allowReservedRoot:!0}),this.enqueueOperation({namespace:e,key:t})}async search(e,t){Ie(e,{allowEmpty:!0,allowReservedRoot:!0});let{filter:r,limit:n=10,offset:s=0,query:i}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:r,limit:n,offset:s,query:i})}async put(e,t,r){return Ie(e),this.enqueueOperation({namespace:e,key:t,value:r})}async delete(e,t){return Ie(e,{allowEmpty:!0,allowReservedRoot:!0}),this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,r)=>{let n=this.nextKey;this.nextKey+=1,this.queue.set(n,{operation:e,resolve:t,reject:r})})}async processBatchQueue(){for(;this.running;){if(await new Promise(t=>{setTimeout(t,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:n})=>n),r=await this.store.batch(t);e.forEach(({resolve:n},s)=>{n(r[Array.from(e.keys()).indexOf(s)])})}catch(t){e.forEach(({reject:r})=>{r(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}};function Gn(e){if(!e)return[];let t=[],r=[],n=0;for(;n<e.length;){let s=e[n];if(s==="["){r.length&&(t.push(r.join("")),r=[]);let i=1,o=["["];for(n+=1;n<e.length&&i>0;)e[n]==="["?i+=1:e[n]==="]"&&(i-=1),o.push(e[n]),n+=1;t.push(o.join(""));continue}else if(s==="{"){r.length&&(t.push(r.join("")),r=[]);let i=1,o=["{"];for(n+=1;n<e.length&&i>0;)e[n]==="{"?i+=1:e[n]==="}"&&(i-=1),o.push(e[n]),n+=1;t.push(o.join(""));continue}else s==="."?r.length&&(t.push(r.join("")),r=[]):r.push(s);n+=1}return r.length&&t.push(r.join("")),t}function om(e){return typeof e=="object"&&e!==null&&Object.keys(e).every(t=>t==="$eq"||t==="$ne"||t==="$gt"||t==="$gte"||t==="$lt"||t==="$lte"||t==="$in"||t==="$nin")}function xh(e,t){return om(t)?Object.keys(t).filter(r=>r.startsWith("$")).every(r=>{let n=t[r];switch(r){case"$eq":return e===n;case"$ne":return e!==n;case"$gt":return Number(e)>Number(n);case"$gte":return Number(e)>=Number(n);case"$lt":return Number(e)<Number(n);case"$lte":return Number(e)<=Number(n);case"$in":return Array.isArray(n)?n.includes(e):!1;case"$nin":return Array.isArray(n)?!n.includes(e):!0;default:return!1}}):e===t}function Th(e,t){if(!t||t==="$")return[JSON.stringify(e,null,2)];let r=Array.isArray(t)?t:Gn(t);function n(s,i,o){if(o>=i.length)return typeof s=="string"||typeof s=="number"||typeof s=="boolean"?[String(s)]:s==null?[]:Array.isArray(s)||typeof s=="object"?[JSON.stringify(s,null,2)]:[];let a=i[o],c=[];if(o===0&&a==="$"&&c.push(JSON.stringify(s,null,2)),a.startsWith("[")&&a.endsWith("]")){if(!Array.isArray(s))return[];let l=a.slice(1,-1);if(l==="*")for(let u of s)c.push(...n(u,i,o+1));else try{let u=parseInt(l,10);u<0&&(u=s.length+u),u>=0&&u<s.length&&c.push(...n(s[u],i,o+1))}catch{return[]}}else if(a.startsWith("{")&&a.endsWith("}")){if(typeof s!="object"||s===null)return[];let l=a.slice(1,-1).split(",").map(u=>u.trim());for(let u of l){let h=Gn(u);if(h.length){let p=s;for(let d of h)if(p&&typeof p=="object"&&d in p)p=p[d];else{p=void 0;break}p!==void 0&&(typeof p=="string"||typeof p=="number"||typeof p=="boolean"?c.push(String(p)):(Array.isArray(p)||typeof p=="object")&&c.push(JSON.stringify(p,null,2)))}}}else if(a==="*"){if(Array.isArray(s))for(let l of s)c.push(...n(l,i,o+1));else if(typeof s=="object"&&s!==null)for(let l of Object.values(s))c.push(...n(l,i,o+1))}else typeof s=="object"&&s!==null&&a in s&&c.push(...n(s[a],i,o+1));return c}return n(e,r,0)}function Ih(e){if(Ie(e,{allowReservedRoot:!0}),e.some(t=>t.includes(":")))throw new pt("Namespace labels cannot contain colons (':'), the InMemoryStore path separator.")}var Ah=class extends Lr{data=new Map;vectors=new Map;_indexConfig;constructor(e){super(),e?.index&&(this._indexConfig={...e.index,__tokenizedFields:(e.index.fields??["$"]).map(t=>[t,t==="$"?[t]:Gn(t)])})}async batch(e){let t=[],r=new Map,n=new Map;for(let s=0;s<e.length;s+=1){let i=e[s];if("namespace"in i&&Ih(i.namespace),"key"in i&&"namespace"in i&&!("value"in i))t.push(this.getOperation(i));else if("namespacePrefix"in i){let o=this.filterItems(i);n.set(s,[i,o]),t.push(null)}else if("value"in i){let o=`${i.namespace.join(":")}:${i.key}`;r.set(o,i),t.push(null)}else"matchConditions"in i&&t.push(this.listNamespacesOperation(i))}if(n.size>0)if(this._indexConfig?.embeddings){let s=new Set;for(let[a]of n.values())a.query&&s.add(a.query);let i=s.size>0?await Promise.all(Array.from(s).map(a=>this._indexConfig.embeddings.embedQuery(a))):[],o=Object.fromEntries(Array.from(s).map((a,c)=>[a,i[c]]));for(let[a,[c,l]]of n.entries())if(c.query&&o[c.query]){let u=o[c.query];t[a]=this.scoreResults(l,u,c.offset??0,c.limit??10)}else t[a]=this.paginateResults(l.map(u=>({...u,score:void 0})),c.offset??0,c.limit??10)}else for(let[s,[i,o]]of n.entries())t[s]=this.paginateResults(o.map(a=>({...a,score:void 0})),i.offset??0,i.limit??10);if(r.size>0&&this._indexConfig?.embeddings){let s=this.extractTexts(Array.from(r.values()));if(Object.keys(s).length>0){let i=await this._indexConfig.embeddings.embedDocuments(Object.keys(s));this.insertVectors(s,i)}}for(let s of r.values())this.putOperation(s);return t}getOperation(e){let t=e.namespace.join(":");return this.data.get(t)?.get(e.key)??null}putOperation(e){let t=e.namespace.join(":");this.data.has(t)||this.data.set(t,new Map);let r=this.data.get(t);if(e.value===null)r.delete(e.key);else{let n=new Date;if(r.has(e.key)){let s=r.get(e.key);s.value=e.value,s.updatedAt=n}else r.set(e.key,{value:e.value,key:e.key,namespace:e.namespace,createdAt:n,updatedAt:n})}}listNamespacesOperation(e){let t=Array.from(this.data.keys()).map(r=>r.split(":"));return e.matchConditions&&e.matchConditions.length>0&&(t=t.filter(r=>e.matchConditions.every(n=>this.doesMatch(n,r)))),e.maxDepth!==void 0&&(t=Array.from(new Set(t.map(r=>r.slice(0,e.maxDepth).join(":")))).map(r=>r.split(":"))),t.sort((r,n)=>r.join(":").localeCompare(n.join(":"))),t.slice(e.offset??0,(e.offset??0)+(e.limit??t.length))}doesMatch(e,t){let{matchType:r,path:n}=e;if(r==="prefix")return n.length>t.length?!1:n.every((s,i)=>{let o=t[i];return s==="*"||o===s});if(r==="suffix")return n.length>t.length?!1:n.every((s,i)=>{let o=t[t.length-n.length+i];return s==="*"||o===s});throw new Error(`Unsupported match type: ${r}`)}filterItems(e){e.namespacePrefix.length>0&&Ih(e.namespacePrefix);let t=e.namespacePrefix.join(":"),r=[];for(let[s,i]of this.data.entries())(t===""||s===t||s.startsWith(`${t}:`))&&r.push(...i.values());let n=r;return e.filter&&(n=r.filter(s=>Object.entries(e.filter).every(([i,o])=>xh(s.value[i],o)))),n}scoreResults(e,t,r=0,n=10){let s=[],i=[],o=[];for(let u of e){let h=this.getVectors(u);if(h.length)for(let p of h)s.push(u),i.push(p);else o.push(u)}let a=this.cosineSimilarity(t,i).map((u,h)=>[u,s[h]]).sort((u,h)=>h[0]-u[0]),c=new Set,l=[];for(let[u,h]of a){let p=`${h.namespace.join(":")}:${h.key}`;if(c.has(p))continue;let d=c.size;if(d>=r+n)break;if(d<r){c.add(p);continue}c.add(p),l.push([u,h])}if(o.length&&l.length<n)for(let u of o.slice(0,n-l.length)){let h=`${u.namespace.join(":")}:${u.key}`;c.has(h)||(c.add(h),l.push([void 0,u]))}return l.map(([u,h])=>({...h,score:u}))}paginateResults(e,t,r){return e.slice(t,t+r)}extractTexts(e){if(!e.length||!this._indexConfig)return{};let t={};for(let r of e)if(r.value!==null&&r.index!==!1){let n=r.index===null||r.index===void 0?this._indexConfig.__tokenizedFields??[]:r.index.map(s=>[s,Gn(s)]);for(let[s,i]of n){let o=Th(r.value,i);o.length&&(o.length>1?o.forEach((a,c)=>{t[a]||(t[a]=[]),t[a].push([r.namespace,r.key,`${s}.${c}`])}):(t[o[0]]||(t[o[0]]=[]),t[o[0]].push([r.namespace,r.key,s])))}}return t}insertVectors(e,t){for(let[r,n]of Object.entries(e)){let s=t.shift();if(!s)throw new Error(`No embedding found for text: ${r}`);for(let[i,o,a]of n){let c=i.join(":");this.vectors.has(c)||this.vectors.set(c,new Map);let l=this.vectors.get(c);l.has(o)||l.set(o,new Map),l.get(o).set(a,s)}}}getVectors(e){let t=e.namespace.join(":"),r=e.key;if(!this.vectors.has(t))return[];let n=this.vectors.get(t);if(!n.has(r))return[];let s=n.get(r),i=Array.from(s.values());return i.length?i:[]}cosineSimilarity(e,t){if(!t.length)return[];let r=t.map(i=>i.reduce((o,a,c)=>o+a*e[c],0)),n=Math.sqrt(e.reduce((i,o)=>i+o*o,0)),s=t.map(i=>Math.sqrt(i.reduce((o,a)=>o+a*a,0)));return r.map((i,o)=>{let a=s[o];return n&&a?i/(n*a):0})}get indexConfig(){return this._indexConfig}};var Zs=class{serde=new Fn;constructor(e){this.serde=e||this.serde}};var Oh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ce(e){return e!=null&&e.lc_graph_name==="DeltaChannel"}function Fr(e,t){return t.filter(([r])=>ce(e[String(r)]))}function ca(e){return e!=null&&e.lg_is_channel===!0}var re=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===V.unminifiable_name)return!1;throw e}}equals(e){return this===e}},aa=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function Ur(e){if(e[aa]===!0)return e;let t={};for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let n=e[r];ca(n)&&(t[r]=n)}return Object.assign(t,{[aa]:!0}),t}function ei(e,t){let r=Ur(e),n={};for(let s in r){if(!Object.prototype.hasOwnProperty.call(r,s))continue;let i=t.channel_values[s];n[s]=r[s].fromCheckpoint(i)}return Object.assign(n,{[aa]:!0}),n}function ti(e,t){if(!Oh.test(t))throw new TypeError(`Invalid task id for exit delta: ${t}`);let r=t.toLowerCase().split("-"),n=`${String(e).padStart(8,"0")}-${r[1]}-${r[2]}-${r[3]}-${r[4]}`;return n==="00000000-0000-0000-0000-000000000000"?kl:n}function la(e,t){if(!Oh.test(t))throw new TypeError(`Invalid task id for exit delta: ${t}`);let r=t.toLowerCase().split("-");return`ffffffff-${(e>>16).toString(16).padStart(4,"0")}-${(e&65535).toString(16).padStart(4,"0")}-${r[3]}-${r[4]}`}function ur(e,t){let r=new Set;if(t===void 0)return r;for(let[,n]of t){let s=e[n];s!=null&&ce(s)&&r.add(n)}return r}function Br(e,t,r){let n=new Set;for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let i=e[s];!ce(i)||!i.isAvailable()||r!==void 0&&r[s]===void 0||ua(i,t[s])&&n.add(s)}return n}function ua(e,t){let[r,n]=t??[0,0];return r>=e.snapshotFrequency||n>=vl()}function Ye(e,t,r,n){let s=n?.channelsToSnapshot??new Set,{storedVersions:i,getNextVersion:o}=n??{},a={},c,l=e.channel_versions;if(t===void 0)c=e.channel_values;else{c={},l={...e.channel_versions};for(let u in t){if(!Object.prototype.hasOwnProperty.call(t,u))continue;let h=t[u];if(s.has(u)){if(o!==void 0&&i!==void 0&&l[u]===i[u]){let p=l[u];l[u]=o(p),a[u]=[p,l[u]]}c[u]=new Ar(h.get());continue}if(!ce(h))try{c[u]=h.checkpoint()}catch(p){if(p.name!==V.unminifiable_name)throw p}}}return{v:4,id:n?.id??yn(r),ts:new Date().toISOString(),channel_values:c,channel_versions:l,versions_seen:am(e.versions_seen,a,n?.triggerToNodes)}}function am(e,t,r={}){if(Object.keys(t).length===0)return e;let n={...e};for(let[i,[o]]of Object.entries(t))if(o===void 0)for(let a of r[i]??[])n[a]??={};let s={...e[dn]};for(let i in n)if(!(!Object.prototype.hasOwnProperty.call(n,i)||i==="__snapshot_bumps__"))for(let[o,[a,c]]of Object.entries(t)){if(n[i][o]!==a)continue;let[l,u]=Ph(i,o);a!==void 0&&s[l]!==a&&(s[u]=a),s[l]=c,n[i]={...n[i],[o]:c}}return Object.keys(s).length>0&&(n[dn]=s),n}var Ph=(e,t)=>[`${e}|${t}`,`${e}:${t}`];function Nh(e){let t=e[dn];if(t===void 0||Object.keys(t).length===0)return e;let r={};for(let n in e)if(!(!Object.prototype.hasOwnProperty.call(e,n)||n==="__snapshot_bumps__")){r[n]={};for(let[s,i]of Object.entries(e[n])){let[o,a]=Ph(n,s);t[o]!==i?r[n][s]=i:a in t&&(r[n][s]=t[a])}}return r}var Hr="delta_writes_versioned";function Kn(e){return e?.[Hr]===!0}function cm(e,t,r){let n=[];for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s)||Object.prototype.hasOwnProperty.call(t.channel_values,s))continue;let i=t.channel_versions[s]!==void 0;(ce(e[s])&&(i||!r)||e[s].lc_graph_name==="BinaryOperatorAggregate"&&i)&&n.push(s)}return n}async function Wr(e,t,r){let n=ei(e,t),{saver:s,config:i}=r??{},o=Ur(e),a=cm(o,t,r?.deltaWritesVersioned??!1),c=a.filter(u=>t.channel_versions[u]!==void 0);if((s===void 0||i===void 0)&&c.length>0)throw new Error(`DeltaChannel ${c.join(", ")} has history to replay but no checkpointer or config was passed to read it`);if(a.length===0||s===void 0||i===void 0)return n;let l=await s.getDeltaChannelHistory({config:i,channels:a});for(let u of a){let h=l[u];if(h===void 0)continue;let p=o[u].fromCheckpoint(h.seed);if(ce(p))p.replayWrites(h.writes);else for(let[,,d]of h.writes)p.update([d]);n[u]=p}return n}var lm=e=>e!=null&&e.lc_graph_name==="BinaryOperatorAggregate",Et=class Rh extends re{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(t,r){super(),this.operator=t,this.initialValueFactory=r,this.value=r?.()}fromCheckpoint(t){let r=new Rh(this.operator,this.initialValueFactory);return typeof t<"u"&&(r.value=vn(t)?t.value:t),r}update(t){let r=t;if(!r.length)return!1;if(this.value===void 0){let s=r[0],[i,o]=xe(s);i?this.value=o:this.value=s,r=r.slice(1)}let n=!1;for(let s of r)if(bt(s)){if(n)throw new M("Can receive only one Overwrite value per step.");let[,i]=xe(s);this.value=i,n=!0;continue}else!n&&this.value!==void 0&&(this.value=this.operator(this.value,s));return!0}get(){if(this.value===void 0)throw new V;return this.value}checkpoint(){if(this.value===void 0)throw new V;return this.value}isAvailable(){return this.value!==void 0}equals(t){return this===t?!0:lm(t)?this.operator===t.operator:!1}};var Xe=class Mh extends re{lc_graph_name="LastValue";value=[];constructor(t){super(),this.initialValueFactory=t,t&&(this.value=[t()])}fromCheckpoint(t){let r=new Mh(this.initialValueFactory);return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0)return!1;if(t.length!==1)throw new M("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new V;return this.value[0]}checkpoint(){if(this.value.length===0)throw new V;return this.value[0]}isAvailable(){return this.value.length!==0}},ha=class $h extends re{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(t){let r=new $h;if(typeof t<"u"){let[n,s]=t;r.value=[n],r.finished=s}return r}update(t){return t.length===0?!1:(this.finished=!1,this.value=[t[t.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new V;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}};var ri=class{lc_graph_name="AnnotationRoot";spec;constructor(e){this.spec=e}static isInstance(e){return typeof e=="object"&&e!==null&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"}},zn=function(e){return e?ni(e):new Xe};zn.Root=e=>new ri(e);function ni(e){return typeof e=="object"&&e&&"reducer"in e&&e.reducer?new Et(e.reducer,e.default):typeof e=="object"&&e&&"value"in e&&e.value?new Et(e.value,e.default):new Xe}var um=["tags","metadata","callbacks","configurable"],hm=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal","heartbeat","executionInfo","serverInfo","control"],pm=25,fm=new Set(["thread_id","checkpoint_id","checkpoint_ns","task_id","run_id","assistant_id","graph_id"]);function dm(e,t){if(!e)return t;let r=t??{};for(let n of fm){if(n in r)continue;let s=e[n];s!==void 0&&(r[n]=s)}return r}function jh(e){if(e==null||e.length===0)return;let t=e.filter(r=>!r.startsWith("seq:step"));return t.length>0?t:void 0}function mm(e,t){if(t===void 0)return e;if(e===void 0)return Array.isArray(t)?[...t]:t.copy();if(Array.isArray(t)){if(Array.isArray(e))return e.concat(t);let n=e.copy();for(let s of t)n.addHandler(Fi(s),!0);return n}if(Array.isArray(e)){let n=t.copy();for(let s of e)n.addHandler(Fi(s),!0);return n}let r=n=>n.filter((s,i)=>n.findIndex(o=>o===s||o.name==="StreamMessagesHandler"&&s.name==="StreamMessagesHandler")===i);return new br(t._parentRunId,{handlers:r(e.handlers.concat(t.handlers)),inheritableHandlers:r(e.inheritableHandlers.concat(t.inheritableHandlers)),tags:Array.from(new Set(e.tags.concat(t.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(t.inheritableTags))),metadata:{...e.metadata,...t.metadata},inheritableMetadata:{...e.inheritableMetadata,...t.inheritableMetadata}})}function gm(e){let t;for(let i=e.length-1;i>=0;i-=1)if(e[i]!==void 0){t=e[i];break}let r=t?.configurable?.thread_id!==void 0,n=e.some(i=>i?.configurable?.[ve]!==void 0),s=ie.getRunnableConfig()?.configurable?.[ve]!==void 0;return r&&!n&&!s}function Gr(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:pm,configurable:{}},r=gm(e),n=ie.getRunnableConfig();if(n!==void 0){for(let[s,i]of Object.entries(n))if(i!==void 0){if(s==="configurable"&&r)continue;if(um.includes(s)){let o;Array.isArray(i)?o=[...i]:typeof i=="object"?s==="callbacks"&&"copy"in i&&typeof i.copy=="function"?o=i.copy():o={...i}:o=i,t[s]=o}else t[s]=i}}for(let s of e)if(s!==void 0)for(let[i,o]of Object.entries(s))o===void 0||!hm.includes(i)||(i==="configurable"?t.configurable={...t.configurable,...o}:i==="metadata"?t.metadata={...t.metadata,...o}:i==="tags"?t.tags=[...t.tags??[],...o]:i==="callbacks"?t.callbacks=mm(t.callbacks,o):t[i]=o);return t.metadata=dm(t.configurable,t.metadata)??{},t}function _m(e){let t=e??ie.getRunnableConfig();if(t===void 0)throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.","If you're running `getStore` in such environment, pass the `config` from the node function directly."].join(`
114
+ `));return t?.store}function ym(e){let t=e??ie.getRunnableConfig();if(t===void 0)throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.","If you're running `getWriter` in such environment, pass the `config` from the node function directly."].join(`
115
+ `));return t?.writer||t?.configurable?.writer}function si(){return ie.getRunnableConfig()}function wm(e){let t=e??ie.getRunnableConfig();if(t===void 0)throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.","If you're running `getCurrentTaskInput` in such environment, pass the `config` from the node function directly."].join(`
116
+ `));if(t.configurable?.__pregel_scratchpad?.currentTaskInput===void 0)throw new Error("BUG: internal scratchpad not initialized.");return t.configurable[pe].currentTaskInput}function pa(e){return e.split("|").filter(t=>!t.match(/^\d+$/)).map(t=>t.split(":")[0]).join("|")}function Dh(e){let t=e.split("|");for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join("|")}var fa=Symbol.for("langgraph.graph_callback_handler"),da=class extends st{name="GraphCallbackHandler";[fa]=!0;static isInstance(e){return typeof e=="object"&&e!==null&&fa in e&&e[fa]===!0}};var ma=class{#e=void 0;requestDrain(e="shutdown"){this.#e=e}get drainRequested(){return this.#e!==void 0}get drainReason(){return this.#e}};var v=e=>BigInt(e),H=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),Uh=v("0x9E3779B1"),Bh=v("0x85EBCA77"),vm=v("0xC2B2AE3D"),Ht=v("0x9E3779B185EBCA87"),hr=v("0xC2B2AE3D27D4EB4F"),Hh=v("0x165667B19E3779F9"),ya=v("0x85EBCA77C2B2AE63"),bm=v("0x27D4EB2F165667C5"),Sm=v("0x165667919E3779F9"),km=v("0x9FB21C651E98DF25"),Em=e=>{let t=e.length;if(t%2!==0)throw new Error("String should have an even number of characters");let r=t/2,n=new Uint8Array(r),s=0,i=0;for(;i<r;){let o=e.slice(s,s+=2);n[i]=Number.parseInt(o,16),i+=1}return H(n)},ft=Em("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Kr=(v(1)<<v(128))-v(1),$=(v(1)<<v(64))-v(1),ci=(v(1)<<v(32))-v(1),Ct=64,Wh=Ct/8,Cm=8,ii=4;function zr(e){if(!e)throw new Error("Assert failed")}function xm(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function Tm(e){let t=e;return t=(t&v(65535))<<v(16)|(t&v(4294901760))>>v(16),t=(t&v(16711935))<<v(8)|(t&v(4278255360))>>v(8),t}function Im(e,t){return(e&ci)*(t&ci)&$}function Am(e,t){return(e<<t|e>>v(32)-t)&ci}function Gh(e,t,r){for(let n=0;n<Wh;n+=1){let s=t.getBigUint64(n*8,!0),i=s^r.getBigUint64(n*8,!0);e[n^1]+=s,e[n]+=Im(i,i>>v(32))}return e}function Vh(e,t,r,n){for(let s=0;s<n;s+=1)Gh(e,H(t,s*Ct),H(r,s*8));return e}function Om(e,t){for(let r=0;r<Wh;r+=1){let n=t.getBigUint64(r*8,!0),s=e[r];s=ga(s,v(47)),s^=n,s*=Uh,e[r]=s&$}return e}function oi(e,t){return Kh(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(Cm,!0))}function Lh(e,t,r){let n=r;return n+=oi(e.slice(0),H(t,0*ii)),n+=oi(e.slice(2),H(t,4*ii)),n+=oi(e.slice(4),H(t,8*ii)),n+=oi(e.slice(6),H(t,12*ii)),dt(n&$)}function Pm(e,t,r,n,s){let i=e,o=Math.floor((r.byteLength-Ct)/8),a=Ct*o,c=Math.floor((t.byteLength-1)/a);for(let l=0;l<c;l+=1)i=Vh(i,H(t,l*a),r,o),i=s(i,H(r,r.byteLength-Ct));{let l=Math.floor((t.byteLength-1-a*c)/Ct);i=Vh(i,H(t,c*a),r,l),i=n(i,H(t,t.byteLength-Ct),H(r,r.byteLength-Ct-7))}return i}function Nm(e,t){let r=new BigUint64Array([vm,Ht,hr,Hh,ya,Bh,bm,Uh]);zr(e.byteLength>128),r=Pm(r,e,t,Gh,Om),zr(r.length*8===64);{let n=Lh(r,H(t,11),v(e.byteLength)*Ht&$);return Lh(r,H(t,t.byteLength-Ct-11),~(v(e.byteLength)*hr)&$)<<v(64)|n}}function Kh(e,t){let r=e*t&Kr;return r&$^r>>v(64)}function Fh(e,t,r){return Kh((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+r)&$,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-r)&$)}function ai(e,t,r,n,s){let i=e&$,o=e>>v(64)&$;return i+=Fh(t,n,s),i^=r.getBigUint64(0,!0)+r.getBigUint64(8,!0),i&=$,o+=Fh(r,H(n,16),s),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=$,o<<v(64)|i}function dt(e){let t=e;return t^=t>>v(37),t*=Sm,t&=$,t^=t>>v(32),t}function li(e){let t=e;return t^=t>>v(33),t*=hr,t&=$,t^=t>>v(29),t*=Hh,t&=$,t^=t>>v(32),t}function Rm(e,t,r){let n=e.byteLength;zr(n>0&&n<=3);let s=v(e.getUint8(n-1))|v(n<<8)|v(e.getUint8(0)<<16)|v(e.getUint8(n>>1)<<24),i=(s^(v(t.getUint32(0,!0))^v(t.getUint32(4,!0)))+r)&$,o=(v(t.getUint32(8,!0))^v(t.getUint32(12,!0)))-r;return(li((Am(Tm(s),v(13))^o)&$)&$)<<v(64)|li(i)}function ga(e,t){return e^e>>t}function Mm(e,t,r){let n=e.byteLength;zr(n>=4&&n<=8);{let s=e.getUint32(0,!0),i=e.getUint32(n-4,!0),o=((v(s)|v(i)<<v(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+r&$)*(Ht+(v(n)<<v(2)))&Kr;return o+=(o&$)<<v(65),o&=Kr,o^=o>>v(67),ga(ga(o&$,v(35))*km&$,v(28))|dt(o>>v(64))<<v(64)}}function $m(e,t,r){let n=e.byteLength;zr(n>=9&&n<=16);{let s=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+r&$,i=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-r&$,o=e.getBigUint64(0,!0),a=e.getBigUint64(n-8,!0),c=(o^a^s)*Ht,l=(c&$)+(v(n-1)<<v(54));c=c&(Kr^$)|l,a^=i,c+=a+(a&ci)*(Bh-v(1))<<v(64),c&=Kr,c^=xm(c>>v(64));let u=(c&$)*hr;return u+=(c>>v(64))*hr<<v(64),u&=Kr,dt(u&$)|dt(u>>v(64))<<v(64)}}function jm(e,t){let r=e.byteLength;return zr(r<=16),r>8?$m(e,ft,t):r>=4?Mm(e,ft,t):r>0?Rm(e,ft,t):li(t^ft.getBigUint64(64,!0)^ft.getBigUint64(72,!0))|li(t^ft.getBigUint64(80,!0)^ft.getBigUint64(88,!0))<<v(64)}function _a(e){return~e+v(1)&$}function Dm(e,t,r){let n=v(e.byteLength)*Ht&$,s=v(e.byteLength-1)/v(32);for(;s>=0;){let a=Number(s);n=ai(n,H(e,16*a),H(e,e.byteLength-16*(a+1)),H(t,32*a),r),s-=v(1)}let i=n+(n>>v(64))&$;i=dt(i);let o=(n&$)*Ht+(n>>v(64))*ya+(v(e.byteLength)-r&$)*hr;return o&=$,o=_a(dt(o)),i|o<<v(64)}function Vm(e,t,r){let n=v(e.byteLength)*Ht&$;for(let o=32;o<160;o+=32)n=ai(n,H(e,o-32),H(e,o-16),H(t,o-32),r);n=dt(n&$)|dt(n>>v(64))<<v(64);for(let o=160;o<=e.byteLength;o+=32)n=ai(n,H(e,o-32),H(e,o-16),H(t,3+o-160),r);n=ai(n,H(e,e.byteLength-16),H(e,e.byteLength-32),H(t,103),_a(r));let s=n+(n>>v(64))&$;s=dt(s);let i=(n&$)*Ht+(n>>v(64))*ya+(v(e.byteLength)-r&$)*hr;return i&=$,i=_a(dt(i)),s|i<<v(64)}function qr(e,t=v(0)){let r=new TextEncoder,n=H(typeof e=="string"?r.encode(e):e),s=n.byteLength,i=o=>o.toString(16).padStart(32,"0");return s<=16?i(jm(n,t)):s<=128?i(Dm(n,ft,t)):s<=240?i(Vm(n,ft,t)):i(Nm(n,ft))}function qn(e){return/^[0-9a-f]{32}$/.test(e)}function wa(e,t){let r=ie.getRunnableConfig();if(!r)throw new Error("Called interrupt() outside the context of a graph.");let n=r.configurable;if(!n)throw new Error("No configurable found in config");if(!n.__pregel_checkpointer)throw new mn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let s=t?.responseSchema,i=u=>{if(s===void 0||!Nc(s))return u;try{return Mt(s,u)}catch(h){throw eo(h),h}},o=n[pe];o.interruptCounter+=1;let a=o.interruptCounter;if(o.resume.length>0&&a<o.resume.length){let u=i(o.resume[a]);return n[ge]?.([[ye,o.resume.slice(0,a+1)]]),u}if(o.nullResume!==void 0){if(o.resume.length!==a)throw new Error(`Resume length mismatch: ${o.resume.length} !== ${a}`);let u=o.consumeNullResume(),h=i(u);return o.resume.push(u),n[ge]?.([[ye,o.resume]]),h}let c=n[Pe],l={id:c!=null?ui(c,o.resume.length):void 0,value:e};throw s!==void 0&&(l.response_schema=We(s)),new Ke([l])}function ui(e,t){return qr(t===0?e:`${e}|${t}`)}var Lm="__remove_all__",Fm={human:it,ai:Z,system:vr,tool:wt,function:bc,generic:sn};function hi(e){let t=Be(e);if(!nn.isInstance(t))return t;let r=Fm[t.getType()];return r===void 0?t:new r(Object.fromEntries(Object.entries(t).filter(([n])=>n!=="type"&&n!=="tool_call_chunks"&&!n.startsWith("lc_"))))}function Wt(e,t){let r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],s=r.map(hi),i=n.map(hi);for(let u of s)(u.id===null||u.id===void 0)&&(u.id=mr(),u.lc_kwargs.id=u.id);let o;for(let u=0;u<i.length;u+=1){let h=i[u];(h.id===null||h.id===void 0)&&(h.id=mr(),h.lc_kwargs.id=h.id),wr.isInstance(h)&&h.id==="__remove_all__"&&(o=u)}if(o!=null)return i.slice(o+1);let a=[...s],c=new Map(a.map((u,h)=>[u.id,h])),l=new Set;for(let u of i){let h=c.get(u.id);if(h!==void 0)wr.isInstance(u)?l.add(u.id):(l.delete(u.id),a[h]=u);else{if(wr.isInstance(u))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);c.set(u.id,a.length),a.push(u)}}return a.filter(u=>!l.has(u.id))}function pi(e,t){let r=[];for(let a of t)Array.isArray(a)?r.push(...a):r.push(a);let n=e.length>0&&ee.isInstance(e[0])?e:e.map(hi),s=r.map(hi),i=new Map;for(let a=0;a<n.length;a+=1){let c=n[a].id;c!=null&&i.set(c,a)}let o=[...n];for(let a of s){let c=a.id;wr.isInstance(a)&&c==="__remove_all__"?(o.length=0,i.clear()):c==null?o.push(a):wr.isInstance(a)?i.has(c)&&(o[i.get(c)]=null,i.delete(c)):i.has(c)?o[i.get(c)]=a:(i.set(c,o.length),o.push(a))}return o.filter(a=>a!==null)}var zh=Symbol.for("langgraph.messages_delta_reducer");Object.defineProperty(pi,zh,{value:!0});function qh(e){return typeof e=="function"&&e[zh]===!0}var va=["values","updates","messages","tools","custom","tasks"];function Jr(e){if(e==null||typeof e!="object")return!1;let t=e;return typeof t.id=="string"&&("source"in t||typeof t.step=="number")&&!("values"in t)&&!("config"in t)}function Um(e){if(!Array.isArray(e)||e.length!==2)return{data:e};let[t,r]=e;if(r==null||typeof r!="object")return{data:e};let n=r,s=typeof n.langgraph_node=="string"?n.langgraph_node:void 0,i=typeof n.run_id=="string"?n.run_id:void 0;return{data:i!=null&&t!=null&&typeof t=="object"?{...t,run_id:i}:t,node:s}}function ba({namespace:e,mode:t,payload:r,seq:n}){let s=Date.now(),i={type:"event"};switch(t){case"messages":{let{data:o,node:a}=Um(r);return[{...i,seq:n,method:"messages",params:{namespace:e,timestamp:s,...a?{node:a}:{},data:o}}]}case"tools":return[{...i,seq:n,method:"tools",params:{namespace:e,timestamp:s,data:Bm(r)}}];case"checkpoints":return Jr(r)?[{...i,seq:n,method:"checkpoints",params:{namespace:e,timestamp:s,data:r}}]:[];case"values":return[{...i,seq:n,method:"values",params:{namespace:e,timestamp:s,data:r}}];case"updates":{let o=Hm(r);return[{...i,seq:n,method:"updates",params:{namespace:e,timestamp:s,...typeof o.node=="string"?{node:o.node}:{},data:o}}]}case"custom":{let o=typeof r=="object"&&r!==null&&!Array.isArray(r)&&"name"in r?r:{payload:r};return[{...i,seq:n,method:"custom",params:{namespace:e,timestamp:s,data:o}}]}case"tasks":return[{...i,seq:n,method:"tasks",params:{namespace:e,timestamp:s,data:r}}];default:return[]}}function Bm(e){if(typeof e!="object"||e===null)return{event:"tool-error",tool_call_id:"",message:"Unexpected tools payload shape"};let t=e,r=String(t.toolCallId??"");switch(t.event){case"on_tool_start":return{event:"tool-started",tool_call_id:r,tool_name:String(t.name??"unknown"),input:t.input};case"on_tool_event":return{event:"tool-output-delta",tool_call_id:r,delta:typeof t.data=="string"?t.data:JSON.stringify(t.data??"")};case"on_tool_end":return{event:"tool-finished",tool_call_id:r,output:t.output};case"on_tool_error":{let n=t.error;return{event:"tool-error",tool_call_id:r,message:typeof n=="object"&&n!==null&&"message"in n&&typeof n.message=="string"?n.message:String(n??"unknown error")}}default:return{event:"tool-error",tool_call_id:"",message:`Unknown tool event: ${String(t.event)}`}}}function Hm(e){if(typeof e!="object"||e===null)return{values:{}};let t=Object.entries(e);if(t.length===0)return{values:{}};let[r,n]=t[0];return{node:r,values:typeof n=="object"&&n!==null?n:{value:n}}}var Sa=Symbol.for("langgraph.stream_channel"),Fe=class ka{[Sa]=!0;channelName;#e=[];#t=[];#n=!1;#i;#s;constructor(t){this.channelName=t}static local(){return new ka}static remote(t){return new ka(t)}static isInstance(t){return typeof t=="object"&&t!==null&&Sa in t&&t[Sa]===!0}push(t){this.#e.push(t),this.#r(),this.#s?.(t)}iterate(t=0){let r=t;return{next:async()=>{for(;;){if(r<this.#e.length)return{value:this.#e[r++],done:!1};if(this.#n){if(this.#i)throw this.#i;return{value:void 0,done:!0}}await new Promise(n=>this.#t.push(n))}}}}toAsyncIterable(t=0){return{[Symbol.asyncIterator]:()=>this.iterate(t)}}toEventStream(t={}){let r=new TextEncoder,n=this.iterate(t.startAt),s=t.event??this.channelName,i=t.serialize??(o=>JSON.stringify(o)??"null");return new ReadableStream({async pull(o){try{let a=await n.next();if(a.done){o.close();return}let c=[];s!=null&&c.push(`event: ${s}`);for(let l of i(a.value).split(/\r\n|\r|\n/))c.push(`data: ${l}`);o.enqueue(r.encode(`${c.join(`
117
+ `)}
118
+
119
+ `))}catch(a){o.error(a)}},async cancel(){await n.return?.()}})}get(t){if(t<0||t>=this.#e.length)throw new RangeError(`StreamChannel index ${t} out of bounds (size=${this.#e.length})`);return this.#e[t]}get size(){return this.#e.length}get done(){return this.#n}close(){this.#n=!0,this.#r()}fail(t){this.#i=t,this.#n=!0,this.#r()}_wire(t){this.#s=t}_close(){this.close()}_fail(t){this.fail(t)}[Symbol.asyncIterator](){return this.iterate()}#r(){let t=this.#t.splice(0);for(let r of t)r()}};function Jh(e){return Fe.isInstance(e)}var Wm="custom:";function Gm(e){return`${Wm}${e}`}function Km(e){return e!=null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}var fi=Symbol("resolveValues"),Ea=Symbol("rejectValues"),Yh=class{_events=Fe.local();_discoveries=Fe.local();#e=0;#t=!1;#n;#i=!1;#s=[];#r=[];#a=[];#o=new Map;#l=new Map;#c=[];#u=[];register(e,t){this.#o.set(ne(e),t)}addTransformer(e){let t=this._events.size;this.#r.push(e),e.onRegister&&e.onRegister({push:(r,n)=>this.push(r,n)});for(let r=0;r<t;r+=1)e.process(this._events.get(r));this.#t&&(this.#n!==void 0?e.fail?.(this.#n):e.finalize?.())}wireChannels(e){for(let[t,r]of Object.entries(e)){if(Jh(r)){if(this.#a.push(r),typeof r.channelName!="string")continue;let n=Gm(r.channelName);r._wire(s=>{this._events.push({type:"event",seq:this.#e++,method:n,params:{namespace:this.#s,timestamp:Date.now(),data:s}})});continue}Km(r)&&this.#u.push({name:t,promise:Promise.resolve(r)})}}push(e,t){t.method==="values"&&this.#l.set(ne(e),t.params.data);let r=this.#s;this.#s=e;let n=!0;for(let s of this.#r)s.process(t)||(n=!1);this.#s=r,n&&this._events.push({...t,seq:this.#e++})}close(){this.#t=!0;for(let[r,n]of this.#l.entries()){let s=r?r.split("\0"):[];this.#o.get(ne(s))?.[fi](n)}let e=[];for(let r of this.#r){let n=r.finalize?.();n!=null&&typeof n.then=="function"&&e.push(n)}for(let r of this.#a)r._close();let t=this.#u;t.length===0&&e.length===0?(this._events.close(),this._discoveries.close()):Promise.allSettled([...e,...t.map(async({name:r,promise:n})=>{try{let s=await n;this._events.done||this._events.push({type:"event",seq:this.#e++,method:"custom",params:{namespace:[],timestamp:Date.now(),data:{name:r,payload:s}}})}catch{}})]).then(()=>{this._events.close(),this._discoveries.close()});for(let r of this.#o.values())r[fi](void 0)}fail(e){this.#t=!0,this.#n=e;for(let t of this.#r)t.fail?.(e);for(let t of this.#a)t._fail(e);this._events.fail(e),this._discoveries.fail(e);for(let t of this.#o.values())t[Ea](e)}markInterrupted(e){this.#i=!0,this.#c.push(...e)}get interrupted(){return this.#i}get interrupts(){return this.#c}subscribeEvents(e,t=0){let r=this._events.iterate(t);return{async next(){for(;;){let n=await r.next();if(n.done||mt(n.value.params.namespace,e))return n}}}}};async function Xh(e,t){let r=0;try{for await(let n of e){let[s,i,o]=n;if(i==="values"&&sr(o)){let c=o[B];t.markInterrupted(c.map(l=>({interruptId:l.id??"",payload:l.value})))}let a=ba({namespace:s,mode:i,payload:o,seq:r});r+=a.length;for(let c of a)t.push(s,c)}}catch(n){t.fail(n);return}t.close()}function ne(e){return e.join("\0")}function mt(e,t){if(t.length>e.length)return!1;for(let r=0;r<t.length;r+=1)if(e[r]!==t[r])return!1;return!0}function di(e,t,r=0){return{[Symbol.asyncIterator](){let n=e.iterate(r);return{async next(){for(;;){let s=await n.next();if(s.done)return{value:void 0,done:!0};if(mt(s.value.namespace,t))return{value:s.value,done:!1}}}}}}}var Qh="root";function zm(e){if(e.length===0)return Qh;let t=e[e.length-1],r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function qm(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jm(e){if(!gt(e)||e.event!=="started")return;let t=e.cause;if(gt(t)&&typeof t.type=="string")return t}function Ym(e){if(gt(e)&&"result"in e&&typeof e.name=="string"&&typeof e.id=="string"&&!e.name.startsWith("__"))return{name:e.name,id:e.id}}function Ca(e={}){let t=e.rootGraphName??Qh,r=e.initialStatus??"running",n=e.emitRootOnRegister??!0,s=e.getGraphName??zm,i=e.serializeError??qm,o=e.getTerminalStatusOverride,a=Fe.local(),c=new Map,l=new Map,u=new Map,h=new Map,p=new Set,d=[],f,m=0,_=!1,y=b=>{if(b.length===0)return t;let x=u.get(ne(b));return typeof x=="string"&&x.length>0?x:s(b)},g=(b,x)=>{let A=ne(b);if(u.has(A))return;let R=(gt(x)&&gt(x.metadata)?x.metadata:void 0)?.lc_agent_name;u.set(A,typeof R=="string"?R:void 0)},w=b=>{if(!gt(b))return;let x=b.id;if(typeof x!="string")return;let A=b.input,R;if(gt(A)&&gt(A.tool_call)){let F=A.tool_call.id;typeof F=="string"&&(R=F)}else if(Array.isArray(A)){for(let F of A)if(gt(F)&&typeof F.id=="string"){R=F.id;break}}R!=null&&h.set(x,R)},S=b=>{if(b.length===0)return;let x=u.get(ne(b));if(typeof x!="string"||x.length===0)return;let A=b[b.length-1],R=A.indexOf(":");if(R===-1)return;let F=A.slice(R+1);if(F.length===0)return;let E=h.get(F);if(!(typeof E!="string"||E.length===0))return{type:"toolCall",tool_call_id:E}},k=b=>l.get(ne(b))??S(b),C=(b,x,A)=>{let R=ne(b),F=c.get(R),E=F?.graphName??y(b);if(F!=null&&F.status===x&&F.graphName===E&&A?.error==null)return;F==null?(F={namespace:b,graphName:E,status:x},c.set(R,F)):F.status=x;let N={event:x,graph_name:E,...A?.cause!=null?{cause:A.cause}:{},...A?.error!=null?{error:A.error}:{}},U=Date.now();if(a.push({namespace:b,timestamp:U,...N}),!(b.length===0&&!n)&&f!=null){m+=1;try{f.push(b,{type:"event",seq:0,method:"lifecycle",params:{namespace:b,timestamp:U,data:N}})}finally{m-=1}}},O=b=>{let x=ne(b),A=c.get(x);return A==null&&(A={namespace:b,graphName:y(b),status:void 0},c.set(x,A)),A},P=()=>{if(d.length===0)return;let b=d.splice(0,d.length);for(let x of b){let A=ne(x.namespace),R=c.get(A);R==null||R.status!=="started"||C(x.namespace,"completed")}},K=b=>{let x=ne(b.namespace),A=c.get(x);A==null||A.status!=="started"||d.some(R=>ne(R.namespace)===x)||d.push(b)},I=(b,x)=>{for(let A=d.length-1;A>=0;A-=1){let R=d[A];R.source.type==="node"&&R.source.node===x&&ne(R.source.parent)===ne(b)&&d.splice(A,1)}},D=b=>{for(let x=1;x<=b.length;x+=1){let A=b.slice(0,x),R=ne(A);if(c.has(R))continue;O(A);let F=k(A);C(A,"started",F!=null?{cause:F}:void 0)}},Me=()=>p.size>0?"interrupted":"completed",Q=b=>{for(let x of c.values())x.namespace.length!==0&&x.status==="started"&&C(x.namespace,b);C([],b),a.close()},W=async()=>{if(o==null)return Me();try{return await o()??Me()}catch{return Me()}},se=(b,x)=>{let A=`${x}:`;for(let R of c.values()){if(R.namespace.length!==b.length+1||R.status!=="started"||!mt(R.namespace,b))continue;let F=R.namespace[R.namespace.length-1];if(F===x||F.startsWith(A))return R.namespace}},q=(b,x)=>{let A=[...b,`${x.name}:${x.id}`];return c.get(ne(A))?.status==="started"?A:void 0};return{__native:!0,init(){return{_lifecycleLog:a,lifecycle:di(a,[],0)}},onRegister(b){f=b,O([]),n&&C([],r)},process(b){let x=b.params.namespace;if(m>0)return!0;let A=b.method==="tasks"?Ym(b.params.data):void 0;if(A!=null?I(x,A.name):b.method==="tasks"&&(g(x,b.params.data),w(b.params.data)),P(),b.method==="lifecycle"){let R=Jm(b.params.data);return R!=null&&l.set(ne(x),R),D(x),!1}if(D(x),b.method==="input"&&gt(b.params.data)&&b.params.data.event==="requested"){let R=b.params.data.id;typeof R=="string"&&p.add(R)}if(A!=null){let R=q(x,A);R!=null&&K({namespace:R,source:{type:"task"}})}if(b.method==="updates"){let R=b.params.node;if(typeof R=="string"&&!R.startsWith("__")){let F=se(x,R);F!=null&&K({namespace:F,source:{type:"node",parent:x,node:R}})}}return!0},finalize(){if(!_){if(_=!0,P(),o==null){Q(Me());return}return W().then(Q).catch(b=>{a.fail(b)})}},fail(b){if(_)return;_=!0;let x=i(b);for(let A of c.values())A.namespace.length!==0&&A.status==="started"&&C(A.namespace,"failed");C([],"failed",{error:x}),a.fail(b)}}}function Yr(e){let t=e;return typeof t.run_id=="string"?`run:${t.run_id}`:e.event==="message-start"&&typeof t.id=="string"?`message:${t.id}`:"__default__"}function Jn(e,t){let r=Fe.local(),n=new Map,s=new Set;return{init:()=>({messages:r.toAsyncIterable()}),process(i){if(i.method!=="messages"||!mt(i.params.namespace,e)||i.params.namespace.length!==e.length+1||t!==void 0&&i.params.node!==t)return!0;let o=i.params.data;switch(o.event){case"message-start":{let a=Yr(o);if(o.role==="tool"){s.add(a);break}let c=Fe.local(),l=Object.assign(new ps(c.toAsyncIterable()),{namespace:i.params.namespace,node:i.params.node});n.set(a,{source:c,stream:l}),c.push(o),r.push(l);break}case"content-block-start":case"content-block-delta":case"content-block-finish":if(s.has(Yr(o)))break;n.get(Yr(o))?.source.push(o);break;case"message-finish":{let a=Yr(o);if(s.delete(a))break;let c=n.get(a);c&&(c.source.push(o),c.source.close(),n.delete(a));break}case"error":if(s.has(Yr(o)))break;n.get(Yr(o))?.source.push(o);break}return!0},finalize(){for(let[i,o]of n)o.source.push({event:"message-finish"}),o.source.close(),n.delete(i);s.clear(),r.close()},fail(i){for(let[o,a]of n)a.source.fail(i),n.delete(o);s.clear(),r.fail(i)}}}function Yn(e,t,r=0){let n=t.length+1;return{[Symbol.asyncIterator](){let s=e.iterate(r);return{async next(){for(;;){let i=await s.next();if(i.done)return{value:void 0,done:!0};let{ns:o,stream:a}=i.value;if(o.length===n&&mt(o,t))return{value:a,done:!1}}}}}}}function xa(e,t){let{createStream:r}=t,n=new Set;return{__native:!0,init(){return{_discoveries:e._discoveries,subgraphs:Yn(e._discoveries,[],0)}},process(s){let i=s.params.namespace;if(i.length===0)return!0;let o=i.slice(0,1),a=ne(o);if(n.has(a))return!0;n.add(a);let c=r(o,e._discoveries.size,e._events.size);return e.register(o,c),e._discoveries.push({ns:o,stream:c}),!0}}}function Ta(e){let t=Fe.local();return{init:()=>({_valuesLog:t}),process(r){return r.method!=="values"||r.params.namespace.length!==e.length||!mt(r.params.namespace,e)||t.push(r.params.data),!0},finalize(){t.close()},fail(r){t.fail(r)}}}function mi(e){return"__native"in e&&e.__native===!0}var Zh=Symbol("setValuesLog"),ep=Symbol("setMessagesIterable"),Ia=Symbol("setLifecycleIterable"),Aa=Symbol("setSubgraphsIterable"),Xm={[Symbol.asyncIterator](){return{next:()=>Promise.resolve({value:void 0,done:!0})}}},Oa=class{path;extensions;_mux;#e;#t;#n;#i;#s;#r;#a;#o;#l;#c;constructor(e,t,r=0,n=0,s,i){this.path=e,this._mux=t,this.#t=r,this.#e=n,this.extensions=s??{},this.#n=i??new AbortController,this.#r=new Promise((o,a)=>{this.#i=o,this.#s=a}),this.#r.catch(()=>{})}[Symbol.asyncIterator](){return this._mux.subscribeEvents(this.path,this.#e)}get subgraphs(){return this.#c?this.#c:Yn(this._mux._discoveries,this.path,this.#t)}get values(){let e=this.#a,t=this.#r,r=this._mux,n=this.#e,s=this.path,i=e?e.toAsyncIterable():{[Symbol.asyncIterator]:()=>{let o=r.subscribeEvents(s,n);return{async next(){for(;;){let a=await o.next();if(a.done)return{value:void 0,done:!0};if(a.value.method==="values"&&a.value.params.namespace.length===s.length)return{value:a.value.params.data,done:!1}}}}}};return{[Symbol.asyncIterator]:()=>i[Symbol.asyncIterator](),then:t.then.bind(t)}}get messages(){if(this.#o)return this.#o;let e=Jn(this.path),t=e.init();return this._mux.addTransformer(e),this.#o=t.messages,this.#o}get lifecycle(){return this.#l??Xm}messagesFrom(e){let t=Jn(this.path,e),r=t.init();return this._mux.addTransformer(t),r.messages}get output(){return this.#r}get interrupted(){return this._mux.interrupted}get interrupts(){return this._mux.interrupts}abort(e){this.#n.abort(e)}get signal(){return this.#n.signal}[fi](e){this.#i?.(e),this.#i=void 0}[Ea](e){this.#s?.(e),this.#s=void 0}[Zh](e){this.#a=e}[ep](e){this.#o=e}[Ia](e){this.#l=e}[Aa](e){this.#c=e}},tp=class extends Oa{name;index;constructor(e,t,r=0,n=0,s,i){super(e,t,r,n,s,i);let o=e[e.length-1]??"",a=o.lastIndexOf(":");if(a>=0){this.name=o.slice(0,a);let c=o.slice(a+1);this.index=/^\d+$/.test(c)?Number(c):0}else this.name=o,this.index=0}};function Pa(e,t=[],r){let{abortController:n}=r instanceof AbortController?{abortController:r}:r??{},s=new Yh,i=Ca(),o=i.init(),a=o._lifecycleLog,c=xa(s,{createStream:(y,g,w)=>{let S=new tp(y,s,g,w);return S[Aa](Yn(s._discoveries,y,g)),S[Ia](di(a,y,a.size)),S}}),l=c.init();s.addTransformer(c),s.addTransformer(i);let u=Ta([]),h=Jn([]);s.addTransformer(u),s.addTransformer(h);let p={},d=[];for(let y of t){let g=y();s.addTransformer(g);let w=g.init();mi(g)?d.push(w):Object.assign(p,w),typeof w=="object"&&w!==null&&!mi(g)&&s.wireChannels(w)}let f=new Oa([],s,0,0,p,n);for(let y of d)Object.assign(f,y);let m=u.init();f[Zh](m._valuesLog);let _=h.init();return f[ep](_.messages),f[Ia](o.lifecycle),f[Aa](l.subgraphs),s.register([],f),Xh(e,s).catch(y=>{}),f}var he=class extends G{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,t,r){return new Promise((n,s)=>{let i=He(t,{callbacks:r?.getChild()});ie.runWithConfig(i,async()=>{try{n(await this.func(e,i))}catch(o){s(o)}})})}async invoke(e,t){let r,n=Gr(t),s=$e(this.config,n);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,s):r=await ie.runWithConfig(s,async()=>this.func(e,s)),G.isRunnable(r)&&this.recurse?await ie.runWithConfig(s,async()=>r.invoke(e,s)):r}};function*_t(e,t){if(t===void 0)yield*e;else for(let r of e)yield[t,r]}async function Qe(e){let t=[];for await(let r of await e)t.push(r);return t}function Gt(e){let t=[];for(let r of e)t.push(r);return t}function Xn(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function Na(e){return e!=null&&typeof e=="function"&&e instanceof Object.getPrototypeOf(async function*(){}).constructor}function Ra(e){return e!=null&&typeof e=="function"&&e instanceof Object.getPrototypeOf(function*(){}).constructor}function Qm(e){return typeof e=="object"&&e?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}var Ae={[Symbol.for("LG_PASSTHROUGH")]:!0};function gi(e){return typeof e=="object"&&e?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}var Ma=Symbol("IS_WRITER"),X=class ja extends he{writes;constructor(t,r){let n=`ChannelWrite<${t.map(s=>oe(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:t,name:n,tags:r,trace:!1,func:async(s,i)=>this._write(s,i??{})}),this.writes=t}async _write(t,r){let n=this.writes.map(s=>$a(s)&&gi(s.value)?{mapper:s.mapper,value:t}:_i(s)&&gi(s.value)?{channel:s.channel,value:t,skipNone:s.skipNone,mapper:s.mapper}:s);return await ja.doWrite(r,n),t}static async doWrite(t,r){for(let i of r){if(_i(i)){if(i.channel==="__pregel_tasks")throw new M("Cannot write to the reserved channel TASKS");if(gi(i.value))throw new M("PASSTHROUGH value must be replaced")}if($a(i)&&gi(i.value))throw new M("PASSTHROUGH value must be replaced")}let n=[];for(let i of r)if(oe(i))n.push([ut,i]);else if($a(i)){let o=await i.mapper.invoke(i.value,t);o!=null&&o.length>0&&n.push(...o)}else if(_i(i)){let o=i.mapper!==void 0?await i.mapper.invoke(i.value,t):i.value;if(Qm(o)||i.skipNone&&o===void 0)continue;n.push([i.channel,o])}else throw new Error(`Invalid write entry: ${JSON.stringify(i)}`);let s=t.configurable?.[ge];s(n)}static isWriter(t){return t instanceof ja||Ma in t&&!!t[Ma]}static registerWriter(t){return Object.defineProperty(t,Ma,{value:!0})}};function _i(e){return e!==void 0&&typeof e.channel=="string"}function $a(e){return e!==void 0&&!_i(e)&&G.isRunnable(e.mapper)}var rp=class np extends he{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(t,r,n=!1){super({trace:!1,func:(s,i)=>np.doRead(i,this.channel,this.fresh,this.mapper)}),this.fresh=n,this.mapper=r,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(",")}>`:`ChannelRead<${t}>`}static doRead(t,r,n,s){let i=t.configurable?.[ve];if(!i)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(i(r,n)):i(r,n)}},Xr=new el,Ze=class Qn extends us{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=Xr;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;timeout;tracePolicy;subgraphs;ends;isErrorHandler;errorHandlerNode;constructor(t){let{channels:r,triggers:n,mapper:s,writers:i,bound:o,kwargs:a,metadata:c,retryPolicy:l,cachePolicy:u,timeout:h,tracePolicy:p,tags:d,subgraphs:f,ends:m,isErrorHandler:_,errorHandlerNode:y}=t,g=[...t.config?.tags?t.config.tags:[],...d??[]];super({...t,bound:t.bound??Xr,config:{...t.config?t.config:{},tags:g}}),this.channels=r,this.triggers=n,this.mapper=s,this.writers=i??this.writers,this.bound=o??this.bound,this.kwargs=a??this.kwargs,this.metadata=c??this.metadata,this.tags=g,this.retryPolicy=l,this.cachePolicy=u,this.timeout=h,this.tracePolicy=p,this.subgraphs=f,this.ends=m,this.isErrorHandler=_,this.errorHandlerNode=y}getWriters(){let t=[...this.writers];for(;t.length>1&&t[t.length-1]instanceof X&&t[t.length-2]instanceof X;){let r=t.slice(-2),n=r[0].writes.concat(r[1].writes);t[t.length-2]=new X(n,r[0].config?.tags),t.pop()}return t}getNode(){let t=this.getWriters();if(!(this.bound===Xr&&t.length===0))return this.bound===Xr&&t.length===1?t[0]:this.bound===Xr?new Zt({first:t[0],middle:t.slice(1,t.length-1),last:t[t.length-1],omitSequenceTags:!0,tracePolicy:this.tracePolicy}):t.length>0?new Zt({first:this.bound,middle:t.slice(0,t.length-1),last:t[t.length-1],omitSequenceTags:!0,tracePolicy:this.tracePolicy}):this.bound}join(t){if(!Array.isArray(t))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 Qn({channels:{...this.channels,...Object.fromEntries(t.map(r=>[r,r]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout,tracePolicy:this.tracePolicy})}pipe(t){return X.isWriter(t)?new Qn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout,tracePolicy:this.tracePolicy}):this.bound===Xr?new Qn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:ot(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout,tracePolicy:this.tracePolicy}):new Qn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout,tracePolicy:this.tracePolicy})}};function Zm(e){return"steps"in e&&Array.isArray(e.steps)}function Zn(e){return"lg_is_pregel"in e&&e.lg_is_pregel===!0}function yi(e){let t=[e];for(let r of t){if(Zn(r))return r;Zm(r)&&t.push(...r.steps)}}function sp(e){let t=e?.handlers.filter(da.isInstance);if(t?.length)return async r=>{for(;r?.length;){let n=r.shift();for(let s of t){let i="interrupts"in n?"handleInterrupt":"handleResume";try{"interrupts"in n?await s.handleInterrupt?.(n):await s.handleResume?.(n)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, ${i}: ${o}`),s.raiseError)throw o}}}}}function es(e,t,r){let n={};for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s)||!ce(e[s]))continue;let[i,o]=r?.[s]??[0,0];n[s]=[t.has(s)?i+1:i,o+1]}return n}function wi(e){return Object.keys(e).length>0?{counters_since_delta_snapshot:e}:{}}function ts(e,t,r,n,s,i){if(r===void 0){let c=new Set;for(let l in e)Object.prototype.hasOwnProperty.call(e,l)&&ce(e[l])&&e[l].isAvailable()&&n[l]!==void 0&&c.add(l);return{channelsToSnapshot:c,metadata:{}}}let o=es(e,t,r.metadata?.counters_since_delta_snapshot),a=Br(e,o,s?n:void 0);for(let c of i)a.add(c);for(let c of a)delete o[c];return{channelsToSnapshot:a,metadata:wi(o)}}async function vi(e,t,r){if(!t.configurable?.checkpoint_id)return!1;let n=await e.getTuple({...t,configurable:{...t.configurable,checkpoint_id:void 0}});return n!==void 0&&n.checkpoint.id!==r.checkpoint.id}function pr(e,t,r=!0,n=!1){try{return e[t].get()}catch(s){if(s.name===V.unminifiable_name){if(n)return s;if(r)return null}throw s}}function et(e,t,r=!0){if(Array.isArray(t)){let n={};for(let s of t)try{n[s]=pr(e,s,!r)}catch(i){if(i.name===V.unminifiable_name)continue}return n}else return pr(e,t)}function*ip(e,t){if(e.graph===Ee.PARENT)throw new M("There is no parent graph.");if(e.goto){let r;Array.isArray(e.goto)?r=e.goto:r=[e.goto];for(let n of r)if(oe(n))yield[fe,ut,n];else if(typeof n=="string")yield[fe,`branch:to:${n}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof n}`)}if(e.resume!=null)if(typeof e.resume=="object"&&Object.keys(e.resume).length&&Object.keys(e.resume).every(qn))for(let[r,n]of Object.entries(e.resume)){let s=t.filter(i=>i[0]===r&&i[1]==="__resume__").map(i=>i[2]).slice(0,1)??[];s.push(n),yield[r,ye,s]}else yield[fe,ye,e.resume];if(e.update){if(typeof e.update!="object"||!e.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(e.update))for(let[r,n]of e.update)yield[fe,r,n];else for(let[r,n]of Object.entries(e.update))yield[fe,r,n]}}function*bi(e,t){if(t!=null)if(Array.isArray(e)&&typeof t=="object"&&!Array.isArray(t))for(let r in t)e.includes(r)&&(yield[r,t[r]]);else{if(Array.isArray(e))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[e,t]}}function*Si(e,t,r){Array.isArray(e)?(t===!0||t.find(([n,s])=>e.includes(n)))&&(yield et(r,e)):(t===!0||t.some(([n,s])=>n===e))&&(yield pr(r,e))}function*op(e,t,r){let n=t.filter(([a,c])=>(a.config===void 0||!a.config.tags?.includes("langsmith:hidden"))&&c[0][0]!=="__error__"&&c[0][0]!=="__interrupt__");if(!n.length)return;let s;n.some(([a])=>a.writes.some(([c,l])=>c==="__return__"))?s=n.flatMap(([a])=>a.writes.filter(([c,l])=>c===Ft).map(([c,l])=>[a.name,l])):Array.isArray(e)?s=n.flatMap(([a])=>{let{writes:c}=a,l={};for(let[u]of c)e.includes(u)&&(l[u]=(l[u]||0)+1);return Object.values(l).some(u=>u>1)?c.filter(([u])=>e.includes(u)).map(([u,h])=>[a.name,{[u]:h}]):[[a.name,Object.fromEntries(c.filter(([u])=>e.includes(u)))]]}):s=n.flatMap(([a])=>a.writes.filter(([c,l])=>c===e).map(([c,l])=>[a.name,l]));let i={};for(let[a,c]of s)a in i||(i[a]=[]),i[a].push(c);let o={};for(let a in i)if(i[a].length===1){let[c]=i[a];o[a]=c}else o[a]=i[a];r&&(o.__metadata__={cached:r}),yield o}function ki(e){let t=typeof e[z];if(t==="number")return 0;if(t==="string")return"";for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let n=typeof e[r];if(n==="number")return 0;if(n==="string")return"";break}}function Kt(e,t){if(Object.keys(e).length>0){let r=ki(t);return Object.fromEntries(Object.entries(t).filter(([n,s])=>s>(e[n]??r)))}else return t}function ap(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}function le(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function zt(e,t){let r=t?.parents??{};return Object.keys(r).length>0?le(e,{[_e]:{...r,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function qt(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};let r=new AbortController,n=()=>{let i=t.find(o=>o.aborted)?.reason;r.abort(i),t.forEach(o=>o.removeEventListener("abort",n))};t.forEach(i=>i.addEventListener("abort",n,{once:!0}));let s=t.find(i=>i.aborted);return s&&r.abort(s.reason),{signal:r.signal,dispose:()=>{t.forEach(i=>i.removeEventListener("abort",n))}}}var cp=class{func;name;input;retry;cache;timeout;callbacks;__lg_type="call";constructor({func:e,name:t,input:r,retry:n,cache:s,timeout:i,callbacks:o}){this.func=e,this.name=t,this.input=r,this.retry=n,this.cache=s,this.timeout=i,this.callbacks=o}};function lp(e){return typeof e=="object"&&e!==null&&"__lg_type"in e&&e.__lg_type==="call"}function up(e,t){return new Zt({name:e,first:new he({func:r=>t(...r),name:e,trace:!1,recurse:!1}),last:new X([{channel:Ft,value:Ae}],[te])})}function hp(e,t){return new he({func:(r,n)=>t(r,n),name:e,trace:!1,recurse:!1})}function pp({func:e,name:t,cache:r,retry:n,timeout:s},...i){let o=ie.getRunnableConfig();if(typeof o.configurable?.__pregel_call=="function")return o.configurable[ct](e,t,i,{retry:n,cache:r,timeout:s,callbacks:o.callbacks});throw new Error("Async local storage not initialized. Please call initializeAsyncLocalStorageSingleton() before using this function.")}var fp=e=>e!==void 0?e+1:1;function xt(e){return Array.isArray(e)?`~${e.map(xt).join(", ")}`:typeof e=="boolean"?e?"0000000001":"0000000000":typeof e=="number"?e<0?`-${String(-e).padStart(9,"0")}`:String(e).padStart(10,"0"):e==null?"~":String(e)}function eg(e,t){if(t==null)return!1;for(let r of e)if(t[r])return!0;return!1}function tg(e){let t;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t==null?t=e[r]:t=Hn(t,e[r]));return t}function rs(e,t,r){let n=ki(e.channel_versions),s=e.versions_seen.__interrupt__??{},i=!1;if((e.channel_versions.__start__??n)>(s.__start__??n))i=!0;else for(let a in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,a)&&e.channel_versions[a]>(s[a]??n)){i=!0;break}let o=r.some(a=>t==="*"?!a.config?.tags?.includes(te):t.includes(a.name));return i&&o}function Qr(e,t,r,n,s=!1){let i=new Set;if(Array.isArray(n))i=new Set(n.filter(a=>r.writes.some(([c,l])=>c===a)));else{for(let[a]of r.writes)if(a===n){i=new Set([a]);break}i=i||new Set}let o;if(s&&i.size>0){let a=Object.fromEntries(Object.entries(t).filter(([h,p])=>i.has(h))),c=new Set;for(let h in a){if(!Object.prototype.hasOwnProperty.call(a,h))continue;let p=a[h];ce(p)&&p.isAvailable()&&c.add(h)}let l=Ye(e,a,-1,{channelsToSnapshot:c}),u=ei(a,l);Se(Je(l),u,[r],void 0,void 0),o=et({...t,...u},n)}else o=et(t,n);return o}function Ei(e,t,r){for(let[n,s]of r)if(["__pregel_push","__pregel_tasks"].includes(n)&&s!=null){if(!oe(s))throw new M(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in t))throw new M(`Invalid node name "${s.node}" in Send packet`)}e(r)}var rg=new Set([pn,Ce,ye,B,Ft,Dt,ln]),ng=new Set(El);function Se(e,t,r,n,s){let i=new Map;for(let f of r)i.set(f,Un(xt(f.path)));r.sort((f,m)=>Bn(i.get(f),i.get(m)));let o=Ur(t),a=!1,c=new Set;for(let f of r){f.triggers.length>0&&(a=!0),e.versions_seen[f.name]??={};for(let m of f.triggers)m in e.channel_versions&&(e.versions_seen[f.name][m]=e.channel_versions[m]),ng.has(m)||c.add(m)}let l=tg(e.channel_versions),u;for(let f of c)f in o&&o[f].consume()&&n!==void 0&&(u??=n(l),e.channel_versions[f]=u);let h={};for(let f of r)for(let[m,_]of f.writes)rg.has(m)||m in o&&(h[m]??=[],h[m].push(_));l!=null&&u!==void 0&&(l=u);let p=n?.(l),d=new Set;for(let[f,m]of Object.entries(h))if(f in o){let _=o[f],y;try{y=_.update(m)}catch(g){if(g.name===M.unminifiable_name){let w=new M(`Invalid update for channel "${f}" with values ${JSON.stringify(m)}: ${g.message}`);throw w.lc_error_code=g.lc_error_code,w}else throw g}y&&n!==void 0&&(e.channel_versions[f]=p,_.isAvailable()&&d.add(f))}if(a)for(let f in o){if(!Object.prototype.hasOwnProperty.call(o,f))continue;let m=o[f];m.isAvailable()&&!d.has(f)&&m.update([])&&n!==void 0&&(e.channel_versions[f]=p,m.isAvailable()&&d.add(f))}if(a&&!eg(d,s))for(let f in o){if(!Object.prototype.hasOwnProperty.call(o,f))continue;let m=o[f];m.finish()&&n!==void 0&&(e.channel_versions[f]=p,m.isAvailable()&&d.add(f))}return d}function*sg(e,t,r){if(r.updatedChannels!=null&&r.triggerToNodes!=null){let n=new Set;for(let s of r.updatedChannels){let i=r.triggerToNodes[s];for(let o of i??[])n.add(o)}yield*[...n].sort();return}if(!(()=>{for(let n in e.channel_versions)if(e.channel_versions[n]!==null)return!1;return!0})())for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(yield n)}function ig(e){let t,r=new Map,n=new Set;if(e)for(let[s,i,o]of e){if(s==="00000000-0000-0000-0000-000000000000"&&i==="__resume__"&&t===void 0&&(t=o),i==="__resume__"&&s!=="00000000-0000-0000-0000-000000000000"){let a=r.get(s);a||(a=[],r.set(s,a)),a.push(o)}i!=="__error__"&&n.add(s)}return{nullResume:t,resumeByTaskId:r,successfulWriteTaskIds:n}}function Jt(e,t,r,n,s,i,o){let a={},c=o.pendingWritesIndex?o:{...o,pendingWritesIndex:ig(t)},l=n[ut];if(l?.isAvailable()){let u=l.get().length;for(let h=0;h<u;h+=1){let p=xi([Ce,h],e,t,r,n,s,i,c);p!==void 0&&(a[p.id]=p)}}for(let u of sg(e,r,c)){let h=xi([ms,u],e,t,r,n,s,i,c);h!==void 0&&(a[h.id]=h)}return a}function xi(e,t,r,n,s,i,o,a){let{step:c,checkpointer:l,manager:u}=a,h=i.configurable??{},p=h.checkpoint_ns??"";if(e[0]==="__pregel_push"&&lp(e[e.length-1])){let d=e[e.length-1],f=up(d.name,d.func),m=[Ce],_=p===""?d.name:`${p}|${d.name}`,y=Ve(JSON.stringify([_,c.toString(),d.name,Ce,e[1],e[2]]),t.id),g=`${_}:${y}`,w=[...e.slice(0,3),!0],S={langgraph_step:c,langgraph_node:d.name,langgraph_triggers:m,langgraph_path:w,langgraph_checkpoint_ns:g,checkpoint_ns:g};if(o){let k=[],C={checkpointId:t.id,checkpointNs:g,taskId:y,threadId:h.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:d.name,input:d.input,proc:f,writes:k,config:{...He($e(i,{metadata:S,store:a.store??i.store}),{runName:d.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[xr]:y,[ge]:O=>Ei(P=>k.push(...P),n,O),[ve]:(O,P=!1)=>Qr(t,s,{name:d.name,writes:k,triggers:m,path:w},O,P),[lt]:l??h.__pregel_checkpointer,[_e]:{...h[_e],[p]:t.id},[pe]:Ci({pendingWrites:r??[],taskId:y,currentTaskInput:d.input,resumeMap:i.configurable?.[nr],taskCheckpointNamespace:g,pendingWritesIndex:a.pendingWritesIndex}),[Vt]:t.channel_values[Ut],checkpoint_id:void 0,checkpoint_ns:g}}),executionInfo:C},triggers:m,retry_policy:d.retry,cache_key:d.cache?{key:qr((d.cache.keyFunc??JSON.stringify)([d.input])),ns:[fs,d.name??"__dynamic__"],ttl:d.cache.ttl}:void 0,id:y,path:w,writers:[],timeout:d.timeout}}else return{id:y,name:d.name,interrupts:[],path:w}}else if(e[0]==="__pregel_push"){let d=typeof e[1]=="number"?e[1]:parseInt(e[1],10);if(!s.__pregel_tasks?.isAvailable())return;let f=s[ut].get();if(d<0||d>=f.length)return;let m=gs(f[d])&&!oe(f[d])?new tr(f[d].node,f[d].args,f[d].timeout!==void 0?{timeout:f[d].timeout}:void 0):f[d];if(!gs(m)){console.warn(`Ignoring invalid packet ${JSON.stringify(m)} in pending sends.`);return}if(!(m.node in n)){console.warn(`Ignoring unknown node name ${m.node} in pending sends.`);return}let _=[Ce],y=p===""?m.node:`${p}|${m.node}`,g=Ve(JSON.stringify([y,c.toString(),m.node,Ce,d.toString()]),t.id),w=`${y}:${g}`,S=[...e.slice(0,3),!1],k={langgraph_step:c,langgraph_node:m.node,langgraph_triggers:_,langgraph_path:S,langgraph_checkpoint_ns:w,checkpoint_ns:w};if(o){let C=n[m.node],O=C.getNode();if(O!==void 0){C.metadata!==void 0&&(k={...k,...C.metadata});let P=[],K={checkpointId:t.id,checkpointNs:w,taskId:g,threadId:h.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:m.node,input:m.args,proc:O,subgraphs:C.subgraphs,writes:P,config:{...He($e(i,{metadata:k,tags:C.tags,store:a.store??i.store}),{runName:m.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[xr]:g,[ge]:I=>Ei(D=>P.push(...D),n,I),[ve]:(I,D=!1)=>Qr(t,s,{name:m.node,writes:P,triggers:_,path:S},I,D),[lt]:l??h.__pregel_checkpointer,[_e]:{...h[_e],[p]:t.id},[pe]:Ci({pendingWrites:r??[],taskId:g,currentTaskInput:m.args,resumeMap:i.configurable?.[nr],taskCheckpointNamespace:w,pendingWritesIndex:a.pendingWritesIndex}),[Vt]:t.channel_values[Ut],checkpoint_id:void 0,checkpoint_ns:w}}),executionInfo:K},triggers:_,retry_policy:C.retryPolicy,cache_key:C.cachePolicy?{key:qr((C.cachePolicy.keyFunc??JSON.stringify)([m.args])),ns:[fs,C.name??"__dynamic__",m.node],ttl:C.cachePolicy.ttl}:void 0,id:g,path:S,writers:C.getWriters(),timeout:m.timeout??C.timeout}}}else return{id:g,name:m.node,interrupts:[],path:S}}else if(e[0]==="__pregel_pull"){let d=e[1].toString(),f=n[d];if(f===void 0)return;if(r?.length){let g=p===""?d:`${p}|${d}`,w=Ve(JSON.stringify([g,c.toString(),d,ms,d]),t.id);if(a.pendingWritesIndex?a.pendingWritesIndex.successfulWriteTaskIds.has(w):r.some(S=>S[0]===w&&S[1]!=="__error__"))return}let m=ki(t.channel_versions);if(m===void 0)return;let _=t.versions_seen[d]??{},y=f.triggers.find(g=>s[g].isAvailable()?(t.channel_versions[g]??m)>(_[g]??m):!1);if(y!==void 0){let g=og(f,s,o);if(g===void 0)return;let w=p===""?d:`${p}|${d}`,S=Ve(JSON.stringify([w,c.toString(),d,ms,[y]]),t.id),k=`${w}:${S}`,C={langgraph_step:c,langgraph_node:d,langgraph_triggers:[y],langgraph_path:e,langgraph_checkpoint_ns:k,checkpoint_ns:k};if(o){let O=f.getNode();if(O!==void 0){f.metadata!==void 0&&(C={...C,...f.metadata});let P=[],K={checkpointId:t.id,checkpointNs:k,taskId:S,threadId:h.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:d,input:g,proc:O,subgraphs:f.subgraphs,writes:P,config:{...He($e(i,{metadata:C,tags:f.tags,store:a.store??i.store}),{runName:d,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[xr]:S,[ge]:I=>Ei(D=>{P.push(...D)},n,I),[ve]:(I,D=!1)=>Qr(t,s,{name:d,writes:P,triggers:[y],path:e},I,D),[lt]:l??h.__pregel_checkpointer,[_e]:{...h[_e],[p]:t.id},[pe]:Ci({pendingWrites:r??[],taskId:S,currentTaskInput:g,resumeMap:i.configurable?.[nr],taskCheckpointNamespace:k,pendingWritesIndex:a.pendingWritesIndex}),[Vt]:t.channel_values[Ut],checkpoint_id:void 0,checkpoint_ns:k}}),executionInfo:K},triggers:[y],retry_policy:f.retryPolicy,cache_key:f.cachePolicy?{key:qr((f.cachePolicy.keyFunc??JSON.stringify)([g])),ns:[fs,f.name??"__dynamic__",d],ttl:f.cachePolicy.ttl}:void 0,id:S,path:e,writers:f.getWriters(),timeout:f.timeout}}}else return{id:S,name:d,interrupts:[],path:e}}}}function dp(e,t,r,n,s,i,o,a,c){let{step:l,checkpointer:u,manager:h}=c,p=i[t];if(p===void 0)return;let d=p.getNode();if(d===void 0)return;let f=a.configurable??{},m=f.checkpoint_ns??"",_=[Ce],y=m===""?t:`${m}|${t}`,g=Ve(JSON.stringify([y,l.toString(),t,Ce,"node_error_handler",e.id]),n.id),w=`${y}:${g}`,S=e.path?.slice(0,3)??[],k=[S[0]??"__pregel_push",...S.slice(1),"node_error_handler",!1],C={langgraph_step:l,langgraph_node:t,langgraph_triggers:_,langgraph_path:k,langgraph_checkpoint_ns:w,checkpoint_ns:w};p.metadata!==void 0&&(C={...C,...p.metadata});let O=[],P={checkpointId:n.id,checkpointNs:w,taskId:g,threadId:f.thread_id,runId:a.runId!=null?String(a.runId):void 0,nodeAttempt:1};return{name:t,input:e.input,proc:d,subgraphs:p.subgraphs,writes:O,config:{...He($e(a,{metadata:C,tags:p.tags,store:c.store??a.store}),{runName:t,callbacks:h?.getChild(`graph:step:${l}`),configurable:{[xr]:g,[ge]:K=>Ei(I=>O.push(...I),i,K),[ve]:(K,I=!1)=>Qr(n,o,{name:t,writes:O,triggers:_,path:k},K,I),[lt]:u??f.__pregel_checkpointer,[_e]:{...f[_e],[m]:n.id},[pe]:Ci({pendingWrites:s??[],taskId:g,currentTaskInput:e.input,resumeMap:a.configurable?.[nr],taskCheckpointNamespace:w}),[Vt]:n.channel_values[Ut],[hn]:new vs(String(e.name),r),checkpoint_id:void 0,checkpoint_ns:w}}),executionInfo:P},triggers:_,retry_policy:p.retryPolicy,cache_key:void 0,id:g,path:k,writers:p.getWriters()}}function og(e,t,r){let n;if(typeof e.channels=="object"&&!Array.isArray(e.channels)){n={};for(let[s,i]of Object.entries(e.channels))if(e.triggers.includes(i))try{n[s]=pr(t,i,!1)}catch(o){if(o.name===V.unminifiable_name)return;throw o}else if(i in t)try{n[s]=pr(t,i,!1)}catch(o){if(o.name===V.unminifiable_name)continue;throw o}}else if(Array.isArray(e.channels)){let s=!1;for(let i of e.channels)try{n=pr(t,i,!1),s=!0;break}catch(o){if(o.name===V.unminifiable_name)continue;throw o}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return r&&e.mapper!==void 0&&(n=e.mapper(n)),n}function mp(e,t){if(typeof e.args!="object"||e.args===null)return e;let r={};for(let[n,s]of Object.entries(e.args)){let i=t[n];(!i||i.lc_graph_name!=="UntrackedValue")&&(r[n]=s)}return new tr(e.node,r)}function Ci({pendingWrites:e,taskId:t,currentTaskInput:r,resumeMap:n,taskCheckpointNamespace:s,pendingWritesIndex:i}){let o=i?i.nullResume:e.find(([c,l])=>c==="00000000-0000-0000-0000-000000000000"&&l==="__resume__")?.[2],a={callCounter:0,interruptCounter:-1,resume:(()=>{let c=i?(i.resumeByTaskId.get(t)??[]).flat():e.filter(([l,u])=>l===t&&u==="__resume__").flatMap(([l,u,h])=>h);if(n!=null){let l=ui(s,c.length),u=ui(s,0);l in n?c.push(n[l]):u in n&&c.push(n[u])}return c})(),nullResume:o,subgraphCounter:0,currentTaskInput:r,consumeNullResume:()=>{if(a.nullResume!=null)return delete a.nullResume,e.splice(e.findIndex(([c,l])=>c==="00000000-0000-0000-0000-000000000000"&&l==="__resume__"),1),o}};return a}var ns={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},ss=(e,t)=>`${e.start}${t}${e.end}`;function ag(e){if(e==null)return;let t={};if(e.metadata!=null)for(let[n,s]of Object.entries(e.metadata))ia.has(n)||(t[n]=s);let r=jh(e.tags);return r!=null&&(t.tags=r),Object.keys(t).length>0?t:void 0}function*Ti(e){for(let{id:t,name:r,input:n,config:s,triggers:i,writes:o}of e){if(s?.tags?.includes("langsmith:hidden"))continue;let a={id:t,name:r,input:n,triggers:i,interrupts:o.filter(([l,u])=>l===t&&u==="__interrupt__").map(([,l])=>l)},c=ag(s);c!=null&&(a.metadata=c),yield a}}function cg(e){return typeof e!="object"||e===null?!1:"$writes"in e&&Array.isArray(e.$writes)}function gp(e){let t={};for(let[r,n]of e){let s=String(r);if(s in t){let i=cg(t[s])?t[s].$writes:[t[s]];i.push(n),t[s]={$writes:i}}else t[s]=n}return t}function*_p(e,t){for(let[{id:r,name:n,config:s},i]of e)s?.tags?.includes("langsmith:hidden")||(yield{id:r,name:n,result:gp(i.filter(([o])=>Array.isArray(t)?t.includes(o):o===t)),interrupts:i.filter(o=>o[0]===B).flatMap(o=>o[1]),error:i.find(o=>o[0]==="__error__")?.[1]??null})}function*yp(e,t,r,n,s,i,o,a){function c(h){let p={};return h.callbacks!=null&&(p.callbacks=h.callbacks),h.configurable!=null&&(p.configurable=h.configurable),h.maxConcurrency!=null&&(p.max_concurrency=h.maxConcurrency),h.metadata!=null&&(p.metadata=h.metadata),h.recursionLimit!=null&&(p.recursion_limit=h.recursionLimit),h.runId!=null&&(p.run_id=h.runId),h.runName!=null&&(p.run_name=h.runName),h.tags!=null&&(p.tags=h.tags),p}let l=e.configurable?.checkpoint_ns,u={};for(let h of s){if(!(h.subgraphs?.length?h.subgraphs:[h.proc]).find(yi))continue;let p=`${h.name}:${h.id}`;l&&(p=`${l}|${p}`),u[h.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:p}}}yield{config:c(e),values:et(t,r),metadata:n,next:s.map(h=>h.name),tasks:Da(s,i,u,a),parentConfig:o?c(o):void 0}}function Da(e,t,r,n){return e.map(s=>{let i=t.find(([u,h])=>u===s.id&&h==="__error__")?.[2],o=t.filter(([u,h])=>u===s.id&&h==="__interrupt__").flatMap(([,,u])=>u),a=t.some(([u,h])=>u===s.id&&fn(h)),c=(()=>{if(!a)return;let u=t.findIndex(([h,p])=>h===s.id&&p==="__return__");if(u>=0)return t[u][2];if(typeof n=="string")return t.find(([h,p])=>h===s.id&&p===n)?.[2];if(Array.isArray(n)){let h=t.filter(([p,d])=>p===s.id&&n.includes(d)).map(([,p,d])=>[p,d]);return h.length?gp(h):void 0}})();if(i)return{id:s.id,name:s.name,path:s.path,error:i,interrupts:o,result:c};let l=r?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:o,...l!==void 0?{state:l}:{},result:c}})}function wp(e,t,r){console.log([`${ss(ns.blue,`[${e}:checkpoint]`)}`,`\x1B[1m State at the end of step ${e}:\x1B[0m
120
+ `,JSON.stringify(et(t,r),null,2)].join(""))}function is(e,t){let r=t.length;console.log([`${ss(ns.blue,`[${e}:tasks]`)}`,`\x1B[1m Starting step ${e} with ${r} task${r===1?"":"s"}:\x1B[0m
121
+ `,t.map(n=>`- ${ss(ns.green,String(n.name))} -> ${JSON.stringify(n.input,null,2)}`).join(`
122
+ `)].join(""))}function vp(e,t,r){let n={};for(let[s,i]of t)r.includes(s)&&(n[s]||(n[s]=[]),n[s].push(i));console.log([`${ss(ns.blue,`[${e}:writes]`)}`,`\x1B[1m Finished step ${e} with writes to ${Object.keys(n).length} channel${Object.keys(n).length!==1?"s":""}:\x1B[0m
123
+ `,Object.entries(n).map(([s,i])=>`- ${ss(ns.yellow,s)} -> ${i.map(o=>JSON.stringify(o)).join(", ")}`).join(`
124
+ `)].join(""))}function os(e,t,r){let n=e.split("|");if(r===void 0)return n;let s=t.langgraph_path,i=1;for(;Array.isArray(s)&&s[0]==="__pregel_push"&&s[s.length-1]===!0;)i+=1,s=s[1];return n.slice(0,Math.max(n.length-i,0))}function Zr(e,t){return t===void 0||t.subgraphs?!1:e.length>0&&e.join("|")!==t.parentNs}var Ii=class extends on{_abortController;_innerReader;constructor(e,t){let r=e.getReader(),n=t??new AbortController;super({start(s){return i();function i(){return r.read().then(({done:o,value:a})=>{if(o){s.close();return}return s.enqueue(a),i()})}},cancel(s){return n.abort(s),r.cancel(s)}}),this._abortController=n,this._innerReader=r}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},La=class extends on{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t,r=new Promise(n=>{t=n});super({start:n=>{t(n)}}),r.then(n=>{this.controller=n}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this._closed||!this.controller||(this.passthroughFn?.(e),this.controller.enqueue(e))}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){try{this.controller?.error(e)}finally{this._closed=!0}}},kp=class extends st{name="StreamToolsHandler";awaitHandlers=!0;streamFn;runs={};namespaceOptions;constructor(e,t){super(),this.streamFn=e,this.namespaceOptions=t}handleToolStart(e,t,r,n,s,i,o,a){if(!i||s&&s.includes("langsmith:hidden"))return;let c=i.langgraph_checkpoint_ns,l=c==null?[]:os(c,i,this.namespaceOptions);if(Zr(l,this.namespaceOptions))return;let u={ns:l,toolCallId:a,toolName:o??"unknown",input:t};this.runs[r]=u,this.streamFn([l,"tools",{event:"on_tool_start",toolCallId:u.toolCallId,name:u.toolName,input:t}])}handleToolEvent(e,t){let r=this.runs[t];r&&this.streamFn([r.ns,"tools",{event:"on_tool_event",toolCallId:r.toolCallId,name:r.toolName,data:e}])}handleToolEnd(e,t){let r=this.runs[t];delete this.runs[t],r&&this.streamFn([r.ns,"tools",{event:"on_tool_end",toolCallId:r.toolCallId,name:r.toolName,output:e}])}handleToolError(e,t){let r=this.runs[t];delete this.runs[t],r&&(De(e)||Tr(e)||this.streamFn([r.ns,"tools",{event:"on_tool_error",toolCallId:r.toolCallId,name:r.toolName,error:e}]))}};function lg(e){return JSON.stringify(e,function(t,r){let n=this[t];if(n!=null&&typeof n=="object"&&"toDict"in n&&typeof n.toDict=="function"){let{type:s,data:i}=n.toDict();return{...i,type:s}}return r})}function ug(e){return e instanceof Error?{error:e.name,message:e.message}:{error:"Error",message:JSON.stringify(e)}}function Fa(e){return typeof e!="object"||e==null?!1:"configurable"in e&&typeof e.configurable=="object"&&e.configurable!=null}function Va(e){return!Fa(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||"",checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function bp(e){if(Fa(e)){let t=Object.fromEntries(Object.entries(e.configurable).filter(([n])=>!n.startsWith("__"))),r={...e,configurable:t};return delete r.callbacks,r}return e}function Sp(e){let t={...e,checkpoint:Va(e.config),parent_checkpoint:Va(e.parentConfig),config:bp(e.config),parent_config:bp(e.parentConfig),tasks:e.tasks.map(r=>{if(Fa(r.state)){let n=Va(r.state);if(n!=null){let s={...r,checkpoint:n};return delete s.state,s}}return r})};return delete t.parentConfig,t}function Ep(e){let t=new TextEncoder;return new ReadableStream({async start(r){let n=s=>{r.enqueue(t.encode(`event: ${s.event}
125
+ data: ${lg(s.data)}
126
+
127
+ `))};try{for await(let s of e){let[i,o,a]=s,c=a;if(o==="debug"){let l=a;l.type==="checkpoint"&&(c={...l,payload:Sp(l.payload)})}o==="checkpoints"&&(c=Sp(a)),n({event:i?.length?`${o}|${i.join("|")}`:o,data:c})}}catch(s){n({event:"error",data:ug(s)})}r.close()}})}function Cp(...e){return new La({passthroughFn:t=>{let r=t[1]==="checkpoints"&&Jr(t[2]);for(let n of e)(n.modes.has(t[1])||r)&&n.push(t)},modes:new Set(e.flatMap(t=>Array.from(t.modes)))})}var xp=class{checkpointId;#e=new Set;constructor(e){this.checkpointId=e}#t(e){let t=e.includes(":")?e.slice(0,e.lastIndexOf(":")):e;return this.#e.has(t)?!1:(this.#e.add(t),!0)}async getCheckpoint(e,t,r){if(this.#t(e)){let n=[];for await(let s of t.list(r,{before:{configurable:{checkpoint_id:this.checkpointId}},limit:1}))n.push(s);return n.length>0?n[0]:void 0}return await t.getTuple(r)??void 0}};var Ai=Symbol.for("INPUT_DONE"),Ua=Symbol.for("INPUT_RESUMING"),hg=25;function en(e,t){let r=[];for(let n=0;n<t.length;n+=1){let[s,i]=t[n],o=e[String(s)];if(ce(o)){if(qh(o.reducer)){let a=pg(i);a!==i&&(t[n]=[s,a])}else Oi(i);r.push(t[n])}}return r}function pg(e){let[t,r]=xe(e);if(!t)return Array.isArray(e)?Tp(e,Ip):Ip(e);if(!Array.isArray(r))return e;let n=Tp(r,Ap);return n===r?e:new Xi(n)}function Tp(e,t){let r=e.map(t);return r.every((n,s)=>n===e[s])?e:r}function Ip(e){if(!Op(e))return Ap(e);try{if(Be(e).id)return e}catch{return e}return{...e,id:mr()}}function Ap(e){if(ee.isInstance(e))return Oi(e),e;let t;try{t=Be(e)}catch{return e}return t.id||Pp(t),t}function Op(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&!("lc"in e)}function Oi(e){if(ee.isInstance(e)){e.id==null&&Pp(e);return}if(Array.isArray(e)){for(let n of e)Oi(n);return}let[t,r]=xe(e);t&&Oi(r)}function Pp(e){e.id=mr(),e.lc_kwargs!=null&&(e.lc_kwargs.id=e.id)}function Np(e){return e===void 0||e===""?[]:e.split("|")}function fg(e){if(!e)return[];let t="";for(let r of Object.keys(e))r!==""&&r.length>t.length&&(t=r);return Np(t)}var dg=class extends Zs{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation("get",e)}async set(e){return this.enqueueOperation("set",e)}async clear(e){return this.enqueueOperation("clear",e)}async stop(){await this.queue}enqueueOperation(e,...t){let r=this.queue.then(()=>this.cache[e](...t));return this.queue=r.then(()=>{},()=>{}),r}},Rp=class Mp{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;_exitDeltaWrites;_storedDeltaWrites=new Set;_exitCommandWrites=[];_exitFirstStep=null;_deltaChannelsForcedSnapshot=new Set;_resumeLoadedWrites=[];_reappliedTaskIds=new Set;_writtenTaskIds=new Set;addressedCheckpointSuperseded;_hasPersistedParent=!1;_loadedLatest=!1;_deltaWritesVersioned=!1;_initialCheckpointConfig;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;addressed;skipDoneTasks=!0;prevCheckpointConfig;updatedChannels;status="pending";lifecycleEvents;control;tasks={};stream;checkpointerPromises=new Set;isNested;resumeAtHead;_checkpointerChainedPromise=Promise.resolve();_pendingDeltaWrites=[];_trackCheckpointerPromise(t){let r=t.then(n=>(this.checkpointerPromises.delete(r),n),n=>{throw n});r.catch(()=>{}),this.checkpointerPromises.add(r)}async _awaitCheckpointerPromises(){await Promise.all([...this.checkpointerPromises])}store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let t=!1;if("__start__"in this.checkpoint.channel_versions)t=!0;else for(let a in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,a)){t=!0;break}let r=this.config.configurable?.__pregel_resuming!==void 0&&this.config.configurable?.__pregel_resuming,n=this.input===null||this.input===void 0,s=ae(this.input)&&this.input.resume!=null,i=this.input===Ua,o=!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 t&&(r||n||s||i||o)}get isReplaying(){return!this.skipDoneTasks}constructor(t){this.input=t.input,this.checkpointer=t.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=fp,this.checkpoint=t.checkpoint,this.checkpointMetadata=t.checkpointMetadata,this.checkpointPreviousVersions=t.checkpointPreviousVersions,this.channels=t.channels,this.checkpointPendingWrites=t.checkpointPendingWrites;for(let[r,n]of this.checkpointPendingWrites)r!=="00000000-0000-0000-0000-000000000000"&&ce(this.channels[n])&&this._storedDeltaWrites.add(`${r}\0${n}`);this.step=t.step,this.stop=t.stop,this.config=t.config,this.checkpointConfig=t.checkpointConfig,this.isNested=t.isNested,this.resumeAtHead=t.resumeAtHead,this.addressedCheckpointSuperseded=t.addressedCheckpointSuperseded,this.manager=t.manager,this.lifecycleEvents=t.hasGraphCallbacks?[]:void 0,this.outputKeys=t.outputKeys,this.streamKeys=t.streamKeys,this.nodes=t.nodes,this.addressed=t.addressed,this.store=t.store,this.cache=t.cache?new dg(t.cache):void 0,this.stream=t.stream,this.checkpointNamespace=t.checkpointNamespace,this.prevCheckpointConfig=t.prevCheckpointConfig,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.durability=t.durability,this.debug=t.debug,this.triggerToNodes=t.triggerToNodes,this.control=this.config.control,this._exitDeltaWrites=this.durability==="exit"&&this.checkpointer!=null?[]:void 0,this._hasPersistedParent=t.hasPersistedParent??!1,this._loadedLatest=t.loadedLatest??!1,this._deltaWritesVersioned=t.deltaWritesVersioned??!1,this._initialCheckpointConfig=t.checkpointConfig,this.checkpointIdSaved=t.checkpoint.id}static async initialize(t){let{config:r,stream:n}=t;n!==void 0&&r.configurable?.__pregel_stream!==void 0&&(n=Cp(n,r.configurable[un]));let s=r.configurable?.[pe];r.configurable&&s&&(s.subgraphCounter>0&&(r=le(r,{[Pe]:[r.configurable[Pe],s.subgraphCounter.toString()].join("|")})),s.subgraphCounter+=1);let i=ve in(r.configurable??{});!i&&r.configurable?.checkpoint_ns!==void 0&&r.configurable?.checkpoint_ns!==""&&(r=le(r,{checkpoint_ns:"",checkpoint_id:void 0}));let o=r;r.configurable?.checkpoint_id===void 0&&r.configurable?.checkpoint_map!==void 0&&r.configurable?.checkpoint_map?.[r.configurable?.checkpoint_ns]&&(o=le(r,{checkpoint_id:r.configurable[_e][r.configurable?.checkpoint_ns]}));let a=!!(o.configurable?.checkpoint_id||r.configurable?.__pregel_replay_state),c=Np(r.configurable?.checkpoint_ns),l,u=!1;t.checkpointer?o.configurable?.checkpoint_id?l=await t.checkpointer.getTuple(o):r.configurable?.__pregel_replay_state?(l=await r.configurable[ds].getCheckpoint(r.configurable?.checkpoint_ns??"",t.checkpointer,o),r.configurable&&delete r.configurable[rr]):(l=await t.checkpointer.getTuple(o),u=!0):l=void 0;let h=l!==void 0,p=o;l||(l={config:r,checkpoint:lr(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]}),o={...r,...l.config,configurable:{checkpoint_ns:"",...r.configurable,...l.config.configurable}};let d=l.parentConfig,f=Je(l.checkpoint),m={...l.metadata},_=l.pendingWrites??[],y=r.configurable?.checkpoint_ns,g=r.configurable?.[_e];typeof y=="string"&&y!==""&&typeof g=="object"&&g!==null&&y in g&&_.length>0&&(_=_.filter(([,D])=>D!==ye));let w=!1,S=!1;if(t.checkpointer&&h){let D=await vi(t.checkpointer,p,l),Me=m.source==="update"||m.source==="fork";w=p.configurable?.checkpoint_id!==void 0&&!D&&!Me,S=D}let k=Object.values(t.channelSpecs).some(ce)&&(!h||Kn(l.metadata)),C=await Wr(t.channelSpecs,f,{saver:t.checkpointer,config:o,deltaWritesVersioned:k}),O=(m.step??0)+1,P=O+(r.recursionLimit??hg)+1,K={...f.channel_versions},I=t.store?new Qs(t.store):void 0;return I&&await I.start(),new Mp({input:t.input,config:r,checkpointer:t.checkpointer,checkpoint:f,checkpointMetadata:m,checkpointConfig:o,prevCheckpointConfig:d,checkpointNamespace:c,channels:C,isNested:i,resumeAtHead:w,addressedCheckpointSuperseded:S,manager:t.manager,hasGraphCallbacks:t.hasGraphCallbacks,addressed:a,step:O,stop:P,checkpointPreviousVersions:K,checkpointPendingWrites:_,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:n,store:I,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes,hasPersistedParent:h,loadedLatest:u,deltaWritesVersioned:k})}_checkpointerPutAfterPrevious(t){let r=this._pendingDeltaWrites;this._pendingDeltaWrites=[],this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>Promise.all(r)).then(()=>this.checkpointer?.put(t.config,t.checkpoint,t.metadata,t.newVersions)),this._trackCheckpointerPromise(this._checkpointerChainedPromise)}putWrites(t,r,n=!1){let s=r;if(s.length===0)return;this._writtenTaskIds.add(t);let i=en(this.channels,r);s.every(([u])=>u in Wn)&&(s=Array.from(new Map(s.map(u=>[u[0],u])).values()));let o=!1;for(let u in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,u)&&this.channels[u].lc_graph_name==="UntrackedValue"){o=!0;break}let a=s;o&&(a=s.filter(([u])=>{let h=this.channels[u];return!h||h.lc_graph_name!=="UntrackedValue"}).map(([u,h])=>u==="__pregel_tasks"&&oe(h)?[u,mp(h,this.channels)]:[u,h])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(u=>u[0]!==t);for(let[u,h]of a)this.checkpointPendingWrites.push([t,u,h]);let c=le(this.checkpointConfig,{[Pe]:this.config.configurable?.checkpoint_ns??"",[Lt]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null){let u=this.tasks[t],h=this.checkpointer.putWrites(c,a,t,u!=null?xt(u.path):"");this._trackCheckpointerPromise(h),i.length>0&&this._pendingDeltaWrites.push(h)}if(this.tasks&&this._outputWrites(t,s,n),n||!r.length||!this.cache||!this.tasks)return;let l=this.tasks[t];l==null||l.cache_key==null||r[0][0]==="__error__"||r[0][0]==="__interrupt__"||this.cache.set([{key:[l.cache_key.ns,l.cache_key.key],value:l.writes,ttl:l.cache_key.ttl}])}_outputCachedWrites(t){for(let r of t)r.writes.length>0&&this._outputWrites(r.id,r.writes,!0)}_outputWrites(t,r,n=!1){let s=this.tasks[t];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes("langsmith:hidden"))return;if(r.length>0)if(r[0][0]==="__interrupt__"){if(s.path?.[0]==="__pregel_push"&&s.path?.[s.path.length-1]===!0)return;let i=r.filter(o=>o[0]===B).flatMap(o=>o[1]);this._emit([["updates",{[B]:i}],["values",{[B]:i}]])}else r[0][0]!=="__error__"&&this._emit(Gt(_t(op(this.outputKeys,[[s,r]],n),"updates")));n||this._emit(Gt(_t(_p([[s,r]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];let t=[],r=([o,a])=>`ns:${o.join(",")}|key:${a}`,n=[],s={};for(let o of Object.values(this.tasks))o.cache_key!=null&&!o.writes.length&&(n.push([o.cache_key.ns,o.cache_key.key]),s[r([o.cache_key.ns,o.cache_key.key])]=o);if(n.length===0)return[];let i=await this.cache.get(n);for(let{key:o,value:a}of i){let c=s[r(o)];c!=null&&(c.writes.push(...a),t.push({task:c,result:a}))}return t}async tick(t){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:r=[]}=t;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![Ai,Ua].includes(this.input))await this._first(r);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new Ke;if(Object.values(this.tasks).every(s=>s.writes.length>0)){let s=Object.values(this.tasks),i=s.flatMap(a=>a.writes);this.updatedChannels=Se(this.checkpoint,this.channels,s,this.checkpointerGetNextVersion,this.triggerToNodes);for(let[a,c]of Fr(this.channels,i))bt(c)&&this._deltaChannelsForcedSnapshot.add(a);if(this._resumeLoadedWrites.length>0){for(let a of ur(this.channels,this._resumeLoadedWrites.filter(([c])=>!this._reappliedTaskIds.has(c))))this._deltaChannelsForcedSnapshot.add(a);this._resumeLoadedWrites=[]}let o=await Qe(_t(Si(this.outputKeys,i,this.channels),"values"));if(this._exitDeltaWrites!==void 0){let a=this._exitFirstStep===null;if(a){this._exitFirstStep=this.step;for(let[c,l]of this._exitCommandWrites)this._exitDeltaWrites.push([this.step,fe,"",c,l])}for(let[c,l,u]of this.checkpointPendingWrites){let h=this.channels[l];if(h==null||!ce(h)||a&&(c==="00000000-0000-0000-0000-000000000000"||this._storedDeltaWrites.has(`${c}\0${l}`)))continue;let p=this.tasks[c];this._exitDeltaWrites.push([this.step,c,p!=null?xt(p.path):"",l,u])}}if(this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),this.durability==="sync"&&await this._awaitCheckpointerPromises(),this._emitValuesWithCheckpointMeta(o),rs(this.checkpoint,this.interruptAfter,s))throw this.status="interrupt_after",new Ke;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[rr]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;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});let n=Object.values(this.tasks);if(this.checkpointer&&(this.stream.modes.has("checkpoints")||this.stream.modes.has("debug"))&&this._emit(await Qe(_t(yp(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,n,this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),n.length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0&&(this._reapplyWritesToSucceededNodes(this.tasks),this._resumeErrorHandlersIfApplicable(),n=Object.values(this.tasks)),n.every(s=>s.writes.length>0))return this._outputCachedWrites(n),this.tick({inputKeys:r});if(rs(this.checkpoint,this.interruptBefore,n))throw this.status="interrupt_before",new Ke;if(this.control!=null&&this.control.drainRequested)return this.status="draining",!1;if(this._outputCachedWrites(n),this.stream.modes.has("tasks")||this.stream.modes.has("debug")){let s=await Qe(_t(Ti(n),"tasks"));this._emit(s)}return!0}async finishAndHandleError(t){this.durability==="exit"&&(!this.isNested||typeof t<"u"||this.checkpointNamespace.every(n=>!n.includes(":")))&&(await this._putExitDeltaWrites(),this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let r=this._suppressInterrupt(t);return(r||t===void 0)&&(this.output=et(this.channels,this.outputKeys)),r&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(n=>n.writes.length>0)&&(this.updatedChannels=Se(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emitValuesWithCheckpointMeta(Gt(_t(Si(this.outputKeys,Object.values(this.tasks).flatMap(n=>n.writes),this.channels),"values")))),De(t)&&!t.interrupts.length&&this._emit([["updates",{[B]:[]}],["values",{[B]:[]}]],this.#e())),r}async acceptPush(t,r,n){if(this.interruptAfter?.length>0&&rs(this.checkpoint,this.interruptAfter,[t])){this.toInterrupt.push(t);return}let s=xi([Ce,t.path??[],r,t.id,n],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,t.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&&rs(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}(this.stream.modes.has("tasks")||this.stream.modes.has("debug"))&&this._emit(Gt(_t(Ti([s]),"tasks"))),this.debug&&is(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});let i=await this._matchCachedWrites();for(let{task:o}of i)this.putWrites(o.id,o.writes,!0);return s}getErrorHandlerNode(t){return this.nodes[t]?.errorHandlerNode}isErrorHandlerNode(t){return this.nodes[t]?.isErrorHandler===!0}scheduleErrorHandler(t,r){let n=this.getErrorHandlerNode(String(t.name));if(!n)return;let s=dp(t,n,r,this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,t.config??this.config,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(s!==void 0)return this.tasks[s.id]=s,this._emit(Gt(_t(Ti([s]),"tasks"))),this.debug&&is(this.step,[s]),s}_resumeErrorHandlersIfApplicable(){let t=new Map;for(let[r,n]of this.checkpointPendingWrites){if(n!=="__error_source_node__")continue;let s=this.checkpointPendingWrites.find(([a,c])=>a===r&&c==="__error__");if(s===void 0)continue;let i=s[2],o=new Error(i?.message??String(i));i?.name&&(o.name=i.name),t.set(r,o)}for(let[r,n]of t){let s=this.tasks[r];s!==void 0&&this.getErrorHandlerNode(String(s.name))&&(s.writes.length===0&&s.writes.push([Dt,{message:n.message,name:n.name}]),this.scheduleErrorHandler(s,n))}}_suppressInterrupt(t){return!De(t)||this.isNested?!1:(this.lifecycleEvents?.push({runId:this.manager?.runId,status:this.status,checkpointId:this.checkpoint.id,checkpointNs:[...this.checkpointNamespace],interrupts:[...t.interrupts]}),!0)}async _first(t){let{configurable:r}=this.config,n=ae(this.input),s=this.addressed&&(this.isNested&&r?.checkpoint_ns!==void 0&&r?.checkpoint_ns!==""&&r?.checkpoint_map!==void 0&&r.checkpoint_ns in r.checkpoint_map||!(n&&this.input.resume!=null||r?.__pregel_resuming===!0||this.resumeAtHead));this.skipDoneTasks=!(s||this.addressedCheckpointSuperseded);let i=this.checkpointMetadata.source==="update"||this.checkpointMetadata.source==="fork",o=s&&(n||this.isResuming)&&(!i||this.addressedCheckpointSuperseded),a=[],c=this.isResuming&&this.skipDoneTasks;if(this._resumeLoadedWrites=c?this.checkpointPendingWrites.filter(([f])=>f!==fe):[],this._reappliedTaskIds=new Set,this._deltaChannelsForcedSnapshot=c?new Set:ur(this.channels,this.checkpointPendingWrites),n){let f=this.input,m=f.resume!=null;if(f.resume!=null&&typeof f.resume=="object"&&Object.keys(f.resume).every(qn)&&(this.config.configurable??={},this.config.configurable[nr]=f.resume),m&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");m&&this.config.configurable?.__pregel_strict_resume===!0&&!this.isNested&&!this.addressedCheckpointSuperseded&&this._refuseUnmatchedResume(f.resume);let _={};for(let[y,g,w]of ip(f,this.checkpointPendingWrites))_[y]??=[],_[y].push([g,w]);if(Object.keys(_).length===0)throw new ks("Received empty Command input");for(let[y,g]of Object.entries(_))if(o){en(this.channels,g);for(let[w,S]of g)a.push([y,w,S])}else this.putWrites(y,g),this._exitDeltaWrites!==void 0&&y==="00000000-0000-0000-0000-000000000000"&&this._exitCommandWrites.push(...Fr(this.channels,g));for(let y of ur(this.channels,a))this._deltaChannelsForcedSnapshot.add(y)}let l=[...this.checkpointPendingWrites??[],...a].filter(f=>f[0]===fe).map(f=>f.slice(1));l.length>0&&Se(this.checkpoint,this.channels,[{name:Ge,writes:l,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let u=n&&l.length>0;s&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(f=>f[1]!==ye));let h=r?.[pe]?.nullResume;h!==void 0&&!o&&this.putWrites(fe,[[ye,h]]);let p,d=this.isResuming;if(d||u){let f={...this.checkpoint.versions_seen[B]};for(let _ in this.channels)Object.prototype.hasOwnProperty.call(this.channels,_)&&this.checkpoint.channel_versions[_]!==void 0&&(f[_]=this.checkpoint.channel_versions[_]);this.checkpoint.versions_seen[B]=f,o&&(i&&this.prevCheckpointConfig&&(p=this.prevCheckpointConfig),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(_=>_[1]!==B),await this._putCheckpoint({source:"fork"}),h!==void 0&&this.putWrites(fe,[[ye,h]]));let m=await Qe(_t(Si(this.outputKeys,!0,this.channels),"values"));d?this.input=Ua:u&&(await this._putCheckpoint({source:"input"}),this.input=Ai),this._emitValuesWithCheckpointMeta(m)}else{let f=await Qe(bi(t,this.input));if(f.length>0){let m=en(this.channels,f),_=Jt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=Se(this.checkpoint,this.channels,Object.values(_).concat([{name:Ge,writes:f,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes);for(let[y,g]of m)bt(g)&&this._deltaChannelsForcedSnapshot.add(y);if(m.length>0){if(this._exitDeltaWrites!==void 0)for(let[y,g]of m)this._exitDeltaWrites.push([this.step,fe,"",y,g]);else if(this.checkpointer!=null)if(this._hasPersistedParent&&this._loadedLatest)this.putWrites(Ve(Ge,this.checkpoint.id),m);else for(let[y]of m)this._deltaChannelsForcedSnapshot.add(y)}await this._putCheckpoint({source:"input"}),this.input=Ai}else if("__pregel_resuming"in(this.config.configurable??{}))this.input=Ai;else throw new ks(`Received no input writes for ${JSON.stringify(t,null,2)}`)}if(!this.isNested){let f;if(s){let m=this.checkpoint.id;p!==void 0?m=p.configurable?.checkpoint_id??m:(this.checkpointMetadata.source==="update"||this.checkpointMetadata.source==="fork")&&this.prevCheckpointConfig&&(m=this.prevCheckpointConfig.configurable?.checkpoint_id??m),f=new xp(m)}this.config=le(this.config,{[rr]:this.isResuming,[ds]:f})}d&&this.lifecycleEvents?.push({runId:this.manager?.runId,status:this.status,checkpointId:this.checkpoint.id,checkpointNs:[...this.checkpointNamespace]})}#e(){let t=this.checkpointNamespace;if(!(t.length===0||t.length===1&&t[0]==="")||this.config.configurable?.__pregel_stream===void 0)return t;let r=fg(this.config.configurable?.[_e]);return r.length>0?r:t}_emit(t,r=this.checkpointNamespace){for(let[n,s]of t)if(this.stream.modes.has(n)&&this.stream.push([r,n,s]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){let i=n==="checkpoints"?this.step-1:this.step,o=new Date().toISOString(),a=n==="checkpoints"?"checkpoint":typeof s=="object"&&s!=null&&"result"in s?"task_result":"task";this.stream.push([r,"debug",{step:i,type:a,timestamp:o,payload:s}])}}_currentCheckpointMeta(){if(!this.checkpointMetadata||!this.checkpoint?.id)return;let t=this.prevCheckpointConfig?.configurable?.checkpoint_id;return{checkpoint:{id:this.checkpoint.id,...t?{parent_id:t}:{},step:this.checkpointMetadata.step,source:this.checkpointMetadata.source}}}_emitValuesWithCheckpointMeta(t){let r=this._currentCheckpointMeta();for(let[n,s]of t)n==="values"&&r?.checkpoint!=null&&!this.stream.modes.has("checkpoints")&&this.stream.push([this.checkpointNamespace,"checkpoints",r.checkpoint]),this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,s])}_putCheckpoint(t){let r=this.checkpointMetadata===t;if(r&&this.checkpoint.id===this.checkpointIdSaved)return;let n=this.checkpointer!=null&&(this.durability!=="exit"||r),s=c=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=le(this.checkpointConfig,{[Pe]:this.config.configurable?.checkpoint_ns??""});let l={...this.checkpoint.channel_versions},u=Kt(this.checkpointPreviousVersions,l);this.checkpointPreviousVersions=l,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:Je(c),metadata:{...this.checkpointMetadata},newVersions:u}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}},i;r?i={...this.checkpointMetadata.counters_since_delta_snapshot??{}}:(i=es(this.channels,this.updatedChannels??new Set,this.checkpointMetadata.counters_since_delta_snapshot),this.checkpointMetadata={...t,step:this.step,parents:this.config.configurable?.checkpoint_map??{}}),this._deltaWritesVersioned&&(this.checkpointMetadata[Hr]=!0);let o=n?Br(this.channels,i,this._deltaWritesVersioned?this.checkpoint.channel_versions:void 0):new Set;if(n)for(let c of this._deltaChannelsForcedSnapshot)o.add(c);this.checkpoint=Ye(this.checkpoint,n?this.channels:void 0,this.step,{id:r?this.checkpoint.id:void 0,channelsToSnapshot:o,storedVersions:this.checkpointPreviousVersions,getNextVersion:n?c=>this.checkpointerGetNextVersion(c):void 0,triggerToNodes:this.triggerToNodes});for(let c of o)i[c]=[0,0],this._deltaChannelsForcedSnapshot.delete(c);let a={};for(let c in i){if(!Object.prototype.hasOwnProperty.call(i,c))continue;let[l,u]=i[c];(l!==0||u!==0)&&(a[c]=[l,u])}Object.keys(a).length>0?this.checkpointMetadata.counters_since_delta_snapshot=a:delete this.checkpointMetadata.counters_since_delta_snapshot,n&&s(this.checkpoint),r||(this.step+=1)}async _putExitDeltaWrites(){if(this._exitDeltaWrites===void 0||this._exitDeltaWrites.length===0||this.checkpointer==null||this._initialCheckpointConfig===void 0)return;if(this._hasPersistedParent&&!this._loadedLatest)for(let[,,,c]of this._exitDeltaWrites)this._deltaChannelsForcedSnapshot.add(c);let t=this.checkpointMetadata.counters_since_delta_snapshot??{},r=Br(this.channels,t,this._deltaWritesVersioned?this.checkpoint.channel_versions:void 0);for(let c of this._deltaChannelsForcedSnapshot)r.add(c);let n=this._exitDeltaWrites.filter(([,,,c])=>!r.has(c));if(n.length===0)return;let s;if(this._hasPersistedParent)s=this._initialCheckpointConfig;else{let c=lr();c.id=this.checkpointIdSaved??c.id,c.ts=new Date().toISOString();let l=le(this._initialCheckpointConfig,{[Lt]:void 0});s=le(this._initialCheckpointConfig,{[Lt]:c.id}),this._checkpointerPutAfterPrevious({config:l,checkpoint:c,metadata:{source:"loop",step:-2,parents:{}},newVersions:{}}),this.checkpointConfig=s}let i=le(s,{[Pe]:this.config.configurable?.checkpoint_ns??"",[Lt]:s.configurable?.[Lt]}),o=new Map,a=[];for(let[c,l,u,h,p]of n){let d,f;l==="00000000-0000-0000-0000-000000000000"?(d=ti(c,l),f=""):c===this._exitFirstStep?(d=ti(c,l),f=u):(d=la(c,l),f=`~~${xt(c)}${u}`);let m=`${d}\0${f}`,_=o.get(m);_===void 0&&(_=[],o.set(m,_),a.push({key:m,tid:d,path:f})),_.push([h,p])}for(let{key:c,tid:l,path:u}of a){let h=this.checkpointer.putWrites(i,o.get(c),l,u);this._trackCheckpointerPromise(h),this._pendingDeltaWrites.push(h)}}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let t=le(this.checkpointConfig,{[Pe]:this.config.configurable?.checkpoint_ns??"",[Lt]:this.checkpoint.id}),r={};for(let[n,s,i]of this.checkpointPendingWrites)this._writtenTaskIds.has(n)&&(r[n]??=[],r[n].push([s,i]));for(let[n,s]of Object.entries(r)){let i=this.tasks[n];this._trackCheckpointerPromise(this.checkpointer.putWrites(t,s,n,i!=null?xt(i.path):""))}}_reapplyWritesToSucceededNodes(t){for(let[r,n,s]of this.checkpointPendingWrites){if(!fn(n))continue;let i=t[r];i&&(i.writes.push([n,s]),this._reappliedTaskIds.add(r))}}_pendingInterruptIds(){let t=new Set(this.checkpointPendingWrites.filter(([,n])=>fn(n)).map(([n])=>n)),r=this.checkpointPendingWrites.filter(([n,s])=>s==="__interrupt__"&&!t.has(n)).flatMap(([,,n])=>n);return new Set(r.flatMap(({id:n})=>n==null?[]:[n]))}_refuseUnmatchedResume(t){let r=this._pendingInterruptIds(),n=[...r].sort();if(Op(t)&&Object.keys(t).every(qn)){let s=Object.keys(t);if(s.length===0)throw new Ir("The resume map names no interrupt",{reason:"empty_map",pendingIds:n});let i=s.filter(o=>!r.has(o)).sort();if(i.length>0)throw new Ir(`Unknown or already-consumed interrupt: ${i[0]}`,{reason:"not_pending",interruptIds:i,pendingIds:n})}else if(r.size>1)throw new Ir("When there are multiple pending interrupts, you must specify the interrupt id when resuming.",{reason:"ambiguous",pendingIds:n})}_matchWrites(t){this._reapplyWritesToSucceededNodes(t);for(let r of Object.values(t))r.writes.length>0&&this._outputWrites(r.id,r.writes,!0)}};function mg(e){return yt(e?.message)}function $p(e,t,r,n){if(!t)return;let s=t.langgraph_checkpoint_ns,i=t.checkpoint_ns,o=s??i;if(o)return[os(o,t,e),{tags:r,name:n,...t}]}var jp=class extends st{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;namespaceOptions;constructor(e,t){super(),this.streamFn=e,this.namespaceOptions=t}_emit(e,t,r,n=!1,s){if(n&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let i=t.id;r!=null&&(vc(t)?i??=`run-${r}-tool-${t.tool_call_id}`:s!==void 0?i??=`run-${r}-out-${s}`:((i==null||i===`run-${r}`)&&(i=this.stableMessageIdMap[r]??i??`run-${r}`),this.stableMessageIdMap[r]??=i)),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,r,n,s,i,o,a){if(o&&(!i||!i.includes("langsmith:nostream")&&!i.includes("nostream"))){let c=$p(this.namespaceOptions,o,i,a);if(c&&Zr(c[0],this.namespaceOptions))return;this.metadatas[r]=c}}handleLLMNewToken(e,t,r,n,s,i){let o=i?.chunk;this.emittedChatModelRunIds[r]=!0,this.metadatas[r]!==void 0&&(mg(o)?this._emit(this.metadatas[r],o.message,r):this._emit(this.metadatas[r],new yr({content:e}),r))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let r=e.generations?.[0]?.[0];yt(r?.message)&&this._emit(this.metadatas[t],r?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,r,n,s,i,o,a){if(i!==void 0&&a===i.langgraph_node&&(s===void 0||!s.includes("langsmith:hidden"))){let c=$p(this.namespaceOptions,i,s,a);if(c&&Zr(c[0],this.namespaceOptions))return;if(this.metadatas[r]=c,typeof t=="object"){for(let l of Object.values(t))if((yt(l)||Li(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(let u of l)(yt(u)||Li(u))&&u.id!==void 0&&(this.seen[u.id]=u)}}}handleChainEnd(e,t){let r=this.metadatas[t];if(delete this.metadatas[t],r===void 0)return;let n=0,s=o=>{yt(o)&&(this._emit(r,o,t,!0,n),n+=1)},i=o=>{if(ae(o))i(o.update);else if(yt(o))s(o);else if(Array.isArray(o)){let a=o.some(ae);for(let c of o)a?i(c):s(c)}else if(o!=null&&typeof o=="object")for(let a of Object.values(o))Array.isArray(a)?i(a):s(a)};i(e)}handleChainError(e,t){delete this.metadatas[t]}};function Dp(e){if("response_metadata"in e&&typeof e.response_metadata=="object"&&e.response_metadata!=null)return e.response_metadata}function Vp(e){if("usage_metadata"in e&&typeof e.usage_metadata=="object"&&e.usage_metadata!=null)return e.usage_metadata}function gg(e){switch(e.type){case"text":return{type:"text",text:""};case"reasoning":return{type:"reasoning",reasoning:""};case"tool_call":case"tool_call_chunk":return{type:"tool_call_chunk",...e.id!=null?{id:e.id}:{},...e.name!=null?{name:e.name}:{},args:""};default:return e}}function _g(e){switch(e.type){case"text":{let t=typeof e.text=="string"?e.text:"";return t.length>0?{event:"content-block-delta",index:typeof e.index=="number"?e.index:0,delta:{type:"text-delta",text:t}}:void 0}case"reasoning":{let t=typeof e.reasoning=="string"?e.reasoning:"";return t.length>0?{event:"content-block-delta",index:typeof e.index=="number"?e.index:0,delta:{type:"reasoning-delta",reasoning:t}}:void 0}case"tool_call_chunk":return{event:"content-block-delta",index:typeof e.index=="number"?e.index:0,delta:{type:"block-delta",fields:{...e,type:"tool_call_chunk"}}};default:return}}var Lp=class extends st{name="StreamProtocolMessagesHandler";streamFn;metadatas={};seen={};streamedRunIds=new Set;stableMessageIdMap={};lc_prefer_chat_model_stream_events=!0;awaitHandlers=!0;constructor(e){super(),this.streamFn=e}normalizeMessageId(e,t){let r=e.id;return t!=null&&(wt.isInstance(e)?r??=`run-${t}-tool-${e.tool_call_id}`:((r==null||r===`run-${t}`)&&(r=this.stableMessageIdMap[t]??r??`run-${t}`),this.stableMessageIdMap[t]??=r)),r!==e.id&&(e.id=r,e.lc_kwargs.id=r),e.id!=null&&(this.seen[e.id]=e),e.id}emit(e,t,r){let n=r!=null?{...e[1],run_id:r}:e[1];this.streamFn([e[0],"messages",[t,n]])}emitFinalMessage(e,t,r,n=!1){let s=t.id??(r!=null?this.stableMessageIdMap[r]:void 0);if(n&&s!=null&&this.seen[s]!==void 0)return;let i=this.normalizeMessageId(t,r),o=t.type==="human"?"human":t.type==="system"?"system":t.type==="tool"?"tool":"ai",a=o==="tool"&&wt.isInstance(t)?t.tool_call_id:void 0;this.emit(e,{event:"message-start",...i!=null?{id:i}:{},...o!=="ai"?{role:o}:{},...typeof a=="string"?{tool_call_id:a}:{}},r),(Array.isArray(t.content)?t.content:typeof t.content=="string"&&t.content.length>0?[{type:"text",text:t.content}]:[]).forEach((c,l)=>{let u=typeof c.index=="number"?c.index:l;this.emit(e,{event:"content-block-start",index:u,content:gg(c)},r);let h=_g({...c,index:u});h!=null&&this.emit(e,h,r),this.emit(e,{event:"content-block-finish",index:u,content:c},r)}),this.emit(e,{event:"message-finish",...Vp(t)!=null?{usage:Vp(t)}:{},...Dp(t)!=null?{responseMetadata:Dp(t)}:{}},r)}handleChatModelStart(e,t,r,n,s,i,o,a){o&&(!i||!i.includes("langsmith:nostream")&&!i.includes("nostream"))&&(this.metadatas[r]=[o.langgraph_checkpoint_ns.split("|"),{tags:i,name:a,...o}])}handleLLMNewToken(){}handleChatModelStreamEvent(e,t){let r=this.metadatas[t];if(r===void 0)return;let n=e;if(e.event==="message-start"){this.streamedRunIds.add(t);let s=e.id??`run-${t}`;this.seen[s]=!0,this.stableMessageIdMap[t]??=s,e.id==null&&(n={...e,id:s})}this.emit(r,n,t)}handleLLMEnd(e,t){let r=this.metadatas[t];if(r===void 0)return;let n=e.generations?.[0]?.[0],s=ee.isInstance(n?.message)?n.message:void 0;if(s!=null)if(this.streamedRunIds.has(t)){let i=this.normalizeMessageId(s,t);i!=null&&(this.seen[i]=s)}else this.emitFinalMessage(r,s,t,!0);this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleLLMError(e,t){this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleChainStart(e,t,r,n,s,i,o,a){if(i!==void 0&&a===i.langgraph_node&&(s===void 0||!s.includes("langsmith:hidden"))&&(this.metadatas[r]=[i.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...i}],typeof t=="object")){for(let c of Object.values(t))if((ee.isInstance(c)||nn.isInstance(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(let l of c)(ee.isInstance(l)||nn.isInstance(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(e,t){let r=this.metadatas[t];if(delete this.metadatas[t],r===void 0)return;let n=s=>{ee.isInstance(s)&&!wt.isInstance(s)&&this.emitFinalMessage(r,s,t,!0)};if(ee.isInstance(e))n(e);else if(Array.isArray(e))for(let s of e)n(s);else if(e!=null&&typeof e=="object")for(let s of Object.values(e))if(Array.isArray(s))for(let i of s)n(i);else n(s);delete this.stableMessageIdMap[t]}handleChainError(e,t){delete this.metadatas[t],delete this.stableMessageIdMap[t]}};var yg=class{active=!0;lastProgress=Date.now();refreshOn;constructor(e){this.refreshOn=e}touch(){this.lastProgress=Date.now()}autoTouch(){this.refreshOn==="auto"&&(this.lastProgress=Date.now())}close(){this.active=!1}},wg=class extends st{name="IdleProgressCallbackHandler";awaitHandlers=!1;#e;constructor(e){super(),this.#e=e}#t=()=>{this.#e.autoTouch()};handleLLMStart=this.#t;handleChatModelStart=this.#t;handleLLMNewToken=this.#t;handleLLMEnd=this.#t;handleLLMError=this.#t;handleChainStart=this.#t;handleChainEnd=this.#t;handleChainError=this.#t;handleToolStart=this.#t;handleToolEnd=this.#t;handleToolError=this.#t;handleText=this.#t;handleRetrieverStart=this.#t;handleRetrieverEnd=this.#t;handleRetrieverError=this.#t;handleCustomEvent=this.#t};function vg(e,t,r,n){let s=e.configurable??{},i={},o=s[ge];typeof o=="function"&&(i[ge]=l=>{if(t.active)return l&&l.length&&t.autoTouch(),o(l)});let a=s[ct];typeof a=="function"&&(i[ct]=(...l)=>{if(!t.active)throw new Error(`Node "${n}" attempt was cancelled after its timeout fired`);return t.autoTouch(),a(...l)});let c={...Object.keys(i).length>0?le(e,i):e};if(c.heartbeat=()=>{r.idleTimeout!==void 0&&t.touch()},typeof c.writer=="function"){let l=c.writer;c.writer=(u=>{if(t.active)return t.autoTouch(),l(u)})}if((r.refreshOn??"auto")==="auto"&&r.idleTimeout!==void 0){let l=new wg(t),u=c.callbacks;if(u===void 0)c.callbacks=[l];else if(Array.isArray(u))c.callbacks=[...u,l];else{let h=u.copy();h.addHandler(l,!0),c.callbacks=h}}return c}async function Fp(e,t,r,n){let s=new yg(r.refreshOn??"auto"),i=new AbortController,{signal:o,dispose:a}=qt(t.signal,i.signal),c=vg({...t,signal:o},s,r,String(e.name)),l=Date.now(),u=n(c).then(y=>({type:"ok",value:y}),y=>({type:"err",error:y})),h,p,d=()=>{h!==void 0&&clearTimeout(h),p!==void 0&&clearTimeout(p)},f=new Promise(y=>{if(r.runTimeout!==void 0&&(h=setTimeout(()=>y({type:"timeout",kind:"run"}),r.runTimeout)),r.idleTimeout!==void 0){let g=r.idleTimeout,w=()=>{let S=s.lastProgress+g-Date.now();S<=0?y({type:"timeout",kind:"idle"}):p=setTimeout(w,S)};p=setTimeout(w,g)}}),m;try{m=await Promise.race([u,f])}finally{d()}if(m.type!=="timeout"){let y=Date.now();r.runTimeout!==void 0&&y-l>=r.runTimeout?m={type:"timeout",kind:"run"}:r.idleTimeout!==void 0&&y-s.lastProgress>=r.idleTimeout&&(m={type:"timeout",kind:"idle"})}if(m.type==="ok")return a?.(),m.value;if(m.type==="err")throw a?.(),m.error;let _=Date.now()-l;throw s.close(),e.writes.splice(0,e.writes.length),i.abort(),a?.(),new Ss({node:String(e.name),elapsed:_,kind:m.kind,runTimeout:r.runTimeout,idleTimeout:r.idleTimeout})}var bg=[400,401,402,403,404,405,406,407,409],Sg=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e.name==="GraphValueError"||e?.code==="ECONNABORTED")return!1;let t=e?.response?.status??e?.status;return!(t&&bg.includes(+t)||e?.error?.code==="insufficient_quota")};async function Pi(e,t,r,n){let s=e.retry_policy??t,i=0,o,a,c=e.config??{};r&&(c=le(c,r)),c={...c,signal:n};let l=Date.now();for(c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeFirstAttemptTime:l});!n?.aborted;){e.writes.splice(0,e.writes.length),o=void 0;try{e.timeout!==void 0?a=await Fp(e,c,e.timeout,u=>e.proc.invoke(e.input,u)):a=await e.proc.invoke(e.input,c);break}catch(u){if(o=u,o.pregelTaskId=e.id,Zi(o)){let _=c?.configurable?.checkpoint_ns,y=o.command;if(y.graph===_){for(let g of e.writers)await g.invoke(y,c);o=void 0;break}else if(y.graph===Ee.PARENT){let g=Dh(_);o.command=new Ee({...o.command,graph:g})}}if(Bt(o)||s===void 0||(i+=1,i>=(s.maxAttempts??3))||!(s.retryOn??Sg)(o))break;let h=s.initialInterval??500,p=Math.min(s.maxInterval??128e3,h*(s.backoffFactor??2)**(i-1)),d=s.jitter??!0?p+Math.random()*1e3:p;await new Promise(_=>setTimeout(_,d));let f=o.name??o.constructor.unminifiable_name??o.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${d.toFixed(2)}ms (attempt ${i}) after ${f}: ${o}`),c=le(c,{[rr]:!0});let m=c.configurable?.[pe];m!==void 0&&(m.interruptCounter=-1),c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeAttempt:i+1,nodeFirstAttemptTime:l})}}return{task:e,result:a,error:o,signalAborted:n?.aborted}}var Ba=Symbol.for("promiseAdded");function kg(){let e={next:()=>{},wait:Promise.resolve(Ba)};function t(r){e.next=()=>{e.wait=new Promise(t),r(Ba)}}return e.wait=new Promise(t),e}var Up=class{nodeFinished;loop;handledExceptions=new WeakSet;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:r,onStepWrite:n,maxConcurrency:s}=e,i=new Set,o,a=new AbortController,c=a.signal,l=t?AbortSignal.timeout(t):void 0,u=Object.values(this.loop.tasks),h=u.filter(m=>m.writes.length===0),{signals:p,disposeCombinedSignal:d}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:e.signal}),f=this._executeTasksWithRetry(h,{signals:p,retryPolicy:r,maxConcurrency:s});for await(let{task:m,error:_,signalAborted:y}of f)this._commit(m,_),!(_!==void 0&&this.handledExceptions.has(_))&&(De(_)?o=De(o)?new Ke([...o.interrupts,..._.interrupts]):_:Bt(_)&&!De(o)?o=_:_&&(i.size===0||!y)&&(to(_)||a.abort(),i.add(_)));if(d?.(),n?.(this.loop.step,u.map(m=>m.writes).flat()),i.size===1)throw Array.from(i)[0];if(i.size>1)throw new AggregateError(Array.from(i),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(De(o)||Tr(o)||Bt(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:r}){let n=this.loop.config.configurable?.__pregel_abort_signals??{},s=n.externalAbortSignal??r,i=t??n.timeoutAbortSignal,{signal:o,dispose:a}=qt(s,i,e),c={externalAbortSignal:s,timeoutAbortSignal:i,composedAbortSignal:o};return this.loop.config=le(this.loop.config,{[Sl]:c}),{signals:c,disposeCombinedSignal:a}}async*_executeTasksWithRetry(e,t){let{retryPolicy:r,maxConcurrency:n,signals:s}=t??{},i=kg(),o={},a={executingTasksMap:o,barrier:i,retryPolicy:r,scheduleTask:async(p,d,f)=>this.loop.acceptPush(p,d,f)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let c=0,l,u=qt(s?.externalAbortSignal,s?.timeoutAbortSignal),h=u.signal?new Promise((p,d)=>{l=()=>d(new Error("Abort")),u.signal?.addEventListener("abort",l,{once:!0})}):void 0;for(;(c===0||Object.keys(o).length>0)&&e.length;){for(;Object.values(o).length<(n??e.length)&&c<e.length;c+=1){let _=e[c];o[_.id]=Pi(_,r,{[ct]:Ha?.bind(a,this,_)},s?.composedAbortSignal).catch(y=>({task:_,error:y,signalAborted:s?.composedAbortSignal?.aborted}))}let p=await Promise.race([...Object.values(o),...h?[h]:[],i.wait]);if(p===Ba)continue;let d=p,{task:f,error:m}=d;if(m!==void 0&&!Bt(m)&&!this.loop.isErrorHandlerNode(String(f.name))&&this.loop.getErrorHandlerNode(String(f.name))!==void 0){let _=this.loop.scheduleErrorHandler(f,m);_!==void 0&&(o[_.id]=Pi(_,r,{[ct]:Ha?.bind(a,this,_)},s?.composedAbortSignal).catch(y=>({task:_,error:y,signalAborted:s?.composedAbortSignal?.aborted})),i.next())}yield d,l!=null&&(u.signal?.removeEventListener("abort",l),u.dispose?.()),delete o[p.task.id]}}_shouldRouteToErrorHandler(e){let t=String(e.name);return this.loop.isErrorHandlerNode(t)?!1:this.loop.getErrorHandlerNode(t)!==void 0}_commit(e,t){if(t!==void 0)if(De(t)){if(t.interrupts.length){let r=[[B,t.interrupts],...e.writes.filter(n=>n[0]===ye)];this.loop.putWrites(e.id,r)}}else Tr(t)?e.writes.length&&this.loop.putWrites(e.id,e.writes):Bt(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):(e.writes.push([Dt,{message:t.message,name:t.name}]),this._shouldRouteToErrorHandler(e)&&(e.writes.push([ln,String(e.name)]),this.handledExceptions.add(t)),this.loop.putWrites(e.id,e.writes));else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes("langsmith:hidden"))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([pn,null]),this.loop.putWrites(e.id,e.writes)}};async function Ha(e,t,r,n,s,i={}){let o=t.config?.configurable?.[pe];if(!o)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let a=o.callCounter;o.callCounter+=1;let c=new cp({func:r,name:n,input:s,cache:i.cache,retry:i.retry,timeout:i.timeout,callbacks:i.callbacks}),l=await this.scheduleTask(t,a,c);if(!l)return;let u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){let h=l.writes.filter(([d])=>d===Ft),p=l.writes.filter(([d])=>d===Dt);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(p.length>0){if(p.length===1){let d=p[0][1],f=d instanceof Error?d:new Error(String(d));return Promise.reject(f)}throw new Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{let h=Pi(l,i.retry,{[ct]:Ha.bind(this,e,l)});return this.executingTasksMap[l.id]=h,this.barrier.next(),h.then(({result:p,error:d})=>d?Promise.reject(d):p)}}var Tt=class extends Error{constructor(e){super(e),this.name="GraphValidationError"}};function Bp({nodes:e,channels:t,inputChannels:r,outputChannels:n,streamChannels:s,interruptAfterNodes:i,interruptBeforeNodes:o}){if(!t)throw new Tt("Channels not provided");let a=new Set,c=new Set;for(let[l,u]of Object.entries(e)){if(l==="__interrupt__")throw new Tt(`"Node name ${B} is reserved"`);if(u.constructor===Ze)u.triggers.forEach(h=>a.add(h));else throw new Tt(`Invalid node type ${typeof u}, expected PregelNode`)}for(let l of a)if(!(l in t))throw new Tt(`Subscribed channel '${String(l)}' not in channels`);if(Array.isArray(r)){if(r.every(l=>!a.has(l)))throw new Tt(`None of the input channels ${r} are subscribed to by any node`)}else if(!a.has(r))throw new Tt(`Input channel ${String(r)} is not subscribed to by any node`);Array.isArray(n)?n.forEach(l=>c.add(l)):c.add(n),s&&!Array.isArray(s)?c.add(s):Array.isArray(s)&&s.forEach(l=>c.add(l));for(let l of c)if(!(l in t))throw new Tt(`Output channel '${String(l)}' not in channels`);if(i&&i!=="*"){for(let l of i)if(!(l in e))throw new Tt(`Node ${String(l)} not in nodes`)}if(o&&o!=="*"){for(let l of o)if(!(l in e))throw new Tt(`Node ${String(l)} not in nodes`)}}function Wa(e,t){if(Array.isArray(e)){for(let r of e)if(!(r in t))throw new Error(`Key ${String(r)} not found in channels`)}else if(!(e in t))throw new Error(`Key ${String(e)} not found in channels`)}function Eg(e){return Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1])}var Ga=class Hp extends re{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(t){super(),this.unique=t?.unique??this.unique,this.accumulate=t?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){let r=new Hp({unique:this.unique,accumulate:this.accumulate});return typeof t>"u"?r:Eg(t)?(r.seen=new Set(t[0]),r.values=[...t[1]],r):(r.values=[...t],this.unique&&(r.seen=new Set(r.values)),r)}update(t){let r=!1;this.accumulate||(r=this.values.length>0,this.values=[]);let n=t.flat();if(n.length>0)if(this.unique)for(let s of n)this.seen.has(s)||(r=!0,this.seen.add(s),this.values.push(s));else r=!0,this.values.push(...n);return r}get(){if(this.values.length===0)throw new V;return this.values}checkpoint(){return this.unique?[[...this.seen],[...this.values]]:[...this.values]}isAvailable(){return this.values.length!==0}};function Cg(e){let t=new TextEncoder;return new ReadableStream({async start(r){try{for await(let n of e){let s=n.params.namespace,i=s.length?`${n.method}|${s.join("|")}`:n.method;r.enqueue(t.encode(`event: ${i}
128
+ data: ${JSON.stringify(n.params.data??{})}
129
+
130
+ `))}}catch(n){r.enqueue(t.encode(`event: error
131
+ data: ${JSON.stringify({message:String(n)})}
132
+
133
+ `))}finally{r.close()}}})}var Wp=class{static subscribeTo(e,t){let{key:r,tags:n}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&r!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;return typeof e=="string"?r?s={[r]:e}:s=[e]:s=Object.fromEntries(e.map(i=>[i,i])),new Ze({channels:s,triggers:Array.isArray(e)?e:[e],tags:n})}static writeTo(e,t){let r=[];for(let n of e)r.push({channel:n,value:Ae,skipNone:!1});for(let[n,s]of Object.entries(t??{}))G.isRunnable(s)||typeof s=="function"?r.push({channel:n,value:Ae,skipNone:!0,mapper:ot(s)}):r.push({channel:n,value:s,skipNone:!1});return new X(r)}},xg=class extends G{lc_namespace=["langgraph","pregel"];invoke(e,t){throw new Error("Not implemented")}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},Ni=class extends xg{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;streamTransformers;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,"__pregel_tasks"in this.channels&&"lc_graph_name"in this.channels.__pregel_tasks&&this.channels.__pregel_tasks.lc_graph_name!=="Topic")throw new Error(`Channel '${ut}' is reserved and cannot be used in the graph.`);this.channels[ut]=new Ga({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.streamTransformers=e.streamTransformers??[],this.autoValidate&&this.validate()}withConfig(e){let{streamTransformers:t,...r}=e,n=$e(this.config,r),s=[...this.streamTransformers,...t??[]];return new this.constructor({...this,config:n,streamTransformers:s})}validate(){Bp({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[e,t]of Object.entries(this.nodes))for(let r of t.triggers)this.triggerToNodes[r]??=[],this.triggerToNodes[r].push(e);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(e){return this.getGraph(e)}*getSubgraphs(e,t){for(let[r,n]of Object.entries(this.nodes)){if(e!==void 0&&e!==r&&!e.startsWith(`${r}|`))continue;let s=n.subgraphs?.length?n.subgraphs:[n.bound];for(let i of s){let o=yi(i);if(o!==void 0){if(r===e){yield[r,o];return}if(e===void 0&&(yield[r,o]),t){let a=e;e!==void 0&&(a=e.slice(r.length+1));for(let[c,l]of o.getSubgraphs(a,t))if(yield[`${r}|${c}`,l],e!==void 0)return}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}_resolveCheckpointer(e){if(this.checkpointer===!1)return;let t=e?.configurable?.[lt];if(t!==void 0)return t;if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");return this.checkpointer}_stateCheckpointer(e){let t=this._resolveCheckpointer(e);if(typeof t!="object"||t===null)throw new mn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});return t}_ownCheckpointConfig(e){if(this.checkpointer!==!0)return e;let t=e.configurable?.checkpoint_ns??"";return{...e,configurable:{...e.configurable,[Pe]:t.split("|").map(r=>r.split(":")[0]).join("|")}}}async _subgraphForNamespace(e,t){let r=e.configurable?.checkpoint_ns??"";if(r===""||e.configurable?.__pregel_read!==void 0||e.configurable?.__pregel_checkpointer!==void 0)return;let n=pa(r);for await(let[,s]of this.getSubgraphsAsync(n,!0))return[s,Xn(e,{[lt]:t})]}async _prepareStateSnapshot({config:e,saved:t,saver:r,recurse:n=!1,applyPendingWrites:s=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};let i=await Wr(this.channels,t.checkpoint,{saver:r,config:t.config??e,deltaWritesVersioned:Kn(t.metadata)});if(t.pendingWrites?.length){let p=t.pendingWrites.filter(([d,f])=>d===fe).map(([d,f,m])=>[String(f),m]);p.length>0&&Se(t.checkpoint,i,[{name:Ge,writes:p,triggers:[]}],void 0,this.triggerToNodes)}let o=Object.values(Jt(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),a=await Qe(this.getSubgraphsAsync()),c=t.config.configurable?.checkpoint_ns??"",l={};for(let p of o){let d=a.find(([m])=>m===p.name);if(!d||d[1].checkpointer===!1)continue;let f=`${String(p.name)}:${p.id}`;if(c&&(f=`${c}|${f}`),n){let m={configurable:{[lt]:r,thread_id:t.config.configurable?.thread_id,checkpoint_ns:f}},_=d[1];l[p.id]=await _.getState(m,{subgraphs:!0})}else{let m={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:f}};l[p.id]=m}}if(s&&t.pendingWrites?.length){let p=Object.fromEntries(o.map(f=>[f.id,f]));for(let[f,m,_]of t.pendingWrites)["__error__","__interrupt__",ir].includes(m)||f in p&&p[f].writes.push([String(m),_]);let d=o.filter(f=>f.writes.length>0);d.length>0&&Se(t.checkpoint,i,d,void 0,this.triggerToNodes)}let u=t?.metadata;u&&t?.config?.configurable?.thread_id&&(u={...u,thread_id:t.config.configurable.thread_id});let h=o.filter(p=>p.writes.length===0).map(p=>p.name);return{values:et(i,this.streamChannelsAsIs),next:h,tasks:Da(o,t?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:u,config:zt(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let r=this._stateCheckpointer(e),n=await this._subgraphForNamespace(e,r);if(n!==void 0){let[a,c]=n;return await a.getState(c,{subgraphs:t?.subgraphs})}let s=this._ownCheckpointConfig(e),i=$e(this.config,s),o=await r.getTuple(s);return await this._prepareStateSnapshot({config:i,saved:o,saver:r,recurse:t?.subgraphs,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let r=this._stateCheckpointer(e),n=await this._subgraphForNamespace(e,r);if(n!==void 0){let[i,o]=n;yield*i.getStateHistory(o,t);return}let s=this._ownCheckpointConfig($e(this.config,e,{configurable:{checkpoint_ns:e.configurable?.checkpoint_ns??""}}));for await(let i of r.list(s,t))yield this._prepareStateSnapshot({config:i.config,saved:i,saver:r})}async bulkUpdateState(e,t){let r=this._stateCheckpointer(e);if(t.length===0)throw new Error("No supersteps provided");if(t.some(a=>a.updates.length===0))throw new Error("No updates provided");let n=await this._subgraphForNamespace(e,r);if(n!==void 0){let[a,c]=n;return await a.bulkUpdateState(c,t)}let s=e.configurable?.checkpoint_ns??"";if(s!==""&&e.configurable?.__pregel_read===void 0&&e.configurable?.__pregel_checkpointer===void 0)throw new Error(`Subgraph "${pa(s)}" not found`);let i=async(a,c,l)=>{let u=this._ownCheckpointConfig(this.config?$e(this.config,a):a),h=await r.getTuple(u),p=h!==void 0?Je(h.checkpoint):lr(),d={...h?.checkpoint.channel_versions},f=h?.metadata?.step??-1,m=Xn(u,{checkpoint_ns:u.configurable?.checkpoint_ns??""}),_=u.metadata??{};h?.config.configurable&&(m=Xn(u,h.config.configurable),_={...h.metadata,..._});let y=Object.values(this.channels).some(ce)&&(h===void 0||Kn(h.metadata)),g=y?{[Hr]:!0}:{},w=E=>r.getNextVersion(E),S=()=>new Set(Object.keys(Kt(d,p.channel_versions))),k=l?ur(this.channels,h?.pendingWrites):new Set,C=async()=>l&&h!==void 0&&await vi(r,u,h),O=this.channels,P=E=>{for(let[N]of Fr(O,E))k.add(String(N))},K=E=>{for(let[N,U]of Fr(O,E))bt(U)&&k.add(String(N))},I=()=>Wr(this.channels,p,{saver:r,config:h?.config??m,deltaWritesVersioned:y}),{values:D,asNode:Me}=c[0];if(D==null&&Me===void 0){if(c.length>1)throw new M("Cannot create empty checkpoint with multiple updates");let E=h===void 0?{}:es(this.channels,new Set,h.metadata?.counters_since_delta_snapshot),N=k.size>0||Object.entries(E).some(([Oe,me])=>ua(this.channels[Oe],me))?await I():void 0,{channelsToSnapshot:U,metadata:L}=N===void 0?{channelsToSnapshot:new Set,metadata:wi(E)}:ts(N,new Set,h,p.channel_versions,y,k),J=Ye(p,N,f,{channelsToSnapshot:U,storedVersions:d,getNextVersion:w,triggerToNodes:this.triggerToNodes});return zt(await r.put(m,J,{source:"update",step:f+1,parents:h?.metadata?.parents??{},...g,...L},Kt(d,J.channel_versions)),h?h.metadata:void 0)}let Q=await I();if(D===null&&Me==="__end__"){if(c.length>1)throw new M("Cannot apply multiple updates when clearing state");if(h){let me=Jt(p,h.pendingWrites||[],this.nodes,Q,h.config,!0,{step:(h.metadata?.step??-1)+1,checkpointer:r,store:this.store}),Qt=(h.pendingWrites||[]).filter(nt=>nt[0]===fe).map(nt=>nt.slice(1));Qt.length>0&&Se(p,Q,[{name:Ge,writes:Qt,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(let[nt,Rt,ji]of h.pendingWrites||[])["__error__","__interrupt__",ir].includes(Rt)||nt in me&&me[nt].writes.push([Rt,ji]);Se(p,Q,Object.values(me),r.getNextVersion.bind(r),this.triggerToNodes)}let{channelsToSnapshot:E,metadata:N}=ts(Q,S(),h,p.channel_versions,y,k),U=Ye(p,Q,f,{channelsToSnapshot:E,storedVersions:d,getNextVersion:w,triggerToNodes:this.triggerToNodes}),{[Hr]:L,counters_since_delta_snapshot:J,...Oe}=_;return zt(await r.put(m,U,{...Oe,source:"update",step:f+1,parents:h?.metadata?.parents??{},...g,...N},Kt(d,U.channel_versions)),h?h.metadata:void 0)}if(Me==="__copy__"){if(c.length>1)throw new M("Cannot copy checkpoint with multiple updates");if(h==null)throw new M("Cannot copy a non-existent checkpoint");let E=L=>!Array.isArray(L)||L.length===0?!1:L.every(J=>Array.isArray(J)&&J.length===2),N=Ye(p,void 0,f),U=await r.put(h.parentConfig??Xn(h.config,{checkpoint_id:void 0}),N,{source:"fork",step:f+1,parents:h.metadata?.parents??{},...g,...wi(h.metadata?.counters_since_delta_snapshot??{})},{});if(E(D)){let L=Jt(N,h.pendingWrites,this.nodes,Q,U,!1,{step:f+2}),J=Object.values(L).reduce((me,{name:Qt,id:nt})=>(me[Qt]??=[],me[Qt].push({id:nt}),me),{}),Oe=D.reduce((me,Qt)=>{let[nt,Rt]=Qt;me[Rt]??=[];let ji=me[Rt].length,lf=J[Rt]?.[ji]?.id;return me[Rt].push({values:nt,asNode:Rt,taskId:lf}),me},{});return i(zt(U,h.metadata),Object.values(Oe).flat(),!1)}return zt(U,h.metadata)}if(Me==="__input__"){if(c.length>1)throw new M("Cannot apply multiple updates when updating as input");let E=await Qe(bi(this.inputChannels,D));if(E.length===0)throw new M(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);en(O,E),await C()?P(E):h!==void 0&&await r.putWrites(m,E,Ve(Ge,p.id)),Se(p,Q,[{name:Ge,writes:E,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes),K(E);let N=h?.metadata?.step!=null?h.metadata.step+1:-1,{channelsToSnapshot:U,metadata:L}=ts(Q,S(),h,p.channel_versions,y,k),J=Ye(p,Q,N,{channelsToSnapshot:U,storedVersions:d,getNextVersion:w,triggerToNodes:this.triggerToNodes});return zt(await r.put(m,J,{source:"input",step:N,parents:h?.metadata?.parents??{},...g,...L},Kt(d,J.channel_versions)),h?h.metadata:void 0)}if(u.configurable?.checkpoint_id===void 0&&h?.pendingWrites!==void 0&&h.pendingWrites.length>0){let E=Jt(p,h.pendingWrites,this.nodes,Q,h.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(h.metadata?.step??-1)+1}),N=(h.pendingWrites??[]).filter(L=>L[0]===fe).map(L=>L.slice(1));N.length>0&&Se(p,Q,[{name:Ge,writes:N,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(let[L,J,Oe]of h.pendingWrites)["__error__","__interrupt__",ir].includes(J)||E[L]===void 0||E[L].writes.push([J,Oe]);let U=Object.values(E).filter(L=>L.writes.length>0);U.length>0&&Se(p,Q,U,r.getNextVersion.bind(r),this.triggerToNodes)}let W=Nh(p.versions_seen),se=Object.values(W).map(E=>Object.values(E)).flat().find(E=>!!E),q=[];if(c.length===1){let{values:E,asNode:N,taskId:U}=c[0];if(N===void 0&&Object.keys(this.nodes).length===1)[N]=Object.keys(this.nodes);else if(N===void 0&&se===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(N=this.inputChannels);else if(N===void 0){let L=Object.entries(W).map(([J,Oe])=>Object.values(Oe).map(me=>[me,J])).flat().filter(([J,Oe])=>Oe!==B).sort(([J],[Oe])=>Ys(J,Oe));L&&(L.length===1?N=L[0][1]:L[L.length-1][0]!==L[L.length-2][0]&&(N=L[L.length-1][1]))}if(N===void 0)throw new M('Ambiguous update, specify "asNode"');q.push({values:E,asNode:N,taskId:U})}else for(let{asNode:E,values:N,taskId:U}of c){if(E==null)throw new M('"asNode" is required when applying multiple updates');q.push({values:N,asNode:E,taskId:U})}let b=[];for(let[E,{asNode:N,values:U,taskId:L}]of q.entries()){if(this.nodes[N]===void 0)throw new M(`Node "${N.toString()}" does not exist`);let J=this.nodes[N].getWriters();if(!J.length)throw new M(`No writers found for node "${N.toString()}"`);b.push({name:N,input:U,proc:J.length>1?Zt.from(J,{omitSequenceTags:!0}):J[0],writes:[],triggers:[B],path:[B,E],id:L??Ve(E===0?"__interrupt__":`__interrupt__:${E}`,p.id),writers:[]})}for(let E of b)await E.proc.invoke(E.input,He({...u,store:u?.store??this.store},{runName:u.runName??`${this.getName()}UpdateState`,configurable:{[ge]:N=>E.writes.push(...N),[ve]:(N,U=!1)=>Qr(p,Q,E,N,U)}}));for(let E of b)en(O,E.writes);if(await C())for(let E of b)P(E.writes);else for(let E of b){let N=E.writes.filter(U=>U[0]!==Ce);h!==void 0&&N.length>0&&await r.putWrites(m,N,E.id,xt(E.path))}Se(p,Q,b,r.getNextVersion.bind(r),this.triggerToNodes);for(let E of b)K(E.writes);let{channelsToSnapshot:x,metadata:A}=ts(Q,S(),h,p.channel_versions,y,k),R=Ye(p,Q,f+1,{channelsToSnapshot:x,storedVersions:d,getNextVersion:w,triggerToNodes:this.triggerToNodes}),F=await r.put(m,R,{source:"update",step:f+1,parents:h?.metadata?.parents??{},...g,...A},Kt(d,R.channel_versions));for(let E of b){let N=E.writes.filter(U=>U[0]===Ce);N.length>0&&await r.putWrites(F,N,E.id)}return zt(F,h?h.metadata:void 0)},o=e;for(let[a,{updates:c}]of t.entries())o=await i(o,c,a===0);return o}async updateState(e,t,r){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:r}]}])}_defaults(e){let{debug:t,streamMode:r,inputKeys:n,outputKeys:s,interruptAfter:i,interruptBefore:o,...a}=e,c=!0,l=t!==void 0?t:this.debug,u=s;u===void 0?u=this.streamChannelsAsIs:Wa(u,this.channels);let h=n;h===void 0?h=this.inputChannels:Wa(h,this.channels);let p=o??this.interruptBefore??[],d=i??this.interruptAfter??[],f;r!==void 0?(f=Array.isArray(r)?r:[r],c=typeof r=="string"):(e.configurable?.__pregel_task_id!==void 0?f=["values"]:f=this.streamMode,c=!0);let m=this._resolveCheckpointer(e),_=e.store??this.store,y=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let g=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),w=e.durability??g??e?.configurable?.__pregel_durability??"async";return[l,f,h,u,a,p,d,m,_,c,y,w]}async stream(e,t){let r=new AbortController,n=si()?.configurable;n?.__pregel_read!==void 0&&t?.configurable?.__pregel_read===void 0&&(t={...t,configurable:{...n,...t?.configurable}});let s={recursionLimit:this.config?.recursionLimit,...t,signal:qt(t?.signal,r.signal).signal},i=await super.stream(e,s);return new Ii(t?.encoding==="text/event-stream"?Ep(i):i,r)}async#e(e,t){let{version:r,encoding:n,transformers:s,...i}=t,o={recursionLimit:this.config?.recursionLimit,...i,configurable:{...this.config?.configurable,...i?.configurable},version:r,streamMode:va,subgraphs:!0,encoding:void 0},a=this.stream(e,o),c=Pa({[Symbol.asyncIterator]:async function*(){let l=await a;for await(let u of l)yield u}},[...this.streamTransformers??[],...s??[]]);if(n==="text/event-stream"){let l=new AbortController;return l.signal.addEventListener("abort",()=>c.abort(l.signal.reason),{once:!0}),new Ii(Cg(c),l)}return c}streamEvents(e,t,r){if(t.version==="v3")return this.#e(e,t);let n=new AbortController,s={recursionLimit:this.config?.recursionLimit,...t,signal:qt(t?.signal,n.signal).signal};return new Ii(super.streamEvents(e,s,r),n)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){let r="version"in(t??{})?void 0:t?.encoding??void 0,n=t?.subgraphs,s=t?.version==="v3",i=Gr(this.config,t);if(i.recursionLimit===void 0||i.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&i.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');let o=await this._validateInput(e),{runId:a,...c}=i,[l,u,,h,p,d,f,m,_,y,g,w]=this._defaults(c);p.metadata={ls_integration:"langgraph",...p.metadata},typeof p.context<"u"?p.context=await this._validateContext(p.context):p.configurable=await this._validateContext(p.configurable);let S=new La({modes:new Set(u)});p.configurable=this._ownCheckpointConfig(p).configurable;let k={subgraphs:n??!1};if(u.includes("messages")){let W=s?new Lp(q=>S.push(q)):new jp(q=>S.push(q),k),{callbacks:se}=p;if(se===void 0)p.callbacks=[W];else if(Array.isArray(se))p.callbacks=se.concat(W);else{let q=se.copy();q.addHandler(W,!0),p.callbacks=q}}if(u.includes("tools")){let W=new kp(q=>S.push(q),s?void 0:k),{callbacks:se}=p;if(se===void 0)p.callbacks=[W];else if(Array.isArray(se))p.callbacks=se.concat(W);else{let q=se.copy();q.addHandler(W,!0),p.callbacks=q}}p.writer??=W=>{if(!u.includes("custom"))return;let se=si()?.configurable?.[Pe]?.split("|").slice(0,-1);S.push([se??[],"custom",W])},p.interrupt??=this.userInterrupt??wa,p.serverInfo==null&&(p.serverInfo=Tg(p)),p.control??=new ma;let C={tracerInheritableMetadata:Og(p)},O=await(await br._configureSync(p?.callbacks,void 0,p?.tags,void 0,p?.metadata,void 0,C))?.handleChainStart(this.toJSON(),ap(e,"input"),a,void 0,void 0,void 0,p?.runName??this.getName()),P=sp(O),K=Ur(this.channels),I,D,Q=(async()=>{try{I=await Rp.initialize({input:o,config:p,checkpointer:m,nodes:this.nodes,channelSpecs:K,outputKeys:h,streamKeys:this.streamChannelsAsIs,store:_,cache:g,stream:S,interruptAfter:f,interruptBefore:d,manager:O,hasGraphCallbacks:P!==void 0,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:w}),k.parentNs=I.config.configurable?.checkpoint_ns||void 0;let W=new Up({loop:I,nodeFinished:p.configurable?.[bl]});t?.subgraphs&&(I.config.configurable={...I.config.configurable,[un]:I.stream}),await this._runLoop({loop:I,runner:W,debug:l,config:p,emitLifecycleEvents:P}),w==="sync"&&await Promise.all(I?.checkpointerPromises??[])}catch(W){D=W}finally{try{I&&(await I.store?.stop(),await I.cache?.stop()),await Promise.all(I?.checkpointerPromises??[])}catch(W){D=D??W}D?(await new Promise(W=>{queueMicrotask(W)}),S.error(D)):S.close()}})();try{for await(let W of S){if(W===void 0)throw new Error("Data structure error.");let[se,q,b]=W,x="version"in(t??{});if(u.includes(q)||q==="checkpoints"&&Jr(b)&&(s||x&&n&&u.includes("values"))){if(r==="text/event-stream"){n?yield[se,q,b]:yield[null,q,b];continue}n&&!y?yield[se,q,b]:y?n?yield[se,b]:yield b:yield[q,b]}}}catch(W){throw await O?.handleChainError(D),W}finally{await Q}await O?.handleChainEnd(I?.output??{},a,void 0,void 0,void 0)}async invoke(e,t){let r=t?.streamMode??"values",n={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:r,encoding:void 0},s=[],i=await this.stream(e,n),o=[],a;for await(let c of i)r==="values"?sr(c)?o.push(c[B]):a=c:s.push(c);if(r==="values"){if(o.length>0){let c=o.flat(1);if(a==null)return{[B]:c};if(typeof a=="object")return{...a,[B]:c}}return a}return s}async _runLoop(e){let{loop:t,runner:r,debug:n,config:s,emitLifecycleEvents:i}=e,o;try{for(;await t.tick({inputKeys:this.inputChannels});){i&&await i(t.lifecycleEvents);for(let{task:a}of await t._matchCachedWrites())t.putWrites(a.id,a.writes,!0);n&&wp(t.checkpointMetadata.step,t.channels,this.streamChannelsList),n&&is(t.step,Object.values(t.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(a,c)=>{n&&vp(a,c,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(t.status==="draining")throw t.control==null?new Error("Draining status requires run control"):new ys(t.control.drainReason??"shutdown");if(t.status==="out_of_steps")throw new Qi([`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(a){if(o=a,!await t.finishAndHandleError(o))throw a}finally{o===void 0&&await t.finishAndHandleError(),i&&await i(t.lifecycleEvents)}}async clearCache(){await this.cache?.clear([])}};function Tg(e){let t=e.metadata??{},r=e.configurable??{},n=r.assistant_id??t.assistant_id,s=r.graph_id??t.graph_id,i=r.langgraph_auth_user,o;if(i!=null&&typeof i=="object"&&"identity"in i&&(o=i),n!=null||s!=null||o!=null)return{assistantId:n!=null?String(n):"",graphId:s!=null?String(s):"",user:o}}var Ig=new Set(["key","token","secret","password","auth"]);function Ag(e,t){let r=e.toLowerCase(),n=!1;for(let s of Ig)if(r.includes(s)){n=!0;break}return e.startsWith("__")||!(typeof t=="string"||typeof t=="number"||typeof t=="boolean")||n}function Og(e){let t=e.configurable;if(!t)return;let r=e.context,n={};for(let[s,i]of Object.entries(t)){if(r!=null&&Object.prototype.hasOwnProperty.call(r,s)&&Object.is(r[s],i)){s.startsWith("__")||(n[s]=void 0);continue}Ag(s,i)||(n[s]=i)}return Object.keys(n).length>0?n:void 0}var tt=class Gp extends re{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){let r=new Gp(this.guard);return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0){let r=this.value.length>0;return this.value=[],r}if(t.length!==1&&this.guard)throw new M("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new V;return this.value[0]}checkpoint(){if(this.value.length===0)throw new V;return this.value[0]}isAvailable(){return this.value.length!==0}};var Ka=class{path;ends;constructor(e){G.isRunnable(e.path)?this.path=e.path:this.path=ot(e.path),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((t,r)=>(t[r]=r,t),{}):e.pathMap}run(e,t){return X.registerWriter(new he({name:"<branch_run>",trace:!1,func:async(r,n)=>{try{return await this._route(r,n,e,t)}catch(s){throw s.name===ws.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
134
+ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(e,t,r,n){let s=await this.path.invoke(n?n(t):e,t);Array.isArray(s)||(s=[s]);let i;if(this.ends?i=s.map(o=>oe(o)?o:this.ends[o]):i=s,i.some(o=>!o))throw new Error("Branch condition returned unknown or null destination");if(i.filter(oe).some(o=>o.node==="__end__"))throw new M("Cannot send a packet to the END node");return await r(i,t)??e}},za=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}let r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,s,i]of r){for(let a of["|",":"])if(n.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."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n==="__end__")throw new Error(`Node \`${n}\` is reserved.`);let o=ot(s);this.nodes[n]={runnable:o,metadata:i?.metadata,subgraphs:Zn(o)?[o]:i?.subgraphs,ends:i?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e==="__end__")throw new Error("END cannot be a start node");if(t==="__start__")throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([r])=>r===e)&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,r){let n=typeof e=="object"?e:{source:e,path:t,pathMap:r};this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),G.isRunnable(n.path)||(n.path=ot(n.path));let s=n.path.getName()==="RunnableLambda"?"condition":n.path.getName();if(this.branches[n.source]&&this.branches[n.source][s])throw new Error(`Condition \`${s}\` already present for node \`${e}\``);return this.branches[n.source]??={},this.branches[n.source][s]=new Ka(n),this}setEntryPoint(e){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(z,e)}setFinishPoint(e){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(e,Y)}compile({checkpointer:e,interruptBefore:t,interruptAfter:r,name:n,transformers:s}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);let i=new qa({builder:this,checkpointer:e,interruptAfter:r,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[z]:new tt,[Y]:new tt},inputChannels:z,outputChannels:Y,streamChannels:[],streamMode:"values",name:n,streamTransformers:s});for(let[o,a]of Object.entries(this.nodes))i.attachNode(o,a);for(let[o,a]of this.edges)i.attachEdge(o,a);for(let[o,a]of Object.entries(this.branches))for(let[c,l]of Object.entries(a))i.attachBranch(o,c,l);return i.validate()}validate(e){let t=new Set([...this.allEdges].map(([n,s])=>n));for(let[n]of Object.entries(this.branches))t.add(n);for(let n of t)if(n!=="__start__"&&!(n in this.nodes))throw new Error(`Found edge starting at unknown node \`${n}\``);let r=new Set([...this.allEdges].map(([n,s])=>s));for(let[n,s]of Object.entries(this.branches))for(let i of Object.values(s))if(i.ends!=null)for(let o of Object.values(i.ends))r.add(o);else{r.add(Y);for(let o of Object.keys(this.nodes))o!==n&&r.add(o)}for(let n of Object.values(this.nodes))for(let s of n.ends??[])r.add(s);if(Object.values(this.nodes).some(n=>n.isErrorHandler))for(let n of Object.keys(this.nodes))r.add(n);for(let n of Object.keys(this.nodes))if(!this.nodes[n].isErrorHandler&&!r.has(n))throw new ro([`Node \`${n}\` 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(`
135
+ `),{lc_error_code:"UNREACHABLE_NODE"});for(let n of r)if(n!=="__end__"&&!(n in this.nodes))throw new Error(`Found edge ending at unknown node \`${n}\``);if(e){for(let n of e)if(!(n in this.nodes))throw new Error(`Interrupt node \`${n}\` is not present`)}this.compiled=!0}},qa=class extends Ni{builder;constructor({builder:e,...t}){super(t),this.builder=e}withConfig(e){return super.withConfig(e)}attachNode(e,t){this.channels[e]=new tt,this.nodes[e]=new Ze({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new X([{channel:e,value:Ae}],[te])),this.streamChannels.push(e)}attachEdge(e,t){if(t==="__end__"){if(e==="__start__")throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new X([{channel:Y,value:Ae}],[te]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e==="__start__"&&!this.nodes.__start__&&(this.nodes[z]=Wp.subscribeTo(z,{tags:[te]})),this.nodes[e].pipe(r.run(s=>new X(s.map(i=>oe(i)?i:{channel:i==="__end__"?Y:`branch:${e}:${t}:${i}`,value:Ae}),[te])));let n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(let s of n)if(s!=="__end__"){let i=`branch:${e}:${t}:${s}`;this.channels[i]=new tt,this.nodes[s].triggers.push(i),this.nodes[s].channels.push(i)}}async getGraphAsync(e){let t=e?.xray,r=new Hi,n={[z]:r.addNode({schema:$t.any()},z)},s={},i={};t&&(i=Object.fromEntries((await Qe(this.getSubgraphsAsync())).filter(l=>Kp(l[1]))));let o=[];function a(l,u,h,p=!1){if(u==="__end__"&&s.__end__===void 0&&(s[Y]=r.addNode({schema:$t.any()},Y)),n[l]!==void 0){if(s[u]===void 0)throw new Error(`End node ${u} not found!`);return o.push({src:l,dest:u,conditional:p}),r.addEdge(n[l],s[u],h!==u?h:void 0,p)}}for(let[l,u]of Object.entries(this.builder.nodes)){let h=ue(l),p=u.runnable,d={...u.metadata};this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?d.__interrupt="before,after":this.interruptBefore?.includes(l)?d.__interrupt="before":this.interruptAfter?.includes(l)&&(d.__interrupt="after");let f=zp(p);if(f!==void 0&&(d.__tools=f),t){let m=typeof t=="number"?t-1:t,_=i[l]!==void 0?await i[l].getGraphAsync({...e,xray:m}):p.getGraph(e);if(_.trimFirstNode(),_.trimLastNode(),Object.keys(_.nodes).length>1){let w=function(k){return k?k.lc_runnable:!1},S=function(k,C){if(k!==void 0&&!Di(k))return k;if(w(C))try{let O=C.getName();return O=O.startsWith("Runnable")?O.slice(8):O,O}catch{return C.getName()}else return C.name??"UnknownSchema"},[y,g]=r.extend(_,h);if(y===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);g!==void 0&&(n[h]={name:S(g.id,g.data),...g}),s[h]={name:S(y.id,y.data),...y}}else{let y=r.addNode(p,h,d);n[h]=y,s[h]=y}}else{let m=r.addNode(p,h,d);n[h]=m,s[h]=m}}let c=[...this.builder.allEdges].sort(([l],[u])=>l<u?-1:u>l?1:0);for(let[l,u]of c)a(ue(l),ue(u));for(let[l,u]of Object.entries(this.builder.branches)){let h={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==l).map(p=>[ue(p),ue(p)])),[Y]:Y};for(let p of Object.values(u)){let d;p.ends!==void 0?d=p.ends:d=h;for(let[f,m]of Object.entries(d))a(ue(l),ue(m),f,!0)}}for(let[l,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let h of u.ends)a(ue(l),ue(h),void 0,!0);return qp(this.builder.nodes,o,a),r}getGraph(e){let t=e?.xray,r=new Hi,n={[z]:r.addNode({schema:$t.any()},z)},s={},i={};t&&(i=Object.fromEntries(Gt(this.getSubgraphs()).filter(l=>Kp(l[1]))));let o=[];function a(l,u,h,p=!1){if(u==="__end__"&&s.__end__===void 0&&(s[Y]=r.addNode({schema:$t.any()},Y)),n[l]!==void 0){if(s[u]===void 0)throw new Error(`End node ${u} not found!`);return o.push({src:l,dest:u,conditional:p}),r.addEdge(n[l],s[u],h!==u?h:void 0,p)}}for(let[l,u]of Object.entries(this.builder.nodes)){let h=ue(l),p=u.runnable,d={...u.metadata};this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?d.__interrupt="before,after":this.interruptBefore?.includes(l)?d.__interrupt="before":this.interruptAfter?.includes(l)&&(d.__interrupt="after");let f=zp(p);if(f!==void 0&&(d.__tools=f),t){let m=typeof t=="number"?t-1:t,_=i[l]!==void 0?i[l].getGraph({...e,xray:m}):p.getGraph(e);if(_.trimFirstNode(),_.trimLastNode(),Object.keys(_.nodes).length>1){let w=function(k){return k?k.lc_runnable:!1},S=function(k,C){if(k!==void 0&&!Di(k))return k;if(w(C))try{let O=C.getName();return O=O.startsWith("Runnable")?O.slice(8):O,O}catch{return C.getName()}else return C.name??"UnknownSchema"},[y,g]=r.extend(_,h);if(y===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);g!==void 0&&(n[h]={name:S(g.id,g.data),...g}),s[h]={name:S(y.id,y.data),...y}}else{let y=r.addNode(p,h,d);n[h]=y,s[h]=y}}else{let m=r.addNode(p,h,d);n[h]=m,s[h]=m}}let c=[...this.builder.allEdges].sort(([l],[u])=>l<u?-1:u>l?1:0);for(let[l,u]of c)a(ue(l),ue(u));for(let[l,u]of Object.entries(this.builder.branches)){let h={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==l).map(p=>[ue(p),ue(p)])),[Y]:Y};for(let p of Object.values(u)){let d;p.ends!==void 0?d=p.ends:d=h;for(let[f,m]of Object.entries(d))a(ue(l),ue(m),f,!0)}}for(let[l,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let h of u.ends)a(ue(l),ue(h),void 0,!0);return qp(this.builder.nodes,o,a),r}};function Kp(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function ue(e){return e==="subgraph"?`"${e}"`:e}function zp(e){let t=e?.tools;if(!(!Array.isArray(t)||t.length===0||!t.every(r=>typeof r?.name=="string")))return t.map(r=>r.name)}function qp(e,t,r){let n=new Set(t.map(i=>i.src)),s=[...new Set(t.filter(i=>!i.conditional&&i.dest!=="__end__").map(i=>i.dest))].sort();for(let i of s){if(n.has(i))continue;let o=Object.keys(e).find(a=>ue(a)===i);o!==void 0&&e[o]?.isErrorHandler||r(i,Y)}}function It(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function Ja(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function Pg(e){return It(e)&&Ja(e)}function Yt(e){if(Ja(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function At(e){if(e!=null&&It(e))try{let t=e["~standard"].validate(void 0);if(t&&typeof t=="object"&&!("then"in t&&typeof t.then=="function")){let r=t;if(!r.issues){let n=r.value;return()=>n}}}catch{}}var Ng=e=>e!=null&&e.lc_graph_name==="DeltaChannel",Ri=class Jp extends re{lc_graph_name="DeltaChannel";value;reducer;snapshotFrequency;initialValueFactory;constructor(t,r){super();let n=r?.snapshotFrequency??100;if(!Number.isInteger(n)||n<=0)throw new Error(`snapshotFrequency must be a positive integer, got ${n}`);this.reducer=t,this.snapshotFrequency=n,this.initialValueFactory=r?.initialValueFactory??(()=>[]),this.value=void 0}fromCheckpoint(t){let r=new Jp(this.reducer,{snapshotFrequency:this.snapshotFrequency,initialValueFactory:this.initialValueFactory});return t===void 0?r.value=this.initialValueFactory():vn(t)?r.value=t.value:r.value=t,r}replayWrites(t){let r=t.map(o=>o[2]);if(r.length===0)return;let n=this.value,s=0;for(let o=0;o<r.length;o+=1){let[a,c]=xe(r[o]);a&&(n=c??this.initialValueFactory(),s=o+1)}let i=r.slice(s);this.value=i.length>0?this.reducer(n,i):n}update(t){if(t.length===0)return!1;let r,n=!1;for(let i of t)if(bt(i)){if(n)throw new M("Can receive only one Overwrite value per step.");n=!0,[,r]=xe(i)}if(n)return this.value=r??this.initialValueFactory(),!0;let s=this.value===void 0?this.initialValueFactory():this.value;return this.value=this.reducer(s,t),!0}get(){if(this.value===void 0)throw new V;return this.value}checkpoint(){}isAvailable(){return this.value!==void 0}equals(t){return this===t?!0:!Ng(t)||this.snapshotFrequency!==t.snapshotFrequency?!1:this.reducer===t.reducer}};var Ya=Symbol.for("langgraph.channel.missing"),Mi=class Yp extends re{lc_graph_name="UntrackedValue";guard;_value=Ya;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new Yp({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new M("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=t[t.length-1],!0}get(){if(this._value===Ya)throw new V;return this._value}checkpoint(){}isAvailable(){return this._value!==Ya}};var Xt=(e,t)=>e.size===t.size&&[...e].every(r=>t.has(r)),Xa=class Xp extends re{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let r=new Xp(this.names);return typeof t<"u"&&(r.seen=new Set(t)),r}update(t){let r=!1;for(let n of t)if(this.names.has(n))this.seen.has(n)||(this.seen.add(n),r=!0);else throw new M(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!Xt(this.names,this.seen))throw new V}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&Xt(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&Xt(this.names,this.seen)}},Qa=class Qp extends re{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(t){super(),this.names=t,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let r=new Qp(this.names);if(typeof t<"u"){let[n,s]=t;r.seen=new Set(n),r.finished=s}return r}update(t){let r=!1;for(let n of t)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),r=!0;else if(!this.names.has(n))throw new M(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!Xt(this.names,this.seen))throw new V}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&Xt(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&Xt(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&Xt(this.names,this.seen)}};var Za=Symbol.for("langgraph.state.reduced_value"),Ot=class{[Za]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema="inputSchema"in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e=="object"&&e!==null&&Za in e&&e[Za]===!0}};var Zp=Symbol.for("langgraph.state.untracked_value"),fr=class{[Zp]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&Zp in e}};var ec=Symbol.for("langgraph.state.delta_value"),Pt=class{[ec]=!0;valueSchema;inputSchema;reducer;snapshotFrequency;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.valueSchema=e,this.inputSchema="inputSchema"in t?t.inputSchema:e,this.snapshotFrequency=t.snapshotFrequency,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e=="object"&&e!==null&&ec in e&&e[ec]===!0}};var tc=Symbol.for("langgraph.state.state_schema"),rt=class{[tc]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,r]of Object.entries(this.fields))if(Pt.isInstance(r)){let n=At(r.valueSchema);e[t]=new Ri(r.reducer,{snapshotFrequency:r.snapshotFrequency,initialValueFactory:n})}else if(Ot.isInstance(r)){let n=At(r.valueSchema);e[t]=new Et(r.reducer,n)}else if(fr.isInstance(r)){let n=r.schema?At(r.schema):void 0;e[t]=new Mi({guard:r.guard,initialValueFactory:n})}else if(It(r))e[t]=new Xe(At(r));else throw new Error(`Invalid state field "${t}": must be a schema, ReducedValue, DeltaValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[r,n]of Object.entries(this.fields)){let s;if(Pt.isInstance(n)||Ot.isInstance(n)?(s=Yt(n.valueSchema),n.jsonSchemaExtra&&(s={...s??{},...n.jsonSchemaExtra})):fr.isInstance(n)?s=n.schema?Yt(n.schema):void 0:It(n)&&(s=Yt(n)),s){e[r]=s;let i=!1;Pt.isInstance(n)||Ot.isInstance(n)?i=At(n.valueSchema)!==void 0:fr.isInstance(n)?i=n.schema?At(n.schema)!==void 0:!1:i=At(n)!==void 0,i||t.push(r)}}return{type:"object",properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,r]of Object.entries(this.fields)){let n;Pt.isInstance(r)||Ot.isInstance(r)?(n=Yt(r.inputSchema),r.jsonSchemaExtra&&(n={...n??{},...r.jsonSchemaExtra})):fr.isInstance(r)?n=r.schema?Yt(r.schema):void 0:It(r)&&(n=Yt(r)),n&&(e[t]=n)}return{type:"object",properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(e==null||typeof e!="object")return e;let t={};for(let[r,n]of Object.entries(e)){let s=this.fields[r];if(s===void 0){t[r]=n;continue}let i;if(Pt.isInstance(s)||Ot.isInstance(s)){let[o,a]=xe(n);if(o){i=s.valueSchema;let c=await i["~standard"].validate(a);if(c.issues)throw new Error(`Validation failed for field "${r}": ${JSON.stringify(c.issues)}`);t[r]={[at]:c.value};continue}i=s.inputSchema}else fr.isInstance(s)?i=s.schema:It(s)&&(i=s);if(i){let o=await i["~standard"].validate(n);if(o.issues)throw new Error(`Validation failed for field "${r}": ${JSON.stringify(o.issues)}`);t[r]=o.value}else t[r]=n}return t}static isInstance(e){return typeof e=="object"&&e!==null&&tc in e&&e[tc]===!0}};var ef=$t.custom().default(()=>[]),tf=$t.custom(),Rg=new Ot(ef,{inputSchema:tf,reducer:Wt,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}}),Mg=new Pt(ef,{inputSchema:tf,reducer:pi,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var $g=class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let r=this.get(e);this._map.set(e,t(r))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},r=an(e);for(let[n,s]of Object.entries(r)){let i=this.get(s);i?.reducer?t[n]=new Et(i.reducer.fn,i.default):t[n]=new Xe(i?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let r=Object.entries(t).filter(([,i])=>i===!0).sort(([i],[o])=>i.localeCompare(o)).map(([i,o])=>`${i}:${o}`).join("|"),n=this._extensionCache.get(r)??new Map;if(n.has(e))return n.get(e);let s=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let i=Object.entries(an(e)).map(([o,a])=>{let c=this.get(a),l=t.withReducerSchema?c?.reducer?.schema??a:a;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let u=Ui(l)??Ui(a),h=JSON.stringify({...c.jsonSchemaExtra,description:u});l=l.describe(`lg:${h}`)}return[o,l]});s=Rc(e,Object.fromEntries(i)),Pc(s)&&(s._def.unknownKeys="strip")}return t.asPartial&&(s=Sr(s)),n.set(e,s),this._extensionCache.set(r,n),s}},as=new $g;function rf(e,t){if(t.reducer&&!t.default){let r=Mc(e);r!=null&&(t.default=r)}if(t.reducer){let r=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return as.extend(r,()=>t),r}else return as.extend(e,()=>t),e}function dr(e){return e==null?!1:!!(rt.isInstance(e)||ke(e)||typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||ca(t)))}function nf(e){if(typeof e!="object"||e==null)return!1;let t=e,r="state"in t&&dr(t.state),n="stateSchema"in t&&dr(t.stateSchema),s="input"in t&&dr(t.input);return!(!r&&!n&&!s||"input"in t&&t.input!=null&&!dr(t.input)||"output"in t&&t.output!=null&&!dr(t.output))}var Nt="__root__",tn="__default_error_handler__",$i=Symbol.for("langgraph.state.partial"),rc=class extends za{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=as;_configSchema;_configRuntimeSchema;_interrupt;_writer;_nodeDefaults={};constructor(e,t){super();let r=this._normalizeToStateGraphInit(e,t),n=r.state??r.stateSchema??r.input;if(!n)throw new gn;let s=this._getChannelsFromSchema(n);this._schemaDefinition=s,rt.isInstance(n)?this._schemaRuntimeDefinition=n:ke(n)&&(this._schemaRuntimeDefinition=n),r.input?rt.isInstance(r.input)?this._inputRuntimeDefinition=r.input:ke(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=$i:this._inputRuntimeDefinition=$i,r.output?rt.isInstance(r.output)?this._outputRuntimeDefinition=r.output:ke(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let i=r.input?this._getChannelsFromSchema(r.input):s,o=r.output?this._getChannelsFromSchema(r.output):s;this._inputDefinition=i,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&ke(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}setNodeDefaults(e){return e.retryPolicy!==void 0&&(this._nodeDefaults.retryPolicy=e.retryPolicy),e.cachePolicy!==void 0&&(this._nodeDefaults.cachePolicy=typeof e.cachePolicy=="boolean"?e.cachePolicy?{}:void 0:e.cachePolicy),e.timeout!==void 0&&(this._nodeDefaults.timeout=jt(e.timeout)),e.errorHandler!==void 0&&(this._nodeDefaults.errorHandler=e.errorHandler),this}_createDefaultErrorHandlerSpec(){let e=this._nodeDefaults.errorHandler;if(e!==void 0)return{runnable:new he({func:(t,r)=>{let n=r?.configurable?.[hn];return e(t,n,r)},name:tn,trace:!1}),metadata:void 0,input:this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0}}_normalizeToStateGraphInit(e,t){if(nf(e)){if(ke(t)||ri.isInstance(t))return{...e,context:t};let r=t;return{...e,input:e.input??r?.input,output:e.output??r?.output,context:e.context??r?.context,interrupt:e.interrupt??r?.interrupt,writer:e.writer??r?.writer,nodes:e.nodes??r?.nodes}}if(dr(e)){if(ke(t)||ri.isInstance(t))return{state:e,context:t};let r=t;return{state:e,input:r?.input,output:r?.output,context:r?.context,interrupt:r?.interrupt,writer:r?.writer,nodes:r?.nodes}}if(Dg(e))return{state:jg(e.channels)};throw new gn}_getChannelsFromSchema(e){if(rt.isInstance(e))return e.getChannels();if(ke(e))return this._metaRegistry.getChannelsForSchema(e);if(typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot")return e.spec;if(typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0)return e;throw new gn("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(r=>[r,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,r]of Object.entries(e)){let n;if(typeof r=="function"?n=r():n=r,this.channels[t]!==void 0){if(!this.channels[t].equals(n)&&n.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=n}}}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}let r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([n,s])=>[n,s]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,s,i]of r){if(n in this.channels)throw new Error(`${n} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let p of["|",":"])if(n.includes(p))throw new Error(`"${p}" 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."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n==="__end__"||n==="__start__")throw new Error(`Node \`${n}\` is reserved.`);let o=this._schemaDefinition;i?.input!==void 0&&(o=this._getChannelsFromSchema(i.input)),this._addSchema(o);let a;G.isRunnable(s)?a=s:typeof s=="function"?a=new he({func:s,name:n,trace:!1}):a=ot(s);let c=i?.cachePolicy,l;c!==void 0&&(l=typeof c=="boolean"?c?{}:!1:c);let u;if(i?.errorHandler!==void 0){if(u=`__error_handler__${n}`,u in this.nodes)throw new Error(`Cannot add error handler to node \`${n}\`: the reserved name \`${u}\` is already in use. StateGraph registers \`__error_handler__<nodeName>\` when you pass \`errorHandler\` in addNode options. Remove or rename the existing node with that name (for example, you may have added it manually).`);let p=i.errorHandler,d={runnable:new he({func:(f,m)=>{let _=m?.configurable?.[hn];return p(f,_,m)},name:u,trace:!1}),metadata:void 0,input:o??this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0};this.nodes[u]=d}let h={runnable:a,retryPolicy:i?.retryPolicy,cachePolicy:l,timeout:jt(i?.timeout),tracePolicy:i?.tracePolicy,metadata:i?.metadata,input:o??this._schemaDefinition,subgraphs:Zn(a)?[a]:i?.subgraphs,ends:i?.ends,defer:i?.defer,errorHandlerNode:u};this.nodes[n]=h}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);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(let r of e){if(r==="__end__")throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(n=>n===r))throw new Error(`Need to add a node named "${r}" first`)}if(t==="__end__")throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(r=>r===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let r;for(let[n,s,i]of t){if(n in this.nodes)throw new Error(`Node names must be unique: node with the name "${n}" already exists.`);let o=n;this.addNode(n,s,i),r!=null&&this.addEdge(r,o),r=o}return this}compile({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:o,transformers:a}={}){let c=this._createDefaultErrorHandlerSpec();if(c!==void 0){if(tn in this.nodes)throw new Error(`Cannot apply a default error handler: the reserved node name \`${tn}\` is already in use. setNodeDefaults({ errorHandler }) registers a node with that name; rename the conflicting node.`);this.nodes[tn]=c}try{return this._compileResolved({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:o,transformers:a,defaultErrorHandlerNode:c!==void 0?tn:void 0})}finally{c!==void 0&&delete this.nodes[tn]}}_compileResolved({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:o,transformers:a,defaultErrorHandlerNode:c}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(s)?s:[]]);let l=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),u=l.length===1&&l[0]===Nt?Nt:l,h=Object.keys(this.channels),p=h.length===1&&h[0]===Nt?Nt:h,d=this._interrupt,f=new of({builder:this,checkpointer:e,interruptAfter:s,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[z]:new tt},inputChannels:z,outputChannels:u,streamChannels:p,streamMode:"updates",store:t,cache:r,name:i,description:o,userInterrupt:d,streamTransformers:a});f.attachNode(z);let m=this._nodeDefaults,_=m.retryPolicy!==void 0||m.cachePolicy!==void 0||m.timeout!==void 0||c!==void 0;for(let[y,g]of Object.entries(this.nodes)){let w=g.isErrorHandler===!0,S=_?{...g,retryPolicy:g.retryPolicy??m.retryPolicy,cachePolicy:w||g.cachePolicy===!1?void 0:g.cachePolicy??m.cachePolicy,timeout:g.timeout??m.timeout,errorHandlerNode:!w&&c!==void 0&&g.errorHandlerNode===void 0?c:g.errorHandlerNode}:g;f.attachNode(y,S)}f.attachBranch(z,Yi,sf(),{withReader:!1});for(let[y]of Object.entries(this.nodes))f.attachBranch(y,Yi,sf(),{withReader:!1});for(let[y,g]of this.edges)f.attachEdge(y,g);for(let[y,g]of this.waitingEdges)f.attachEdge(y,g);for(let[y,g]of Object.entries(this.branches))for(let[w,S]of Object.entries(g))f.attachBranch(y,w,S);return f.validate()}};function jg(e){let t={};for(let[r,n]of Object.entries(e))r===Nt?t[r]=ni(n):t[r]=ni(n);return t}var of=class extends qa{description;_metaRegistry=as;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let r;e==="__start__"?r=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([c])=>c):r=Object.keys(this.builder.channels);function n(c){if(ae(c))return c.graph===Ee.PARENT?null:c._updateAsTuples();if(Array.isArray(c)&&c.length>0&&c.some(l=>ae(l))){let l=[];for(let u of c)if(ae(u)){if(u.graph===Ee.PARENT)continue;l.push(...u._updateAsTuples())}else l.push([Nt,u]);return l}else if(c!=null)return[[Nt,c]];return null}let s=e,i=async c=>{if(c==null||c.length===0)return c;let l=this.builder._schemaRuntimeDefinition;if(rt.isInstance(l)){let u=new Set(l.getChannelKeys());return Promise.all(c.map(async([h,p])=>{if(!u.has(h))return[h,p];let d=await l.validateInput({[h]:p});return[h,Object.prototype.hasOwnProperty.call(d,h)?d[h]:p]}))}if(ke(l)){let u=new Set(Object.keys(an(l)));if(c.filter(([d])=>u.has(d)).length===0)return c;let h=Sr(this._metaRegistry.getExtendedChannelSchemas(l,{withReducerSchema:!0})),p=Sr(l);return c.map(([d,f])=>{if(!u.has(d))return[d,f];let[m,_]=xe(f);if(m){let g=Mt(p,{[d]:_});return[d,Object.prototype.hasOwnProperty.call(g,d)?{[at]:g[d]}:f]}let y=Mt(h,{[d]:f});return[d,Object.prototype.hasOwnProperty.call(y,d)?y[d]:f]})}return c};async function o(c){if(c){if(ae(c))return c.graph===Ee.PARENT?null:i(c._updateAsTuples().filter(([l])=>r.includes(l)));if(Array.isArray(c)&&c.length>0&&c.some(ae)){let l=[];for(let u of c)if(ae(u)){if(u.graph===Ee.PARENT)continue;l.push(...u._updateAsTuples().filter(([h])=>r.includes(h)))}else{let h=await o(u);h&&l.push(...h??[])}return i(l)}else{if(typeof c=="object"&&!Array.isArray(c))return i(Object.entries(c).filter(([l])=>r.includes(l)));{let l=Array.isArray(c)?"array":typeof c;throw new M(`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}let a=[{value:Ae,mapper:new he({func:r.length&&r[0]===Nt?n:o,trace:!1,recurse:!1})}];if(e==="__start__")this.nodes[e]=new Ze({tags:[te],triggers:[z],channels:[z],writers:[new X(a,[te])]});else{let c=t?.input??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(c)).map(f=>[f,f])),u=Object.keys(l).length===1&&Nt in l,h=`branch:to:${e}`;this.channels[h]=t?.defer?new ha:new tt(!1);let p=t?.cachePolicy,d=p===!1?void 0:p;this.nodes[e]=new Ze({triggers:[h],channels:u?Object.keys(l):l,writers:[new X(a,[te])],mapper:u?void 0:f=>Object.fromEntries(Object.entries(f).filter(([m])=>m in l)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:d,timeout:t?.timeout,tracePolicy:t?.tracePolicy,subgraphs:t?.subgraphs,ends:t?.ends,isErrorHandler:t?.isErrorHandler,errorHandlerNode:t?.errorHandlerNode})}}attachEdge(e,t){if(t!=="__end__"){if(typeof e=="string")this.nodes[e].writers.push(new X([{channel:`branch:to:${t}`,value:null}],[te]));else if(Array.isArray(e)){let r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new Qa(new Set(e)):new Xa(new Set(e)),this.nodes[t].triggers.push(r);for(let n of e)this.nodes[n].writers.push(new X([{channel:r,value:n}],[te]))}}}attachBranch(e,t,r,n={withReader:!0}){let s=async(i,o)=>{let a=i.filter(l=>l!==Y);if(!a.length)return;let c=a.map(l=>oe(l)?l:{channel:l==="__end__"?l:`branch:to:${l}`,value:e});await X.doWrite({...o,tags:(o.tags??[]).concat([te])},c)};this.nodes[e].writers.push(r.run(s,n.withReader?i=>rp.doRead(i,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition;if(rt.isInstance(t)){if(ae(e)){let s=e;return e.update&&(s.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await t.validateInput(e)}if(t===$i&&rt.isInstance(r)){if(ae(e)){let s=e;return e.update&&(s.update=await r.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await r.validateInput(e)}let n=(()=>{let s=i=>{if(i!=null)return this._metaRegistry.getExtendedChannelSchemas(i,{withReducerSchema:!0})};if(ke(t))return s(t);if(t===$i)return ke(r)?Sr(s(r)):void 0})();if(ae(e)){let s=e;if(e.update&&n!=null){let i=Array.isArray(e.update)?Object.fromEntries(e.update):e.update,o=Mt(n,i);s.update=Object.fromEntries(Object.keys(i).map(a=>[a,o[a]]))}return s}return n!=null?Mt(n,e):e}isInterrupted(e){return sr(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return ke(t)&&Mt(t,e),e}};function Dg(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function Vg(e){if(oe(e))return[e];let t=[];ae(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(ae));let r=[];for(let n of t){if(n.graph===Ee.PARENT)throw new bs(n);oe(n.goto)||typeof n.goto=="string"?r.push(n.goto):Array.isArray(n.goto)&&r.push(...n.goto)}return r}function sf(){return new Ka({path:new he({func:Vg,tags:[te],trace:!1,recurse:!1,name:"<control_branch>"})})}var Lg=class extends rc{constructor(){super({channels:{__root__:{reducer:Wt,default:()=>[]}}})}};function Fg(e,t){let{stateKey:r,...n}=t??{},s=Gr(n),i=r??"messages";r===null&&(i=void 0);let o=Be(e);if(!o.id)throw new Error("Message ID is required.");let a=Array.isArray(s.callbacks)?s.callbacks:typeof s.callbacks<"u"?s.callbacks.handlers:[],c=a.filter(u=>"name"in u&&u.name==="StreamMessagesHandler"),l=a.find(u=>"name"in u&&u.name==="StreamProtocolMessagesHandler");if(c.length>0||l){let u=s.metadata??{},h=u.langgraph_checkpoint_ns??"",p=h.split("|");if(c.length>0)for(let d of c){let f=d.namespaceOptions,m=os(h,u,f);Zr(m,f)||d._emit([m,u],o,void 0,!1)}else l&&l.emitFinalMessage([p,u],o,void 0,!1)}return i&&s.configurable?.__pregel_send?.([[i,o]]),o}function Ug(e,t){let r=typeof e=="string"?{name:e,retry:void 0,cachePolicy:void 0,timeout:void 0}:e,{name:n,retry:s}=r,i=jt(r.timeout);if(Na(t)||Ra(t))throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write.");let o=r.cachePolicy??("cache"in r?r.cache:void 0),a;return typeof o=="boolean"?a=o?{}:void 0:a=o,(...c)=>pp({func:t,name:n,retry:s,cache:a,timeout:i},...c)}var af=function(t,r){let{name:n,checkpointer:s,store:i,cache:o}=typeof t=="string"?{name:t,checkpointer:void 0,store:void 0}:t,a=jt(typeof t=="string"?void 0:t.timeout);if(Na(r)||Ra(r))throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");let c="updates",l=hp(n,r);function u(f){return typeof f=="object"&&f!==null&&"__lg_type"in f&&f.__lg_type==="__pregel_final"}let h=new he({name:"pluckReturnValue",func:f=>u(f)?f.value:f}),p=new he({name:"pluckSaveValue",func:f=>u(f)?f.save:f}),d=new Ze({bound:l,triggers:[z],channels:[z],timeout:a,writers:[new X([{channel:Y,value:Ae,mapper:h},{channel:Ut,value:Ae,mapper:p}],[te])]});return new Ni({name:n,checkpointer:s,nodes:{[n]:d},channels:{[z]:new tt,[Y]:new Xe,[Ut]:new Xe},inputChannels:z,outputChannels:Y,streamChannels:Y,streamMode:c,store:i,cache:o})};af.final=function({value:t,save:r}){return{value:t,save:r,__lg_type:"__pregel_final"}};function Bg(){return ie.getRunnableConfig().configurable?.[Vt]}var Hg=zn.Root({messages:zn({reducer:Wt,default:()=>[]})}),cf={reducer:{fn:Wt},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},Wg=Bi.object({messages:rf(Bi.custom(),cf)});function Gg(e){let t=ie.getRunnableConfig();if(!t)throw new Error("Called interrupt() outside the context of a graph.");let r=t.configurable;if(!r)throw new Error("No configurable found in config");return r.writer?.(e)}export{jr as a,z as b,Y as c,B as d,Ji as e,Cl as f,tr as g,Xi as h,sr as i,Ee as j,ae as k,Ne as l,_s as m,Qi as n,mn as o,ys as p,Tr as q,Ke as r,ws as s,vs as t,pf as u,bs as v,Zi as w,Bt as x,eo as y,to as z,De as A,Ss as B,ff as C,ks as D,Ir as E,df as F,V as G,M as H,mf as I,ro as J,gf as K,gn as L,_f as M,lr as N,Je as O,Js as P,Ch as Q,Lr as R,Qs as S,Ah as T,re as U,Et as V,zn as W,_m as X,ym as Y,si as Z,wm as _,da as $,ma as aa,wa as ba,Lm as ca,Wt as da,pi as ea,va as fa,Jr as ga,ba as ha,Fe as ia,di as ja,Ca as ka,Jn as la,Yn as ma,xa as na,Ta as oa,mi as pa,Oa as qa,tp as ra,Pa as sa,za as ta,It as ua,Pg as va,Yt as wa,At as xa,Ri as ya,Mi as za,Ot as Aa,fr as Ba,Pt as Ca,rt as Da,Rg as Ea,Mg as Fa,as as Ga,rf as Ha,rc as Ia,of as Ja,Lg as Ka,Fg as La,Ug as Ma,af as Na,Bg as Oa,Hg as Pa,cf as Qa,Wg as Ra,Gg as Sa};