@langchain/langgraph 0.4.9 → 1.0.0-alpha.1

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 (505) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +1 -2
  3. package/dist/_virtual/rolldown_runtime.cjs +25 -0
  4. package/dist/channels/any_value.cjs +44 -63
  5. package/dist/channels/any_value.cjs.map +1 -0
  6. package/dist/channels/any_value.d.cts +24 -0
  7. package/dist/channels/any_value.d.cts.map +1 -0
  8. package/dist/channels/any_value.d.ts +16 -11
  9. package/dist/channels/any_value.d.ts.map +1 -0
  10. package/dist/channels/any_value.js +42 -57
  11. package/dist/channels/any_value.js.map +1 -1
  12. package/dist/channels/base.cjs +93 -133
  13. package/dist/channels/base.cjs.map +1 -0
  14. package/dist/channels/base.d.cts +79 -0
  15. package/dist/channels/base.d.cts.map +1 -0
  16. package/dist/channels/base.d.ts +77 -73
  17. package/dist/channels/base.d.ts.map +1 -0
  18. package/dist/channels/base.js +90 -127
  19. package/dist/channels/base.js.map +1 -1
  20. package/dist/channels/binop.cjs +47 -77
  21. package/dist/channels/binop.cjs.map +1 -0
  22. package/dist/channels/binop.d.cts +22 -0
  23. package/dist/channels/binop.d.cts.map +1 -0
  24. package/dist/channels/binop.d.ts +17 -12
  25. package/dist/channels/binop.d.ts.map +1 -0
  26. package/dist/channels/binop.js +45 -71
  27. package/dist/channels/binop.js.map +1 -1
  28. package/dist/channels/dynamic_barrier_value.cjs +72 -208
  29. package/dist/channels/dynamic_barrier_value.cjs.map +1 -0
  30. package/dist/channels/dynamic_barrier_value.d.cts +42 -0
  31. package/dist/channels/dynamic_barrier_value.d.cts.map +1 -0
  32. package/dist/channels/dynamic_barrier_value.d.ts +20 -35
  33. package/dist/channels/dynamic_barrier_value.d.ts.map +1 -0
  34. package/dist/channels/dynamic_barrier_value.js +69 -200
  35. package/dist/channels/dynamic_barrier_value.js.map +1 -1
  36. package/dist/channels/ephemeral_value.cjs +44 -70
  37. package/dist/channels/ephemeral_value.cjs.map +1 -0
  38. package/dist/channels/ephemeral_value.d.cts +22 -0
  39. package/dist/channels/ephemeral_value.d.cts.map +1 -0
  40. package/dist/channels/ephemeral_value.d.ts +18 -12
  41. package/dist/channels/ephemeral_value.d.ts.map +1 -0
  42. package/dist/channels/ephemeral_value.js +43 -65
  43. package/dist/channels/ephemeral_value.js.map +1 -1
  44. package/dist/channels/index.cjs +21 -10
  45. package/dist/channels/index.d.cts +9 -0
  46. package/dist/channels/index.d.ts +9 -7
  47. package/dist/channels/index.js +10 -3
  48. package/dist/channels/last_value.cjs +90 -140
  49. package/dist/channels/last_value.cjs.map +1 -0
  50. package/dist/channels/last_value.d.cts +42 -0
  51. package/dist/channels/last_value.d.cts.map +1 -0
  52. package/dist/channels/last_value.d.ts +27 -23
  53. package/dist/channels/last_value.d.ts.map +1 -0
  54. package/dist/channels/last_value.js +87 -133
  55. package/dist/channels/last_value.js.map +1 -1
  56. package/dist/channels/named_barrier_value.cjs +114 -170
  57. package/dist/channels/named_barrier_value.cjs.map +1 -0
  58. package/dist/channels/named_barrier_value.d.cts +46 -0
  59. package/dist/channels/named_barrier_value.d.cts.map +1 -0
  60. package/dist/channels/named_barrier_value.d.ts +32 -29
  61. package/dist/channels/named_barrier_value.d.ts.map +1 -0
  62. package/dist/channels/named_barrier_value.js +111 -163
  63. package/dist/channels/named_barrier_value.js.map +1 -1
  64. package/dist/channels/topic.cjs +63 -96
  65. package/dist/channels/topic.cjs.map +1 -0
  66. package/dist/channels/topic.d.cts +32 -0
  67. package/dist/channels/topic.d.cts.map +1 -0
  68. package/dist/channels/topic.d.ts +28 -19
  69. package/dist/channels/topic.d.ts.map +1 -0
  70. package/dist/channels/topic.js +61 -90
  71. package/dist/channels/topic.js.map +1 -1
  72. package/dist/constants.cjs +376 -452
  73. package/dist/constants.cjs.map +1 -0
  74. package/dist/constants.d.cts +285 -0
  75. package/dist/constants.d.cts.map +1 -0
  76. package/dist/constants.d.ts +113 -148
  77. package/dist/constants.d.ts.map +1 -0
  78. package/dist/constants.js +336 -444
  79. package/dist/constants.js.map +1 -1
  80. package/dist/errors.cjs +151 -179
  81. package/dist/errors.cjs.map +1 -0
  82. package/dist/errors.d.cts +81 -0
  83. package/dist/errors.d.cts.map +1 -0
  84. package/dist/errors.d.ts +56 -46
  85. package/dist/errors.d.ts.map +1 -0
  86. package/dist/errors.js +140 -165
  87. package/dist/errors.js.map +1 -1
  88. package/dist/func/index.cjs +292 -290
  89. package/dist/func/index.cjs.map +1 -0
  90. package/dist/func/index.d.cts +293 -0
  91. package/dist/func/index.d.cts.map +1 -0
  92. package/dist/func/index.d.ts +86 -72
  93. package/dist/func/index.d.ts.map +1 -0
  94. package/dist/func/index.js +288 -284
  95. package/dist/func/index.js.map +1 -1
  96. package/dist/func/types.d.cts +64 -0
  97. package/dist/func/types.d.cts.map +1 -0
  98. package/dist/func/types.d.ts +24 -19
  99. package/dist/func/types.d.ts.map +1 -0
  100. package/dist/graph/annotation.cjs +96 -120
  101. package/dist/graph/annotation.cjs.map +1 -0
  102. package/dist/graph/annotation.d.cts +116 -0
  103. package/dist/graph/annotation.d.cts.map +1 -0
  104. package/dist/graph/annotation.d.ts +33 -34
  105. package/dist/graph/annotation.d.ts.map +1 -0
  106. package/dist/graph/annotation.js +91 -112
  107. package/dist/graph/annotation.js.map +1 -1
  108. package/dist/graph/graph.cjs +419 -723
  109. package/dist/graph/graph.cjs.map +1 -0
  110. package/dist/graph/graph.d.cts +133 -0
  111. package/dist/graph/graph.d.cts.map +1 -0
  112. package/dist/graph/graph.d.ts +124 -91
  113. package/dist/graph/graph.d.ts.map +1 -0
  114. package/dist/graph/graph.js +412 -713
  115. package/dist/graph/graph.js.map +1 -1
  116. package/dist/graph/index.cjs +4 -17
  117. package/dist/graph/index.js +6 -5
  118. package/dist/graph/message.cjs +59 -104
  119. package/dist/graph/message.cjs.map +1 -0
  120. package/dist/graph/message.d.cts +19 -0
  121. package/dist/graph/message.d.cts.map +1 -0
  122. package/dist/graph/message.d.ts +11 -10
  123. package/dist/graph/message.d.ts.map +1 -0
  124. package/dist/graph/message.js +56 -98
  125. package/dist/graph/message.js.map +1 -1
  126. package/dist/graph/messages_annotation.cjs +106 -106
  127. package/dist/graph/messages_annotation.cjs.map +1 -0
  128. package/dist/graph/messages_annotation.d.cts +111 -0
  129. package/dist/graph/messages_annotation.d.cts.map +1 -0
  130. package/dist/graph/messages_annotation.d.ts +18 -9
  131. package/dist/graph/messages_annotation.d.ts.map +1 -0
  132. package/dist/graph/messages_annotation.js +100 -100
  133. package/dist/graph/messages_annotation.js.map +1 -1
  134. package/dist/graph/state.cjs +475 -779
  135. package/dist/graph/state.cjs.map +1 -0
  136. package/dist/graph/state.d.cts +231 -0
  137. package/dist/graph/state.d.cts.map +1 -0
  138. package/dist/graph/state.d.ts +148 -138
  139. package/dist/graph/state.d.ts.map +1 -0
  140. package/dist/graph/state.js +469 -769
  141. package/dist/graph/state.js.map +1 -1
  142. package/dist/graph/zod/index.cjs +10 -21
  143. package/dist/graph/zod/index.d.cts +3 -0
  144. package/dist/graph/zod/index.d.ts +3 -3
  145. package/dist/graph/zod/index.js +4 -4
  146. package/dist/graph/zod/meta.cjs +142 -177
  147. package/dist/graph/zod/meta.cjs.map +1 -0
  148. package/dist/graph/zod/meta.d.cts +116 -0
  149. package/dist/graph/zod/meta.d.cts.map +1 -0
  150. package/dist/graph/zod/meta.d.ts +99 -97
  151. package/dist/graph/zod/meta.d.ts.map +1 -0
  152. package/dist/graph/zod/meta.js +136 -170
  153. package/dist/graph/zod/meta.js.map +1 -1
  154. package/dist/graph/zod/plugin.cjs +36 -39
  155. package/dist/graph/zod/plugin.cjs.map +1 -0
  156. package/dist/graph/zod/plugin.js +34 -35
  157. package/dist/graph/zod/plugin.js.map +1 -1
  158. package/dist/graph/zod/schema.cjs +82 -110
  159. package/dist/graph/zod/schema.cjs.map +1 -0
  160. package/dist/graph/zod/schema.d.cts +38 -0
  161. package/dist/graph/zod/schema.d.cts.map +1 -0
  162. package/dist/graph/zod/schema.d.ts +12 -6
  163. package/dist/graph/zod/schema.d.ts.map +1 -0
  164. package/dist/graph/zod/schema.js +77 -103
  165. package/dist/graph/zod/schema.js.map +1 -1
  166. package/dist/graph/zod/zod-registry.cjs +41 -47
  167. package/dist/graph/zod/zod-registry.cjs.map +1 -0
  168. package/dist/graph/zod/zod-registry.d.cts +51 -0
  169. package/dist/graph/zod/zod-registry.d.cts.map +1 -0
  170. package/dist/graph/zod/zod-registry.d.ts +34 -26
  171. package/dist/graph/zod/zod-registry.d.ts.map +1 -0
  172. package/dist/graph/zod/zod-registry.js +37 -41
  173. package/dist/graph/zod/zod-registry.js.map +1 -1
  174. package/dist/hash.cjs +205 -267
  175. package/dist/hash.cjs.map +1 -0
  176. package/dist/hash.js +205 -265
  177. package/dist/hash.js.map +1 -1
  178. package/dist/index.cjs +111 -33
  179. package/dist/index.cjs.map +1 -0
  180. package/dist/index.d.cts +26 -0
  181. package/dist/index.d.ts +26 -5
  182. package/dist/index.js +19 -7
  183. package/dist/index.js.map +1 -1
  184. package/dist/interrupt.cjs +79 -85
  185. package/dist/interrupt.cjs.map +1 -0
  186. package/dist/interrupt.d.cts +49 -0
  187. package/dist/interrupt.d.cts.map +1 -0
  188. package/dist/interrupt.d.ts +6 -1
  189. package/dist/interrupt.d.ts.map +1 -0
  190. package/dist/interrupt.js +76 -80
  191. package/dist/interrupt.js.map +1 -1
  192. package/dist/prebuilt/agentName.cjs +139 -172
  193. package/dist/prebuilt/agentName.cjs.map +1 -0
  194. package/dist/prebuilt/agentName.d.cts +42 -0
  195. package/dist/prebuilt/agentName.d.cts.map +1 -0
  196. package/dist/prebuilt/agentName.d.ts +13 -21
  197. package/dist/prebuilt/agentName.d.ts.map +1 -0
  198. package/dist/prebuilt/agentName.js +139 -168
  199. package/dist/prebuilt/agentName.js.map +1 -1
  200. package/dist/prebuilt/agent_executor.cjs +42 -80
  201. package/dist/prebuilt/agent_executor.cjs.map +1 -0
  202. package/dist/prebuilt/agent_executor.d.cts +57 -0
  203. package/dist/prebuilt/agent_executor.d.cts.map +1 -0
  204. package/dist/prebuilt/agent_executor.d.ts +47 -38
  205. package/dist/prebuilt/agent_executor.d.ts.map +1 -0
  206. package/dist/prebuilt/agent_executor.js +40 -75
  207. package/dist/prebuilt/agent_executor.js.map +1 -1
  208. package/dist/prebuilt/chat_agent_executor.cjs +66 -128
  209. package/dist/prebuilt/chat_agent_executor.cjs.map +1 -0
  210. package/dist/prebuilt/chat_agent_executor.d.cts +23 -0
  211. package/dist/prebuilt/chat_agent_executor.d.cts.map +1 -0
  212. package/dist/prebuilt/chat_agent_executor.d.ts +18 -10
  213. package/dist/prebuilt/chat_agent_executor.d.ts.map +1 -0
  214. package/dist/prebuilt/chat_agent_executor.js +63 -123
  215. package/dist/prebuilt/chat_agent_executor.js.map +1 -1
  216. package/dist/prebuilt/index.cjs +15 -18
  217. package/dist/prebuilt/index.d.cts +8 -0
  218. package/dist/prebuilt/index.d.ts +8 -8
  219. package/dist/prebuilt/index.js +8 -7
  220. package/dist/prebuilt/interrupt.d.cts +73 -0
  221. package/dist/prebuilt/interrupt.d.cts.map +1 -0
  222. package/dist/prebuilt/interrupt.d.ts +32 -15
  223. package/dist/prebuilt/interrupt.d.ts.map +1 -0
  224. package/dist/prebuilt/react_agent_executor.cjs +317 -473
  225. package/dist/prebuilt/react_agent_executor.cjs.map +1 -0
  226. package/dist/prebuilt/react_agent_executor.d.cts +229 -0
  227. package/dist/prebuilt/react_agent_executor.d.cts.map +1 -0
  228. package/dist/prebuilt/react_agent_executor.d.ts +171 -143
  229. package/dist/prebuilt/react_agent_executor.d.ts.map +1 -0
  230. package/dist/prebuilt/react_agent_executor.js +315 -465
  231. package/dist/prebuilt/react_agent_executor.js.map +1 -1
  232. package/dist/prebuilt/tool_executor.cjs +45 -67
  233. package/dist/prebuilt/tool_executor.cjs.map +1 -0
  234. package/dist/prebuilt/tool_executor.d.cts +42 -0
  235. package/dist/prebuilt/tool_executor.d.cts.map +1 -0
  236. package/dist/prebuilt/tool_executor.d.ts +30 -24
  237. package/dist/prebuilt/tool_executor.d.ts.map +1 -0
  238. package/dist/prebuilt/tool_executor.js +44 -63
  239. package/dist/prebuilt/tool_executor.js.map +1 -1
  240. package/dist/prebuilt/tool_node.cjs +213 -275
  241. package/dist/prebuilt/tool_node.cjs.map +1 -0
  242. package/dist/prebuilt/tool_node.d.cts +151 -0
  243. package/dist/prebuilt/tool_node.d.cts.map +1 -0
  244. package/dist/prebuilt/tool_node.d.ts +30 -17
  245. package/dist/prebuilt/tool_node.d.ts.map +1 -0
  246. package/dist/prebuilt/tool_node.js +209 -268
  247. package/dist/prebuilt/tool_node.js.map +1 -1
  248. package/dist/pregel/algo.cjs +551 -692
  249. package/dist/pregel/algo.cjs.map +1 -0
  250. package/dist/pregel/algo.d.cts +13 -0
  251. package/dist/pregel/algo.d.cts.map +1 -0
  252. package/dist/pregel/algo.d.ts +8 -38
  253. package/dist/pregel/algo.d.ts.map +1 -0
  254. package/dist/pregel/algo.js +546 -683
  255. package/dist/pregel/algo.js.map +1 -1
  256. package/dist/pregel/call.cjs +46 -42
  257. package/dist/pregel/call.cjs.map +1 -0
  258. package/dist/pregel/call.js +43 -37
  259. package/dist/pregel/call.js.map +1 -1
  260. package/dist/pregel/debug.cjs +153 -223
  261. package/dist/pregel/debug.cjs.map +1 -0
  262. package/dist/pregel/debug.js +152 -215
  263. package/dist/pregel/debug.js.map +1 -1
  264. package/dist/pregel/index.cjs +1138 -1604
  265. package/dist/pregel/index.cjs.map +1 -0
  266. package/dist/pregel/index.d.cts +536 -0
  267. package/dist/pregel/index.d.cts.map +1 -0
  268. package/dist/pregel/index.d.ts +460 -422
  269. package/dist/pregel/index.d.ts.map +1 -0
  270. package/dist/pregel/index.js +1129 -1592
  271. package/dist/pregel/index.js.map +1 -1
  272. package/dist/pregel/io.cjs +127 -234
  273. package/dist/pregel/io.cjs.map +1 -0
  274. package/dist/pregel/io.js +122 -225
  275. package/dist/pregel/io.js.map +1 -1
  276. package/dist/pregel/loop.cjs +542 -954
  277. package/dist/pregel/loop.cjs.map +1 -0
  278. package/dist/pregel/loop.js +539 -948
  279. package/dist/pregel/loop.js.map +1 -1
  280. package/dist/pregel/messages.cjs +104 -196
  281. package/dist/pregel/messages.cjs.map +1 -0
  282. package/dist/pregel/messages.js +102 -191
  283. package/dist/pregel/messages.js.map +1 -1
  284. package/dist/pregel/read.cjs +150 -280
  285. package/dist/pregel/read.cjs.map +1 -0
  286. package/dist/pregel/read.d.cts +51 -0
  287. package/dist/pregel/read.d.cts.map +1 -0
  288. package/dist/pregel/read.d.ts +48 -46
  289. package/dist/pregel/read.d.ts.map +1 -0
  290. package/dist/pregel/read.js +147 -274
  291. package/dist/pregel/read.js.map +1 -1
  292. package/dist/pregel/remote.cjs +339 -458
  293. package/dist/pregel/remote.cjs.map +1 -0
  294. package/dist/pregel/remote.d.cts +121 -0
  295. package/dist/pregel/remote.d.cts.map +1 -0
  296. package/dist/pregel/remote.d.ts +79 -69
  297. package/dist/pregel/remote.d.ts.map +1 -0
  298. package/dist/pregel/remote.js +337 -453
  299. package/dist/pregel/remote.js.map +1 -1
  300. package/dist/pregel/retry.cjs +87 -138
  301. package/dist/pregel/retry.cjs.map +1 -0
  302. package/dist/pregel/retry.js +83 -130
  303. package/dist/pregel/retry.js.map +1 -1
  304. package/dist/pregel/runnable_types.d.cts +49 -0
  305. package/dist/pregel/runnable_types.d.cts.map +1 -0
  306. package/dist/pregel/runnable_types.d.ts +47 -17
  307. package/dist/pregel/runnable_types.d.ts.map +1 -0
  308. package/dist/pregel/runner.cjs +222 -315
  309. package/dist/pregel/runner.cjs.map +1 -0
  310. package/dist/pregel/runner.js +219 -308
  311. package/dist/pregel/runner.js.map +1 -1
  312. package/dist/pregel/stream.cjs +89 -130
  313. package/dist/pregel/stream.cjs.map +1 -0
  314. package/dist/pregel/stream.js +87 -125
  315. package/dist/pregel/stream.js.map +1 -1
  316. package/dist/pregel/types.cjs +25 -62
  317. package/dist/pregel/types.cjs.map +1 -0
  318. package/dist/pregel/types.d.cts +440 -0
  319. package/dist/pregel/types.d.cts.map +1 -0
  320. package/dist/pregel/types.d.ts +381 -432
  321. package/dist/pregel/types.d.ts.map +1 -0
  322. package/dist/pregel/types.js +23 -57
  323. package/dist/pregel/types.js.map +1 -1
  324. package/dist/pregel/utils/config.cjs +101 -147
  325. package/dist/pregel/utils/config.cjs.map +1 -0
  326. package/dist/pregel/utils/config.d.cts +36 -0
  327. package/dist/pregel/utils/config.d.cts.map +1 -0
  328. package/dist/pregel/utils/config.d.ts +12 -9
  329. package/dist/pregel/utils/config.d.ts.map +1 -0
  330. package/dist/pregel/utils/config.js +99 -143
  331. package/dist/pregel/utils/config.js.map +1 -1
  332. package/dist/pregel/utils/index.cjs +87 -125
  333. package/dist/pregel/utils/index.cjs.map +1 -0
  334. package/dist/pregel/utils/index.d.cts +51 -0
  335. package/dist/pregel/utils/index.d.cts.map +1 -0
  336. package/dist/pregel/utils/index.d.ts +45 -61
  337. package/dist/pregel/utils/index.d.ts.map +1 -0
  338. package/dist/pregel/utils/index.js +86 -120
  339. package/dist/pregel/utils/index.js.map +1 -1
  340. package/dist/pregel/utils/subgraph.cjs +15 -26
  341. package/dist/pregel/utils/subgraph.cjs.map +1 -0
  342. package/dist/pregel/utils/subgraph.js +12 -21
  343. package/dist/pregel/utils/subgraph.js.map +1 -1
  344. package/dist/pregel/validate.cjs +42 -92
  345. package/dist/pregel/validate.cjs.map +1 -0
  346. package/dist/pregel/validate.js +39 -84
  347. package/dist/pregel/validate.js.map +1 -1
  348. package/dist/pregel/write.cjs +87 -137
  349. package/dist/pregel/write.cjs.map +1 -0
  350. package/dist/pregel/write.d.cts +35 -0
  351. package/dist/pregel/write.d.cts.map +1 -0
  352. package/dist/pregel/write.d.ts +27 -23
  353. package/dist/pregel/write.d.ts.map +1 -0
  354. package/dist/pregel/write.js +83 -131
  355. package/dist/pregel/write.js.map +1 -1
  356. package/dist/remote.cjs +3 -6
  357. package/dist/remote.d.cts +2 -0
  358. package/dist/remote.d.ts +2 -1
  359. package/dist/remote.js +3 -2
  360. package/dist/setup/async_local_storage.cjs +10 -7
  361. package/dist/setup/async_local_storage.cjs.map +1 -0
  362. package/dist/setup/async_local_storage.js +7 -2
  363. package/dist/setup/async_local_storage.js.map +1 -1
  364. package/dist/ui/index.cjs +4 -0
  365. package/dist/ui/index.d.cts +5 -0
  366. package/dist/ui/index.d.ts +5 -0
  367. package/dist/ui/index.js +3 -0
  368. package/dist/ui/stream.cjs +145 -0
  369. package/dist/ui/stream.cjs.map +1 -0
  370. package/dist/ui/stream.d.cts +25 -0
  371. package/dist/ui/stream.d.cts.map +1 -0
  372. package/dist/ui/stream.d.ts +25 -0
  373. package/dist/ui/stream.d.ts.map +1 -0
  374. package/dist/ui/stream.js +143 -0
  375. package/dist/ui/stream.js.map +1 -0
  376. package/dist/ui/types.infer.d.cts +53 -0
  377. package/dist/ui/types.infer.d.cts.map +1 -0
  378. package/dist/ui/types.infer.d.ts +53 -0
  379. package/dist/ui/types.infer.d.ts.map +1 -0
  380. package/dist/ui/types.message.d.cts +95 -0
  381. package/dist/ui/types.message.d.cts.map +1 -0
  382. package/dist/ui/types.message.d.ts +95 -0
  383. package/dist/ui/types.message.d.ts.map +1 -0
  384. package/dist/ui/types.schema.d.cts +228 -0
  385. package/dist/ui/types.schema.d.cts.map +1 -0
  386. package/dist/ui/types.schema.d.ts +228 -0
  387. package/dist/ui/types.schema.d.ts.map +1 -0
  388. package/dist/utils.cjs +77 -147
  389. package/dist/utils.cjs.map +1 -0
  390. package/dist/utils.d.cts +32 -0
  391. package/dist/utils.d.cts.map +1 -0
  392. package/dist/utils.d.ts +29 -25
  393. package/dist/utils.d.ts.map +1 -0
  394. package/dist/utils.js +73 -140
  395. package/dist/utils.js.map +1 -1
  396. package/dist/web.cjs +96 -55
  397. package/dist/web.d.cts +23 -0
  398. package/dist/web.d.ts +23 -14
  399. package/dist/web.js +15 -8
  400. package/dist/writer.cjs +15 -0
  401. package/dist/writer.cjs.map +1 -0
  402. package/dist/writer.d.cts +5 -0
  403. package/dist/writer.d.cts.map +1 -0
  404. package/dist/writer.d.ts +5 -0
  405. package/dist/writer.d.ts.map +1 -0
  406. package/dist/writer.js +14 -0
  407. package/dist/writer.js.map +1 -0
  408. package/package.json +90 -83
  409. package/dist/channels/index.js.map +0 -1
  410. package/dist/func/types.cjs +0 -15
  411. package/dist/func/types.js +0 -12
  412. package/dist/func/types.js.map +0 -1
  413. package/dist/graph/index.d.ts +0 -4
  414. package/dist/graph/index.js.map +0 -1
  415. package/dist/graph/message.test.cjs +0 -196
  416. package/dist/graph/message.test.d.ts +0 -1
  417. package/dist/graph/message.test.js +0 -194
  418. package/dist/graph/message.test.js.map +0 -1
  419. package/dist/graph/zod/index.js.map +0 -1
  420. package/dist/graph/zod/plugin.d.ts +0 -28
  421. package/dist/hash.d.ts +0 -2
  422. package/dist/prebuilt/index.js.map +0 -1
  423. package/dist/prebuilt/interrupt.cjs +0 -3
  424. package/dist/prebuilt/interrupt.js +0 -2
  425. package/dist/prebuilt/interrupt.js.map +0 -1
  426. package/dist/pregel/call.d.ts +0 -16
  427. package/dist/pregel/debug.d.ts +0 -41
  428. package/dist/pregel/debug.test.cjs +0 -258
  429. package/dist/pregel/debug.test.d.ts +0 -1
  430. package/dist/pregel/debug.test.js +0 -256
  431. package/dist/pregel/debug.test.js.map +0 -1
  432. package/dist/pregel/io.d.ts +0 -30
  433. package/dist/pregel/io.mapCommand.test.cjs +0 -150
  434. package/dist/pregel/io.mapCommand.test.d.ts +0 -1
  435. package/dist/pregel/io.mapCommand.test.js +0 -148
  436. package/dist/pregel/io.mapCommand.test.js.map +0 -1
  437. package/dist/pregel/loop.d.ts +0 -147
  438. package/dist/pregel/messages.d.ts +0 -30
  439. package/dist/pregel/messages.test.cjs +0 -369
  440. package/dist/pregel/messages.test.d.ts +0 -1
  441. package/dist/pregel/messages.test.js +0 -367
  442. package/dist/pregel/messages.test.js.map +0 -1
  443. package/dist/pregel/read.test.cjs +0 -194
  444. package/dist/pregel/read.test.d.ts +0 -1
  445. package/dist/pregel/read.test.js +0 -192
  446. package/dist/pregel/read.test.js.map +0 -1
  447. package/dist/pregel/retry.d.ts +0 -17
  448. package/dist/pregel/runnable_types.cjs +0 -3
  449. package/dist/pregel/runnable_types.js +0 -2
  450. package/dist/pregel/runnable_types.js.map +0 -1
  451. package/dist/pregel/runner.d.ts +0 -79
  452. package/dist/pregel/runner.test.cjs +0 -66
  453. package/dist/pregel/runner.test.d.ts +0 -1
  454. package/dist/pregel/runner.test.js +0 -64
  455. package/dist/pregel/runner.test.js.map +0 -1
  456. package/dist/pregel/stream.d.ts +0 -40
  457. package/dist/pregel/utils/config.test.cjs +0 -214
  458. package/dist/pregel/utils/config.test.d.ts +0 -1
  459. package/dist/pregel/utils/config.test.js +0 -212
  460. package/dist/pregel/utils/config.test.js.map +0 -1
  461. package/dist/pregel/utils/subgraph.d.ts +0 -4
  462. package/dist/pregel/utils/subgraph.test.cjs +0 -83
  463. package/dist/pregel/utils/subgraph.test.d.ts +0 -1
  464. package/dist/pregel/utils/subgraph.test.js +0 -81
  465. package/dist/pregel/utils/subgraph.test.js.map +0 -1
  466. package/dist/pregel/validate.d.ts +0 -16
  467. package/dist/pregel/validate.test.cjs +0 -220
  468. package/dist/pregel/validate.test.d.ts +0 -1
  469. package/dist/pregel/validate.test.js +0 -218
  470. package/dist/pregel/validate.test.js.map +0 -1
  471. package/dist/pregel/write.test.cjs +0 -181
  472. package/dist/pregel/write.test.d.ts +0 -1
  473. package/dist/pregel/write.test.js +0 -179
  474. package/dist/pregel/write.test.js.map +0 -1
  475. package/dist/remote.js.map +0 -1
  476. package/dist/setup/async_local_storage.d.ts +0 -1
  477. package/dist/web.js.map +0 -1
  478. package/index.cjs +0 -1
  479. package/index.d.cts +0 -1
  480. package/index.d.ts +0 -1
  481. package/index.js +0 -1
  482. package/prebuilt.cjs +0 -1
  483. package/prebuilt.d.cts +0 -1
  484. package/prebuilt.d.ts +0 -1
  485. package/prebuilt.js +0 -1
  486. package/pregel.cjs +0 -1
  487. package/pregel.d.cts +0 -1
  488. package/pregel.d.ts +0 -1
  489. package/pregel.js +0 -1
  490. package/remote.cjs +0 -1
  491. package/remote.d.cts +0 -1
  492. package/remote.d.ts +0 -1
  493. package/remote.js +0 -1
  494. package/web.cjs +0 -1
  495. package/web.d.cts +0 -1
  496. package/web.d.ts +0 -1
  497. package/web.js +0 -1
  498. package/zod/schema.cjs +0 -1
  499. package/zod/schema.d.cts +0 -1
  500. package/zod/schema.d.ts +0 -1
  501. package/zod/schema.js +0 -1
  502. package/zod.cjs +0 -1
  503. package/zod.d.cts +0 -1
  504. package/zod.d.ts +0 -1
  505. package/zod.js +0 -1
@@ -1,1607 +1,1141 @@
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 require_interrupt = require('../interrupt.cjs');
21
+ const __langchain_langgraph_checkpoint = require_rolldown_runtime.__toESM(require("@langchain/langgraph-checkpoint"));
22
+ const __langchain_core_runnables = require_rolldown_runtime.__toESM(require("@langchain/core/runnables"));
23
+
24
+ //#region src/pregel/index.ts
25
25
  /**
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
- }
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
+ var Channel = class {
33
+ static subscribeTo(channels, options) {
34
+ const { key, tags } = {
35
+ key: void 0,
36
+ tags: void 0,
37
+ ...options ?? {}
38
+ };
39
+ if (Array.isArray(channels) && key !== void 0) throw new Error("Can't specify a key when subscribing to multiple channels");
40
+ let channelMappingOrArray;
41
+ if (typeof channels === "string") if (key) channelMappingOrArray = { [key]: channels };
42
+ else channelMappingOrArray = [channels];
43
+ else channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan]));
44
+ const triggers = Array.isArray(channels) ? channels : [channels];
45
+ return new require_read.PregelNode({
46
+ channels: channelMappingOrArray,
47
+ triggers,
48
+ tags
49
+ });
50
+ }
51
+ /**
52
+ * Creates a ChannelWrite that specifies how to write values to channels.
53
+ * This is used to define how nodes send output to channels.
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * // Write to multiple channels
58
+ * const write = Channel.writeTo(["output", "state"]);
59
+ *
60
+ * // Write with specific values
61
+ * const write = Channel.writeTo(["output"], {
62
+ * state: "completed",
63
+ * result: calculateResult()
64
+ * });
65
+ *
66
+ * // Write with a transformation function
67
+ * const write = Channel.writeTo(["output"], {
68
+ * result: (x) => processResult(x)
69
+ * });
70
+ * ```
71
+ *
72
+ * @param channels - Array of channel names to write to
73
+ * @param writes - Optional map of channel names to values or transformations
74
+ * @returns A ChannelWrite object that can be used to write to the specified channels
75
+ */
76
+ static writeTo(channels, writes) {
77
+ const channelWriteEntries = [];
78
+ for (const channel of channels) channelWriteEntries.push({
79
+ channel,
80
+ value: require_write.PASSTHROUGH,
81
+ skipNone: false
82
+ });
83
+ for (const [key, value] of Object.entries(writes ?? {})) if (__langchain_core_runnables.Runnable.isRunnable(value) || typeof value === "function") channelWriteEntries.push({
84
+ channel: key,
85
+ value: require_write.PASSTHROUGH,
86
+ skipNone: true,
87
+ mapper: (0, __langchain_core_runnables._coerceToRunnable)(value)
88
+ });
89
+ else channelWriteEntries.push({
90
+ channel: key,
91
+ value,
92
+ skipNone: false
93
+ });
94
+ return new require_write.ChannelWrite(channelWriteEntries);
95
+ }
96
+ };
97
+ var PartialRunnable = class extends __langchain_core_runnables.Runnable {
98
+ lc_namespace = ["langgraph", "pregel"];
99
+ invoke(_input, _options) {
100
+ throw new Error("Not implemented");
101
+ }
102
+ withConfig(_config) {
103
+ return super.withConfig(_config);
104
+ }
105
+ stream(input, options) {
106
+ return super.stream(input, options);
107
+ }
108
+ };
146
109
  /**
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
- }
110
+ * The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model
111
+ * inspired by [Google's Pregel system](https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/).
112
+ * It provides the foundation for building reliable, controllable agent workflows that can evolve state over time.
113
+ *
114
+ * Key features:
115
+ * - Message passing between nodes in discrete "supersteps"
116
+ * - Built-in persistence layer through checkpointers
117
+ * - First-class streaming support for values, updates, and events
118
+ * - Human-in-the-loop capabilities via interrupts
119
+ * - Support for parallel node execution within supersteps
120
+ *
121
+ * The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs:
122
+ * - {@link StateGraph}: The main graph class for building agent workflows
123
+ * - Compiling a {@link StateGraph} will return a {@link CompiledGraph} instance, which extends `Pregel`
124
+ * - Functional API: A declarative approach using tasks and entrypoints
125
+ * - A `Pregel` instance is returned by the {@link entrypoint} function
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * // Using StateGraph API
130
+ * const graph = new StateGraph(annotation)
131
+ * .addNode("nodeA", myNodeFunction)
132
+ * .addEdge("nodeA", "nodeB")
133
+ * .compile();
134
+ *
135
+ * // The compiled graph is a Pregel instance
136
+ * const result = await graph.invoke(input);
137
+ * ```
138
+ *
139
+ * @example
140
+ * ```typescript
141
+ * // Using Functional API
142
+ * import { task, entrypoint } from "@langchain/langgraph";
143
+ * import { MemorySaver } from "@langchain/langgraph-checkpoint";
144
+ *
145
+ * // Define tasks that can be composed
146
+ * const addOne = task("add", async (x: number) => x + 1);
147
+ *
148
+ * // Create a workflow using the entrypoint function
149
+ * const workflow = entrypoint({
150
+ * name: "workflow",
151
+ * checkpointer: new MemorySaver()
152
+ * }, async (numbers: number[]) => {
153
+ * // Tasks can be run in parallel
154
+ * const results = await Promise.all(numbers.map(n => addOne(n)));
155
+ * return results;
156
+ * });
157
+ *
158
+ * // The workflow is a Pregel instance
159
+ * const result = await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]
160
+ * ```
161
+ *
162
+ * @typeParam Nodes - Mapping of node names to their {@link PregelNode} implementations
163
+ * @typeParam Channels - Mapping of channel names to their {@link BaseChannel} or {@link ManagedValueSpec} implementations
164
+ * @typeParam ContextType - Type of context that can be passed to the graph
165
+ * @typeParam InputType - Type of input values accepted by the graph
166
+ * @typeParam OutputType - Type of output values produced by the graph
167
+ */
168
+ var Pregel = class extends PartialRunnable {
169
+ /**
170
+ * Name of the class when serialized
171
+ * @internal
172
+ */
173
+ static lc_name() {
174
+ return "LangGraph";
175
+ }
176
+ /** @internal LangChain namespace for serialization necessary because Pregel extends Runnable */
177
+ lc_namespace = ["langgraph", "pregel"];
178
+ /** @internal Flag indicating this is a Pregel instance - necessary for serialization */
179
+ lg_is_pregel = true;
180
+ /** The nodes in the graph, mapping node names to their PregelNode instances */
181
+ nodes;
182
+ /** The channels in the graph, mapping channel names to their BaseChannel or ManagedValueSpec instances */
183
+ channels;
184
+ /**
185
+ * The input channels for the graph. These channels receive the initial input when the graph is invoked.
186
+ * Can be a single channel key or an array of channel keys.
187
+ */
188
+ inputChannels;
189
+ /**
190
+ * The output channels for the graph. These channels contain the final output when the graph completes.
191
+ * Can be a single channel key or an array of channel keys.
192
+ */
193
+ outputChannels;
194
+ /** Whether to automatically validate the graph structure when it is compiled. Defaults to true. */
195
+ autoValidate = true;
196
+ /**
197
+ * The streaming modes enabled for this graph. Defaults to ["values"].
198
+ * Supported modes:
199
+ * - "values": Streams the full state after each step
200
+ * - "updates": Streams state updates after each step
201
+ * - "messages": Streams messages from within nodes
202
+ * - "custom": Streams custom events from within nodes
203
+ * - "debug": Streams events related to the execution of the graph - useful for tracing & debugging graph execution
204
+ */
205
+ streamMode = ["values"];
206
+ /**
207
+ * Optional channels to stream. If not specified, all channels will be streamed.
208
+ * Can be a single channel key or an array of channel keys.
209
+ */
210
+ streamChannels;
211
+ /**
212
+ * Optional array of node names or "all" to interrupt after executing these nodes.
213
+ * Used for implementing human-in-the-loop workflows.
214
+ */
215
+ interruptAfter;
216
+ /**
217
+ * Optional array of node names or "all" to interrupt before executing these nodes.
218
+ * Used for implementing human-in-the-loop workflows.
219
+ */
220
+ interruptBefore;
221
+ /** Optional timeout in milliseconds for the execution of each superstep */
222
+ stepTimeout;
223
+ /** Whether to enable debug logging. Defaults to false. */
224
+ debug = false;
225
+ /**
226
+ * Optional checkpointer for persisting graph state.
227
+ * When provided, saves a checkpoint of the graph state at every superstep.
228
+ * When false or undefined, checkpointing is disabled, and the graph will not be able to save or restore state.
229
+ */
230
+ checkpointer;
231
+ /** Optional retry policy for handling failures in node execution */
232
+ retryPolicy;
233
+ /** The default configuration for graph execution, can be overridden on a per-invocation basis */
234
+ config;
235
+ /**
236
+ * Optional long-term memory store for the graph, allows for persistence & retrieval of data across threads
237
+ */
238
+ store;
239
+ triggerToNodes = {};
240
+ /**
241
+ * Optional cache for the graph, useful for caching tasks.
242
+ */
243
+ cache;
244
+ /**
245
+ * Constructor for Pregel - meant for internal use only.
246
+ *
247
+ * @internal
248
+ */
249
+ constructor(fields) {
250
+ super(fields);
251
+ let { streamMode } = fields;
252
+ if (streamMode != null && !Array.isArray(streamMode)) streamMode = [streamMode];
253
+ this.nodes = fields.nodes;
254
+ this.channels = fields.channels;
255
+ 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.`);
256
+ else this.channels[require_constants.TASKS] = new require_topic.Topic({ accumulate: false });
257
+ this.autoValidate = fields.autoValidate ?? this.autoValidate;
258
+ this.streamMode = streamMode ?? this.streamMode;
259
+ this.inputChannels = fields.inputChannels;
260
+ this.outputChannels = fields.outputChannels;
261
+ this.streamChannels = fields.streamChannels ?? this.streamChannels;
262
+ this.interruptAfter = fields.interruptAfter;
263
+ this.interruptBefore = fields.interruptBefore;
264
+ this.stepTimeout = fields.stepTimeout ?? this.stepTimeout;
265
+ this.debug = fields.debug ?? this.debug;
266
+ this.checkpointer = fields.checkpointer;
267
+ this.retryPolicy = fields.retryPolicy;
268
+ this.config = fields.config;
269
+ this.store = fields.store;
270
+ this.cache = fields.cache;
271
+ this.name = fields.name;
272
+ this.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes;
273
+ if (this.autoValidate) this.validate();
274
+ }
275
+ /**
276
+ * Creates a new instance of the Pregel graph with updated configuration.
277
+ * This method follows the immutable pattern - instead of modifying the current instance,
278
+ * it returns a new instance with the merged configuration.
279
+ *
280
+ * @example
281
+ * ```typescript
282
+ * // Create a new instance with debug enabled
283
+ * const debugGraph = graph.withConfig({ debug: true });
284
+ *
285
+ * // Create a new instance with a specific thread ID
286
+ * const threadGraph = graph.withConfig({
287
+ * configurable: { thread_id: "123" }
288
+ * });
289
+ * ```
290
+ *
291
+ * @param config - The configuration to merge with the current configuration
292
+ * @returns A new Pregel instance with the merged configuration
293
+ */
294
+ withConfig(config) {
295
+ const mergedConfig = (0, __langchain_core_runnables.mergeConfigs)(this.config, config);
296
+ return new this.constructor({
297
+ ...this,
298
+ config: mergedConfig
299
+ });
300
+ }
301
+ /**
302
+ * Validates the graph structure to ensure it is well-formed.
303
+ * Checks for:
304
+ * - No orphaned nodes
305
+ * - Valid input/output channel configurations
306
+ * - Valid interrupt configurations
307
+ *
308
+ * @returns this - The Pregel instance for method chaining
309
+ * @throws {GraphValidationError} If the graph structure is invalid
310
+ */
311
+ validate() {
312
+ require_validate.validateGraph({
313
+ nodes: this.nodes,
314
+ channels: this.channels,
315
+ outputChannels: this.outputChannels,
316
+ inputChannels: this.inputChannels,
317
+ streamChannels: this.streamChannels,
318
+ interruptAfterNodes: this.interruptAfter,
319
+ interruptBeforeNodes: this.interruptBefore
320
+ });
321
+ for (const [name, node] of Object.entries(this.nodes)) for (const trigger of node.triggers) {
322
+ this.triggerToNodes[trigger] ??= [];
323
+ this.triggerToNodes[trigger].push(name);
324
+ }
325
+ return this;
326
+ }
327
+ /**
328
+ * Gets a list of all channels that should be streamed.
329
+ * If streamChannels is specified, returns those channels.
330
+ * Otherwise, returns all channels in the graph.
331
+ *
332
+ * @returns Array of channel keys to stream
333
+ */
334
+ get streamChannelsList() {
335
+ if (Array.isArray(this.streamChannels)) return this.streamChannels;
336
+ else if (this.streamChannels) return [this.streamChannels];
337
+ else return Object.keys(this.channels);
338
+ }
339
+ /**
340
+ * Gets the channels to stream in their original format.
341
+ * If streamChannels is specified, returns it as-is (either single key or array).
342
+ * Otherwise, returns all channels in the graph as an array.
343
+ *
344
+ * @returns Channel keys to stream, either as a single key or array
345
+ */
346
+ get streamChannelsAsIs() {
347
+ if (this.streamChannels) return this.streamChannels;
348
+ else return Object.keys(this.channels);
349
+ }
350
+ /**
351
+ * Gets a drawable representation of the graph structure.
352
+ * This is an async version of getGraph() and is the preferred method to use.
353
+ *
354
+ * @param config - Configuration for generating the graph visualization
355
+ * @returns A representation of the graph that can be visualized
356
+ */
357
+ async getGraphAsync(config) {
358
+ return this.getGraph(config);
359
+ }
360
+ /**
361
+ * Gets all subgraphs within this graph.
362
+ * A subgraph is a Pregel instance that is nested within a node of this graph.
363
+ *
364
+ * @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release.
365
+ * @param namespace - Optional namespace to filter subgraphs
366
+ * @param recurse - Whether to recursively get subgraphs of subgraphs
367
+ * @returns Generator yielding tuples of [name, subgraph]
368
+ */
369
+ *getSubgraphs(namespace, recurse) {
370
+ for (const [name, node] of Object.entries(this.nodes)) {
371
+ if (namespace !== void 0) {
372
+ if (!namespace.startsWith(name)) continue;
373
+ }
374
+ const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound];
375
+ for (const candidate of candidates) {
376
+ const graph = require_subgraph.findSubgraphPregel(candidate);
377
+ if (graph !== void 0) {
378
+ if (name === namespace) {
379
+ yield [name, graph];
380
+ return;
381
+ }
382
+ if (namespace === void 0) yield [name, graph];
383
+ if (recurse) {
384
+ let newNamespace = namespace;
385
+ if (namespace !== void 0) newNamespace = namespace.slice(name.length + 1);
386
+ for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) yield [`${name}${require_constants.CHECKPOINT_NAMESPACE_SEPARATOR}${subgraphName}`, subgraph];
387
+ }
388
+ }
389
+ }
390
+ }
391
+ }
392
+ /**
393
+ * Gets all subgraphs within this graph asynchronously.
394
+ * A subgraph is a Pregel instance that is nested within a node of this graph.
395
+ *
396
+ * @param namespace - Optional namespace to filter subgraphs
397
+ * @param recurse - Whether to recursively get subgraphs of subgraphs
398
+ * @returns AsyncGenerator yielding tuples of [name, subgraph]
399
+ */
400
+ async *getSubgraphsAsync(namespace, recurse) {
401
+ yield* this.getSubgraphs(namespace, recurse);
402
+ }
403
+ /**
404
+ * Prepares a state snapshot from saved checkpoint data.
405
+ * This is an internal method used by getState and getStateHistory.
406
+ *
407
+ * @param config - Configuration for preparing the snapshot
408
+ * @param saved - Optional saved checkpoint data
409
+ * @param subgraphCheckpointer - Optional checkpointer for subgraphs
410
+ * @param applyPendingWrites - Whether to apply pending writes to tasks and then to channels
411
+ * @returns A snapshot of the graph state
412
+ * @internal
413
+ */
414
+ async _prepareStateSnapshot({ config, saved, subgraphCheckpointer, applyPendingWrites = false }) {
415
+ if (saved === void 0) return {
416
+ values: {},
417
+ next: [],
418
+ config,
419
+ tasks: []
420
+ };
421
+ const channels = require_base.emptyChannels(this.channels, saved.checkpoint);
422
+ if (saved.pendingWrites?.length) {
423
+ const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === require_constants.NULL_TASK_ID).map(([_, channel, value]) => [String(channel), value]);
424
+ if (nullWrites.length > 0) require_algo._applyWrites(saved.checkpoint, channels, [{
425
+ name: require_constants.INPUT,
426
+ writes: nullWrites,
427
+ triggers: []
428
+ }], void 0, this.triggerToNodes);
429
+ }
430
+ const nextTasks = Object.values(require_algo._prepareNextTasks(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, {
431
+ step: (saved.metadata?.step ?? -1) + 1,
432
+ store: this.store
433
+ }));
434
+ const subgraphs = await require_utils.gatherIterator(this.getSubgraphsAsync());
435
+ const parentNamespace = saved.config.configurable?.checkpoint_ns ?? "";
436
+ const taskStates = {};
437
+ for (const task of nextTasks) {
438
+ const matchingSubgraph = subgraphs.find(([name]) => name === task.name);
439
+ if (!matchingSubgraph) continue;
440
+ let taskNs = `${String(task.name)}${require_constants.CHECKPOINT_NAMESPACE_END}${task.id}`;
441
+ if (parentNamespace) taskNs = `${parentNamespace}${require_constants.CHECKPOINT_NAMESPACE_SEPARATOR}${taskNs}`;
442
+ if (subgraphCheckpointer === void 0) {
443
+ const config$1 = { configurable: {
444
+ thread_id: saved.config.configurable?.thread_id,
445
+ checkpoint_ns: taskNs
446
+ } };
447
+ taskStates[task.id] = config$1;
448
+ } else {
449
+ const subgraphConfig = { configurable: {
450
+ [require_constants.CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer,
451
+ thread_id: saved.config.configurable?.thread_id,
452
+ checkpoint_ns: taskNs
453
+ } };
454
+ const pregel = matchingSubgraph[1];
455
+ taskStates[task.id] = await pregel.getState(subgraphConfig, { subgraphs: true });
456
+ }
457
+ }
458
+ if (applyPendingWrites && saved.pendingWrites?.length) {
459
+ const nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task]));
460
+ for (const [taskId, channel, value] of saved.pendingWrites) {
461
+ if ([
462
+ require_constants.ERROR,
463
+ require_constants.INTERRUPT,
464
+ __langchain_langgraph_checkpoint.SCHEDULED
465
+ ].includes(channel)) continue;
466
+ if (!(taskId in nextTaskById)) continue;
467
+ nextTaskById[taskId].writes.push([String(channel), value]);
468
+ }
469
+ const tasksWithWrites$1 = nextTasks.filter((task) => task.writes.length > 0);
470
+ if (tasksWithWrites$1.length > 0) require_algo._applyWrites(saved.checkpoint, channels, tasksWithWrites$1, void 0, this.triggerToNodes);
471
+ }
472
+ let metadata = saved?.metadata;
473
+ if (metadata && saved?.config?.configurable?.thread_id) metadata = {
474
+ ...metadata,
475
+ thread_id: saved.config.configurable.thread_id
476
+ };
477
+ const nextList = nextTasks.filter((task) => task.writes.length === 0).map((task) => task.name);
478
+ return {
479
+ values: require_io.readChannels(channels, this.streamChannelsAsIs),
480
+ next: nextList,
481
+ tasks: require_debug.tasksWithWrites(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs),
482
+ metadata,
483
+ config: require_index.patchCheckpointMap(saved.config, saved.metadata),
484
+ createdAt: saved.checkpoint.ts,
485
+ parentConfig: saved.parentConfig
486
+ };
487
+ }
488
+ /**
489
+ * Gets the current state of the graph.
490
+ * Requires a checkpointer to be configured.
491
+ *
492
+ * @param config - Configuration for retrieving the state
493
+ * @param options - Additional options
494
+ * @returns A snapshot of the current graph state
495
+ * @throws {GraphValueError} If no checkpointer is configured
496
+ */
497
+ async getState(config, options) {
498
+ const checkpointer = config.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
499
+ if (!checkpointer) throw new require_errors.GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" });
500
+ const checkpointNamespace = config.configurable?.checkpoint_ns ?? "";
501
+ if (checkpointNamespace !== "" && config.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] === void 0) {
502
+ const recastNamespace = require_config.recastCheckpointNamespace(checkpointNamespace);
503
+ 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 });
504
+ throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`);
505
+ }
506
+ const mergedConfig = (0, __langchain_core_runnables.mergeConfigs)(this.config, config);
507
+ const saved = await checkpointer.getTuple(config);
508
+ const snapshot = await this._prepareStateSnapshot({
509
+ config: mergedConfig,
510
+ saved,
511
+ subgraphCheckpointer: options?.subgraphs ? checkpointer : void 0,
512
+ applyPendingWrites: !config.configurable?.checkpoint_id
513
+ });
514
+ return snapshot;
515
+ }
516
+ /**
517
+ * Gets the history of graph states.
518
+ * Requires a checkpointer to be configured.
519
+ * Useful for:
520
+ * - Debugging execution history
521
+ * - Implementing time travel
522
+ * - Analyzing graph behavior
523
+ *
524
+ * @param config - Configuration for retrieving the history
525
+ * @param options - Options for filtering the history
526
+ * @returns An async iterator of state snapshots
527
+ * @throws {Error} If no checkpointer is configured
528
+ */
529
+ async *getStateHistory(config, options) {
530
+ const checkpointer = config.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
531
+ if (!checkpointer) throw new require_errors.GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" });
532
+ const checkpointNamespace = config.configurable?.checkpoint_ns ?? "";
533
+ if (checkpointNamespace !== "" && config.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] === void 0) {
534
+ const recastNamespace = require_config.recastCheckpointNamespace(checkpointNamespace);
535
+ for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) {
536
+ yield* pregel.getStateHistory(require_utils.patchConfigurable(config, { [require_constants.CONFIG_KEY_CHECKPOINTER]: checkpointer }), options);
537
+ return;
538
+ }
539
+ throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`);
540
+ }
541
+ const mergedConfig = (0, __langchain_core_runnables.mergeConfigs)(this.config, config, { configurable: { checkpoint_ns: checkpointNamespace } });
542
+ for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) yield this._prepareStateSnapshot({
543
+ config: checkpointTuple.config,
544
+ saved: checkpointTuple
545
+ });
546
+ }
547
+ /**
548
+ * Apply updates to the graph state in bulk.
549
+ * Requires a checkpointer to be configured.
550
+ *
551
+ * This method is useful for recreating a thread
552
+ * from a list of updates, especially if a checkpoint
553
+ * is created as a result of multiple tasks.
554
+ *
555
+ * @internal The API might change in the future.
556
+ *
557
+ * @param startConfig - Configuration for the update
558
+ * @param updates - The list of updates to apply to graph state
559
+ * @returns Updated configuration
560
+ * @throws {GraphValueError} If no checkpointer is configured
561
+ * @throws {InvalidUpdateError} If the update cannot be attributed to a node or an update can be only applied in sequence.
562
+ */
563
+ async bulkUpdateState(startConfig, supersteps) {
564
+ const checkpointer = startConfig.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
565
+ if (!checkpointer) throw new require_errors.GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" });
566
+ if (supersteps.length === 0) throw new Error("No supersteps provided");
567
+ if (supersteps.some((s) => s.updates.length === 0)) throw new Error("No updates provided");
568
+ const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? "";
569
+ if (checkpointNamespace !== "" && startConfig.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] === void 0) {
570
+ const recastNamespace = require_config.recastCheckpointNamespace(checkpointNamespace);
571
+ for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) return await pregel.bulkUpdateState(require_utils.patchConfigurable(startConfig, { [require_constants.CONFIG_KEY_CHECKPOINTER]: checkpointer }), supersteps);
572
+ throw new Error(`Subgraph "${recastNamespace}" not found`);
573
+ }
574
+ const updateSuperStep = async (inputConfig, updates) => {
575
+ const config = this.config ? (0, __langchain_core_runnables.mergeConfigs)(this.config, inputConfig) : inputConfig;
576
+ const saved = await checkpointer.getTuple(config);
577
+ const checkpoint = saved !== void 0 ? (0, __langchain_langgraph_checkpoint.copyCheckpoint)(saved.checkpoint) : (0, __langchain_langgraph_checkpoint.emptyCheckpoint)();
578
+ const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions };
579
+ const step = saved?.metadata?.step ?? -1;
580
+ let checkpointConfig = require_utils.patchConfigurable(config, { checkpoint_ns: config.configurable?.checkpoint_ns ?? "" });
581
+ let checkpointMetadata = config.metadata ?? {};
582
+ if (saved?.config.configurable) {
583
+ checkpointConfig = require_utils.patchConfigurable(config, saved.config.configurable);
584
+ checkpointMetadata = {
585
+ ...saved.metadata,
586
+ ...checkpointMetadata
587
+ };
588
+ }
589
+ const { values, asNode } = updates[0];
590
+ if (values == null && asNode === void 0) {
591
+ if (updates.length > 1) throw new require_errors.InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`);
592
+ const nextConfig$1 = await checkpointer.put(checkpointConfig, require_base.createCheckpoint(checkpoint, void 0, step), {
593
+ source: "update",
594
+ step: step + 1,
595
+ parents: saved?.metadata?.parents ?? {}
596
+ }, {});
597
+ return require_index.patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);
598
+ }
599
+ const channels = require_base.emptyChannels(this.channels, checkpoint);
600
+ if (values === null && asNode === require_constants.END) {
601
+ if (updates.length > 1) throw new require_errors.InvalidUpdateError(`Cannot apply multiple updates when clearing state`);
602
+ if (saved) {
603
+ const nextTasks = require_algo._prepareNextTasks(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, {
604
+ step: (saved.metadata?.step ?? -1) + 1,
605
+ checkpointer,
606
+ store: this.store
607
+ });
608
+ const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === require_constants.NULL_TASK_ID).map((w) => w.slice(1));
609
+ if (nullWrites.length > 0) require_algo._applyWrites(checkpoint, channels, [{
610
+ name: require_constants.INPUT,
611
+ writes: nullWrites,
612
+ triggers: []
613
+ }], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);
614
+ for (const [taskId, k, v] of saved.pendingWrites || []) {
615
+ if ([
616
+ require_constants.ERROR,
617
+ require_constants.INTERRUPT,
618
+ __langchain_langgraph_checkpoint.SCHEDULED
619
+ ].includes(k)) continue;
620
+ if (!(taskId in nextTasks)) continue;
621
+ nextTasks[taskId].writes.push([k, v]);
622
+ }
623
+ require_algo._applyWrites(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);
624
+ }
625
+ const nextConfig$1 = await checkpointer.put(checkpointConfig, require_base.createCheckpoint(checkpoint, channels, step), {
626
+ ...checkpointMetadata,
627
+ source: "update",
628
+ step: step + 1,
629
+ parents: saved?.metadata?.parents ?? {}
630
+ }, require_index.getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions));
631
+ return require_index.patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);
632
+ }
633
+ if (asNode === require_constants.COPY) {
634
+ if (updates.length > 1) throw new require_errors.InvalidUpdateError(`Cannot copy checkpoint with multiple updates`);
635
+ if (saved == null) throw new require_errors.InvalidUpdateError(`Cannot copy a non-existent checkpoint`);
636
+ const isCopyWithUpdates = (values$1) => {
637
+ if (!Array.isArray(values$1)) return false;
638
+ if (values$1.length === 0) return false;
639
+ return values$1.every((v) => Array.isArray(v) && v.length === 2);
640
+ };
641
+ const nextCheckpoint = require_base.createCheckpoint(checkpoint, void 0, step);
642
+ const nextConfig$1 = await checkpointer.put(saved.parentConfig ?? require_utils.patchConfigurable(saved.config, { checkpoint_id: void 0 }), nextCheckpoint, {
643
+ source: "fork",
644
+ step: step + 1,
645
+ parents: saved.metadata?.parents ?? {}
646
+ }, {});
647
+ if (isCopyWithUpdates(values)) {
648
+ const nextTasks = require_algo._prepareNextTasks(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig$1, false, { step: step + 2 });
649
+ const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => {
650
+ acc[name] ??= [];
651
+ acc[name].push({ id });
652
+ return acc;
653
+ }, {});
654
+ const userGroupBy = values.reduce((acc, item) => {
655
+ const [values$1, asNode$1] = item;
656
+ acc[asNode$1] ??= [];
657
+ const targetIdx = acc[asNode$1].length;
658
+ const taskId = tasksGroupBy[asNode$1]?.[targetIdx]?.id;
659
+ acc[asNode$1].push({
660
+ values: values$1,
661
+ asNode: asNode$1,
662
+ taskId
663
+ });
664
+ return acc;
665
+ }, {});
666
+ return updateSuperStep(require_index.patchCheckpointMap(nextConfig$1, saved.metadata), Object.values(userGroupBy).flat());
667
+ }
668
+ return require_index.patchCheckpointMap(nextConfig$1, saved.metadata);
669
+ }
670
+ if (asNode === require_constants.INPUT) {
671
+ if (updates.length > 1) throw new require_errors.InvalidUpdateError(`Cannot apply multiple updates when updating as input`);
672
+ const inputWrites = await require_utils.gatherIterator(require_io.mapInput(this.inputChannels, values));
673
+ if (inputWrites.length === 0) throw new require_errors.InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`);
674
+ require_algo._applyWrites(checkpoint, channels, [{
675
+ name: require_constants.INPUT,
676
+ writes: inputWrites,
677
+ triggers: []
678
+ }], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);
679
+ const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1;
680
+ const nextConfig$1 = await checkpointer.put(checkpointConfig, require_base.createCheckpoint(checkpoint, channels, nextStep), {
681
+ source: "input",
682
+ step: nextStep,
683
+ parents: saved?.metadata?.parents ?? {}
684
+ }, require_index.getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions));
685
+ await checkpointer.putWrites(nextConfig$1, inputWrites, (0, __langchain_langgraph_checkpoint.uuid5)(require_constants.INPUT, checkpoint.id));
686
+ return require_index.patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);
687
+ }
688
+ if (config.configurable?.checkpoint_id === void 0 && saved?.pendingWrites !== void 0 && saved.pendingWrites.length > 0) {
689
+ const nextTasks = require_algo._prepareNextTasks(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, {
690
+ store: this.store,
691
+ checkpointer: this.checkpointer,
692
+ step: (saved.metadata?.step ?? -1) + 1
693
+ });
694
+ const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === require_constants.NULL_TASK_ID).map((w) => w.slice(1));
695
+ if (nullWrites.length > 0) require_algo._applyWrites(saved.checkpoint, channels, [{
696
+ name: require_constants.INPUT,
697
+ writes: nullWrites,
698
+ triggers: []
699
+ }], void 0, this.triggerToNodes);
700
+ for (const [tid, k, v] of saved.pendingWrites) {
701
+ if ([
702
+ require_constants.ERROR,
703
+ require_constants.INTERRUPT,
704
+ __langchain_langgraph_checkpoint.SCHEDULED
705
+ ].includes(k) || nextTasks[tid] === void 0) continue;
706
+ nextTasks[tid].writes.push([k, v]);
707
+ }
708
+ const tasks$1 = Object.values(nextTasks).filter((task) => {
709
+ return task.writes.length > 0;
710
+ });
711
+ if (tasks$1.length > 0) require_algo._applyWrites(checkpoint, channels, tasks$1, void 0, this.triggerToNodes);
712
+ }
713
+ const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => {
714
+ return Object.values(seenVersions);
715
+ }).flat().find((v) => !!v);
716
+ const validUpdates = [];
717
+ if (updates.length === 1) {
718
+ let { values: values$1, asNode: asNode$1, taskId } = updates[0];
719
+ if (asNode$1 === void 0 && Object.keys(this.nodes).length === 1) [asNode$1] = Object.keys(this.nodes);
720
+ else if (asNode$1 === void 0 && nonNullVersion === void 0) {
721
+ if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== void 0) asNode$1 = this.inputChannels;
722
+ } else if (asNode$1 === void 0) {
723
+ const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n, seen]) => {
724
+ return Object.values(seen).map((v) => {
725
+ return [v, n];
726
+ });
727
+ }).flat().filter(([_, v]) => v !== require_constants.INTERRUPT).sort(([aNumber], [bNumber]) => (0, __langchain_langgraph_checkpoint.compareChannelVersions)(aNumber, bNumber));
728
+ if (lastSeenByNode) {
729
+ if (lastSeenByNode.length === 1) asNode$1 = lastSeenByNode[0][1];
730
+ else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) asNode$1 = lastSeenByNode[lastSeenByNode.length - 1][1];
731
+ }
732
+ }
733
+ if (asNode$1 === void 0) throw new require_errors.InvalidUpdateError(`Ambiguous update, specify "asNode"`);
734
+ validUpdates.push({
735
+ values: values$1,
736
+ asNode: asNode$1,
737
+ taskId
738
+ });
739
+ } else for (const { asNode: asNode$1, values: values$1, taskId } of updates) {
740
+ if (asNode$1 == null) throw new require_errors.InvalidUpdateError(`"asNode" is required when applying multiple updates`);
741
+ validUpdates.push({
742
+ values: values$1,
743
+ asNode: asNode$1,
744
+ taskId
745
+ });
746
+ }
747
+ const tasks = [];
748
+ for (const { asNode: asNode$1, values: values$1, taskId } of validUpdates) {
749
+ if (this.nodes[asNode$1] === void 0) throw new require_errors.InvalidUpdateError(`Node "${asNode$1.toString()}" does not exist`);
750
+ const writers = this.nodes[asNode$1].getWriters();
751
+ if (!writers.length) throw new require_errors.InvalidUpdateError(`No writers found for node "${asNode$1.toString()}"`);
752
+ tasks.push({
753
+ name: asNode$1,
754
+ input: values$1,
755
+ proc: writers.length > 1 ? __langchain_core_runnables.RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0],
756
+ writes: [],
757
+ triggers: [require_constants.INTERRUPT],
758
+ id: taskId ?? (0, __langchain_langgraph_checkpoint.uuid5)(require_constants.INTERRUPT, checkpoint.id),
759
+ writers: []
760
+ });
761
+ }
762
+ for (const task of tasks) await task.proc.invoke(task.input, (0, __langchain_core_runnables.patchConfig)({
763
+ ...config,
764
+ store: config?.store ?? this.store
765
+ }, {
766
+ runName: config.runName ?? `${this.getName()}UpdateState`,
767
+ configurable: {
768
+ [require_constants.CONFIG_KEY_SEND]: (items) => task.writes.push(...items),
769
+ [require_constants.CONFIG_KEY_READ]: (select_, fresh_ = false) => require_algo._localRead(checkpoint, channels, task, select_, fresh_)
770
+ }
771
+ }));
772
+ for (const task of tasks) {
773
+ const channelWrites = task.writes.filter((w) => w[0] !== require_constants.PUSH);
774
+ if (saved !== void 0 && channelWrites.length > 0) await checkpointer.putWrites(checkpointConfig, channelWrites, task.id);
775
+ }
776
+ require_algo._applyWrites(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);
777
+ const newVersions = require_index.getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions);
778
+ const nextConfig = await checkpointer.put(checkpointConfig, require_base.createCheckpoint(checkpoint, channels, step + 1), {
779
+ source: "update",
780
+ step: step + 1,
781
+ parents: saved?.metadata?.parents ?? {}
782
+ }, newVersions);
783
+ for (const task of tasks) {
784
+ const pushWrites = task.writes.filter((w) => w[0] === require_constants.PUSH);
785
+ if (pushWrites.length > 0) await checkpointer.putWrites(nextConfig, pushWrites, task.id);
786
+ }
787
+ return require_index.patchCheckpointMap(nextConfig, saved ? saved.metadata : void 0);
788
+ };
789
+ let currentConfig = startConfig;
790
+ for (const { updates } of supersteps) currentConfig = await updateSuperStep(currentConfig, updates);
791
+ return currentConfig;
792
+ }
793
+ /**
794
+ * Updates the state of the graph with new values.
795
+ * Requires a checkpointer to be configured.
796
+ *
797
+ * This method can be used for:
798
+ * - Implementing human-in-the-loop workflows
799
+ * - Modifying graph state during breakpoints
800
+ * - Integrating external inputs into the graph
801
+ *
802
+ * @param inputConfig - Configuration for the update
803
+ * @param values - The values to update the state with
804
+ * @param asNode - Optional node name to attribute the update to
805
+ * @returns Updated configuration
806
+ * @throws {GraphValueError} If no checkpointer is configured
807
+ * @throws {InvalidUpdateError} If the update cannot be attributed to a node
808
+ */
809
+ async updateState(inputConfig, values, asNode) {
810
+ return this.bulkUpdateState(inputConfig, [{ updates: [{
811
+ values,
812
+ asNode
813
+ }] }]);
814
+ }
815
+ /**
816
+ * Gets the default values for various graph configuration options.
817
+ * This is an internal method used to process and normalize configuration options.
818
+ *
819
+ * @param config - The input configuration options
820
+ * @returns A tuple containing normalized values for:
821
+ * - debug mode
822
+ * - stream modes
823
+ * - input keys
824
+ * - output keys
825
+ * - remaining config
826
+ * - interrupt before nodes
827
+ * - interrupt after nodes
828
+ * - checkpointer
829
+ * - store
830
+ * - whether stream mode is single
831
+ * - node cache
832
+ * - whether checkpoint during is enabled
833
+ * @internal
834
+ */
835
+ _defaults(config) {
836
+ const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore,...rest } = config;
837
+ let streamModeSingle = true;
838
+ const defaultDebug = debug !== void 0 ? debug : this.debug;
839
+ let defaultOutputKeys = outputKeys;
840
+ if (defaultOutputKeys === void 0) defaultOutputKeys = this.streamChannelsAsIs;
841
+ else require_validate.validateKeys(defaultOutputKeys, this.channels);
842
+ let defaultInputKeys = inputKeys;
843
+ if (defaultInputKeys === void 0) defaultInputKeys = this.inputChannels;
844
+ else require_validate.validateKeys(defaultInputKeys, this.channels);
845
+ const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? [];
846
+ const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? [];
847
+ let defaultStreamMode;
848
+ if (streamMode !== void 0) {
849
+ defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode];
850
+ streamModeSingle = typeof streamMode === "string";
851
+ } else {
852
+ if (config.configurable?.[require_constants.CONFIG_KEY_TASK_ID] !== void 0) defaultStreamMode = ["values"];
853
+ else defaultStreamMode = this.streamMode;
854
+ streamModeSingle = true;
855
+ }
856
+ let defaultCheckpointer;
857
+ if (this.checkpointer === false) defaultCheckpointer = void 0;
858
+ else if (config !== void 0 && config.configurable?.[require_constants.CONFIG_KEY_CHECKPOINTER] !== void 0) defaultCheckpointer = config.configurable[require_constants.CONFIG_KEY_CHECKPOINTER];
859
+ else if (this.checkpointer === true) throw new Error("checkpointer: true cannot be used for root graphs.");
860
+ else defaultCheckpointer = this.checkpointer;
861
+ const defaultStore = config.store ?? this.store;
862
+ const defaultCache = config.cache ?? this.cache;
863
+ if (config.durability != null && config.checkpointDuring != null) throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");
864
+ const checkpointDuringDurability = (() => {
865
+ if (config.checkpointDuring == null) return void 0;
866
+ if (config.checkpointDuring === false) return "exit";
867
+ return "async";
868
+ })();
869
+ const defaultDurability = config.durability ?? checkpointDuringDurability ?? config?.configurable?.[require_constants.CONFIG_KEY_DURABILITY] ?? "async";
870
+ return [
871
+ defaultDebug,
872
+ defaultStreamMode,
873
+ defaultInputKeys,
874
+ defaultOutputKeys,
875
+ rest,
876
+ defaultInterruptBefore,
877
+ defaultInterruptAfter,
878
+ defaultCheckpointer,
879
+ defaultStore,
880
+ streamModeSingle,
881
+ defaultCache,
882
+ defaultDurability
883
+ ];
884
+ }
885
+ /**
886
+ * Streams the execution of the graph, emitting state updates as they occur.
887
+ * This is the primary method for observing graph execution in real-time.
888
+ *
889
+ * Stream modes:
890
+ * - "values": Emits complete state after each step
891
+ * - "updates": Emits only state changes after each step
892
+ * - "debug": Emits detailed debug information
893
+ * - "messages": Emits messages from within nodes
894
+ *
895
+ * For more details, see the [Streaming how-to guides](../../how-tos/#streaming_1).
896
+ *
897
+ * @param input - The input to start graph execution with
898
+ * @param options - Configuration options for streaming
899
+ * @returns An async iterable stream of graph state updates
900
+ */
901
+ async stream(input, options) {
902
+ const abortController = new AbortController();
903
+ const config = {
904
+ recursionLimit: this.config?.recursionLimit,
905
+ ...options,
906
+ signal: require_index.combineAbortSignals(options?.signal, abortController.signal).signal
907
+ };
908
+ return new require_stream.IterableReadableStreamWithAbortSignal(await super.stream(input, config), abortController);
909
+ }
910
+ streamEvents(input, options, streamOptions) {
911
+ const abortController = new AbortController();
912
+ const config = {
913
+ recursionLimit: this.config?.recursionLimit,
914
+ ...options,
915
+ callbacks: require_index.combineCallbacks(this.config?.callbacks, options?.callbacks),
916
+ signal: require_index.combineAbortSignals(options?.signal, abortController.signal).signal
917
+ };
918
+ return new require_stream.IterableReadableStreamWithAbortSignal(super.streamEvents(input, config, streamOptions), abortController);
919
+ }
920
+ /**
921
+ * Validates the input for the graph.
922
+ * @param input - The input to validate
923
+ * @returns The validated input
924
+ * @internal
925
+ */
926
+ async _validateInput(input) {
927
+ return input;
928
+ }
929
+ /**
930
+ * Validates the context options for the graph.
931
+ * @param context - The context options to validate
932
+ * @returns The validated context options
933
+ * @internal
934
+ */
935
+ async _validateContext(context) {
936
+ return context;
937
+ }
938
+ /**
939
+ * Internal iterator used by stream() to generate state updates.
940
+ * This method handles the core logic of graph execution and streaming.
941
+ *
942
+ * @param input - The input to start graph execution with
943
+ * @param options - Configuration options for streaming
944
+ * @returns AsyncGenerator yielding state updates
945
+ * @internal
946
+ */
947
+ async *_streamIterator(input, options) {
948
+ const streamSubgraphs = options?.subgraphs;
949
+ const inputConfig = require_config.ensureLangGraphConfig(this.config, options);
950
+ if (inputConfig.recursionLimit === void 0 || inputConfig.recursionLimit < 1) throw new Error(`Passed "recursionLimit" must be at least 1.`);
951
+ 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"`);
952
+ const validInput = await this._validateInput(input);
953
+ const { runId,...restConfig } = inputConfig;
954
+ const [debug, streamMode, , outputKeys, config, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache, durability] = this._defaults(restConfig);
955
+ if (typeof config.context !== "undefined") config.context = await this._validateContext(config.context);
956
+ else config.configurable = await this._validateContext(config.configurable);
957
+ const stream = new require_stream.IterableReadableWritableStream({ modes: new Set(streamMode) });
958
+ if (this.checkpointer === true) {
959
+ config.configurable ??= {};
960
+ const ns = config.configurable[require_constants.CONFIG_KEY_CHECKPOINT_NS] ?? "";
961
+ 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);
962
+ }
963
+ if (streamMode.includes("messages")) {
964
+ const messageStreamer = new require_messages.StreamMessagesHandler((chunk) => stream.push(chunk));
965
+ const { callbacks } = config;
966
+ if (callbacks === void 0) config.callbacks = [messageStreamer];
967
+ else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(messageStreamer);
968
+ else {
969
+ const copiedCallbacks = callbacks.copy();
970
+ copiedCallbacks.addHandler(messageStreamer, true);
971
+ config.callbacks = copiedCallbacks;
972
+ }
973
+ }
974
+ config.writer ??= (chunk) => {
975
+ if (!streamMode.includes("custom")) return;
976
+ const ns = (require_config.getConfig()?.configurable?.[require_constants.CONFIG_KEY_CHECKPOINT_NS])?.split(require_constants.CHECKPOINT_NAMESPACE_SEPARATOR).slice(0, -1);
977
+ stream.push([
978
+ ns ?? [],
979
+ "custom",
980
+ chunk
981
+ ]);
982
+ };
983
+ config.interrupt ??= require_interrupt.interrupt;
984
+ const callbackManager = await (0, __langchain_core_runnables.getCallbackManagerForConfig)(config);
985
+ const runManager = await callbackManager?.handleChainStart(this.toJSON(), require_index._coerceToDict(input, "input"), runId, void 0, void 0, void 0, config?.runName ?? this.getName());
986
+ const channelSpecs = require_base.getOnlyChannels(this.channels);
987
+ let loop;
988
+ let loopError;
989
+ /**
990
+ * The PregelLoop will yield events from concurrent tasks as soon as they are
991
+ * generated. Each task can push multiple events onto the stream in any order.
992
+ *
993
+ * We use a separate background method and stream here in order to yield events
994
+ * from the loop to the main stream and therefore back to the user as soon as
995
+ * they are available.
996
+ */
997
+ const createAndRunLoop = async () => {
998
+ try {
999
+ loop = await require_loop.PregelLoop.initialize({
1000
+ input: validInput,
1001
+ config,
1002
+ checkpointer,
1003
+ nodes: this.nodes,
1004
+ channelSpecs,
1005
+ outputKeys,
1006
+ streamKeys: this.streamChannelsAsIs,
1007
+ store,
1008
+ cache,
1009
+ stream,
1010
+ interruptAfter,
1011
+ interruptBefore,
1012
+ manager: runManager,
1013
+ debug: this.debug,
1014
+ triggerToNodes: this.triggerToNodes,
1015
+ durability
1016
+ });
1017
+ const runner = new require_runner.PregelRunner({
1018
+ loop,
1019
+ nodeFinished: config.configurable?.[require_constants.CONFIG_KEY_NODE_FINISHED]
1020
+ });
1021
+ if (options?.subgraphs) loop.config.configurable = {
1022
+ ...loop.config.configurable,
1023
+ [require_constants.CONFIG_KEY_STREAM]: loop.stream
1024
+ };
1025
+ await this._runLoop({
1026
+ loop,
1027
+ runner,
1028
+ debug,
1029
+ config
1030
+ });
1031
+ if (durability === "sync") await Promise.all(loop?.checkpointerPromises ?? []);
1032
+ } catch (e) {
1033
+ loopError = e;
1034
+ } finally {
1035
+ try {
1036
+ if (loop) {
1037
+ await loop.store?.stop();
1038
+ await loop.cache?.stop();
1039
+ }
1040
+ await Promise.all(loop?.checkpointerPromises ?? []);
1041
+ } catch (e) {
1042
+ loopError = loopError ?? e;
1043
+ }
1044
+ if (loopError) stream.error(loopError);
1045
+ else stream.close();
1046
+ }
1047
+ };
1048
+ const runLoopPromise = createAndRunLoop();
1049
+ try {
1050
+ for await (const chunk of stream) {
1051
+ if (chunk === void 0) throw new Error("Data structure error.");
1052
+ const [namespace, mode, payload] = chunk;
1053
+ if (streamMode.includes(mode)) if (streamSubgraphs && !streamModeSingle) yield [
1054
+ namespace,
1055
+ mode,
1056
+ payload
1057
+ ];
1058
+ else if (!streamModeSingle) yield [mode, payload];
1059
+ else if (streamSubgraphs) yield [namespace, payload];
1060
+ else yield payload;
1061
+ }
1062
+ } catch (e) {
1063
+ await runManager?.handleChainError(loopError);
1064
+ throw e;
1065
+ } finally {
1066
+ await runLoopPromise;
1067
+ }
1068
+ await runManager?.handleChainEnd(loop?.output ?? {}, runId, void 0, void 0, void 0);
1069
+ }
1070
+ /**
1071
+ * Run the graph with a single input and config.
1072
+ * @param input The input to the graph.
1073
+ * @param options The configuration to use for the run.
1074
+ */
1075
+ async invoke(input, options) {
1076
+ const streamMode = options?.streamMode ?? "values";
1077
+ const config = {
1078
+ ...options,
1079
+ outputKeys: options?.outputKeys ?? this.outputChannels,
1080
+ streamMode
1081
+ };
1082
+ const chunks = [];
1083
+ const stream = await this.stream(input, config);
1084
+ const interruptChunks = [];
1085
+ let latest;
1086
+ for await (const chunk of stream) if (streamMode === "values") if (require_constants.isInterrupted(chunk)) interruptChunks.push(chunk[require_constants.INTERRUPT]);
1087
+ else latest = chunk;
1088
+ else chunks.push(chunk);
1089
+ if (streamMode === "values") {
1090
+ if (interruptChunks.length > 0) {
1091
+ const interrupts = interruptChunks.flat(1);
1092
+ if (latest == null) return { [require_constants.INTERRUPT]: interrupts };
1093
+ if (typeof latest === "object") return {
1094
+ ...latest,
1095
+ [require_constants.INTERRUPT]: interrupts
1096
+ };
1097
+ }
1098
+ return latest;
1099
+ }
1100
+ return chunks;
1101
+ }
1102
+ async _runLoop(params) {
1103
+ const { loop, runner, debug, config } = params;
1104
+ let tickError;
1105
+ try {
1106
+ while (await loop.tick({ inputKeys: this.inputChannels })) {
1107
+ for (const { task } of await loop._matchCachedWrites()) loop._outputWrites(task.id, task.writes, true);
1108
+ if (debug) require_debug.printStepCheckpoint(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList);
1109
+ if (debug) require_debug.printStepTasks(loop.step, Object.values(loop.tasks));
1110
+ await runner.tick({
1111
+ timeout: this.stepTimeout,
1112
+ retryPolicy: this.retryPolicy,
1113
+ onStepWrite: (step, writes) => {
1114
+ if (debug) require_debug.printStepWrites(step, writes, this.streamChannelsList);
1115
+ },
1116
+ maxConcurrency: config.maxConcurrency,
1117
+ signal: config.signal
1118
+ });
1119
+ }
1120
+ if (loop.status === "out_of_steps") throw new require_errors.GraphRecursionError([
1121
+ `Recursion limit of ${config.recursionLimit} reached`,
1122
+ "without hitting a stop condition. You can increase the",
1123
+ `limit by setting the "recursionLimit" config key.`
1124
+ ].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" });
1125
+ } catch (e) {
1126
+ tickError = e;
1127
+ const suppress = await loop.finishAndHandleError(tickError);
1128
+ if (!suppress) throw e;
1129
+ } finally {
1130
+ if (tickError === void 0) await loop.finishAndHandleError();
1131
+ }
1132
+ }
1133
+ async clearCache() {
1134
+ await this.cache?.clear([]);
1135
+ }
1136
+ };
1137
+
1138
+ //#endregion
1139
+ exports.Channel = Channel;
1606
1140
  exports.Pregel = Pregel;
1607
- //# sourceMappingURL=index.js.map
1141
+ //# sourceMappingURL=index.cjs.map