@librechat/agents 3.1.75 → 3.1.77-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/dist/cjs/graphs/Graph.cjs +22 -3
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/hitl/askUserQuestion.cjs +67 -0
  4. package/dist/cjs/hitl/askUserQuestion.cjs.map +1 -0
  5. package/dist/cjs/hooks/HookRegistry.cjs +54 -0
  6. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  7. package/dist/cjs/hooks/createToolPolicyHook.cjs +115 -0
  8. package/dist/cjs/hooks/createToolPolicyHook.cjs.map +1 -0
  9. package/dist/cjs/hooks/executeHooks.cjs +40 -1
  10. package/dist/cjs/hooks/executeHooks.cjs.map +1 -1
  11. package/dist/cjs/hooks/types.cjs +1 -0
  12. package/dist/cjs/hooks/types.cjs.map +1 -1
  13. package/dist/cjs/langchain/google-common.cjs +3 -0
  14. package/dist/cjs/langchain/google-common.cjs.map +1 -0
  15. package/dist/cjs/langchain/index.cjs +86 -0
  16. package/dist/cjs/langchain/index.cjs.map +1 -0
  17. package/dist/cjs/langchain/language_models/chat_models.cjs +3 -0
  18. package/dist/cjs/langchain/language_models/chat_models.cjs.map +1 -0
  19. package/dist/cjs/langchain/messages/tool.cjs +3 -0
  20. package/dist/cjs/langchain/messages/tool.cjs.map +1 -0
  21. package/dist/cjs/langchain/messages.cjs +51 -0
  22. package/dist/cjs/langchain/messages.cjs.map +1 -0
  23. package/dist/cjs/langchain/openai.cjs +3 -0
  24. package/dist/cjs/langchain/openai.cjs.map +1 -0
  25. package/dist/cjs/langchain/prompts.cjs +11 -0
  26. package/dist/cjs/langchain/prompts.cjs.map +1 -0
  27. package/dist/cjs/langchain/runnables.cjs +19 -0
  28. package/dist/cjs/langchain/runnables.cjs.map +1 -0
  29. package/dist/cjs/langchain/tools.cjs +23 -0
  30. package/dist/cjs/langchain/tools.cjs.map +1 -0
  31. package/dist/cjs/langchain/utils/env.cjs +11 -0
  32. package/dist/cjs/langchain/utils/env.cjs.map +1 -0
  33. package/dist/cjs/llm/anthropic/index.cjs +145 -52
  34. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  35. package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
  36. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +21 -14
  37. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  38. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +84 -70
  39. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
  40. package/dist/cjs/llm/bedrock/index.cjs +1 -1
  41. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  42. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +213 -3
  43. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  44. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +2 -1
  45. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -1
  46. package/dist/cjs/llm/google/utils/common.cjs +5 -4
  47. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  48. package/dist/cjs/llm/openai/index.cjs +519 -655
  49. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  50. package/dist/cjs/llm/openai/utils/index.cjs +20 -458
  51. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  52. package/dist/cjs/llm/openrouter/index.cjs +57 -175
  53. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  54. package/dist/cjs/llm/vertexai/index.cjs +5 -3
  55. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  56. package/dist/cjs/main.cjs +112 -3
  57. package/dist/cjs/main.cjs.map +1 -1
  58. package/dist/cjs/messages/cache.cjs +2 -1
  59. package/dist/cjs/messages/cache.cjs.map +1 -1
  60. package/dist/cjs/messages/core.cjs +7 -6
  61. package/dist/cjs/messages/core.cjs.map +1 -1
  62. package/dist/cjs/messages/format.cjs +73 -15
  63. package/dist/cjs/messages/format.cjs.map +1 -1
  64. package/dist/cjs/messages/langchain.cjs +26 -0
  65. package/dist/cjs/messages/langchain.cjs.map +1 -0
  66. package/dist/cjs/messages/prune.cjs +7 -6
  67. package/dist/cjs/messages/prune.cjs.map +1 -1
  68. package/dist/cjs/run.cjs +400 -42
  69. package/dist/cjs/run.cjs.map +1 -1
  70. package/dist/cjs/tools/ToolNode.cjs +556 -56
  71. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  72. package/dist/cjs/tools/search/search.cjs +55 -66
  73. package/dist/cjs/tools/search/search.cjs.map +1 -1
  74. package/dist/cjs/tools/search/tavily-scraper.cjs +189 -0
  75. package/dist/cjs/tools/search/tavily-scraper.cjs.map +1 -0
  76. package/dist/cjs/tools/search/tavily-search.cjs +372 -0
  77. package/dist/cjs/tools/search/tavily-search.cjs.map +1 -0
  78. package/dist/cjs/tools/search/tool.cjs +26 -4
  79. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  80. package/dist/cjs/tools/search/utils.cjs +10 -3
  81. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  82. package/dist/esm/graphs/Graph.mjs +22 -3
  83. package/dist/esm/graphs/Graph.mjs.map +1 -1
  84. package/dist/esm/hitl/askUserQuestion.mjs +65 -0
  85. package/dist/esm/hitl/askUserQuestion.mjs.map +1 -0
  86. package/dist/esm/hooks/HookRegistry.mjs +54 -0
  87. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  88. package/dist/esm/hooks/createToolPolicyHook.mjs +113 -0
  89. package/dist/esm/hooks/createToolPolicyHook.mjs.map +1 -0
  90. package/dist/esm/hooks/executeHooks.mjs +40 -1
  91. package/dist/esm/hooks/executeHooks.mjs.map +1 -1
  92. package/dist/esm/hooks/types.mjs +1 -0
  93. package/dist/esm/hooks/types.mjs.map +1 -1
  94. package/dist/esm/langchain/google-common.mjs +2 -0
  95. package/dist/esm/langchain/google-common.mjs.map +1 -0
  96. package/dist/esm/langchain/index.mjs +5 -0
  97. package/dist/esm/langchain/index.mjs.map +1 -0
  98. package/dist/esm/langchain/language_models/chat_models.mjs +2 -0
  99. package/dist/esm/langchain/language_models/chat_models.mjs.map +1 -0
  100. package/dist/esm/langchain/messages/tool.mjs +2 -0
  101. package/dist/esm/langchain/messages/tool.mjs.map +1 -0
  102. package/dist/esm/langchain/messages.mjs +2 -0
  103. package/dist/esm/langchain/messages.mjs.map +1 -0
  104. package/dist/esm/langchain/openai.mjs +2 -0
  105. package/dist/esm/langchain/openai.mjs.map +1 -0
  106. package/dist/esm/langchain/prompts.mjs +2 -0
  107. package/dist/esm/langchain/prompts.mjs.map +1 -0
  108. package/dist/esm/langchain/runnables.mjs +2 -0
  109. package/dist/esm/langchain/runnables.mjs.map +1 -0
  110. package/dist/esm/langchain/tools.mjs +2 -0
  111. package/dist/esm/langchain/tools.mjs.map +1 -0
  112. package/dist/esm/langchain/utils/env.mjs +2 -0
  113. package/dist/esm/langchain/utils/env.mjs.map +1 -0
  114. package/dist/esm/llm/anthropic/index.mjs +146 -54
  115. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  116. package/dist/esm/llm/anthropic/types.mjs.map +1 -1
  117. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +21 -14
  118. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  119. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +84 -71
  120. package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
  121. package/dist/esm/llm/bedrock/index.mjs +1 -1
  122. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  123. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +214 -4
  124. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  125. package/dist/esm/llm/bedrock/utils/message_outputs.mjs +2 -1
  126. package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -1
  127. package/dist/esm/llm/google/utils/common.mjs +5 -4
  128. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  129. package/dist/esm/llm/openai/index.mjs +520 -656
  130. package/dist/esm/llm/openai/index.mjs.map +1 -1
  131. package/dist/esm/llm/openai/utils/index.mjs +23 -459
  132. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  133. package/dist/esm/llm/openrouter/index.mjs +57 -175
  134. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  135. package/dist/esm/llm/vertexai/index.mjs +5 -3
  136. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  137. package/dist/esm/main.mjs +7 -0
  138. package/dist/esm/main.mjs.map +1 -1
  139. package/dist/esm/messages/cache.mjs +2 -1
  140. package/dist/esm/messages/cache.mjs.map +1 -1
  141. package/dist/esm/messages/core.mjs +7 -6
  142. package/dist/esm/messages/core.mjs.map +1 -1
  143. package/dist/esm/messages/format.mjs +73 -15
  144. package/dist/esm/messages/format.mjs.map +1 -1
  145. package/dist/esm/messages/langchain.mjs +23 -0
  146. package/dist/esm/messages/langchain.mjs.map +1 -0
  147. package/dist/esm/messages/prune.mjs +7 -6
  148. package/dist/esm/messages/prune.mjs.map +1 -1
  149. package/dist/esm/run.mjs +400 -42
  150. package/dist/esm/run.mjs.map +1 -1
  151. package/dist/esm/tools/ToolNode.mjs +557 -57
  152. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  153. package/dist/esm/tools/search/search.mjs +55 -66
  154. package/dist/esm/tools/search/search.mjs.map +1 -1
  155. package/dist/esm/tools/search/tavily-scraper.mjs +186 -0
  156. package/dist/esm/tools/search/tavily-scraper.mjs.map +1 -0
  157. package/dist/esm/tools/search/tavily-search.mjs +370 -0
  158. package/dist/esm/tools/search/tavily-search.mjs.map +1 -0
  159. package/dist/esm/tools/search/tool.mjs +26 -4
  160. package/dist/esm/tools/search/tool.mjs.map +1 -1
  161. package/dist/esm/tools/search/utils.mjs +10 -3
  162. package/dist/esm/tools/search/utils.mjs.map +1 -1
  163. package/dist/types/graphs/Graph.d.ts +7 -0
  164. package/dist/types/hitl/askUserQuestion.d.ts +55 -0
  165. package/dist/types/hitl/index.d.ts +6 -0
  166. package/dist/types/hooks/HookRegistry.d.ts +58 -0
  167. package/dist/types/hooks/createToolPolicyHook.d.ts +87 -0
  168. package/dist/types/hooks/index.d.ts +4 -1
  169. package/dist/types/hooks/types.d.ts +109 -3
  170. package/dist/types/index.d.ts +10 -0
  171. package/dist/types/langchain/google-common.d.ts +1 -0
  172. package/dist/types/langchain/index.d.ts +8 -0
  173. package/dist/types/langchain/language_models/chat_models.d.ts +1 -0
  174. package/dist/types/langchain/messages/tool.d.ts +1 -0
  175. package/dist/types/langchain/messages.d.ts +2 -0
  176. package/dist/types/langchain/openai.d.ts +1 -0
  177. package/dist/types/langchain/prompts.d.ts +1 -0
  178. package/dist/types/langchain/runnables.d.ts +2 -0
  179. package/dist/types/langchain/tools.d.ts +2 -0
  180. package/dist/types/langchain/utils/env.d.ts +1 -0
  181. package/dist/types/llm/anthropic/index.d.ts +22 -9
  182. package/dist/types/llm/anthropic/types.d.ts +5 -1
  183. package/dist/types/llm/anthropic/utils/message_outputs.d.ts +13 -6
  184. package/dist/types/llm/anthropic/utils/output_parsers.d.ts +1 -1
  185. package/dist/types/llm/openai/index.d.ts +21 -24
  186. package/dist/types/llm/openrouter/index.d.ts +11 -9
  187. package/dist/types/llm/vertexai/index.d.ts +1 -0
  188. package/dist/types/messages/cache.d.ts +4 -1
  189. package/dist/types/messages/format.d.ts +4 -1
  190. package/dist/types/messages/langchain.d.ts +27 -0
  191. package/dist/types/run.d.ts +117 -1
  192. package/dist/types/tools/ToolNode.d.ts +26 -1
  193. package/dist/types/tools/search/tavily-scraper.d.ts +19 -0
  194. package/dist/types/tools/search/tavily-search.d.ts +4 -0
  195. package/dist/types/tools/search/types.d.ts +99 -5
  196. package/dist/types/tools/search/utils.d.ts +2 -2
  197. package/dist/types/types/graph.d.ts +23 -37
  198. package/dist/types/types/hitl.d.ts +272 -0
  199. package/dist/types/types/index.d.ts +1 -0
  200. package/dist/types/types/llm.d.ts +3 -3
  201. package/dist/types/types/run.d.ts +33 -0
  202. package/dist/types/types/stream.d.ts +1 -1
  203. package/dist/types/types/tools.d.ts +19 -0
  204. package/package.json +80 -17
  205. package/src/graphs/Graph.ts +33 -4
  206. package/src/graphs/__tests__/composition.smoke.test.ts +188 -0
  207. package/src/hitl/askUserQuestion.ts +72 -0
  208. package/src/hitl/index.ts +7 -0
  209. package/src/hooks/HookRegistry.ts +71 -0
  210. package/src/hooks/__tests__/createToolPolicyHook.test.ts +259 -0
  211. package/src/hooks/createToolPolicyHook.ts +184 -0
  212. package/src/hooks/executeHooks.ts +50 -1
  213. package/src/hooks/index.ts +6 -0
  214. package/src/hooks/types.ts +112 -0
  215. package/src/index.ts +22 -0
  216. package/src/langchain/google-common.ts +1 -0
  217. package/src/langchain/index.ts +8 -0
  218. package/src/langchain/language_models/chat_models.ts +1 -0
  219. package/src/langchain/messages/tool.ts +5 -0
  220. package/src/langchain/messages.ts +21 -0
  221. package/src/langchain/openai.ts +1 -0
  222. package/src/langchain/prompts.ts +1 -0
  223. package/src/langchain/runnables.ts +7 -0
  224. package/src/langchain/tools.ts +8 -0
  225. package/src/langchain/utils/env.ts +1 -0
  226. package/src/llm/anthropic/index.ts +252 -84
  227. package/src/llm/anthropic/llm.spec.ts +751 -102
  228. package/src/llm/anthropic/types.ts +9 -1
  229. package/src/llm/anthropic/utils/message_inputs.ts +37 -19
  230. package/src/llm/anthropic/utils/message_outputs.ts +119 -101
  231. package/src/llm/bedrock/index.ts +2 -2
  232. package/src/llm/bedrock/llm.spec.ts +341 -0
  233. package/src/llm/bedrock/utils/message_inputs.ts +303 -4
  234. package/src/llm/bedrock/utils/message_outputs.ts +2 -1
  235. package/src/llm/custom-chat-models.smoke.test.ts +836 -0
  236. package/src/llm/google/llm.spec.ts +339 -57
  237. package/src/llm/google/utils/common.ts +53 -48
  238. package/src/llm/openai/contentBlocks.test.ts +346 -0
  239. package/src/llm/openai/index.ts +856 -833
  240. package/src/llm/openai/utils/index.ts +107 -78
  241. package/src/llm/openai/utils/messages.test.ts +159 -0
  242. package/src/llm/openrouter/index.ts +124 -247
  243. package/src/llm/openrouter/reasoning.test.ts +8 -1
  244. package/src/llm/vertexai/index.ts +11 -5
  245. package/src/llm/vertexai/llm.spec.ts +28 -1
  246. package/src/messages/cache.test.ts +4 -3
  247. package/src/messages/cache.ts +3 -2
  248. package/src/messages/core.ts +16 -9
  249. package/src/messages/format.ts +96 -16
  250. package/src/messages/formatAgentMessages.test.ts +166 -1
  251. package/src/messages/langchain.ts +39 -0
  252. package/src/messages/prune.ts +12 -8
  253. package/src/run.ts +456 -47
  254. package/src/scripts/caching.ts +2 -3
  255. package/src/specs/summarization.test.ts +51 -58
  256. package/src/tools/ToolNode.ts +706 -63
  257. package/src/tools/__tests__/hitl.test.ts +3593 -0
  258. package/src/tools/search/search.ts +83 -73
  259. package/src/tools/search/tavily-scraper.ts +235 -0
  260. package/src/tools/search/tavily-search.ts +424 -0
  261. package/src/tools/search/tavily.test.ts +965 -0
  262. package/src/tools/search/tool.ts +36 -26
  263. package/src/tools/search/types.ts +133 -8
  264. package/src/tools/search/utils.ts +13 -5
  265. package/src/types/graph.ts +32 -87
  266. package/src/types/hitl.ts +303 -0
  267. package/src/types/index.ts +1 -0
  268. package/src/types/llm.ts +3 -3
  269. package/src/types/run.ts +33 -0
  270. package/src/types/stream.ts +1 -1
  271. package/src/types/tools.ts +19 -0
  272. package/src/utils/llmConfig.ts +1 -6
@@ -1 +1 @@
1
- {"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n HumanMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type {\n ToolOutputResolveView,\n PreResolvedArgsMap,\n ResolvedArgsByCallId,\n} from '@/tools/toolOutputReferences';\nimport type { HookRegistry, AggregatedHookResult } from '@/hooks';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\nimport {\n calculateMaxToolResultChars,\n truncateToolResultContent,\n} from '@/utils/truncation';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { executeHooks } from '@/hooks';\nimport { Constants, GraphEvents, CODE_EXECUTION_TOOLS } from '@/common';\nimport {\n buildReferenceKey,\n ToolOutputReferenceRegistry,\n} from '@/tools/toolOutputReferences';\n\n/**\n * Per-call batch context for `runTool`. Bundles every optional\n * batch-scoped value the method needs so the signature stays at\n * three positional parameters even as new context fields are added.\n */\ntype RunToolBatchContext = {\n /** Position of this call within the parent ToolNode batch. */\n batchIndex?: number;\n /** Batch turn shared across every call in the batch. */\n turn?: number;\n /** Registry partition scope (run id or anonymous batch id). */\n batchScopeId?: string;\n /** Batch-local sink for post-substitution args. */\n resolvedArgsByCallId?: ResolvedArgsByCallId;\n};\n\n/**\n * Per-batch context for `dispatchToolEvents` / `executeViaEvent`.\n * Mirrors {@link RunToolBatchContext} for the event-driven path,\n * with bulk indices and the snapshot/pre-resolved-args carriers\n * used in the mixed direct+event flow.\n */\ntype DispatchBatchContext = {\n /** Per-call batch indices, parallel to the `toolCalls` array. */\n batchIndices?: number[];\n /** Batch turn shared across every call in the batch. */\n turn?: number;\n /** Registry partition scope (run id or anonymous batch id). */\n batchScopeId?: string;\n /**\n * Pre-resolved args keyed by `toolCallId`. Populated by the mixed\n * path so event calls don't re-resolve against a registry that\n * already contains same-turn direct outputs.\n */\n preResolvedArgs?: PreResolvedArgsMap;\n /**\n * Frozen pre-batch registry view used to re-resolve placeholders\n * a `PreToolUse` hook injects via `updatedInput` — preserves the\n * same-turn isolation guarantee for hook-rewritten args.\n */\n preBatchSnapshot?: ToolOutputResolveView;\n};\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n/**\n * Merges code execution session context into the sessions map.\n *\n * The codeapi worker reports two distinct ids on a code-execution result:\n * - `artifact.session_id` (the `sessionId` arg here) is the EXEC session\n * — the sandbox VM that ran the code. It's transient and torn down\n * post-execution; subsequent calls cannot reuse it as a sandbox.\n * - `file.session_id` on each `artifact.files[i]` is the STORAGE\n * session — the file-server bucket prefix where the artifact actually\n * lives and is served from.\n *\n * Per-file `session_id` is preserved (not overwritten with the exec id)\n * because `_injected_files` are looked up against the file-server's\n * storage path on subsequent tool calls. Stomping the storage id with\n * the exec id silently 404s every follow-up tool call within the same\n * run — `cat /mnt/data/foo.txt` reports \"No such file or directory\"\n * because the worker can't mount a file at a path the storage doesn't\n * know about. Fall back to `sessionId` only when the per-file id is\n * absent (older worker payloads).\n */\nfunction updateCodeSession(\n sessions: t.ToolSessionMap,\n sessionId: string,\n files: t.FileRefs | undefined\n): void {\n const newFiles = files ?? [];\n const existingSession = sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n if (newFiles.length > 0) {\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: file.session_id ?? sessionId,\n }));\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n sessions.set(Constants.EXECUTE_CODE, {\n session_id: sessionId,\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n } else {\n sessions.set(Constants.EXECUTE_CODE, {\n session_id: sessionId,\n files: existingFiles,\n lastUpdated: Date.now(),\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n /** Maps toolCallId → turn captured in runTool, used by handleRunToolCompletions */\n private toolCallTurns: Map<string, number> = new Map();\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n /** Tool names that bypass event dispatch and execute directly (e.g., graph-managed handoff tools) */\n private directToolNames?: Set<string>;\n /** Maximum characters allowed in a single tool result before truncation. */\n private maxToolResultChars: number;\n /** Hook registry for PreToolUse/PostToolUse lifecycle hooks */\n private hookRegistry?: HookRegistry;\n /**\n * Registry of tool outputs keyed by `tool<idx>turn<turn>`.\n *\n * Populated only when `toolOutputReferences.enabled` is true. The\n * registry owns the run-scoped state (turn counter, last-seen runId,\n * warn-once memo, stored outputs), so sharing a single instance\n * across multiple ToolNodes in a run lets cross-agent `{{…}}`\n * references resolve — which is why multi-agent graphs pass the\n * *same* instance to every ToolNode they compile rather than each\n * ToolNode building its own.\n */\n private toolOutputRegistry?: ToolOutputReferenceRegistry;\n /**\n * Monotonic counter used to mint a unique scope id for anonymous\n * batches (ones invoked without a `run_id` in\n * `config.configurable`). Each such batch gets its own registry\n * partition so concurrent anonymous invocations can't delete each\n * other's in-flight state.\n */\n private anonBatchCounter: number = 0;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n agentId,\n directToolNames,\n maxContextTokens,\n maxToolResultChars,\n hookRegistry,\n toolOutputReferences,\n toolOutputRegistry,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n this.toolRegistry = toolRegistry;\n this.sessions = sessions;\n this.eventDrivenMode = eventDrivenMode ?? false;\n this.agentId = agentId;\n this.directToolNames = directToolNames;\n this.maxToolResultChars =\n maxToolResultChars ?? calculateMaxToolResultChars(maxContextTokens);\n this.hookRegistry = hookRegistry;\n /**\n * Precedence: an explicitly passed `toolOutputRegistry` instance\n * wins over a config object so a host (`Graph`) can share one\n * registry across many ToolNodes. When only the config is\n * provided (direct ToolNode usage), build a local registry so\n * the feature still works without graph-level plumbing. Registry\n * caps are intentionally decoupled from `maxToolResultChars`:\n * the registry stores the raw untruncated output so a later\n * `{{…}}` substitution pipes the full payload into the next\n * tool, even when the LLM saw a truncated preview.\n */\n if (toolOutputRegistry != null) {\n this.toolOutputRegistry = toolOutputRegistry;\n } else if (toolOutputReferences?.enabled === true) {\n this.toolOutputRegistry = new ToolOutputReferenceRegistry({\n maxOutputSize: toolOutputReferences.maxOutputSize,\n maxTotalSize: toolOutputReferences.maxTotalSize,\n });\n }\n }\n\n /**\n * Returns the run-scoped tool output registry, or `undefined` when\n * the feature is disabled.\n *\n * @internal Exposed for test observation only. Host code should rely\n * on `{{tool<i>turn<n>}}` substitution at tool-invocation time and\n * not mutate the registry directly.\n */\n public _unsafeGetToolOutputRegistry():\n | ToolOutputReferenceRegistry\n | undefined {\n return this.toolOutputRegistry;\n }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n /**\n * Runs a single tool call with error handling.\n *\n * `batchIndex` is the tool's position within the current ToolNode\n * batch and, together with `this.currentTurn`, forms the key used to\n * register the output for future `{{tool<idx>turn<turn>}}`\n * substitutions. Omit when no registration should occur.\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig,\n batchContext: RunToolBatchContext = {}\n ): Promise<BaseMessage | Command> {\n const { batchIndex, turn, batchScopeId, resolvedArgsByCallId } =\n batchContext;\n const tool = this.toolMap.get(call.name);\n const registry = this.toolOutputRegistry;\n /**\n * Precompute the reference key once per call — captured locally\n * so concurrent `invoke()` calls on the same ToolNode cannot race\n * on a shared turn field.\n */\n const refKey =\n registry != null && batchIndex != null && turn != null\n ? buildReferenceKey(batchIndex, turn)\n : undefined;\n /**\n * Hoisted outside the try so the catch branch can append\n * `[unresolved refs: …]` to error messages — otherwise the LLM\n * only sees a generic error when it references a bad key, losing\n * the self-correction signal this feature is meant to provide.\n */\n let unresolvedRefs: string[] = [];\n /**\n * Use the caller-provided `batchScopeId` when threaded from\n * `run()` (so anonymous batches get their own unique scope).\n * Fall back to the config's `run_id` when runTool is invoked\n * from a context that doesn't thread it — that still preserves\n * the runId-based partitioning for named runs.\n */\n const runId =\n batchScopeId ?? (config.configurable?.run_id as string | undefined);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n /**\n * `usageCount` is the per-tool-name invocation index that\n * web-search and other tools observe via `invokeParams.turn`.\n * It is intentionally distinct from the outer `turn` parameter\n * (the batch turn used for ref keys); the latter is captured\n * before the try block when constructing `refKey`.\n */\n const usageCount = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, usageCount + 1);\n if (call.id != null && call.id !== '') {\n this.toolCallTurns.set(call.id, usageCount);\n }\n let args = call.args;\n if (registry != null) {\n const { resolved, unresolved } = registry.resolve(runId, args);\n args = resolved;\n unresolvedRefs = unresolved;\n /**\n * Expose the post-substitution args to downstream completion\n * events so audit logs / host-side `ON_RUN_STEP_COMPLETED`\n * handlers observe what actually ran, not the `{{…}}`\n * template. Only string/object args are worth recording.\n */\n if (\n resolvedArgsByCallId != null &&\n call.id != null &&\n call.id !== '' &&\n resolved !== call.args &&\n typeof resolved === 'object'\n ) {\n resolvedArgsByCallId.set(\n call.id,\n resolved as Record<string, unknown>\n );\n }\n }\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n // `turn` here is the per-tool usage count (matches what tools have\n // observed historically via config.toolCall.turn — e.g. web search).\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn: usageCount,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING ||\n call.name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING\n ) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n *\n * session_id is always injected when available (even without tracked files)\n * so the CodeExecutor can fall back to the /files endpoint for session continuity.\n */\n if (CODE_EXECUTION_TOOLS.has(call.name)) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.session_id != null && codeSession.session_id !== '') {\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files != null && codeSession.files.length > 0) {\n const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n invokeParams._injected_files = fileRefs;\n }\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n if (isCommand(output)) {\n return output;\n }\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n const isError = toolMsg.status === 'error';\n if (isError) {\n /**\n * Error ToolMessages bypass registration but still stamp the\n * unresolved-refs hint into `additional_kwargs` so the lazy\n * annotation transform surfaces it to the LLM, letting the\n * model self-correct when its reference key caused the\n * failure. Persisted `content` stays clean.\n */\n if (unresolvedRefs.length > 0) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n _unresolvedRefs: unresolvedRefs,\n };\n }\n return toolMsg;\n }\n if (this.toolOutputRegistry != null || unresolvedRefs.length > 0) {\n if (typeof toolMsg.content === 'string') {\n const rawContent = toolMsg.content;\n const llmContent = truncateToolResultContent(\n rawContent,\n this.maxToolResultChars\n );\n toolMsg.content = llmContent;\n const refMeta = this.recordOutputReference(\n runId,\n rawContent,\n refKey,\n unresolvedRefs\n );\n if (refMeta != null) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n ...refMeta,\n };\n }\n } else {\n /**\n * Non-string content (multi-part content blocks — text +\n * image). Known limitation: we cannot register under a\n * reference key because there's no canonical serialized\n * form. Warn once per tool per run when the caller\n * intended to register. The unresolved-refs hint is still\n * stamped as metadata; the lazy transform prepends a text\n * block at request time so the LLM gets the self-correction\n * signal.\n */\n if (unresolvedRefs.length > 0) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n _unresolvedRefs: unresolvedRefs,\n };\n }\n if (\n refKey != null &&\n this.toolOutputRegistry!.claimWarnOnce(runId, call.name)\n ) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] Skipping tool output reference for \"${call.name}\": ` +\n 'ToolMessage content is not a string (further occurrences for this tool in the same run are suppressed).'\n );\n }\n }\n }\n return toolMsg;\n }\n const rawContent =\n typeof output === 'string' ? output : JSON.stringify(output);\n const truncated = truncateToolResultContent(\n rawContent,\n this.maxToolResultChars\n );\n const refMeta = this.recordOutputReference(\n runId,\n rawContent,\n refKey,\n unresolvedRefs\n );\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: truncated,\n tool_call_id: call.id!,\n ...(refMeta != null && {\n additional_kwargs: refMeta as Record<string, unknown>,\n }),\n });\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n const errorContent = `Error: ${e.message}\\n Please fix your mistakes.`;\n const refMeta =\n unresolvedRefs.length > 0\n ? this.recordOutputReference(\n runId,\n errorContent,\n undefined,\n unresolvedRefs\n )\n : undefined;\n return new ToolMessage({\n status: 'error',\n content: errorContent,\n name: call.name,\n tool_call_id: call.id ?? '',\n ...(refMeta != null && {\n additional_kwargs: refMeta as Record<string, unknown>,\n }),\n });\n }\n }\n\n /**\n * Registers the full, raw output under `refKey` (when provided) and\n * builds the per-message ref metadata stamped onto the resulting\n * `ToolMessage.additional_kwargs`. The metadata is read at LLM-\n * request time by `annotateMessagesForLLM` to produce a transient\n * annotated copy of the message — the persisted `content` itself\n * stays clean.\n *\n * @param registryContent The full, untruncated output to store in\n * the registry so `{{tool<i>turn<n>}}` substitutions deliver the\n * complete payload. Ignored when `refKey` is undefined.\n * @param refKey Precomputed `tool<i>turn<n>` key, or undefined when\n * the output is not to be registered (errors, disabled feature,\n * unavailable batch/turn).\n * @param unresolved Placeholder keys that did not resolve; surfaced\n * to the LLM lazily so it can self-correct.\n * @returns A `ToolMessageRefMetadata` object when there is anything\n * to stamp, otherwise `undefined`.\n */\n private recordOutputReference(\n runId: string | undefined,\n registryContent: string,\n refKey: string | undefined,\n unresolved: string[]\n ): t.ToolMessageRefMetadata | undefined {\n if (this.toolOutputRegistry != null && refKey != null) {\n this.toolOutputRegistry.set(runId, refKey, registryContent);\n }\n if (refKey == null && unresolved.length === 0) return undefined;\n const meta: t.ToolMessageRefMetadata = {};\n if (refKey != null) {\n meta._refKey = refKey;\n /**\n * Stamp the registry scope alongside the key so the lazy\n * annotation transform can look up the right bucket. Anonymous\n * invocations get a synthetic per-batch scope (`\\0anon-<n>`)\n * that `attemptInvoke` cannot derive from\n * `config.configurable.run_id` — without this, anonymous-run\n * refs would silently fail registry lookup and the LLM would\n * never see `[ref: …]` markers for outputs that were registered.\n */\n if (runId != null) meta._refScope = runId;\n }\n if (unresolved.length > 0) meta._unresolvedRefs = unresolved;\n return meta;\n }\n\n /**\n * Builds code session context for injection into event-driven tool calls.\n * Mirrors the session injection logic in runTool() for direct execution.\n */\n private getCodeSessionContext(): t.ToolCallRequest['codeSessionContext'] {\n if (!this.sessions) {\n return undefined;\n }\n\n const codeSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (!codeSession) {\n return undefined;\n }\n\n const context: NonNullable<t.ToolCallRequest['codeSessionContext']> = {\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files && codeSession.files.length > 0) {\n context.files = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n }\n\n return context;\n }\n\n /**\n * Extracts code execution session context from tool results and stores in Graph.sessions.\n * Mirrors the session storage logic in handleRunToolCompletions for direct execution.\n */\n private storeCodeSessionFromResults(\n results: t.ToolExecuteResult[],\n requestMap: Map<string, t.ToolCallRequest>\n ): void {\n if (!this.sessions) {\n return;\n }\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n if (result.status !== 'success' || result.artifact == null) {\n continue;\n }\n\n const request = requestMap.get(result.toolCallId);\n if (\n !request?.name ||\n (!CODE_EXECUTION_TOOLS.has(request.name) &&\n request.name !== Constants.SKILL_TOOL)\n ) {\n continue;\n }\n\n const artifact = result.artifact as t.CodeExecutionArtifact | undefined;\n if (artifact?.session_id == null || artifact.session_id === '') {\n continue;\n }\n\n updateCodeSession(this.sessions, artifact.session_id!, artifact.files);\n }\n }\n\n /**\n * Post-processes standard runTool outputs: dispatches ON_RUN_STEP_COMPLETED\n * and stores code session context. Mirrors the completion handling in\n * dispatchToolEvents for the event-driven path.\n *\n * By handling completions here in graph context (rather than in the\n * stream consumer via ToolEndHandler), the race between the stream\n * consumer and graph execution is eliminated.\n *\n * @param resolvedArgsByCallId Per-batch resolved-args sink populated\n * by `runTool`. Threaded as a local map (instead of instance state)\n * so concurrent batches cannot read each other's entries.\n */\n private handleRunToolCompletions(\n calls: ToolCall[],\n outputs: (BaseMessage | Command)[],\n config: RunnableConfig,\n resolvedArgsByCallId?: ResolvedArgsByCallId\n ): void {\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i];\n const output = outputs[i];\n const turn = this.toolCallTurns.get(call.id!) ?? 0;\n\n if (isCommand(output)) {\n continue;\n }\n\n const toolMessage = output as ToolMessage;\n const toolCallId = call.id ?? '';\n\n // Skip error ToolMessages when errorHandler already dispatched ON_RUN_STEP_COMPLETED\n // via handleToolCallErrorStatic. Without this check, errors would be double-dispatched.\n if (toolMessage.status === 'error' && this.errorHandler != null) {\n continue;\n }\n\n if (this.sessions && CODE_EXECUTION_TOOLS.has(call.name)) {\n const artifact = toolMessage.artifact as\n | t.CodeExecutionArtifact\n | undefined;\n if (artifact?.session_id != null && artifact.session_id !== '') {\n updateCodeSession(this.sessions, artifact.session_id, artifact.files);\n }\n }\n\n // Dispatch ON_RUN_STEP_COMPLETED via custom event (same path as dispatchToolEvents)\n const stepId = this.toolCallStepIds?.get(toolCallId) ?? '';\n if (!stepId) {\n continue;\n }\n\n const contentString =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n /**\n * Prefer the post-substitution args when a `{{…}}` placeholder\n * was resolved in `runTool`. This keeps\n * `ON_RUN_STEP_COMPLETED.tool_call.args` consistent with what\n * the tool actually received rather than leaking the template.\n */\n const effectiveArgs = resolvedArgsByCallId?.get(toolCallId) ?? call.args;\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof effectiveArgs === 'string'\n ? (effectiveArgs as string)\n : JSON.stringify((effectiveArgs as unknown) ?? {}),\n name: call.name,\n id: toolCallId,\n output: contentString,\n progress: 1,\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: turn,\n type: 'tool_call' as const,\n tool_call,\n },\n },\n config\n );\n }\n }\n\n /**\n * Dispatches tool calls to the host via ON_TOOL_EXECUTE event and returns raw ToolMessages.\n * Core logic for event-driven execution, separated from output shaping.\n *\n * Hook lifecycle (when `hookRegistry` is set):\n * 1. **PreToolUse** fires per call in parallel before dispatch. Denied\n * calls produce error ToolMessages and fire **PermissionDenied**;\n * surviving calls proceed with optional `updatedInput`.\n * 2. Surviving calls are dispatched to the host via `ON_TOOL_EXECUTE`.\n * 3. **PostToolUse** / **PostToolUseFailure** fire per result. Post hooks\n * can replace tool output via `updatedOutput`.\n * 4. Injected messages from results are collected and returned alongside\n * ToolMessages (appended AFTER to respect provider ordering).\n */\n private async dispatchToolEvents(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n batchContext: DispatchBatchContext = {}\n ): Promise<{ toolMessages: ToolMessage[]; injected: BaseMessage[] }> {\n const {\n batchIndices,\n turn,\n batchScopeId,\n preResolvedArgs,\n preBatchSnapshot,\n } = batchContext;\n const runId = (config.configurable?.run_id as string | undefined) ?? '';\n /**\n * Registry-facing scope id — prefers the caller-threaded\n * `batchScopeId` so anonymous batches target their own unique\n * bucket and don't step on concurrent anonymous invocations.\n * Hooks and event payloads keep using the empty-string coerced\n * `runId` for backward compat.\n */\n const registryRunId =\n batchScopeId ?? (config.configurable?.run_id as string | undefined);\n const threadId = config.configurable?.thread_id as string | undefined;\n const registry = this.toolOutputRegistry;\n const unresolvedByCallId = new Map<string, string[]>();\n\n const preToolCalls = toolCalls.map((call, i) => {\n const originalArgs = call.args as Record<string, unknown>;\n let resolvedArgs = originalArgs;\n /**\n * When the caller provided a pre-resolved map (the mixed\n * direct+event path snapshots event args synchronously before\n * awaiting directs so they can't accidentally resolve\n * same-turn direct outputs), use those entries verbatim instead\n * of re-resolving against a registry that may have changed\n * since the batch started.\n */\n const pre = call.id != null ? preResolvedArgs?.get(call.id) : undefined;\n if (pre != null) {\n resolvedArgs = pre.resolved;\n if (pre.unresolved.length > 0 && call.id != null) {\n unresolvedByCallId.set(call.id, pre.unresolved);\n }\n } else if (registry != null) {\n const { resolved, unresolved } = registry.resolve(\n registryRunId,\n originalArgs\n );\n resolvedArgs = resolved as Record<string, unknown>;\n if (unresolved.length > 0 && call.id != null) {\n unresolvedByCallId.set(call.id, unresolved);\n }\n }\n return {\n call,\n stepId: this.toolCallStepIds?.get(call.id!) ?? '',\n args: resolvedArgs,\n batchIndex: batchIndices?.[i],\n };\n });\n\n const messageByCallId = new Map<string, ToolMessage>();\n const approvedEntries: typeof preToolCalls = [];\n const HOOK_FALLBACK: AggregatedHookResult = Object.freeze({\n additionalContexts: [] as string[],\n errors: [] as string[],\n });\n\n if (this.hookRegistry?.hasHookFor('PreToolUse', runId) === true) {\n const preResults = await Promise.all(\n preToolCalls.map((entry) =>\n executeHooks({\n registry: this.hookRegistry!,\n input: {\n hook_event_name: 'PreToolUse',\n runId,\n threadId,\n agentId: this.agentId,\n toolName: entry.call.name,\n toolInput: entry.args,\n toolUseId: entry.call.id!,\n stepId: entry.stepId,\n turn: this.toolUsageCount.get(entry.call.name) ?? 0,\n },\n sessionId: runId,\n matchQuery: entry.call.name,\n }).catch((): AggregatedHookResult => HOOK_FALLBACK)\n )\n );\n\n for (let i = 0; i < preToolCalls.length; i++) {\n const hookResult = preResults[i];\n const entry = preToolCalls[i];\n const isDenied =\n hookResult.decision === 'deny' || hookResult.decision === 'ask';\n if (isDenied) {\n const reason = hookResult.reason ?? 'Blocked by hook';\n const contentString = `Blocked: ${reason}`;\n messageByCallId.set(\n entry.call.id!,\n new ToolMessage({\n status: 'error',\n content: contentString,\n name: entry.call.name,\n tool_call_id: entry.call.id!,\n })\n );\n this.dispatchStepCompleted(\n entry.call.id!,\n entry.call.name,\n entry.args,\n contentString,\n config\n );\n if (this.hookRegistry.hasHookFor('PermissionDenied', runId)) {\n executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'PermissionDenied',\n runId,\n threadId,\n agentId: this.agentId,\n toolName: entry.call.name,\n toolInput: entry.args,\n toolUseId: entry.call.id!,\n reason,\n },\n sessionId: runId,\n matchQuery: entry.call.name,\n }).catch(() => {\n /* PermissionDenied is observational — swallow errors */\n });\n }\n continue;\n }\n if (hookResult.updatedInput != null) {\n /**\n * Re-resolve after PreToolUse replaces the input: a hook may\n * introduce new `{{tool<i>turn<n>}}` placeholders (e.g., by\n * copying user-supplied text) that the pre-hook pass never\n * saw. Re-running the resolver on the hook-rewritten args\n * keeps substitution and the unresolved-refs record in sync\n * with what the tool will actually receive.\n */\n if (registry != null) {\n /**\n * Mixed direct+event batches must use the pre-batch\n * snapshot so a hook-introduced placeholder cannot\n * accidentally resolve to a same-turn direct output that\n * has just registered. Pure event batches don't have a\n * snapshot and resolve against the live registry — safe\n * because no event-side registrations have happened yet.\n */\n const view: ToolOutputResolveView = preBatchSnapshot ?? {\n resolve: <T>(args: T) => registry.resolve(registryRunId, args),\n };\n const { resolved, unresolved } = view.resolve(\n hookResult.updatedInput\n );\n entry.args = resolved as Record<string, unknown>;\n if (entry.call.id != null) {\n if (unresolved.length > 0) {\n unresolvedByCallId.set(entry.call.id, unresolved);\n } else {\n unresolvedByCallId.delete(entry.call.id);\n }\n }\n } else {\n entry.args = hookResult.updatedInput;\n }\n }\n approvedEntries.push(entry);\n }\n } else {\n approvedEntries.push(...preToolCalls);\n }\n\n const injected: BaseMessage[] = [];\n\n const batchIndexByCallId = new Map<string, number>();\n\n if (approvedEntries.length > 0) {\n const requests: t.ToolCallRequest[] = approvedEntries.map((entry) => {\n const turn = this.toolUsageCount.get(entry.call.name) ?? 0;\n this.toolUsageCount.set(entry.call.name, turn + 1);\n\n if (entry.batchIndex != null && entry.call.id != null) {\n batchIndexByCallId.set(entry.call.id, entry.batchIndex);\n }\n\n const request: t.ToolCallRequest = {\n id: entry.call.id!,\n name: entry.call.name,\n args: entry.args,\n stepId: entry.stepId,\n turn,\n };\n\n /**\n * Emit `codeSessionContext` for any tool whose host handler may need\n * to reach into the code-execution sandbox:\n * - `CODE_EXECUTION_TOOLS` — direct executors that POST to /exec.\n * - `SKILL_TOOL` — skill files live alongside code-env state.\n * - `READ_FILE` — when the requested path is a code-env artifact\n * (e.g. `/mnt/data/...`) the host falls back to reading via the\n * same sandbox session; without the seeded `session_id` /\n * `_injected_files` here, that fallback can't see prior-turn\n * artifacts on the very first call of a turn.\n */\n if (\n CODE_EXECUTION_TOOLS.has(entry.call.name) ||\n entry.call.name === Constants.SKILL_TOOL ||\n entry.call.name === Constants.READ_FILE\n ) {\n request.codeSessionContext = this.getCodeSessionContext();\n }\n\n return request;\n });\n\n const requestMap = new Map(requests.map((r) => [r.id, r]));\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const batchRequest: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_EXECUTE,\n batchRequest,\n config\n );\n }\n );\n\n this.storeCodeSessionFromResults(results, requestMap);\n\n const hasPostHook =\n this.hookRegistry?.hasHookFor('PostToolUse', runId) === true;\n const hasFailureHook =\n this.hookRegistry?.hasHookFor('PostToolUseFailure', runId) === true;\n\n for (const result of results) {\n if (result.injectedMessages && result.injectedMessages.length > 0) {\n try {\n injected.push(\n ...this.convertInjectedMessages(result.injectedMessages)\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] Failed to convert injectedMessages for toolCallId=${result.toolCallId}:`,\n e instanceof Error ? e.message : e\n );\n }\n }\n const request = requestMap.get(result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n\n let contentString: string;\n let toolMessage: ToolMessage;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n /**\n * Error results bypass registration but stamp the\n * unresolved-refs hint into `additional_kwargs` so the lazy\n * annotation transform surfaces it to the LLM at request\n * time, letting the model self-correct when its reference\n * key caused the failure. Persisted `content` stays clean.\n */\n const unresolved = unresolvedByCallId.get(result.toolCallId) ?? [];\n const errorRefMeta =\n unresolved.length > 0\n ? this.recordOutputReference(\n registryRunId,\n contentString,\n undefined,\n unresolved\n )\n : undefined;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n ...(errorRefMeta != null && {\n additional_kwargs: errorRefMeta as Record<string, unknown>,\n }),\n });\n\n if (hasFailureHook) {\n await executeHooks({\n registry: this.hookRegistry!,\n input: {\n hook_event_name: 'PostToolUseFailure',\n runId,\n threadId,\n agentId: this.agentId,\n toolName,\n toolInput: request?.args ?? {},\n toolUseId: result.toolCallId,\n error: result.errorMessage ?? 'Unknown error',\n stepId: request?.stepId,\n turn: request?.turn,\n },\n sessionId: runId,\n matchQuery: toolName,\n }).catch(() => {\n /* PostToolUseFailure is observational — swallow errors */\n });\n }\n } else {\n let registryRaw =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n contentString = truncateToolResultContent(\n registryRaw,\n this.maxToolResultChars\n );\n\n if (hasPostHook) {\n const hookResult = await executeHooks({\n registry: this.hookRegistry!,\n input: {\n hook_event_name: 'PostToolUse',\n runId,\n threadId,\n agentId: this.agentId,\n toolName,\n toolInput: request?.args ?? {},\n toolOutput: result.content,\n toolUseId: result.toolCallId,\n stepId: request?.stepId,\n turn: request?.turn,\n },\n sessionId: runId,\n matchQuery: toolName,\n }).catch((): undefined => undefined);\n if (hookResult?.updatedOutput != null) {\n const replaced =\n typeof hookResult.updatedOutput === 'string'\n ? hookResult.updatedOutput\n : JSON.stringify(hookResult.updatedOutput);\n registryRaw = replaced;\n contentString = truncateToolResultContent(\n replaced,\n this.maxToolResultChars\n );\n }\n }\n\n const batchIndex = batchIndexByCallId.get(result.toolCallId);\n const unresolved = unresolvedByCallId.get(result.toolCallId) ?? [];\n const refKey =\n this.toolOutputRegistry != null &&\n batchIndex != null &&\n turn != null\n ? buildReferenceKey(batchIndex, turn)\n : undefined;\n const successRefMeta = this.recordOutputReference(\n registryRunId,\n registryRaw,\n refKey,\n unresolved\n );\n\n toolMessage = new ToolMessage({\n status: 'success',\n name: toolName,\n content: contentString,\n artifact: result.artifact,\n tool_call_id: result.toolCallId,\n ...(successRefMeta != null && {\n additional_kwargs: successRefMeta as Record<string, unknown>,\n }),\n });\n }\n\n this.dispatchStepCompleted(\n result.toolCallId,\n toolName,\n request?.args ?? {},\n contentString,\n config,\n request?.turn\n );\n\n messageByCallId.set(result.toolCallId, toolMessage);\n }\n }\n\n const toolMessages = toolCalls\n .map((call) => messageByCallId.get(call.id!))\n .filter((m): m is ToolMessage => m != null);\n return { toolMessages, injected };\n }\n\n private dispatchStepCompleted(\n toolCallId: string,\n toolName: string,\n args: Record<string, unknown>,\n output: string,\n config: RunnableConfig,\n turn?: number\n ): void {\n const stepId = this.toolCallStepIds?.get(toolCallId) ?? '';\n if (!stepId) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] toolCallStepIds missing entry for toolCallId=${toolCallId} (tool=${toolName}). ` +\n 'This indicates a race between the stream consumer and graph execution. ' +\n `Map size: ${this.toolCallStepIds?.size ?? 0}`\n );\n }\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: turn ?? this.toolUsageCount.get(toolName) ?? 0,\n type: 'tool_call' as const,\n tool_call: {\n args: JSON.stringify(args),\n name: toolName,\n id: toolCallId,\n output,\n progress: 1,\n } as t.ProcessedToolCall,\n },\n },\n config\n );\n }\n\n /**\n * Converts InjectedMessage instances to LangChain HumanMessage objects.\n * Both 'user' and 'system' roles become HumanMessage to avoid provider\n * rejections (Anthropic/Google reject non-leading SystemMessages).\n * The original role is preserved in additional_kwargs for downstream consumers.\n */\n private convertInjectedMessages(\n messages: t.InjectedMessage[]\n ): BaseMessage[] {\n const converted: BaseMessage[] = [];\n for (const msg of messages) {\n const additional_kwargs: Record<string, unknown> = {\n role: msg.role,\n };\n if (msg.isMeta != null) additional_kwargs.isMeta = msg.isMeta;\n if (msg.source != null) additional_kwargs.source = msg.source;\n if (msg.skillName != null) additional_kwargs.skillName = msg.skillName;\n\n converted.push(\n new HumanMessage({ content: msg.content, additional_kwargs })\n );\n }\n return converted;\n }\n\n /**\n * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Injected messages are placed AFTER ToolMessages to respect provider\n * message ordering (AIMessage tool_calls must be immediately followed\n * by their ToolMessage results).\n *\n * `batchIndices` mirrors `toolCalls` and carries each call's position\n * within the parent batch. `turn` is the per-`run()` batch index\n * captured locally by the caller. Both are threaded so concurrent\n * invocations cannot race on shared mutable state.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n batchContext: DispatchBatchContext = {}\n ): Promise<T> {\n const { toolMessages, injected } = await this.dispatchToolEvents(\n toolCalls,\n config,\n batchContext\n );\n const outputs: BaseMessage[] = [...toolMessages, ...injected];\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n this.toolCallTurns.clear();\n /**\n * Per-batch local map for resolved (post-substitution) args.\n * Lives on the stack so concurrent `run()` calls on the same\n * ToolNode cannot read or wipe each other's entries.\n */\n const resolvedArgsByCallId = new Map<string, Record<string, unknown>>();\n /**\n * Claim this batch's turn synchronously from the registry (or\n * fall back to 0 when the feature is disabled). The registry is\n * partitioned by scope id so overlapping batches cannot\n * overwrite each other's state even under a shared registry.\n *\n * For anonymous callers (no `run_id` in config), mint a unique\n * per-batch scope id so two concurrent anonymous invocations\n * don't target the same bucket. The scope is threaded down to\n * every subsequent registry call on this batch.\n */\n const incomingRunId = config.configurable?.run_id as string | undefined;\n const batchScopeId = incomingRunId ?? `\\0anon-${this.anonBatchCounter++}`;\n const turn = this.toolOutputRegistry?.nextTurn(batchScopeId) ?? 0;\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n const isDirectTool = this.directToolNames?.has(input.lg_tool_call.name);\n if (this.eventDrivenMode && isDirectTool !== true) {\n return this.executeViaEvent([input.lg_tool_call], config, input, {\n batchIndices: [0],\n turn,\n batchScopeId,\n });\n }\n outputs = [\n await this.runTool(input.lg_tool_call, config, {\n batchIndex: 0,\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n }),\n ];\n this.handleRunToolCompletions(\n [input.lg_tool_call],\n outputs,\n config,\n resolvedArgsByCallId\n );\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.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--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(\n call.id?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ??\n false\n )\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n const filteredIndices = filteredCalls.map((_, idx) => idx);\n\n if (!this.directToolNames || this.directToolNames.size === 0) {\n return this.executeViaEvent(filteredCalls, config, input, {\n batchIndices: filteredIndices,\n turn,\n batchScopeId,\n });\n }\n\n const directEntries: Array<{ call: ToolCall; batchIndex: number }> = [];\n const eventEntries: Array<{ call: ToolCall; batchIndex: number }> = [];\n for (let i = 0; i < filteredCalls.length; i++) {\n const call = filteredCalls[i];\n const entry = { call, batchIndex: i };\n if (this.directToolNames!.has(call.name)) {\n directEntries.push(entry);\n } else {\n eventEntries.push(entry);\n }\n }\n\n const directCalls = directEntries.map((e) => e.call);\n const directIndices = directEntries.map((e) => e.batchIndex);\n const eventCalls = eventEntries.map((e) => e.call);\n const eventIndices = eventEntries.map((e) => e.batchIndex);\n\n /**\n * Snapshot the event calls' args against the *pre-batch*\n * registry state synchronously, before any await runs. The\n * directs are then awaited first (preserving fail-fast\n * semantics — a thrown error in a direct tool, e.g. with\n * `handleToolErrors=false` or a `GraphInterrupt`, aborts\n * before we dispatch any event-driven tools to the host).\n * Because the event args were captured pre-await, they stay\n * isolated from same-turn direct outputs that register\n * during the await.\n */\n const preResolvedEventArgs = new Map<\n string,\n { resolved: Record<string, unknown>; unresolved: string[] }\n >();\n /**\n * Take a frozen snapshot of the registry state before any\n * direct registrations land. The snapshot resolves\n * placeholders against this point-in-time view, so a\n * `PreToolUse` hook later rewriting event args via\n * `updatedInput` can introduce placeholders that resolve\n * cross-batch (against prior runs) without ever picking up\n * same-turn direct outputs.\n */\n const preBatchSnapshot =\n this.toolOutputRegistry?.snapshot(batchScopeId);\n if (preBatchSnapshot != null) {\n for (const entry of eventEntries) {\n if (entry.call.id != null) {\n const { resolved, unresolved } = preBatchSnapshot.resolve(\n entry.call.args as Record<string, unknown>\n );\n preResolvedEventArgs.set(entry.call.id, {\n resolved: resolved as Record<string, unknown>,\n unresolved,\n });\n }\n }\n }\n\n const directOutputs: (BaseMessage | Command)[] =\n directCalls.length > 0\n ? await Promise.all(\n directCalls.map((call, i) =>\n this.runTool(call, config, {\n batchIndex: directIndices[i],\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n })\n )\n )\n : [];\n\n if (directCalls.length > 0 && directOutputs.length > 0) {\n this.handleRunToolCompletions(\n directCalls,\n directOutputs,\n config,\n resolvedArgsByCallId\n );\n }\n\n const eventResult =\n eventCalls.length > 0\n ? await this.dispatchToolEvents(eventCalls, config, {\n batchIndices: eventIndices,\n turn,\n batchScopeId,\n preResolvedArgs: preResolvedEventArgs,\n preBatchSnapshot,\n })\n : {\n toolMessages: [] as ToolMessage[],\n injected: [] as BaseMessage[],\n };\n\n outputs = [\n ...directOutputs,\n ...eventResult.toolMessages,\n ...eventResult.injected,\n ];\n } else {\n outputs = await Promise.all(\n filteredCalls.map((call, i) =>\n this.runTool(call, config, {\n batchIndex: i,\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n })\n )\n );\n this.handleRunToolCompletions(\n filteredCalls,\n outputs,\n config,\n resolvedArgsByCallId\n );\n }\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\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): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\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 if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const messages = Array.isArray(state) ? state : state.messages;\n const message = messages[messages.length - 1] as AIMessage | undefined;\n\n if (\n message &&\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n }\n return END;\n}\n"],"names":["Send","Constants","RunnableCallable","toolOutputReferences","calculateMaxToolResultChars","ToolOutputReferenceRegistry","buildReferenceKey","CODE_EXECUTION_TOOLS","isCommand","isBaseMessage","truncateToolResultContent","ToolMessage","isGraphInterrupt","safeDispatchCustomEvent","GraphEvents","executeHooks","messages","HumanMessage","isAIMessage","Command","END"],"mappings":";;;;;;;;;;;;;;;;AAoFA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA,cAAI;AAC9B;AAEA;;;;;;;;;;;;;;;;;;;AAmBG;AACH,SAAS,iBAAiB,CACxB,QAA0B,EAC1B,SAAiB,EACjB,KAA6B,EAAA;AAE7B,IAAA,MAAM,QAAQ,GAAG,KAAK,IAAI,EAAE;IAC5B,MAAM,eAAe,GAAG,QAAQ,CAAC,GAAG,CAACC,eAAS,CAAC,YAAY,CAE9C;AACb,IAAA,MAAM,aAAa,GAAG,eAAe,EAAE,KAAK,IAAI,EAAE;AAElD,IAAA,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;QACvB,MAAM,gBAAgB,GAAe,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,MAAM;AAC3D,YAAA,GAAG,IAAI;AACP,YAAA,UAAU,EAAE,IAAI,CAAC,UAAU,IAAI,SA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AAK,CAAC;AAAE,QAAA,OAAO,KAAK;AAC9D,IAAA,QACE,OAAO,CAAC,UAAU,EAAE,KAAK,CACvB,CAAC,QAAQ,KAAK,QAAQ,CAAC,EAAE,IAAI,IAAI,IAAI,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CACrE,IAAI,KAAK;AAEd;SAEgB,cAAc,CAC5B,KAAsD,EACtD,QAAW,EACX,cAA4B,EAAA;AAE5B,IAAA,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,QAAQ;IAC9D,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAA0B;AAEtE,IAAA,IACE,OAAO;AACP,QAAA,YAAY,IAAI,OAAO;QACvB,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;AACA,QAAA,OAAO,QAAQ;IACjB;AACA,IAAA,OAAOW,aAAG;AACZ;;;;;"}
1
+ {"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n HumanMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n interrupt,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\nimport { AsyncLocalStorageProviderSingleton } from '@langchain/core/singletons';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type {\n ToolOutputResolveView,\n PreResolvedArgsMap,\n ResolvedArgsByCallId,\n} from '@/tools/toolOutputReferences';\nimport type {\n HookRegistry,\n AggregatedHookResult,\n PostToolBatchEntry,\n} from '@/hooks';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\nimport {\n calculateMaxToolResultChars,\n truncateToolResultContent,\n} from '@/utils/truncation';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { executeHooks } from '@/hooks';\nimport { toLangChainContent } from '@/messages/langchain';\nimport { Constants, GraphEvents, CODE_EXECUTION_TOOLS } from '@/common';\nimport {\n buildReferenceKey,\n ToolOutputReferenceRegistry,\n} from '@/tools/toolOutputReferences';\n\n/**\n * Per-call batch context for `runTool`. Bundles every optional\n * batch-scoped value the method needs so the signature stays at\n * three positional parameters even as new context fields are added.\n */\ntype RunToolBatchContext = {\n /** Position of this call within the parent ToolNode batch. */\n batchIndex?: number;\n /** Batch turn shared across every call in the batch. */\n turn?: number;\n /** Registry partition scope (run id or anonymous batch id). */\n batchScopeId?: string;\n /** Batch-local sink for post-substitution args. */\n resolvedArgsByCallId?: ResolvedArgsByCallId;\n};\n\n/**\n * Per-batch context for `dispatchToolEvents` / `executeViaEvent`.\n * Mirrors {@link RunToolBatchContext} for the event-driven path,\n * with bulk indices and the snapshot/pre-resolved-args carriers\n * used in the mixed direct+event flow.\n */\ntype DispatchBatchContext = {\n /** Per-call batch indices, parallel to the `toolCalls` array. */\n batchIndices?: number[];\n /** Batch turn shared across every call in the batch. */\n turn?: number;\n /** Registry partition scope (run id or anonymous batch id). */\n batchScopeId?: string;\n /**\n * Pre-resolved args keyed by `toolCallId`. Populated by the mixed\n * path so event calls don't re-resolve against a registry that\n * already contains same-turn direct outputs.\n */\n preResolvedArgs?: PreResolvedArgsMap;\n /**\n * Frozen pre-batch registry view used to re-resolve placeholders\n * a `PreToolUse` hook injects via `updatedInput` — preserves the\n * same-turn isolation guarantee for hook-rewritten args.\n */\n preBatchSnapshot?: ToolOutputResolveView;\n};\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n/**\n * Format a fail-closed diagnostic for malformed approval-decision\n * fields. Hosts deserialize resume payloads from untyped JSON, so\n * `responseText` and `updatedInput` can land here as anything; the\n * blocking ToolMessage carries this string so the host can debug the\n * exact wire shape that was rejected.\n */\nfunction describeOfferedShape(value: unknown): string {\n if (value === undefined) {\n return '<missing>';\n }\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return 'array';\n }\n return typeof value;\n}\n\n/**\n * Per-entry record collected during PreToolUse hook handling for tool\n * calls that need human approval. Carries everything\n * `buildToolApprovalInterruptPayload` needs to assemble the interrupt\n * payload, plus the per-tool decision allowlist if the hook supplied\n * one. Defined at module scope so the payload-builder helper can be\n * extracted out of `dispatchToolEvents` without leaking the locally-\n * inferred shape.\n */\ntype AskEntry = {\n entry: {\n call: ToolCall;\n args: Record<string, unknown>;\n stepId: string;\n };\n reason?: string;\n allowedDecisions?: ReadonlyArray<'approve' | 'reject' | 'edit' | 'respond'>;\n};\n\n/**\n * Build the `tool_approval` interrupt payload from the set of pending\n * `ask`-decision entries collected during PreToolUse hook handling.\n * Pure function — doesn't touch ToolNode state — so it lives at module\n * scope. The interrupt itself is raised by the caller (which still\n * needs `interrupt()` plus the AsyncLocalStorage anchoring shim).\n */\nfunction buildToolApprovalInterruptPayload(\n askEntries: ReadonlyArray<AskEntry>\n): t.ToolApprovalInterruptPayload {\n return {\n type: 'tool_approval',\n action_requests: askEntries.map(({ entry, reason }) => {\n const request: t.ToolApprovalRequest = {\n tool_call_id: entry.call.id!,\n name: entry.call.name,\n arguments: entry.args,\n };\n if (reason != null) {\n request.description = reason;\n }\n return request;\n }),\n review_configs: askEntries.map(({ entry, allowedDecisions }) => ({\n action_name: entry.call.name,\n tool_call_id: entry.call.id!,\n allowed_decisions: (allowedDecisions ?? [\n 'approve',\n 'reject',\n 'edit',\n 'respond',\n ]) as t.ToolApprovalDecisionType[],\n })),\n };\n}\n\n/**\n * Build a `tool_call_id → ToolApprovalDecision` map from the host's\n * resume value. Hosts may return decisions either as an array (one per\n * action_request, in order) or as a record keyed by `tool_call_id`. Any\n * unrecognized shape (or a decision missing for a given call id) is\n * treated as \"no decision\" by callers — typically rejected so the run\n * doesn't silently invoke a tool the human never approved.\n */\nfunction normalizeApprovalDecisions(\n callIds: string[],\n resumeValue: t.ToolApprovalDecision[] | t.ToolApprovalDecisionMap | undefined\n): Map<string, t.ToolApprovalDecision> {\n const map = new Map<string, t.ToolApprovalDecision>();\n if (resumeValue == null) {\n return map;\n }\n if (Array.isArray(resumeValue)) {\n const limit = Math.min(callIds.length, resumeValue.length);\n for (let i = 0; i < limit; i++) {\n map.set(callIds[i], resumeValue[i]);\n }\n return map;\n }\n if (typeof resumeValue === 'object') {\n for (const callId of callIds) {\n const decision = (resumeValue as Partial<t.ToolApprovalDecisionMap>)[\n callId\n ];\n if (decision !== undefined) {\n map.set(callId, decision);\n }\n }\n }\n return map;\n}\n\n/**\n * Merges code execution session context into the sessions map.\n *\n * The codeapi worker reports two distinct ids on a code-execution result:\n * - `artifact.session_id` (the `sessionId` arg here) is the EXEC session\n * — the sandbox VM that ran the code. It's transient and torn down\n * post-execution; subsequent calls cannot reuse it as a sandbox.\n * - `file.session_id` on each `artifact.files[i]` is the STORAGE\n * session — the file-server bucket prefix where the artifact actually\n * lives and is served from.\n *\n * Per-file `session_id` is preserved (not overwritten with the exec id)\n * because `_injected_files` are looked up against the file-server's\n * storage path on subsequent tool calls. Stomping the storage id with\n * the exec id silently 404s every follow-up tool call within the same\n * run — `cat /mnt/data/foo.txt` reports \"No such file or directory\"\n * because the worker can't mount a file at a path the storage doesn't\n * know about. Fall back to `sessionId` only when the per-file id is\n * absent (older worker payloads).\n */\nfunction updateCodeSession(\n sessions: t.ToolSessionMap,\n sessionId: string,\n files: t.FileRefs | undefined\n): void {\n const newFiles = files ?? [];\n const existingSession = sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n if (newFiles.length > 0) {\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: file.session_id ?? sessionId,\n }));\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n sessions.set(Constants.EXECUTE_CODE, {\n session_id: sessionId,\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n } else {\n sessions.set(Constants.EXECUTE_CODE, {\n session_id: sessionId,\n files: existingFiles,\n lastUpdated: Date.now(),\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n /** Maps toolCallId → turn captured in runTool, used by handleRunToolCompletions */\n private toolCallTurns: Map<string, number> = new Map();\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n /** Tool names that bypass event dispatch and execute directly (e.g., graph-managed handoff tools) */\n private directToolNames?: Set<string>;\n /** Maximum characters allowed in a single tool result before truncation. */\n private maxToolResultChars: number;\n /** Hook registry for PreToolUse/PostToolUse lifecycle hooks */\n private hookRegistry?: HookRegistry;\n /**\n * Run-scoped HITL config. When `enabled`, `ask` decisions from\n * PreToolUse hooks raise a LangGraph `interrupt()` instead of being\n * treated as fail-closed denies.\n */\n private humanInTheLoop?: t.HumanInTheLoopConfig;\n /**\n * Registry of tool outputs keyed by `tool<idx>turn<turn>`.\n *\n * Populated only when `toolOutputReferences.enabled` is true. The\n * registry owns the run-scoped state (turn counter, last-seen runId,\n * warn-once memo, stored outputs), so sharing a single instance\n * across multiple ToolNodes in a run lets cross-agent `{{…}}`\n * references resolve — which is why multi-agent graphs pass the\n * *same* instance to every ToolNode they compile rather than each\n * ToolNode building its own.\n */\n private toolOutputRegistry?: ToolOutputReferenceRegistry;\n /**\n * Monotonic counter used to mint a unique scope id for anonymous\n * batches (ones invoked without a `run_id` in\n * `config.configurable`). Each such batch gets its own registry\n * partition so concurrent anonymous invocations can't delete each\n * other's in-flight state.\n */\n private anonBatchCounter: number = 0;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n agentId,\n directToolNames,\n maxContextTokens,\n maxToolResultChars,\n hookRegistry,\n humanInTheLoop,\n toolOutputReferences,\n toolOutputRegistry,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n this.toolRegistry = toolRegistry;\n this.sessions = sessions;\n this.eventDrivenMode = eventDrivenMode ?? false;\n this.agentId = agentId;\n this.directToolNames = directToolNames;\n this.maxToolResultChars =\n maxToolResultChars ?? calculateMaxToolResultChars(maxContextTokens);\n this.hookRegistry = hookRegistry;\n this.humanInTheLoop = humanInTheLoop;\n /**\n * Precedence: an explicitly passed `toolOutputRegistry` instance\n * wins over a config object so a host (`Graph`) can share one\n * registry across many ToolNodes. When only the config is\n * provided (direct ToolNode usage), build a local registry so\n * the feature still works without graph-level plumbing. Registry\n * caps are intentionally decoupled from `maxToolResultChars`:\n * the registry stores the raw untruncated output so a later\n * `{{…}}` substitution pipes the full payload into the next\n * tool, even when the LLM saw a truncated preview.\n */\n if (toolOutputRegistry != null) {\n this.toolOutputRegistry = toolOutputRegistry;\n } else if (toolOutputReferences?.enabled === true) {\n this.toolOutputRegistry = new ToolOutputReferenceRegistry({\n maxOutputSize: toolOutputReferences.maxOutputSize,\n maxTotalSize: toolOutputReferences.maxTotalSize,\n });\n }\n }\n\n /**\n * Returns the run-scoped tool output registry, or `undefined` when\n * the feature is disabled.\n *\n * @internal Exposed for test observation only. Host code should rely\n * on `{{tool<i>turn<n>}}` substitution at tool-invocation time and\n * not mutate the registry directly.\n */\n public _unsafeGetToolOutputRegistry():\n | ToolOutputReferenceRegistry\n | undefined {\n return this.toolOutputRegistry;\n }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n /**\n * Runs a single tool call with error handling.\n *\n * `batchIndex` is the tool's position within the current ToolNode\n * batch and, together with `this.currentTurn`, forms the key used to\n * register the output for future `{{tool<idx>turn<turn>}}`\n * substitutions. Omit when no registration should occur.\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig,\n batchContext: RunToolBatchContext = {}\n ): Promise<BaseMessage | Command> {\n const { batchIndex, turn, batchScopeId, resolvedArgsByCallId } =\n batchContext;\n const tool = this.toolMap.get(call.name);\n const registry = this.toolOutputRegistry;\n /**\n * Precompute the reference key once per call — captured locally\n * so concurrent `invoke()` calls on the same ToolNode cannot race\n * on a shared turn field.\n */\n const refKey =\n registry != null && batchIndex != null && turn != null\n ? buildReferenceKey(batchIndex, turn)\n : undefined;\n /**\n * Hoisted outside the try so the catch branch can append\n * `[unresolved refs: …]` to error messages — otherwise the LLM\n * only sees a generic error when it references a bad key, losing\n * the self-correction signal this feature is meant to provide.\n */\n let unresolvedRefs: string[] = [];\n /**\n * Use the caller-provided `batchScopeId` when threaded from\n * `run()` (so anonymous batches get their own unique scope).\n * Fall back to the config's `run_id` when runTool is invoked\n * from a context that doesn't thread it — that still preserves\n * the runId-based partitioning for named runs.\n */\n const runId =\n batchScopeId ?? (config.configurable?.run_id as string | undefined);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n /**\n * `usageCount` is the per-tool-name invocation index that\n * web-search and other tools observe via `invokeParams.turn`.\n * It is intentionally distinct from the outer `turn` parameter\n * (the batch turn used for ref keys); the latter is captured\n * before the try block when constructing `refKey`.\n */\n const usageCount = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, usageCount + 1);\n if (call.id != null && call.id !== '') {\n this.toolCallTurns.set(call.id, usageCount);\n }\n let args = call.args;\n if (registry != null) {\n const { resolved, unresolved } = registry.resolve(runId, args);\n args = resolved;\n unresolvedRefs = unresolved;\n /**\n * Expose the post-substitution args to downstream completion\n * events so audit logs / host-side `ON_RUN_STEP_COMPLETED`\n * handlers observe what actually ran, not the `{{…}}`\n * template. Only string/object args are worth recording.\n */\n if (\n resolvedArgsByCallId != null &&\n call.id != null &&\n call.id !== '' &&\n resolved !== call.args &&\n typeof resolved === 'object'\n ) {\n resolvedArgsByCallId.set(\n call.id,\n resolved as Record<string, unknown>\n );\n }\n }\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n // `turn` here is the per-tool usage count (matches what tools have\n // observed historically via config.toolCall.turn — e.g. web search).\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn: usageCount,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING ||\n call.name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING\n ) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n *\n * session_id is always injected when available (even without tracked files)\n * so the CodeExecutor can fall back to the /files endpoint for session continuity.\n */\n if (CODE_EXECUTION_TOOLS.has(call.name)) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.session_id != null && codeSession.session_id !== '') {\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files != null && codeSession.files.length > 0) {\n const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n invokeParams._injected_files = fileRefs;\n }\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n if (isCommand(output)) {\n return output;\n }\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n const isError = toolMsg.status === 'error';\n if (isError) {\n /**\n * Error ToolMessages bypass registration but still stamp the\n * unresolved-refs hint into `additional_kwargs` so the lazy\n * annotation transform surfaces it to the LLM, letting the\n * model self-correct when its reference key caused the\n * failure. Persisted `content` stays clean.\n */\n if (unresolvedRefs.length > 0) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n _unresolvedRefs: unresolvedRefs,\n };\n }\n return toolMsg;\n }\n if (this.toolOutputRegistry != null || unresolvedRefs.length > 0) {\n if (typeof toolMsg.content === 'string') {\n const rawContent = toolMsg.content;\n const llmContent = truncateToolResultContent(\n rawContent,\n this.maxToolResultChars\n );\n toolMsg.content = llmContent;\n const refMeta = this.recordOutputReference(\n runId,\n rawContent,\n refKey,\n unresolvedRefs\n );\n if (refMeta != null) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n ...refMeta,\n };\n }\n } else {\n /**\n * Non-string content (multi-part content blocks — text +\n * image). Known limitation: we cannot register under a\n * reference key because there's no canonical serialized\n * form. Warn once per tool per run when the caller\n * intended to register. The unresolved-refs hint is still\n * stamped as metadata; the lazy transform prepends a text\n * block at request time so the LLM gets the self-correction\n * signal.\n */\n if (unresolvedRefs.length > 0) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n _unresolvedRefs: unresolvedRefs,\n };\n }\n if (\n refKey != null &&\n this.toolOutputRegistry!.claimWarnOnce(runId, call.name)\n ) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] Skipping tool output reference for \"${call.name}\": ` +\n 'ToolMessage content is not a string (further occurrences for this tool in the same run are suppressed).'\n );\n }\n }\n }\n return toolMsg;\n }\n const rawContent =\n typeof output === 'string' ? output : JSON.stringify(output);\n const truncated = truncateToolResultContent(\n rawContent,\n this.maxToolResultChars\n );\n const refMeta = this.recordOutputReference(\n runId,\n rawContent,\n refKey,\n unresolvedRefs\n );\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: truncated,\n tool_call_id: call.id!,\n ...(refMeta != null && {\n additional_kwargs: refMeta as Record<string, unknown>,\n }),\n });\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n const errorContent = `Error: ${e.message}\\n Please fix your mistakes.`;\n const refMeta =\n unresolvedRefs.length > 0\n ? this.recordOutputReference(\n runId,\n errorContent,\n undefined,\n unresolvedRefs\n )\n : undefined;\n return new ToolMessage({\n status: 'error',\n content: errorContent,\n name: call.name,\n tool_call_id: call.id ?? '',\n ...(refMeta != null && {\n additional_kwargs: refMeta as Record<string, unknown>,\n }),\n });\n }\n }\n\n /**\n * Registers the full, raw output under `refKey` (when provided) and\n * builds the per-message ref metadata stamped onto the resulting\n * `ToolMessage.additional_kwargs`. The metadata is read at LLM-\n * request time by `annotateMessagesForLLM` to produce a transient\n * annotated copy of the message — the persisted `content` itself\n * stays clean.\n *\n * @param registryContent The full, untruncated output to store in\n * the registry so `{{tool<i>turn<n>}}` substitutions deliver the\n * complete payload. Ignored when `refKey` is undefined.\n * @param refKey Precomputed `tool<i>turn<n>` key, or undefined when\n * the output is not to be registered (errors, disabled feature,\n * unavailable batch/turn).\n * @param unresolved Placeholder keys that did not resolve; surfaced\n * to the LLM lazily so it can self-correct.\n * @returns A `ToolMessageRefMetadata` object when there is anything\n * to stamp, otherwise `undefined`.\n */\n private recordOutputReference(\n runId: string | undefined,\n registryContent: string,\n refKey: string | undefined,\n unresolved: string[]\n ): t.ToolMessageRefMetadata | undefined {\n if (this.toolOutputRegistry != null && refKey != null) {\n this.toolOutputRegistry.set(runId, refKey, registryContent);\n }\n if (refKey == null && unresolved.length === 0) return undefined;\n const meta: t.ToolMessageRefMetadata = {};\n if (refKey != null) {\n meta._refKey = refKey;\n /**\n * Stamp the registry scope alongside the key so the lazy\n * annotation transform can look up the right bucket. Anonymous\n * invocations get a synthetic per-batch scope (`\\0anon-<n>`)\n * that `attemptInvoke` cannot derive from\n * `config.configurable.run_id` — without this, anonymous-run\n * refs would silently fail registry lookup and the LLM would\n * never see `[ref: …]` markers for outputs that were registered.\n */\n if (runId != null) meta._refScope = runId;\n }\n if (unresolved.length > 0) meta._unresolvedRefs = unresolved;\n return meta;\n }\n\n /**\n * Builds code session context for injection into event-driven tool calls.\n * Mirrors the session injection logic in runTool() for direct execution.\n */\n private getCodeSessionContext(): t.ToolCallRequest['codeSessionContext'] {\n if (!this.sessions) {\n return undefined;\n }\n\n const codeSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (!codeSession) {\n return undefined;\n }\n\n const context: NonNullable<t.ToolCallRequest['codeSessionContext']> = {\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files && codeSession.files.length > 0) {\n context.files = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n }\n\n return context;\n }\n\n /**\n * Extracts code execution session context from tool results and stores in Graph.sessions.\n * Mirrors the session storage logic in handleRunToolCompletions for direct execution.\n */\n private storeCodeSessionFromResults(\n results: t.ToolExecuteResult[],\n requestMap: Map<string, t.ToolCallRequest>\n ): void {\n if (!this.sessions) {\n return;\n }\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n if (result.status !== 'success' || result.artifact == null) {\n continue;\n }\n\n const request = requestMap.get(result.toolCallId);\n if (\n !request?.name ||\n (!CODE_EXECUTION_TOOLS.has(request.name) &&\n request.name !== Constants.SKILL_TOOL)\n ) {\n continue;\n }\n\n const artifact = result.artifact as t.CodeExecutionArtifact | undefined;\n if (artifact?.session_id == null || artifact.session_id === '') {\n continue;\n }\n\n updateCodeSession(this.sessions, artifact.session_id!, artifact.files);\n }\n }\n\n /**\n * Post-processes standard runTool outputs: dispatches ON_RUN_STEP_COMPLETED\n * and stores code session context. Mirrors the completion handling in\n * dispatchToolEvents for the event-driven path.\n *\n * By handling completions here in graph context (rather than in the\n * stream consumer via ToolEndHandler), the race between the stream\n * consumer and graph execution is eliminated.\n *\n * @param resolvedArgsByCallId Per-batch resolved-args sink populated\n * by `runTool`. Threaded as a local map (instead of instance state)\n * so concurrent batches cannot read each other's entries.\n */\n private handleRunToolCompletions(\n calls: ToolCall[],\n outputs: (BaseMessage | Command)[],\n config: RunnableConfig,\n resolvedArgsByCallId?: ResolvedArgsByCallId\n ): void {\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i];\n const output = outputs[i];\n const turn = this.toolCallTurns.get(call.id!) ?? 0;\n\n if (isCommand(output)) {\n continue;\n }\n\n const toolMessage = output as ToolMessage;\n const toolCallId = call.id ?? '';\n\n // Skip error ToolMessages when errorHandler already dispatched ON_RUN_STEP_COMPLETED\n // via handleToolCallErrorStatic. Without this check, errors would be double-dispatched.\n if (toolMessage.status === 'error' && this.errorHandler != null) {\n continue;\n }\n\n if (this.sessions && CODE_EXECUTION_TOOLS.has(call.name)) {\n const artifact = toolMessage.artifact as\n | t.CodeExecutionArtifact\n | undefined;\n if (artifact?.session_id != null && artifact.session_id !== '') {\n updateCodeSession(this.sessions, artifact.session_id, artifact.files);\n }\n }\n\n // Dispatch ON_RUN_STEP_COMPLETED via custom event (same path as dispatchToolEvents)\n const stepId = this.toolCallStepIds?.get(toolCallId) ?? '';\n if (!stepId) {\n continue;\n }\n\n const contentString =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n /**\n * Prefer the post-substitution args when a `{{…}}` placeholder\n * was resolved in `runTool`. This keeps\n * `ON_RUN_STEP_COMPLETED.tool_call.args` consistent with what\n * the tool actually received rather than leaking the template.\n */\n const effectiveArgs = resolvedArgsByCallId?.get(toolCallId) ?? call.args;\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof effectiveArgs === 'string'\n ? (effectiveArgs as string)\n : JSON.stringify((effectiveArgs as unknown) ?? {}),\n name: call.name,\n id: toolCallId,\n output: contentString,\n progress: 1,\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: turn,\n type: 'tool_call' as const,\n tool_call,\n },\n },\n config\n );\n }\n }\n\n /**\n * Dispatches tool calls to the host via ON_TOOL_EXECUTE event and returns raw ToolMessages.\n * Core logic for event-driven execution, separated from output shaping.\n *\n * Hook lifecycle (when `hookRegistry` is set):\n * 1. **PreToolUse** fires per call in parallel before dispatch. Denied\n * calls produce error ToolMessages and fire **PermissionDenied**;\n * surviving calls proceed with optional `updatedInput`.\n * 2. Surviving calls are dispatched to the host via `ON_TOOL_EXECUTE`.\n * 3. **PostToolUse** / **PostToolUseFailure** fire per result. Post hooks\n * can replace tool output via `updatedOutput`.\n * 4. Injected messages from results are collected and returned alongside\n * ToolMessages (appended AFTER to respect provider ordering).\n */\n private async dispatchToolEvents(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n batchContext: DispatchBatchContext = {}\n ): Promise<{ toolMessages: ToolMessage[]; injected: BaseMessage[] }> {\n const {\n batchIndices,\n turn,\n batchScopeId,\n preResolvedArgs,\n preBatchSnapshot,\n } = batchContext;\n const runId = (config.configurable?.run_id as string | undefined) ?? '';\n /**\n * Registry-facing scope id — prefers the caller-threaded\n * `batchScopeId` so anonymous batches target their own unique\n * bucket and don't step on concurrent anonymous invocations.\n * Hooks and event payloads keep using the empty-string coerced\n * `runId` for backward compat.\n */\n const registryRunId =\n batchScopeId ?? (config.configurable?.run_id as string | undefined);\n const threadId = config.configurable?.thread_id as string | undefined;\n const registry = this.toolOutputRegistry;\n const unresolvedByCallId = new Map<string, string[]>();\n\n const preToolCalls = toolCalls.map((call, i) => {\n const originalArgs = call.args as Record<string, unknown>;\n let resolvedArgs = originalArgs;\n /**\n * When the caller provided a pre-resolved map (the mixed\n * direct+event path snapshots event args synchronously before\n * awaiting directs so they can't accidentally resolve\n * same-turn direct outputs), use those entries verbatim instead\n * of re-resolving against a registry that may have changed\n * since the batch started.\n */\n const pre = call.id != null ? preResolvedArgs?.get(call.id) : undefined;\n if (pre != null) {\n resolvedArgs = pre.resolved;\n if (pre.unresolved.length > 0 && call.id != null) {\n unresolvedByCallId.set(call.id, pre.unresolved);\n }\n } else if (registry != null) {\n const { resolved, unresolved } = registry.resolve(\n registryRunId,\n originalArgs\n );\n resolvedArgs = resolved as Record<string, unknown>;\n if (unresolved.length > 0 && call.id != null) {\n unresolvedByCallId.set(call.id, unresolved);\n }\n }\n return {\n call,\n stepId: this.toolCallStepIds?.get(call.id!) ?? '',\n args: resolvedArgs,\n batchIndex: batchIndices?.[i],\n };\n });\n\n const messageByCallId = new Map<string, ToolMessage>();\n const approvedEntries: typeof preToolCalls = [];\n /**\n * Batch-level accumulator for `additionalContext` strings returned\n * by any PreToolUse / PostToolUse / PostToolUseFailure hook in this\n * dispatch. We emit one consolidated `HumanMessage` after all tool\n * results land so the next model turn sees the injected context\n * exactly once, ordered after the ToolMessages.\n */\n const batchAdditionalContexts: string[] = [];\n /**\n * Batch-level outcome record keyed by `tool_call_id`. Captures\n * every tool call's final result (success / error from the host,\n * blocked from HITL deny / reject, substituted from HITL respond)\n * across the three call sites that touch it. We materialize the\n * `PostToolBatch` entry array in `toolCalls` order at dispatch\n * time so hooks correlating outcomes by position see exactly the\n * same sequence the model emitted — independent of when each\n * outcome was recorded (deny entries land synchronously in the\n * hook loop, approved entries land after host execution, respond\n * entries land in the resume branch).\n */\n const postToolBatchEntryByCallId = new Map<string, PostToolBatchEntry>();\n const HOOK_FALLBACK: AggregatedHookResult = Object.freeze({\n additionalContexts: [] as string[],\n errors: [] as string[],\n });\n\n if (this.hookRegistry?.hasHookFor('PreToolUse', runId) === true) {\n /**\n * Capture as a non-null local so the inner `blockEntry` closure\n * doesn't lose narrowing on `this.hookRegistry` and we don't have\n * to defensively `?.` it across every reference inside.\n */\n const hookRegistry = this.hookRegistry;\n const preResults = await Promise.all(\n preToolCalls.map((entry) =>\n executeHooks({\n registry: hookRegistry,\n input: {\n hook_event_name: 'PreToolUse',\n runId,\n threadId,\n agentId: this.agentId,\n toolName: entry.call.name,\n toolInput: entry.args,\n toolUseId: entry.call.id!,\n stepId: entry.stepId,\n turn: this.toolUsageCount.get(entry.call.name) ?? 0,\n },\n sessionId: runId,\n matchQuery: entry.call.name,\n }).catch((): AggregatedHookResult => HOOK_FALLBACK)\n )\n );\n\n type PendingEntry = (typeof preToolCalls)[number];\n\n /**\n * Side effects deferred from `blockEntry` until after any pending\n * `interrupt()` resolves. Without deferral, a batch that mixes a\n * `deny` decision with an `ask` decision would dispatch\n * `ON_RUN_STEP_COMPLETED` for the denied tool on the FIRST node\n * execution (before `interrupt()` throws), then dispatch the\n * same event AGAIN on the resume re-execution — hosts would\n * observe two completion events for one logical denial. By\n * queueing the dispatch + PermissionDenied hook here and\n * flushing after the interrupt block, we ensure each side effect\n * fires exactly once: never on the first pass when interrupt\n * throws (the flush is unreachable), once on resume / no-ask\n * passes when control reaches the flush.\n */\n const deferredBlockedSideEffects: Array<{\n callId: string;\n toolName: string;\n args: Record<string, unknown>;\n contentString: string;\n reason: string;\n }> = [];\n\n const blockEntry = (entry: PendingEntry, reason: string): void => {\n const contentString = `Blocked: ${reason}`;\n messageByCallId.set(\n entry.call.id!,\n new ToolMessage({\n status: 'error',\n content: contentString,\n name: entry.call.name,\n tool_call_id: entry.call.id!,\n })\n );\n postToolBatchEntryByCallId.set(entry.call.id!, {\n toolName: entry.call.name,\n toolInput: entry.args,\n toolUseId: entry.call.id!,\n stepId: entry.stepId,\n /**\n * Records the pre-invocation turn count — the same value the\n * executed path captures before incrementing `toolUsageCount`.\n * For a blocked tool the counter is never incremented (no\n * invocation happened), so this is always the count of prior\n * successful invocations of this tool name in earlier batches.\n * Surfaces in the `PostToolBatch` entry so batch hooks see\n * a uniform shape regardless of outcome.\n */\n turn: this.toolUsageCount.get(entry.call.name) ?? 0,\n status: 'error',\n error: contentString,\n });\n deferredBlockedSideEffects.push({\n callId: entry.call.id!,\n toolName: entry.call.name,\n args: entry.args,\n contentString,\n reason,\n });\n };\n\n const flushDeferredBlockedSideEffects = (): void => {\n for (const item of deferredBlockedSideEffects) {\n this.dispatchStepCompleted(\n item.callId,\n item.toolName,\n item.args,\n item.contentString,\n config\n );\n if (hookRegistry.hasHookFor('PermissionDenied', runId)) {\n executeHooks({\n registry: hookRegistry,\n input: {\n hook_event_name: 'PermissionDenied',\n runId,\n threadId,\n agentId: this.agentId,\n toolName: item.toolName,\n toolInput: item.args,\n toolUseId: item.callId,\n reason: item.reason,\n },\n sessionId: runId,\n matchQuery: item.toolName,\n }).catch(() => {\n /* PermissionDenied is observational — swallow errors */\n });\n }\n }\n deferredBlockedSideEffects.length = 0;\n };\n\n /**\n * Apply a hook-supplied or host-supplied input override to a pending\n * entry, re-running the `{{tool<i>turn<n>}}` resolver so any new\n * placeholders introduced by the override are substituted (and any\n * formerly-unresolved refs cleared from the unresolved set).\n *\n * Mixed direct+event batches must use the pre-batch snapshot so a\n * hook-introduced placeholder cannot accidentally resolve to a\n * same-turn direct output that has just registered. Pure event\n * batches don't have a snapshot and resolve against the live\n * registry — safe because no event-side registrations have happened\n * yet.\n */\n const applyInputOverride = (\n entry: PendingEntry,\n nextArgs: Record<string, unknown>\n ): void => {\n if (registry != null) {\n const view: ToolOutputResolveView = preBatchSnapshot ?? {\n resolve: <T>(args: T) => registry.resolve(registryRunId, args),\n };\n const { resolved, unresolved } = view.resolve(nextArgs);\n entry.args = resolved as Record<string, unknown>;\n if (entry.call.id != null) {\n if (unresolved.length > 0) {\n unresolvedByCallId.set(entry.call.id, unresolved);\n } else {\n unresolvedByCallId.delete(entry.call.id);\n }\n }\n return;\n }\n entry.args = nextArgs;\n };\n\n const askEntries: Array<{\n entry: PendingEntry;\n reason?: string;\n allowedDecisions?: ReadonlyArray<\n 'approve' | 'reject' | 'edit' | 'respond'\n >;\n }> = [];\n\n for (let i = 0; i < preToolCalls.length; i++) {\n const hookResult = preResults[i];\n const entry = preToolCalls[i];\n\n for (const ctx of hookResult.additionalContexts) {\n batchAdditionalContexts.push(ctx);\n }\n\n if (hookResult.decision === 'deny') {\n blockEntry(entry, hookResult.reason ?? 'Blocked by hook');\n continue;\n }\n\n if (hookResult.decision === 'ask') {\n /**\n * HITL is OFF by default — hosts must explicitly opt in via\n * `humanInTheLoop: { enabled: true }` to engage the\n * `interrupt()` path. When opted out (or omitted), `ask`\n * collapses into the pre-HITL fail-closed path: a blocked\n * tool with an error `ToolMessage`. The default stays\n * conservative until host UIs are ready to render\n * `tool_approval` interrupts; see `HumanInTheLoopConfig`\n * JSDoc for the full rationale and the migration plan.\n */\n if (this.humanInTheLoop?.enabled !== true) {\n blockEntry(entry, hookResult.reason ?? 'Blocked by hook');\n continue;\n }\n /**\n * Apply `updatedInput` BEFORE queuing into `askEntries` —\n * a hook is allowed to return both a sanitization rewrite\n * and an `ask` decision (e.g. one matcher redacts secrets,\n * another matcher requires approval). Without this, the\n * interrupt payload would surface the original args to the\n * reviewer AND the post-approve execution would run with\n * the original args, silently dropping the hook's rewrite.\n */\n if (hookResult.updatedInput != null) {\n applyInputOverride(entry, hookResult.updatedInput);\n }\n askEntries.push({\n entry,\n reason: hookResult.reason,\n allowedDecisions: hookResult.allowedDecisions,\n });\n continue;\n }\n\n if (hookResult.updatedInput != null) {\n applyInputOverride(entry, hookResult.updatedInput);\n }\n approvedEntries.push(entry);\n }\n\n /**\n * If any entries asked for approval, raise a single LangGraph\n * `interrupt()` carrying every pending request together. The host\n * pauses, gathers human input, and resumes the run with one\n * decision per request. On resume LangGraph re-executes this node\n * from the start; `interrupt()` then returns the resume value\n * instead of throwing, so the loop above re-runs and the same\n * `askEntries` list is rebuilt deterministically (assuming hooks\n * are pure — see `humanInTheLoop` docs).\n */\n if (askEntries.length > 0) {\n const payload = buildToolApprovalInterruptPayload(askEntries);\n\n /**\n * `interrupt()` reads the current `RunnableConfig` from\n * AsyncLocalStorage, but our `RunnableCallable` sets\n * `trace = false` for ToolNode (intentional — avoids LangSmith\n * tracing per tool call). Without the trace path, the upstream\n * `runWithConfig` frame is never established, so we re-anchor\n * here using the node's own `config` — Pregel hands us a\n * config that already carries every checkpoint/scratchpad key\n * `interrupt()` needs to suspend and resume.\n */\n const resumeValue = AsyncLocalStorageProviderSingleton.runWithConfig(\n config,\n () =>\n interrupt<\n t.ToolApprovalInterruptPayload,\n t.ToolApprovalDecision[] | t.ToolApprovalDecisionMap\n >(payload)\n );\n\n const decisionByCallId = normalizeApprovalDecisions(\n askEntries.map(({ entry }) => entry.call.id!),\n resumeValue\n );\n\n for (const {\n entry,\n reason: askReason,\n allowedDecisions,\n } of askEntries) {\n const decision = decisionByCallId.get(entry.call.id!) ?? {\n type: 'reject' as const,\n reason: 'No decision provided for tool approval',\n };\n /**\n * Read `decision.type` through a widened view once: hosts\n * deserialize resume payloads from untyped JSON, so the\n * runtime value can be a typo, the wrong type, or missing\n * entirely. Both the `allowedDecisions` enforcement\n * immediately below and the unknown-type fallthrough at the\n * end of this loop body share this single read so the\n * fail-closed checks compare against the same source.\n */\n const declaredType = (decision as { type?: unknown }).type;\n\n /**\n * Enforce the per-tool `allowedDecisions` allowlist that the\n * `PreToolUse` hook surfaced in `review_configs`. The host\n * UI is supposed to honor this when collecting the user's\n * decision, but the wire is untrusted: a buggy or hostile\n * host could submit a decision type the policy explicitly\n * forbids (e.g. `'edit'` when the hook restricted to\n * `['approve', 'reject']`), bypassing argument-mutation /\n * response-substitution safeguards. Fail closed when the\n * declared type isn't in the allowlist.\n */\n if (\n allowedDecisions != null &&\n (typeof declaredType !== 'string' ||\n !allowedDecisions.includes(\n declaredType as t.ToolApprovalDecisionType\n ))\n ) {\n const offered =\n typeof declaredType === 'string' ? declaredType : '<missing>';\n blockEntry(\n entry,\n `Decision \"${offered}\" not in allowedDecisions [${allowedDecisions.join(', ')}] — failing closed`\n );\n continue;\n }\n\n if (decision.type === 'reject') {\n blockEntry(\n entry,\n decision.reason ?? askReason ?? 'Rejected by user'\n );\n continue;\n }\n\n /**\n * `respond` short-circuits tool execution: the human supplies\n * the result the model should see in place of running the\n * tool. We emit a successful `ToolMessage` directly and skip\n * dispatch — no host event fires, no real tool side effect\n * occurs. Mirrors LangChain HITL middleware semantics.\n */\n if (decision.type === 'respond') {\n /**\n * Validate the wire shape before touching it: hosts\n * deserialize resume payloads from untyped JSON, so a\n * malformed `{ type: 'respond' }` (no `responseText`) or\n * `{ type: 'respond', responseText: 42 }` would crash\n * `truncateToolResultContent` (which calls\n * `content.length`) and turn a fail-closed approval path\n * into a hard run failure. Route bad shapes through\n * `blockEntry` like any other unusable decision.\n */\n const responseText = (decision as { responseText?: unknown })\n .responseText;\n if (typeof responseText !== 'string') {\n blockEntry(\n entry,\n `Decision \"respond\" missing string responseText (got ${describeOfferedShape(responseText)}) — failing closed`\n );\n continue;\n }\n /**\n * Truncate the human-supplied text just like the success\n * path does for real tool output. Without this, a user\n * pasting a large document as a manual response bypasses\n * `maxToolResultChars` and can blow past the model's\n * context window. The PostToolBatch entry surfaces the\n * truncated text too so batch hooks see what the model\n * will actually see.\n */\n const truncatedResponse = truncateToolResultContent(\n responseText,\n this.maxToolResultChars\n );\n messageByCallId.set(\n entry.call.id!,\n new ToolMessage({\n status: 'success',\n content: truncatedResponse,\n name: entry.call.name,\n tool_call_id: entry.call.id!,\n })\n );\n postToolBatchEntryByCallId.set(entry.call.id!, {\n toolName: entry.call.name,\n toolInput: entry.args,\n toolUseId: entry.call.id!,\n stepId: entry.stepId,\n turn: this.toolUsageCount.get(entry.call.name) ?? 0,\n status: 'success',\n toolOutput: truncatedResponse,\n });\n /**\n * Safe to dispatch immediately — unlike `blockEntry` which\n * defers, `respond` only executes inside the decision-\n * processing loop, which is reachable only AFTER\n * `interrupt()` has returned (the resume pass). There is\n * no risk of being rolled back by a subsequent throw, so\n * no risk of a duplicate `ON_RUN_STEP_COMPLETED` event.\n */\n this.dispatchStepCompleted(\n entry.call.id!,\n entry.call.name,\n entry.args,\n truncatedResponse,\n config\n );\n continue;\n }\n\n if (decision.type === 'edit') {\n /**\n * Validate the wire shape before touching it: hosts\n * deserialize resume payloads from untyped JSON, so a\n * malformed `{ type: 'edit' }` (no `updatedInput`),\n * `{ type: 'edit', updatedInput: 'string' }` (non-object),\n * or `{ type: 'edit', updatedInput: [...] }` (array, not a\n * plain object) would feed garbage into\n * `applyInputOverride` and silently approve a tool with\n * undefined / wrong-shape args. Same trust boundary as\n * the `respond` validation above — fail closed via\n * `blockEntry` with a diagnostic.\n */\n const updatedInput = (decision as { updatedInput?: unknown })\n .updatedInput;\n if (\n updatedInput === null ||\n typeof updatedInput !== 'object' ||\n Array.isArray(updatedInput)\n ) {\n blockEntry(\n entry,\n `Decision \"edit\" missing object updatedInput (got ${describeOfferedShape(updatedInput)}) — failing closed`\n );\n continue;\n }\n applyInputOverride(entry, updatedInput as Record<string, unknown>);\n approvedEntries.push(entry);\n continue;\n }\n\n /**\n * Defensive type widening: hosts deserialize resume payloads\n * from untyped JSON, so the `decision.type` value at runtime\n * is whatever string the wire sent — not necessarily one of\n * the four union variants TS knows about. We compare against\n * the literal `'approve'` through the widened `declaredType`\n * captured at the top of this iteration, so a typo or schema\n * drift (`'aproved'`, `null`, `undefined`) hits the fail-\n * closed branch below instead of silently approving the\n * tool. Without this widening, TS narrows the union after\n * the three earlier branches and treats `=== 'approve'` as\n * trivially true.\n */\n if (declaredType === 'approve') {\n approvedEntries.push(entry);\n continue;\n }\n\n /**\n * Unknown / missing decision type — fail closed. The whole\n * point of an approval gate is that \"no decision\" or\n * \"garbled decision\" deny by default.\n */\n const unknownType =\n typeof declaredType === 'string' ? declaredType : '<missing>';\n blockEntry(\n entry,\n `Unknown approval decision type \"${unknownType}\" — failing closed`\n );\n }\n }\n\n /**\n * Flush deferred denial side effects exactly once. On the FIRST\n * pass through a batch that contains an `ask`, `interrupt()`\n * threw above and we never reach this line — so no\n * `ON_RUN_STEP_COMPLETED` / `PermissionDenied` events fire\n * for blocked tools yet. On resume the node re-executes from\n * scratch, `blockEntry` re-queues the same entries, and the\n * flush below dispatches them once. For batches without any\n * `ask` (deny-only or empty), the flush still runs here and\n * dispatches in the same relative position as the pre-deferral\n * code did (after hook processing, before tool execution).\n */\n flushDeferredBlockedSideEffects();\n } else {\n approvedEntries.push(...preToolCalls);\n }\n\n const injected: BaseMessage[] = [];\n\n const batchIndexByCallId = new Map<string, number>();\n\n if (approvedEntries.length > 0) {\n const requests: t.ToolCallRequest[] = approvedEntries.map((entry) => {\n const turn = this.toolUsageCount.get(entry.call.name) ?? 0;\n this.toolUsageCount.set(entry.call.name, turn + 1);\n\n if (entry.batchIndex != null && entry.call.id != null) {\n batchIndexByCallId.set(entry.call.id, entry.batchIndex);\n }\n\n const request: t.ToolCallRequest = {\n id: entry.call.id!,\n name: entry.call.name,\n args: entry.args,\n stepId: entry.stepId,\n turn,\n };\n\n /**\n * Emit `codeSessionContext` for any tool whose host handler may need\n * to reach into the code-execution sandbox:\n * - `CODE_EXECUTION_TOOLS` — direct executors that POST to /exec.\n * - `SKILL_TOOL` — skill files live alongside code-env state.\n * - `READ_FILE` — when the requested path is a code-env artifact\n * (e.g. `/mnt/data/...`) the host falls back to reading via the\n * same sandbox session; without the seeded `session_id` /\n * `_injected_files` here, that fallback can't see prior-turn\n * artifacts on the very first call of a turn.\n */\n if (\n CODE_EXECUTION_TOOLS.has(entry.call.name) ||\n entry.call.name === Constants.SKILL_TOOL ||\n entry.call.name === Constants.READ_FILE\n ) {\n request.codeSessionContext = this.getCodeSessionContext();\n }\n\n return request;\n });\n\n const requestMap = new Map(requests.map((r) => [r.id, r]));\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const batchRequest: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_EXECUTE,\n batchRequest,\n config\n );\n }\n );\n\n this.storeCodeSessionFromResults(results, requestMap);\n\n const hasPostHook =\n this.hookRegistry?.hasHookFor('PostToolUse', runId) === true;\n const hasFailureHook =\n this.hookRegistry?.hasHookFor('PostToolUseFailure', runId) === true;\n\n for (const result of results) {\n if (result.injectedMessages && result.injectedMessages.length > 0) {\n try {\n injected.push(\n ...this.convertInjectedMessages(result.injectedMessages)\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] Failed to convert injectedMessages for toolCallId=${result.toolCallId}:`,\n e instanceof Error ? e.message : e\n );\n }\n }\n const request = requestMap.get(result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n\n let contentString: string;\n let toolMessage: ToolMessage;\n /**\n * Tracks the post-PostToolUse-hook output so the\n * `PostToolBatch` entry below sees the final transformed value\n * even when a hook replaced the original via `updatedOutput`.\n * Lives at the loop-iteration scope so the success branch can\n * mutate it; the error branch leaves it unset (and the batch\n * entry uses `error` instead of `toolOutput` in that case).\n */\n let finalToolOutput: unknown = result.content;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n /**\n * Error results bypass registration but stamp the\n * unresolved-refs hint into `additional_kwargs` so the lazy\n * annotation transform surfaces it to the LLM at request\n * time, letting the model self-correct when its reference\n * key caused the failure. Persisted `content` stays clean.\n */\n const unresolved = unresolvedByCallId.get(result.toolCallId) ?? [];\n const errorRefMeta =\n unresolved.length > 0\n ? this.recordOutputReference(\n registryRunId,\n contentString,\n undefined,\n unresolved\n )\n : undefined;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n ...(errorRefMeta != null && {\n additional_kwargs: errorRefMeta as Record<string, unknown>,\n }),\n });\n\n if (hasFailureHook) {\n const failureHookResult = await executeHooks({\n registry: this.hookRegistry!,\n input: {\n hook_event_name: 'PostToolUseFailure',\n runId,\n threadId,\n agentId: this.agentId,\n toolName,\n toolInput: request?.args ?? {},\n toolUseId: result.toolCallId,\n error: result.errorMessage ?? 'Unknown error',\n stepId: request?.stepId,\n turn: request?.turn,\n },\n sessionId: runId,\n matchQuery: toolName,\n }).catch((): undefined => undefined);\n /**\n * Collect `additionalContext` from failure hooks too. Without\n * this, recovery guidance returned on tool errors (e.g.\n * \"if this tool errors with X, suggest Y to the user\") is\n * silently dropped even though the API surface advertises\n * `additionalContext` for this event. PostToolUseFailure\n * remains observational for errors thrown by the hook\n * itself, but a successfully-returned result is honored.\n */\n if (failureHookResult != null) {\n for (const ctx of failureHookResult.additionalContexts) {\n batchAdditionalContexts.push(ctx);\n }\n }\n }\n } else {\n let registryRaw =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n contentString = truncateToolResultContent(\n registryRaw,\n this.maxToolResultChars\n );\n\n if (hasPostHook) {\n const hookResult = await executeHooks({\n registry: this.hookRegistry!,\n input: {\n hook_event_name: 'PostToolUse',\n runId,\n threadId,\n agentId: this.agentId,\n toolName,\n toolInput: request?.args ?? {},\n toolOutput: result.content,\n toolUseId: result.toolCallId,\n stepId: request?.stepId,\n turn: request?.turn,\n },\n sessionId: runId,\n matchQuery: toolName,\n }).catch((): undefined => undefined);\n if (hookResult != null) {\n for (const ctx of hookResult.additionalContexts) {\n batchAdditionalContexts.push(ctx);\n }\n }\n if (hookResult?.updatedOutput != null) {\n const replaced =\n typeof hookResult.updatedOutput === 'string'\n ? hookResult.updatedOutput\n : JSON.stringify(hookResult.updatedOutput);\n registryRaw = replaced;\n contentString = truncateToolResultContent(\n replaced,\n this.maxToolResultChars\n );\n finalToolOutput = hookResult.updatedOutput;\n }\n }\n\n const batchIndex = batchIndexByCallId.get(result.toolCallId);\n const unresolved = unresolvedByCallId.get(result.toolCallId) ?? [];\n const refKey =\n this.toolOutputRegistry != null &&\n batchIndex != null &&\n turn != null\n ? buildReferenceKey(batchIndex, turn)\n : undefined;\n const successRefMeta = this.recordOutputReference(\n registryRunId,\n registryRaw,\n refKey,\n unresolved\n );\n\n toolMessage = new ToolMessage({\n status: 'success',\n name: toolName,\n content: contentString,\n artifact: result.artifact,\n tool_call_id: result.toolCallId,\n ...(successRefMeta != null && {\n additional_kwargs: successRefMeta as Record<string, unknown>,\n }),\n });\n }\n\n this.dispatchStepCompleted(\n result.toolCallId,\n toolName,\n request?.args ?? {},\n contentString,\n config,\n request?.turn\n );\n\n postToolBatchEntryByCallId.set(result.toolCallId, {\n toolName,\n toolInput: request?.args ?? {},\n toolUseId: result.toolCallId,\n stepId: request?.stepId,\n turn: request?.turn,\n status: result.status === 'error' ? 'error' : 'success',\n ...(result.status === 'error'\n ? { error: result.errorMessage ?? 'Unknown error' }\n : { toolOutput: finalToolOutput }),\n });\n\n messageByCallId.set(result.toolCallId, toolMessage);\n }\n }\n\n const toolMessages = toolCalls\n .map((call) => messageByCallId.get(call.id!))\n .filter((m): m is ToolMessage => m != null);\n\n await this.dispatchPostToolBatchAndInjectContext({\n toolCalls,\n entriesByCallId: postToolBatchEntryByCallId,\n batchAdditionalContexts,\n injected,\n runId,\n threadId,\n });\n\n return { toolMessages, injected };\n }\n\n /**\n * Fires the `PostToolBatch` hook (if registered) and appends the\n * accumulated batch-level `additionalContext` strings to `injected`\n * as a single `HumanMessage`. Entries are materialized in the\n * original `toolCalls` order so hooks correlating outcomes by\n * position (as the type docs promise) see exactly the sequence\n * the model emitted, regardless of when each individual outcome\n * was recorded into the map (deny synchronous, approved\n * post-execution, respond on resume).\n *\n * The PostToolBatch hook's `additionalContexts` flow into the same\n * batch accumulator per-tool hooks already use, so a single\n * batch-level convention message can be injected through one path.\n *\n * Mutates `batchAdditionalContexts` (push from batch hook) and\n * `injected` (push the consolidated HumanMessage). The caller owns\n * those arrays and consumes them right after this returns.\n */\n private async dispatchPostToolBatchAndInjectContext(args: {\n toolCalls: ToolCall[];\n entriesByCallId: Map<string, PostToolBatchEntry>;\n batchAdditionalContexts: string[];\n injected: BaseMessage[];\n runId: string;\n threadId: string | undefined;\n }): Promise<void> {\n const {\n toolCalls,\n entriesByCallId,\n batchAdditionalContexts,\n injected,\n runId,\n threadId,\n } = args;\n\n const orderedBatchEntries: PostToolBatchEntry[] = [];\n for (const call of toolCalls) {\n const callId = call.id;\n if (callId == null) {\n continue;\n }\n const entry = entriesByCallId.get(callId);\n if (entry != null) {\n orderedBatchEntries.push(entry);\n }\n }\n if (\n this.hookRegistry?.hasHookFor('PostToolBatch', runId) === true &&\n orderedBatchEntries.length > 0\n ) {\n const batchHookResult = await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'PostToolBatch',\n runId,\n threadId,\n agentId: this.agentId,\n entries: orderedBatchEntries,\n },\n sessionId: runId,\n }).catch((): undefined => undefined);\n if (batchHookResult != null) {\n for (const ctx of batchHookResult.additionalContexts) {\n batchAdditionalContexts.push(ctx);\n }\n }\n }\n\n if (batchAdditionalContexts.length > 0) {\n /**\n * `HumanMessage` carrying a metadata `role: 'system'` marker —\n * see `convertInjectedMessages` for the wider rationale. Anthropic\n * and Google reject mid-conversation `SystemMessage`s, so we use\n * a user-role message and surface the system intent through\n * `additional_kwargs` for hosts inspecting state. The model sees\n * a user message; `role` is metadata only.\n */\n injected.push(\n new HumanMessage({\n content: batchAdditionalContexts.join('\\n\\n'),\n additional_kwargs: { role: 'system', source: 'hook' },\n })\n );\n }\n }\n\n private dispatchStepCompleted(\n toolCallId: string,\n toolName: string,\n args: Record<string, unknown>,\n output: string,\n config: RunnableConfig,\n turn?: number\n ): void {\n const stepId = this.toolCallStepIds?.get(toolCallId) ?? '';\n if (!stepId) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] toolCallStepIds missing entry for toolCallId=${toolCallId} (tool=${toolName}). ` +\n 'This indicates a race between the stream consumer and graph execution. ' +\n `Map size: ${this.toolCallStepIds?.size ?? 0}`\n );\n }\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: turn ?? this.toolUsageCount.get(toolName) ?? 0,\n type: 'tool_call' as const,\n tool_call: {\n args: JSON.stringify(args),\n name: toolName,\n id: toolCallId,\n output,\n progress: 1,\n } as t.ProcessedToolCall,\n },\n },\n config\n );\n }\n\n /**\n * Converts InjectedMessage instances to LangChain HumanMessage objects.\n * Both 'user' and 'system' roles become HumanMessage to avoid provider\n * rejections (Anthropic/Google reject non-leading SystemMessages).\n * The original role is preserved in additional_kwargs for downstream consumers.\n */\n private convertInjectedMessages(\n messages: t.InjectedMessage[]\n ): BaseMessage[] {\n const converted: BaseMessage[] = [];\n for (const msg of messages) {\n const additional_kwargs: Record<string, unknown> = {\n role: msg.role,\n };\n if (msg.isMeta != null) additional_kwargs.isMeta = msg.isMeta;\n if (msg.source != null) additional_kwargs.source = msg.source;\n if (msg.skillName != null) additional_kwargs.skillName = msg.skillName;\n\n converted.push(\n new HumanMessage({\n content: toLangChainContent(msg.content),\n additional_kwargs,\n })\n );\n }\n return converted;\n }\n\n /**\n * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Injected messages are placed AFTER ToolMessages to respect provider\n * message ordering (AIMessage tool_calls must be immediately followed\n * by their ToolMessage results).\n *\n * `batchIndices` mirrors `toolCalls` and carries each call's position\n * within the parent batch. `turn` is the per-`run()` batch index\n * captured locally by the caller. Both are threaded so concurrent\n * invocations cannot race on shared mutable state.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n batchContext: DispatchBatchContext = {}\n ): Promise<T> {\n const { toolMessages, injected } = await this.dispatchToolEvents(\n toolCalls,\n config,\n batchContext\n );\n const outputs: BaseMessage[] = [...toolMessages, ...injected];\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n this.toolCallTurns.clear();\n /**\n * Per-batch local map for resolved (post-substitution) args.\n * Lives on the stack so concurrent `run()` calls on the same\n * ToolNode cannot read or wipe each other's entries.\n */\n const resolvedArgsByCallId = new Map<string, Record<string, unknown>>();\n /**\n * Claim this batch's turn synchronously from the registry (or\n * fall back to 0 when the feature is disabled). The registry is\n * partitioned by scope id so overlapping batches cannot\n * overwrite each other's state even under a shared registry.\n *\n * For anonymous callers (no `run_id` in config), mint a unique\n * per-batch scope id so two concurrent anonymous invocations\n * don't target the same bucket. The scope is threaded down to\n * every subsequent registry call on this batch.\n */\n const incomingRunId = config.configurable?.run_id as string | undefined;\n const batchScopeId = incomingRunId ?? `\\0anon-${this.anonBatchCounter++}`;\n const turn = this.toolOutputRegistry?.nextTurn(batchScopeId) ?? 0;\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n const isDirectTool = this.directToolNames?.has(input.lg_tool_call.name);\n if (this.eventDrivenMode && isDirectTool !== true) {\n return this.executeViaEvent([input.lg_tool_call], config, input, {\n batchIndices: [0],\n turn,\n batchScopeId,\n });\n }\n outputs = [\n await this.runTool(input.lg_tool_call, config, {\n batchIndex: 0,\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n }),\n ];\n this.handleRunToolCompletions(\n [input.lg_tool_call],\n outputs,\n config,\n resolvedArgsByCallId\n );\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.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--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(\n call.id?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ??\n false\n )\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n const filteredIndices = filteredCalls.map((_, idx) => idx);\n\n if (!this.directToolNames || this.directToolNames.size === 0) {\n return this.executeViaEvent(filteredCalls, config, input, {\n batchIndices: filteredIndices,\n turn,\n batchScopeId,\n });\n }\n\n const directEntries: Array<{ call: ToolCall; batchIndex: number }> = [];\n const eventEntries: Array<{ call: ToolCall; batchIndex: number }> = [];\n for (let i = 0; i < filteredCalls.length; i++) {\n const call = filteredCalls[i];\n const entry = { call, batchIndex: i };\n if (this.directToolNames!.has(call.name)) {\n directEntries.push(entry);\n } else {\n eventEntries.push(entry);\n }\n }\n\n const directCalls = directEntries.map((e) => e.call);\n const directIndices = directEntries.map((e) => e.batchIndex);\n const eventCalls = eventEntries.map((e) => e.call);\n const eventIndices = eventEntries.map((e) => e.batchIndex);\n\n /**\n * Snapshot the event calls' args against the *pre-batch*\n * registry state synchronously, before any await runs. The\n * directs are then awaited first (preserving fail-fast\n * semantics — a thrown error in a direct tool, e.g. with\n * `handleToolErrors=false` or a `GraphInterrupt`, aborts\n * before we dispatch any event-driven tools to the host).\n * Because the event args were captured pre-await, they stay\n * isolated from same-turn direct outputs that register\n * during the await.\n */\n const preResolvedEventArgs = new Map<\n string,\n { resolved: Record<string, unknown>; unresolved: string[] }\n >();\n /**\n * Take a frozen snapshot of the registry state before any\n * direct registrations land. The snapshot resolves\n * placeholders against this point-in-time view, so a\n * `PreToolUse` hook later rewriting event args via\n * `updatedInput` can introduce placeholders that resolve\n * cross-batch (against prior runs) without ever picking up\n * same-turn direct outputs.\n */\n const preBatchSnapshot =\n this.toolOutputRegistry?.snapshot(batchScopeId);\n if (preBatchSnapshot != null) {\n for (const entry of eventEntries) {\n if (entry.call.id != null) {\n const { resolved, unresolved } = preBatchSnapshot.resolve(\n entry.call.args as Record<string, unknown>\n );\n preResolvedEventArgs.set(entry.call.id, {\n resolved: resolved as Record<string, unknown>,\n unresolved,\n });\n }\n }\n }\n\n const directOutputs: (BaseMessage | Command)[] =\n directCalls.length > 0\n ? await Promise.all(\n directCalls.map((call, i) =>\n this.runTool(call, config, {\n batchIndex: directIndices[i],\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n })\n )\n )\n : [];\n\n if (directCalls.length > 0 && directOutputs.length > 0) {\n this.handleRunToolCompletions(\n directCalls,\n directOutputs,\n config,\n resolvedArgsByCallId\n );\n }\n\n const eventResult =\n eventCalls.length > 0\n ? await this.dispatchToolEvents(eventCalls, config, {\n batchIndices: eventIndices,\n turn,\n batchScopeId,\n preResolvedArgs: preResolvedEventArgs,\n preBatchSnapshot,\n })\n : {\n toolMessages: [] as ToolMessage[],\n injected: [] as BaseMessage[],\n };\n\n outputs = [\n ...directOutputs,\n ...eventResult.toolMessages,\n ...eventResult.injected,\n ];\n } else {\n outputs = await Promise.all(\n filteredCalls.map((call, i) =>\n this.runTool(call, config, {\n batchIndex: i,\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n })\n )\n );\n this.handleRunToolCompletions(\n filteredCalls,\n outputs,\n config,\n resolvedArgsByCallId\n );\n }\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\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): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\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 if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const messages = Array.isArray(state) ? state : state.messages;\n const message = messages[messages.length - 1] as AIMessage | undefined;\n\n if (\n message &&\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n }\n return END;\n}\n"],"names":["Send","Constants","RunnableCallable","toolOutputReferences","calculateMaxToolResultChars","ToolOutputReferenceRegistry","buildReferenceKey","CODE_EXECUTION_TOOLS","isCommand","isBaseMessage","truncateToolResultContent","ToolMessage","isGraphInterrupt","safeDispatchCustomEvent","GraphEvents","executeHooks","AsyncLocalStorageProviderSingleton","interrupt","HumanMessage","messages","toLangChainContent","isAIMessage","Command","END"],"mappings":";;;;;;;;;;;;;;;;;;AA2FA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA,cAAI;AAC9B;AAEA;;;;;;AAMG;AACH,SAAS,oBAAoB,CAAC,KAAc,EAAA;AAC1C,IAAA,IAAI,KAAK,KAAK,SAAS,EAAE;AACvB,QAAA,OAAO,WAAW;IACpB;AACA,IAAA,IAAI,KAAK,KAAK,IAAI,EAAE;AAClB,QAAA,OAAO,MAAM;IACf;AACA,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACxB,QAAA,OAAO,OAAO;IAChB;IACA,OAAO,OAAO,KAAK;AACrB;AAqBA;;;;;;AAMG;AACH,SAAS,iCAAiC,CACxC,UAAmC,EAAA;IAEnC,OAAO;AACL,QAAA,IAAI,EAAE,eAAe;AACrB,QAAA,eAAe,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,KAAI;AACpD,YAAA,MAAM,OAAO,GAA0B;AACrC,gBAAA,YAAY,EAAE,KAAK,CAAC,IAAI,CAAC,EAAG;AAC5B,gBAAA,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI;gBACrB,SAAS,EAAE,KAAK,CAAC,IAAI;aACtB;AACD,YAAA,IAAI,MAAM,IAAI,IAAI,EAAE;AAClB,gBAAA,OAAO,CAAC,WAAW,GAAG,MAAM;YAC9B;AACA,YAAA,OAAO,OAAO;AAChB,QAAA,CAAC,CAAC;AACF,QA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