@librechat/agents 3.2.31 → 3.2.33

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 (582) hide show
  1. package/dist/cjs/_virtual/_rolldown/runtime.cjs +23 -0
  2. package/dist/cjs/agents/AgentContext.cjs +844 -1046
  3. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  4. package/dist/cjs/common/constants.cjs +13 -13
  5. package/dist/cjs/common/constants.cjs.map +1 -1
  6. package/dist/cjs/common/enum.cjs +233 -240
  7. package/dist/cjs/common/enum.cjs.map +1 -1
  8. package/dist/cjs/common/index.cjs +2 -0
  9. package/dist/cjs/events.cjs +121 -169
  10. package/dist/cjs/events.cjs.map +1 -1
  11. package/dist/cjs/graphs/Graph.cjs +1389 -1807
  12. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  13. package/dist/cjs/graphs/MultiAgentGraph.cjs +713 -945
  14. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  15. package/dist/cjs/graphs/index.cjs +2 -0
  16. package/dist/cjs/hitl/askUserQuestion.cjs +60 -62
  17. package/dist/cjs/hitl/askUserQuestion.cjs.map +1 -1
  18. package/dist/cjs/hitl/index.cjs +1 -0
  19. package/dist/cjs/hooks/HookRegistry.cjs +176 -202
  20. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  21. package/dist/cjs/hooks/createToolPolicyHook.cjs +71 -101
  22. package/dist/cjs/hooks/createToolPolicyHook.cjs.map +1 -1
  23. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +170 -273
  24. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs.map +1 -1
  25. package/dist/cjs/hooks/executeHooks.cjs +227 -282
  26. package/dist/cjs/hooks/executeHooks.cjs.map +1 -1
  27. package/dist/cjs/hooks/index.cjs +6 -0
  28. package/dist/cjs/hooks/matchers.cjs +196 -230
  29. package/dist/cjs/hooks/matchers.cjs.map +1 -1
  30. package/dist/cjs/hooks/types.cjs +24 -24
  31. package/dist/cjs/hooks/types.cjs.map +1 -1
  32. package/dist/cjs/instrumentation.cjs +110 -137
  33. package/dist/cjs/instrumentation.cjs.map +1 -1
  34. package/dist/cjs/langchain/google-common.cjs +0 -3
  35. package/dist/cjs/langchain/index.cjs +80 -43
  36. package/dist/cjs/langchain/language_models/chat_models.cjs +0 -3
  37. package/dist/cjs/langchain/messages/tool.cjs +0 -3
  38. package/dist/cjs/langchain/messages.cjs +35 -18
  39. package/dist/cjs/langchain/openai.cjs +0 -3
  40. package/dist/cjs/langchain/prompts.cjs +5 -8
  41. package/dist/cjs/langchain/runnables.cjs +11 -10
  42. package/dist/cjs/langchain/tools.cjs +14 -11
  43. package/dist/cjs/langchain/utils/env.cjs +5 -8
  44. package/dist/cjs/langfuse.cjs +60 -79
  45. package/dist/cjs/langfuse.cjs.map +1 -1
  46. package/dist/cjs/langfuseToolOutputTracing.cjs +267 -399
  47. package/dist/cjs/langfuseToolOutputTracing.cjs.map +1 -1
  48. package/dist/cjs/llm/anthropic/index.cjs +432 -562
  49. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  50. package/dist/cjs/llm/anthropic/types.cjs +23 -47
  51. package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
  52. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +441 -696
  53. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  54. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +171 -252
  55. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
  56. package/dist/cjs/llm/anthropic/utils/output_parsers.cjs +2 -0
  57. package/dist/cjs/llm/anthropic/utils/tools.cjs +12 -26
  58. package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -1
  59. package/dist/cjs/llm/bedrock/index.cjs +195 -240
  60. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  61. package/dist/cjs/llm/bedrock/toolCache.cjs +84 -106
  62. package/dist/cjs/llm/bedrock/toolCache.cjs.map +1 -1
  63. package/dist/cjs/llm/bedrock/utils/index.cjs +2 -0
  64. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +357 -620
  65. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  66. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +105 -149
  67. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -1
  68. package/dist/cjs/llm/fake.cjs +86 -96
  69. package/dist/cjs/llm/fake.cjs.map +1 -1
  70. package/dist/cjs/llm/google/index.cjs +183 -237
  71. package/dist/cjs/llm/google/index.cjs.map +1 -1
  72. package/dist/cjs/llm/google/utils/common.cjs +398 -674
  73. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  74. package/dist/cjs/llm/google/utils/zod_to_genai_parameters.cjs +2 -0
  75. package/dist/cjs/llm/init.cjs +44 -53
  76. package/dist/cjs/llm/init.cjs.map +1 -1
  77. package/dist/cjs/llm/invoke.cjs +142 -182
  78. package/dist/cjs/llm/invoke.cjs.map +1 -1
  79. package/dist/cjs/llm/openai/index.cjs +991 -1276
  80. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  81. package/dist/cjs/llm/openai/utils/index.cjs +189 -316
  82. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  83. package/dist/cjs/llm/openrouter/index.cjs +102 -153
  84. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  85. package/dist/cjs/llm/openrouter/toolCache.cjs +35 -44
  86. package/dist/cjs/llm/openrouter/toolCache.cjs.map +1 -1
  87. package/dist/cjs/llm/providers.cjs +29 -37
  88. package/dist/cjs/llm/providers.cjs.map +1 -1
  89. package/dist/cjs/llm/request.cjs +20 -33
  90. package/dist/cjs/llm/request.cjs.map +1 -1
  91. package/dist/cjs/llm/vertexai/index.cjs +427 -453
  92. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  93. package/dist/cjs/main.cjs +547 -528
  94. package/dist/cjs/messages/anthropicToolCache.cjs +68 -119
  95. package/dist/cjs/messages/anthropicToolCache.cjs.map +1 -1
  96. package/dist/cjs/messages/cache.cjs +308 -401
  97. package/dist/cjs/messages/cache.cjs.map +1 -1
  98. package/dist/cjs/messages/content.cjs +36 -49
  99. package/dist/cjs/messages/content.cjs.map +1 -1
  100. package/dist/cjs/messages/contextPruning.cjs +112 -145
  101. package/dist/cjs/messages/contextPruning.cjs.map +1 -1
  102. package/dist/cjs/messages/contextPruningSettings.cjs +36 -46
  103. package/dist/cjs/messages/contextPruningSettings.cjs.map +1 -1
  104. package/dist/cjs/messages/core.cjs +256 -397
  105. package/dist/cjs/messages/core.cjs.map +1 -1
  106. package/dist/cjs/messages/format.cjs +904 -1382
  107. package/dist/cjs/messages/format.cjs.map +1 -1
  108. package/dist/cjs/messages/ids.cjs +16 -20
  109. package/dist/cjs/messages/ids.cjs.map +1 -1
  110. package/dist/cjs/messages/index.cjs +12 -0
  111. package/dist/cjs/messages/langchain.cjs +18 -18
  112. package/dist/cjs/messages/langchain.cjs.map +1 -1
  113. package/dist/cjs/messages/prune.cjs +1054 -1517
  114. package/dist/cjs/messages/prune.cjs.map +1 -1
  115. package/dist/cjs/messages/recency.cjs +77 -95
  116. package/dist/cjs/messages/recency.cjs.map +1 -1
  117. package/dist/cjs/messages/reducer.cjs +63 -78
  118. package/dist/cjs/messages/reducer.cjs.map +1 -1
  119. package/dist/cjs/messages/tools.cjs +51 -79
  120. package/dist/cjs/messages/tools.cjs.map +1 -1
  121. package/dist/cjs/openai/index.cjs +171 -217
  122. package/dist/cjs/openai/index.cjs.map +1 -1
  123. package/dist/cjs/responses/index.cjs +302 -391
  124. package/dist/cjs/responses/index.cjs.map +1 -1
  125. package/dist/cjs/run.cjs +903 -1113
  126. package/dist/cjs/run.cjs.map +1 -1
  127. package/dist/cjs/session/AgentSession.cjs +805 -986
  128. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  129. package/dist/cjs/session/JsonlSessionStore.cjs +327 -410
  130. package/dist/cjs/session/JsonlSessionStore.cjs.map +1 -1
  131. package/dist/cjs/session/handlers.cjs +192 -208
  132. package/dist/cjs/session/handlers.cjs.map +1 -1
  133. package/dist/cjs/session/ids.cjs +9 -10
  134. package/dist/cjs/session/ids.cjs.map +1 -1
  135. package/dist/cjs/session/index.cjs +4 -0
  136. package/dist/cjs/session/messageSerialization.cjs +94 -156
  137. package/dist/cjs/session/messageSerialization.cjs.map +1 -1
  138. package/dist/cjs/splitStream.cjs +147 -206
  139. package/dist/cjs/splitStream.cjs.map +1 -1
  140. package/dist/cjs/stream.cjs +856 -1344
  141. package/dist/cjs/stream.cjs.map +1 -1
  142. package/dist/cjs/summarization/index.cjs +57 -101
  143. package/dist/cjs/summarization/index.cjs.map +1 -1
  144. package/dist/cjs/summarization/node.cjs +643 -796
  145. package/dist/cjs/summarization/node.cjs.map +1 -1
  146. package/dist/cjs/tools/BashExecutor.cjs +110 -136
  147. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  148. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +165 -245
  149. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  150. package/dist/cjs/tools/Calculator.cjs +36 -57
  151. package/dist/cjs/tools/Calculator.cjs.map +1 -1
  152. package/dist/cjs/tools/CodeExecutor.cjs +126 -168
  153. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  154. package/dist/cjs/tools/CodeSessionFileSummary.cjs +36 -46
  155. package/dist/cjs/tools/CodeSessionFileSummary.cjs.map +1 -1
  156. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +459 -649
  157. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  158. package/dist/cjs/tools/ReadFile.cjs +17 -20
  159. package/dist/cjs/tools/ReadFile.cjs.map +1 -1
  160. package/dist/cjs/tools/SkillTool.cjs +26 -27
  161. package/dist/cjs/tools/SkillTool.cjs.map +1 -1
  162. package/dist/cjs/tools/SubagentTool.cjs +59 -61
  163. package/dist/cjs/tools/SubagentTool.cjs.map +1 -1
  164. package/dist/cjs/tools/ToolNode.cjs +2109 -2686
  165. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  166. package/dist/cjs/tools/ToolSearch.cjs +663 -825
  167. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  168. package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs +248 -340
  169. package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs.map +1 -1
  170. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs +170 -197
  171. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs.map +1 -1
  172. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs +425 -520
  173. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs.map +1 -1
  174. package/dist/cjs/tools/cloudflare/CloudflareSandboxTools.cjs +91 -124
  175. package/dist/cjs/tools/cloudflare/CloudflareSandboxTools.cjs.map +1 -1
  176. package/dist/cjs/tools/cloudflare/index.cjs +4 -0
  177. package/dist/cjs/tools/eagerEventExecution.cjs +75 -99
  178. package/dist/cjs/tools/eagerEventExecution.cjs.map +1 -1
  179. package/dist/cjs/tools/handlers.cjs +200 -262
  180. package/dist/cjs/tools/handlers.cjs.map +1 -1
  181. package/dist/cjs/tools/local/CompileCheckTool.cjs +150 -212
  182. package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -1
  183. package/dist/cjs/tools/local/FileCheckpointer.cjs +77 -85
  184. package/dist/cjs/tools/local/FileCheckpointer.cjs.map +1 -1
  185. package/dist/cjs/tools/local/LocalCodingTools.cjs +763 -1022
  186. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  187. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +666 -941
  188. package/dist/cjs/tools/local/LocalExecutionEngine.cjs.map +1 -1
  189. package/dist/cjs/tools/local/LocalExecutionTools.cjs +49 -92
  190. package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -1
  191. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +286 -354
  192. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -1
  193. package/dist/cjs/tools/local/attachments.cjs +108 -165
  194. package/dist/cjs/tools/local/attachments.cjs.map +1 -1
  195. package/dist/cjs/tools/local/bashAst.cjs +99 -113
  196. package/dist/cjs/tools/local/bashAst.cjs.map +1 -1
  197. package/dist/cjs/tools/local/editStrategies.cjs +126 -169
  198. package/dist/cjs/tools/local/editStrategies.cjs.map +1 -1
  199. package/dist/cjs/tools/local/index.cjs +12 -0
  200. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +136 -218
  201. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
  202. package/dist/cjs/tools/local/syntaxCheck.cjs +142 -161
  203. package/dist/cjs/tools/local/syntaxCheck.cjs.map +1 -1
  204. package/dist/cjs/tools/local/textEncoding.cjs +25 -23
  205. package/dist/cjs/tools/local/textEncoding.cjs.map +1 -1
  206. package/dist/cjs/tools/local/workspaceFS.cjs +38 -46
  207. package/dist/cjs/tools/local/workspaceFS.cjs.map +1 -1
  208. package/dist/cjs/tools/ptcTimeout.cjs +27 -47
  209. package/dist/cjs/tools/ptcTimeout.cjs.map +1 -1
  210. package/dist/cjs/tools/schema.cjs +24 -23
  211. package/dist/cjs/tools/schema.cjs.map +1 -1
  212. package/dist/cjs/tools/search/anthropic.cjs +24 -33
  213. package/dist/cjs/tools/search/anthropic.cjs.map +1 -1
  214. package/dist/cjs/tools/search/content.cjs +95 -137
  215. package/dist/cjs/tools/search/content.cjs.map +1 -1
  216. package/dist/cjs/tools/search/firecrawl.cjs +141 -172
  217. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  218. package/dist/cjs/tools/search/format.cjs +128 -196
  219. package/dist/cjs/tools/search/format.cjs.map +1 -1
  220. package/dist/cjs/tools/search/highlights.cjs +165 -232
  221. package/dist/cjs/tools/search/highlights.cjs.map +1 -1
  222. package/dist/cjs/tools/search/index.cjs +2 -0
  223. package/dist/cjs/tools/search/rerankers.cjs +151 -174
  224. package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
  225. package/dist/cjs/tools/search/schema.cjs +40 -39
  226. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  227. package/dist/cjs/tools/search/search.cjs +428 -530
  228. package/dist/cjs/tools/search/search.cjs.map +1 -1
  229. package/dist/cjs/tools/search/serper-scraper.cjs +106 -127
  230. package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -1
  231. package/dist/cjs/tools/search/tavily-scraper.cjs +129 -181
  232. package/dist/cjs/tools/search/tavily-scraper.cjs.map +1 -1
  233. package/dist/cjs/tools/search/tavily-search.cjs +295 -359
  234. package/dist/cjs/tools/search/tavily-search.cjs.map +1 -1
  235. package/dist/cjs/tools/search/tool.cjs +260 -299
  236. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  237. package/dist/cjs/tools/search/utils.cjs +74 -117
  238. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  239. package/dist/cjs/tools/skillCatalog.cjs +54 -72
  240. package/dist/cjs/tools/skillCatalog.cjs.map +1 -1
  241. package/dist/cjs/tools/streamedToolCallSeals.cjs +19 -36
  242. package/dist/cjs/tools/streamedToolCallSeals.cjs.map +1 -1
  243. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +612 -771
  244. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  245. package/dist/cjs/tools/subagent/index.cjs +1 -0
  246. package/dist/cjs/tools/toolOutputReferences.cjs +523 -630
  247. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  248. package/dist/cjs/utils/callbacks.cjs +11 -21
  249. package/dist/cjs/utils/callbacks.cjs.map +1 -1
  250. package/dist/cjs/utils/errors.cjs +70 -95
  251. package/dist/cjs/utils/errors.cjs.map +1 -1
  252. package/dist/cjs/utils/events.cjs +32 -42
  253. package/dist/cjs/utils/events.cjs.map +1 -1
  254. package/dist/cjs/utils/graph.cjs +8 -12
  255. package/dist/cjs/utils/graph.cjs.map +1 -1
  256. package/dist/cjs/utils/handlers.cjs +60 -82
  257. package/dist/cjs/utils/handlers.cjs.map +1 -1
  258. package/dist/cjs/utils/index.cjs +9 -0
  259. package/dist/cjs/utils/llm.cjs +19 -27
  260. package/dist/cjs/utils/llm.cjs.map +1 -1
  261. package/dist/cjs/utils/misc.cjs +30 -46
  262. package/dist/cjs/utils/misc.cjs.map +1 -1
  263. package/dist/cjs/utils/run.cjs +50 -66
  264. package/dist/cjs/utils/run.cjs.map +1 -1
  265. package/dist/cjs/utils/schema.cjs +11 -19
  266. package/dist/cjs/utils/schema.cjs.map +1 -1
  267. package/dist/cjs/utils/title.cjs +71 -106
  268. package/dist/cjs/utils/title.cjs.map +1 -1
  269. package/dist/cjs/utils/tokens.cjs +186 -283
  270. package/dist/cjs/utils/tokens.cjs.map +1 -1
  271. package/dist/cjs/utils/truncation.cjs +95 -114
  272. package/dist/cjs/utils/truncation.cjs.map +1 -1
  273. package/dist/esm/agents/AgentContext.mjs +844 -1044
  274. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  275. package/dist/esm/common/constants.mjs +13 -11
  276. package/dist/esm/common/constants.mjs.map +1 -1
  277. package/dist/esm/common/enum.mjs +221 -238
  278. package/dist/esm/common/enum.mjs.map +1 -1
  279. package/dist/esm/common/index.mjs +3 -0
  280. package/dist/esm/events.mjs +121 -167
  281. package/dist/esm/events.mjs.map +1 -1
  282. package/dist/esm/graphs/Graph.mjs +1388 -1804
  283. package/dist/esm/graphs/Graph.mjs.map +1 -1
  284. package/dist/esm/graphs/MultiAgentGraph.mjs +713 -943
  285. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  286. package/dist/esm/graphs/index.mjs +3 -0
  287. package/dist/esm/hitl/askUserQuestion.mjs +60 -60
  288. package/dist/esm/hitl/askUserQuestion.mjs.map +1 -1
  289. package/dist/esm/hitl/index.mjs +2 -0
  290. package/dist/esm/hooks/HookRegistry.mjs +176 -200
  291. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  292. package/dist/esm/hooks/createToolPolicyHook.mjs +71 -99
  293. package/dist/esm/hooks/createToolPolicyHook.mjs.map +1 -1
  294. package/dist/esm/hooks/createWorkspacePolicyHook.mjs +170 -271
  295. package/dist/esm/hooks/createWorkspacePolicyHook.mjs.map +1 -1
  296. package/dist/esm/hooks/executeHooks.mjs +227 -280
  297. package/dist/esm/hooks/executeHooks.mjs.map +1 -1
  298. package/dist/esm/hooks/index.mjs +7 -0
  299. package/dist/esm/hooks/matchers.mjs +196 -228
  300. package/dist/esm/hooks/matchers.mjs.map +1 -1
  301. package/dist/esm/hooks/types.mjs +24 -22
  302. package/dist/esm/hooks/types.mjs.map +1 -1
  303. package/dist/esm/instrumentation.mjs +109 -132
  304. package/dist/esm/instrumentation.mjs.map +1 -1
  305. package/dist/esm/langchain/google-common.mjs +1 -2
  306. package/dist/esm/langchain/index.mjs +5 -5
  307. package/dist/esm/langchain/language_models/chat_models.mjs +1 -2
  308. package/dist/esm/langchain/messages/tool.mjs +1 -2
  309. package/dist/esm/langchain/messages.mjs +2 -2
  310. package/dist/esm/langchain/openai.mjs +1 -2
  311. package/dist/esm/langchain/prompts.mjs +2 -2
  312. package/dist/esm/langchain/runnables.mjs +2 -2
  313. package/dist/esm/langchain/tools.mjs +2 -2
  314. package/dist/esm/langchain/utils/env.mjs +2 -2
  315. package/dist/esm/langfuse.mjs +60 -76
  316. package/dist/esm/langfuse.mjs.map +1 -1
  317. package/dist/esm/langfuseToolOutputTracing.mjs +267 -395
  318. package/dist/esm/langfuseToolOutputTracing.mjs.map +1 -1
  319. package/dist/esm/llm/anthropic/index.mjs +432 -559
  320. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  321. package/dist/esm/llm/anthropic/types.mjs +23 -45
  322. package/dist/esm/llm/anthropic/types.mjs.map +1 -1
  323. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +439 -690
  324. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  325. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +171 -249
  326. package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
  327. package/dist/esm/llm/anthropic/utils/output_parsers.mjs +3 -0
  328. package/dist/esm/llm/anthropic/utils/tools.mjs +12 -24
  329. package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -1
  330. package/dist/esm/llm/bedrock/index.mjs +195 -238
  331. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  332. package/dist/esm/llm/bedrock/toolCache.mjs +84 -104
  333. package/dist/esm/llm/bedrock/toolCache.mjs.map +1 -1
  334. package/dist/esm/llm/bedrock/utils/index.mjs +3 -0
  335. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +357 -618
  336. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  337. package/dist/esm/llm/bedrock/utils/message_outputs.mjs +105 -147
  338. package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -1
  339. package/dist/esm/llm/fake.mjs +86 -94
  340. package/dist/esm/llm/fake.mjs.map +1 -1
  341. package/dist/esm/llm/google/index.mjs +183 -235
  342. package/dist/esm/llm/google/index.mjs.map +1 -1
  343. package/dist/esm/llm/google/utils/common.mjs +397 -666
  344. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  345. package/dist/esm/llm/google/utils/zod_to_genai_parameters.mjs +3 -0
  346. package/dist/esm/llm/init.mjs +44 -51
  347. package/dist/esm/llm/init.mjs.map +1 -1
  348. package/dist/esm/llm/invoke.mjs +142 -180
  349. package/dist/esm/llm/invoke.mjs.map +1 -1
  350. package/dist/esm/llm/openai/index.mjs +991 -1271
  351. package/dist/esm/llm/openai/index.mjs.map +1 -1
  352. package/dist/esm/llm/openai/utils/index.mjs +188 -312
  353. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  354. package/dist/esm/llm/openrouter/index.mjs +102 -151
  355. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  356. package/dist/esm/llm/openrouter/toolCache.mjs +35 -42
  357. package/dist/esm/llm/openrouter/toolCache.mjs.map +1 -1
  358. package/dist/esm/llm/providers.mjs +29 -34
  359. package/dist/esm/llm/providers.mjs.map +1 -1
  360. package/dist/esm/llm/request.mjs +20 -31
  361. package/dist/esm/llm/request.mjs.map +1 -1
  362. package/dist/esm/llm/vertexai/index.mjs +427 -449
  363. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  364. package/dist/esm/main.mjs +99 -87
  365. package/dist/esm/messages/anthropicToolCache.mjs +68 -117
  366. package/dist/esm/messages/anthropicToolCache.mjs.map +1 -1
  367. package/dist/esm/messages/cache.mjs +308 -399
  368. package/dist/esm/messages/cache.mjs.map +1 -1
  369. package/dist/esm/messages/content.mjs +36 -47
  370. package/dist/esm/messages/content.mjs.map +1 -1
  371. package/dist/esm/messages/contextPruning.mjs +112 -143
  372. package/dist/esm/messages/contextPruning.mjs.map +1 -1
  373. package/dist/esm/messages/contextPruningSettings.mjs +36 -44
  374. package/dist/esm/messages/contextPruningSettings.mjs.map +1 -1
  375. package/dist/esm/messages/core.mjs +254 -393
  376. package/dist/esm/messages/core.mjs.map +1 -1
  377. package/dist/esm/messages/format.mjs +902 -1378
  378. package/dist/esm/messages/format.mjs.map +1 -1
  379. package/dist/esm/messages/ids.mjs +16 -18
  380. package/dist/esm/messages/ids.mjs.map +1 -1
  381. package/dist/esm/messages/index.mjs +13 -0
  382. package/dist/esm/messages/langchain.mjs +18 -16
  383. package/dist/esm/messages/langchain.mjs.map +1 -1
  384. package/dist/esm/messages/prune.mjs +1053 -1514
  385. package/dist/esm/messages/prune.mjs.map +1 -1
  386. package/dist/esm/messages/recency.mjs +77 -93
  387. package/dist/esm/messages/recency.mjs.map +1 -1
  388. package/dist/esm/messages/reducer.mjs +63 -76
  389. package/dist/esm/messages/reducer.mjs.map +1 -1
  390. package/dist/esm/messages/tools.mjs +49 -75
  391. package/dist/esm/messages/tools.mjs.map +1 -1
  392. package/dist/esm/openai/index.mjs +170 -215
  393. package/dist/esm/openai/index.mjs.map +1 -1
  394. package/dist/esm/responses/index.mjs +301 -389
  395. package/dist/esm/responses/index.mjs.map +1 -1
  396. package/dist/esm/run.mjs +903 -1111
  397. package/dist/esm/run.mjs.map +1 -1
  398. package/dist/esm/session/AgentSession.mjs +806 -985
  399. package/dist/esm/session/AgentSession.mjs.map +1 -1
  400. package/dist/esm/session/JsonlSessionStore.mjs +326 -407
  401. package/dist/esm/session/JsonlSessionStore.mjs.map +1 -1
  402. package/dist/esm/session/handlers.mjs +192 -206
  403. package/dist/esm/session/handlers.mjs.map +1 -1
  404. package/dist/esm/session/ids.mjs +9 -8
  405. package/dist/esm/session/ids.mjs.map +1 -1
  406. package/dist/esm/session/index.mjs +5 -0
  407. package/dist/esm/session/messageSerialization.mjs +94 -154
  408. package/dist/esm/session/messageSerialization.mjs.map +1 -1
  409. package/dist/esm/splitStream.mjs +147 -204
  410. package/dist/esm/splitStream.mjs.map +1 -1
  411. package/dist/esm/stream.mjs +854 -1341
  412. package/dist/esm/stream.mjs.map +1 -1
  413. package/dist/esm/summarization/index.mjs +57 -99
  414. package/dist/esm/summarization/index.mjs.map +1 -1
  415. package/dist/esm/summarization/node.mjs +640 -790
  416. package/dist/esm/summarization/node.mjs.map +1 -1
  417. package/dist/esm/tools/BashExecutor.mjs +103 -129
  418. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  419. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +162 -239
  420. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  421. package/dist/esm/tools/Calculator.mjs +34 -36
  422. package/dist/esm/tools/Calculator.mjs.map +1 -1
  423. package/dist/esm/tools/CodeExecutor.mjs +123 -164
  424. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  425. package/dist/esm/tools/CodeSessionFileSummary.mjs +36 -44
  426. package/dist/esm/tools/CodeSessionFileSummary.mjs.map +1 -1
  427. package/dist/esm/tools/ProgrammaticToolCalling.mjs +454 -644
  428. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  429. package/dist/esm/tools/ReadFile.mjs +17 -18
  430. package/dist/esm/tools/ReadFile.mjs.map +1 -1
  431. package/dist/esm/tools/SkillTool.mjs +26 -25
  432. package/dist/esm/tools/SkillTool.mjs.map +1 -1
  433. package/dist/esm/tools/SubagentTool.mjs +59 -59
  434. package/dist/esm/tools/SubagentTool.mjs.map +1 -1
  435. package/dist/esm/tools/ToolNode.mjs +2107 -2684
  436. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  437. package/dist/esm/tools/ToolSearch.mjs +659 -804
  438. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  439. package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs +248 -338
  440. package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs.map +1 -1
  441. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs +170 -195
  442. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs.map +1 -1
  443. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs +424 -517
  444. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs.map +1 -1
  445. package/dist/esm/tools/cloudflare/CloudflareSandboxTools.mjs +91 -122
  446. package/dist/esm/tools/cloudflare/CloudflareSandboxTools.mjs.map +1 -1
  447. package/dist/esm/tools/cloudflare/index.mjs +5 -0
  448. package/dist/esm/tools/eagerEventExecution.mjs +75 -96
  449. package/dist/esm/tools/eagerEventExecution.mjs.map +1 -1
  450. package/dist/esm/tools/handlers.mjs +200 -260
  451. package/dist/esm/tools/handlers.mjs.map +1 -1
  452. package/dist/esm/tools/local/CompileCheckTool.mjs +150 -210
  453. package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -1
  454. package/dist/esm/tools/local/FileCheckpointer.mjs +77 -83
  455. package/dist/esm/tools/local/FileCheckpointer.mjs.map +1 -1
  456. package/dist/esm/tools/local/LocalCodingTools.mjs +760 -1017
  457. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  458. package/dist/esm/tools/local/LocalExecutionEngine.mjs +663 -936
  459. package/dist/esm/tools/local/LocalExecutionEngine.mjs.map +1 -1
  460. package/dist/esm/tools/local/LocalExecutionTools.mjs +49 -90
  461. package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -1
  462. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +283 -349
  463. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -1
  464. package/dist/esm/tools/local/attachments.mjs +108 -163
  465. package/dist/esm/tools/local/attachments.mjs.map +1 -1
  466. package/dist/esm/tools/local/bashAst.mjs +99 -111
  467. package/dist/esm/tools/local/bashAst.mjs.map +1 -1
  468. package/dist/esm/tools/local/editStrategies.mjs +126 -167
  469. package/dist/esm/tools/local/editStrategies.mjs.map +1 -1
  470. package/dist/esm/tools/local/index.mjs +13 -0
  471. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +136 -216
  472. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
  473. package/dist/esm/tools/local/syntaxCheck.mjs +138 -155
  474. package/dist/esm/tools/local/syntaxCheck.mjs.map +1 -1
  475. package/dist/esm/tools/local/textEncoding.mjs +25 -21
  476. package/dist/esm/tools/local/textEncoding.mjs.map +1 -1
  477. package/dist/esm/tools/local/workspaceFS.mjs +38 -44
  478. package/dist/esm/tools/local/workspaceFS.mjs.map +1 -1
  479. package/dist/esm/tools/ptcTimeout.mjs +27 -42
  480. package/dist/esm/tools/ptcTimeout.mjs.map +1 -1
  481. package/dist/esm/tools/schema.mjs +24 -21
  482. package/dist/esm/tools/schema.mjs.map +1 -1
  483. package/dist/esm/tools/search/anthropic.mjs +24 -31
  484. package/dist/esm/tools/search/anthropic.mjs.map +1 -1
  485. package/dist/esm/tools/search/content.mjs +93 -116
  486. package/dist/esm/tools/search/content.mjs.map +1 -1
  487. package/dist/esm/tools/search/firecrawl.mjs +139 -169
  488. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  489. package/dist/esm/tools/search/format.mjs +128 -194
  490. package/dist/esm/tools/search/format.mjs.map +1 -1
  491. package/dist/esm/tools/search/highlights.mjs +165 -230
  492. package/dist/esm/tools/search/highlights.mjs.map +1 -1
  493. package/dist/esm/tools/search/index.mjs +3 -0
  494. package/dist/esm/tools/search/rerankers.mjs +149 -168
  495. package/dist/esm/tools/search/rerankers.mjs.map +1 -1
  496. package/dist/esm/tools/search/schema.mjs +39 -37
  497. package/dist/esm/tools/search/schema.mjs.map +1 -1
  498. package/dist/esm/tools/search/search.mjs +426 -528
  499. package/dist/esm/tools/search/search.mjs.map +1 -1
  500. package/dist/esm/tools/search/serper-scraper.mjs +104 -124
  501. package/dist/esm/tools/search/serper-scraper.mjs.map +1 -1
  502. package/dist/esm/tools/search/tavily-scraper.mjs +127 -178
  503. package/dist/esm/tools/search/tavily-scraper.mjs.map +1 -1
  504. package/dist/esm/tools/search/tavily-search.mjs +293 -357
  505. package/dist/esm/tools/search/tavily-search.mjs.map +1 -1
  506. package/dist/esm/tools/search/tool.mjs +259 -297
  507. package/dist/esm/tools/search/tool.mjs.map +1 -1
  508. package/dist/esm/tools/search/utils.mjs +74 -115
  509. package/dist/esm/tools/search/utils.mjs.map +1 -1
  510. package/dist/esm/tools/skillCatalog.mjs +54 -70
  511. package/dist/esm/tools/skillCatalog.mjs.map +1 -1
  512. package/dist/esm/tools/streamedToolCallSeals.mjs +19 -31
  513. package/dist/esm/tools/streamedToolCallSeals.mjs.map +1 -1
  514. package/dist/esm/tools/subagent/SubagentExecutor.mjs +612 -768
  515. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  516. package/dist/esm/tools/subagent/index.mjs +2 -0
  517. package/dist/esm/tools/toolOutputReferences.mjs +523 -624
  518. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  519. package/dist/esm/utils/callbacks.mjs +11 -19
  520. package/dist/esm/utils/callbacks.mjs.map +1 -1
  521. package/dist/esm/utils/errors.mjs +70 -93
  522. package/dist/esm/utils/errors.mjs.map +1 -1
  523. package/dist/esm/utils/events.mjs +32 -40
  524. package/dist/esm/utils/events.mjs.map +1 -1
  525. package/dist/esm/utils/graph.mjs +8 -10
  526. package/dist/esm/utils/graph.mjs.map +1 -1
  527. package/dist/esm/utils/handlers.mjs +60 -80
  528. package/dist/esm/utils/handlers.mjs.map +1 -1
  529. package/dist/esm/utils/index.mjs +10 -0
  530. package/dist/esm/utils/llm.mjs +19 -25
  531. package/dist/esm/utils/llm.mjs.map +1 -1
  532. package/dist/esm/utils/misc.mjs +30 -44
  533. package/dist/esm/utils/misc.mjs.map +1 -1
  534. package/dist/esm/utils/run.mjs +50 -64
  535. package/dist/esm/utils/run.mjs.map +1 -1
  536. package/dist/esm/utils/schema.mjs +11 -17
  537. package/dist/esm/utils/schema.mjs.map +1 -1
  538. package/dist/esm/utils/title.mjs +71 -104
  539. package/dist/esm/utils/title.mjs.map +1 -1
  540. package/dist/esm/utils/tokens.mjs +186 -281
  541. package/dist/esm/utils/tokens.mjs.map +1 -1
  542. package/dist/esm/utils/truncation.mjs +95 -112
  543. package/dist/esm/utils/truncation.mjs.map +1 -1
  544. package/dist/types/messages/format.d.ts +5 -0
  545. package/dist/types/tools/search/tool.d.ts +17 -0
  546. package/dist/types/tools/search/types.d.ts +4 -0
  547. package/package.json +11 -17
  548. package/src/llm/anthropic/llm.spec.ts +36 -0
  549. package/src/llm/anthropic/utils/message_inputs.ts +45 -3
  550. package/src/llm/anthropic/utils/message_outputs.ts +6 -2
  551. package/src/llm/anthropic/utils/streaming-tool-input.test.ts +186 -0
  552. package/src/messages/cache.test.ts +122 -0
  553. package/src/messages/cache.ts +25 -1
  554. package/src/messages/format.ts +9 -0
  555. package/src/messages/formatAgentMessages.skills.test.ts +100 -0
  556. package/src/tools/search/highlights.ts +9 -1
  557. package/src/tools/search/search.ts +41 -3
  558. package/src/tools/search/source-processing.test.ts +373 -0
  559. package/src/tools/search/tool.ts +22 -2
  560. package/src/tools/search/types.ts +4 -0
  561. package/dist/cjs/langchain/google-common.cjs.map +0 -1
  562. package/dist/cjs/langchain/index.cjs.map +0 -1
  563. package/dist/cjs/langchain/language_models/chat_models.cjs.map +0 -1
  564. package/dist/cjs/langchain/messages/tool.cjs.map +0 -1
  565. package/dist/cjs/langchain/messages.cjs.map +0 -1
  566. package/dist/cjs/langchain/openai.cjs.map +0 -1
  567. package/dist/cjs/langchain/prompts.cjs.map +0 -1
  568. package/dist/cjs/langchain/runnables.cjs.map +0 -1
  569. package/dist/cjs/langchain/tools.cjs.map +0 -1
  570. package/dist/cjs/langchain/utils/env.cjs.map +0 -1
  571. package/dist/cjs/main.cjs.map +0 -1
  572. package/dist/esm/langchain/google-common.mjs.map +0 -1
  573. package/dist/esm/langchain/index.mjs.map +0 -1
  574. package/dist/esm/langchain/language_models/chat_models.mjs.map +0 -1
  575. package/dist/esm/langchain/messages/tool.mjs.map +0 -1
  576. package/dist/esm/langchain/messages.mjs.map +0 -1
  577. package/dist/esm/langchain/openai.mjs.map +0 -1
  578. package/dist/esm/langchain/prompts.mjs.map +0 -1
  579. package/dist/esm/langchain/runnables.mjs.map +0 -1
  580. package/dist/esm/langchain/tools.mjs.map +0 -1
  581. package/dist/esm/langchain/utils/env.mjs.map +0 -1
  582. package/dist/esm/main.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"MultiAgentGraph.cjs","sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n getCurrentTaskInput,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { ToolRunnableConfig } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst HANDOFF_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\\s*(.+)/is;\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns.\n *\n * Key behavior:\n * - Agents with ONLY handoff edges: Can dynamically route to any handoff destination\n * - Agents with ONLY direct edges: Always follow their direct edges\n * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)\n * - If handoff occurs: Only the handoff destination executes\n * - If no handoff: Direct edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either delegates (handoff)\n * OR continues its workflow (direct edges), but not both simultaneously.\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.validateEdgeAgents();\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Fails fast when an edge references an agent that is not in\n * `agentContexts`. Without this check, the underlying LangGraph\n * `StateGraph.compile()` would throw the opaque\n * `Found edge ending at unknown node \"<id>\"` error after graph\n * construction — far from the true root cause.\n *\n * This catches the common misuse of passing `edges` into a multi-agent\n * config without also passing the corresponding sub-agent configs in\n * `agents` (e.g. a host that forgot to pre-load handoff targets).\n */\n private validateEdgeAgents(): void {\n const known = new Set(this.agentContexts.keys());\n const unknown = new Set<string>();\n for (const edge of this.edges) {\n const participants = [\n ...(Array.isArray(edge.from) ? edge.from : [edge.from]),\n ...(Array.isArray(edge.to) ? edge.to : [edge.to]),\n ];\n for (const id of participants) {\n if (typeof id === 'string' && !known.has(id)) {\n unknown.add(id);\n }\n }\n }\n if (unknown.size === 0) {\n return;\n }\n const missing = Array.from(unknown)\n .map((id) => `\"${id}\"`)\n .join(', ');\n throw new Error(\n `MultiAgentGraph: edges reference agent(s) not present in agents: [${missing}]. ` +\n 'Ensure every agent referenced by an edge is also included in the `agents` array, ' +\n 'or filter orphaned edges before constructing the graph.'\n );\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\n }\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n\n // Determine if graph has parallel execution capability\n this.computeParallelCapability();\n }\n\n /**\n * Compute parallel groups by traversing the graph in execution order.\n * Assigns incrementing group IDs that reflect the sequential order of execution.\n *\n * For: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: no group (first sequential node)\n * - analyst1, analyst2, analyst3: groupId 1 (first parallel group)\n * - summarizer: no group (next sequential node)\n *\n * This allows frontend to render in order:\n * Row 0: researcher\n * Row 1: [analyst1, analyst2, analyst3] (grouped)\n * Row 2: summarizer\n */\n private computeParallelCapability(): void {\n let groupCounter = 1; // Start at 1, 0 reserved for \"no group\"\n\n // Check 1: Multiple starting nodes means parallel from the start (group 1)\n if (this.startingNodes.size > 1) {\n for (const agentId of this.startingNodes) {\n this.agentParallelGroups.set(agentId, groupCounter);\n }\n groupCounter++;\n }\n\n // Check 2: Traverse direct edges in order to find fan-out patterns\n // Build a simple execution order by following edges from starting nodes\n const visited = new Set<string>();\n const queue: string[] = [...this.startingNodes];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n // Find direct edges from this node\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n // Fan-out: multiple destinations = parallel group\n if (destinations.length > 1) {\n for (const dest of destinations) {\n // Only set if not already in a group (first group wins)\n if (!this.agentParallelGroups.has(dest)) {\n this.agentParallelGroups.set(dest, groupCounter);\n }\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n groupCounter++;\n } else {\n // Single destination - add to queue for traversal\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n\n // Also follow handoff edges for traversal (but they don't create parallel groups)\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Returns undefined if the agent is not part of a parallel group.\n * Group IDs are incrementing numbers reflecting execution order.\n */\n getParallelGroupId(agentId: string): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Override to indicate this is a multi-agent graph.\n * Enables agentId to be included in RunStep for frontend agent labeling.\n */\n protected override isMultiAgentGraph(): boolean {\n return true;\n }\n\n /**\n * Override base class method to provide parallel group IDs for run steps.\n */\n protected override getParallelGroupIdForAgent(\n agentId: string\n ): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Create handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n const sourceAgentName = agentContext.name ?? agentId;\n for (const edge of edges) {\n handoffTools.push(\n ...this.createHandoffToolsForEdge(edge, agentId, sourceAgentName)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...handoffTools);\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n * @param edge - The graph edge defining the handoff\n * @param sourceAgentId - The ID of the agent that will perform the handoff\n * @param sourceAgentName - The human-readable name of the source agent\n */\n private createHandoffToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string,\n sourceAgentName: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const state = getCurrentTaskInput() as t.BaseGraphState;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n let content = `Conditionally transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store destination for programmatic access in handoff detection */\n handoff_destination: destination,\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n let content = `Successfully transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n const state = getCurrentTaskInput() as t.BaseGraphState;\n\n /**\n * For parallel handoff support:\n * Build messages that include ONLY this tool call's context.\n * This prevents errors when LLM calls multiple transfers simultaneously -\n * each destination gets a valid AIMessage with matching tool_call and tool_result.\n *\n * Strategy:\n * 1. Find the AIMessage containing this tool call\n * 2. Create a filtered AIMessage with ONLY this tool_call\n * 3. Include all messages before the AIMessage plus the filtered pair\n */\n const messages = state.messages;\n let filteredMessages = messages;\n let aiMessageIndex = -1;\n\n /** Find the AIMessage containing this tool call */\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage;\n const hasThisCall = aiMsg.tool_calls?.some(\n (tc) => tc.id === toolCallId\n );\n if (hasThisCall === true) {\n aiMessageIndex = i;\n break;\n }\n }\n }\n\n if (aiMessageIndex >= 0) {\n const originalAiMsg = messages[aiMessageIndex] as AIMessage;\n const thisToolCall = originalAiMsg.tool_calls?.find(\n (tc) => tc.id === toolCallId\n );\n\n if (\n thisToolCall != null &&\n (originalAiMsg.tool_calls?.length ?? 0) > 1\n ) {\n /**\n * Multiple tool calls - create filtered AIMessage with ONLY this call.\n * This ensures valid message structure for parallel handoffs.\n */\n const filteredAiMsg = new AIMessage({\n content: originalAiMsg.content,\n tool_calls: [thisToolCall],\n id: originalAiMsg.id,\n });\n\n filteredMessages = [\n ...messages.slice(0, aiMessageIndex),\n filteredAiMsg,\n toolMessage,\n ];\n } else {\n /** Single tool call - use messages as-is */\n filteredMessages = messages.concat(toolMessage);\n }\n } else {\n /** Fallback - append tool message */\n filteredMessages = messages.concat(toolMessage);\n }\n\n return new Command({\n goto: destination,\n update: { messages: filteredMessages },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * Search for a transfer ToolMessage targeting this agent.\n * For parallel handoffs, multiple transfer messages may exist - find ours.\n * Search backwards from the end to find the most recent transfer to this agent.\n */\n let toolMessage: ToolMessage | null = null;\n let toolMessageIndex = -1;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'tool') continue;\n\n const candidateMsg = msg as ToolMessage;\n const toolName = candidateMsg.name;\n\n if (typeof toolName !== 'string') continue;\n\n /** Check for standard transfer pattern */\n const isTransferMessage = toolName.startsWith(Constants.LC_TRANSFER_TO_);\n const isConditionalTransfer = toolName === 'conditional_transfer';\n\n if (!isTransferMessage && !isConditionalTransfer) continue;\n\n /** Extract destination from tool name or additional_kwargs */\n let destinationAgent: string | null = null;\n\n if (isTransferMessage) {\n destinationAgent = toolName.replace(Constants.LC_TRANSFER_TO_, '');\n } else if (isConditionalTransfer) {\n const handoffDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof handoffDest === 'string' ? handoffDest : null;\n }\n\n /** Check if this transfer targets our agent */\n if (destinationAgent === agentId) {\n toolMessage = candidateMsg;\n toolMessageIndex = i;\n break;\n }\n }\n\n /** No transfer targeting this agent found */\n if (toolMessage === null || toolMessageIndex < 0) return null;\n\n /** Extract instructions from the ToolMessage content */\n const contentStr =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n const instructionsMatch = contentStr.match(HANDOFF_INSTRUCTIONS_PATTERN);\n const instructions = instructionsMatch?.[1]?.trim() ?? null;\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n\n /** Get the tool_call_id to find and filter the AI message's tool call */\n const toolCallId = toolMessage.tool_call_id;\n\n /**\n * Collect all transfer tool_call_ids to filter out.\n * For parallel handoffs, we filter ALL transfer messages (not just ours)\n * to give the receiving agent a clean context without handoff noise.\n */\n const transferToolCallIds = new Set<string>([toolCallId]);\n for (const msg of messages) {\n if (msg.getType() !== 'tool') continue;\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (typeof tName !== 'string') continue;\n if (\n tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer'\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n }\n\n /** Filter out all transfer messages */\n const filteredMessages: BaseMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const msgType = msg.getType();\n\n /** Skip transfer ToolMessages */\n if (msgType === 'tool') {\n const tm = msg as ToolMessage;\n if (transferToolCallIds.has(tm.tool_call_id)) {\n continue;\n }\n }\n\n if (msgType === 'ai') {\n /** Check if this AI message contains any transfer tool calls */\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Filter out all transfer tool calls */\n const remainingToolCalls = toolCalls.filter(\n (tc) => tc.id == null || !transferToolCallIds.has(tc.id)\n );\n\n const hasTransferCalls = remainingToolCalls.length < toolCalls.length;\n\n if (hasTransferCalls) {\n if (\n remainingToolCalls.length > 0 ||\n (typeof aiMsg.content === 'string' && aiMsg.content.trim())\n ) {\n /** Keep the message but without transfer tool calls */\n const filteredAiMsg = new AIMessage({\n content: aiMsg.content,\n tool_calls: remainingToolCalls,\n id: aiMsg.id,\n });\n filteredMessages.push(filteredAiMsg);\n }\n /** If no remaining content or tool calls, skip this message entirely */\n continue;\n }\n }\n }\n\n /** Keep all other messages */\n filteredMessages.push(msg);\n }\n\n return {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n // Add all agents as complete subgraphs\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => directDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH handoff and direct edges */\n const hasHandoffEdges = handoffDestinations.size > 0;\n const hasDirectEdges = directDestinations.size > 0;\n const needsCommandRouting = hasHandoffEdges && hasDirectEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...handoffDestinations,\n ...directDestinations,\n ]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState,\n config?: LangGraphRunnableConfig\n ): Promise<t.MultiAgentGraphState | Command> => {\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a handoff.\n * If so, filter out the transfer messages and inject instructions as preamble.\n * This prevents the receiving agent from seeing the transfer as \"completed work\"\n * and prematurely producing an end token.\n */\n const handoffContext = this.processHandoffReception(\n state.messages,\n agentId\n );\n\n if (handoffContext !== null) {\n const {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n } = handoffContext;\n\n /**\n * Set handoff context on the receiving agent.\n * Uses pre-computed graph position for depth and parallel info.\n */\n const agentContext = this.agentContexts.get(agentId);\n if (\n agentContext &&\n sourceAgentName != null &&\n sourceAgentName !== ''\n ) {\n agentContext.setHandoffContext(sourceAgentName, parallelSiblings);\n }\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n new HumanMessage(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n new HumanMessage(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n agentMessages: [],\n };\n } else if (\n state.agentMessages != null &&\n state.agentMessages.length > 0\n ) {\n /**\n * When using agentMessages (excludeResults=true), we need to update\n * the token map to account for the new prompt message\n */\n const agentContext = this.agentContexts.get(agentId);\n if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** If agent has both handoff and direct edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a handoff occurred */\n const lastMessage = result.messages[\n result.messages.length - 1\n ] as BaseMessage | null;\n if (\n lastMessage != null &&\n lastMessage.getType() === 'tool' &&\n typeof lastMessage.name === 'string' &&\n lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) {\n /** Handoff occurred - extract destination and navigate there exclusively */\n const handoffDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n return new Command({\n update: result,\n goto: handoffDest,\n });\n } else {\n /** No handoff - proceed with direct edges */\n const directDests = Array.from(directDestinations);\n if (directDests.length === 1) {\n return new Command({\n update: result,\n goto: directDests[0],\n });\n } else if (directDests.length > 1) {\n /** Multiple direct destinations - they'll run in parallel */\n return new Command({\n update: result,\n goto: directDests,\n });\n }\n }\n }\n\n /** No special routing needed - return state normally */\n return result;\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(allDestinations),\n });\n }\n\n // Add starting edges for all starting nodes\n for (const startNode of this.startingNodes) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(START, startNode);\n }\n\n /**\n * Add direct edges for automatic transitions\n * Group edges by destination to handle fan-in scenarios\n */\n const edgesByDestination = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.directEdges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n if (!edgesByDestination.has(destination)) {\n edgesByDestination.set(destination, []);\n }\n edgesByDestination.get(destination)!.push(edge);\n }\n }\n\n for (const [destination, edges] of edgesByDestination) {\n /** Checks if this is a fan-in scenario with prompt instructions */\n const edgesWithPrompt = edges.filter(\n (edge) => edge.prompt != null && edge.prompt !== ''\n );\n\n if (edgesWithPrompt.length > 0) {\n /**\n * Single wrapper node for destination (Fan-in with prompt)\n */\n const wrapperNodeId = `fan_in_${destination}_prompt`;\n /**\n * First edge's `prompt`\n * (they should all be the same for fan-in)\n */\n const prompt = edgesWithPrompt[0].prompt;\n /**\n * First edge's `excludeResults` flag\n * (they should all be the same for fan-in)\n */\n const excludeResults = edgesWithPrompt[0].excludeResults;\n\n builder.addNode(wrapperNodeId, async (state: t.BaseGraphState) => {\n let promptText: string | undefined;\n let effectiveExcludeResults = excludeResults;\n\n if (typeof prompt === 'function') {\n promptText = await prompt(state.messages, this.startIndex);\n } else if (prompt != null) {\n if (prompt.includes('{results}')) {\n const resultsMessages = state.messages.slice(this.startIndex);\n const resultsString = getBufferString(resultsMessages);\n const promptTemplate = PromptTemplate.fromTemplate(prompt);\n const result = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = result.value;\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [new HumanMessage(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n const promptMessage = new HumanMessage(promptText);\n return {\n messages: [promptMessage],\n agentMessages: messagesStateReducer(filteredMessages, [\n promptMessage,\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges (skip if source uses Command routing) */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n /** Check if this source node has both handoff and direct edges */\n const sourceHandoffEdges = this.handoffEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceDirectEdges = this.directEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n\n /** Skip adding edge if source uses Command routing (has both types) */\n if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n }\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"names":["StandardGraph","tools","tool","getCurrentTaskInput","ToolMessage","Command","Constants","messages","AIMessage","Annotation","messagesStateReducer","StateGraph","END","HumanMessage","START","getBufferString","PromptTemplate"],"mappings":";;;;;;;;;AAwBA;AACA,MAAM,4BAA4B,GAAG,qCAAqC;AAE1E;;;;;;;;;;;;;AAaG;AACG,MAAO,eAAgB,SAAQA,mBAAa,CAAA;AACxC,IAAA,KAAK;AACL,IAAA,aAAa,GAAgB,IAAI,GAAG,EAAE;IACtC,WAAW,GAAkB,EAAE;IAC/B,YAAY,GAAkB,EAAE;AACxC;;;;;;;;;AASG;AACK,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AAE5D,IAAA,WAAA,CAAY,KAA6B,EAAA;QACvC,KAAK,CAAC,KAAK,CAAC;AACZ,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK;QACxB,IAAI,CAAC,kBAAkB,EAAE;QACzB,IAAI,CAAC,eAAe,EAAE;QACtB,IAAI,CAAC,YAAY,EAAE;QACnB,IAAI,CAAC,kBAAkB,EAAE;IAC3B;AAEA;;;;;;;;;;AAUG;IACK,kBAAkB,GAAA;AACxB,QAAA,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC;A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AO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;AAClE,oBAAA,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;;wBAE5B,MAAM,kBAAkB,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,KAAI;4BACxD,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,4BAAA,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClC,wBAAA,CAAC,CAAC;wBACF,MAAM,iBAAiB,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,KAAI;4BACtD,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,4BAAA,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClC,wBAAA,CAAC,CAAC;;AAGF,wBAAA,IAAI,kBAAkB,CAAC,MAAM,GAAG,CAAC,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE;4BACjE;wBACF;;;AAIA,wBAAA,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC;oBACtC;gBACF;YACF;QACF;QAEA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,cAAkC,CAAC;IACjE;AACD;;;;"}
1
+ {"version":3,"file":"MultiAgentGraph.cjs","names":["StandardGraph","ToolMessage","Command","aiMsg","AIMessage","StateGraph","Annotation","END","HumanMessage","START","PromptTemplate"],"sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n getCurrentTaskInput,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { ToolRunnableConfig } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst HANDOFF_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\\s*(.+)/is;\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns.\n *\n * Key behavior:\n * - Agents with ONLY handoff edges: Can dynamically route to any handoff destination\n * - Agents with ONLY direct edges: Always follow their direct edges\n * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)\n * - If handoff occurs: Only the handoff destination executes\n * - If no handoff: Direct edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either delegates (handoff)\n * OR continues its workflow (direct edges), but not both simultaneously.\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.validateEdgeAgents();\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Fails fast when an edge references an agent that is not in\n * `agentContexts`. Without this check, the underlying LangGraph\n * `StateGraph.compile()` would throw the opaque\n * `Found edge ending at unknown node \"<id>\"` error after graph\n * construction — far from the true root cause.\n *\n * This catches the common misuse of passing `edges` into a multi-agent\n * config without also passing the corresponding sub-agent configs in\n * `agents` (e.g. a host that forgot to pre-load handoff targets).\n */\n private validateEdgeAgents(): void {\n const known = new Set(this.agentContexts.keys());\n const unknown = new Set<string>();\n for (const edge of this.edges) {\n const participants = [\n ...(Array.isArray(edge.from) ? edge.from : [edge.from]),\n ...(Array.isArray(edge.to) ? edge.to : [edge.to]),\n ];\n for (const id of participants) {\n if (typeof id === 'string' && !known.has(id)) {\n unknown.add(id);\n }\n }\n }\n if (unknown.size === 0) {\n return;\n }\n const missing = Array.from(unknown)\n .map((id) => `\"${id}\"`)\n .join(', ');\n throw new Error(\n `MultiAgentGraph: edges reference agent(s) not present in agents: [${missing}]. ` +\n 'Ensure every agent referenced by an edge is also included in the `agents` array, ' +\n 'or filter orphaned edges before constructing the graph.'\n );\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\n }\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n\n // Determine if graph has parallel execution capability\n this.computeParallelCapability();\n }\n\n /**\n * Compute parallel groups by traversing the graph in execution order.\n * Assigns incrementing group IDs that reflect the sequential order of execution.\n *\n * For: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: no group (first sequential node)\n * - analyst1, analyst2, analyst3: groupId 1 (first parallel group)\n * - summarizer: no group (next sequential node)\n *\n * This allows frontend to render in order:\n * Row 0: researcher\n * Row 1: [analyst1, analyst2, analyst3] (grouped)\n * Row 2: summarizer\n */\n private computeParallelCapability(): void {\n let groupCounter = 1; // Start at 1, 0 reserved for \"no group\"\n\n // Check 1: Multiple starting nodes means parallel from the start (group 1)\n if (this.startingNodes.size > 1) {\n for (const agentId of this.startingNodes) {\n this.agentParallelGroups.set(agentId, groupCounter);\n }\n groupCounter++;\n }\n\n // Check 2: Traverse direct edges in order to find fan-out patterns\n // Build a simple execution order by following edges from starting nodes\n const visited = new Set<string>();\n const queue: string[] = [...this.startingNodes];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n // Find direct edges from this node\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n // Fan-out: multiple destinations = parallel group\n if (destinations.length > 1) {\n for (const dest of destinations) {\n // Only set if not already in a group (first group wins)\n if (!this.agentParallelGroups.has(dest)) {\n this.agentParallelGroups.set(dest, groupCounter);\n }\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n groupCounter++;\n } else {\n // Single destination - add to queue for traversal\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n\n // Also follow handoff edges for traversal (but they don't create parallel groups)\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Returns undefined if the agent is not part of a parallel group.\n * Group IDs are incrementing numbers reflecting execution order.\n */\n getParallelGroupId(agentId: string): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Override to indicate this is a multi-agent graph.\n * Enables agentId to be included in RunStep for frontend agent labeling.\n */\n protected override isMultiAgentGraph(): boolean {\n return true;\n }\n\n /**\n * Override base class method to provide parallel group IDs for run steps.\n */\n protected override getParallelGroupIdForAgent(\n agentId: string\n ): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Create handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n const sourceAgentName = agentContext.name ?? agentId;\n for (const edge of edges) {\n handoffTools.push(\n ...this.createHandoffToolsForEdge(edge, agentId, sourceAgentName)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...handoffTools);\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n * @param edge - The graph edge defining the handoff\n * @param sourceAgentId - The ID of the agent that will perform the handoff\n * @param sourceAgentName - The human-readable name of the source agent\n */\n private createHandoffToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string,\n sourceAgentName: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const state = getCurrentTaskInput() as t.BaseGraphState;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n let content = `Conditionally transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store destination for programmatic access in handoff detection */\n handoff_destination: destination,\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n let content = `Successfully transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n const state = getCurrentTaskInput() as t.BaseGraphState;\n\n /**\n * For parallel handoff support:\n * Build messages that include ONLY this tool call's context.\n * This prevents errors when LLM calls multiple transfers simultaneously -\n * each destination gets a valid AIMessage with matching tool_call and tool_result.\n *\n * Strategy:\n * 1. Find the AIMessage containing this tool call\n * 2. Create a filtered AIMessage with ONLY this tool_call\n * 3. Include all messages before the AIMessage plus the filtered pair\n */\n const messages = state.messages;\n let filteredMessages = messages;\n let aiMessageIndex = -1;\n\n /** Find the AIMessage containing this tool call */\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage;\n const hasThisCall = aiMsg.tool_calls?.some(\n (tc) => tc.id === toolCallId\n );\n if (hasThisCall === true) {\n aiMessageIndex = i;\n break;\n }\n }\n }\n\n if (aiMessageIndex >= 0) {\n const originalAiMsg = messages[aiMessageIndex] as AIMessage;\n const thisToolCall = originalAiMsg.tool_calls?.find(\n (tc) => tc.id === toolCallId\n );\n\n if (\n thisToolCall != null &&\n (originalAiMsg.tool_calls?.length ?? 0) > 1\n ) {\n /**\n * Multiple tool calls - create filtered AIMessage with ONLY this call.\n * This ensures valid message structure for parallel handoffs.\n */\n const filteredAiMsg = new AIMessage({\n content: originalAiMsg.content,\n tool_calls: [thisToolCall],\n id: originalAiMsg.id,\n });\n\n filteredMessages = [\n ...messages.slice(0, aiMessageIndex),\n filteredAiMsg,\n toolMessage,\n ];\n } else {\n /** Single tool call - use messages as-is */\n filteredMessages = messages.concat(toolMessage);\n }\n } else {\n /** Fallback - append tool message */\n filteredMessages = messages.concat(toolMessage);\n }\n\n return new Command({\n goto: destination,\n update: { messages: filteredMessages },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * Search for a transfer ToolMessage targeting this agent.\n * For parallel handoffs, multiple transfer messages may exist - find ours.\n * Search backwards from the end to find the most recent transfer to this agent.\n */\n let toolMessage: ToolMessage | null = null;\n let toolMessageIndex = -1;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'tool') continue;\n\n const candidateMsg = msg as ToolMessage;\n const toolName = candidateMsg.name;\n\n if (typeof toolName !== 'string') continue;\n\n /** Check for standard transfer pattern */\n const isTransferMessage = toolName.startsWith(Constants.LC_TRANSFER_TO_);\n const isConditionalTransfer = toolName === 'conditional_transfer';\n\n if (!isTransferMessage && !isConditionalTransfer) continue;\n\n /** Extract destination from tool name or additional_kwargs */\n let destinationAgent: string | null = null;\n\n if (isTransferMessage) {\n destinationAgent = toolName.replace(Constants.LC_TRANSFER_TO_, '');\n } else if (isConditionalTransfer) {\n const handoffDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof handoffDest === 'string' ? handoffDest : null;\n }\n\n /** Check if this transfer targets our agent */\n if (destinationAgent === agentId) {\n toolMessage = candidateMsg;\n toolMessageIndex = i;\n break;\n }\n }\n\n /** No transfer targeting this agent found */\n if (toolMessage === null || toolMessageIndex < 0) return null;\n\n /** Extract instructions from the ToolMessage content */\n const contentStr =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n const instructionsMatch = contentStr.match(HANDOFF_INSTRUCTIONS_PATTERN);\n const instructions = instructionsMatch?.[1]?.trim() ?? null;\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n\n /** Get the tool_call_id to find and filter the AI message's tool call */\n const toolCallId = toolMessage.tool_call_id;\n\n /**\n * Collect all transfer tool_call_ids to filter out.\n * For parallel handoffs, we filter ALL transfer messages (not just ours)\n * to give the receiving agent a clean context without handoff noise.\n */\n const transferToolCallIds = new Set<string>([toolCallId]);\n for (const msg of messages) {\n if (msg.getType() !== 'tool') continue;\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (typeof tName !== 'string') continue;\n if (\n tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer'\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n }\n\n /** Filter out all transfer messages */\n const filteredMessages: BaseMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const msgType = msg.getType();\n\n /** Skip transfer ToolMessages */\n if (msgType === 'tool') {\n const tm = msg as ToolMessage;\n if (transferToolCallIds.has(tm.tool_call_id)) {\n continue;\n }\n }\n\n if (msgType === 'ai') {\n /** Check if this AI message contains any transfer tool calls */\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Filter out all transfer tool calls */\n const remainingToolCalls = toolCalls.filter(\n (tc) => tc.id == null || !transferToolCallIds.has(tc.id)\n );\n\n const hasTransferCalls = remainingToolCalls.length < toolCalls.length;\n\n if (hasTransferCalls) {\n if (\n remainingToolCalls.length > 0 ||\n (typeof aiMsg.content === 'string' && aiMsg.content.trim())\n ) {\n /** Keep the message but without transfer tool calls */\n const filteredAiMsg = new AIMessage({\n content: aiMsg.content,\n tool_calls: remainingToolCalls,\n id: aiMsg.id,\n });\n filteredMessages.push(filteredAiMsg);\n }\n /** If no remaining content or tool calls, skip this message entirely */\n continue;\n }\n }\n }\n\n /** Keep all other messages */\n filteredMessages.push(msg);\n }\n\n return {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n // Add all agents as complete subgraphs\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => directDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH handoff and direct edges */\n const hasHandoffEdges = handoffDestinations.size > 0;\n const hasDirectEdges = directDestinations.size > 0;\n const needsCommandRouting = hasHandoffEdges && hasDirectEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...handoffDestinations,\n ...directDestinations,\n ]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState,\n config?: LangGraphRunnableConfig\n ): Promise<t.MultiAgentGraphState | Command> => {\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a handoff.\n * If so, filter out the transfer messages and inject instructions as preamble.\n * This prevents the receiving agent from seeing the transfer as \"completed work\"\n * and prematurely producing an end token.\n */\n const handoffContext = this.processHandoffReception(\n state.messages,\n agentId\n );\n\n if (handoffContext !== null) {\n const {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n } = handoffContext;\n\n /**\n * Set handoff context on the receiving agent.\n * Uses pre-computed graph position for depth and parallel info.\n */\n const agentContext = this.agentContexts.get(agentId);\n if (\n agentContext &&\n sourceAgentName != null &&\n sourceAgentName !== ''\n ) {\n agentContext.setHandoffContext(sourceAgentName, parallelSiblings);\n }\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n new HumanMessage(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n new HumanMessage(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n agentMessages: [],\n };\n } else if (\n state.agentMessages != null &&\n state.agentMessages.length > 0\n ) {\n /**\n * When using agentMessages (excludeResults=true), we need to update\n * the token map to account for the new prompt message\n */\n const agentContext = this.agentContexts.get(agentId);\n if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** If agent has both handoff and direct edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a handoff occurred */\n const lastMessage = result.messages[\n result.messages.length - 1\n ] as BaseMessage | null;\n if (\n lastMessage != null &&\n lastMessage.getType() === 'tool' &&\n typeof lastMessage.name === 'string' &&\n lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) {\n /** Handoff occurred - extract destination and navigate there exclusively */\n const handoffDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n return new Command({\n update: result,\n goto: handoffDest,\n });\n } else {\n /** No handoff - proceed with direct edges */\n const directDests = Array.from(directDestinations);\n if (directDests.length === 1) {\n return new Command({\n update: result,\n goto: directDests[0],\n });\n } else if (directDests.length > 1) {\n /** Multiple direct destinations - they'll run in parallel */\n return new Command({\n update: result,\n goto: directDests,\n });\n }\n }\n }\n\n /** No special routing needed - return state normally */\n return result;\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(allDestinations),\n });\n }\n\n // Add starting edges for all starting nodes\n for (const startNode of this.startingNodes) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(START, startNode);\n }\n\n /**\n * Add direct edges for automatic transitions\n * Group edges by destination to handle fan-in scenarios\n */\n const edgesByDestination = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.directEdges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n if (!edgesByDestination.has(destination)) {\n edgesByDestination.set(destination, []);\n }\n edgesByDestination.get(destination)!.push(edge);\n }\n }\n\n for (const [destination, edges] of edgesByDestination) {\n /** Checks if this is a fan-in scenario with prompt instructions */\n const edgesWithPrompt = edges.filter(\n (edge) => edge.prompt != null && edge.prompt !== ''\n );\n\n if (edgesWithPrompt.length > 0) {\n /**\n * Single wrapper node for destination (Fan-in with prompt)\n */\n const wrapperNodeId = `fan_in_${destination}_prompt`;\n /**\n * First edge's `prompt`\n * (they should all be the same for fan-in)\n */\n const prompt = edgesWithPrompt[0].prompt;\n /**\n * First edge's `excludeResults` flag\n * (they should all be the same for fan-in)\n */\n const excludeResults = edgesWithPrompt[0].excludeResults;\n\n builder.addNode(wrapperNodeId, async (state: t.BaseGraphState) => {\n let promptText: string | undefined;\n let effectiveExcludeResults = excludeResults;\n\n if (typeof prompt === 'function') {\n promptText = await prompt(state.messages, this.startIndex);\n } else if (prompt != null) {\n if (prompt.includes('{results}')) {\n const resultsMessages = state.messages.slice(this.startIndex);\n const resultsString = getBufferString(resultsMessages);\n const promptTemplate = PromptTemplate.fromTemplate(prompt);\n const result = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = result.value;\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [new HumanMessage(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n const promptMessage = new HumanMessage(promptText);\n return {\n messages: [promptMessage],\n agentMessages: messagesStateReducer(filteredMessages, [\n promptMessage,\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges (skip if source uses Command routing) */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n /** Check if this source node has both handoff and direct edges */\n const sourceHandoffEdges = this.handoffEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceDirectEdges = this.directEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n\n /** Skip adding edge if source uses Command routing (has both types) */\n if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n }\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"mappings":";;;;;;;;;AAyBA,MAAM,+BAA+B;;;;;;;;;;;;;;;AAgBrC,IAAa,kBAAb,cAAqCA,cAAAA,cAAc;CACjD;CACA,gCAAqC,IAAI,IAAI;CAC7C,cAAqC,CAAC;CACtC,eAAsC,CAAC;;;;;;;;;;;CAWvC,sCAAmD,IAAI,IAAI;CAE3D,YAAY,OAA+B;EACzC,MAAM,KAAK;EACX,KAAK,QAAQ,MAAM;EACnB,KAAK,mBAAmB;EACxB,KAAK,gBAAgB;EACrB,KAAK,aAAa;EAClB,KAAK,mBAAmB;CAC1B;;;;;;;;;;;;CAaA,qBAAmC;EACjC,MAAM,QAAQ,IAAI,IAAI,KAAK,cAAc,KAAK,CAAC;EAC/C,MAAM,0BAAU,IAAI,IAAY;EAChC,KAAK,MAAM,QAAQ,KAAK,OAAO;GAC7B,MAAM,eAAe,CACnB,GAAI,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAA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,MAAM,qBAAqB,KAAK,aAAa,QAAQ,MAAM;MAEzD,QADiB,MAAM,QAAQ,EAAE,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,CAAC;KACD,MAAM,oBAAoB,KAAK,YAAY,QAAQ,MAAM;MAEvD,QADiB,MAAM,QAAQ,EAAE,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,CAAC;;KAGD,IAAI,mBAAmB,SAAS,KAAK,kBAAkB,SAAS,GAC9D;;KAKF,QAAQ,QAAQ,QAAQ,WAAW;IACrC;GACF;EAEJ;EAEA,OAAO,QAAQ,QAAQ,KAAK,cAAkC;CAChE;AACF"}
@@ -0,0 +1,2 @@
1
+ require("./Graph.cjs");
2
+ require("./MultiAgentGraph.cjs");
@@ -1,67 +1,65 @@
1
- 'use strict';
2
-
3
- var langgraph = require('@langchain/langgraph');
4
-
1
+ let _langchain_langgraph = require("@langchain/langgraph");
2
+ //#region src/hitl/askUserQuestion.ts
5
3
  /**
6
- * Typed convenience wrapper around LangGraph's `interrupt()` for the
7
- * `ask_user_question` interrupt category. Lets a custom graph node
8
- * (or a tool implementation) suspend execution to collect a free-form
9
- * answer from the human, without the host having to assemble the
10
- * interrupt payload by hand. The companion to `Run.resume(answer)` on
11
- * the host side.
12
- *
13
- * AsyncLocalStorage anchoring: this helper does NOT call
14
- * `runWithConfig` itself — it expects to be invoked from inside a
15
- * LangGraph node where the framework has already established the
16
- * runnable config. ToolNode is the one place in this codebase that
17
- * needs the manual `runWithConfig` shim, because its
18
- * `RunnableCallable.trace = false` skips the upstream tracing path
19
- * that normally sets up the AsyncLocalStorage frame; ordinary user
20
- * nodes (RunnableLambda, addNode callbacks) do not have that
21
- * constraint.
22
- */
4
+ * Typed convenience wrapper around LangGraph's `interrupt()` for the
5
+ * `ask_user_question` interrupt category. Lets a custom graph node
6
+ * (or a tool implementation) suspend execution to collect a free-form
7
+ * answer from the human, without the host having to assemble the
8
+ * interrupt payload by hand. The companion to `Run.resume(answer)` on
9
+ * the host side.
10
+ *
11
+ * AsyncLocalStorage anchoring: this helper does NOT call
12
+ * `runWithConfig` itself — it expects to be invoked from inside a
13
+ * LangGraph node where the framework has already established the
14
+ * runnable config. ToolNode is the one place in this codebase that
15
+ * needs the manual `runWithConfig` shim, because its
16
+ * `RunnableCallable.trace = false` skips the upstream tracing path
17
+ * that normally sets up the AsyncLocalStorage frame; ordinary user
18
+ * nodes (RunnableLambda, addNode callbacks) do not have that
19
+ * constraint.
20
+ */
23
21
  /**
24
- * Suspend the current graph node to ask the human a question. Returns
25
- * the host-supplied resolution after `Run.resume(resolution)` is
26
- * called against a Run rebuilt with the same `thread_id` and
27
- * checkpointer.
28
- *
29
- * On the FIRST call (no resume value available), `interrupt()` throws
30
- * a `GraphInterrupt` that LangGraph catches; this function does not
31
- * return — execution unwinds, the SDK persists the checkpoint, and
32
- * the run completes with `run.getInterrupt()` returning a
33
- * `RunInterruptResult` whose `payload` is an
34
- * `AskUserQuestionInterruptPayload`.
35
- *
36
- * On RESUME, LangGraph re-runs the node from the start and this call
37
- * returns the host's `AskUserQuestionResolution` directly.
38
- *
39
- * Hosts that prefer the raw `interrupt()` (e.g., to attach extra
40
- * metadata) can construct an `AskUserQuestionInterruptPayload` and
41
- * call `interrupt()` themselves — this helper is purely convenience.
42
- *
43
- * @example
44
- * ```ts
45
- * const builder = new StateGraph(MessagesAnnotation)
46
- * .addNode('clarifier', () => {
47
- * const { answer } = askUserQuestion({
48
- * question: 'Which environment should I deploy to?',
49
- * options: [
50
- * { label: 'Staging', value: 'staging' },
51
- * { label: 'Production', value: 'production' },
52
- * ],
53
- * });
54
- * return { messages: [new HumanMessage(`Use ${answer}`)] };
55
- * });
56
- * ```
57
- */
22
+ * Suspend the current graph node to ask the human a question. Returns
23
+ * the host-supplied resolution after `Run.resume(resolution)` is
24
+ * called against a Run rebuilt with the same `thread_id` and
25
+ * checkpointer.
26
+ *
27
+ * On the FIRST call (no resume value available), `interrupt()` throws
28
+ * a `GraphInterrupt` that LangGraph catches; this function does not
29
+ * return — execution unwinds, the SDK persists the checkpoint, and
30
+ * the run completes with `run.getInterrupt()` returning a
31
+ * `RunInterruptResult` whose `payload` is an
32
+ * `AskUserQuestionInterruptPayload`.
33
+ *
34
+ * On RESUME, LangGraph re-runs the node from the start and this call
35
+ * returns the host's `AskUserQuestionResolution` directly.
36
+ *
37
+ * Hosts that prefer the raw `interrupt()` (e.g., to attach extra
38
+ * metadata) can construct an `AskUserQuestionInterruptPayload` and
39
+ * call `interrupt()` themselves — this helper is purely convenience.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const builder = new StateGraph(MessagesAnnotation)
44
+ * .addNode('clarifier', () => {
45
+ * const { answer } = askUserQuestion({
46
+ * question: 'Which environment should I deploy to?',
47
+ * options: [
48
+ * { label: 'Staging', value: 'staging' },
49
+ * { label: 'Production', value: 'production' },
50
+ * ],
51
+ * });
52
+ * return { messages: [new HumanMessage(`Use ${answer}`)] };
53
+ * });
54
+ * ```
55
+ */
58
56
  function askUserQuestion(question) {
59
- const payload = {
60
- type: 'ask_user_question',
61
- question,
62
- };
63
- return langgraph.interrupt(payload);
57
+ return (0, _langchain_langgraph.interrupt)({
58
+ type: "ask_user_question",
59
+ question
60
+ });
64
61
  }
65
-
62
+ //#endregion
66
63
  exports.askUserQuestion = askUserQuestion;
67
- //# sourceMappingURL=askUserQuestion.cjs.map
64
+
65
+ //# sourceMappingURL=askUserQuestion.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"askUserQuestion.cjs","sources":["../../../src/hitl/askUserQuestion.ts"],"sourcesContent":["/**\n * Typed convenience wrapper around LangGraph's `interrupt()` for the\n * `ask_user_question` interrupt category. Lets a custom graph node\n * (or a tool implementation) suspend execution to collect a free-form\n * answer from the human, without the host having to assemble the\n * interrupt payload by hand. The companion to `Run.resume(answer)` on\n * the host side.\n *\n * AsyncLocalStorage anchoring: this helper does NOT call\n * `runWithConfig` itself — it expects to be invoked from inside a\n * LangGraph node where the framework has already established the\n * runnable config. ToolNode is the one place in this codebase that\n * needs the manual `runWithConfig` shim, because its\n * `RunnableCallable.trace = false` skips the upstream tracing path\n * that normally sets up the AsyncLocalStorage frame; ordinary user\n * nodes (RunnableLambda, addNode callbacks) do not have that\n * constraint.\n */\n\nimport { interrupt } from '@langchain/langgraph';\nimport type {\n AskUserQuestionRequest,\n AskUserQuestionResolution,\n AskUserQuestionInterruptPayload,\n} from '@/types/hitl';\n\n/**\n * Suspend the current graph node to ask the human a question. Returns\n * the host-supplied resolution after `Run.resume(resolution)` is\n * called against a Run rebuilt with the same `thread_id` and\n * checkpointer.\n *\n * On the FIRST call (no resume value available), `interrupt()` throws\n * a `GraphInterrupt` that LangGraph catches; this function does not\n * return — execution unwinds, the SDK persists the checkpoint, and\n * the run completes with `run.getInterrupt()` returning a\n * `RunInterruptResult` whose `payload` is an\n * `AskUserQuestionInterruptPayload`.\n *\n * On RESUME, LangGraph re-runs the node from the start and this call\n * returns the host's `AskUserQuestionResolution` directly.\n *\n * Hosts that prefer the raw `interrupt()` (e.g., to attach extra\n * metadata) can construct an `AskUserQuestionInterruptPayload` and\n * call `interrupt()` themselves — this helper is purely convenience.\n *\n * @example\n * ```ts\n * const builder = new StateGraph(MessagesAnnotation)\n * .addNode('clarifier', () => {\n * const { answer } = askUserQuestion({\n * question: 'Which environment should I deploy to?',\n * options: [\n * { label: 'Staging', value: 'staging' },\n * { label: 'Production', value: 'production' },\n * ],\n * });\n * return { messages: [new HumanMessage(`Use ${answer}`)] };\n * });\n * ```\n */\nexport function askUserQuestion(\n question: AskUserQuestionRequest\n): AskUserQuestionResolution {\n const payload: AskUserQuestionInterruptPayload = {\n type: 'ask_user_question',\n question,\n };\n return interrupt<AskUserQuestionInterruptPayload, AskUserQuestionResolution>(\n payload\n );\n}\n"],"names":["interrupt"],"mappings":";;;;AAAA;;;;;;;;;;;;;;;;;AAiBG;AASH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCG;AACG,SAAU,eAAe,CAC7B,QAAgC,EAAA;AAEhC,IAAA,MAAM,OAAO,GAAoC;AAC/C,QAAA,IAAI,EAAE,mBAAmB;QACzB,QAAQ;KACT;AACD,IAAA,OAAOA,mBAAS,CACd,OAAO,CACR;AACH;;;;"}
1
+ {"version":3,"file":"askUserQuestion.cjs","names":[],"sources":["../../../src/hitl/askUserQuestion.ts"],"sourcesContent":["/**\n * Typed convenience wrapper around LangGraph's `interrupt()` for the\n * `ask_user_question` interrupt category. Lets a custom graph node\n * (or a tool implementation) suspend execution to collect a free-form\n * answer from the human, without the host having to assemble the\n * interrupt payload by hand. The companion to `Run.resume(answer)` on\n * the host side.\n *\n * AsyncLocalStorage anchoring: this helper does NOT call\n * `runWithConfig` itself — it expects to be invoked from inside a\n * LangGraph node where the framework has already established the\n * runnable config. ToolNode is the one place in this codebase that\n * needs the manual `runWithConfig` shim, because its\n * `RunnableCallable.trace = false` skips the upstream tracing path\n * that normally sets up the AsyncLocalStorage frame; ordinary user\n * nodes (RunnableLambda, addNode callbacks) do not have that\n * constraint.\n */\n\nimport { interrupt } from '@langchain/langgraph';\nimport type {\n AskUserQuestionRequest,\n AskUserQuestionResolution,\n AskUserQuestionInterruptPayload,\n} from '@/types/hitl';\n\n/**\n * Suspend the current graph node to ask the human a question. Returns\n * the host-supplied resolution after `Run.resume(resolution)` is\n * called against a Run rebuilt with the same `thread_id` and\n * checkpointer.\n *\n * On the FIRST call (no resume value available), `interrupt()` throws\n * a `GraphInterrupt` that LangGraph catches; this function does not\n * return — execution unwinds, the SDK persists the checkpoint, and\n * the run completes with `run.getInterrupt()` returning a\n * `RunInterruptResult` whose `payload` is an\n * `AskUserQuestionInterruptPayload`.\n *\n * On RESUME, LangGraph re-runs the node from the start and this call\n * returns the host's `AskUserQuestionResolution` directly.\n *\n * Hosts that prefer the raw `interrupt()` (e.g., to attach extra\n * metadata) can construct an `AskUserQuestionInterruptPayload` and\n * call `interrupt()` themselves — this helper is purely convenience.\n *\n * @example\n * ```ts\n * const builder = new StateGraph(MessagesAnnotation)\n * .addNode('clarifier', () => {\n * const { answer } = askUserQuestion({\n * question: 'Which environment should I deploy to?',\n * options: [\n * { label: 'Staging', value: 'staging' },\n * { label: 'Production', value: 'production' },\n * ],\n * });\n * return { messages: [new HumanMessage(`Use ${answer}`)] };\n * });\n * ```\n */\nexport function askUserQuestion(\n question: AskUserQuestionRequest\n): AskUserQuestionResolution {\n const payload: AskUserQuestionInterruptPayload = {\n type: 'ask_user_question',\n question,\n };\n return interrupt<AskUserQuestionInterruptPayload, AskUserQuestionResolution>(\n payload\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,SAAgB,gBACd,UAC2B;CAK3B,QAAA,GAAA,qBAAA,UAAA,CACE;EAJA,MAAM;EACN;CAGM,CACR;AACF"}
@@ -0,0 +1 @@
1
+ require("./askUserQuestion.cjs");