@langchain/langgraph 0.4.7 → 1.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (494) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +1 -2
  3. package/dist/_virtual/rolldown_runtime.cjs +25 -0
  4. package/dist/channels/any_value.d.cts +26 -0
  5. package/dist/channels/any_value.d.cts.map +1 -0
  6. package/dist/channels/any_value.d.ts +16 -9
  7. package/dist/channels/any_value.d.ts.map +1 -0
  8. package/dist/channels/base.cjs +97 -133
  9. package/dist/channels/base.cjs.map +1 -0
  10. package/dist/channels/base.d.cts +73 -0
  11. package/dist/channels/base.d.cts.map +1 -0
  12. package/dist/channels/base.d.ts +73 -74
  13. package/dist/channels/base.d.ts.map +1 -0
  14. package/dist/channels/base.js +94 -127
  15. package/dist/channels/base.js.map +1 -1
  16. package/dist/channels/binop.cjs +47 -77
  17. package/dist/channels/binop.cjs.map +1 -0
  18. package/dist/channels/binop.d.cts +22 -0
  19. package/dist/channels/binop.d.cts.map +1 -0
  20. package/dist/channels/binop.d.ts +17 -12
  21. package/dist/channels/binop.d.ts.map +1 -0
  22. package/dist/channels/binop.js +45 -71
  23. package/dist/channels/binop.js.map +1 -1
  24. package/dist/channels/dynamic_barrier_value.d.cts +43 -0
  25. package/dist/channels/dynamic_barrier_value.d.cts.map +1 -0
  26. package/dist/channels/dynamic_barrier_value.d.ts +20 -34
  27. package/dist/channels/dynamic_barrier_value.d.ts.map +1 -0
  28. package/dist/channels/ephemeral_value.cjs +46 -70
  29. package/dist/channels/ephemeral_value.cjs.map +1 -0
  30. package/dist/channels/ephemeral_value.d.cts +23 -0
  31. package/dist/channels/ephemeral_value.d.cts.map +1 -0
  32. package/dist/channels/ephemeral_value.d.ts +18 -11
  33. package/dist/channels/ephemeral_value.d.ts.map +1 -0
  34. package/dist/channels/ephemeral_value.js +45 -65
  35. package/dist/channels/ephemeral_value.js.map +1 -1
  36. package/dist/channels/index.cjs +2 -10
  37. package/dist/channels/index.js +4 -3
  38. package/dist/channels/last_value.cjs +91 -140
  39. package/dist/channels/last_value.cjs.map +1 -0
  40. package/dist/channels/last_value.d.cts +30 -0
  41. package/dist/channels/last_value.d.cts.map +1 -0
  42. package/dist/channels/last_value.d.ts +15 -23
  43. package/dist/channels/last_value.d.ts.map +1 -0
  44. package/dist/channels/last_value.js +88 -133
  45. package/dist/channels/last_value.js.map +1 -1
  46. package/dist/channels/named_barrier_value.cjs +114 -170
  47. package/dist/channels/named_barrier_value.cjs.map +1 -0
  48. package/dist/channels/named_barrier_value.d.cts +33 -0
  49. package/dist/channels/named_barrier_value.d.cts.map +1 -0
  50. package/dist/channels/named_barrier_value.d.ts +19 -29
  51. package/dist/channels/named_barrier_value.d.ts.map +1 -0
  52. package/dist/channels/named_barrier_value.js +112 -163
  53. package/dist/channels/named_barrier_value.js.map +1 -1
  54. package/dist/channels/topic.cjs +63 -96
  55. package/dist/channels/topic.cjs.map +1 -0
  56. package/dist/channels/topic.d.cts +26 -0
  57. package/dist/channels/topic.d.cts.map +1 -0
  58. package/dist/channels/topic.d.ts +21 -18
  59. package/dist/channels/topic.d.ts.map +1 -0
  60. package/dist/channels/topic.js +61 -90
  61. package/dist/channels/topic.js.map +1 -1
  62. package/dist/constants.cjs +373 -452
  63. package/dist/constants.cjs.map +1 -0
  64. package/dist/constants.d.cts +284 -0
  65. package/dist/constants.d.cts.map +1 -0
  66. package/dist/constants.d.ts +112 -148
  67. package/dist/constants.d.ts.map +1 -0
  68. package/dist/constants.js +333 -444
  69. package/dist/constants.js.map +1 -1
  70. package/dist/errors.cjs +150 -179
  71. package/dist/errors.cjs.map +1 -0
  72. package/dist/errors.d.cts +80 -0
  73. package/dist/errors.d.cts.map +1 -0
  74. package/dist/errors.d.ts +55 -46
  75. package/dist/errors.d.ts.map +1 -0
  76. package/dist/errors.js +139 -165
  77. package/dist/errors.js.map +1 -1
  78. package/dist/func/index.cjs +289 -290
  79. package/dist/func/index.cjs.map +1 -0
  80. package/dist/func/index.d.cts +289 -0
  81. package/dist/func/index.d.cts.map +1 -0
  82. package/dist/func/index.d.ts +81 -71
  83. package/dist/func/index.d.ts.map +1 -0
  84. package/dist/func/index.js +285 -284
  85. package/dist/func/index.js.map +1 -1
  86. package/dist/func/types.d.cts +64 -0
  87. package/dist/func/types.d.cts.map +1 -0
  88. package/dist/func/types.d.ts +24 -19
  89. package/dist/func/types.d.ts.map +1 -0
  90. package/dist/graph/annotation.cjs +96 -120
  91. package/dist/graph/annotation.cjs.map +1 -0
  92. package/dist/graph/annotation.d.cts +116 -0
  93. package/dist/graph/annotation.d.cts.map +1 -0
  94. package/dist/graph/annotation.d.ts +33 -34
  95. package/dist/graph/annotation.d.ts.map +1 -0
  96. package/dist/graph/annotation.js +91 -112
  97. package/dist/graph/annotation.js.map +1 -1
  98. package/dist/graph/graph.cjs +419 -723
  99. package/dist/graph/graph.cjs.map +1 -0
  100. package/dist/graph/graph.d.cts +131 -0
  101. package/dist/graph/graph.d.cts.map +1 -0
  102. package/dist/graph/graph.d.ts +122 -91
  103. package/dist/graph/graph.d.ts.map +1 -0
  104. package/dist/graph/graph.js +412 -713
  105. package/dist/graph/graph.js.map +1 -1
  106. package/dist/graph/index.cjs +4 -17
  107. package/dist/graph/index.js +6 -5
  108. package/dist/graph/message.cjs +59 -104
  109. package/dist/graph/message.cjs.map +1 -0
  110. package/dist/graph/message.d.cts +19 -0
  111. package/dist/graph/message.d.cts.map +1 -0
  112. package/dist/graph/message.d.ts +11 -10
  113. package/dist/graph/message.d.ts.map +1 -0
  114. package/dist/graph/message.js +56 -98
  115. package/dist/graph/message.js.map +1 -1
  116. package/dist/graph/messages_annotation.cjs +106 -106
  117. package/dist/graph/messages_annotation.cjs.map +1 -0
  118. package/dist/graph/messages_annotation.d.cts +111 -0
  119. package/dist/graph/messages_annotation.d.cts.map +1 -0
  120. package/dist/graph/messages_annotation.d.ts +18 -9
  121. package/dist/graph/messages_annotation.d.ts.map +1 -0
  122. package/dist/graph/messages_annotation.js +100 -100
  123. package/dist/graph/messages_annotation.js.map +1 -1
  124. package/dist/graph/state.cjs +476 -777
  125. package/dist/graph/state.cjs.map +1 -0
  126. package/dist/graph/state.d.cts +216 -0
  127. package/dist/graph/state.d.cts.map +1 -0
  128. package/dist/graph/state.d.ts +129 -134
  129. package/dist/graph/state.d.ts.map +1 -0
  130. package/dist/graph/state.js +470 -768
  131. package/dist/graph/state.js.map +1 -1
  132. package/dist/graph/zod/index.cjs +10 -21
  133. package/dist/graph/zod/index.d.cts +3 -0
  134. package/dist/graph/zod/index.d.ts +3 -3
  135. package/dist/graph/zod/index.js +4 -4
  136. package/dist/graph/zod/meta.cjs +142 -177
  137. package/dist/graph/zod/meta.cjs.map +1 -0
  138. package/dist/graph/zod/meta.d.cts +116 -0
  139. package/dist/graph/zod/meta.d.cts.map +1 -0
  140. package/dist/graph/zod/meta.d.ts +99 -97
  141. package/dist/graph/zod/meta.d.ts.map +1 -0
  142. package/dist/graph/zod/meta.js +136 -170
  143. package/dist/graph/zod/meta.js.map +1 -1
  144. package/dist/graph/zod/plugin.cjs +36 -39
  145. package/dist/graph/zod/plugin.cjs.map +1 -0
  146. package/dist/graph/zod/plugin.js +34 -35
  147. package/dist/graph/zod/plugin.js.map +1 -1
  148. package/dist/graph/zod/schema.cjs +82 -110
  149. package/dist/graph/zod/schema.cjs.map +1 -0
  150. package/dist/graph/zod/schema.d.cts +38 -0
  151. package/dist/graph/zod/schema.d.cts.map +1 -0
  152. package/dist/graph/zod/schema.d.ts +12 -6
  153. package/dist/graph/zod/schema.d.ts.map +1 -0
  154. package/dist/graph/zod/schema.js +77 -103
  155. package/dist/graph/zod/schema.js.map +1 -1
  156. package/dist/graph/zod/zod-registry.cjs +41 -47
  157. package/dist/graph/zod/zod-registry.cjs.map +1 -0
  158. package/dist/graph/zod/zod-registry.d.cts +51 -0
  159. package/dist/graph/zod/zod-registry.d.cts.map +1 -0
  160. package/dist/graph/zod/zod-registry.d.ts +34 -26
  161. package/dist/graph/zod/zod-registry.d.ts.map +1 -0
  162. package/dist/graph/zod/zod-registry.js +37 -41
  163. package/dist/graph/zod/zod-registry.js.map +1 -1
  164. package/dist/hash.cjs +205 -267
  165. package/dist/hash.cjs.map +1 -0
  166. package/dist/hash.js +205 -265
  167. package/dist/hash.js.map +1 -1
  168. package/dist/index.cjs +110 -33
  169. package/dist/index.cjs.map +1 -0
  170. package/dist/index.d.cts +25 -0
  171. package/dist/index.d.ts +25 -5
  172. package/dist/index.js +18 -7
  173. package/dist/index.js.map +1 -1
  174. package/dist/interrupt.cjs +79 -85
  175. package/dist/interrupt.cjs.map +1 -0
  176. package/dist/interrupt.d.cts +49 -0
  177. package/dist/interrupt.d.cts.map +1 -0
  178. package/dist/interrupt.d.ts +6 -1
  179. package/dist/interrupt.d.ts.map +1 -0
  180. package/dist/interrupt.js +76 -80
  181. package/dist/interrupt.js.map +1 -1
  182. package/dist/prebuilt/agentName.cjs +139 -172
  183. package/dist/prebuilt/agentName.cjs.map +1 -0
  184. package/dist/prebuilt/agentName.d.cts +42 -0
  185. package/dist/prebuilt/agentName.d.cts.map +1 -0
  186. package/dist/prebuilt/agentName.d.ts +13 -21
  187. package/dist/prebuilt/agentName.d.ts.map +1 -0
  188. package/dist/prebuilt/agentName.js +139 -168
  189. package/dist/prebuilt/agentName.js.map +1 -1
  190. package/dist/prebuilt/agent_executor.cjs +42 -80
  191. package/dist/prebuilt/agent_executor.cjs.map +1 -0
  192. package/dist/prebuilt/agent_executor.d.cts +57 -0
  193. package/dist/prebuilt/agent_executor.d.cts.map +1 -0
  194. package/dist/prebuilt/agent_executor.d.ts +46 -37
  195. package/dist/prebuilt/agent_executor.d.ts.map +1 -0
  196. package/dist/prebuilt/agent_executor.js +40 -75
  197. package/dist/prebuilt/agent_executor.js.map +1 -1
  198. package/dist/prebuilt/chat_agent_executor.cjs +66 -128
  199. package/dist/prebuilt/chat_agent_executor.cjs.map +1 -0
  200. package/dist/prebuilt/chat_agent_executor.d.cts +23 -0
  201. package/dist/prebuilt/chat_agent_executor.d.cts.map +1 -0
  202. package/dist/prebuilt/chat_agent_executor.d.ts +18 -10
  203. package/dist/prebuilt/chat_agent_executor.d.ts.map +1 -0
  204. package/dist/prebuilt/chat_agent_executor.js +63 -123
  205. package/dist/prebuilt/chat_agent_executor.js.map +1 -1
  206. package/dist/prebuilt/index.cjs +15 -18
  207. package/dist/prebuilt/index.d.cts +8 -0
  208. package/dist/prebuilt/index.d.ts +8 -8
  209. package/dist/prebuilt/index.js +8 -7
  210. package/dist/prebuilt/interrupt.d.cts +73 -0
  211. package/dist/prebuilt/interrupt.d.cts.map +1 -0
  212. package/dist/prebuilt/interrupt.d.ts +32 -15
  213. package/dist/prebuilt/interrupt.d.ts.map +1 -0
  214. package/dist/prebuilt/react_agent_executor.cjs +317 -473
  215. package/dist/prebuilt/react_agent_executor.cjs.map +1 -0
  216. package/dist/prebuilt/react_agent_executor.d.cts +229 -0
  217. package/dist/prebuilt/react_agent_executor.d.cts.map +1 -0
  218. package/dist/prebuilt/react_agent_executor.d.ts +171 -143
  219. package/dist/prebuilt/react_agent_executor.d.ts.map +1 -0
  220. package/dist/prebuilt/react_agent_executor.js +315 -465
  221. package/dist/prebuilt/react_agent_executor.js.map +1 -1
  222. package/dist/prebuilt/tool_executor.cjs +45 -67
  223. package/dist/prebuilt/tool_executor.cjs.map +1 -0
  224. package/dist/prebuilt/tool_executor.d.cts +42 -0
  225. package/dist/prebuilt/tool_executor.d.cts.map +1 -0
  226. package/dist/prebuilt/tool_executor.d.ts +30 -24
  227. package/dist/prebuilt/tool_executor.d.ts.map +1 -0
  228. package/dist/prebuilt/tool_executor.js +44 -63
  229. package/dist/prebuilt/tool_executor.js.map +1 -1
  230. package/dist/prebuilt/tool_node.cjs +213 -275
  231. package/dist/prebuilt/tool_node.cjs.map +1 -0
  232. package/dist/prebuilt/tool_node.d.cts +151 -0
  233. package/dist/prebuilt/tool_node.d.cts.map +1 -0
  234. package/dist/prebuilt/tool_node.d.ts +30 -17
  235. package/dist/prebuilt/tool_node.d.ts.map +1 -0
  236. package/dist/prebuilt/tool_node.js +209 -268
  237. package/dist/prebuilt/tool_node.js.map +1 -1
  238. package/dist/pregel/algo.cjs +521 -692
  239. package/dist/pregel/algo.cjs.map +1 -0
  240. package/dist/pregel/algo.d.cts +13 -0
  241. package/dist/pregel/algo.d.cts.map +1 -0
  242. package/dist/pregel/algo.d.ts +8 -38
  243. package/dist/pregel/algo.d.ts.map +1 -0
  244. package/dist/pregel/algo.js +516 -683
  245. package/dist/pregel/algo.js.map +1 -1
  246. package/dist/pregel/call.cjs +46 -42
  247. package/dist/pregel/call.cjs.map +1 -0
  248. package/dist/pregel/call.js +43 -37
  249. package/dist/pregel/call.js.map +1 -1
  250. package/dist/pregel/debug.cjs +153 -223
  251. package/dist/pregel/debug.cjs.map +1 -0
  252. package/dist/pregel/debug.js +152 -215
  253. package/dist/pregel/debug.js.map +1 -1
  254. package/dist/pregel/index.cjs +1134 -1604
  255. package/dist/pregel/index.cjs.map +1 -0
  256. package/dist/pregel/index.d.cts +534 -0
  257. package/dist/pregel/index.d.cts.map +1 -0
  258. package/dist/pregel/index.d.ts +458 -422
  259. package/dist/pregel/index.d.ts.map +1 -0
  260. package/dist/pregel/index.js +1125 -1592
  261. package/dist/pregel/index.js.map +1 -1
  262. package/dist/pregel/io.cjs +127 -234
  263. package/dist/pregel/io.cjs.map +1 -0
  264. package/dist/pregel/io.js +122 -225
  265. package/dist/pregel/io.js.map +1 -1
  266. package/dist/pregel/loop.cjs +539 -954
  267. package/dist/pregel/loop.cjs.map +1 -0
  268. package/dist/pregel/loop.js +536 -948
  269. package/dist/pregel/loop.js.map +1 -1
  270. package/dist/pregel/messages.cjs +104 -196
  271. package/dist/pregel/messages.cjs.map +1 -0
  272. package/dist/pregel/messages.js +102 -191
  273. package/dist/pregel/messages.js.map +1 -1
  274. package/dist/pregel/read.cjs +150 -280
  275. package/dist/pregel/read.cjs.map +1 -0
  276. package/dist/pregel/read.d.cts +51 -0
  277. package/dist/pregel/read.d.cts.map +1 -0
  278. package/dist/pregel/read.d.ts +48 -46
  279. package/dist/pregel/read.d.ts.map +1 -0
  280. package/dist/pregel/read.js +147 -274
  281. package/dist/pregel/read.js.map +1 -1
  282. package/dist/pregel/remote.cjs +339 -458
  283. package/dist/pregel/remote.cjs.map +1 -0
  284. package/dist/pregel/remote.d.cts +121 -0
  285. package/dist/pregel/remote.d.cts.map +1 -0
  286. package/dist/pregel/remote.d.ts +79 -69
  287. package/dist/pregel/remote.d.ts.map +1 -0
  288. package/dist/pregel/remote.js +337 -453
  289. package/dist/pregel/remote.js.map +1 -1
  290. package/dist/pregel/retry.cjs +87 -138
  291. package/dist/pregel/retry.cjs.map +1 -0
  292. package/dist/pregel/retry.js +83 -130
  293. package/dist/pregel/retry.js.map +1 -1
  294. package/dist/pregel/runnable_types.d.cts +25 -0
  295. package/dist/pregel/runnable_types.d.cts.map +1 -0
  296. package/dist/pregel/runnable_types.d.ts +22 -16
  297. package/dist/pregel/runnable_types.d.ts.map +1 -0
  298. package/dist/pregel/runner.cjs +222 -315
  299. package/dist/pregel/runner.cjs.map +1 -0
  300. package/dist/pregel/runner.js +219 -308
  301. package/dist/pregel/runner.js.map +1 -1
  302. package/dist/pregel/stream.cjs +89 -130
  303. package/dist/pregel/stream.cjs.map +1 -0
  304. package/dist/pregel/stream.js +87 -125
  305. package/dist/pregel/stream.js.map +1 -1
  306. package/dist/pregel/types.cjs +25 -62
  307. package/dist/pregel/types.cjs.map +1 -0
  308. package/dist/pregel/types.d.cts +437 -0
  309. package/dist/pregel/types.d.cts.map +1 -0
  310. package/dist/pregel/types.d.ts +377 -431
  311. package/dist/pregel/types.d.ts.map +1 -0
  312. package/dist/pregel/types.js +23 -57
  313. package/dist/pregel/types.js.map +1 -1
  314. package/dist/pregel/utils/config.cjs +100 -147
  315. package/dist/pregel/utils/config.cjs.map +1 -0
  316. package/dist/pregel/utils/config.d.cts +36 -0
  317. package/dist/pregel/utils/config.d.cts.map +1 -0
  318. package/dist/pregel/utils/config.d.ts +12 -9
  319. package/dist/pregel/utils/config.d.ts.map +1 -0
  320. package/dist/pregel/utils/config.js +98 -143
  321. package/dist/pregel/utils/config.js.map +1 -1
  322. package/dist/pregel/utils/index.cjs +87 -125
  323. package/dist/pregel/utils/index.cjs.map +1 -0
  324. package/dist/pregel/utils/index.d.cts +51 -0
  325. package/dist/pregel/utils/index.d.cts.map +1 -0
  326. package/dist/pregel/utils/index.d.ts +45 -61
  327. package/dist/pregel/utils/index.d.ts.map +1 -0
  328. package/dist/pregel/utils/index.js +86 -120
  329. package/dist/pregel/utils/index.js.map +1 -1
  330. package/dist/pregel/utils/subgraph.cjs +15 -26
  331. package/dist/pregel/utils/subgraph.cjs.map +1 -0
  332. package/dist/pregel/utils/subgraph.js +12 -21
  333. package/dist/pregel/utils/subgraph.js.map +1 -1
  334. package/dist/pregel/validate.cjs +42 -92
  335. package/dist/pregel/validate.cjs.map +1 -0
  336. package/dist/pregel/validate.js +39 -84
  337. package/dist/pregel/validate.js.map +1 -1
  338. package/dist/pregel/write.cjs +87 -137
  339. package/dist/pregel/write.cjs.map +1 -0
  340. package/dist/pregel/write.d.cts +35 -0
  341. package/dist/pregel/write.d.cts.map +1 -0
  342. package/dist/pregel/write.d.ts +27 -23
  343. package/dist/pregel/write.d.ts.map +1 -0
  344. package/dist/pregel/write.js +83 -131
  345. package/dist/pregel/write.js.map +1 -1
  346. package/dist/remote.cjs +3 -6
  347. package/dist/remote.d.cts +2 -0
  348. package/dist/remote.d.ts +2 -1
  349. package/dist/remote.js +3 -2
  350. package/dist/setup/async_local_storage.cjs +10 -7
  351. package/dist/setup/async_local_storage.cjs.map +1 -0
  352. package/dist/setup/async_local_storage.js +7 -2
  353. package/dist/setup/async_local_storage.js.map +1 -1
  354. package/dist/ui/index.cjs +4 -0
  355. package/dist/ui/index.d.cts +5 -0
  356. package/dist/ui/index.d.ts +5 -0
  357. package/dist/ui/index.js +3 -0
  358. package/dist/ui/stream.cjs +145 -0
  359. package/dist/ui/stream.cjs.map +1 -0
  360. package/dist/ui/stream.d.cts +25 -0
  361. package/dist/ui/stream.d.cts.map +1 -0
  362. package/dist/ui/stream.d.ts +25 -0
  363. package/dist/ui/stream.d.ts.map +1 -0
  364. package/dist/ui/stream.js +143 -0
  365. package/dist/ui/stream.js.map +1 -0
  366. package/dist/ui/types.infer.d.cts +53 -0
  367. package/dist/ui/types.infer.d.cts.map +1 -0
  368. package/dist/ui/types.infer.d.ts +53 -0
  369. package/dist/ui/types.infer.d.ts.map +1 -0
  370. package/dist/ui/types.message.d.cts +95 -0
  371. package/dist/ui/types.message.d.cts.map +1 -0
  372. package/dist/ui/types.message.d.ts +95 -0
  373. package/dist/ui/types.message.d.ts.map +1 -0
  374. package/dist/ui/types.schema.d.cts +228 -0
  375. package/dist/ui/types.schema.d.cts.map +1 -0
  376. package/dist/ui/types.schema.d.ts +228 -0
  377. package/dist/ui/types.schema.d.ts.map +1 -0
  378. package/dist/utils.cjs +77 -147
  379. package/dist/utils.cjs.map +1 -0
  380. package/dist/utils.d.cts +32 -0
  381. package/dist/utils.d.cts.map +1 -0
  382. package/dist/utils.d.ts +29 -25
  383. package/dist/utils.d.ts.map +1 -0
  384. package/dist/utils.js +73 -140
  385. package/dist/utils.js.map +1 -1
  386. package/dist/web.cjs +97 -55
  387. package/dist/web.d.cts +23 -0
  388. package/dist/web.d.ts +23 -14
  389. package/dist/web.js +15 -8
  390. package/package.json +77 -80
  391. package/dist/channels/any_value.cjs +0 -65
  392. package/dist/channels/any_value.js +0 -61
  393. package/dist/channels/any_value.js.map +0 -1
  394. package/dist/channels/dynamic_barrier_value.cjs +0 -212
  395. package/dist/channels/dynamic_barrier_value.js +0 -207
  396. package/dist/channels/dynamic_barrier_value.js.map +0 -1
  397. package/dist/channels/index.d.ts +0 -7
  398. package/dist/channels/index.js.map +0 -1
  399. package/dist/func/types.cjs +0 -15
  400. package/dist/func/types.js +0 -12
  401. package/dist/func/types.js.map +0 -1
  402. package/dist/graph/index.d.ts +0 -4
  403. package/dist/graph/index.js.map +0 -1
  404. package/dist/graph/message.test.cjs +0 -196
  405. package/dist/graph/message.test.d.ts +0 -1
  406. package/dist/graph/message.test.js +0 -194
  407. package/dist/graph/message.test.js.map +0 -1
  408. package/dist/graph/zod/index.js.map +0 -1
  409. package/dist/graph/zod/plugin.d.ts +0 -28
  410. package/dist/hash.d.ts +0 -2
  411. package/dist/prebuilt/index.js.map +0 -1
  412. package/dist/prebuilt/interrupt.cjs +0 -3
  413. package/dist/prebuilt/interrupt.js +0 -2
  414. package/dist/prebuilt/interrupt.js.map +0 -1
  415. package/dist/pregel/call.d.ts +0 -16
  416. package/dist/pregel/debug.d.ts +0 -41
  417. package/dist/pregel/debug.test.cjs +0 -258
  418. package/dist/pregel/debug.test.d.ts +0 -1
  419. package/dist/pregel/debug.test.js +0 -256
  420. package/dist/pregel/debug.test.js.map +0 -1
  421. package/dist/pregel/io.d.ts +0 -30
  422. package/dist/pregel/io.mapCommand.test.cjs +0 -150
  423. package/dist/pregel/io.mapCommand.test.d.ts +0 -1
  424. package/dist/pregel/io.mapCommand.test.js +0 -148
  425. package/dist/pregel/io.mapCommand.test.js.map +0 -1
  426. package/dist/pregel/loop.d.ts +0 -147
  427. package/dist/pregel/messages.d.ts +0 -30
  428. package/dist/pregel/messages.test.cjs +0 -369
  429. package/dist/pregel/messages.test.d.ts +0 -1
  430. package/dist/pregel/messages.test.js +0 -367
  431. package/dist/pregel/messages.test.js.map +0 -1
  432. package/dist/pregel/read.test.cjs +0 -194
  433. package/dist/pregel/read.test.d.ts +0 -1
  434. package/dist/pregel/read.test.js +0 -192
  435. package/dist/pregel/read.test.js.map +0 -1
  436. package/dist/pregel/retry.d.ts +0 -17
  437. package/dist/pregel/runnable_types.cjs +0 -3
  438. package/dist/pregel/runnable_types.js +0 -2
  439. package/dist/pregel/runnable_types.js.map +0 -1
  440. package/dist/pregel/runner.d.ts +0 -79
  441. package/dist/pregel/runner.test.cjs +0 -66
  442. package/dist/pregel/runner.test.d.ts +0 -1
  443. package/dist/pregel/runner.test.js +0 -64
  444. package/dist/pregel/runner.test.js.map +0 -1
  445. package/dist/pregel/stream.d.ts +0 -40
  446. package/dist/pregel/utils/config.test.cjs +0 -214
  447. package/dist/pregel/utils/config.test.d.ts +0 -1
  448. package/dist/pregel/utils/config.test.js +0 -212
  449. package/dist/pregel/utils/config.test.js.map +0 -1
  450. package/dist/pregel/utils/subgraph.d.ts +0 -4
  451. package/dist/pregel/utils/subgraph.test.cjs +0 -83
  452. package/dist/pregel/utils/subgraph.test.d.ts +0 -1
  453. package/dist/pregel/utils/subgraph.test.js +0 -81
  454. package/dist/pregel/utils/subgraph.test.js.map +0 -1
  455. package/dist/pregel/validate.d.ts +0 -16
  456. package/dist/pregel/validate.test.cjs +0 -220
  457. package/dist/pregel/validate.test.d.ts +0 -1
  458. package/dist/pregel/validate.test.js +0 -218
  459. package/dist/pregel/validate.test.js.map +0 -1
  460. package/dist/pregel/write.test.cjs +0 -181
  461. package/dist/pregel/write.test.d.ts +0 -1
  462. package/dist/pregel/write.test.js +0 -179
  463. package/dist/pregel/write.test.js.map +0 -1
  464. package/dist/remote.js.map +0 -1
  465. package/dist/setup/async_local_storage.d.ts +0 -1
  466. package/dist/web.js.map +0 -1
  467. package/index.cjs +0 -1
  468. package/index.d.cts +0 -1
  469. package/index.d.ts +0 -1
  470. package/index.js +0 -1
  471. package/prebuilt.cjs +0 -1
  472. package/prebuilt.d.cts +0 -1
  473. package/prebuilt.d.ts +0 -1
  474. package/prebuilt.js +0 -1
  475. package/pregel.cjs +0 -1
  476. package/pregel.d.cts +0 -1
  477. package/pregel.d.ts +0 -1
  478. package/pregel.js +0 -1
  479. package/remote.cjs +0 -1
  480. package/remote.d.cts +0 -1
  481. package/remote.d.ts +0 -1
  482. package/remote.js +0 -1
  483. package/web.cjs +0 -1
  484. package/web.d.cts +0 -1
  485. package/web.d.ts +0 -1
  486. package/web.js +0 -1
  487. package/zod/schema.cjs +0 -1
  488. package/zod/schema.d.cts +0 -1
  489. package/zod/schema.d.ts +0 -1
  490. package/zod/schema.js +0 -1
  491. package/zod.cjs +0 -1
  492. package/zod.d.cts +0 -1
  493. package/zod.d.ts +0 -1
  494. package/zod.js +0 -1
@@ -1,1607 +1,1137 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Pregel = exports.Channel = void 0;
4
- /* eslint-disable no-param-reassign */
5
- const runnables_1 = require("@langchain/core/runnables");
6
- const langgraph_checkpoint_1 = require("@langchain/langgraph-checkpoint");
7
- const base_js_1 = require("../channels/base.cjs");
8
- const constants_js_1 = require("../constants.cjs");
9
- const errors_js_1 = require("../errors.cjs");
10
- const utils_js_1 = require("../utils.cjs");
11
- const algo_js_1 = require("./algo.cjs");
12
- const debug_js_1 = require("./debug.cjs");
13
- const io_js_1 = require("./io.cjs");
14
- const loop_js_1 = require("./loop.cjs");
15
- const messages_js_1 = require("./messages.cjs");
16
- const read_js_1 = require("./read.cjs");
17
- const runner_js_1 = require("./runner.cjs");
18
- const stream_js_1 = require("./stream.cjs");
19
- const config_js_1 = require("./utils/config.cjs");
20
- const index_js_1 = require("./utils/index.cjs");
21
- const subgraph_js_1 = require("./utils/subgraph.cjs");
22
- const validate_js_1 = require("./validate.cjs");
23
- const write_js_1 = require("./write.cjs");
24
- const topic_js_1 = require("../channels/topic.cjs");
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_errors = require('../errors.cjs');
3
+ const require_base = require('../channels/base.cjs');
4
+ const require_constants = require('../constants.cjs');
5
+ const require_config = require('./utils/config.cjs');
6
+ const require_utils = require('../utils.cjs');
7
+ const require_write = require('./write.cjs');
8
+ const require_read = require('./read.cjs');
9
+ const require_io = require('./io.cjs');
10
+ const require_index = require('./utils/index.cjs');
11
+ const require_algo = require('./algo.cjs');
12
+ const require_subgraph = require('./utils/subgraph.cjs');
13
+ const require_debug = require('./debug.cjs');
14
+ const require_stream = require('./stream.cjs');
15
+ const require_loop = require('./loop.cjs');
16
+ const require_messages = require('./messages.cjs');
17
+ const require_runner = require('./runner.cjs');
18
+ const require_validate = require('./validate.cjs');
19
+ const require_topic = require('../channels/topic.cjs');
20
+ const __langchain_langgraph_checkpoint = require_rolldown_runtime.__toESM(require("@langchain/langgraph-checkpoint"));
21
+ const __langchain_core_runnables = require_rolldown_runtime.__toESM(require("@langchain/core/runnables"));
22
+
23
+ //#region src/pregel/index.ts
25
24
  /**
26
- * Utility class for working with channels in the Pregel system.
27
- * Provides static methods for subscribing to channels and writing to them.
28
- *
29
- * Channels are the communication pathways between nodes in a Pregel graph.
30
- * They enable message passing and state updates between different parts of the graph.
31
- */
32
- class Channel {
33
- static subscribeTo(channels, options) {
34
- const { key, tags } = {
35
- key: undefined,
36
- tags: undefined,
37
- ...(options ?? {}),
38
- };
39
- if (Array.isArray(channels) && key !== undefined) {
40
- throw new Error("Can't specify a key when subscribing to multiple channels");
41
- }
42
- let channelMappingOrArray;
43
- if (typeof channels === "string") {
44
- if (key) {
45
- channelMappingOrArray = { [key]: channels };
46
- }
47
- else {
48
- channelMappingOrArray = [channels];
49
- }
50
- }
51
- else {
52
- channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan]));
53
- }
54
- const triggers = Array.isArray(channels) ? channels : [channels];
55
- return new read_js_1.PregelNode({
56
- channels: channelMappingOrArray,
57
- triggers,
58
- tags,
59
- });
60
- }
61
- /**
62
- * Creates a ChannelWrite that specifies how to write values to channels.
63
- * This is used to define how nodes send output to channels.
64
- *
65
- * @example
66
- * ```typescript
67
- * // Write to multiple channels
68
- * const write = Channel.writeTo(["output", "state"]);
69
- *
70
- * // Write with specific values
71
- * const write = Channel.writeTo(["output"], {
72
- * state: "completed",
73
- * result: calculateResult()
74
- * });
75
- *
76
- * // Write with a transformation function
77
- * const write = Channel.writeTo(["output"], {
78
- * result: (x) => processResult(x)
79
- * });
80
- * ```
81
- *
82
- * @param channels - Array of channel names to write to
83
- * @param writes - Optional map of channel names to values or transformations
84
- * @returns A ChannelWrite object that can be used to write to the specified channels
85
- */
86
- static writeTo(channels, writes) {
87
- const channelWriteEntries = [];
88
- for (const channel of channels) {
89
- channelWriteEntries.push({
90
- channel,
91
- value: write_js_1.PASSTHROUGH,
92
- skipNone: false,
93
- });
94
- }
95
- for (const [key, value] of Object.entries(writes ?? {})) {
96
- if (runnables_1.Runnable.isRunnable(value) || typeof value === "function") {
97
- channelWriteEntries.push({
98
- channel: key,
99
- value: write_js_1.PASSTHROUGH,
100
- skipNone: true,
101
- mapper: (0, runnables_1._coerceToRunnable)(value),
102
- });
103
- }
104
- else {
105
- channelWriteEntries.push({
106
- channel: key,
107
- value,
108
- skipNone: false,
109
- });
110
- }
111
- }
112
- return new write_js_1.ChannelWrite(channelWriteEntries);
113
- }
114
- }
115
- exports.Channel = Channel;
116
- // This is a workaround to allow Pregel to override `invoke` / `stream` and `withConfig`
117
- // without having to adhere to the types in the `Runnable` class (thanks to `any`).
118
- // Alternatively we could mark those methods with @ts-ignore / @ts-expect-error,
119
- // but these do not get carried over when building via `tsc`.
120
- class PartialRunnable extends runnables_1.Runnable {
121
- constructor() {
122
- super(...arguments);
123
- Object.defineProperty(this, "lc_namespace", {
124
- enumerable: true,
125
- configurable: true,
126
- writable: true,
127
- value: ["langgraph", "pregel"]
128
- });
129
- }
130
- invoke(_input, _options
131
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
132
- ) {
133
- throw new Error("Not implemented");
134
- }
135
- // Overriden by `Pregel`
136
- withConfig(_config) {
137
- return super.withConfig(_config);
138
- }
139
- // Overriden by `Pregel`
140
- stream(input, options
141
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
142
- ) {
143
- return super.stream(input, options);
144
- }
145
- }
25
+ * Utility class for working with channels in the Pregel system.
26
+ * Provides static methods for subscribing to channels and writing to them.
27
+ *
28
+ * Channels are the communication pathways between nodes in a Pregel graph.
29
+ * They enable message passing and state updates between different parts of the graph.
30
+ */
31
+ var Channel = class {
32
+ static subscribeTo(channels, options) {
33
+ const { key, tags } = {
34
+ key: void 0,
35
+ tags: void 0,
36
+ ...options ?? {}
37
+ };
38
+ if (Array.isArray(channels) && key !== void 0) throw new Error("Can't specify a key when subscribing to multiple channels");
39
+ let channelMappingOrArray;
40
+ if (typeof channels === "string") if (key) channelMappingOrArray = { [key]: channels };
41
+ else channelMappingOrArray = [channels];
42
+ else channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan]));
43
+ const triggers = Array.isArray(channels) ? channels : [channels];
44
+ return new require_read.PregelNode({
45
+ channels: channelMappingOrArray,
46
+ triggers,
47
+ tags
48
+ });
49
+ }
50
+ /**
51
+ * Creates a ChannelWrite that specifies how to write values to channels.
52
+ * This is used to define how nodes send output to channels.
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * // Write to multiple channels
57
+ * const write = Channel.writeTo(["output", "state"]);
58
+ *
59
+ * // Write with specific values
60
+ * const write = Channel.writeTo(["output"], {
61
+ * state: "completed",
62
+ * result: calculateResult()
63
+ * });
64
+ *
65
+ * // Write with a transformation function
66
+ * const write = Channel.writeTo(["output"], {
67
+ * result: (x) => processResult(x)
68
+ * });
69
+ * ```
70
+ *
71
+ * @param channels - Array of channel names to write to
72
+ * @param writes - Optional map of channel names to values or transformations
73
+ * @returns A ChannelWrite object that can be used to write to the specified channels
74
+ */
75
+ static writeTo(channels, writes) {
76
+ const channelWriteEntries = [];
77
+ for (const channel of channels) channelWriteEntries.push({
78
+ channel,
79
+ value: require_write.PASSTHROUGH,
80
+ skipNone: false
81
+ });
82
+ for (const [key, value] of Object.entries(writes ?? {})) if (__langchain_core_runnables.Runnable.isRunnable(value) || typeof value === "function") channelWriteEntries.push({
83
+ channel: key,
84
+ value: require_write.PASSTHROUGH,
85
+ skipNone: true,
86
+ mapper: (0, __langchain_core_runnables._coerceToRunnable)(value)
87
+ });
88
+ else channelWriteEntries.push({
89
+ channel: key,
90
+ value,
91
+ skipNone: false
92
+ });
93
+ return new require_write.ChannelWrite(channelWriteEntries);
94
+ }
95
+ };
96
+ var PartialRunnable = class extends __langchain_core_runnables.Runnable {
97
+ lc_namespace = ["langgraph", "pregel"];
98
+ invoke(_input, _options) {
99
+ throw new Error("Not implemented");
100
+ }
101
+ withConfig(_config) {
102
+ return super.withConfig(_config);
103
+ }
104
+ stream(input, options) {
105
+ return super.stream(input, options);
106
+ }
107
+ };
146
108
  /**
147
- * The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model
148
- * inspired by [Google's Pregel system](https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/).
149
- * It provides the foundation for building reliable, controllable agent workflows that can evolve state over time.
150
- *
151
- * Key features:
152
- * - Message passing between nodes in discrete "supersteps"
153
- * - Built-in persistence layer through checkpointers
154
- * - First-class streaming support for values, updates, and events
155
- * - Human-in-the-loop capabilities via interrupts
156
- * - Support for parallel node execution within supersteps
157
- *
158
- * The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs:
159
- * - {@link StateGraph}: The main graph class for building agent workflows
160
- * - Compiling a {@link StateGraph} will return a {@link CompiledGraph} instance, which extends `Pregel`
161
- * - Functional API: A declarative approach using tasks and entrypoints
162
- * - A `Pregel` instance is returned by the {@link entrypoint} function
163
- *
164
- * @example
165
- * ```typescript
166
- * // Using StateGraph API
167
- * const graph = new StateGraph(annotation)
168
- * .addNode("nodeA", myNodeFunction)
169
- * .addEdge("nodeA", "nodeB")
170
- * .compile();
171
- *
172
- * // The compiled graph is a Pregel instance
173
- * const result = await graph.invoke(input);
174
- * ```
175
- *
176
- * @example
177
- * ```typescript
178
- * // Using Functional API
179
- * import { task, entrypoint } from "@langchain/langgraph";
180
- * import { MemorySaver } from "@langchain/langgraph-checkpoint";
181
- *
182
- * // Define tasks that can be composed
183
- * const addOne = task("add", async (x: number) => x + 1);
184
- *
185
- * // Create a workflow using the entrypoint function
186
- * const workflow = entrypoint({
187
- * name: "workflow",
188
- * checkpointer: new MemorySaver()
189
- * }, async (numbers: number[]) => {
190
- * // Tasks can be run in parallel
191
- * const results = await Promise.all(numbers.map(n => addOne(n)));
192
- * return results;
193
- * });
194
- *
195
- * // The workflow is a Pregel instance
196
- * const result = await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]
197
- * ```
198
- *
199
- * @typeParam Nodes - Mapping of node names to their {@link PregelNode} implementations
200
- * @typeParam Channels - Mapping of channel names to their {@link BaseChannel} or {@link ManagedValueSpec} implementations
201
- * @typeParam ContextType - Type of context that can be passed to the graph
202
- * @typeParam InputType - Type of input values accepted by the graph
203
- * @typeParam OutputType - Type of output values produced by the graph
204
- */
205
- class Pregel extends PartialRunnable {
206
- /**
207
- * Name of the class when serialized
208
- * @internal
209
- */
210
- static lc_name() {
211
- return "LangGraph";
212
- }
213
- /**
214
- * Constructor for Pregel - meant for internal use only.
215
- *
216
- * @internal
217
- */
218
- constructor(fields) {
219
- super(fields);
220
- /** @internal LangChain namespace for serialization necessary because Pregel extends Runnable */
221
- Object.defineProperty(this, "lc_namespace", {
222
- enumerable: true,
223
- configurable: true,
224
- writable: true,
225
- value: ["langgraph", "pregel"]
226
- });
227
- /** @internal Flag indicating this is a Pregel instance - necessary for serialization */
228
- Object.defineProperty(this, "lg_is_pregel", {
229
- enumerable: true,
230
- configurable: true,
231
- writable: true,
232
- value: true
233
- });
234
- /** The nodes in the graph, mapping node names to their PregelNode instances */
235
- Object.defineProperty(this, "nodes", {
236
- enumerable: true,
237
- configurable: true,
238
- writable: true,
239
- value: void 0
240
- });
241
- /** The channels in the graph, mapping channel names to their BaseChannel or ManagedValueSpec instances */
242
- Object.defineProperty(this, "channels", {
243
- enumerable: true,
244
- configurable: true,
245
- writable: true,
246
- value: void 0
247
- });
248
- /**
249
- * The input channels for the graph. These channels receive the initial input when the graph is invoked.
250
- * Can be a single channel key or an array of channel keys.
251
- */
252
- Object.defineProperty(this, "inputChannels", {
253
- enumerable: true,
254
- configurable: true,
255
- writable: true,
256
- value: void 0
257
- });
258
- /**
259
- * The output channels for the graph. These channels contain the final output when the graph completes.
260
- * Can be a single channel key or an array of channel keys.
261
- */
262
- Object.defineProperty(this, "outputChannels", {
263
- enumerable: true,
264
- configurable: true,
265
- writable: true,
266
- value: void 0
267
- });
268
- /** Whether to automatically validate the graph structure when it is compiled. Defaults to true. */
269
- Object.defineProperty(this, "autoValidate", {
270
- enumerable: true,
271
- configurable: true,
272
- writable: true,
273
- value: true
274
- });
275
- /**
276
- * The streaming modes enabled for this graph. Defaults to ["values"].
277
- * Supported modes:
278
- * - "values": Streams the full state after each step
279
- * - "updates": Streams state updates after each step
280
- * - "messages": Streams messages from within nodes
281
- * - "custom": Streams custom events from within nodes
282
- * - "debug": Streams events related to the execution of the graph - useful for tracing & debugging graph execution
283
- */
284
- Object.defineProperty(this, "streamMode", {
285
- enumerable: true,
286
- configurable: true,
287
- writable: true,
288
- value: ["values"]
289
- });
290
- /**
291
- * Optional channels to stream. If not specified, all channels will be streamed.
292
- * Can be a single channel key or an array of channel keys.
293
- */
294
- Object.defineProperty(this, "streamChannels", {
295
- enumerable: true,
296
- configurable: true,
297
- writable: true,
298
- value: void 0
299
- });
300
- /**
301
- * Optional array of node names or "all" to interrupt after executing these nodes.
302
- * Used for implementing human-in-the-loop workflows.
303
- */
304
- Object.defineProperty(this, "interruptAfter", {
305
- enumerable: true,
306
- configurable: true,
307
- writable: true,
308
- value: void 0
309
- });
310
- /**
311
- * Optional array of node names or "all" to interrupt before executing these nodes.
312
- * Used for implementing human-in-the-loop workflows.
313
- */
314
- Object.defineProperty(this, "interruptBefore", {
315
- enumerable: true,
316
- configurable: true,
317
- writable: true,
318
- value: void 0
319
- });
320
- /** Optional timeout in milliseconds for the execution of each superstep */
321
- Object.defineProperty(this, "stepTimeout", {
322
- enumerable: true,
323
- configurable: true,
324
- writable: true,
325
- value: void 0
326
- });
327
- /** Whether to enable debug logging. Defaults to false. */
328
- Object.defineProperty(this, "debug", {
329
- enumerable: true,
330
- configurable: true,
331
- writable: true,
332
- value: false
333
- });
334
- /**
335
- * Optional checkpointer for persisting graph state.
336
- * When provided, saves a checkpoint of the graph state at every superstep.
337
- * When false or undefined, checkpointing is disabled, and the graph will not be able to save or restore state.
338
- */
339
- Object.defineProperty(this, "checkpointer", {
340
- enumerable: true,
341
- configurable: true,
342
- writable: true,
343
- value: void 0
344
- });
345
- /** Optional retry policy for handling failures in node execution */
346
- Object.defineProperty(this, "retryPolicy", {
347
- enumerable: true,
348
- configurable: true,
349
- writable: true,
350
- value: void 0
351
- });
352
- /** The default configuration for graph execution, can be overridden on a per-invocation basis */
353
- Object.defineProperty(this, "config", {
354
- enumerable: true,
355
- configurable: true,
356
- writable: true,
357
- value: void 0
358
- });
359
- /**
360
- * Optional long-term memory store for the graph, allows for persistence & retrieval of data across threads
361
- */
362
- Object.defineProperty(this, "store", {
363
- enumerable: true,
364
- configurable: true,
365
- writable: true,
366
- value: void 0
367
- });
368
- Object.defineProperty(this, "triggerToNodes", {
369
- enumerable: true,
370
- configurable: true,
371
- writable: true,
372
- value: {}
373
- });
374
- /**
375
- * Optional cache for the graph, useful for caching tasks.
376
- */
377
- Object.defineProperty(this, "cache", {
378
- enumerable: true,
379
- configurable: true,
380
- writable: true,
381
- value: void 0
382
- });
383
- let { streamMode } = fields;
384
- if (streamMode != null && !Array.isArray(streamMode)) {
385
- streamMode = [streamMode];
386
- }
387
- this.nodes = fields.nodes;
388
- this.channels = fields.channels;
389
- if (constants_js_1.TASKS in this.channels &&
390
- "lc_graph_name" in this.channels[constants_js_1.TASKS] &&
391
- this.channels[constants_js_1.TASKS].lc_graph_name !== "Topic") {
392
- throw new Error(`Channel '${constants_js_1.TASKS}' is reserved and cannot be used in the graph.`);
393
- }
394
- else {
395
- this.channels[constants_js_1.TASKS] =
396
- new topic_js_1.Topic({ accumulate: false });
397
- }
398
- this.autoValidate = fields.autoValidate ?? this.autoValidate;
399
- this.streamMode = streamMode ?? this.streamMode;
400
- this.inputChannels = fields.inputChannels;
401
- this.outputChannels = fields.outputChannels;
402
- this.streamChannels = fields.streamChannels ?? this.streamChannels;
403
- this.interruptAfter = fields.interruptAfter;
404
- this.interruptBefore = fields.interruptBefore;
405
- this.stepTimeout = fields.stepTimeout ?? this.stepTimeout;
406
- this.debug = fields.debug ?? this.debug;
407
- this.checkpointer = fields.checkpointer;
408
- this.retryPolicy = fields.retryPolicy;
409
- this.config = fields.config;
410
- this.store = fields.store;
411
- this.cache = fields.cache;
412
- this.name = fields.name;
413
- if (this.autoValidate) {
414
- this.validate();
415
- }
416
- }
417
- /**
418
- * Creates a new instance of the Pregel graph with updated configuration.
419
- * This method follows the immutable pattern - instead of modifying the current instance,
420
- * it returns a new instance with the merged configuration.
421
- *
422
- * @example
423
- * ```typescript
424
- * // Create a new instance with debug enabled
425
- * const debugGraph = graph.withConfig({ debug: true });
426
- *
427
- * // Create a new instance with a specific thread ID
428
- * const threadGraph = graph.withConfig({
429
- * configurable: { thread_id: "123" }
430
- * });
431
- * ```
432
- *
433
- * @param config - The configuration to merge with the current configuration
434
- * @returns A new Pregel instance with the merged configuration
435
- */
436
- withConfig(config) {
437
- const mergedConfig = (0, runnables_1.mergeConfigs)(this.config, config);
438
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
439
- return new this.constructor({ ...this, config: mergedConfig });
440
- }
441
- /**
442
- * Validates the graph structure to ensure it is well-formed.
443
- * Checks for:
444
- * - No orphaned nodes
445
- * - Valid input/output channel configurations
446
- * - Valid interrupt configurations
447
- *
448
- * @returns this - The Pregel instance for method chaining
449
- * @throws {GraphValidationError} If the graph structure is invalid
450
- */
451
- validate() {
452
- (0, validate_js_1.validateGraph)({
453
- nodes: this.nodes,
454
- channels: this.channels,
455
- outputChannels: this.outputChannels,
456
- inputChannels: this.inputChannels,
457
- streamChannels: this.streamChannels,
458
- interruptAfterNodes: this.interruptAfter,
459
- interruptBeforeNodes: this.interruptBefore,
460
- });
461
- for (const [name, node] of Object.entries(this.nodes)) {
462
- for (const trigger of node.triggers) {
463
- this.triggerToNodes[trigger] ??= [];
464
- this.triggerToNodes[trigger].push(name);
465
- }
466
- }
467
- return this;
468
- }
469
- /**
470
- * Gets a list of all channels that should be streamed.
471
- * If streamChannels is specified, returns those channels.
472
- * Otherwise, returns all channels in the graph.
473
- *
474
- * @returns Array of channel keys to stream
475
- */
476
- get streamChannelsList() {
477
- if (Array.isArray(this.streamChannels)) {
478
- return this.streamChannels;
479
- }
480
- else if (this.streamChannels) {
481
- return [this.streamChannels];
482
- }
483
- else {
484
- return Object.keys(this.channels);
485
- }
486
- }
487
- /**
488
- * Gets the channels to stream in their original format.
489
- * If streamChannels is specified, returns it as-is (either single key or array).
490
- * Otherwise, returns all channels in the graph as an array.
491
- *
492
- * @returns Channel keys to stream, either as a single key or array
493
- */
494
- get streamChannelsAsIs() {
495
- if (this.streamChannels) {
496
- return this.streamChannels;
497
- }
498
- else {
499
- return Object.keys(this.channels);
500
- }
501
- }
502
- /**
503
- * Gets a drawable representation of the graph structure.
504
- * This is an async version of getGraph() and is the preferred method to use.
505
- *
506
- * @param config - Configuration for generating the graph visualization
507
- * @returns A representation of the graph that can be visualized
508
- */
509
- async getGraphAsync(config) {
510
- return this.getGraph(config);
511
- }
512
- /**
513
- * Gets all subgraphs within this graph.
514
- * A subgraph is a Pregel instance that is nested within a node of this graph.
515
- *
516
- * @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release.
517
- * @param namespace - Optional namespace to filter subgraphs
518
- * @param recurse - Whether to recursively get subgraphs of subgraphs
519
- * @returns Generator yielding tuples of [name, subgraph]
520
- */
521
- *getSubgraphs(namespace, recurse
522
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
523
- ) {
524
- for (const [name, node] of Object.entries(this.nodes)) {
525
- // filter by prefix
526
- if (namespace !== undefined) {
527
- if (!namespace.startsWith(name)) {
528
- continue;
529
- }
530
- }
531
- const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound];
532
- for (const candidate of candidates) {
533
- const graph = (0, subgraph_js_1.findSubgraphPregel)(candidate);
534
- if (graph !== undefined) {
535
- if (name === namespace) {
536
- yield [name, graph];
537
- return;
538
- }
539
- if (namespace === undefined) {
540
- yield [name, graph];
541
- }
542
- if (recurse) {
543
- let newNamespace = namespace;
544
- if (namespace !== undefined) {
545
- newNamespace = namespace.slice(name.length + 1);
546
- }
547
- for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) {
548
- yield [
549
- `${name}${constants_js_1.CHECKPOINT_NAMESPACE_SEPARATOR}${subgraphName}`,
550
- subgraph,
551
- ];
552
- }
553
- }
554
- }
555
- }
556
- }
557
- }
558
- /**
559
- * Gets all subgraphs within this graph asynchronously.
560
- * A subgraph is a Pregel instance that is nested within a node of this graph.
561
- *
562
- * @param namespace - Optional namespace to filter subgraphs
563
- * @param recurse - Whether to recursively get subgraphs of subgraphs
564
- * @returns AsyncGenerator yielding tuples of [name, subgraph]
565
- */
566
- async *getSubgraphsAsync(namespace, recurse
567
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
568
- ) {
569
- yield* this.getSubgraphs(namespace, recurse);
570
- }
571
- /**
572
- * Prepares a state snapshot from saved checkpoint data.
573
- * This is an internal method used by getState and getStateHistory.
574
- *
575
- * @param config - Configuration for preparing the snapshot
576
- * @param saved - Optional saved checkpoint data
577
- * @param subgraphCheckpointer - Optional checkpointer for subgraphs
578
- * @param applyPendingWrites - Whether to apply pending writes to tasks and then to channels
579
- * @returns A snapshot of the graph state
580
- * @internal
581
- */
582
- async _prepareStateSnapshot({ config, saved, subgraphCheckpointer, applyPendingWrites = false, }) {
583
- if (saved === undefined) {
584
- return {
585
- values: {},
586
- next: [],
587
- config,
588
- tasks: [],
589
- };
590
- }
591
- // Create all channels
592
- const channels = (0, base_js_1.emptyChannels)(this.channels, saved.checkpoint);
593
- // Apply null writes first (from NULL_TASK_ID)
594
- if (saved.pendingWrites?.length) {
595
- const nullWrites = saved.pendingWrites
596
- .filter(([taskId, _]) => taskId === constants_js_1.NULL_TASK_ID)
597
- .map(([_, channel, value]) => [String(channel), value]);
598
- if (nullWrites.length > 0) {
599
- (0, algo_js_1._applyWrites)(saved.checkpoint, channels, [
600
- {
601
- name: constants_js_1.INPUT,
602
- writes: nullWrites,
603
- triggers: [],
604
- },
605
- ], undefined, this.triggerToNodes);
606
- }
607
- }
608
- // Prepare next tasks
609
- const nextTasks = Object.values((0, algo_js_1._prepareNextTasks)(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { step: (saved.metadata?.step ?? -1) + 1, store: this.store }));
610
- // Find subgraphs
611
- const subgraphs = await (0, utils_js_1.gatherIterator)(this.getSubgraphsAsync());
612
- const parentNamespace = saved.config.configurable?.checkpoint_ns ?? "";
613
- const taskStates = {};
614
- // Prepare task states for subgraphs
615
- for (const task of nextTasks) {
616
- const matchingSubgraph = subgraphs.find(([name]) => name === task.name);
617
- if (!matchingSubgraph) {
618
- continue;
619
- }
620
- // assemble checkpoint_ns for this task
621
- let taskNs = `${String(task.name)}${constants_js_1.CHECKPOINT_NAMESPACE_END}${task.id}`;
622
- if (parentNamespace) {
623
- taskNs = `${parentNamespace}${constants_js_1.CHECKPOINT_NAMESPACE_SEPARATOR}${taskNs}`;
624
- }
625
- if (subgraphCheckpointer === undefined) {
626
- // set config as signal that subgraph checkpoints exist
627
- const config = {
628
- configurable: {
629
- thread_id: saved.config.configurable?.thread_id,
630
- checkpoint_ns: taskNs,
631
- },
632
- };
633
- taskStates[task.id] = config;
634
- }
635
- else {
636
- // get the state of the subgraph
637
- const subgraphConfig = {
638
- configurable: {
639
- [constants_js_1.CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer,
640
- thread_id: saved.config.configurable?.thread_id,
641
- checkpoint_ns: taskNs,
642
- },
643
- };
644
- const pregel = matchingSubgraph[1];
645
- taskStates[task.id] = await pregel.getState(subgraphConfig, {
646
- subgraphs: true,
647
- });
648
- }
649
- }
650
- // Apply pending writes to tasks and then to channels if applyPendingWrites is true
651
- if (applyPendingWrites && saved.pendingWrites?.length) {
652
- // Map task IDs to task objects for easy lookup
653
- const nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task]));
654
- // Apply pending writes to the appropriate tasks
655
- for (const [taskId, channel, value] of saved.pendingWrites) {
656
- // Skip special channels and tasks not in nextTasks
657
- if ([constants_js_1.ERROR, constants_js_1.INTERRUPT, langgraph_checkpoint_1.SCHEDULED].includes(channel)) {
658
- continue;
659
- }
660
- if (!(taskId in nextTaskById)) {
661
- continue;
662
- }
663
- // Add the write to the task
664
- nextTaskById[taskId].writes.push([String(channel), value]);
665
- }
666
- // Apply writes from tasks that have writes
667
- const tasksWithWrites = nextTasks.filter((task) => task.writes.length > 0);
668
- if (tasksWithWrites.length > 0) {
669
- (0, algo_js_1._applyWrites)(saved.checkpoint, channels, tasksWithWrites, undefined, this.triggerToNodes);
670
- }
671
- }
672
- // Preserve thread_id from the config in metadata
673
- let metadata = saved?.metadata;
674
- if (metadata && saved?.config?.configurable?.thread_id) {
675
- metadata = {
676
- ...metadata,
677
- thread_id: saved.config.configurable.thread_id,
678
- };
679
- }
680
- // Filter next tasks - only include tasks without writes
681
- const nextList = nextTasks
682
- .filter((task) => task.writes.length === 0)
683
- .map((task) => task.name);
684
- // assemble the state snapshot
685
- return {
686
- values: (0, io_js_1.readChannels)(channels, this.streamChannelsAsIs),
687
- next: nextList,
688
- tasks: (0, debug_js_1.tasksWithWrites)(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs),
689
- metadata,
690
- config: (0, index_js_1.patchCheckpointMap)(saved.config, saved.metadata),
691
- createdAt: saved.checkpoint.ts,
692
- parentConfig: saved.parentConfig,
693
- };
694
- }
695
- /**
696
- * Gets the current state of the graph.
697
- * Requires a checkpointer to be configured.
698
- *
699
- * @param config - Configuration for retrieving the state
700
- * @param options - Additional options
701
- * @returns A snapshot of the current graph state
702
- * @throws {GraphValueError} If no checkpointer is configured
703
- */
704
- async getState(config, options) {
705
- const checkpointer = config.configurable?.[constants_js_1.CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
706
- if (!checkpointer) {
707
- throw new errors_js_1.GraphValueError("No checkpointer set");
708
- }
709
- const checkpointNamespace = config.configurable?.checkpoint_ns ?? "";
710
- if (checkpointNamespace !== "" &&
711
- config.configurable?.[constants_js_1.CONFIG_KEY_CHECKPOINTER] === undefined) {
712
- // remove task_ids from checkpoint_ns
713
- const recastNamespace = (0, config_js_1.recastCheckpointNamespace)(checkpointNamespace);
714
- for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) {
715
- if (name === recastNamespace) {
716
- return await subgraph.getState((0, utils_js_1.patchConfigurable)(config, {
717
- [constants_js_1.CONFIG_KEY_CHECKPOINTER]: checkpointer,
718
- }), { subgraphs: options?.subgraphs });
719
- }
720
- }
721
- throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`);
722
- }
723
- const mergedConfig = (0, runnables_1.mergeConfigs)(this.config, config);
724
- const saved = await checkpointer.getTuple(config);
725
- const snapshot = await this._prepareStateSnapshot({
726
- config: mergedConfig,
727
- saved,
728
- subgraphCheckpointer: options?.subgraphs ? checkpointer : undefined,
729
- applyPendingWrites: !config.configurable?.checkpoint_id,
730
- });
731
- return snapshot;
732
- }
733
- /**
734
- * Gets the history of graph states.
735
- * Requires a checkpointer to be configured.
736
- * Useful for:
737
- * - Debugging execution history
738
- * - Implementing time travel
739
- * - Analyzing graph behavior
740
- *
741
- * @param config - Configuration for retrieving the history
742
- * @param options - Options for filtering the history
743
- * @returns An async iterator of state snapshots
744
- * @throws {Error} If no checkpointer is configured
745
- */
746
- async *getStateHistory(config, options) {
747
- const checkpointer = config.configurable?.[constants_js_1.CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
748
- if (!checkpointer) {
749
- throw new errors_js_1.GraphValueError("No checkpointer set");
750
- }
751
- const checkpointNamespace = config.configurable?.checkpoint_ns ?? "";
752
- if (checkpointNamespace !== "" &&
753
- config.configurable?.[constants_js_1.CONFIG_KEY_CHECKPOINTER] === undefined) {
754
- const recastNamespace = (0, config_js_1.recastCheckpointNamespace)(checkpointNamespace);
755
- // find the subgraph with the matching name
756
- for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) {
757
- if (name === recastNamespace) {
758
- yield* pregel.getStateHistory((0, utils_js_1.patchConfigurable)(config, {
759
- [constants_js_1.CONFIG_KEY_CHECKPOINTER]: checkpointer,
760
- }), options);
761
- return;
762
- }
763
- }
764
- throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`);
765
- }
766
- const mergedConfig = (0, runnables_1.mergeConfigs)(this.config, config, {
767
- configurable: { checkpoint_ns: checkpointNamespace },
768
- });
769
- for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) {
770
- yield this._prepareStateSnapshot({
771
- config: checkpointTuple.config,
772
- saved: checkpointTuple,
773
- });
774
- }
775
- }
776
- /**
777
- * Apply updates to the graph state in bulk.
778
- * Requires a checkpointer to be configured.
779
- *
780
- * This method is useful for recreating a thread
781
- * from a list of updates, especially if a checkpoint
782
- * is created as a result of multiple tasks.
783
- *
784
- * @internal The API might change in the future.
785
- *
786
- * @param startConfig - Configuration for the update
787
- * @param updates - The list of updates to apply to graph state
788
- * @returns Updated configuration
789
- * @throws {GraphValueError} If no checkpointer is configured
790
- * @throws {InvalidUpdateError} If the update cannot be attributed to a node or an update can be only applied in sequence.
791
- */
792
- async bulkUpdateState(startConfig, supersteps) {
793
- const checkpointer = startConfig.configurable?.[constants_js_1.CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
794
- if (!checkpointer) {
795
- throw new errors_js_1.GraphValueError("No checkpointer set");
796
- }
797
- if (supersteps.length === 0) {
798
- throw new Error("No supersteps provided");
799
- }
800
- if (supersteps.some((s) => s.updates.length === 0)) {
801
- throw new Error("No updates provided");
802
- }
803
- // delegate to subgraph
804
- const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? "";
805
- if (checkpointNamespace !== "" &&
806
- startConfig.configurable?.[constants_js_1.CONFIG_KEY_CHECKPOINTER] === undefined) {
807
- // remove task_ids from checkpoint_ns
808
- const recastNamespace = (0, config_js_1.recastCheckpointNamespace)(checkpointNamespace);
809
- // find the subgraph with the matching name
810
- // eslint-disable-next-line no-unreachable-loop
811
- for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) {
812
- return await pregel.bulkUpdateState((0, utils_js_1.patchConfigurable)(startConfig, {
813
- [constants_js_1.CONFIG_KEY_CHECKPOINTER]: checkpointer,
814
- }), supersteps);
815
- }
816
- throw new Error(`Subgraph "${recastNamespace}" not found`);
817
- }
818
- const updateSuperStep = async (inputConfig, updates) => {
819
- // get last checkpoint
820
- const config = this.config
821
- ? (0, runnables_1.mergeConfigs)(this.config, inputConfig)
822
- : inputConfig;
823
- const saved = await checkpointer.getTuple(config);
824
- const checkpoint = saved !== undefined
825
- ? (0, langgraph_checkpoint_1.copyCheckpoint)(saved.checkpoint)
826
- : (0, langgraph_checkpoint_1.emptyCheckpoint)();
827
- const checkpointPreviousVersions = {
828
- ...saved?.checkpoint.channel_versions,
829
- };
830
- const step = saved?.metadata?.step ?? -1;
831
- // merge configurable fields with previous checkpoint config
832
- let checkpointConfig = (0, utils_js_1.patchConfigurable)(config, {
833
- checkpoint_ns: config.configurable?.checkpoint_ns ?? "",
834
- });
835
- let checkpointMetadata = config.metadata ?? {};
836
- if (saved?.config.configurable) {
837
- checkpointConfig = (0, utils_js_1.patchConfigurable)(config, saved.config.configurable);
838
- checkpointMetadata = {
839
- ...saved.metadata,
840
- ...checkpointMetadata,
841
- };
842
- }
843
- // Find last node that updated the state, if not provided
844
- const { values, asNode } = updates[0];
845
- if (values == null && asNode === undefined) {
846
- if (updates.length > 1) {
847
- throw new errors_js_1.InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`);
848
- }
849
- const nextConfig = await checkpointer.put(checkpointConfig, (0, base_js_1.createCheckpoint)(checkpoint, undefined, step), {
850
- source: "update",
851
- step: step + 1,
852
- parents: saved?.metadata?.parents ?? {},
853
- }, {});
854
- return (0, index_js_1.patchCheckpointMap)(nextConfig, saved ? saved.metadata : undefined);
855
- }
856
- // update channels
857
- const channels = (0, base_js_1.emptyChannels)(this.channels, checkpoint);
858
- if (values === null && asNode === constants_js_1.END) {
859
- if (updates.length > 1) {
860
- throw new errors_js_1.InvalidUpdateError(`Cannot apply multiple updates when clearing state`);
861
- }
862
- if (saved) {
863
- // tasks for this checkpoint
864
- const nextTasks = (0, algo_js_1._prepareNextTasks)(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, {
865
- step: (saved.metadata?.step ?? -1) + 1,
866
- checkpointer,
867
- store: this.store,
868
- });
869
- // apply null writes
870
- const nullWrites = (saved.pendingWrites || [])
871
- .filter((w) => w[0] === constants_js_1.NULL_TASK_ID)
872
- .map((w) => w.slice(1));
873
- if (nullWrites.length > 0) {
874
- (0, algo_js_1._applyWrites)(checkpoint, channels, [
875
- {
876
- name: constants_js_1.INPUT,
877
- writes: nullWrites,
878
- triggers: [],
879
- },
880
- ], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);
881
- }
882
- // apply writes from tasks that already ran
883
- for (const [taskId, k, v] of saved.pendingWrites || []) {
884
- if ([constants_js_1.ERROR, constants_js_1.INTERRUPT, langgraph_checkpoint_1.SCHEDULED].includes(k)) {
885
- continue;
886
- }
887
- if (!(taskId in nextTasks)) {
888
- continue;
889
- }
890
- nextTasks[taskId].writes.push([k, v]);
891
- }
892
- // clear all current tasks
893
- (0, algo_js_1._applyWrites)(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);
894
- }
895
- // save checkpoint
896
- const nextConfig = await checkpointer.put(checkpointConfig, (0, base_js_1.createCheckpoint)(checkpoint, channels, step), {
897
- ...checkpointMetadata,
898
- source: "update",
899
- step: step + 1,
900
- parents: saved?.metadata?.parents ?? {},
901
- }, (0, index_js_1.getNewChannelVersions)(checkpointPreviousVersions, checkpoint.channel_versions));
902
- return (0, index_js_1.patchCheckpointMap)(nextConfig, saved ? saved.metadata : undefined);
903
- }
904
- if (asNode === constants_js_1.COPY) {
905
- if (updates.length > 1) {
906
- throw new errors_js_1.InvalidUpdateError(`Cannot copy checkpoint with multiple updates`);
907
- }
908
- if (saved == null) {
909
- throw new errors_js_1.InvalidUpdateError(`Cannot copy a non-existent checkpoint`);
910
- }
911
- const isCopyWithUpdates = (values) => {
912
- if (!Array.isArray(values))
913
- return false;
914
- if (values.length === 0)
915
- return false;
916
- return values.every((v) => Array.isArray(v) && v.length === 2);
917
- };
918
- const nextCheckpoint = (0, base_js_1.createCheckpoint)(checkpoint, undefined, step);
919
- const nextConfig = await checkpointer.put(saved.parentConfig ??
920
- (0, utils_js_1.patchConfigurable)(saved.config, { checkpoint_id: undefined }), nextCheckpoint, {
921
- source: "fork",
922
- step: step + 1,
923
- parents: saved.metadata?.parents ?? {},
924
- }, {});
925
- // We want to both clone a checkpoint and update state in one go.
926
- // Reuse the same task ID if possible.
927
- if (isCopyWithUpdates(values)) {
928
- // figure out the task IDs for the next update checkpoint
929
- const nextTasks = (0, algo_js_1._prepareNextTasks)(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig, false, { step: step + 2 });
930
- const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => {
931
- acc[name] ??= [];
932
- acc[name].push({ id });
933
- return acc;
934
- }, {});
935
- const userGroupBy = values.reduce((acc, item) => {
936
- const [values, asNode] = item;
937
- acc[asNode] ??= [];
938
- const targetIdx = acc[asNode].length;
939
- const taskId = tasksGroupBy[asNode]?.[targetIdx]?.id;
940
- acc[asNode].push({ values, asNode, taskId });
941
- return acc;
942
- }, {});
943
- return updateSuperStep((0, index_js_1.patchCheckpointMap)(nextConfig, saved.metadata), Object.values(userGroupBy).flat());
944
- }
945
- return (0, index_js_1.patchCheckpointMap)(nextConfig, saved.metadata);
946
- }
947
- if (asNode === constants_js_1.INPUT) {
948
- if (updates.length > 1) {
949
- throw new errors_js_1.InvalidUpdateError(`Cannot apply multiple updates when updating as input`);
950
- }
951
- const inputWrites = await (0, utils_js_1.gatherIterator)((0, io_js_1.mapInput)(this.inputChannels, values));
952
- if (inputWrites.length === 0) {
953
- throw new errors_js_1.InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`);
954
- }
955
- // apply to checkpoint
956
- (0, algo_js_1._applyWrites)(checkpoint, channels, [
957
- {
958
- name: constants_js_1.INPUT,
959
- writes: inputWrites,
960
- triggers: [],
961
- },
962
- ], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);
963
- // apply input write to channels
964
- const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1;
965
- const nextConfig = await checkpointer.put(checkpointConfig, (0, base_js_1.createCheckpoint)(checkpoint, channels, nextStep), {
966
- source: "input",
967
- step: nextStep,
968
- parents: saved?.metadata?.parents ?? {},
969
- }, (0, index_js_1.getNewChannelVersions)(checkpointPreviousVersions, checkpoint.channel_versions));
970
- // Store the writes
971
- await checkpointer.putWrites(nextConfig, inputWrites, (0, langgraph_checkpoint_1.uuid5)(constants_js_1.INPUT, checkpoint.id));
972
- return (0, index_js_1.patchCheckpointMap)(nextConfig, saved ? saved.metadata : undefined);
973
- }
974
- // apply pending writes, if not on specific checkpoint
975
- if (config.configurable?.checkpoint_id === undefined &&
976
- saved?.pendingWrites !== undefined &&
977
- saved.pendingWrites.length > 0) {
978
- // tasks for this checkpoint
979
- const nextTasks = (0, algo_js_1._prepareNextTasks)(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, {
980
- store: this.store,
981
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
982
- checkpointer: this.checkpointer,
983
- step: (saved.metadata?.step ?? -1) + 1,
984
- });
985
- // apply null writes
986
- const nullWrites = (saved.pendingWrites ?? [])
987
- .filter((w) => w[0] === constants_js_1.NULL_TASK_ID)
988
- .map((w) => w.slice(1));
989
- if (nullWrites.length > 0) {
990
- (0, algo_js_1._applyWrites)(saved.checkpoint, channels, [{ name: constants_js_1.INPUT, writes: nullWrites, triggers: [] }], undefined, this.triggerToNodes);
991
- }
992
- // apply writes
993
- for (const [tid, k, v] of saved.pendingWrites) {
994
- if ([constants_js_1.ERROR, constants_js_1.INTERRUPT, langgraph_checkpoint_1.SCHEDULED].includes(k) ||
995
- nextTasks[tid] === undefined) {
996
- continue;
997
- }
998
- nextTasks[tid].writes.push([k, v]);
999
- }
1000
- const tasks = Object.values(nextTasks).filter((task) => {
1001
- return task.writes.length > 0;
1002
- });
1003
- if (tasks.length > 0) {
1004
- (0, algo_js_1._applyWrites)(checkpoint, channels, tasks, undefined, this.triggerToNodes);
1005
- }
1006
- }
1007
- const nonNullVersion = Object.values(checkpoint.versions_seen)
1008
- .map((seenVersions) => {
1009
- return Object.values(seenVersions);
1010
- })
1011
- .flat()
1012
- .find((v) => !!v);
1013
- const validUpdates = [];
1014
- if (updates.length === 1) {
1015
- // eslint-disable-next-line prefer-const
1016
- let { values, asNode, taskId } = updates[0];
1017
- if (asNode === undefined && Object.keys(this.nodes).length === 1) {
1018
- // if only one node, use it
1019
- [asNode] = Object.keys(this.nodes);
1020
- }
1021
- else if (asNode === undefined && nonNullVersion === undefined) {
1022
- if (typeof this.inputChannels === "string" &&
1023
- this.nodes[this.inputChannels] !== undefined) {
1024
- asNode = this.inputChannels;
1025
- }
1026
- }
1027
- else if (asNode === undefined) {
1028
- const lastSeenByNode = Object.entries(checkpoint.versions_seen)
1029
- .map(([n, seen]) => {
1030
- return Object.values(seen).map((v) => {
1031
- return [v, n];
1032
- });
1033
- })
1034
- .flat()
1035
- .filter(([_, v]) => v !== constants_js_1.INTERRUPT)
1036
- .sort(([aNumber], [bNumber]) => (0, langgraph_checkpoint_1.compareChannelVersions)(aNumber, bNumber));
1037
- // if two nodes updated the state at the same time, it's ambiguous
1038
- if (lastSeenByNode) {
1039
- if (lastSeenByNode.length === 1) {
1040
- // eslint-disable-next-line prefer-destructuring
1041
- asNode = lastSeenByNode[0][1];
1042
- }
1043
- else if (lastSeenByNode[lastSeenByNode.length - 1][0] !==
1044
- lastSeenByNode[lastSeenByNode.length - 2][0]) {
1045
- // eslint-disable-next-line prefer-destructuring
1046
- asNode = lastSeenByNode[lastSeenByNode.length - 1][1];
1047
- }
1048
- }
1049
- }
1050
- if (asNode === undefined) {
1051
- throw new errors_js_1.InvalidUpdateError(`Ambiguous update, specify "asNode"`);
1052
- }
1053
- validUpdates.push({ values, asNode, taskId });
1054
- }
1055
- else {
1056
- for (const { asNode, values, taskId } of updates) {
1057
- if (asNode == null) {
1058
- throw new errors_js_1.InvalidUpdateError(`"asNode" is required when applying multiple updates`);
1059
- }
1060
- validUpdates.push({ values, asNode, taskId });
1061
- }
1062
- }
1063
- const tasks = [];
1064
- for (const { asNode, values, taskId } of validUpdates) {
1065
- if (this.nodes[asNode] === undefined) {
1066
- throw new errors_js_1.InvalidUpdateError(`Node "${asNode.toString()}" does not exist`);
1067
- }
1068
- // run all writers of the chosen node
1069
- const writers = this.nodes[asNode].getWriters();
1070
- if (!writers.length) {
1071
- throw new errors_js_1.InvalidUpdateError(`No writers found for node "${asNode.toString()}"`);
1072
- }
1073
- tasks.push({
1074
- name: asNode,
1075
- input: values,
1076
- proc: writers.length > 1
1077
- ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
1078
- runnables_1.RunnableSequence.from(writers, {
1079
- omitSequenceTags: true,
1080
- })
1081
- : writers[0],
1082
- writes: [],
1083
- triggers: [constants_js_1.INTERRUPT],
1084
- id: taskId ?? (0, langgraph_checkpoint_1.uuid5)(constants_js_1.INTERRUPT, checkpoint.id),
1085
- writers: [],
1086
- });
1087
- }
1088
- for (const task of tasks) {
1089
- // execute task
1090
- await task.proc.invoke(task.input, (0, runnables_1.patchConfig)({
1091
- ...config,
1092
- store: config?.store ?? this.store,
1093
- }, {
1094
- runName: config.runName ?? `${this.getName()}UpdateState`,
1095
- configurable: {
1096
- [constants_js_1.CONFIG_KEY_SEND]: (items) => task.writes.push(...items),
1097
- [constants_js_1.CONFIG_KEY_READ]: (select_, fresh_ = false) => (0, algo_js_1._localRead)(checkpoint, channels,
1098
- // TODO: Why does keyof StrRecord allow number and symbol?
1099
- task, select_, fresh_),
1100
- },
1101
- }));
1102
- }
1103
- for (const task of tasks) {
1104
- // channel writes are saved to current checkpoint
1105
- const channelWrites = task.writes.filter((w) => w[0] !== constants_js_1.PUSH);
1106
- // save task writes
1107
- if (saved !== undefined && channelWrites.length > 0) {
1108
- await checkpointer.putWrites(checkpointConfig, channelWrites, task.id);
1109
- }
1110
- }
1111
- // apply to checkpoint
1112
- // TODO: Why does keyof StrRecord allow number and symbol?
1113
- (0, algo_js_1._applyWrites)(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);
1114
- const newVersions = (0, index_js_1.getNewChannelVersions)(checkpointPreviousVersions, checkpoint.channel_versions);
1115
- const nextConfig = await checkpointer.put(checkpointConfig, (0, base_js_1.createCheckpoint)(checkpoint, channels, step + 1), {
1116
- source: "update",
1117
- step: step + 1,
1118
- parents: saved?.metadata?.parents ?? {},
1119
- }, newVersions);
1120
- for (const task of tasks) {
1121
- // push writes are saved to next checkpoint
1122
- const pushWrites = task.writes.filter((w) => w[0] === constants_js_1.PUSH);
1123
- if (pushWrites.length > 0) {
1124
- await checkpointer.putWrites(nextConfig, pushWrites, task.id);
1125
- }
1126
- }
1127
- return (0, index_js_1.patchCheckpointMap)(nextConfig, saved ? saved.metadata : undefined);
1128
- };
1129
- let currentConfig = startConfig;
1130
- for (const { updates } of supersteps) {
1131
- currentConfig = await updateSuperStep(currentConfig, updates);
1132
- }
1133
- return currentConfig;
1134
- }
1135
- /**
1136
- * Updates the state of the graph with new values.
1137
- * Requires a checkpointer to be configured.
1138
- *
1139
- * This method can be used for:
1140
- * - Implementing human-in-the-loop workflows
1141
- * - Modifying graph state during breakpoints
1142
- * - Integrating external inputs into the graph
1143
- *
1144
- * @param inputConfig - Configuration for the update
1145
- * @param values - The values to update the state with
1146
- * @param asNode - Optional node name to attribute the update to
1147
- * @returns Updated configuration
1148
- * @throws {GraphValueError} If no checkpointer is configured
1149
- * @throws {InvalidUpdateError} If the update cannot be attributed to a node
1150
- */
1151
- async updateState(inputConfig, values, asNode) {
1152
- return this.bulkUpdateState(inputConfig, [
1153
- { updates: [{ values, asNode }] },
1154
- ]);
1155
- }
1156
- /**
1157
- * Gets the default values for various graph configuration options.
1158
- * This is an internal method used to process and normalize configuration options.
1159
- *
1160
- * @param config - The input configuration options
1161
- * @returns A tuple containing normalized values for:
1162
- * - debug mode
1163
- * - stream modes
1164
- * - input keys
1165
- * - output keys
1166
- * - remaining config
1167
- * - interrupt before nodes
1168
- * - interrupt after nodes
1169
- * - checkpointer
1170
- * - store
1171
- * - whether stream mode is single
1172
- * - node cache
1173
- * - whether checkpoint during is enabled
1174
- * @internal
1175
- */
1176
- _defaults(config) {
1177
- const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore, ...rest } = config;
1178
- let streamModeSingle = true;
1179
- const defaultDebug = debug !== undefined ? debug : this.debug;
1180
- let defaultOutputKeys = outputKeys;
1181
- if (defaultOutputKeys === undefined) {
1182
- defaultOutputKeys = this.streamChannelsAsIs;
1183
- }
1184
- else {
1185
- (0, validate_js_1.validateKeys)(defaultOutputKeys, this.channels);
1186
- }
1187
- let defaultInputKeys = inputKeys;
1188
- if (defaultInputKeys === undefined) {
1189
- defaultInputKeys = this.inputChannels;
1190
- }
1191
- else {
1192
- (0, validate_js_1.validateKeys)(defaultInputKeys, this.channels);
1193
- }
1194
- const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? [];
1195
- const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? [];
1196
- let defaultStreamMode;
1197
- if (streamMode !== undefined) {
1198
- defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode];
1199
- streamModeSingle = typeof streamMode === "string";
1200
- }
1201
- else {
1202
- // if being called as a node in another graph, default to values mode
1203
- // but don't overwrite `streamMode`if provided
1204
- if (config.configurable?.[constants_js_1.CONFIG_KEY_TASK_ID] !== undefined) {
1205
- defaultStreamMode = ["values"];
1206
- }
1207
- else {
1208
- defaultStreamMode = this.streamMode;
1209
- }
1210
- streamModeSingle = true;
1211
- }
1212
- let defaultCheckpointer;
1213
- if (this.checkpointer === false) {
1214
- defaultCheckpointer = undefined;
1215
- }
1216
- else if (config !== undefined &&
1217
- config.configurable?.[constants_js_1.CONFIG_KEY_CHECKPOINTER] !== undefined) {
1218
- defaultCheckpointer = config.configurable[constants_js_1.CONFIG_KEY_CHECKPOINTER];
1219
- }
1220
- else if (this.checkpointer === true) {
1221
- throw new Error("checkpointer: true cannot be used for root graphs.");
1222
- }
1223
- else {
1224
- defaultCheckpointer = this.checkpointer;
1225
- }
1226
- const defaultStore = config.store ?? this.store;
1227
- const defaultCache = config.cache ?? this.cache;
1228
- if (config.durability != null && config.checkpointDuring != null) {
1229
- throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");
1230
- }
1231
- const checkpointDuringDurability = (() => {
1232
- if (config.checkpointDuring == null)
1233
- return undefined;
1234
- if (config.checkpointDuring === false)
1235
- return "exit";
1236
- return "async";
1237
- })();
1238
- const defaultDurability = config.durability ??
1239
- checkpointDuringDurability ??
1240
- config?.configurable?.[constants_js_1.CONFIG_KEY_DURABILITY] ??
1241
- "async";
1242
- return [
1243
- defaultDebug,
1244
- defaultStreamMode,
1245
- defaultInputKeys,
1246
- defaultOutputKeys,
1247
- rest,
1248
- defaultInterruptBefore,
1249
- defaultInterruptAfter,
1250
- defaultCheckpointer,
1251
- defaultStore,
1252
- streamModeSingle,
1253
- defaultCache,
1254
- defaultDurability,
1255
- ];
1256
- }
1257
- /**
1258
- * Streams the execution of the graph, emitting state updates as they occur.
1259
- * This is the primary method for observing graph execution in real-time.
1260
- *
1261
- * Stream modes:
1262
- * - "values": Emits complete state after each step
1263
- * - "updates": Emits only state changes after each step
1264
- * - "debug": Emits detailed debug information
1265
- * - "messages": Emits messages from within nodes
1266
- *
1267
- * For more details, see the [Streaming how-to guides](../../how-tos/#streaming_1).
1268
- *
1269
- * @param input - The input to start graph execution with
1270
- * @param options - Configuration options for streaming
1271
- * @returns An async iterable stream of graph state updates
1272
- */
1273
- async stream(input, options) {
1274
- // The ensureConfig method called internally defaults recursionLimit to 25 if not
1275
- // passed directly in `options`.
1276
- // There is currently no way in _streamIterator to determine whether this was
1277
- // set by by ensureConfig or manually by the user, so we specify the bound value here
1278
- // and override if it is passed as an explicit param in `options`.
1279
- const abortController = new AbortController();
1280
- const config = {
1281
- recursionLimit: this.config?.recursionLimit,
1282
- ...options,
1283
- signal: (0, index_js_1.combineAbortSignals)(options?.signal, abortController.signal)
1284
- .signal,
1285
- };
1286
- return new stream_js_1.IterableReadableStreamWithAbortSignal((await super.stream(input, config)), abortController);
1287
- }
1288
- streamEvents(input, options, streamOptions) {
1289
- const abortController = new AbortController();
1290
- const config = {
1291
- recursionLimit: this.config?.recursionLimit,
1292
- ...options,
1293
- // Similar to `stream`, we need to pass the `config.callbacks` here,
1294
- // otherwise the user-provided callback will get lost in `ensureLangGraphConfig`.
1295
- // extend the callbacks with the ones from the config
1296
- callbacks: (0, index_js_1.combineCallbacks)(this.config?.callbacks, options?.callbacks),
1297
- signal: (0, index_js_1.combineAbortSignals)(options?.signal, abortController.signal)
1298
- .signal,
1299
- };
1300
- return new stream_js_1.IterableReadableStreamWithAbortSignal(super.streamEvents(input, config, streamOptions), abortController);
1301
- }
1302
- /**
1303
- * Validates the input for the graph.
1304
- * @param input - The input to validate
1305
- * @returns The validated input
1306
- * @internal
1307
- */
1308
- async _validateInput(input) {
1309
- return input;
1310
- }
1311
- /**
1312
- * Validates the context options for the graph.
1313
- * @param context - The context options to validate
1314
- * @returns The validated context options
1315
- * @internal
1316
- */
1317
- async _validateContext(context) {
1318
- return context;
1319
- }
1320
- /**
1321
- * Internal iterator used by stream() to generate state updates.
1322
- * This method handles the core logic of graph execution and streaming.
1323
- *
1324
- * @param input - The input to start graph execution with
1325
- * @param options - Configuration options for streaming
1326
- * @returns AsyncGenerator yielding state updates
1327
- * @internal
1328
- */
1329
- async *_streamIterator(input, options) {
1330
- const streamSubgraphs = options?.subgraphs;
1331
- const inputConfig = (0, config_js_1.ensureLangGraphConfig)(this.config, options);
1332
- if (inputConfig.recursionLimit === undefined ||
1333
- inputConfig.recursionLimit < 1) {
1334
- throw new Error(`Passed "recursionLimit" must be at least 1.`);
1335
- }
1336
- if (this.checkpointer !== undefined &&
1337
- this.checkpointer !== false &&
1338
- inputConfig.configurable === undefined) {
1339
- throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`);
1340
- }
1341
- const validInput = await this._validateInput(input);
1342
- const { runId, ...restConfig } = inputConfig;
1343
- // assign defaults
1344
- const [debug, streamMode, , outputKeys, config, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache, durability,] = this._defaults(restConfig);
1345
- // At entrypoint, `configurable` is an alias for `context`.
1346
- if (typeof config.context !== "undefined") {
1347
- config.context = await this._validateContext(config.context);
1348
- }
1349
- else {
1350
- config.configurable = await this._validateContext(config.configurable);
1351
- }
1352
- const stream = new stream_js_1.IterableReadableWritableStream({
1353
- modes: new Set(streamMode),
1354
- });
1355
- // set up subgraph checkpointing
1356
- if (this.checkpointer === true) {
1357
- config.configurable ??= {};
1358
- const ns = config.configurable[constants_js_1.CONFIG_KEY_CHECKPOINT_NS] ?? "";
1359
- config.configurable[constants_js_1.CONFIG_KEY_CHECKPOINT_NS] = ns
1360
- .split(constants_js_1.CHECKPOINT_NAMESPACE_SEPARATOR)
1361
- .map((part) => part.split(constants_js_1.CHECKPOINT_NAMESPACE_END)[0])
1362
- .join(constants_js_1.CHECKPOINT_NAMESPACE_SEPARATOR);
1363
- }
1364
- // set up messages stream mode
1365
- if (streamMode.includes("messages")) {
1366
- const messageStreamer = new messages_js_1.StreamMessagesHandler((chunk) => stream.push(chunk));
1367
- const { callbacks } = config;
1368
- if (callbacks === undefined) {
1369
- config.callbacks = [messageStreamer];
1370
- }
1371
- else if (Array.isArray(callbacks)) {
1372
- config.callbacks = callbacks.concat(messageStreamer);
1373
- }
1374
- else {
1375
- const copiedCallbacks = callbacks.copy();
1376
- copiedCallbacks.addHandler(messageStreamer, true);
1377
- config.callbacks = copiedCallbacks;
1378
- }
1379
- }
1380
- // setup custom stream mode
1381
- if (streamMode.includes("custom")) {
1382
- config.writer = (chunk) => {
1383
- const ns = (0, config_js_1.getConfig)()?.configurable?.[constants_js_1.CONFIG_KEY_CHECKPOINT_NS]
1384
- ?.split(constants_js_1.CHECKPOINT_NAMESPACE_SEPARATOR)
1385
- .slice(0, -1);
1386
- stream.push([ns ?? [], "custom", chunk]);
1387
- };
1388
- }
1389
- const callbackManager = await (0, runnables_1.getCallbackManagerForConfig)(config);
1390
- const runManager = await callbackManager?.handleChainStart(this.toJSON(), // chain
1391
- (0, index_js_1._coerceToDict)(input, "input"), // inputs
1392
- runId, // run_id
1393
- undefined, // run_type
1394
- undefined, // tags
1395
- undefined, // metadata
1396
- config?.runName ?? this.getName() // run_name
1397
- );
1398
- const channelSpecs = (0, base_js_1.getOnlyChannels)(this.channels);
1399
- let loop;
1400
- let loopError;
1401
- /**
1402
- * The PregelLoop will yield events from concurrent tasks as soon as they are
1403
- * generated. Each task can push multiple events onto the stream in any order.
1404
- *
1405
- * We use a separate background method and stream here in order to yield events
1406
- * from the loop to the main stream and therefore back to the user as soon as
1407
- * they are available.
1408
- */
1409
- const createAndRunLoop = async () => {
1410
- try {
1411
- loop = await loop_js_1.PregelLoop.initialize({
1412
- input: validInput,
1413
- config,
1414
- checkpointer,
1415
- nodes: this.nodes,
1416
- channelSpecs,
1417
- outputKeys,
1418
- streamKeys: this.streamChannelsAsIs,
1419
- store,
1420
- cache: cache,
1421
- stream,
1422
- interruptAfter,
1423
- interruptBefore,
1424
- manager: runManager,
1425
- debug: this.debug,
1426
- triggerToNodes: this.triggerToNodes,
1427
- durability,
1428
- });
1429
- const runner = new runner_js_1.PregelRunner({
1430
- loop,
1431
- nodeFinished: config.configurable?.[constants_js_1.CONFIG_KEY_NODE_FINISHED],
1432
- });
1433
- if (options?.subgraphs) {
1434
- loop.config.configurable = {
1435
- ...loop.config.configurable,
1436
- [constants_js_1.CONFIG_KEY_STREAM]: loop.stream,
1437
- };
1438
- }
1439
- await this._runLoop({ loop, runner, debug, config });
1440
- // wait for checkpoints to be persisted
1441
- if (durability === "sync") {
1442
- await Promise.all(loop?.checkpointerPromises ?? []);
1443
- }
1444
- }
1445
- catch (e) {
1446
- loopError = e;
1447
- }
1448
- finally {
1449
- try {
1450
- // Call `.stop()` again incase it was not called in the loop, e.g due to an error.
1451
- if (loop) {
1452
- await loop.store?.stop();
1453
- await loop.cache?.stop();
1454
- }
1455
- await Promise.all(loop?.checkpointerPromises ?? []);
1456
- }
1457
- catch (e) {
1458
- loopError = loopError ?? e;
1459
- }
1460
- if (loopError) {
1461
- // "Causes any future interactions with the associated stream to error".
1462
- // Wraps ReadableStreamDefaultController#error:
1463
- // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultController/error
1464
- stream.error(loopError);
1465
- }
1466
- else {
1467
- // Will end the iterator outside of this method,
1468
- // keeping previously enqueued chunks.
1469
- // Wraps ReadableStreamDefaultController#close:
1470
- // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultController/close
1471
- stream.close();
1472
- }
1473
- }
1474
- };
1475
- const runLoopPromise = createAndRunLoop();
1476
- try {
1477
- for await (const chunk of stream) {
1478
- if (chunk === undefined) {
1479
- throw new Error("Data structure error.");
1480
- }
1481
- const [namespace, mode, payload] = chunk;
1482
- if (streamMode.includes(mode)) {
1483
- if (streamSubgraphs && !streamModeSingle) {
1484
- yield [namespace, mode, payload];
1485
- }
1486
- else if (!streamModeSingle) {
1487
- yield [mode, payload];
1488
- }
1489
- else if (streamSubgraphs) {
1490
- yield [namespace, payload];
1491
- }
1492
- else {
1493
- yield payload;
1494
- }
1495
- }
1496
- }
1497
- }
1498
- catch (e) {
1499
- await runManager?.handleChainError(loopError);
1500
- throw e;
1501
- }
1502
- finally {
1503
- await runLoopPromise;
1504
- }
1505
- await runManager?.handleChainEnd(loop?.output ?? {}, runId, // run_id
1506
- undefined, // run_type
1507
- undefined, // tags
1508
- undefined // metadata
1509
- );
1510
- }
1511
- /**
1512
- * Run the graph with a single input and config.
1513
- * @param input The input to the graph.
1514
- * @param options The configuration to use for the run.
1515
- */
1516
- async invoke(input, options) {
1517
- const streamMode = options?.streamMode ?? "values";
1518
- const config = {
1519
- ...options,
1520
- outputKeys: options?.outputKeys ?? this.outputChannels,
1521
- streamMode,
1522
- };
1523
- const chunks = [];
1524
- const stream = await this.stream(input, config);
1525
- const interruptChunks = [];
1526
- let latest;
1527
- for await (const chunk of stream) {
1528
- if (streamMode === "values") {
1529
- if ((0, constants_js_1.isInterrupted)(chunk)) {
1530
- interruptChunks.push(chunk[constants_js_1.INTERRUPT]);
1531
- }
1532
- else {
1533
- latest = chunk;
1534
- }
1535
- }
1536
- else {
1537
- chunks.push(chunk);
1538
- }
1539
- }
1540
- if (streamMode === "values") {
1541
- if (interruptChunks.length > 0) {
1542
- const interrupts = interruptChunks.flat(1);
1543
- if (latest == null)
1544
- return { [constants_js_1.INTERRUPT]: interrupts };
1545
- if (typeof latest === "object") {
1546
- return { ...latest, [constants_js_1.INTERRUPT]: interrupts };
1547
- }
1548
- }
1549
- return latest;
1550
- }
1551
- return chunks;
1552
- }
1553
- async _runLoop(params) {
1554
- const { loop, runner, debug, config } = params;
1555
- let tickError;
1556
- try {
1557
- while (await loop.tick({ inputKeys: this.inputChannels })) {
1558
- for (const { task } of await loop._matchCachedWrites()) {
1559
- loop._outputWrites(task.id, task.writes, true);
1560
- }
1561
- if (debug) {
1562
- (0, debug_js_1.printStepCheckpoint)(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList);
1563
- }
1564
- if (debug) {
1565
- (0, debug_js_1.printStepTasks)(loop.step, Object.values(loop.tasks));
1566
- }
1567
- await runner.tick({
1568
- timeout: this.stepTimeout,
1569
- retryPolicy: this.retryPolicy,
1570
- onStepWrite: (step, writes) => {
1571
- if (debug) {
1572
- (0, debug_js_1.printStepWrites)(step, writes, this.streamChannelsList);
1573
- }
1574
- },
1575
- maxConcurrency: config.maxConcurrency,
1576
- signal: config.signal,
1577
- });
1578
- }
1579
- if (loop.status === "out_of_steps") {
1580
- throw new errors_js_1.GraphRecursionError([
1581
- `Recursion limit of ${config.recursionLimit} reached`,
1582
- "without hitting a stop condition. You can increase the",
1583
- `limit by setting the "recursionLimit" config key.`,
1584
- ].join(" "), {
1585
- lc_error_code: "GRAPH_RECURSION_LIMIT",
1586
- });
1587
- }
1588
- }
1589
- catch (e) {
1590
- tickError = e;
1591
- const suppress = await loop.finishAndHandleError(tickError);
1592
- if (!suppress) {
1593
- throw e;
1594
- }
1595
- }
1596
- finally {
1597
- if (tickError === undefined) {
1598
- await loop.finishAndHandleError();
1599
- }
1600
- }
1601
- }
1602
- async clearCache() {
1603
- await this.cache?.clear([]);
1604
- }
1605
- }
109
+ * The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model
110
+ * inspired by [Google's Pregel system](https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/).
111
+ * It provides the foundation for building reliable, controllable agent workflows that can evolve state over time.
112
+ *
113
+ * Key features:
114
+ * - Message passing between nodes in discrete "supersteps"
115
+ * - Built-in persistence layer through checkpointers
116
+ * - First-class streaming support for values, updates, and events
117
+ * - Human-in-the-loop capabilities via interrupts
118
+ * - Support for parallel node execution within supersteps
119
+ *
120
+ * The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs:
121
+ * - {@link StateGraph}: The main graph class for building agent workflows
122
+ * - Compiling a {@link StateGraph} will return a {@link CompiledGraph} instance, which extends `Pregel`
123
+ * - Functional API: A declarative approach using tasks and entrypoints
124
+ * - A `Pregel` instance is returned by the {@link entrypoint} function
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * // Using StateGraph API
129
+ * const graph = new StateGraph(annotation)
130
+ * .addNode("nodeA", myNodeFunction)
131
+ * .addEdge("nodeA", "nodeB")
132
+ * .compile();
133
+ *
134
+ * // The compiled graph is a Pregel instance
135
+ * const result = await graph.invoke(input);
136
+ * ```
137
+ *
138
+ * @example
139
+ * ```typescript
140
+ * // Using Functional API
141
+ * import { task, entrypoint } from "@langchain/langgraph";
142
+ * import { MemorySaver } from "@langchain/langgraph-checkpoint";
143
+ *
144
+ * // Define tasks that can be composed
145
+ * const addOne = task("add", async (x: number) => x + 1);
146
+ *
147
+ * // Create a workflow using the entrypoint function
148
+ * const workflow = entrypoint({
149
+ * name: "workflow",
150
+ * checkpointer: new MemorySaver()
151
+ * }, async (numbers: number[]) => {
152
+ * // Tasks can be run in parallel
153
+ * const results = await Promise.all(numbers.map(n => addOne(n)));
154
+ * return results;
155
+ * });
156
+ *
157
+ * // The workflow is a Pregel instance
158
+ * const result = await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]
159
+ * ```
160
+ *
161
+ * @typeParam Nodes - Mapping of node names to their {@link PregelNode} implementations
162
+ * @typeParam Channels - Mapping of channel names to their {@link BaseChannel} or {@link ManagedValueSpec} implementations
163
+ * @typeParam ContextType - Type of context that can be passed to the graph
164
+ * @typeParam InputType - Type of input values accepted by the graph
165
+ * @typeParam OutputType - Type of output values produced by the graph
166
+ */
167
+ var Pregel = class extends PartialRunnable {
168
+ /**
169
+ * Name of the class when serialized
170
+ * @internal
171
+ */
172
+ static lc_name() {
173
+ return "LangGraph";
174
+ }
175
+ /** @internal LangChain namespace for serialization necessary because Pregel extends Runnable */
176
+ lc_namespace = ["langgraph", "pregel"];
177
+ /** @internal Flag indicating this is a Pregel instance - necessary for serialization */
178
+ lg_is_pregel = true;
179
+ /** The nodes in the graph, mapping node names to their PregelNode instances */
180
+ nodes;
181
+ /** The channels in the graph, mapping channel names to their BaseChannel or ManagedValueSpec instances */
182
+ channels;
183
+ /**
184
+ * The input channels for the graph. These channels receive the initial input when the graph is invoked.
185
+ * Can be a single channel key or an array of channel keys.
186
+ */
187
+ inputChannels;
188
+ /**
189
+ * The output channels for the graph. These channels contain the final output when the graph completes.
190
+ * Can be a single channel key or an array of channel keys.
191
+ */
192
+ outputChannels;
193
+ /** Whether to automatically validate the graph structure when it is compiled. Defaults to true. */
194
+ autoValidate = true;
195
+ /**
196
+ * The streaming modes enabled for this graph. Defaults to ["values"].
197
+ * Supported modes:
198
+ * - "values": Streams the full state after each step
199
+ * - "updates": Streams state updates after each step
200
+ * - "messages": Streams messages from within nodes
201
+ * - "custom": Streams custom events from within nodes
202
+ * - "debug": Streams events related to the execution of the graph - useful for tracing & debugging graph execution
203
+ */
204
+ streamMode = ["values"];
205
+ /**
206
+ * Optional channels to stream. If not specified, all channels will be streamed.
207
+ * Can be a single channel key or an array of channel keys.
208
+ */
209
+ streamChannels;
210
+ /**
211
+ * Optional array of node names or "all" to interrupt after executing these nodes.
212
+ * Used for implementing human-in-the-loop workflows.
213
+ */
214
+ interruptAfter;
215
+ /**
216
+ * Optional array of node names or "all" to interrupt before executing these nodes.
217
+ * Used for implementing human-in-the-loop workflows.
218
+ */
219
+ interruptBefore;
220
+ /** Optional timeout in milliseconds for the execution of each superstep */
221
+ stepTimeout;
222
+ /** Whether to enable debug logging. Defaults to false. */
223
+ debug = false;
224
+ /**
225
+ * Optional checkpointer for persisting graph state.
226
+ * When provided, saves a checkpoint of the graph state at every superstep.
227
+ * When false or undefined, checkpointing is disabled, and the graph will not be able to save or restore state.
228
+ */
229
+ checkpointer;
230
+ /** Optional retry policy for handling failures in node execution */
231
+ retryPolicy;
232
+ /** The default configuration for graph execution, can be overridden on a per-invocation basis */
233
+ config;
234
+ /**
235
+ * Optional long-term memory store for the graph, allows for persistence & retrieval of data across threads
236
+ */
237
+ store;
238
+ triggerToNodes = {};
239
+ /**
240
+ * Optional cache for the graph, useful for caching tasks.
241
+ */
242
+ cache;
243
+ /**
244
+ * Constructor for Pregel - meant for internal use only.
245
+ *
246
+ * @internal
247
+ */
248
+ constructor(fields) {
249
+ super(fields);
250
+ let { streamMode } = fields;
251
+ if (streamMode != null && !Array.isArray(streamMode)) streamMode = [streamMode];
252
+ this.nodes = fields.nodes;
253
+ this.channels = fields.channels;
254
+ if (require_constants.TASKS in this.channels && "lc_graph_name" in this.channels[require_constants.TASKS] && this.channels[require_constants.TASKS].lc_graph_name !== "Topic") throw new Error(`Channel '${require_constants.TASKS}' is reserved and cannot be used in the graph.`);
255
+ else this.channels[require_constants.TASKS] = new require_topic.Topic({ accumulate: false });
256
+ this.autoValidate = fields.autoValidate ?? this.autoValidate;
257
+ this.streamMode = streamMode ?? this.streamMode;
258
+ this.inputChannels = fields.inputChannels;
259
+ this.outputChannels = fields.outputChannels;
260
+ this.streamChannels = fields.streamChannels ?? this.streamChannels;
261
+ this.interruptAfter = fields.interruptAfter;
262
+ this.interruptBefore = fields.interruptBefore;
263
+ this.stepTimeout = fields.stepTimeout ?? this.stepTimeout;
264
+ this.debug = fields.debug ?? this.debug;
265
+ this.checkpointer = fields.checkpointer;
266
+ this.retryPolicy = fields.retryPolicy;
267
+ this.config = fields.config;
268
+ this.store = fields.store;
269
+ this.cache = fields.cache;
270
+ this.name = fields.name;
271
+ if (this.autoValidate) this.validate();
272
+ }
273
+ /**
274
+ * Creates a new instance of the Pregel graph with updated configuration.
275
+ * This method follows the immutable pattern - instead of modifying the current instance,
276
+ * it returns a new instance with the merged configuration.
277
+ *
278
+ * @example
279
+ * ```typescript
280
+ * // Create a new instance with debug enabled
281
+ * const debugGraph = graph.withConfig({ debug: true });
282
+ *
283
+ * // Create a new instance with a specific thread ID
284
+ * const threadGraph = graph.withConfig({
285
+ * configurable: { thread_id: "123" }
286
+ * });
287
+ * ```
288
+ *
289
+ * @param config - The configuration to merge with the current configuration
290
+ * @returns A new Pregel instance with the merged configuration
291
+ */
292
+ withConfig(config) {
293
+ const mergedConfig = (0, __langchain_core_runnables.mergeConfigs)(this.config, config);
294
+ return new this.constructor({
295
+ ...this,
296
+ config: mergedConfig
297
+ });
298
+ }
299
+ /**
300
+ * Validates the graph structure to ensure it is well-formed.
301
+ * Checks for:
302
+ * - No orphaned nodes
303
+ * - Valid input/output channel configurations
304
+ * - Valid interrupt configurations
305
+ *
306
+ * @returns this - The Pregel instance for method chaining
307
+ * @throws {GraphValidationError} If the graph structure is invalid
308
+ */
309
+ validate() {
310
+ require_validate.validateGraph({
311
+ nodes: this.nodes,
312
+ channels: this.channels,
313
+ outputChannels: this.outputChannels,
314
+ inputChannels: this.inputChannels,
315
+ streamChannels: this.streamChannels,
316
+ interruptAfterNodes: this.interruptAfter,
317
+ interruptBeforeNodes: this.interruptBefore
318
+ });
319
+ for (const [name, node] of Object.entries(this.nodes)) for (const trigger of node.triggers) {
320
+ this.triggerToNodes[trigger] ??= [];
321
+ this.triggerToNodes[trigger].push(name);
322
+ }
323
+ return this;
324
+ }
325
+ /**
326
+ * Gets a list of all channels that should be streamed.
327
+ * If streamChannels is specified, returns those channels.
328
+ * Otherwise, returns all channels in the graph.
329
+ *
330
+ * @returns Array of channel keys to stream
331
+ */
332
+ get streamChannelsList() {
333
+ if (Array.isArray(this.streamChannels)) return this.streamChannels;
334
+ else if (this.streamChannels) return [this.streamChannels];
335
+ else return Object.keys(this.channels);
336
+ }
337
+ /**
338
+ * Gets the channels to stream in their original format.
339
+ * If streamChannels is specified, returns it as-is (either single key or array).
340
+ * Otherwise, returns all channels in the graph as an array.
341
+ *
342
+ * @returns Channel keys to stream, either as a single key or array
343
+ */
344
+ get streamChannelsAsIs() {
345
+ if (this.streamChannels) return this.streamChannels;
346
+ else return Object.keys(this.channels);
347
+ }
348
+ /**
349
+ * Gets a drawable representation of the graph structure.
350
+ * This is an async version of getGraph() and is the preferred method to use.
351
+ *
352
+ * @param config - Configuration for generating the graph visualization
353
+ * @returns A representation of the graph that can be visualized
354
+ */
355
+ async getGraphAsync(config) {
356
+ return this.getGraph(config);
357
+ }
358
+ /**
359
+ * Gets all subgraphs within this graph.
360
+ * A subgraph is a Pregel instance that is nested within a node of this graph.
361
+ *
362
+ * @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release.
363
+ * @param namespace - Optional namespace to filter subgraphs
364
+ * @param recurse - Whether to recursively get subgraphs of subgraphs
365
+ * @returns Generator yielding tuples of [name, subgraph]
366
+ */
367
+ *getSubgraphs(namespace, recurse) {
368
+ for (const [name, node] of Object.entries(this.nodes)) {
369
+ if (namespace !== void 0) {
370
+ if (!namespace.startsWith(name)) continue;
371
+ }
372
+ const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound];
373
+ for (const candidate of candidates) {
374
+ const graph = require_subgraph.findSubgraphPregel(candidate);
375
+ if (graph !== void 0) {
376
+ if (name === namespace) {
377
+ yield [name, graph];
378
+ return;
379
+ }
380
+ if (namespace === void 0) yield [name, graph];
381
+ if (recurse) {
382
+ let newNamespace = namespace;
383
+ if (namespace !== void 0) newNamespace = namespace.slice(name.length + 1);
384
+ for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) yield [`${name}${require_constants.CHECKPOINT_NAMESPACE_SEPARATOR}${subgraphName}`, subgraph];
385
+ }
386
+ }
387
+ }
388
+ }
389
+ }
390
+ /**
391
+ * Gets all subgraphs within this graph asynchronously.
392
+ * A subgraph is a Pregel instance that is nested within a node of this graph.
393
+ *
394
+ * @param namespace - Optional namespace to filter subgraphs
395
+ * @param recurse - Whether to recursively get subgraphs of subgraphs
396
+ * @returns AsyncGenerator yielding tuples of [name, subgraph]
397
+ */
398
+ async *getSubgraphsAsync(namespace, recurse) {
399
+ yield* this.getSubgraphs(namespace, recurse);
400
+ }
401
+ /**
402
+ * Prepares a state snapshot from saved checkpoint data.
403
+ * This is an internal method used by getState and getStateHistory.
404
+ *
405
+ * @param config - Configuration for preparing the snapshot
406
+ * @param saved - Optional saved checkpoint data
407
+ * @param subgraphCheckpointer - Optional checkpointer for subgraphs
408
+ * @param applyPendingWrites - Whether to apply pending writes to tasks and then to channels
409
+ * @returns A snapshot of the graph state
410
+ * @internal
411
+ */
412
+ async _prepareStateSnapshot({ config, saved, subgraphCheckpointer, applyPendingWrites = false }) {
413
+ if (saved === void 0) return {
414
+ values: {},
415
+ next: [],
416
+ config,
417
+ tasks: []
418
+ };
419
+ const channels = require_base.emptyChannels(this.channels, saved.checkpoint);
420
+ if (saved.pendingWrites?.length) {
421
+ const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === require_constants.NULL_TASK_ID).map(([_, channel, value]) => [String(channel), value]);
422
+ if (nullWrites.length > 0) require_algo._applyWrites(saved.checkpoint, channels, [{
423
+ name: require_constants.INPUT,
424
+ writes: nullWrites,
425
+ triggers: []
426
+ }], void 0, this.triggerToNodes);
427
+ }
428
+ const nextTasks = Object.values(require_algo._prepareNextTasks(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, {
429
+ step: (saved.metadata?.step ?? -1) + 1,
430
+ store: this.store
431
+ }));
432
+ const subgraphs = await require_utils.gatherIterator(this.getSubgraphsAsync());
433
+ const parentNamespace = saved.config.configurable?.checkpoint_ns ?? "";
434
+ const taskStates = {};
435
+ for (const task of nextTasks) {
436
+ const matchingSubgraph = subgraphs.find(([name]) => name === task.name);
437
+ if (!matchingSubgraph) continue;
438
+ let taskNs = `${String(task.name)}${require_constants.CHECKPOINT_NAMESPACE_END}${task.id}`;
439
+ if (parentNamespace) taskNs = `${parentNamespace}${require_constants.CHECKPOINT_NAMESPACE_SEPARATOR}${taskNs}`;
440
+ if (subgraphCheckpointer === void 0) {
441
+ const config$1 = { configurable: {
442
+ thread_id: saved.config.configurable?.thread_id,
443
+ checkpoint_ns: taskNs
444
+ } };
445
+ taskStates[task.id] = config$1;
446
+ } else {
447
+ const subgraphConfig = { configurable: {
448
+ [require_constants.CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer,
449
+ thread_id: saved.config.configurable?.thread_id,
450
+ checkpoint_ns: taskNs
451
+ } };
452
+ const pregel = matchingSubgraph[1];
453
+ taskStates[task.id] = await pregel.getState(subgraphConfig, { subgraphs: true });
454
+ }
455
+ }
456
+ if (applyPendingWrites && saved.pendingWrites?.length) {
457
+ const nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task]));
458
+ for (const [taskId, channel, value] of saved.pendingWrites) {
459
+ if ([
460
+ require_constants.ERROR,
461
+ require_constants.INTERRUPT,
462
+ __langchain_langgraph_checkpoint.SCHEDULED
463
+ ].includes(channel)) continue;
464
+ if (!(taskId in nextTaskById)) continue;
465
+ nextTaskById[taskId].writes.push([String(channel), value]);
466
+ }
467
+ const tasksWithWrites$1 = nextTasks.filter((task) => task.writes.length > 0);
468
+ if (tasksWithWrites$1.length > 0) require_algo._applyWrites(saved.checkpoint, channels, tasksWithWrites$1, void 0, this.triggerToNodes);
469
+ }
470
+ let metadata = saved?.metadata;
471
+ if (metadata && saved?.config?.configurable?.thread_id) metadata = {
472
+ ...metadata,
473
+ thread_id: saved.config.configurable.thread_id
474
+ };
475
+ const nextList = nextTasks.filter((task) => task.writes.length === 0).map((task) => task.name);
476
+ return {
477
+ values: require_io.readChannels(channels, this.streamChannelsAsIs),
478
+ next: nextList,
479
+ tasks: require_debug.tasksWithWrites(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs),
480
+ metadata,
481
+ config: require_index.patchCheckpointMap(saved.config, saved.metadata),
482
+ createdAt: saved.checkpoint.ts,
483
+ parentConfig: saved.parentConfig
484
+ };
485
+ }
486
+ /**
487
+ * Gets the current state of the graph.
488
+ * Requires a checkpointer to be configured.
489
+ *
490
+ * @param config - Configuration for retrieving the state
491
+ * @param options - Additional options
492
+ * @returns A snapshot of the current graph state
493
+ * @throws {GraphValueError} If no checkpointer is configured
494
+ */
495
+ async getState(config, options) {
496
+ const checkpointer = config.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
497
+ if (!checkpointer) throw new require_errors.GraphValueError("No checkpointer set");
498
+ const checkpointNamespace = config.configurable?.checkpoint_ns ?? "";
499
+ if (checkpointNamespace !== "" && config.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] === void 0) {
500
+ const recastNamespace = require_config.recastCheckpointNamespace(checkpointNamespace);
501
+ for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) return await subgraph.getState(require_utils.patchConfigurable(config, { [require_constants.CONFIG_KEY_CHECKPOINTER]: checkpointer }), { subgraphs: options?.subgraphs });
502
+ throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`);
503
+ }
504
+ const mergedConfig = (0, __langchain_core_runnables.mergeConfigs)(this.config, config);
505
+ const saved = await checkpointer.getTuple(config);
506
+ const snapshot = await this._prepareStateSnapshot({
507
+ config: mergedConfig,
508
+ saved,
509
+ subgraphCheckpointer: options?.subgraphs ? checkpointer : void 0,
510
+ applyPendingWrites: !config.configurable?.checkpoint_id
511
+ });
512
+ return snapshot;
513
+ }
514
+ /**
515
+ * Gets the history of graph states.
516
+ * Requires a checkpointer to be configured.
517
+ * Useful for:
518
+ * - Debugging execution history
519
+ * - Implementing time travel
520
+ * - Analyzing graph behavior
521
+ *
522
+ * @param config - Configuration for retrieving the history
523
+ * @param options - Options for filtering the history
524
+ * @returns An async iterator of state snapshots
525
+ * @throws {Error} If no checkpointer is configured
526
+ */
527
+ async *getStateHistory(config, options) {
528
+ const checkpointer = config.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
529
+ if (!checkpointer) throw new require_errors.GraphValueError("No checkpointer set");
530
+ const checkpointNamespace = config.configurable?.checkpoint_ns ?? "";
531
+ if (checkpointNamespace !== "" && config.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] === void 0) {
532
+ const recastNamespace = require_config.recastCheckpointNamespace(checkpointNamespace);
533
+ for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) {
534
+ yield* pregel.getStateHistory(require_utils.patchConfigurable(config, { [require_constants.CONFIG_KEY_CHECKPOINTER]: checkpointer }), options);
535
+ return;
536
+ }
537
+ throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`);
538
+ }
539
+ const mergedConfig = (0, __langchain_core_runnables.mergeConfigs)(this.config, config, { configurable: { checkpoint_ns: checkpointNamespace } });
540
+ for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) yield this._prepareStateSnapshot({
541
+ config: checkpointTuple.config,
542
+ saved: checkpointTuple
543
+ });
544
+ }
545
+ /**
546
+ * Apply updates to the graph state in bulk.
547
+ * Requires a checkpointer to be configured.
548
+ *
549
+ * This method is useful for recreating a thread
550
+ * from a list of updates, especially if a checkpoint
551
+ * is created as a result of multiple tasks.
552
+ *
553
+ * @internal The API might change in the future.
554
+ *
555
+ * @param startConfig - Configuration for the update
556
+ * @param updates - The list of updates to apply to graph state
557
+ * @returns Updated configuration
558
+ * @throws {GraphValueError} If no checkpointer is configured
559
+ * @throws {InvalidUpdateError} If the update cannot be attributed to a node or an update can be only applied in sequence.
560
+ */
561
+ async bulkUpdateState(startConfig, supersteps) {
562
+ const checkpointer = startConfig.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
563
+ if (!checkpointer) throw new require_errors.GraphValueError("No checkpointer set");
564
+ if (supersteps.length === 0) throw new Error("No supersteps provided");
565
+ if (supersteps.some((s) => s.updates.length === 0)) throw new Error("No updates provided");
566
+ const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? "";
567
+ if (checkpointNamespace !== "" && startConfig.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] === void 0) {
568
+ const recastNamespace = require_config.recastCheckpointNamespace(checkpointNamespace);
569
+ for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) return await pregel.bulkUpdateState(require_utils.patchConfigurable(startConfig, { [require_constants.CONFIG_KEY_CHECKPOINTER]: checkpointer }), supersteps);
570
+ throw new Error(`Subgraph "${recastNamespace}" not found`);
571
+ }
572
+ const updateSuperStep = async (inputConfig, updates) => {
573
+ const config = this.config ? (0, __langchain_core_runnables.mergeConfigs)(this.config, inputConfig) : inputConfig;
574
+ const saved = await checkpointer.getTuple(config);
575
+ const checkpoint = saved !== void 0 ? (0, __langchain_langgraph_checkpoint.copyCheckpoint)(saved.checkpoint) : (0, __langchain_langgraph_checkpoint.emptyCheckpoint)();
576
+ const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions };
577
+ const step = saved?.metadata?.step ?? -1;
578
+ let checkpointConfig = require_utils.patchConfigurable(config, { checkpoint_ns: config.configurable?.checkpoint_ns ?? "" });
579
+ let checkpointMetadata = config.metadata ?? {};
580
+ if (saved?.config.configurable) {
581
+ checkpointConfig = require_utils.patchConfigurable(config, saved.config.configurable);
582
+ checkpointMetadata = {
583
+ ...saved.metadata,
584
+ ...checkpointMetadata
585
+ };
586
+ }
587
+ const { values, asNode } = updates[0];
588
+ if (values == null && asNode === void 0) {
589
+ if (updates.length > 1) throw new require_errors.InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`);
590
+ const nextConfig$1 = await checkpointer.put(checkpointConfig, require_base.createCheckpoint(checkpoint, void 0, step), {
591
+ source: "update",
592
+ step: step + 1,
593
+ parents: saved?.metadata?.parents ?? {}
594
+ }, {});
595
+ return require_index.patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);
596
+ }
597
+ const channels = require_base.emptyChannels(this.channels, checkpoint);
598
+ if (values === null && asNode === require_constants.END) {
599
+ if (updates.length > 1) throw new require_errors.InvalidUpdateError(`Cannot apply multiple updates when clearing state`);
600
+ if (saved) {
601
+ const nextTasks = require_algo._prepareNextTasks(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, {
602
+ step: (saved.metadata?.step ?? -1) + 1,
603
+ checkpointer,
604
+ store: this.store
605
+ });
606
+ const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === require_constants.NULL_TASK_ID).map((w) => w.slice(1));
607
+ if (nullWrites.length > 0) require_algo._applyWrites(checkpoint, channels, [{
608
+ name: require_constants.INPUT,
609
+ writes: nullWrites,
610
+ triggers: []
611
+ }], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);
612
+ for (const [taskId, k, v] of saved.pendingWrites || []) {
613
+ if ([
614
+ require_constants.ERROR,
615
+ require_constants.INTERRUPT,
616
+ __langchain_langgraph_checkpoint.SCHEDULED
617
+ ].includes(k)) continue;
618
+ if (!(taskId in nextTasks)) continue;
619
+ nextTasks[taskId].writes.push([k, v]);
620
+ }
621
+ require_algo._applyWrites(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);
622
+ }
623
+ const nextConfig$1 = await checkpointer.put(checkpointConfig, require_base.createCheckpoint(checkpoint, channels, step), {
624
+ ...checkpointMetadata,
625
+ source: "update",
626
+ step: step + 1,
627
+ parents: saved?.metadata?.parents ?? {}
628
+ }, require_index.getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions));
629
+ return require_index.patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);
630
+ }
631
+ if (asNode === require_constants.COPY) {
632
+ if (updates.length > 1) throw new require_errors.InvalidUpdateError(`Cannot copy checkpoint with multiple updates`);
633
+ if (saved == null) throw new require_errors.InvalidUpdateError(`Cannot copy a non-existent checkpoint`);
634
+ const isCopyWithUpdates = (values$1) => {
635
+ if (!Array.isArray(values$1)) return false;
636
+ if (values$1.length === 0) return false;
637
+ return values$1.every((v) => Array.isArray(v) && v.length === 2);
638
+ };
639
+ const nextCheckpoint = require_base.createCheckpoint(checkpoint, void 0, step);
640
+ const nextConfig$1 = await checkpointer.put(saved.parentConfig ?? require_utils.patchConfigurable(saved.config, { checkpoint_id: void 0 }), nextCheckpoint, {
641
+ source: "fork",
642
+ step: step + 1,
643
+ parents: saved.metadata?.parents ?? {}
644
+ }, {});
645
+ if (isCopyWithUpdates(values)) {
646
+ const nextTasks = require_algo._prepareNextTasks(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig$1, false, { step: step + 2 });
647
+ const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => {
648
+ acc[name] ??= [];
649
+ acc[name].push({ id });
650
+ return acc;
651
+ }, {});
652
+ const userGroupBy = values.reduce((acc, item) => {
653
+ const [values$1, asNode$1] = item;
654
+ acc[asNode$1] ??= [];
655
+ const targetIdx = acc[asNode$1].length;
656
+ const taskId = tasksGroupBy[asNode$1]?.[targetIdx]?.id;
657
+ acc[asNode$1].push({
658
+ values: values$1,
659
+ asNode: asNode$1,
660
+ taskId
661
+ });
662
+ return acc;
663
+ }, {});
664
+ return updateSuperStep(require_index.patchCheckpointMap(nextConfig$1, saved.metadata), Object.values(userGroupBy).flat());
665
+ }
666
+ return require_index.patchCheckpointMap(nextConfig$1, saved.metadata);
667
+ }
668
+ if (asNode === require_constants.INPUT) {
669
+ if (updates.length > 1) throw new require_errors.InvalidUpdateError(`Cannot apply multiple updates when updating as input`);
670
+ const inputWrites = await require_utils.gatherIterator(require_io.mapInput(this.inputChannels, values));
671
+ if (inputWrites.length === 0) throw new require_errors.InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`);
672
+ require_algo._applyWrites(checkpoint, channels, [{
673
+ name: require_constants.INPUT,
674
+ writes: inputWrites,
675
+ triggers: []
676
+ }], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);
677
+ const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1;
678
+ const nextConfig$1 = await checkpointer.put(checkpointConfig, require_base.createCheckpoint(checkpoint, channels, nextStep), {
679
+ source: "input",
680
+ step: nextStep,
681
+ parents: saved?.metadata?.parents ?? {}
682
+ }, require_index.getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions));
683
+ await checkpointer.putWrites(nextConfig$1, inputWrites, (0, __langchain_langgraph_checkpoint.uuid5)(require_constants.INPUT, checkpoint.id));
684
+ return require_index.patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);
685
+ }
686
+ if (config.configurable?.checkpoint_id === void 0 && saved?.pendingWrites !== void 0 && saved.pendingWrites.length > 0) {
687
+ const nextTasks = require_algo._prepareNextTasks(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, {
688
+ store: this.store,
689
+ checkpointer: this.checkpointer,
690
+ step: (saved.metadata?.step ?? -1) + 1
691
+ });
692
+ const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === require_constants.NULL_TASK_ID).map((w) => w.slice(1));
693
+ if (nullWrites.length > 0) require_algo._applyWrites(saved.checkpoint, channels, [{
694
+ name: require_constants.INPUT,
695
+ writes: nullWrites,
696
+ triggers: []
697
+ }], void 0, this.triggerToNodes);
698
+ for (const [tid, k, v] of saved.pendingWrites) {
699
+ if ([
700
+ require_constants.ERROR,
701
+ require_constants.INTERRUPT,
702
+ __langchain_langgraph_checkpoint.SCHEDULED
703
+ ].includes(k) || nextTasks[tid] === void 0) continue;
704
+ nextTasks[tid].writes.push([k, v]);
705
+ }
706
+ const tasks$1 = Object.values(nextTasks).filter((task) => {
707
+ return task.writes.length > 0;
708
+ });
709
+ if (tasks$1.length > 0) require_algo._applyWrites(checkpoint, channels, tasks$1, void 0, this.triggerToNodes);
710
+ }
711
+ const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => {
712
+ return Object.values(seenVersions);
713
+ }).flat().find((v) => !!v);
714
+ const validUpdates = [];
715
+ if (updates.length === 1) {
716
+ let { values: values$1, asNode: asNode$1, taskId } = updates[0];
717
+ if (asNode$1 === void 0 && Object.keys(this.nodes).length === 1) [asNode$1] = Object.keys(this.nodes);
718
+ else if (asNode$1 === void 0 && nonNullVersion === void 0) {
719
+ if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== void 0) asNode$1 = this.inputChannels;
720
+ } else if (asNode$1 === void 0) {
721
+ const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n, seen]) => {
722
+ return Object.values(seen).map((v) => {
723
+ return [v, n];
724
+ });
725
+ }).flat().filter(([_, v]) => v !== require_constants.INTERRUPT).sort(([aNumber], [bNumber]) => (0, __langchain_langgraph_checkpoint.compareChannelVersions)(aNumber, bNumber));
726
+ if (lastSeenByNode) {
727
+ if (lastSeenByNode.length === 1) asNode$1 = lastSeenByNode[0][1];
728
+ else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) asNode$1 = lastSeenByNode[lastSeenByNode.length - 1][1];
729
+ }
730
+ }
731
+ if (asNode$1 === void 0) throw new require_errors.InvalidUpdateError(`Ambiguous update, specify "asNode"`);
732
+ validUpdates.push({
733
+ values: values$1,
734
+ asNode: asNode$1,
735
+ taskId
736
+ });
737
+ } else for (const { asNode: asNode$1, values: values$1, taskId } of updates) {
738
+ if (asNode$1 == null) throw new require_errors.InvalidUpdateError(`"asNode" is required when applying multiple updates`);
739
+ validUpdates.push({
740
+ values: values$1,
741
+ asNode: asNode$1,
742
+ taskId
743
+ });
744
+ }
745
+ const tasks = [];
746
+ for (const { asNode: asNode$1, values: values$1, taskId } of validUpdates) {
747
+ if (this.nodes[asNode$1] === void 0) throw new require_errors.InvalidUpdateError(`Node "${asNode$1.toString()}" does not exist`);
748
+ const writers = this.nodes[asNode$1].getWriters();
749
+ if (!writers.length) throw new require_errors.InvalidUpdateError(`No writers found for node "${asNode$1.toString()}"`);
750
+ tasks.push({
751
+ name: asNode$1,
752
+ input: values$1,
753
+ proc: writers.length > 1 ? __langchain_core_runnables.RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0],
754
+ writes: [],
755
+ triggers: [require_constants.INTERRUPT],
756
+ id: taskId ?? (0, __langchain_langgraph_checkpoint.uuid5)(require_constants.INTERRUPT, checkpoint.id),
757
+ writers: []
758
+ });
759
+ }
760
+ for (const task of tasks) await task.proc.invoke(task.input, (0, __langchain_core_runnables.patchConfig)({
761
+ ...config,
762
+ store: config?.store ?? this.store
763
+ }, {
764
+ runName: config.runName ?? `${this.getName()}UpdateState`,
765
+ configurable: {
766
+ [require_constants.CONFIG_KEY_SEND]: (items) => task.writes.push(...items),
767
+ [require_constants.CONFIG_KEY_READ]: (select_, fresh_ = false) => require_algo._localRead(checkpoint, channels, task, select_, fresh_)
768
+ }
769
+ }));
770
+ for (const task of tasks) {
771
+ const channelWrites = task.writes.filter((w) => w[0] !== require_constants.PUSH);
772
+ if (saved !== void 0 && channelWrites.length > 0) await checkpointer.putWrites(checkpointConfig, channelWrites, task.id);
773
+ }
774
+ require_algo._applyWrites(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);
775
+ const newVersions = require_index.getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions);
776
+ const nextConfig = await checkpointer.put(checkpointConfig, require_base.createCheckpoint(checkpoint, channels, step + 1), {
777
+ source: "update",
778
+ step: step + 1,
779
+ parents: saved?.metadata?.parents ?? {}
780
+ }, newVersions);
781
+ for (const task of tasks) {
782
+ const pushWrites = task.writes.filter((w) => w[0] === require_constants.PUSH);
783
+ if (pushWrites.length > 0) await checkpointer.putWrites(nextConfig, pushWrites, task.id);
784
+ }
785
+ return require_index.patchCheckpointMap(nextConfig, saved ? saved.metadata : void 0);
786
+ };
787
+ let currentConfig = startConfig;
788
+ for (const { updates } of supersteps) currentConfig = await updateSuperStep(currentConfig, updates);
789
+ return currentConfig;
790
+ }
791
+ /**
792
+ * Updates the state of the graph with new values.
793
+ * Requires a checkpointer to be configured.
794
+ *
795
+ * This method can be used for:
796
+ * - Implementing human-in-the-loop workflows
797
+ * - Modifying graph state during breakpoints
798
+ * - Integrating external inputs into the graph
799
+ *
800
+ * @param inputConfig - Configuration for the update
801
+ * @param values - The values to update the state with
802
+ * @param asNode - Optional node name to attribute the update to
803
+ * @returns Updated configuration
804
+ * @throws {GraphValueError} If no checkpointer is configured
805
+ * @throws {InvalidUpdateError} If the update cannot be attributed to a node
806
+ */
807
+ async updateState(inputConfig, values, asNode) {
808
+ return this.bulkUpdateState(inputConfig, [{ updates: [{
809
+ values,
810
+ asNode
811
+ }] }]);
812
+ }
813
+ /**
814
+ * Gets the default values for various graph configuration options.
815
+ * This is an internal method used to process and normalize configuration options.
816
+ *
817
+ * @param config - The input configuration options
818
+ * @returns A tuple containing normalized values for:
819
+ * - debug mode
820
+ * - stream modes
821
+ * - input keys
822
+ * - output keys
823
+ * - remaining config
824
+ * - interrupt before nodes
825
+ * - interrupt after nodes
826
+ * - checkpointer
827
+ * - store
828
+ * - whether stream mode is single
829
+ * - node cache
830
+ * - whether checkpoint during is enabled
831
+ * @internal
832
+ */
833
+ _defaults(config) {
834
+ const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore,...rest } = config;
835
+ let streamModeSingle = true;
836
+ const defaultDebug = debug !== void 0 ? debug : this.debug;
837
+ let defaultOutputKeys = outputKeys;
838
+ if (defaultOutputKeys === void 0) defaultOutputKeys = this.streamChannelsAsIs;
839
+ else require_validate.validateKeys(defaultOutputKeys, this.channels);
840
+ let defaultInputKeys = inputKeys;
841
+ if (defaultInputKeys === void 0) defaultInputKeys = this.inputChannels;
842
+ else require_validate.validateKeys(defaultInputKeys, this.channels);
843
+ const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? [];
844
+ const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? [];
845
+ let defaultStreamMode;
846
+ if (streamMode !== void 0) {
847
+ defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode];
848
+ streamModeSingle = typeof streamMode === "string";
849
+ } else {
850
+ if (config.configurable?.[require_constants.CONFIG_KEY_TASK_ID] !== void 0) defaultStreamMode = ["values"];
851
+ else defaultStreamMode = this.streamMode;
852
+ streamModeSingle = true;
853
+ }
854
+ let defaultCheckpointer;
855
+ if (this.checkpointer === false) defaultCheckpointer = void 0;
856
+ else if (config !== void 0 && config.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] !== void 0) defaultCheckpointer = config.configurable[require_constants.CONFIG_KEY_CHECKPOINTER];
857
+ else if (this.checkpointer === true) throw new Error("checkpointer: true cannot be used for root graphs.");
858
+ else defaultCheckpointer = this.checkpointer;
859
+ const defaultStore = config.store ?? this.store;
860
+ const defaultCache = config.cache ?? this.cache;
861
+ if (config.durability != null && config.checkpointDuring != null) throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");
862
+ const checkpointDuringDurability = (() => {
863
+ if (config.checkpointDuring == null) return void 0;
864
+ if (config.checkpointDuring === false) return "exit";
865
+ return "async";
866
+ })();
867
+ const defaultDurability = config.durability ?? checkpointDuringDurability ?? config?.configurable?.[require_constants.CONFIG_KEY_DURABILITY] ?? "async";
868
+ return [
869
+ defaultDebug,
870
+ defaultStreamMode,
871
+ defaultInputKeys,
872
+ defaultOutputKeys,
873
+ rest,
874
+ defaultInterruptBefore,
875
+ defaultInterruptAfter,
876
+ defaultCheckpointer,
877
+ defaultStore,
878
+ streamModeSingle,
879
+ defaultCache,
880
+ defaultDurability
881
+ ];
882
+ }
883
+ /**
884
+ * Streams the execution of the graph, emitting state updates as they occur.
885
+ * This is the primary method for observing graph execution in real-time.
886
+ *
887
+ * Stream modes:
888
+ * - "values": Emits complete state after each step
889
+ * - "updates": Emits only state changes after each step
890
+ * - "debug": Emits detailed debug information
891
+ * - "messages": Emits messages from within nodes
892
+ *
893
+ * For more details, see the [Streaming how-to guides](../../how-tos/#streaming_1).
894
+ *
895
+ * @param input - The input to start graph execution with
896
+ * @param options - Configuration options for streaming
897
+ * @returns An async iterable stream of graph state updates
898
+ */
899
+ async stream(input, options) {
900
+ const abortController = new AbortController();
901
+ const config = {
902
+ recursionLimit: this.config?.recursionLimit,
903
+ ...options,
904
+ signal: require_index.combineAbortSignals(options?.signal, abortController.signal).signal
905
+ };
906
+ return new require_stream.IterableReadableStreamWithAbortSignal(await super.stream(input, config), abortController);
907
+ }
908
+ streamEvents(input, options, streamOptions) {
909
+ const abortController = new AbortController();
910
+ const config = {
911
+ recursionLimit: this.config?.recursionLimit,
912
+ ...options,
913
+ callbacks: require_index.combineCallbacks(this.config?.callbacks, options?.callbacks),
914
+ signal: require_index.combineAbortSignals(options?.signal, abortController.signal).signal
915
+ };
916
+ return new require_stream.IterableReadableStreamWithAbortSignal(super.streamEvents(input, config, streamOptions), abortController);
917
+ }
918
+ /**
919
+ * Validates the input for the graph.
920
+ * @param input - The input to validate
921
+ * @returns The validated input
922
+ * @internal
923
+ */
924
+ async _validateInput(input) {
925
+ return input;
926
+ }
927
+ /**
928
+ * Validates the context options for the graph.
929
+ * @param context - The context options to validate
930
+ * @returns The validated context options
931
+ * @internal
932
+ */
933
+ async _validateContext(context) {
934
+ return context;
935
+ }
936
+ /**
937
+ * Internal iterator used by stream() to generate state updates.
938
+ * This method handles the core logic of graph execution and streaming.
939
+ *
940
+ * @param input - The input to start graph execution with
941
+ * @param options - Configuration options for streaming
942
+ * @returns AsyncGenerator yielding state updates
943
+ * @internal
944
+ */
945
+ async *_streamIterator(input, options) {
946
+ const streamSubgraphs = options?.subgraphs;
947
+ const inputConfig = require_config.ensureLangGraphConfig(this.config, options);
948
+ if (inputConfig.recursionLimit === void 0 || inputConfig.recursionLimit < 1) throw new Error(`Passed "recursionLimit" must be at least 1.`);
949
+ if (this.checkpointer !== void 0 && this.checkpointer !== false && inputConfig.configurable === void 0) throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`);
950
+ const validInput = await this._validateInput(input);
951
+ const { runId,...restConfig } = inputConfig;
952
+ const [debug, streamMode, , outputKeys, config, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache, durability] = this._defaults(restConfig);
953
+ if (typeof config.context !== "undefined") config.context = await this._validateContext(config.context);
954
+ else config.configurable = await this._validateContext(config.configurable);
955
+ const stream = new require_stream.IterableReadableWritableStream({ modes: new Set(streamMode) });
956
+ if (this.checkpointer === true) {
957
+ config.configurable ??= {};
958
+ const ns = config.configurable[require_constants.CONFIG_KEY_CHECKPOINT_NS] ?? "";
959
+ config.configurable[require_constants.CONFIG_KEY_CHECKPOINT_NS] = ns.split(require_constants.CHECKPOINT_NAMESPACE_SEPARATOR).map((part) => part.split(require_constants.CHECKPOINT_NAMESPACE_END)[0]).join(require_constants.CHECKPOINT_NAMESPACE_SEPARATOR);
960
+ }
961
+ if (streamMode.includes("messages")) {
962
+ const messageStreamer = new require_messages.StreamMessagesHandler((chunk) => stream.push(chunk));
963
+ const { callbacks } = config;
964
+ if (callbacks === void 0) config.callbacks = [messageStreamer];
965
+ else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(messageStreamer);
966
+ else {
967
+ const copiedCallbacks = callbacks.copy();
968
+ copiedCallbacks.addHandler(messageStreamer, true);
969
+ config.callbacks = copiedCallbacks;
970
+ }
971
+ }
972
+ if (streamMode.includes("custom")) config.writer = (chunk) => {
973
+ const ns = (require_config.getConfig()?.configurable?.[require_constants.CONFIG_KEY_CHECKPOINT_NS])?.split(require_constants.CHECKPOINT_NAMESPACE_SEPARATOR).slice(0, -1);
974
+ stream.push([
975
+ ns ?? [],
976
+ "custom",
977
+ chunk
978
+ ]);
979
+ };
980
+ const callbackManager = await (0, __langchain_core_runnables.getCallbackManagerForConfig)(config);
981
+ const runManager = await callbackManager?.handleChainStart(this.toJSON(), require_index._coerceToDict(input, "input"), runId, void 0, void 0, void 0, config?.runName ?? this.getName());
982
+ const channelSpecs = require_base.getOnlyChannels(this.channels);
983
+ let loop;
984
+ let loopError;
985
+ /**
986
+ * The PregelLoop will yield events from concurrent tasks as soon as they are
987
+ * generated. Each task can push multiple events onto the stream in any order.
988
+ *
989
+ * We use a separate background method and stream here in order to yield events
990
+ * from the loop to the main stream and therefore back to the user as soon as
991
+ * they are available.
992
+ */
993
+ const createAndRunLoop = async () => {
994
+ try {
995
+ loop = await require_loop.PregelLoop.initialize({
996
+ input: validInput,
997
+ config,
998
+ checkpointer,
999
+ nodes: this.nodes,
1000
+ channelSpecs,
1001
+ outputKeys,
1002
+ streamKeys: this.streamChannelsAsIs,
1003
+ store,
1004
+ cache,
1005
+ stream,
1006
+ interruptAfter,
1007
+ interruptBefore,
1008
+ manager: runManager,
1009
+ debug: this.debug,
1010
+ triggerToNodes: this.triggerToNodes,
1011
+ durability
1012
+ });
1013
+ const runner = new require_runner.PregelRunner({
1014
+ loop,
1015
+ nodeFinished: config.configurable?.[require_constants.CONFIG_KEY_NODE_FINISHED]
1016
+ });
1017
+ if (options?.subgraphs) loop.config.configurable = {
1018
+ ...loop.config.configurable,
1019
+ [require_constants.CONFIG_KEY_STREAM]: loop.stream
1020
+ };
1021
+ await this._runLoop({
1022
+ loop,
1023
+ runner,
1024
+ debug,
1025
+ config
1026
+ });
1027
+ if (durability === "sync") await Promise.all(loop?.checkpointerPromises ?? []);
1028
+ } catch (e) {
1029
+ loopError = e;
1030
+ } finally {
1031
+ try {
1032
+ if (loop) {
1033
+ await loop.store?.stop();
1034
+ await loop.cache?.stop();
1035
+ }
1036
+ await Promise.all(loop?.checkpointerPromises ?? []);
1037
+ } catch (e) {
1038
+ loopError = loopError ?? e;
1039
+ }
1040
+ if (loopError) stream.error(loopError);
1041
+ else stream.close();
1042
+ }
1043
+ };
1044
+ const runLoopPromise = createAndRunLoop();
1045
+ try {
1046
+ for await (const chunk of stream) {
1047
+ if (chunk === void 0) throw new Error("Data structure error.");
1048
+ const [namespace, mode, payload] = chunk;
1049
+ if (streamMode.includes(mode)) if (streamSubgraphs && !streamModeSingle) yield [
1050
+ namespace,
1051
+ mode,
1052
+ payload
1053
+ ];
1054
+ else if (!streamModeSingle) yield [mode, payload];
1055
+ else if (streamSubgraphs) yield [namespace, payload];
1056
+ else yield payload;
1057
+ }
1058
+ } catch (e) {
1059
+ await runManager?.handleChainError(loopError);
1060
+ throw e;
1061
+ } finally {
1062
+ await runLoopPromise;
1063
+ }
1064
+ await runManager?.handleChainEnd(loop?.output ?? {}, runId, void 0, void 0, void 0);
1065
+ }
1066
+ /**
1067
+ * Run the graph with a single input and config.
1068
+ * @param input The input to the graph.
1069
+ * @param options The configuration to use for the run.
1070
+ */
1071
+ async invoke(input, options) {
1072
+ const streamMode = options?.streamMode ?? "values";
1073
+ const config = {
1074
+ ...options,
1075
+ outputKeys: options?.outputKeys ?? this.outputChannels,
1076
+ streamMode
1077
+ };
1078
+ const chunks = [];
1079
+ const stream = await this.stream(input, config);
1080
+ const interruptChunks = [];
1081
+ let latest;
1082
+ for await (const chunk of stream) if (streamMode === "values") if (require_constants.isInterrupted(chunk)) interruptChunks.push(chunk[require_constants.INTERRUPT]);
1083
+ else latest = chunk;
1084
+ else chunks.push(chunk);
1085
+ if (streamMode === "values") {
1086
+ if (interruptChunks.length > 0) {
1087
+ const interrupts = interruptChunks.flat(1);
1088
+ if (latest == null) return { [require_constants.INTERRUPT]: interrupts };
1089
+ if (typeof latest === "object") return {
1090
+ ...latest,
1091
+ [require_constants.INTERRUPT]: interrupts
1092
+ };
1093
+ }
1094
+ return latest;
1095
+ }
1096
+ return chunks;
1097
+ }
1098
+ async _runLoop(params) {
1099
+ const { loop, runner, debug, config } = params;
1100
+ let tickError;
1101
+ try {
1102
+ while (await loop.tick({ inputKeys: this.inputChannels })) {
1103
+ for (const { task } of await loop._matchCachedWrites()) loop._outputWrites(task.id, task.writes, true);
1104
+ if (debug) require_debug.printStepCheckpoint(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList);
1105
+ if (debug) require_debug.printStepTasks(loop.step, Object.values(loop.tasks));
1106
+ await runner.tick({
1107
+ timeout: this.stepTimeout,
1108
+ retryPolicy: this.retryPolicy,
1109
+ onStepWrite: (step, writes) => {
1110
+ if (debug) require_debug.printStepWrites(step, writes, this.streamChannelsList);
1111
+ },
1112
+ maxConcurrency: config.maxConcurrency,
1113
+ signal: config.signal
1114
+ });
1115
+ }
1116
+ if (loop.status === "out_of_steps") throw new require_errors.GraphRecursionError([
1117
+ `Recursion limit of ${config.recursionLimit} reached`,
1118
+ "without hitting a stop condition. You can increase the",
1119
+ `limit by setting the "recursionLimit" config key.`
1120
+ ].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" });
1121
+ } catch (e) {
1122
+ tickError = e;
1123
+ const suppress = await loop.finishAndHandleError(tickError);
1124
+ if (!suppress) throw e;
1125
+ } finally {
1126
+ if (tickError === void 0) await loop.finishAndHandleError();
1127
+ }
1128
+ }
1129
+ async clearCache() {
1130
+ await this.cache?.clear([]);
1131
+ }
1132
+ };
1133
+
1134
+ //#endregion
1135
+ exports.Channel = Channel;
1606
1136
  exports.Pregel = Pregel;
1607
- //# sourceMappingURL=index.js.map
1137
+ //# sourceMappingURL=index.cjs.map