langchain 1.2.24 → 1.2.25

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 (325) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/_virtual/{rolldown_runtime.cjs → _rolldown/runtime.cjs} +24 -13
  3. package/dist/_virtual/_rolldown/runtime.js +36 -0
  4. package/dist/agents/ReactAgent.cjs +52 -65
  5. package/dist/agents/ReactAgent.cjs.map +1 -1
  6. package/dist/agents/ReactAgent.d.cts.map +1 -1
  7. package/dist/agents/ReactAgent.d.ts.map +1 -1
  8. package/dist/agents/ReactAgent.js +11 -24
  9. package/dist/agents/ReactAgent.js.map +1 -1
  10. package/dist/agents/RunnableCallable.cjs +7 -7
  11. package/dist/agents/RunnableCallable.cjs.map +1 -1
  12. package/dist/agents/RunnableCallable.js.map +1 -1
  13. package/dist/agents/annotation.cjs +41 -37
  14. package/dist/agents/annotation.cjs.map +1 -1
  15. package/dist/agents/annotation.js +21 -17
  16. package/dist/agents/annotation.js.map +1 -1
  17. package/dist/agents/constants.d.cts.map +1 -1
  18. package/dist/agents/constants.d.ts.map +1 -1
  19. package/dist/agents/errors.cjs +3 -3
  20. package/dist/agents/errors.cjs.map +1 -1
  21. package/dist/agents/errors.d.cts.map +1 -1
  22. package/dist/agents/errors.d.ts.map +1 -1
  23. package/dist/agents/errors.js.map +1 -1
  24. package/dist/agents/index.cjs.map +1 -1
  25. package/dist/agents/index.d.cts +2 -2
  26. package/dist/agents/index.d.cts.map +1 -1
  27. package/dist/agents/index.d.ts +2 -2
  28. package/dist/agents/index.d.ts.map +1 -1
  29. package/dist/agents/index.js.map +1 -1
  30. package/dist/agents/middleware/constants.cjs +2 -2
  31. package/dist/agents/middleware/constants.cjs.map +1 -1
  32. package/dist/agents/middleware/constants.js.map +1 -1
  33. package/dist/agents/middleware/contextEditing.cjs +14 -27
  34. package/dist/agents/middleware/contextEditing.cjs.map +1 -1
  35. package/dist/agents/middleware/contextEditing.d.cts +2 -3
  36. package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
  37. package/dist/agents/middleware/contextEditing.d.ts +2 -3
  38. package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
  39. package/dist/agents/middleware/contextEditing.js +5 -18
  40. package/dist/agents/middleware/contextEditing.js.map +1 -1
  41. package/dist/agents/middleware/dynamicSystemPrompt.cjs +3 -4
  42. package/dist/agents/middleware/dynamicSystemPrompt.cjs.map +1 -1
  43. package/dist/agents/middleware/dynamicSystemPrompt.d.cts +2 -2
  44. package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
  45. package/dist/agents/middleware/dynamicSystemPrompt.d.ts +2 -2
  46. package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
  47. package/dist/agents/middleware/dynamicSystemPrompt.js +1 -2
  48. package/dist/agents/middleware/dynamicSystemPrompt.js.map +1 -1
  49. package/dist/agents/middleware/error.cjs +2 -2
  50. package/dist/agents/middleware/error.cjs.map +1 -1
  51. package/dist/agents/middleware/error.js.map +1 -1
  52. package/dist/agents/middleware/hitl.cjs +16 -26
  53. package/dist/agents/middleware/hitl.cjs.map +1 -1
  54. package/dist/agents/middleware/hitl.d.cts.map +1 -1
  55. package/dist/agents/middleware/hitl.d.ts.map +1 -1
  56. package/dist/agents/middleware/hitl.js +8 -18
  57. package/dist/agents/middleware/hitl.js.map +1 -1
  58. package/dist/agents/middleware/index.js +2 -0
  59. package/dist/agents/middleware/llmToolSelector.cjs +9 -10
  60. package/dist/agents/middleware/llmToolSelector.cjs.map +1 -1
  61. package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
  62. package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
  63. package/dist/agents/middleware/llmToolSelector.d.ts +4 -4
  64. package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
  65. package/dist/agents/middleware/llmToolSelector.js +3 -4
  66. package/dist/agents/middleware/llmToolSelector.js.map +1 -1
  67. package/dist/agents/middleware/modelCallLimit.cjs +5 -5
  68. package/dist/agents/middleware/modelCallLimit.cjs.map +1 -1
  69. package/dist/agents/middleware/modelCallLimit.d.cts +2 -2
  70. package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
  71. package/dist/agents/middleware/modelCallLimit.d.ts +2 -2
  72. package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
  73. package/dist/agents/middleware/modelCallLimit.js.map +1 -1
  74. package/dist/agents/middleware/modelFallback.cjs.map +1 -1
  75. package/dist/agents/middleware/modelFallback.d.cts +0 -1
  76. package/dist/agents/middleware/modelFallback.d.cts.map +1 -1
  77. package/dist/agents/middleware/modelFallback.d.ts +0 -1
  78. package/dist/agents/middleware/modelFallback.d.ts.map +1 -1
  79. package/dist/agents/middleware/modelFallback.js.map +1 -1
  80. package/dist/agents/middleware/modelRetry.cjs +19 -17
  81. package/dist/agents/middleware/modelRetry.cjs.map +1 -1
  82. package/dist/agents/middleware/modelRetry.d.cts +0 -1
  83. package/dist/agents/middleware/modelRetry.d.cts.map +1 -1
  84. package/dist/agents/middleware/modelRetry.d.ts +0 -1
  85. package/dist/agents/middleware/modelRetry.d.ts.map +1 -1
  86. package/dist/agents/middleware/modelRetry.js +15 -13
  87. package/dist/agents/middleware/modelRetry.js.map +1 -1
  88. package/dist/agents/middleware/pii.cjs +21 -32
  89. package/dist/agents/middleware/pii.cjs.map +1 -1
  90. package/dist/agents/middleware/pii.d.cts +0 -1
  91. package/dist/agents/middleware/pii.d.cts.map +1 -1
  92. package/dist/agents/middleware/pii.d.ts +0 -1
  93. package/dist/agents/middleware/pii.d.ts.map +1 -1
  94. package/dist/agents/middleware/pii.js +10 -21
  95. package/dist/agents/middleware/pii.js.map +1 -1
  96. package/dist/agents/middleware/piiRedaction.cjs +22 -28
  97. package/dist/agents/middleware/piiRedaction.cjs.map +1 -1
  98. package/dist/agents/middleware/piiRedaction.d.cts +0 -1
  99. package/dist/agents/middleware/piiRedaction.d.cts.map +1 -1
  100. package/dist/agents/middleware/piiRedaction.d.ts +0 -1
  101. package/dist/agents/middleware/piiRedaction.d.ts.map +1 -1
  102. package/dist/agents/middleware/piiRedaction.js +8 -14
  103. package/dist/agents/middleware/piiRedaction.js.map +1 -1
  104. package/dist/agents/middleware/provider/anthropic/promptCaching.cjs +5 -8
  105. package/dist/agents/middleware/provider/anthropic/promptCaching.cjs.map +1 -1
  106. package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts +2 -2
  107. package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts.map +1 -1
  108. package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts +2 -2
  109. package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts.map +1 -1
  110. package/dist/agents/middleware/provider/anthropic/promptCaching.js +3 -6
  111. package/dist/agents/middleware/provider/anthropic/promptCaching.js.map +1 -1
  112. package/dist/agents/middleware/provider/openai/moderation.cjs +17 -22
  113. package/dist/agents/middleware/provider/openai/moderation.cjs.map +1 -1
  114. package/dist/agents/middleware/provider/openai/moderation.d.cts +0 -2
  115. package/dist/agents/middleware/provider/openai/moderation.d.cts.map +1 -1
  116. package/dist/agents/middleware/provider/openai/moderation.d.ts +0 -2
  117. package/dist/agents/middleware/provider/openai/moderation.d.ts.map +1 -1
  118. package/dist/agents/middleware/provider/openai/moderation.js +10 -15
  119. package/dist/agents/middleware/provider/openai/moderation.js.map +1 -1
  120. package/dist/agents/middleware/summarization.cjs +39 -62
  121. package/dist/agents/middleware/summarization.cjs.map +1 -1
  122. package/dist/agents/middleware/summarization.d.cts +2 -2
  123. package/dist/agents/middleware/summarization.d.cts.map +1 -1
  124. package/dist/agents/middleware/summarization.d.ts +2 -2
  125. package/dist/agents/middleware/summarization.d.ts.map +1 -1
  126. package/dist/agents/middleware/summarization.js +17 -40
  127. package/dist/agents/middleware/summarization.js.map +1 -1
  128. package/dist/agents/middleware/todoListMiddleware.cjs +21 -27
  129. package/dist/agents/middleware/todoListMiddleware.cjs.map +1 -1
  130. package/dist/agents/middleware/todoListMiddleware.d.cts +4 -4
  131. package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
  132. package/dist/agents/middleware/todoListMiddleware.d.ts +4 -4
  133. package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
  134. package/dist/agents/middleware/todoListMiddleware.js +12 -18
  135. package/dist/agents/middleware/todoListMiddleware.js.map +1 -1
  136. package/dist/agents/middleware/toolCallLimit.cjs +24 -46
  137. package/dist/agents/middleware/toolCallLimit.cjs.map +1 -1
  138. package/dist/agents/middleware/toolCallLimit.d.cts +2 -3
  139. package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
  140. package/dist/agents/middleware/toolCallLimit.d.ts +2 -3
  141. package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
  142. package/dist/agents/middleware/toolCallLimit.js +17 -39
  143. package/dist/agents/middleware/toolCallLimit.js.map +1 -1
  144. package/dist/agents/middleware/toolEmulator.cjs +8 -13
  145. package/dist/agents/middleware/toolEmulator.cjs.map +1 -1
  146. package/dist/agents/middleware/toolEmulator.d.cts +0 -1
  147. package/dist/agents/middleware/toolEmulator.d.cts.map +1 -1
  148. package/dist/agents/middleware/toolEmulator.d.ts +0 -1
  149. package/dist/agents/middleware/toolEmulator.d.ts.map +1 -1
  150. package/dist/agents/middleware/toolEmulator.js +5 -10
  151. package/dist/agents/middleware/toolEmulator.js.map +1 -1
  152. package/dist/agents/middleware/toolRetry.cjs +19 -17
  153. package/dist/agents/middleware/toolRetry.cjs.map +1 -1
  154. package/dist/agents/middleware/toolRetry.d.cts +0 -1
  155. package/dist/agents/middleware/toolRetry.d.cts.map +1 -1
  156. package/dist/agents/middleware/toolRetry.d.ts +0 -1
  157. package/dist/agents/middleware/toolRetry.d.ts.map +1 -1
  158. package/dist/agents/middleware/toolRetry.js +15 -13
  159. package/dist/agents/middleware/toolRetry.js.map +1 -1
  160. package/dist/agents/middleware/types.cjs.map +1 -1
  161. package/dist/agents/middleware/types.d.cts +33 -33
  162. package/dist/agents/middleware/types.d.cts.map +1 -1
  163. package/dist/agents/middleware/types.d.ts +33 -33
  164. package/dist/agents/middleware/types.d.ts.map +1 -1
  165. package/dist/agents/middleware/types.js.map +1 -1
  166. package/dist/agents/middleware/utils.cjs +8 -8
  167. package/dist/agents/middleware/utils.cjs.map +1 -1
  168. package/dist/agents/middleware/utils.d.cts +0 -1
  169. package/dist/agents/middleware/utils.d.cts.map +1 -1
  170. package/dist/agents/middleware/utils.d.ts +0 -1
  171. package/dist/agents/middleware/utils.d.ts.map +1 -1
  172. package/dist/agents/middleware/utils.js +3 -3
  173. package/dist/agents/middleware/utils.js.map +1 -1
  174. package/dist/agents/middleware.cjs +1 -2
  175. package/dist/agents/middleware.cjs.map +1 -1
  176. package/dist/agents/middleware.d.cts +0 -1
  177. package/dist/agents/middleware.d.cts.map +1 -1
  178. package/dist/agents/middleware.d.ts +0 -1
  179. package/dist/agents/middleware.d.ts.map +1 -1
  180. package/dist/agents/middleware.js +1 -2
  181. package/dist/agents/middleware.js.map +1 -1
  182. package/dist/agents/model.cjs.map +1 -1
  183. package/dist/agents/model.js.map +1 -1
  184. package/dist/agents/nodes/AfterAgentNode.cjs +1 -2
  185. package/dist/agents/nodes/AfterAgentNode.cjs.map +1 -1
  186. package/dist/agents/nodes/AfterAgentNode.js +1 -2
  187. package/dist/agents/nodes/AfterAgentNode.js.map +1 -1
  188. package/dist/agents/nodes/AfterModelNode.cjs +1 -2
  189. package/dist/agents/nodes/AfterModelNode.cjs.map +1 -1
  190. package/dist/agents/nodes/AfterModelNode.js +1 -2
  191. package/dist/agents/nodes/AfterModelNode.js.map +1 -1
  192. package/dist/agents/nodes/AgentNode.cjs +46 -58
  193. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  194. package/dist/agents/nodes/AgentNode.js +16 -28
  195. package/dist/agents/nodes/AgentNode.js.map +1 -1
  196. package/dist/agents/nodes/BeforeAgentNode.cjs +1 -2
  197. package/dist/agents/nodes/BeforeAgentNode.cjs.map +1 -1
  198. package/dist/agents/nodes/BeforeAgentNode.js +1 -2
  199. package/dist/agents/nodes/BeforeAgentNode.js.map +1 -1
  200. package/dist/agents/nodes/BeforeModelNode.cjs +1 -2
  201. package/dist/agents/nodes/BeforeModelNode.cjs.map +1 -1
  202. package/dist/agents/nodes/BeforeModelNode.js +1 -2
  203. package/dist/agents/nodes/BeforeModelNode.js.map +1 -1
  204. package/dist/agents/nodes/ToolNode.cjs +25 -25
  205. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  206. package/dist/agents/nodes/ToolNode.js +6 -6
  207. package/dist/agents/nodes/ToolNode.js.map +1 -1
  208. package/dist/agents/nodes/middleware.cjs +3 -3
  209. package/dist/agents/nodes/middleware.cjs.map +1 -1
  210. package/dist/agents/nodes/middleware.js.map +1 -1
  211. package/dist/agents/nodes/types.d.cts +0 -1
  212. package/dist/agents/nodes/types.d.cts.map +1 -1
  213. package/dist/agents/nodes/types.d.ts +0 -1
  214. package/dist/agents/nodes/types.d.ts.map +1 -1
  215. package/dist/agents/nodes/utils.cjs +16 -17
  216. package/dist/agents/nodes/utils.cjs.map +1 -1
  217. package/dist/agents/nodes/utils.js +2 -3
  218. package/dist/agents/nodes/utils.js.map +1 -1
  219. package/dist/agents/responses.cjs +20 -30
  220. package/dist/agents/responses.cjs.map +1 -1
  221. package/dist/agents/responses.d.cts +0 -1
  222. package/dist/agents/responses.d.cts.map +1 -1
  223. package/dist/agents/responses.d.ts +0 -1
  224. package/dist/agents/responses.d.ts.map +1 -1
  225. package/dist/agents/responses.js +12 -22
  226. package/dist/agents/responses.js.map +1 -1
  227. package/dist/agents/runtime.d.cts +0 -1
  228. package/dist/agents/runtime.d.cts.map +1 -1
  229. package/dist/agents/runtime.d.ts +0 -1
  230. package/dist/agents/runtime.d.ts.map +1 -1
  231. package/dist/agents/state.cjs +1 -2
  232. package/dist/agents/state.cjs.map +1 -1
  233. package/dist/agents/state.js +1 -2
  234. package/dist/agents/state.js.map +1 -1
  235. package/dist/agents/tests/utils.cjs +21 -26
  236. package/dist/agents/tests/utils.cjs.map +1 -1
  237. package/dist/agents/tests/utils.d.cts +0 -1
  238. package/dist/agents/tests/utils.d.cts.map +1 -1
  239. package/dist/agents/tests/utils.d.ts +0 -1
  240. package/dist/agents/tests/utils.d.ts.map +1 -1
  241. package/dist/agents/tests/utils.js +12 -17
  242. package/dist/agents/tests/utils.js.map +1 -1
  243. package/dist/agents/types.d.cts +4 -5
  244. package/dist/agents/types.d.cts.map +1 -1
  245. package/dist/agents/types.d.ts +4 -5
  246. package/dist/agents/types.d.ts.map +1 -1
  247. package/dist/agents/utils.cjs +32 -32
  248. package/dist/agents/utils.cjs.map +1 -1
  249. package/dist/agents/utils.js +6 -6
  250. package/dist/agents/utils.js.map +1 -1
  251. package/dist/agents/withAgentName.cjs +5 -5
  252. package/dist/agents/withAgentName.cjs.map +1 -1
  253. package/dist/agents/withAgentName.js.map +1 -1
  254. package/dist/chat_models/universal.cjs +34 -41
  255. package/dist/chat_models/universal.cjs.map +1 -1
  256. package/dist/chat_models/universal.d.cts.map +1 -1
  257. package/dist/chat_models/universal.d.ts.map +1 -1
  258. package/dist/chat_models/universal.js +21 -29
  259. package/dist/chat_models/universal.js.map +1 -1
  260. package/dist/hub/base.cjs +3 -4
  261. package/dist/hub/base.cjs.map +1 -1
  262. package/dist/hub/base.d.cts +0 -1
  263. package/dist/hub/base.d.cts.map +1 -1
  264. package/dist/hub/base.d.ts +0 -1
  265. package/dist/hub/base.d.ts.map +1 -1
  266. package/dist/hub/base.js +1 -2
  267. package/dist/hub/base.js.map +1 -1
  268. package/dist/hub/index.cjs +2 -2
  269. package/dist/hub/index.cjs.map +1 -1
  270. package/dist/hub/index.d.cts +0 -1
  271. package/dist/hub/index.d.cts.map +1 -1
  272. package/dist/hub/index.d.ts +0 -1
  273. package/dist/hub/index.d.ts.map +1 -1
  274. package/dist/hub/index.js +1 -2
  275. package/dist/hub/index.js.map +1 -1
  276. package/dist/hub/node.cjs +7 -13
  277. package/dist/hub/node.cjs.map +1 -1
  278. package/dist/hub/node.d.cts +0 -1
  279. package/dist/hub/node.d.cts.map +1 -1
  280. package/dist/hub/node.d.ts +0 -1
  281. package/dist/hub/node.d.ts.map +1 -1
  282. package/dist/hub/node.js +6 -13
  283. package/dist/hub/node.js.map +1 -1
  284. package/dist/index.cjs +48 -48
  285. package/dist/index.d.cts +2 -1
  286. package/dist/index.d.ts +2 -1
  287. package/dist/index.js +2 -3
  288. package/dist/load/import_constants.cjs.map +1 -1
  289. package/dist/load/import_constants.js.map +1 -1
  290. package/dist/load/import_map.cjs +46 -47
  291. package/dist/load/import_map.cjs.map +1 -1
  292. package/dist/load/import_map.js +2 -3
  293. package/dist/load/import_map.js.map +1 -1
  294. package/dist/load/import_type.d.cts.map +1 -1
  295. package/dist/load/import_type.d.ts.map +1 -1
  296. package/dist/load/index.cjs +13 -3
  297. package/dist/load/index.cjs.map +1 -1
  298. package/dist/load/index.d.cts +9 -1
  299. package/dist/load/index.d.cts.map +1 -1
  300. package/dist/load/index.d.ts +9 -1
  301. package/dist/load/index.d.ts.map +1 -1
  302. package/dist/load/index.js +9 -0
  303. package/dist/load/index.js.map +1 -1
  304. package/dist/load/serializable.cjs +7 -6
  305. package/dist/load/serializable.js +4 -4
  306. package/dist/storage/encoder_backed.cjs +9 -10
  307. package/dist/storage/encoder_backed.cjs.map +1 -1
  308. package/dist/storage/encoder_backed.d.cts +0 -1
  309. package/dist/storage/encoder_backed.d.cts.map +1 -1
  310. package/dist/storage/encoder_backed.d.ts +0 -1
  311. package/dist/storage/encoder_backed.d.ts.map +1 -1
  312. package/dist/storage/encoder_backed.js +4 -6
  313. package/dist/storage/encoder_backed.js.map +1 -1
  314. package/dist/storage/file_system.cjs +12 -11
  315. package/dist/storage/file_system.cjs.map +1 -1
  316. package/dist/storage/file_system.d.cts +0 -1
  317. package/dist/storage/file_system.d.cts.map +1 -1
  318. package/dist/storage/file_system.d.ts +0 -1
  319. package/dist/storage/file_system.d.ts.map +1 -1
  320. package/dist/storage/file_system.js +5 -7
  321. package/dist/storage/file_system.js.map +1 -1
  322. package/dist/storage/in_memory.cjs +5 -5
  323. package/dist/storage/in_memory.js +2 -3
  324. package/package.json +6 -6
  325. package/dist/_virtual/rolldown_runtime.js +0 -25
@@ -1 +1 @@
1
- {"version":3,"file":"AgentNode.js","names":["response: unknown","options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","#systemMessage","model: string | LanguageModelLike","state: InternalAgentState<StructuredResponseFormat>","config: RunnableConfig","#invokeModel","commands: Command[]","aiMessage: AIMessage | null","#areMoreStepsNeeded","options: {\n lastMessage?: string;\n }","#deriveModel","lastAiMessage: AIMessage | null","collectedCommands: Command[]","request: ModelRequest","#getResponseFormat","#bindTools","response","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>>","request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >","runtime: Runtime<unknown>","requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >","req: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >","initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >","response: AIMessage","toolCalls: ToolCall[]","responseFormat: ToolResponseFormat","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","model: LanguageModelLike","preparedOptions: ModelRequest | undefined","structuredResponseFormat: ResponseFormat | undefined","options: Partial<BaseChatModelCallOptions>"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport {\n Command,\n isCommand,\n type LangGraphRunnableConfig,\n} from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport { raceWithSignal } from \"@langchain/core/runnables\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError, MiddlewareError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport {\n bindTools,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n isClientTool,\n} from \"../utils.js\";\nimport { mergeAbortSignals, toPartialZodObject } from \"../nodes/utils.js\";\nimport { CreateAgentParams } from \"../types.js\";\nimport type { InternalAgentState, Runtime } from \"../runtime.js\";\nimport type {\n AgentMiddleware,\n AnyAnnotationRoot,\n WrapModelCallHandler,\n} from \"../middleware/types.js\";\nimport type { ModelRequest } from \"./types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\n/**\n * Wrap the base handler with middleware wrapModelCall hooks\n * Middleware are composed so the first middleware is the outermost wrapper\n * Example: [auth, retry, cache] means auth wraps retry wraps cache wraps baseHandler\n */\ntype InternalModelResponse<StructuredResponseFormat> =\n | AIMessage\n | ResponseHandlerResult<StructuredResponseFormat>\n | Command;\n\n/**\n * Check if the response is an internal model response.\n * @param response - The response to check.\n * @returns True if the response is an internal model response, false otherwise.\n */\nfunction isInternalModelResponse<StructuredResponseFormat>(\n response: unknown\n): response is InternalModelResponse<StructuredResponseFormat> {\n return (\n AIMessage.isInstance(response) ||\n isCommand(response) ||\n (typeof response === \"object\" &&\n response !== null &&\n \"structuredResponse\" in response &&\n \"messages\" in response)\n );\n}\n\n/**\n * The name of the agent node in the state graph.\n */\nexport const AGENT_NODE_NAME = \"model_request\";\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject =\n AnyAnnotationRoot,\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema>,\n \"model\" | \"includeAgentName\" | \"name\" | \"responseFormat\" | \"middleware\"\n> {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n systemMessage: SystemMessage;\n wrapModelCallHookMiddleware?: [\n AgentMiddleware,\n () => Record<string, unknown>,\n ][];\n}\n\ninterface NativeResponseFormat {\n type: \"native\";\n strategy: ProviderStrategy;\n}\n\ninterface ToolResponseFormat {\n type: \"tool\";\n tools: Record<string, ToolStrategy>;\n}\n\ntype ResponseFormat = NativeResponseFormat | ToolResponseFormat;\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject =\n AnyAnnotationRoot,\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat>,\n | Command[]\n | {\n messages: BaseMessage[];\n structuredResponse: StructuredResponseFormat;\n }\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n #systemMessage: SystemMessage;\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) => this.#run(input, config as RunnableConfig),\n });\n\n this.#options = options;\n this.#systemMessage = options.systemMessage;\n }\n\n /**\n * Returns response format primtivies based on given model and response format provided by the user.\n *\n * If the user selects a tool output:\n * - return a record of tools to extract structured output from the model's response\n *\n * if the the user selects a native schema output or if the model supports JSON schema output:\n * - return a provider strategy to extract structured output from the model's response\n *\n * @param model - The model to get the response format for.\n * @returns The response format.\n */\n #getResponseFormat(\n model: string | LanguageModelLike\n ): ResponseFormat | undefined {\n if (!this.#options.responseFormat) {\n return undefined;\n }\n\n const strategies = transformResponseFormat(\n this.#options.responseFormat,\n undefined,\n model\n );\n\n /**\n * we either define a list of provider strategies or a list of tool strategies\n */\n const isProviderStrategy = strategies.every(\n (format) => format instanceof ProviderStrategy\n );\n\n /**\n * Populate a list of structured tool info.\n */\n if (!isProviderStrategy) {\n return {\n type: \"tool\",\n tools: (\n strategies.filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce(\n (acc, format) => {\n acc[format.name] = format;\n return acc;\n },\n {} as Record<string, ToolStrategy>\n ),\n };\n }\n\n return {\n type: \"native\",\n /**\n * there can only be one provider strategy\n */\n strategy: strategies[0] as ProviderStrategy,\n };\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat>,\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n return [new Command({ update: { messages: [] } })];\n }\n\n const { response, lastAiMessage, collectedCommands } =\n await this.#invokeModel(state, config);\n\n /**\n * structuredResponse — return as a plain state update dict (not a Command)\n * because the structuredResponse channel uses UntrackedValue(guard=true)\n * which only allows a single write per step.\n */\n if (\n typeof response === \"object\" &&\n response !== null &&\n \"structuredResponse\" in response &&\n \"messages\" in response\n ) {\n const { structuredResponse, messages } = response as {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n };\n return {\n messages: [...state.messages, ...messages],\n structuredResponse,\n };\n }\n\n const commands: Command[] = [];\n const aiMessage: AIMessage | null = AIMessage.isInstance(response)\n ? response\n : lastAiMessage;\n\n // messages\n if (aiMessage) {\n aiMessage.name = this.name;\n aiMessage.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, aiMessage)) {\n commands.push(\n new Command({\n update: {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: aiMessage.id,\n }),\n ],\n },\n })\n );\n } else {\n commands.push(new Command({ update: { messages: [aiMessage] } }));\n }\n }\n\n // Commands (from base handler retries or middleware)\n if (isCommand(response) && !collectedCommands.includes(response)) {\n commands.push(response);\n }\n commands.push(...collectedCommands);\n\n return commands;\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel() {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n if (this.#options.model) {\n return this.#options.model;\n }\n\n throw new Error(\"No model option was provided, either via `model` option.\");\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat>,\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<{\n response: InternalModelResponse<StructuredResponseFormat>;\n lastAiMessage: AIMessage | null;\n collectedCommands: Command[];\n }> {\n const model = await this.#deriveModel();\n const lgConfig = config as LangGraphRunnableConfig;\n\n /**\n * Create a local variable for current system message to avoid concurrency issues\n * Each invocation gets its own copy\n */\n let currentSystemMessage = this.#systemMessage;\n\n /**\n * Shared tracking state for AIMessage and Command collection.\n * lastAiMessage tracks the effective AIMessage through the middleware chain.\n * collectedCommands accumulates Commands returned by middleware (not base handler).\n */\n let lastAiMessage: AIMessage | null = null;\n const collectedCommands: Command[] = [];\n\n /**\n * Create the base handler that performs the actual model invocation\n */\n const baseHandler = async (\n request: ModelRequest\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> => {\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(request.model);\n\n const structuredResponseFormat = this.#getResponseFormat(request.model);\n const modelWithTools = await this.#bindTools(\n request.model,\n request,\n structuredResponseFormat\n );\n\n /**\n * prepend the system message to the messages if it is not empty\n */\n const messages = [\n ...(currentSystemMessage.text === \"\" ? [] : [currentSystemMessage]),\n ...request.messages,\n ];\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const response = (await raceWithSignal(\n modelWithTools.invoke(messages, {\n ...config,\n signal,\n }),\n signal\n )) as AIMessage;\n\n lastAiMessage = response;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (structuredResponseFormat?.type === \"native\") {\n const structuredResponse =\n structuredResponseFormat.strategy.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n\n return response;\n }\n\n if (!structuredResponseFormat || !response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in structuredResponseFormat.tools\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(\n response,\n toolCalls,\n structuredResponseFormat\n );\n }\n\n const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n structuredResponseFormat,\n toolMessageContent ?? options.lastMessage\n );\n };\n\n const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? [];\n let wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>> = baseHandler;\n\n /**\n * Build composed handler from last to first so first middleware becomes outermost\n */\n for (let i = wrapperMiddleware.length - 1; i >= 0; i--) {\n const [middleware, getMiddlewareState] = wrapperMiddleware[i];\n if (middleware.wrapModelCall) {\n const innerHandler = wrappedHandler;\n const currentMiddleware = middleware;\n const currentGetState = getMiddlewareState;\n\n wrappedHandler = async (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Merge context with default context of middleware\n */\n const context = currentMiddleware.contextSchema\n ? interopParse(\n currentMiddleware.contextSchema,\n lgConfig?.context || {}\n )\n : lgConfig?.context;\n\n /**\n * Create runtime\n */\n const runtime: Runtime<unknown> = Object.freeze({\n context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n });\n\n /**\n * Create the request with state and runtime\n */\n const requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n > = {\n ...request,\n state: {\n ...(middleware.stateSchema\n ? interopParse(\n toPartialZodObject(middleware.stateSchema),\n state\n )\n : {}),\n ...currentGetState(),\n messages: state.messages,\n } as InternalAgentState<StructuredResponseFormat>,\n runtime,\n };\n\n /**\n * Create handler that validates tools and calls the inner handler\n */\n const handlerWithValidation = async (\n req: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Verify that the user didn't add any new tools.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const modifiedTools = req.tools ?? [];\n const newTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n !this.#options.toolClasses.some((t) => t.name === tool.name)\n );\n if (newTools.length > 0) {\n throw new Error(\n `You have added a new tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${newTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n /**\n * Verify that user has not added or modified a tool with the same name.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const invalidTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n this.#options.toolClasses.every((t) => t !== tool)\n );\n if (invalidTools.length > 0) {\n throw new Error(\n `You have modified a tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${invalidTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n let normalizedReq = req;\n const hasSystemPromptChanged =\n req.systemPrompt !== currentSystemMessage.text;\n const hasSystemMessageChanged =\n req.systemMessage !== currentSystemMessage;\n if (hasSystemPromptChanged && hasSystemMessageChanged) {\n throw new Error(\n \"Cannot change both systemPrompt and systemMessage in the same request.\"\n );\n }\n\n /**\n * Check if systemPrompt is a string was changed, if so create a new SystemMessage\n */\n if (hasSystemPromptChanged) {\n currentSystemMessage = new SystemMessage({\n content: [{ type: \"text\", text: req.systemPrompt }],\n });\n normalizedReq = {\n ...req,\n systemPrompt: currentSystemMessage.text,\n systemMessage: currentSystemMessage,\n };\n }\n /**\n * If the systemMessage was changed, update the current system message\n */\n if (hasSystemMessageChanged) {\n currentSystemMessage = new SystemMessage({\n ...req.systemMessage,\n });\n normalizedReq = {\n ...req,\n systemPrompt: currentSystemMessage.text,\n systemMessage: currentSystemMessage,\n };\n }\n\n const innerHandlerResult = await innerHandler(normalizedReq);\n\n /**\n * Normalize Commands so middleware always sees AIMessage from handler().\n * When an inner middleware returns a Command, substitute the tracked\n * lastAiMessage. The raw Command is still captured in innerHandlerResult\n * for the framework's Command collection.\n */\n if (isCommand(innerHandlerResult) && lastAiMessage) {\n return lastAiMessage as InternalModelResponse<StructuredResponseFormat>;\n }\n\n return innerHandlerResult;\n };\n\n // Call middleware's wrapModelCall with the validation handler\n if (!currentMiddleware.wrapModelCall) {\n return handlerWithValidation(requestWithStateAndRuntime);\n }\n\n try {\n const middlewareResponse = await currentMiddleware.wrapModelCall(\n requestWithStateAndRuntime,\n handlerWithValidation as WrapModelCallHandler\n );\n\n /**\n * Validate that this specific middleware returned a valid response\n */\n if (!isInternalModelResponse(middlewareResponse)) {\n throw new Error(\n `Invalid response from \"wrapModelCall\" in middleware \"${\n currentMiddleware.name\n }\": expected AIMessage or Command, got ${typeof middlewareResponse}`\n );\n }\n\n if (AIMessage.isInstance(middlewareResponse)) {\n lastAiMessage = middlewareResponse;\n } else if (isCommand(middlewareResponse)) {\n collectedCommands.push(middlewareResponse);\n }\n\n return middlewareResponse;\n } catch (error) {\n throw MiddlewareError.wrap(error, currentMiddleware.name);\n }\n };\n }\n }\n\n /**\n * Execute the wrapped handler with the initial request\n * Reset current system prompt to initial state and convert to string using .text getter\n * for backwards compatibility with ModelRequest\n */\n currentSystemMessage = this.#systemMessage;\n const initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n > = {\n model,\n systemPrompt: currentSystemMessage?.text,\n systemMessage: currentSystemMessage,\n messages: state.messages,\n tools: this.#options.toolClasses,\n state,\n runtime: Object.freeze({\n context: lgConfig?.context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n }) as Runtime<unknown>,\n };\n\n const response = await wrappedHandler(initialRequest);\n return { response, lastAiMessage, collectedCommands };\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[],\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0],\n responseFormat\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = responseFormat.tools[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new ToolMessage({\n tool_call_id: toolCall.id ?? \"\",\n content: JSON.stringify(structuredResponse),\n name: toolCall.name,\n }),\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall,\n responseFormat\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(responseFormat.tools).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * Default behavior: retry if `errorHandler` is undefined or truthy.\n * Only throw if explicitly set to `false`.\n */\n if (errorHandler === false) {\n throw error;\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided truthy value as the `errorHandler`, return a new AIMessage\n * with the error message and retry the tool call.\n */\n errorHandler === undefined ||\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * Default: retry if we reach here\n */\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat>,\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages.at(-1))))\n );\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions: ModelRequest | undefined,\n structuredResponseFormat: ResponseFormat | undefined\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(\n structuredResponseFormat && \"tools\" in structuredResponseFormat\n ? structuredResponseFormat.tools\n : {}\n );\n\n /**\n * Use tools from preparedOptions if provided, otherwise use default tools\n */\n const allTools = [\n ...(preparedOptions?.tools ?? this.#options.toolClasses),\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ];\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (structuredResponseFormat?.type === \"native\") {\n const resolvedStrict =\n preparedOptions?.modelSettings?.strict ??\n structuredResponseFormat?.strategy?.strict ??\n true;\n\n const jsonSchemaParams = {\n name: structuredResponseFormat.strategy.schema?.name ?? \"extract\",\n description: getSchemaDescription(\n structuredResponseFormat.strategy.schema\n ),\n schema: structuredResponseFormat.strategy.schema,\n strict: resolvedStrict,\n };\n\n Object.assign(options, {\n /**\n * OpenAI-style options\n * Used by ChatOpenAI, ChatXAI, and other OpenAI-compatible providers.\n */\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n\n /**\n * Anthropic-style options\n */\n outputConfig: {\n format: {\n type: \"json_schema\",\n schema: structuredResponseFormat.strategy.schema,\n },\n },\n\n /**\n * for LangSmith structured output tracing\n */\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: structuredResponseFormat.strategy.schema,\n },\n strict: resolvedStrict,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n ...preparedOptions?.modelSettings,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n * Use current SystemMessage state (which may have been modified by middleware)\n */\n const modelRunnable =\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools;\n\n return modelRunnable;\n }\n\n /**\n * Returns internal bookkeeping state for StateManager, not graph output.\n * The return shape differs from the node's output type (Command).\n */\n // @ts-expect-error Internal state shape differs from graph output type\n getState(): { messages: BaseMessage[] } {\n const state = super.getState();\n const origState = state && !isCommand(state) ? state : {};\n\n return {\n messages: [],\n ...origState,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwEA,SAAS,wBACPA,UAC6D;AAC7D,QACE,UAAU,WAAW,SAAS,IAC9B,UAAU,SAAS,IAClB,OAAO,aAAa,YACnB,aAAa,QACb,wBAAwB,YACxB,cAAc;AAEnB;;;;AAKD,MAAa,kBAAkB;AAoC/B,IAAa,YAAb,cAOU,iBAOR;CACA;CACA;CA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AqB,WAC/B,cAAc,gBAAgB,KAAKA,SAAS,iBAAiB,GAC7D;AAEN,SAAO;CACR;;;;;CAOD,WAAwC;EACtC,MAAM,QAAQ,MAAM,UAAU;EAC9B,MAAM,YAAY,SAAS,CAAC,UAAU,MAAM,GAAG,QAAQ,CAAE;AAEzD,SAAO;GACL,UAAU,CAAE;GACZ,GAAG;EACJ;CACF;AACF"}
1
+ {"version":3,"file":"AgentNode.js","names":["#run","#options","#systemMessage","#invokeModel","#areMoreStepsNeeded","#deriveModel","#getResponseFormat","#bindTools","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","#handleToolStrategyError"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport {\n Command,\n isCommand,\n type LangGraphRunnableConfig,\n} from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport { raceWithSignal } from \"@langchain/core/runnables\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError, MiddlewareError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport {\n bindTools,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n isClientTool,\n} from \"../utils.js\";\nimport { mergeAbortSignals, toPartialZodObject } from \"../nodes/utils.js\";\nimport { CreateAgentParams } from \"../types.js\";\nimport type { InternalAgentState, Runtime } from \"../runtime.js\";\nimport type {\n AgentMiddleware,\n AnyAnnotationRoot,\n WrapModelCallHandler,\n} from \"../middleware/types.js\";\nimport type { ModelRequest } from \"./types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\n/**\n * Wrap the base handler with middleware wrapModelCall hooks\n * Middleware are composed so the first middleware is the outermost wrapper\n * Example: [auth, retry, cache] means auth wraps retry wraps cache wraps baseHandler\n */\ntype InternalModelResponse<StructuredResponseFormat> =\n | AIMessage\n | ResponseHandlerResult<StructuredResponseFormat>\n | Command;\n\n/**\n * Check if the response is an internal model response.\n * @param response - The response to check.\n * @returns True if the response is an internal model response, false otherwise.\n */\nfunction isInternalModelResponse<StructuredResponseFormat>(\n response: unknown\n): response is InternalModelResponse<StructuredResponseFormat> {\n return (\n AIMessage.isInstance(response) ||\n isCommand(response) ||\n (typeof response === \"object\" &&\n response !== null &&\n \"structuredResponse\" in response &&\n \"messages\" in response)\n );\n}\n\n/**\n * The name of the agent node in the state graph.\n */\nexport const AGENT_NODE_NAME = \"model_request\";\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject =\n AnyAnnotationRoot,\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema>,\n \"model\" | \"includeAgentName\" | \"name\" | \"responseFormat\" | \"middleware\"\n> {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n systemMessage: SystemMessage;\n wrapModelCallHookMiddleware?: [\n AgentMiddleware,\n () => Record<string, unknown>,\n ][];\n}\n\ninterface NativeResponseFormat {\n type: \"native\";\n strategy: ProviderStrategy;\n}\n\ninterface ToolResponseFormat {\n type: \"tool\";\n tools: Record<string, ToolStrategy>;\n}\n\ntype ResponseFormat = NativeResponseFormat | ToolResponseFormat;\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject =\n AnyAnnotationRoot,\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat>,\n | Command[]\n | {\n messages: BaseMessage[];\n structuredResponse: StructuredResponseFormat;\n }\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n #systemMessage: SystemMessage;\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) => this.#run(input, config as RunnableConfig),\n });\n\n this.#options = options;\n this.#systemMessage = options.systemMessage;\n }\n\n /**\n * Returns response format primtivies based on given model and response format provided by the user.\n *\n * If the user selects a tool output:\n * - return a record of tools to extract structured output from the model's response\n *\n * if the the user selects a native schema output or if the model supports JSON schema output:\n * - return a provider strategy to extract structured output from the model's response\n *\n * @param model - The model to get the response format for.\n * @returns The response format.\n */\n #getResponseFormat(\n model: string | LanguageModelLike\n ): ResponseFormat | undefined {\n if (!this.#options.responseFormat) {\n return undefined;\n }\n\n const strategies = transformResponseFormat(\n this.#options.responseFormat,\n undefined,\n model\n );\n\n /**\n * we either define a list of provider strategies or a list of tool strategies\n */\n const isProviderStrategy = strategies.every(\n (format) => format instanceof ProviderStrategy\n );\n\n /**\n * Populate a list of structured tool info.\n */\n if (!isProviderStrategy) {\n return {\n type: \"tool\",\n tools: (\n strategies.filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce(\n (acc, format) => {\n acc[format.name] = format;\n return acc;\n },\n {} as Record<string, ToolStrategy>\n ),\n };\n }\n\n return {\n type: \"native\",\n /**\n * there can only be one provider strategy\n */\n strategy: strategies[0] as ProviderStrategy,\n };\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat>,\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n return [new Command({ update: { messages: [] } })];\n }\n\n const { response, lastAiMessage, collectedCommands } =\n await this.#invokeModel(state, config);\n\n /**\n * structuredResponse — return as a plain state update dict (not a Command)\n * because the structuredResponse channel uses UntrackedValue(guard=true)\n * which only allows a single write per step.\n */\n if (\n typeof response === \"object\" &&\n response !== null &&\n \"structuredResponse\" in response &&\n \"messages\" in response\n ) {\n const { structuredResponse, messages } = response as {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n };\n return {\n messages: [...state.messages, ...messages],\n structuredResponse,\n };\n }\n\n const commands: Command[] = [];\n const aiMessage: AIMessage | null = AIMessage.isInstance(response)\n ? response\n : lastAiMessage;\n\n // messages\n if (aiMessage) {\n aiMessage.name = this.name;\n aiMessage.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, aiMessage)) {\n commands.push(\n new Command({\n update: {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: aiMessage.id,\n }),\n ],\n },\n })\n );\n } else {\n commands.push(new Command({ update: { messages: [aiMessage] } }));\n }\n }\n\n // Commands (from base handler retries or middleware)\n if (isCommand(response) && !collectedCommands.includes(response)) {\n commands.push(response);\n }\n commands.push(...collectedCommands);\n\n return commands;\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel() {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n if (this.#options.model) {\n return this.#options.model;\n }\n\n throw new Error(\"No model option was provided, either via `model` option.\");\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat>,\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<{\n response: InternalModelResponse<StructuredResponseFormat>;\n lastAiMessage: AIMessage | null;\n collectedCommands: Command[];\n }> {\n const model = await this.#deriveModel();\n const lgConfig = config as LangGraphRunnableConfig;\n\n /**\n * Create a local variable for current system message to avoid concurrency issues\n * Each invocation gets its own copy\n */\n let currentSystemMessage = this.#systemMessage;\n\n /**\n * Shared tracking state for AIMessage and Command collection.\n * lastAiMessage tracks the effective AIMessage through the middleware chain.\n * collectedCommands accumulates Commands returned by middleware (not base handler).\n */\n let lastAiMessage: AIMessage | null = null;\n const collectedCommands: Command[] = [];\n\n /**\n * Create the base handler that performs the actual model invocation\n */\n const baseHandler = async (\n request: ModelRequest\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> => {\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(request.model);\n\n const structuredResponseFormat = this.#getResponseFormat(request.model);\n const modelWithTools = await this.#bindTools(\n request.model,\n request,\n structuredResponseFormat\n );\n\n /**\n * prepend the system message to the messages if it is not empty\n */\n const messages = [\n ...(currentSystemMessage.text === \"\" ? [] : [currentSystemMessage]),\n ...request.messages,\n ];\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const response = (await raceWithSignal(\n modelWithTools.invoke(messages, {\n ...config,\n signal,\n }),\n signal\n )) as AIMessage;\n\n lastAiMessage = response;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (structuredResponseFormat?.type === \"native\") {\n const structuredResponse =\n structuredResponseFormat.strategy.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n\n return response;\n }\n\n if (!structuredResponseFormat || !response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in structuredResponseFormat.tools\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(\n response,\n toolCalls,\n structuredResponseFormat\n );\n }\n\n const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n structuredResponseFormat,\n toolMessageContent ?? options.lastMessage\n );\n };\n\n const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? [];\n let wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>> = baseHandler;\n\n /**\n * Build composed handler from last to first so first middleware becomes outermost\n */\n for (let i = wrapperMiddleware.length - 1; i >= 0; i--) {\n const [middleware, getMiddlewareState] = wrapperMiddleware[i];\n if (middleware.wrapModelCall) {\n const innerHandler = wrappedHandler;\n const currentMiddleware = middleware;\n const currentGetState = getMiddlewareState;\n\n wrappedHandler = async (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Merge context with default context of middleware\n */\n const context = currentMiddleware.contextSchema\n ? interopParse(\n currentMiddleware.contextSchema,\n lgConfig?.context || {}\n )\n : lgConfig?.context;\n\n /**\n * Create runtime\n */\n const runtime: Runtime<unknown> = Object.freeze({\n context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n });\n\n /**\n * Create the request with state and runtime\n */\n const requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n > = {\n ...request,\n state: {\n ...(middleware.stateSchema\n ? interopParse(\n toPartialZodObject(middleware.stateSchema),\n state\n )\n : {}),\n ...currentGetState(),\n messages: state.messages,\n } as InternalAgentState<StructuredResponseFormat>,\n runtime,\n };\n\n /**\n * Create handler that validates tools and calls the inner handler\n */\n const handlerWithValidation = async (\n req: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Verify that the user didn't add any new tools.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const modifiedTools = req.tools ?? [];\n const newTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n !this.#options.toolClasses.some((t) => t.name === tool.name)\n );\n if (newTools.length > 0) {\n throw new Error(\n `You have added a new tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${newTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n /**\n * Verify that user has not added or modified a tool with the same name.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const invalidTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n this.#options.toolClasses.every((t) => t !== tool)\n );\n if (invalidTools.length > 0) {\n throw new Error(\n `You have modified a tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${invalidTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n let normalizedReq = req;\n const hasSystemPromptChanged =\n req.systemPrompt !== currentSystemMessage.text;\n const hasSystemMessageChanged =\n req.systemMessage !== currentSystemMessage;\n if (hasSystemPromptChanged && hasSystemMessageChanged) {\n throw new Error(\n \"Cannot change both systemPrompt and systemMessage in the same request.\"\n );\n }\n\n /**\n * Check if systemPrompt is a string was changed, if so create a new SystemMessage\n */\n if (hasSystemPromptChanged) {\n currentSystemMessage = new SystemMessage({\n content: [{ type: \"text\", text: req.systemPrompt }],\n });\n normalizedReq = {\n ...req,\n systemPrompt: currentSystemMessage.text,\n systemMessage: currentSystemMessage,\n };\n }\n /**\n * If the systemMessage was changed, update the current system message\n */\n if (hasSystemMessageChanged) {\n currentSystemMessage = new SystemMessage({\n ...req.systemMessage,\n });\n normalizedReq = {\n ...req,\n systemPrompt: currentSystemMessage.text,\n systemMessage: currentSystemMessage,\n };\n }\n\n const innerHandlerResult = await innerHandler(normalizedReq);\n\n /**\n * Normalize Commands so middleware always sees AIMessage from handler().\n * When an inner middleware returns a Command, substitute the tracked\n * lastAiMessage. The raw Command is still captured in innerHandlerResult\n * for the framework's Command collection.\n */\n if (isCommand(innerHandlerResult) && lastAiMessage) {\n return lastAiMessage as InternalModelResponse<StructuredResponseFormat>;\n }\n\n return innerHandlerResult;\n };\n\n // Call middleware's wrapModelCall with the validation handler\n if (!currentMiddleware.wrapModelCall) {\n return handlerWithValidation(requestWithStateAndRuntime);\n }\n\n try {\n const middlewareResponse = await currentMiddleware.wrapModelCall(\n requestWithStateAndRuntime,\n handlerWithValidation as WrapModelCallHandler\n );\n\n /**\n * Validate that this specific middleware returned a valid response\n */\n if (!isInternalModelResponse(middlewareResponse)) {\n throw new Error(\n `Invalid response from \"wrapModelCall\" in middleware \"${\n currentMiddleware.name\n }\": expected AIMessage or Command, got ${typeof middlewareResponse}`\n );\n }\n\n if (AIMessage.isInstance(middlewareResponse)) {\n lastAiMessage = middlewareResponse;\n } else if (isCommand(middlewareResponse)) {\n collectedCommands.push(middlewareResponse);\n }\n\n return middlewareResponse;\n } catch (error) {\n throw MiddlewareError.wrap(error, currentMiddleware.name);\n }\n };\n }\n }\n\n /**\n * Execute the wrapped handler with the initial request\n * Reset current system prompt to initial state and convert to string using .text getter\n * for backwards compatibility with ModelRequest\n */\n currentSystemMessage = this.#systemMessage;\n const initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat>,\n unknown\n > = {\n model,\n systemPrompt: currentSystemMessage?.text,\n systemMessage: currentSystemMessage,\n messages: state.messages,\n tools: this.#options.toolClasses,\n state,\n runtime: Object.freeze({\n context: lgConfig?.context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n }) as Runtime<unknown>,\n };\n\n const response = await wrappedHandler(initialRequest);\n return { response, lastAiMessage, collectedCommands };\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[],\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0],\n responseFormat\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = responseFormat.tools[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new ToolMessage({\n tool_call_id: toolCall.id ?? \"\",\n content: JSON.stringify(structuredResponse),\n name: toolCall.name,\n }),\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall,\n responseFormat\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(responseFormat.tools).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * Default behavior: retry if `errorHandler` is undefined or truthy.\n * Only throw if explicitly set to `false`.\n */\n if (errorHandler === false) {\n throw error;\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided truthy value as the `errorHandler`, return a new AIMessage\n * with the error message and retry the tool call.\n */\n errorHandler === undefined ||\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n /**\n * Default: retry if we reach here\n */\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: AGENT_NODE_NAME,\n });\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat>,\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages.at(-1))))\n );\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions: ModelRequest | undefined,\n structuredResponseFormat: ResponseFormat | undefined\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(\n structuredResponseFormat && \"tools\" in structuredResponseFormat\n ? structuredResponseFormat.tools\n : {}\n );\n\n /**\n * Use tools from preparedOptions if provided, otherwise use default tools\n */\n const allTools = [\n ...(preparedOptions?.tools ?? this.#options.toolClasses),\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ];\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (structuredResponseFormat?.type === \"native\") {\n const resolvedStrict =\n preparedOptions?.modelSettings?.strict ??\n structuredResponseFormat?.strategy?.strict ??\n true;\n\n const jsonSchemaParams = {\n name: structuredResponseFormat.strategy.schema?.name ?? \"extract\",\n description: getSchemaDescription(\n structuredResponseFormat.strategy.schema\n ),\n schema: structuredResponseFormat.strategy.schema,\n strict: resolvedStrict,\n };\n\n Object.assign(options, {\n /**\n * OpenAI-style options\n * Used by ChatOpenAI, ChatXAI, and other OpenAI-compatible providers.\n */\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n\n /**\n * Anthropic-style options\n */\n outputConfig: {\n format: {\n type: \"json_schema\",\n schema: structuredResponseFormat.strategy.schema,\n },\n },\n\n /**\n * for LangSmith structured output tracing\n */\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: structuredResponseFormat.strategy.schema,\n },\n strict: resolvedStrict,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n ...preparedOptions?.modelSettings,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n * Use current SystemMessage state (which may have been modified by middleware)\n */\n const modelRunnable =\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools;\n\n return modelRunnable;\n }\n\n /**\n * Returns internal bookkeeping state for StateManager, not graph output.\n * The return shape differs from the node's output type (Command).\n */\n // @ts-expect-error Internal state shape differs from graph output type\n getState(): { messages: BaseMessage[] } {\n const state = super.getState();\n const origState = state && !isCommand(state) ? state : {};\n\n return {\n messages: [],\n ...origState,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwEA,SAAS,wBACP,UAC6D;AAC7D,QACE,UAAU,WAAW,SAAS,IAC9B,UAAU,SAAS,IAClB,OAAO,aAAa,YACnB,aAAa,QACb,wBAAwB,YACxB,cAAc;;;;;AAOpB,MAAa,kBAAkB;AAoC/B,IAAa,YAAb,cAOU,iBAOR;CACA;CACA;CAEA,YACE,SACA;AACA,QAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,OAAO,OAAO,WAAW,MAAKA,IAAK,OAAO,OAAyB;GACpE,CAAC;AAEF,QAAKC,UAAW;AAChB,QAAKC,gBAAiB,QAAQ;;;;;;;;;;;;;;CAehC,mBACE,OAC4B;AAC5B,MAAI,CAAC,MAAKD,QAAS,eACjB;EAGF,MAAM,aAAa,wBACjB,MAAKA,QAAS,gBACd,QACA,MACD;;;;AAYD,MAAI,CAPuB,WAAW,OACnC,WAAW,kBAAkB,iBAC/B,CAMC,QAAO;GACL,MAAM;GACN,OACE,WAAW,QACR,WAAW,kBAAkB,aAC/B,CACD,QACC,KAAK,WAAW;AACf,QAAI,OAAO,QAAQ;AACnB,WAAO;MAET,EAAE,CACH;GACF;AAGH,SAAO;GACL,MAAM;GAIN,UAAU,WAAW;GACtB;;CAGH,OAAMD,IACJ,OACA,QACA;;;;;EAKA,MAAM,cAAc,MAAM,SAAS,GAAG,GAAG;AACzC,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ACZ,QAAQ;KACN,MAAM;KACN,QAAQ,yBAAyB,SAAS;KAC3C,EACF;IAKD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,eAAe;KACjC,QAAQ,yBAAyB,SAAS;KAC3C;IACD,QAAQ;IACT,CAAC;;;;;EAMJ,MAAM,iBAAiB,MAAM,UAAU,OAAO,UAAU;GACtD,GAAG;GACH,GAAG,iBAAiB;GACpB,aAAa;GACd,CAAC;AAWF,SAJE,MAAKA,QAAS,qBAAqB,WAC/B,cAAc,gBAAgB,MAAKA,QAAS,iBAAiB,GAC7D;;;;;;CAUR,WAAwC;EACtC,MAAM,QAAQ,MAAM,UAAU;AAG9B,SAAO;GACL,UAAU,EAAE;GACZ,GAJgB,SAAS,CAAC,UAAU,MAAM,GAAG,QAAQ,EAAE;GAKxD"}
@@ -19,8 +19,7 @@ var BeforeAgentNode = class extends require_middleware.MiddlewareNode {
19
19
  this.middleware = middleware;
20
20
  }
21
21
  runHook(state, runtime) {
22
- const fn = require_utils.getHookFunction(this.middleware.beforeAgent);
23
- return fn(state, runtime);
22
+ return require_utils.getHookFunction(this.middleware.beforeAgent)(state, runtime);
24
23
  }
25
24
  };
26
25
 
@@ -1 +1 @@
1
- {"version":3,"file":"BeforeAgentNode.cjs","names":["MiddlewareNode","middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >","options: MiddlewareNodeOptions","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<TContextSchema>","getHookFunction"],"sources":["../../../src/agents/nodes/BeforeAgentNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, type MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's beforeAgent hook.\n */\nexport class BeforeAgentNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeAgentNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `BeforeAgentNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.beforeAgent!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,kBAAb,cAGUA,kCAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAmB;CAE1D,YACSC,YAIPC,SACA;EACA,MACE;GACE,MAAM,CAAC,gBAAgB,EAAE,WAAW,MAAM;GAC1C,MAAM,OACJC,OACAC,WACG,KAAK,iBAAiB,OAAO,OAAO;EAC1C,GACD,QACD;EAfM;CAgBR;CAED,QAAQD,OAAqBE,SAAkC;EAC7D,MAAM,KAAKC,8BAAgB,KAAK,WAAW,YAAa;AACxD,SAAO,GACL,OACA,QACD;CACF;AACF"}
1
+ {"version":3,"file":"BeforeAgentNode.cjs","names":["MiddlewareNode","getHookFunction"],"sources":["../../../src/agents/nodes/BeforeAgentNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, type MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's beforeAgent hook.\n */\nexport class BeforeAgentNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeAgentNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `BeforeAgentNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.beforeAgent!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,kBAAb,cAGUA,kCAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;EAAmB;CAE1D,YACE,AAAO,YAIP,SACA;AACA,QACE;GACE,MAAM,mBAAmB,WAAW;GACpC,MAAM,OACJ,OACA,WACG,KAAK,iBAAiB,OAAO,OAAO;GAC1C,EACD,QACD;EAfM;;CAkBT,QAAQ,OAAqB,SAAkC;AAE7D,SADWC,8BAAgB,KAAK,WAAW,YAAa,CAEtD,OACA,QACD"}
@@ -19,8 +19,7 @@ var BeforeAgentNode = class extends MiddlewareNode {
19
19
  this.middleware = middleware;
20
20
  }
21
21
  runHook(state, runtime) {
22
- const fn = getHookFunction(this.middleware.beforeAgent);
23
- return fn(state, runtime);
22
+ return getHookFunction(this.middleware.beforeAgent)(state, runtime);
24
23
  }
25
24
  };
26
25
 
@@ -1 +1 @@
1
- {"version":3,"file":"BeforeAgentNode.js","names":["middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >","options: MiddlewareNodeOptions","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<TContextSchema>"],"sources":["../../../src/agents/nodes/BeforeAgentNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, type MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's beforeAgent hook.\n */\nexport class BeforeAgentNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeAgentNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `BeforeAgentNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.beforeAgent!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,kBAAb,cAGU,eAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAmB;CAE1D,YACSA,YAIPC,SACA;EACA,MACE;GACE,MAAM,CAAC,gBAAgB,EAAE,WAAW,MAAM;GAC1C,MAAM,OACJC,OACAC,WACG,KAAK,iBAAiB,OAAO,OAAO;EAC1C,GACD,QACD;EAfM;CAgBR;CAED,QAAQD,OAAqBE,SAAkC;EAC7D,MAAM,KAAK,gBAAgB,KAAK,WAAW,YAAa;AACxD,SAAO,GACL,OACA,QACD;CACF;AACF"}
1
+ {"version":3,"file":"BeforeAgentNode.js","names":[],"sources":["../../../src/agents/nodes/BeforeAgentNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, type MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's beforeAgent hook.\n */\nexport class BeforeAgentNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeAgentNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `BeforeAgentNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.beforeAgent!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,kBAAb,cAGU,eAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;EAAmB;CAE1D,YACE,AAAO,YAIP,SACA;AACA,QACE;GACE,MAAM,mBAAmB,WAAW;GACpC,MAAM,OACJ,OACA,WACG,KAAK,iBAAiB,OAAO,OAAO;GAC1C,EACD,QACD;EAfM;;CAkBT,QAAQ,OAAqB,SAAkC;AAE7D,SADW,gBAAgB,KAAK,WAAW,YAAa,CAEtD,OACA,QACD"}
@@ -19,8 +19,7 @@ var BeforeModelNode = class extends require_middleware.MiddlewareNode {
19
19
  this.middleware = middleware;
20
20
  }
21
21
  runHook(state, runtime) {
22
- const fn = require_utils.getHookFunction(this.middleware.beforeModel);
23
- return fn(state, runtime);
22
+ return require_utils.getHookFunction(this.middleware.beforeModel)(state, runtime);
24
23
  }
25
24
  };
26
25
 
@@ -1 +1 @@
1
- {"version":3,"file":"BeforeModelNode.cjs","names":["MiddlewareNode","middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >","options: MiddlewareNodeOptions","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<TContextSchema>","getHookFunction"],"sources":["../../../src/agents/nodes/BeforeModelNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, type MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's beforeModel hook.\n */\nexport class BeforeModelNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeModelNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `BeforeModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.beforeModel!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,kBAAb,cAGUA,kCAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAmB;CAE1D,YACSC,YAIPC,SACA;EACA,MACE;GACE,MAAM,CAAC,gBAAgB,EAAE,WAAW,MAAM;GAC1C,MAAM,OACJC,OACAC,WACG,KAAK,iBAAiB,OAAO,OAAO;EAC1C,GACD,QACD;EAfM;CAgBR;CAED,QAAQD,OAAqBE,SAAkC;EAC7D,MAAM,KAAKC,8BAAgB,KAAK,WAAW,YAAa;AACxD,SAAO,GACL,OACA,QACD;CACF;AACF"}
1
+ {"version":3,"file":"BeforeModelNode.cjs","names":["MiddlewareNode","getHookFunction"],"sources":["../../../src/agents/nodes/BeforeModelNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, type MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's beforeModel hook.\n */\nexport class BeforeModelNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeModelNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `BeforeModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.beforeModel!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,kBAAb,cAGUA,kCAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;EAAmB;CAE1D,YACE,AAAO,YAIP,SACA;AACA,QACE;GACE,MAAM,mBAAmB,WAAW;GACpC,MAAM,OACJ,OACA,WACG,KAAK,iBAAiB,OAAO,OAAO;GAC1C,EACD,QACD;EAfM;;CAkBT,QAAQ,OAAqB,SAAkC;AAE7D,SADWC,8BAAgB,KAAK,WAAW,YAAa,CAEtD,OACA,QACD"}
@@ -19,8 +19,7 @@ var BeforeModelNode = class extends MiddlewareNode {
19
19
  this.middleware = middleware;
20
20
  }
21
21
  runHook(state, runtime) {
22
- const fn = getHookFunction(this.middleware.beforeModel);
23
- return fn(state, runtime);
22
+ return getHookFunction(this.middleware.beforeModel)(state, runtime);
24
23
  }
25
24
  };
26
25
 
@@ -1 +1 @@
1
- {"version":3,"file":"BeforeModelNode.js","names":["middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >","options: MiddlewareNodeOptions","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<TContextSchema>"],"sources":["../../../src/agents/nodes/BeforeModelNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, type MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's beforeModel hook.\n */\nexport class BeforeModelNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeModelNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `BeforeModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.beforeModel!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,kBAAb,cAGU,eAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAmB;CAE1D,YACSA,YAIPC,SACA;EACA,MACE;GACE,MAAM,CAAC,gBAAgB,EAAE,WAAW,MAAM;GAC1C,MAAM,OACJC,OACAC,WACG,KAAK,iBAAiB,OAAO,OAAO;EAC1C,GACD,QACD;EAfM;CAgBR;CAED,QAAQD,OAAqBE,SAAkC;EAC7D,MAAM,KAAK,gBAAgB,KAAK,WAAW,YAAa;AACxD,SAAO,GACL,OACA,QACD;CACF;AACF"}
1
+ {"version":3,"file":"BeforeModelNode.js","names":[],"sources":["../../../src/agents/nodes/BeforeModelNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, type MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's beforeModel hook.\n */\nexport class BeforeModelNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeModelNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `BeforeModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.beforeModel!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,kBAAb,cAGU,eAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;EAAmB;CAE1D,YACE,AAAO,YAIP,SACA;AACA,QACE;GACE,MAAM,mBAAmB,WAAW;GACpC,MAAM,OACJ,OACA,WACG,KAAK,iBAAiB,OAAO,OAAO;GAC1C,EACD,QACD;EAfM;;CAkBT,QAAQ,OAAqB,SAAkC;AAE7D,SADW,gBAAgB,KAAK,WAAW,YAAa,CAEtD,OACA,QACD"}
@@ -1,10 +1,10 @@
1
- const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
1
+ const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
2
  const require_errors = require('../errors.cjs');
3
3
  const require_RunnableCallable = require('../RunnableCallable.cjs');
4
4
  const require_utils = require('./utils.cjs');
5
- const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
6
- const __langchain_core_tools = require_rolldown_runtime.__toESM(require("@langchain/core/tools"));
7
- const __langchain_langgraph = require_rolldown_runtime.__toESM(require("@langchain/langgraph"));
5
+ let _langchain_core_messages = require("@langchain/core/messages");
6
+ let _langchain_core_tools = require("@langchain/core/tools");
7
+ let _langchain_langgraph = require("@langchain/langgraph");
8
8
 
9
9
  //#region src/agents/nodes/ToolNode.ts
10
10
  /**
@@ -17,7 +17,7 @@ const getInvalidToolError = (toolName, availableTools) => `Error: ${toolName} is
17
17
  * The name of the tool node in the state graph.
18
18
  */
19
19
  const TOOLS_NODE_NAME = "tools";
20
- const isBaseMessageArray = (input) => Array.isArray(input) && input.every(__langchain_core_messages.BaseMessage.isInstance);
20
+ const isBaseMessageArray = (input) => Array.isArray(input) && input.every(_langchain_core_messages.BaseMessage.isInstance);
21
21
  const isMessagesState = (input) => typeof input === "object" && input != null && "messages" in input && isBaseMessageArray(input.messages);
22
22
  const isSendInput = (input) => typeof input === "object" && input != null && "lg_tool_call" in input;
23
23
  /**
@@ -31,7 +31,7 @@ const isSendInput = (input) => typeof input === "object" && input != null && "lg
31
31
  * This allows the LLM to see the error and potentially retry with different arguments.
32
32
  */
33
33
  function defaultHandleToolErrors(error, toolCall) {
34
- if (error instanceof require_errors.ToolInvocationError) return new __langchain_core_messages.ToolMessage({
34
+ if (error instanceof require_errors.ToolInvocationError) return new _langchain_core_messages.ToolMessage({
35
35
  content: error.message,
36
36
  tool_call_id: toolCall.id,
37
37
  name: toolCall.name
@@ -39,7 +39,7 @@ function defaultHandleToolErrors(error, toolCall) {
39
39
  /**
40
40
  * Catch all other tool errors and convert to ToolMessage
41
41
  */
42
- return new __langchain_core_messages.ToolMessage({
42
+ return new _langchain_core_messages.ToolMessage({
43
43
  content: `${error}\n Please fix your mistakes.`,
44
44
  tool_call_id: toolCall.id,
45
45
  name: toolCall.name
@@ -121,7 +121,7 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
121
121
  * As such, they are not recoverable by the agent and shouldn't be fed
122
122
  * back. Instead, re-throw these errors even when `handleToolErrors = true`.
123
123
  */
124
- if ((0, __langchain_langgraph.isGraphInterrupt)(error)) throw error;
124
+ if ((0, _langchain_langgraph.isGraphInterrupt)(error)) throw error;
125
125
  /**
126
126
  * If the signal is aborted, we want to bubble up the error to the invoke caller.
127
127
  */
@@ -140,12 +140,12 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
140
140
  */
141
141
  if (typeof this.handleToolErrors === "function") {
142
142
  const result = this.handleToolErrors(error, call);
143
- if (result && __langchain_core_messages.ToolMessage.isInstance(result)) return result;
143
+ if (result && _langchain_core_messages.ToolMessage.isInstance(result)) return result;
144
144
  /**
145
145
  * `handleToolErrors` returned undefined - re-raise
146
146
  */
147
147
  throw error;
148
- } else if (this.handleToolErrors) return new __langchain_core_messages.ToolMessage({
148
+ } else if (this.handleToolErrors) return new _langchain_core_messages.ToolMessage({
149
149
  name: call.name,
150
150
  content: `${error}\n Please fix your mistakes.`,
151
151
  tool_call_id: call.id
@@ -180,8 +180,8 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
180
180
  * The handler now accepts an overridden tool from the request, allowing
181
181
  * middleware to provide tool implementations for dynamically registered tools.
182
182
  */
183
- const baseHandler = async (request$1) => {
184
- const { toolCall, tool: requestTool } = request$1;
183
+ const baseHandler = async (request) => {
184
+ const { toolCall, tool: requestTool } = request;
185
185
  /**
186
186
  * Use the tool from the request (which may be overridden via spread syntax)
187
187
  * or fall back to finding it in registered tools.
@@ -194,7 +194,7 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
194
194
  * This allows the LLM to see the error and potentially retry.
195
195
  */
196
196
  const availableTools = this.tools.map((t) => t.name);
197
- return new __langchain_core_messages.ToolMessage({
197
+ return new _langchain_core_messages.ToolMessage({
198
198
  content: getInvalidToolError(toolCall.name, availableTools),
199
199
  tool_call_id: toolCall.id,
200
200
  name: toolCall.name,
@@ -218,8 +218,8 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
218
218
  state: config.configurable?.__pregel_scratchpad?.currentTaskInput,
219
219
  signal: require_utils.mergeAbortSignals(this.signal, config.signal)
220
220
  });
221
- if (__langchain_core_messages.ToolMessage.isInstance(output) || (0, __langchain_langgraph.isCommand)(output)) return output;
222
- return new __langchain_core_messages.ToolMessage({
221
+ if (_langchain_core_messages.ToolMessage.isInstance(output) || (0, _langchain_langgraph.isCommand)(output)) return output;
222
+ return new _langchain_core_messages.ToolMessage({
223
223
  name: invokableTool.name,
224
224
  content: typeof output === "string" ? output : JSON.stringify(output),
225
225
  tool_call_id: toolCall.id
@@ -229,7 +229,7 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
229
229
  * Handle errors from tool execution (not from wrapToolCall)
230
230
  * If tool invocation fails due to input parsing error, throw a {@link ToolInvocationError}
231
231
  */
232
- if (e instanceof __langchain_core_tools.ToolInputParsingException) throw new require_errors.ToolInvocationError(e, toolCall);
232
+ if (e instanceof _langchain_core_tools.ToolInputParsingException) throw new require_errors.ToolInvocationError(e, toolCall);
233
233
  /**
234
234
  * Re-throw to be handled by caller
235
235
  */
@@ -263,7 +263,7 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
263
263
  */
264
264
  if (!registeredTool) {
265
265
  const availableTools = this.tools.map((t) => t.name);
266
- return new __langchain_core_messages.ToolMessage({
266
+ return new _langchain_core_messages.ToolMessage({
267
267
  content: getInvalidToolError(call.name, availableTools),
268
268
  tool_call_id: call.id,
269
269
  name: call.name,
@@ -285,7 +285,7 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
285
285
  async run(state, config) {
286
286
  let outputs;
287
287
  if (isSendInput(state)) {
288
- const { lg_tool_call: _, jumpTo: __,...newState } = state;
288
+ const { lg_tool_call: _, jumpTo: __, ...newState } = state;
289
289
  outputs = [await this.runTool(state.lg_tool_call, config, newState)];
290
290
  } else {
291
291
  let messages;
@@ -296,20 +296,20 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
296
296
  let aiMessage;
297
297
  for (let i = messages.length - 1; i >= 0; i -= 1) {
298
298
  const message = messages[i];
299
- if (__langchain_core_messages.AIMessage.isInstance(message)) {
299
+ if (_langchain_core_messages.AIMessage.isInstance(message)) {
300
300
  aiMessage = message;
301
301
  break;
302
302
  }
303
303
  }
304
- if (!__langchain_core_messages.AIMessage.isInstance(aiMessage)) throw new Error("ToolNode only accepts AIMessages as input.");
304
+ if (!_langchain_core_messages.AIMessage.isInstance(aiMessage)) throw new Error("ToolNode only accepts AIMessages as input.");
305
305
  outputs = await Promise.all(aiMessage.tool_calls?.filter((call) => call.id == null || !toolMessageIds.has(call.id)).map((call) => this.runTool(call, config, state)) ?? []);
306
306
  }
307
- if (!outputs.some(__langchain_langgraph.isCommand)) return Array.isArray(state) ? outputs : { messages: outputs };
307
+ if (!outputs.some(_langchain_langgraph.isCommand)) return Array.isArray(state) ? outputs : { messages: outputs };
308
308
  const combinedOutputs = [];
309
309
  let parentCommand = null;
310
- for (const output of outputs) if ((0, __langchain_langgraph.isCommand)(output)) if (output.graph === __langchain_langgraph.Command.PARENT && Array.isArray(output.goto) && output.goto.every((send) => isSend(send))) if (parentCommand) parentCommand.goto.push(...output.goto);
311
- else parentCommand = new __langchain_langgraph.Command({
312
- graph: __langchain_langgraph.Command.PARENT,
310
+ for (const output of outputs) if ((0, _langchain_langgraph.isCommand)(output)) if (output.graph === _langchain_langgraph.Command.PARENT && Array.isArray(output.goto) && output.goto.every((send) => isSend(send))) if (parentCommand) parentCommand.goto.push(...output.goto);
311
+ else parentCommand = new _langchain_langgraph.Command({
312
+ graph: _langchain_langgraph.Command.PARENT,
313
313
  goto: output.goto
314
314
  });
315
315
  else combinedOutputs.push(output);
@@ -319,7 +319,7 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
319
319
  }
320
320
  };
321
321
  function isSend(x) {
322
- return x instanceof __langchain_langgraph.Send;
322
+ return x instanceof _langchain_langgraph.Send;
323
323
  }
324
324
 
325
325
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"ToolNode.cjs","names":["toolName: string","availableTools: string[]","input: unknown","BaseMessage","error: unknown","toolCall: ToolCall","ToolInvocationError","ToolMessage","RunnableCallable","tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[]","options?: ToolNodeOptions","call: ToolCall","isMiddlewareError: boolean","config: RunnableConfig","state: AgentBuiltInState","request: ToolCallRequest","request","mergeAbortSignals","e: unknown","ToolInputParsingException","request: ToolCallRequest<AgentBuiltInState>","#handleError","state: ToAnnotationRoot<StateSchema>[\"State\"] & AgentBuiltInState","outputs: (ToolMessage | Command)[]","messages: BaseMessage[]","toolMessageIds: Set<string>","aiMessage: AIMessage | undefined","AIMessage","isCommand","combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[]","parentCommand: Command | null","Command","x: unknown","Send"],"sources":["../../../src/agents/nodes/ToolNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { BaseMessage, ToolMessage, AIMessage } from \"@langchain/core/messages\";\nimport { RunnableConfig, RunnableToolLike } from \"@langchain/core/runnables\";\nimport {\n DynamicTool,\n StructuredToolInterface,\n ToolInputParsingException,\n} from \"@langchain/core/tools\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport {\n isCommand,\n Command,\n Send,\n isGraphInterrupt,\n type LangGraphRunnableConfig,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport { ToolInvocationError } from \"../errors.js\";\nimport type {\n WrapToolCallHook,\n ToolCallRequest,\n ToAnnotationRoot,\n} from \"../middleware/types.js\";\nimport type { AgentBuiltInState } from \"../runtime.js\";\n\n/**\n * Error message template for when middleware adds tools that can't be executed.\n * This happens when middleware modifies tools in wrapModelCall but doesn't provide\n * a wrapToolCall handler to execute them.\n */\nconst getInvalidToolError = (\n toolName: string,\n availableTools: string[]\n): string =>\n `Error: ${toolName} is not a valid tool, try one of [${availableTools.join(\", \")}].`;\n\n/**\n * The name of the tool node in the state graph.\n */\nexport const TOOLS_NODE_NAME = \"tools\";\n\nexport interface ToolNodeOptions {\n /**\n * The name of the tool node.\n */\n name?: string;\n /**\n * The tags to add to the tool call.\n */\n tags?: string[];\n /**\n * The abort signal to cancel the tool call.\n */\n signal?: AbortSignal;\n /**\n * Whether to throw the error immediately if the tool fails or handle it by the `onToolError` function or via ToolMessage.\n *\n * **Default behavior** (matches Python):\n * - Catches only `ToolInvocationError` (invalid arguments from model) and converts to ToolMessage\n * - Re-raises all other errors including errors from `wrapToolCall` middleware\n *\n * If `true`:\n * - Catches all errors and returns a ToolMessage with the error\n *\n * If `false`:\n * - All errors are thrown immediately\n *\n * If a function is provided:\n * - If function returns a `ToolMessage`, use it as the result\n * - If function returns `undefined`, re-raise the error\n *\n * @default A function that only catches ToolInvocationError\n */\n handleToolErrors?:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined);\n /**\n * Optional wrapper function for tool execution.\n * Allows middleware to intercept and modify tool calls before execution.\n * The wrapper receives the tool call request and a handler function to execute the tool.\n */\n wrapToolCall?: WrapToolCallHook;\n}\n\nconst isBaseMessageArray = (input: unknown): input is BaseMessage[] =>\n Array.isArray(input) && input.every(BaseMessage.isInstance);\n\nconst isMessagesState = (\n input: unknown\n): input is { messages: BaseMessage[] } =>\n typeof input === \"object\" &&\n input != null &&\n \"messages\" in input &&\n isBaseMessageArray(input.messages);\n\nconst isSendInput = (\n input: unknown\n): input is { lg_tool_call: ToolCall; jumpTo?: string } =>\n typeof input === \"object\" && input != null && \"lg_tool_call\" in input;\n\n/**\n * Default error handler for tool errors.\n *\n * This is applied to errors from baseHandler (tool execution).\n * For errors from wrapToolCall middleware, those are handled separately\n * and will bubble up by default.\n *\n * Catches all tool execution errors and converts them to ToolMessage.\n * This allows the LLM to see the error and potentially retry with different arguments.\n */\nfunction defaultHandleToolErrors(\n error: unknown,\n toolCall: ToolCall\n): ToolMessage | undefined {\n if (error instanceof ToolInvocationError) {\n return new ToolMessage({\n content: error.message,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n });\n }\n /**\n * Catch all other tool errors and convert to ToolMessage\n */\n return new ToolMessage({\n content: `${error}\\n Please fix your mistakes.`,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n });\n}\n\n/**\n * `ToolNode` is a built-in LangGraph component that handles tool calls within an agent's workflow.\n * It works seamlessly with `createAgent`, offering advanced tool execution control, built\n * in parallelism, and error handling.\n *\n * @example\n * ```ts\n * import { ToolNode, tool, AIMessage } from \"langchain\";\n * import { z } from \"zod/v3\";\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * }),\n * });\n *\n * const tools = [getWeather];\n * const toolNode = new ToolNode(tools);\n *\n * const messageWithSingleToolCall = new AIMessage({\n * content: \"\",\n * tool_calls: [\n * {\n * name: \"get_weather\",\n * args: { location: \"sf\" },\n * id: \"tool_call_id\",\n * type: \"tool_call\",\n * }\n * ]\n * })\n *\n * await toolNode.invoke({ messages: [messageWithSingleToolCall] });\n * // Returns tool invocation responses as:\n * // { messages: ToolMessage[] }\n * ```\n */\nexport class ToolNode<\n StateSchema extends StateDefinitionInit = any,\n ContextSchema extends InteropZodObject = any,\n> extends RunnableCallable<StateSchema, ContextSchema> {\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[];\n\n trace = false;\n\n signal?: AbortSignal;\n\n handleToolErrors:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined) =\n defaultHandleToolErrors;\n\n wrapToolCall: WrapToolCallHook | undefined;\n\n constructor(\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[],\n public options?: ToolNodeOptions\n ) {\n const { name, tags, handleToolErrors, signal, wrapToolCall } =\n options ?? {};\n super({\n name,\n tags,\n func: (state, config) =>\n this.run(\n state as ToAnnotationRoot<StateDefinitionInit>[\"State\"] &\n AgentBuiltInState,\n config as RunnableConfig\n ),\n });\n this.tools = tools;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.signal = signal;\n this.wrapToolCall = wrapToolCall;\n }\n\n /**\n * Handle errors from tool execution or middleware.\n * @param error - The error to handle\n * @param call - The tool call that caused the error\n * @param isMiddlewareError - Whether the error came from wrapToolCall middleware\n * @returns ToolMessage if error is handled, otherwise re-throws\n */\n #handleError(\n error: unknown,\n call: ToolCall,\n isMiddlewareError: boolean\n ): ToolMessage {\n /**\n * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop.\n * As such, they are not recoverable by the agent and shouldn't be fed\n * back. Instead, re-throw these errors even when `handleToolErrors = true`.\n */\n if (isGraphInterrupt(error)) {\n throw error;\n }\n\n /**\n * If the signal is aborted, we want to bubble up the error to the invoke caller.\n */\n if (this.signal?.aborted) {\n throw error;\n }\n\n /**\n * If error is from middleware and handleToolErrors is not true, bubble up\n * (default handler and false both re-raise middleware errors)\n */\n if (isMiddlewareError && this.handleToolErrors !== true) {\n throw error;\n }\n\n /**\n * If handleToolErrors is false, throw all errors\n */\n if (!this.handleToolErrors) {\n throw error;\n }\n\n /**\n * Apply handleToolErrors to the error\n */\n if (typeof this.handleToolErrors === \"function\") {\n const result = this.handleToolErrors(error, call);\n if (result && ToolMessage.isInstance(result)) {\n return result;\n }\n\n /**\n * `handleToolErrors` returned undefined - re-raise\n */\n throw error;\n } else if (this.handleToolErrors) {\n return new ToolMessage({\n name: call.name,\n content: `${error}\\n Please fix your mistakes.`,\n tool_call_id: call.id!,\n });\n }\n\n /**\n * Shouldn't reach here, but throw as fallback\n */\n throw error;\n }\n\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig,\n state: AgentBuiltInState\n ): Promise<ToolMessage | Command> {\n /**\n * Build runtime from LangGraph config\n */\n const lgConfig = config as LangGraphRunnableConfig;\n const runtime = {\n context: lgConfig?.context,\n writer: lgConfig?.writer,\n interrupt: lgConfig?.interrupt,\n signal: lgConfig?.signal,\n };\n\n /**\n * Find the tool instance to include in the request.\n * For dynamically registered tools, this may be undefined.\n */\n const registeredTool = this.tools.find((t) => t.name === call.name);\n\n /**\n * Define the base handler that executes the tool.\n * When wrapToolCall middleware is present, this handler does NOT catch errors\n * so the middleware can handle them.\n * When no middleware, errors are caught and handled here.\n *\n * The handler now accepts an overridden tool from the request, allowing\n * middleware to provide tool implementations for dynamically registered tools.\n */\n const baseHandler = async (\n request: ToolCallRequest\n ): Promise<ToolMessage | Command> => {\n const { toolCall, tool: requestTool } = request;\n\n /**\n * Use the tool from the request (which may be overridden via spread syntax)\n * or fall back to finding it in registered tools.\n * This allows middleware to provide dynamic tool implementations.\n */\n const tool =\n requestTool ?? this.tools.find((t) => t.name === toolCall.name);\n\n if (tool === undefined) {\n /**\n * Tool not found - return a graceful error message rather than throwing.\n * This allows the LLM to see the error and potentially retry.\n */\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(toolCall.name, availableTools),\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n }\n\n /**\n * Cast tool to a common invokable type.\n * The tool can be from registered tools (StructuredToolInterface | DynamicTool | RunnableToolLike)\n * or from middleware override (ClientTool | ServerTool).\n */\n const invokableTool = tool as\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n\n try {\n const output = await invokableTool.invoke(\n { ...toolCall, type: \"tool_call\" },\n {\n ...config,\n /**\n * extend to match ToolRuntime\n */\n config,\n toolCallId: toolCall.id!,\n state: config.configurable?.__pregel_scratchpad?.currentTaskInput,\n signal: mergeAbortSignals(this.signal, config.signal),\n }\n );\n\n if (ToolMessage.isInstance(output) || isCommand(output)) {\n return output as ToolMessage | Command;\n }\n\n return new ToolMessage({\n name: invokableTool.name,\n content: typeof output === \"string\" ? output : JSON.stringify(output),\n tool_call_id: toolCall.id!,\n });\n } catch (e: unknown) {\n /**\n * Handle errors from tool execution (not from wrapToolCall)\n * If tool invocation fails due to input parsing error, throw a {@link ToolInvocationError}\n */\n if (e instanceof ToolInputParsingException) {\n throw new ToolInvocationError(e, toolCall);\n }\n /**\n * Re-throw to be handled by caller\n */\n throw e;\n }\n };\n\n /**\n * Create request object for middleware\n * Cast to ToolCallRequest<AgentBuiltInState> to satisfy type constraints\n * of wrapToolCall which expects AgentBuiltInState\n */\n const request: ToolCallRequest<AgentBuiltInState> = {\n toolCall: call,\n tool: registeredTool,\n state,\n runtime,\n };\n\n /**\n * If wrapToolCall is provided, use it to wrap the tool execution\n */\n if (this.wrapToolCall) {\n try {\n return await this.wrapToolCall(request, baseHandler);\n } catch (e: unknown) {\n /**\n * Handle middleware errors\n */\n return this.#handleError(e, call, true);\n }\n }\n\n /**\n * No wrapToolCall - if tool wasn't found, return graceful error\n */\n if (!registeredTool) {\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(call.name, availableTools),\n tool_call_id: call.id!,\n name: call.name,\n status: \"error\",\n });\n }\n\n /**\n * No wrapToolCall - execute tool directly and handle errors here\n */\n try {\n return await baseHandler(request);\n } catch (e: unknown) {\n /**\n * Handle tool errors when no middleware provided\n */\n return this.#handleError(e, call, false);\n }\n }\n\n protected async run(\n state: ToAnnotationRoot<StateSchema>[\"State\"] & AgentBuiltInState,\n config: RunnableConfig\n ): Promise<ContextSchema> {\n let outputs: (ToolMessage | Command)[];\n\n if (isSendInput(state)) {\n const { lg_tool_call: _, jumpTo: __, ...newState } = state;\n outputs = [await this.runTool(state.lg_tool_call, config, newState)];\n } else {\n let messages: BaseMessage[];\n if (isBaseMessageArray(state)) {\n messages = state;\n } else if (isMessagesState(state)) {\n messages = state.messages;\n } else {\n throw new Error(\n \"ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.\"\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg.getType() === \"tool\")\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (AIMessage.isInstance(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (!AIMessage.isInstance(aiMessage)) {\n throw new Error(\"ToolNode only accepts AIMessages as input.\");\n }\n\n outputs = await Promise.all(\n aiMessage.tool_calls\n ?.filter((call) => call.id == null || !toolMessageIds.has(call.id))\n .map((call) => this.runTool(call, config, state)) ?? []\n );\n }\n\n // Preserve existing behavior for non-command tool outputs for backwards compatibility\n if (!outputs.some(isCommand)) {\n return (Array.isArray(state)\n ? outputs\n : { messages: outputs }) as unknown as ContextSchema;\n }\n\n // Handle mixed Command and non-Command outputs\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send) => isSend(send))\n ) {\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else {\n combinedOutputs.push(output);\n }\n } else {\n combinedOutputs.push(\n Array.isArray(state) ? [output] : { messages: [output] }\n );\n }\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as unknown as ContextSchema;\n }\n}\n\nexport function isSend(x: unknown): x is Send {\n return x instanceof Send;\n}\n"],"mappings":";;;;;;;;;;;;;;AAmCA,MAAM,sBAAsB,CAC1BA,UACAC,mBAEA,CAAC,OAAO,EAAE,SAAS,kCAAkC,EAAE,eAAe,KAAK,KAAK,CAAC,EAAE,CAAC;;;;AAKtF,MAAa,kBAAkB;AA6C/B,MAAM,qBAAqB,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AAE;KACjC,YAAY;AACZ;IACD;GACF;AAED,OAAI,CAACA,oCAAU,WAAW,UAAU,CAClC,OAAM,IAAI,MAAM;GAGlB,UAAU,MAAM,QAAQ,IACtB,UAAU,YACN,OAAO,CAAC,SAAS,KAAK,MAAM,QAAQ,CAAC,eAAe,IAAI,KAAK,GAAG,CAAC,CAClE,IAAI,CAAC,SAAS,KAAK,QAAQ,MAAM,QAAQ,MAAM,CAAC,IAAI,CAAE,EAC1D;EACF;AAGD,MAAI,CAAC,QAAQ,KAAKC,gCAAU,CAC1B,QAAQ,MAAM,QAAQ,MAAM,GACxB,UACA,EAAE,UAAU,QAAS;EAI3B,MAAMC,kBAIA,CAAE;EACR,IAAIC,gBAAgC;AAEpC,OAAK,MAAM,UAAU,QACnB,0CAAc,OAAO,CACnB,KACE,OAAO,UAAUC,8BAAQ,UACzB,MAAM,QAAQ,OAAO,KAAK,IAC1B,OAAO,KAAK,MAAM,CAAC,SAAS,OAAO,KAAK,CAAC,CAEzC,KAAI,eACD,cAAc,KAAgB,KAAK,GAAI,OAAO,KAAgB;OAE/D,gBAAgB,IAAIA,8BAAQ;GAC1B,OAAOA,8BAAQ;GACf,MAAM,OAAO;EACd;OAGH,gBAAgB,KAAK,OAAO;OAG9B,gBAAgB,KACd,MAAM,QAAQ,MAAM,GAAG,CAAC,MAAO,IAAG,EAAE,UAAU,CAAC,MAAO,EAAE,EACzD;AAIL,MAAI,eACF,gBAAgB,KAAK,cAAc;AAGrC,SAAO;CACR;AACF;AAED,SAAgB,OAAOC,GAAuB;AAC5C,QAAO,aAAaC;AACrB"}
1
+ {"version":3,"file":"ToolNode.cjs","names":["BaseMessage","ToolInvocationError","ToolMessage","RunnableCallable","mergeAbortSignals","ToolInputParsingException","#handleError","AIMessage","isCommand","Command","Send"],"sources":["../../../src/agents/nodes/ToolNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { BaseMessage, ToolMessage, AIMessage } from \"@langchain/core/messages\";\nimport { RunnableConfig, RunnableToolLike } from \"@langchain/core/runnables\";\nimport {\n DynamicTool,\n StructuredToolInterface,\n ToolInputParsingException,\n} from \"@langchain/core/tools\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport {\n isCommand,\n Command,\n Send,\n isGraphInterrupt,\n type LangGraphRunnableConfig,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport { ToolInvocationError } from \"../errors.js\";\nimport type {\n WrapToolCallHook,\n ToolCallRequest,\n ToAnnotationRoot,\n} from \"../middleware/types.js\";\nimport type { AgentBuiltInState } from \"../runtime.js\";\n\n/**\n * Error message template for when middleware adds tools that can't be executed.\n * This happens when middleware modifies tools in wrapModelCall but doesn't provide\n * a wrapToolCall handler to execute them.\n */\nconst getInvalidToolError = (\n toolName: string,\n availableTools: string[]\n): string =>\n `Error: ${toolName} is not a valid tool, try one of [${availableTools.join(\", \")}].`;\n\n/**\n * The name of the tool node in the state graph.\n */\nexport const TOOLS_NODE_NAME = \"tools\";\n\nexport interface ToolNodeOptions {\n /**\n * The name of the tool node.\n */\n name?: string;\n /**\n * The tags to add to the tool call.\n */\n tags?: string[];\n /**\n * The abort signal to cancel the tool call.\n */\n signal?: AbortSignal;\n /**\n * Whether to throw the error immediately if the tool fails or handle it by the `onToolError` function or via ToolMessage.\n *\n * **Default behavior** (matches Python):\n * - Catches only `ToolInvocationError` (invalid arguments from model) and converts to ToolMessage\n * - Re-raises all other errors including errors from `wrapToolCall` middleware\n *\n * If `true`:\n * - Catches all errors and returns a ToolMessage with the error\n *\n * If `false`:\n * - All errors are thrown immediately\n *\n * If a function is provided:\n * - If function returns a `ToolMessage`, use it as the result\n * - If function returns `undefined`, re-raise the error\n *\n * @default A function that only catches ToolInvocationError\n */\n handleToolErrors?:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined);\n /**\n * Optional wrapper function for tool execution.\n * Allows middleware to intercept and modify tool calls before execution.\n * The wrapper receives the tool call request and a handler function to execute the tool.\n */\n wrapToolCall?: WrapToolCallHook;\n}\n\nconst isBaseMessageArray = (input: unknown): input is BaseMessage[] =>\n Array.isArray(input) && input.every(BaseMessage.isInstance);\n\nconst isMessagesState = (\n input: unknown\n): input is { messages: BaseMessage[] } =>\n typeof input === \"object\" &&\n input != null &&\n \"messages\" in input &&\n isBaseMessageArray(input.messages);\n\nconst isSendInput = (\n input: unknown\n): input is { lg_tool_call: ToolCall; jumpTo?: string } =>\n typeof input === \"object\" && input != null && \"lg_tool_call\" in input;\n\n/**\n * Default error handler for tool errors.\n *\n * This is applied to errors from baseHandler (tool execution).\n * For errors from wrapToolCall middleware, those are handled separately\n * and will bubble up by default.\n *\n * Catches all tool execution errors and converts them to ToolMessage.\n * This allows the LLM to see the error and potentially retry with different arguments.\n */\nfunction defaultHandleToolErrors(\n error: unknown,\n toolCall: ToolCall\n): ToolMessage | undefined {\n if (error instanceof ToolInvocationError) {\n return new ToolMessage({\n content: error.message,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n });\n }\n /**\n * Catch all other tool errors and convert to ToolMessage\n */\n return new ToolMessage({\n content: `${error}\\n Please fix your mistakes.`,\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n });\n}\n\n/**\n * `ToolNode` is a built-in LangGraph component that handles tool calls within an agent's workflow.\n * It works seamlessly with `createAgent`, offering advanced tool execution control, built\n * in parallelism, and error handling.\n *\n * @example\n * ```ts\n * import { ToolNode, tool, AIMessage } from \"langchain\";\n * import { z } from \"zod/v3\";\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * }),\n * });\n *\n * const tools = [getWeather];\n * const toolNode = new ToolNode(tools);\n *\n * const messageWithSingleToolCall = new AIMessage({\n * content: \"\",\n * tool_calls: [\n * {\n * name: \"get_weather\",\n * args: { location: \"sf\" },\n * id: \"tool_call_id\",\n * type: \"tool_call\",\n * }\n * ]\n * })\n *\n * await toolNode.invoke({ messages: [messageWithSingleToolCall] });\n * // Returns tool invocation responses as:\n * // { messages: ToolMessage[] }\n * ```\n */\nexport class ToolNode<\n StateSchema extends StateDefinitionInit = any,\n ContextSchema extends InteropZodObject = any,\n> extends RunnableCallable<StateSchema, ContextSchema> {\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[];\n\n trace = false;\n\n signal?: AbortSignal;\n\n handleToolErrors:\n | boolean\n | ((error: unknown, toolCall: ToolCall) => ToolMessage | undefined) =\n defaultHandleToolErrors;\n\n wrapToolCall: WrapToolCallHook | undefined;\n\n constructor(\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[],\n public options?: ToolNodeOptions\n ) {\n const { name, tags, handleToolErrors, signal, wrapToolCall } =\n options ?? {};\n super({\n name,\n tags,\n func: (state, config) =>\n this.run(\n state as ToAnnotationRoot<StateDefinitionInit>[\"State\"] &\n AgentBuiltInState,\n config as RunnableConfig\n ),\n });\n this.tools = tools;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.signal = signal;\n this.wrapToolCall = wrapToolCall;\n }\n\n /**\n * Handle errors from tool execution or middleware.\n * @param error - The error to handle\n * @param call - The tool call that caused the error\n * @param isMiddlewareError - Whether the error came from wrapToolCall middleware\n * @returns ToolMessage if error is handled, otherwise re-throws\n */\n #handleError(\n error: unknown,\n call: ToolCall,\n isMiddlewareError: boolean\n ): ToolMessage {\n /**\n * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop.\n * As such, they are not recoverable by the agent and shouldn't be fed\n * back. Instead, re-throw these errors even when `handleToolErrors = true`.\n */\n if (isGraphInterrupt(error)) {\n throw error;\n }\n\n /**\n * If the signal is aborted, we want to bubble up the error to the invoke caller.\n */\n if (this.signal?.aborted) {\n throw error;\n }\n\n /**\n * If error is from middleware and handleToolErrors is not true, bubble up\n * (default handler and false both re-raise middleware errors)\n */\n if (isMiddlewareError && this.handleToolErrors !== true) {\n throw error;\n }\n\n /**\n * If handleToolErrors is false, throw all errors\n */\n if (!this.handleToolErrors) {\n throw error;\n }\n\n /**\n * Apply handleToolErrors to the error\n */\n if (typeof this.handleToolErrors === \"function\") {\n const result = this.handleToolErrors(error, call);\n if (result && ToolMessage.isInstance(result)) {\n return result;\n }\n\n /**\n * `handleToolErrors` returned undefined - re-raise\n */\n throw error;\n } else if (this.handleToolErrors) {\n return new ToolMessage({\n name: call.name,\n content: `${error}\\n Please fix your mistakes.`,\n tool_call_id: call.id!,\n });\n }\n\n /**\n * Shouldn't reach here, but throw as fallback\n */\n throw error;\n }\n\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig,\n state: AgentBuiltInState\n ): Promise<ToolMessage | Command> {\n /**\n * Build runtime from LangGraph config\n */\n const lgConfig = config as LangGraphRunnableConfig;\n const runtime = {\n context: lgConfig?.context,\n writer: lgConfig?.writer,\n interrupt: lgConfig?.interrupt,\n signal: lgConfig?.signal,\n };\n\n /**\n * Find the tool instance to include in the request.\n * For dynamically registered tools, this may be undefined.\n */\n const registeredTool = this.tools.find((t) => t.name === call.name);\n\n /**\n * Define the base handler that executes the tool.\n * When wrapToolCall middleware is present, this handler does NOT catch errors\n * so the middleware can handle them.\n * When no middleware, errors are caught and handled here.\n *\n * The handler now accepts an overridden tool from the request, allowing\n * middleware to provide tool implementations for dynamically registered tools.\n */\n const baseHandler = async (\n request: ToolCallRequest\n ): Promise<ToolMessage | Command> => {\n const { toolCall, tool: requestTool } = request;\n\n /**\n * Use the tool from the request (which may be overridden via spread syntax)\n * or fall back to finding it in registered tools.\n * This allows middleware to provide dynamic tool implementations.\n */\n const tool =\n requestTool ?? this.tools.find((t) => t.name === toolCall.name);\n\n if (tool === undefined) {\n /**\n * Tool not found - return a graceful error message rather than throwing.\n * This allows the LLM to see the error and potentially retry.\n */\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(toolCall.name, availableTools),\n tool_call_id: toolCall.id!,\n name: toolCall.name,\n status: \"error\",\n });\n }\n\n /**\n * Cast tool to a common invokable type.\n * The tool can be from registered tools (StructuredToolInterface | DynamicTool | RunnableToolLike)\n * or from middleware override (ClientTool | ServerTool).\n */\n const invokableTool = tool as\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n\n try {\n const output = await invokableTool.invoke(\n { ...toolCall, type: \"tool_call\" },\n {\n ...config,\n /**\n * extend to match ToolRuntime\n */\n config,\n toolCallId: toolCall.id!,\n state: config.configurable?.__pregel_scratchpad?.currentTaskInput,\n signal: mergeAbortSignals(this.signal, config.signal),\n }\n );\n\n if (ToolMessage.isInstance(output) || isCommand(output)) {\n return output as ToolMessage | Command;\n }\n\n return new ToolMessage({\n name: invokableTool.name,\n content: typeof output === \"string\" ? output : JSON.stringify(output),\n tool_call_id: toolCall.id!,\n });\n } catch (e: unknown) {\n /**\n * Handle errors from tool execution (not from wrapToolCall)\n * If tool invocation fails due to input parsing error, throw a {@link ToolInvocationError}\n */\n if (e instanceof ToolInputParsingException) {\n throw new ToolInvocationError(e, toolCall);\n }\n /**\n * Re-throw to be handled by caller\n */\n throw e;\n }\n };\n\n /**\n * Create request object for middleware\n * Cast to ToolCallRequest<AgentBuiltInState> to satisfy type constraints\n * of wrapToolCall which expects AgentBuiltInState\n */\n const request: ToolCallRequest<AgentBuiltInState> = {\n toolCall: call,\n tool: registeredTool,\n state,\n runtime,\n };\n\n /**\n * If wrapToolCall is provided, use it to wrap the tool execution\n */\n if (this.wrapToolCall) {\n try {\n return await this.wrapToolCall(request, baseHandler);\n } catch (e: unknown) {\n /**\n * Handle middleware errors\n */\n return this.#handleError(e, call, true);\n }\n }\n\n /**\n * No wrapToolCall - if tool wasn't found, return graceful error\n */\n if (!registeredTool) {\n const availableTools = this.tools.map((t) => t.name);\n return new ToolMessage({\n content: getInvalidToolError(call.name, availableTools),\n tool_call_id: call.id!,\n name: call.name,\n status: \"error\",\n });\n }\n\n /**\n * No wrapToolCall - execute tool directly and handle errors here\n */\n try {\n return await baseHandler(request);\n } catch (e: unknown) {\n /**\n * Handle tool errors when no middleware provided\n */\n return this.#handleError(e, call, false);\n }\n }\n\n protected async run(\n state: ToAnnotationRoot<StateSchema>[\"State\"] & AgentBuiltInState,\n config: RunnableConfig\n ): Promise<ContextSchema> {\n let outputs: (ToolMessage | Command)[];\n\n if (isSendInput(state)) {\n const { lg_tool_call: _, jumpTo: __, ...newState } = state;\n outputs = [await this.runTool(state.lg_tool_call, config, newState)];\n } else {\n let messages: BaseMessage[];\n if (isBaseMessageArray(state)) {\n messages = state;\n } else if (isMessagesState(state)) {\n messages = state.messages;\n } else {\n throw new Error(\n \"ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.\"\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg.getType() === \"tool\")\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (AIMessage.isInstance(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (!AIMessage.isInstance(aiMessage)) {\n throw new Error(\"ToolNode only accepts AIMessages as input.\");\n }\n\n outputs = await Promise.all(\n aiMessage.tool_calls\n ?.filter((call) => call.id == null || !toolMessageIds.has(call.id))\n .map((call) => this.runTool(call, config, state)) ?? []\n );\n }\n\n // Preserve existing behavior for non-command tool outputs for backwards compatibility\n if (!outputs.some(isCommand)) {\n return (Array.isArray(state)\n ? outputs\n : { messages: outputs }) as unknown as ContextSchema;\n }\n\n // Handle mixed Command and non-Command outputs\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send) => isSend(send))\n ) {\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else {\n combinedOutputs.push(output);\n }\n } else {\n combinedOutputs.push(\n Array.isArray(state) ? [output] : { messages: [output] }\n );\n }\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as unknown as ContextSchema;\n }\n}\n\nexport function isSend(x: unknown): x is Send {\n return x instanceof Send;\n}\n"],"mappings":";;;;;;;;;;;;;;AAmCA,MAAM,uBACJ,UACA,mBAEA,UAAU,SAAS,oCAAoC,eAAe,KAAK,KAAK,CAAC;;;;AAKnF,MAAa,kBAAkB;AA6C/B,MAAM,sBAAsB,UAC1B,MAAM,QAAQ,MAAM,IAAI,MAAM,MAAMA,qCAAY,WAAW;AAE7D,MAAM,mBACJ,UAEA,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,mBAAmB,MAAM,SAAS;AAEpC,MAAM,eACJ,UAEA,OAAO,UAAU,YAAY,SAAS,QAAQ,kBAAkB;;;;;;;;;;;AAYlE,SAAS,wBACP,OACA,UACyB;AACzB,KAAI,iBAAiBC,mCACnB,QAAO,IAAIC,qCAAY;EACrB,SAAS,MAAM;EACf,cAAc,SAAS;EACvB,MAAM,SAAS;EAChB,CAAC;;;;AAKJ,QAAO,IAAIA,qCAAY;EACrB,SAAS,GAAG,MAAM;EAClB,cAAc,SAAS;EACvB,MAAM,SAAS;EAChB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CJ,IAAa,WAAb,cAGUC,0CAA6C;CACrD;CAEA,QAAQ;CAER;CAEA,mBAGE;CAEF;CAEA,YACE,OACA,AAAO,SACP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OAAO;MAG9B,iBAAgB,KACd,MAAM,QAAQ,MAAM,GAAG,CAAC,OAAO,GAAG,EAAE,UAAU,CAAC,OAAO,EAAE,CACzD;AAIL,MAAI,cACF,iBAAgB,KAAK,cAAc;AAGrC,SAAO;;;AAIX,SAAgB,OAAO,GAAuB;AAC5C,QAAO,aAAaC"}
@@ -179,15 +179,15 @@ var ToolNode = class extends RunnableCallable {
179
179
  * The handler now accepts an overridden tool from the request, allowing
180
180
  * middleware to provide tool implementations for dynamically registered tools.
181
181
  */
182
- const baseHandler = async (request$1) => {
183
- const { toolCall, tool: requestTool } = request$1;
182
+ const baseHandler = async (request) => {
183
+ const { toolCall, tool: requestTool } = request;
184
184
  /**
185
185
  * Use the tool from the request (which may be overridden via spread syntax)
186
186
  * or fall back to finding it in registered tools.
187
187
  * This allows middleware to provide dynamic tool implementations.
188
188
  */
189
- const tool$1 = requestTool ?? this.tools.find((t) => t.name === toolCall.name);
190
- if (tool$1 === void 0) {
189
+ const tool = requestTool ?? this.tools.find((t) => t.name === toolCall.name);
190
+ if (tool === void 0) {
191
191
  /**
192
192
  * Tool not found - return a graceful error message rather than throwing.
193
193
  * This allows the LLM to see the error and potentially retry.
@@ -205,7 +205,7 @@ var ToolNode = class extends RunnableCallable {
205
205
  * The tool can be from registered tools (StructuredToolInterface | DynamicTool | RunnableToolLike)
206
206
  * or from middleware override (ClientTool | ServerTool).
207
207
  */
208
- const invokableTool = tool$1;
208
+ const invokableTool = tool;
209
209
  try {
210
210
  const output = await invokableTool.invoke({
211
211
  ...toolCall,
@@ -284,7 +284,7 @@ var ToolNode = class extends RunnableCallable {
284
284
  async run(state, config) {
285
285
  let outputs;
286
286
  if (isSendInput(state)) {
287
- const { lg_tool_call: _, jumpTo: __,...newState } = state;
287
+ const { lg_tool_call: _, jumpTo: __, ...newState } = state;
288
288
  outputs = [await this.runTool(state.lg_tool_call, config, newState)];
289
289
  } else {
290
290
  let messages;