@librechat/agents 3.2.31 → 3.2.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (582) hide show
  1. package/dist/cjs/_virtual/_rolldown/runtime.cjs +23 -0
  2. package/dist/cjs/agents/AgentContext.cjs +844 -1046
  3. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  4. package/dist/cjs/common/constants.cjs +13 -13
  5. package/dist/cjs/common/constants.cjs.map +1 -1
  6. package/dist/cjs/common/enum.cjs +233 -240
  7. package/dist/cjs/common/enum.cjs.map +1 -1
  8. package/dist/cjs/common/index.cjs +2 -0
  9. package/dist/cjs/events.cjs +121 -169
  10. package/dist/cjs/events.cjs.map +1 -1
  11. package/dist/cjs/graphs/Graph.cjs +1389 -1807
  12. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  13. package/dist/cjs/graphs/MultiAgentGraph.cjs +713 -945
  14. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  15. package/dist/cjs/graphs/index.cjs +2 -0
  16. package/dist/cjs/hitl/askUserQuestion.cjs +60 -62
  17. package/dist/cjs/hitl/askUserQuestion.cjs.map +1 -1
  18. package/dist/cjs/hitl/index.cjs +1 -0
  19. package/dist/cjs/hooks/HookRegistry.cjs +176 -202
  20. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  21. package/dist/cjs/hooks/createToolPolicyHook.cjs +71 -101
  22. package/dist/cjs/hooks/createToolPolicyHook.cjs.map +1 -1
  23. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +170 -273
  24. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs.map +1 -1
  25. package/dist/cjs/hooks/executeHooks.cjs +227 -282
  26. package/dist/cjs/hooks/executeHooks.cjs.map +1 -1
  27. package/dist/cjs/hooks/index.cjs +6 -0
  28. package/dist/cjs/hooks/matchers.cjs +196 -230
  29. package/dist/cjs/hooks/matchers.cjs.map +1 -1
  30. package/dist/cjs/hooks/types.cjs +24 -24
  31. package/dist/cjs/hooks/types.cjs.map +1 -1
  32. package/dist/cjs/instrumentation.cjs +110 -137
  33. package/dist/cjs/instrumentation.cjs.map +1 -1
  34. package/dist/cjs/langchain/google-common.cjs +0 -3
  35. package/dist/cjs/langchain/index.cjs +80 -43
  36. package/dist/cjs/langchain/language_models/chat_models.cjs +0 -3
  37. package/dist/cjs/langchain/messages/tool.cjs +0 -3
  38. package/dist/cjs/langchain/messages.cjs +35 -18
  39. package/dist/cjs/langchain/openai.cjs +0 -3
  40. package/dist/cjs/langchain/prompts.cjs +5 -8
  41. package/dist/cjs/langchain/runnables.cjs +11 -10
  42. package/dist/cjs/langchain/tools.cjs +14 -11
  43. package/dist/cjs/langchain/utils/env.cjs +5 -8
  44. package/dist/cjs/langfuse.cjs +60 -79
  45. package/dist/cjs/langfuse.cjs.map +1 -1
  46. package/dist/cjs/langfuseToolOutputTracing.cjs +267 -399
  47. package/dist/cjs/langfuseToolOutputTracing.cjs.map +1 -1
  48. package/dist/cjs/llm/anthropic/index.cjs +432 -562
  49. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  50. package/dist/cjs/llm/anthropic/types.cjs +23 -47
  51. package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
  52. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +441 -696
  53. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  54. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +171 -252
  55. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
  56. package/dist/cjs/llm/anthropic/utils/output_parsers.cjs +2 -0
  57. package/dist/cjs/llm/anthropic/utils/tools.cjs +12 -26
  58. package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -1
  59. package/dist/cjs/llm/bedrock/index.cjs +195 -240
  60. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  61. package/dist/cjs/llm/bedrock/toolCache.cjs +84 -106
  62. package/dist/cjs/llm/bedrock/toolCache.cjs.map +1 -1
  63. package/dist/cjs/llm/bedrock/utils/index.cjs +2 -0
  64. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +357 -620
  65. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  66. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +105 -149
  67. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -1
  68. package/dist/cjs/llm/fake.cjs +86 -96
  69. package/dist/cjs/llm/fake.cjs.map +1 -1
  70. package/dist/cjs/llm/google/index.cjs +183 -237
  71. package/dist/cjs/llm/google/index.cjs.map +1 -1
  72. package/dist/cjs/llm/google/utils/common.cjs +398 -674
  73. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  74. package/dist/cjs/llm/google/utils/zod_to_genai_parameters.cjs +2 -0
  75. package/dist/cjs/llm/init.cjs +44 -53
  76. package/dist/cjs/llm/init.cjs.map +1 -1
  77. package/dist/cjs/llm/invoke.cjs +142 -182
  78. package/dist/cjs/llm/invoke.cjs.map +1 -1
  79. package/dist/cjs/llm/openai/index.cjs +991 -1276
  80. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  81. package/dist/cjs/llm/openai/utils/index.cjs +189 -316
  82. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  83. package/dist/cjs/llm/openrouter/index.cjs +102 -153
  84. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  85. package/dist/cjs/llm/openrouter/toolCache.cjs +35 -44
  86. package/dist/cjs/llm/openrouter/toolCache.cjs.map +1 -1
  87. package/dist/cjs/llm/providers.cjs +29 -37
  88. package/dist/cjs/llm/providers.cjs.map +1 -1
  89. package/dist/cjs/llm/request.cjs +20 -33
  90. package/dist/cjs/llm/request.cjs.map +1 -1
  91. package/dist/cjs/llm/vertexai/index.cjs +427 -453
  92. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  93. package/dist/cjs/main.cjs +547 -528
  94. package/dist/cjs/messages/anthropicToolCache.cjs +68 -119
  95. package/dist/cjs/messages/anthropicToolCache.cjs.map +1 -1
  96. package/dist/cjs/messages/cache.cjs +308 -401
  97. package/dist/cjs/messages/cache.cjs.map +1 -1
  98. package/dist/cjs/messages/content.cjs +36 -49
  99. package/dist/cjs/messages/content.cjs.map +1 -1
  100. package/dist/cjs/messages/contextPruning.cjs +112 -145
  101. package/dist/cjs/messages/contextPruning.cjs.map +1 -1
  102. package/dist/cjs/messages/contextPruningSettings.cjs +36 -46
  103. package/dist/cjs/messages/contextPruningSettings.cjs.map +1 -1
  104. package/dist/cjs/messages/core.cjs +256 -397
  105. package/dist/cjs/messages/core.cjs.map +1 -1
  106. package/dist/cjs/messages/format.cjs +904 -1382
  107. package/dist/cjs/messages/format.cjs.map +1 -1
  108. package/dist/cjs/messages/ids.cjs +16 -20
  109. package/dist/cjs/messages/ids.cjs.map +1 -1
  110. package/dist/cjs/messages/index.cjs +12 -0
  111. package/dist/cjs/messages/langchain.cjs +18 -18
  112. package/dist/cjs/messages/langchain.cjs.map +1 -1
  113. package/dist/cjs/messages/prune.cjs +1054 -1517
  114. package/dist/cjs/messages/prune.cjs.map +1 -1
  115. package/dist/cjs/messages/recency.cjs +77 -95
  116. package/dist/cjs/messages/recency.cjs.map +1 -1
  117. package/dist/cjs/messages/reducer.cjs +63 -78
  118. package/dist/cjs/messages/reducer.cjs.map +1 -1
  119. package/dist/cjs/messages/tools.cjs +51 -79
  120. package/dist/cjs/messages/tools.cjs.map +1 -1
  121. package/dist/cjs/openai/index.cjs +171 -217
  122. package/dist/cjs/openai/index.cjs.map +1 -1
  123. package/dist/cjs/responses/index.cjs +302 -391
  124. package/dist/cjs/responses/index.cjs.map +1 -1
  125. package/dist/cjs/run.cjs +903 -1113
  126. package/dist/cjs/run.cjs.map +1 -1
  127. package/dist/cjs/session/AgentSession.cjs +805 -986
  128. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  129. package/dist/cjs/session/JsonlSessionStore.cjs +327 -410
  130. package/dist/cjs/session/JsonlSessionStore.cjs.map +1 -1
  131. package/dist/cjs/session/handlers.cjs +192 -208
  132. package/dist/cjs/session/handlers.cjs.map +1 -1
  133. package/dist/cjs/session/ids.cjs +9 -10
  134. package/dist/cjs/session/ids.cjs.map +1 -1
  135. package/dist/cjs/session/index.cjs +4 -0
  136. package/dist/cjs/session/messageSerialization.cjs +94 -156
  137. package/dist/cjs/session/messageSerialization.cjs.map +1 -1
  138. package/dist/cjs/splitStream.cjs +147 -206
  139. package/dist/cjs/splitStream.cjs.map +1 -1
  140. package/dist/cjs/stream.cjs +856 -1344
  141. package/dist/cjs/stream.cjs.map +1 -1
  142. package/dist/cjs/summarization/index.cjs +57 -101
  143. package/dist/cjs/summarization/index.cjs.map +1 -1
  144. package/dist/cjs/summarization/node.cjs +643 -796
  145. package/dist/cjs/summarization/node.cjs.map +1 -1
  146. package/dist/cjs/tools/BashExecutor.cjs +110 -136
  147. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  148. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +165 -245
  149. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  150. package/dist/cjs/tools/Calculator.cjs +36 -57
  151. package/dist/cjs/tools/Calculator.cjs.map +1 -1
  152. package/dist/cjs/tools/CodeExecutor.cjs +126 -168
  153. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  154. package/dist/cjs/tools/CodeSessionFileSummary.cjs +36 -46
  155. package/dist/cjs/tools/CodeSessionFileSummary.cjs.map +1 -1
  156. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +459 -649
  157. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  158. package/dist/cjs/tools/ReadFile.cjs +17 -20
  159. package/dist/cjs/tools/ReadFile.cjs.map +1 -1
  160. package/dist/cjs/tools/SkillTool.cjs +26 -27
  161. package/dist/cjs/tools/SkillTool.cjs.map +1 -1
  162. package/dist/cjs/tools/SubagentTool.cjs +59 -61
  163. package/dist/cjs/tools/SubagentTool.cjs.map +1 -1
  164. package/dist/cjs/tools/ToolNode.cjs +2109 -2686
  165. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  166. package/dist/cjs/tools/ToolSearch.cjs +663 -825
  167. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  168. package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs +248 -340
  169. package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs.map +1 -1
  170. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs +170 -197
  171. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs.map +1 -1
  172. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs +425 -520
  173. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs.map +1 -1
  174. package/dist/cjs/tools/cloudflare/CloudflareSandboxTools.cjs +91 -124
  175. package/dist/cjs/tools/cloudflare/CloudflareSandboxTools.cjs.map +1 -1
  176. package/dist/cjs/tools/cloudflare/index.cjs +4 -0
  177. package/dist/cjs/tools/eagerEventExecution.cjs +75 -99
  178. package/dist/cjs/tools/eagerEventExecution.cjs.map +1 -1
  179. package/dist/cjs/tools/handlers.cjs +200 -262
  180. package/dist/cjs/tools/handlers.cjs.map +1 -1
  181. package/dist/cjs/tools/local/CompileCheckTool.cjs +150 -212
  182. package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -1
  183. package/dist/cjs/tools/local/FileCheckpointer.cjs +77 -85
  184. package/dist/cjs/tools/local/FileCheckpointer.cjs.map +1 -1
  185. package/dist/cjs/tools/local/LocalCodingTools.cjs +763 -1022
  186. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  187. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +666 -941
  188. package/dist/cjs/tools/local/LocalExecutionEngine.cjs.map +1 -1
  189. package/dist/cjs/tools/local/LocalExecutionTools.cjs +49 -92
  190. package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -1
  191. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +286 -354
  192. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -1
  193. package/dist/cjs/tools/local/attachments.cjs +108 -165
  194. package/dist/cjs/tools/local/attachments.cjs.map +1 -1
  195. package/dist/cjs/tools/local/bashAst.cjs +99 -113
  196. package/dist/cjs/tools/local/bashAst.cjs.map +1 -1
  197. package/dist/cjs/tools/local/editStrategies.cjs +126 -169
  198. package/dist/cjs/tools/local/editStrategies.cjs.map +1 -1
  199. package/dist/cjs/tools/local/index.cjs +12 -0
  200. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +136 -218
  201. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
  202. package/dist/cjs/tools/local/syntaxCheck.cjs +142 -161
  203. package/dist/cjs/tools/local/syntaxCheck.cjs.map +1 -1
  204. package/dist/cjs/tools/local/textEncoding.cjs +25 -23
  205. package/dist/cjs/tools/local/textEncoding.cjs.map +1 -1
  206. package/dist/cjs/tools/local/workspaceFS.cjs +38 -46
  207. package/dist/cjs/tools/local/workspaceFS.cjs.map +1 -1
  208. package/dist/cjs/tools/ptcTimeout.cjs +27 -47
  209. package/dist/cjs/tools/ptcTimeout.cjs.map +1 -1
  210. package/dist/cjs/tools/schema.cjs +24 -23
  211. package/dist/cjs/tools/schema.cjs.map +1 -1
  212. package/dist/cjs/tools/search/anthropic.cjs +24 -33
  213. package/dist/cjs/tools/search/anthropic.cjs.map +1 -1
  214. package/dist/cjs/tools/search/content.cjs +95 -137
  215. package/dist/cjs/tools/search/content.cjs.map +1 -1
  216. package/dist/cjs/tools/search/firecrawl.cjs +141 -172
  217. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  218. package/dist/cjs/tools/search/format.cjs +128 -196
  219. package/dist/cjs/tools/search/format.cjs.map +1 -1
  220. package/dist/cjs/tools/search/highlights.cjs +165 -232
  221. package/dist/cjs/tools/search/highlights.cjs.map +1 -1
  222. package/dist/cjs/tools/search/index.cjs +2 -0
  223. package/dist/cjs/tools/search/rerankers.cjs +151 -174
  224. package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
  225. package/dist/cjs/tools/search/schema.cjs +40 -39
  226. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  227. package/dist/cjs/tools/search/search.cjs +428 -530
  228. package/dist/cjs/tools/search/search.cjs.map +1 -1
  229. package/dist/cjs/tools/search/serper-scraper.cjs +106 -127
  230. package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -1
  231. package/dist/cjs/tools/search/tavily-scraper.cjs +129 -181
  232. package/dist/cjs/tools/search/tavily-scraper.cjs.map +1 -1
  233. package/dist/cjs/tools/search/tavily-search.cjs +295 -359
  234. package/dist/cjs/tools/search/tavily-search.cjs.map +1 -1
  235. package/dist/cjs/tools/search/tool.cjs +260 -299
  236. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  237. package/dist/cjs/tools/search/utils.cjs +74 -117
  238. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  239. package/dist/cjs/tools/skillCatalog.cjs +54 -72
  240. package/dist/cjs/tools/skillCatalog.cjs.map +1 -1
  241. package/dist/cjs/tools/streamedToolCallSeals.cjs +19 -36
  242. package/dist/cjs/tools/streamedToolCallSeals.cjs.map +1 -1
  243. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +612 -771
  244. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  245. package/dist/cjs/tools/subagent/index.cjs +1 -0
  246. package/dist/cjs/tools/toolOutputReferences.cjs +523 -630
  247. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  248. package/dist/cjs/utils/callbacks.cjs +11 -21
  249. package/dist/cjs/utils/callbacks.cjs.map +1 -1
  250. package/dist/cjs/utils/errors.cjs +70 -95
  251. package/dist/cjs/utils/errors.cjs.map +1 -1
  252. package/dist/cjs/utils/events.cjs +32 -42
  253. package/dist/cjs/utils/events.cjs.map +1 -1
  254. package/dist/cjs/utils/graph.cjs +8 -12
  255. package/dist/cjs/utils/graph.cjs.map +1 -1
  256. package/dist/cjs/utils/handlers.cjs +60 -82
  257. package/dist/cjs/utils/handlers.cjs.map +1 -1
  258. package/dist/cjs/utils/index.cjs +9 -0
  259. package/dist/cjs/utils/llm.cjs +19 -27
  260. package/dist/cjs/utils/llm.cjs.map +1 -1
  261. package/dist/cjs/utils/misc.cjs +30 -46
  262. package/dist/cjs/utils/misc.cjs.map +1 -1
  263. package/dist/cjs/utils/run.cjs +50 -66
  264. package/dist/cjs/utils/run.cjs.map +1 -1
  265. package/dist/cjs/utils/schema.cjs +11 -19
  266. package/dist/cjs/utils/schema.cjs.map +1 -1
  267. package/dist/cjs/utils/title.cjs +71 -106
  268. package/dist/cjs/utils/title.cjs.map +1 -1
  269. package/dist/cjs/utils/tokens.cjs +186 -283
  270. package/dist/cjs/utils/tokens.cjs.map +1 -1
  271. package/dist/cjs/utils/truncation.cjs +95 -114
  272. package/dist/cjs/utils/truncation.cjs.map +1 -1
  273. package/dist/esm/agents/AgentContext.mjs +844 -1044
  274. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  275. package/dist/esm/common/constants.mjs +13 -11
  276. package/dist/esm/common/constants.mjs.map +1 -1
  277. package/dist/esm/common/enum.mjs +221 -238
  278. package/dist/esm/common/enum.mjs.map +1 -1
  279. package/dist/esm/common/index.mjs +3 -0
  280. package/dist/esm/events.mjs +121 -167
  281. package/dist/esm/events.mjs.map +1 -1
  282. package/dist/esm/graphs/Graph.mjs +1388 -1804
  283. package/dist/esm/graphs/Graph.mjs.map +1 -1
  284. package/dist/esm/graphs/MultiAgentGraph.mjs +713 -943
  285. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  286. package/dist/esm/graphs/index.mjs +3 -0
  287. package/dist/esm/hitl/askUserQuestion.mjs +60 -60
  288. package/dist/esm/hitl/askUserQuestion.mjs.map +1 -1
  289. package/dist/esm/hitl/index.mjs +2 -0
  290. package/dist/esm/hooks/HookRegistry.mjs +176 -200
  291. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  292. package/dist/esm/hooks/createToolPolicyHook.mjs +71 -99
  293. package/dist/esm/hooks/createToolPolicyHook.mjs.map +1 -1
  294. package/dist/esm/hooks/createWorkspacePolicyHook.mjs +170 -271
  295. package/dist/esm/hooks/createWorkspacePolicyHook.mjs.map +1 -1
  296. package/dist/esm/hooks/executeHooks.mjs +227 -280
  297. package/dist/esm/hooks/executeHooks.mjs.map +1 -1
  298. package/dist/esm/hooks/index.mjs +7 -0
  299. package/dist/esm/hooks/matchers.mjs +196 -228
  300. package/dist/esm/hooks/matchers.mjs.map +1 -1
  301. package/dist/esm/hooks/types.mjs +24 -22
  302. package/dist/esm/hooks/types.mjs.map +1 -1
  303. package/dist/esm/instrumentation.mjs +109 -132
  304. package/dist/esm/instrumentation.mjs.map +1 -1
  305. package/dist/esm/langchain/google-common.mjs +1 -2
  306. package/dist/esm/langchain/index.mjs +5 -5
  307. package/dist/esm/langchain/language_models/chat_models.mjs +1 -2
  308. package/dist/esm/langchain/messages/tool.mjs +1 -2
  309. package/dist/esm/langchain/messages.mjs +2 -2
  310. package/dist/esm/langchain/openai.mjs +1 -2
  311. package/dist/esm/langchain/prompts.mjs +2 -2
  312. package/dist/esm/langchain/runnables.mjs +2 -2
  313. package/dist/esm/langchain/tools.mjs +2 -2
  314. package/dist/esm/langchain/utils/env.mjs +2 -2
  315. package/dist/esm/langfuse.mjs +60 -76
  316. package/dist/esm/langfuse.mjs.map +1 -1
  317. package/dist/esm/langfuseToolOutputTracing.mjs +267 -395
  318. package/dist/esm/langfuseToolOutputTracing.mjs.map +1 -1
  319. package/dist/esm/llm/anthropic/index.mjs +432 -559
  320. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  321. package/dist/esm/llm/anthropic/types.mjs +23 -45
  322. package/dist/esm/llm/anthropic/types.mjs.map +1 -1
  323. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +439 -690
  324. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  325. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +171 -249
  326. package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
  327. package/dist/esm/llm/anthropic/utils/output_parsers.mjs +3 -0
  328. package/dist/esm/llm/anthropic/utils/tools.mjs +12 -24
  329. package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -1
  330. package/dist/esm/llm/bedrock/index.mjs +195 -238
  331. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  332. package/dist/esm/llm/bedrock/toolCache.mjs +84 -104
  333. package/dist/esm/llm/bedrock/toolCache.mjs.map +1 -1
  334. package/dist/esm/llm/bedrock/utils/index.mjs +3 -0
  335. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +357 -618
  336. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  337. package/dist/esm/llm/bedrock/utils/message_outputs.mjs +105 -147
  338. package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -1
  339. package/dist/esm/llm/fake.mjs +86 -94
  340. package/dist/esm/llm/fake.mjs.map +1 -1
  341. package/dist/esm/llm/google/index.mjs +183 -235
  342. package/dist/esm/llm/google/index.mjs.map +1 -1
  343. package/dist/esm/llm/google/utils/common.mjs +397 -666
  344. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  345. package/dist/esm/llm/google/utils/zod_to_genai_parameters.mjs +3 -0
  346. package/dist/esm/llm/init.mjs +44 -51
  347. package/dist/esm/llm/init.mjs.map +1 -1
  348. package/dist/esm/llm/invoke.mjs +142 -180
  349. package/dist/esm/llm/invoke.mjs.map +1 -1
  350. package/dist/esm/llm/openai/index.mjs +991 -1271
  351. package/dist/esm/llm/openai/index.mjs.map +1 -1
  352. package/dist/esm/llm/openai/utils/index.mjs +188 -312
  353. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  354. package/dist/esm/llm/openrouter/index.mjs +102 -151
  355. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  356. package/dist/esm/llm/openrouter/toolCache.mjs +35 -42
  357. package/dist/esm/llm/openrouter/toolCache.mjs.map +1 -1
  358. package/dist/esm/llm/providers.mjs +29 -34
  359. package/dist/esm/llm/providers.mjs.map +1 -1
  360. package/dist/esm/llm/request.mjs +20 -31
  361. package/dist/esm/llm/request.mjs.map +1 -1
  362. package/dist/esm/llm/vertexai/index.mjs +427 -449
  363. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  364. package/dist/esm/main.mjs +99 -87
  365. package/dist/esm/messages/anthropicToolCache.mjs +68 -117
  366. package/dist/esm/messages/anthropicToolCache.mjs.map +1 -1
  367. package/dist/esm/messages/cache.mjs +308 -399
  368. package/dist/esm/messages/cache.mjs.map +1 -1
  369. package/dist/esm/messages/content.mjs +36 -47
  370. package/dist/esm/messages/content.mjs.map +1 -1
  371. package/dist/esm/messages/contextPruning.mjs +112 -143
  372. package/dist/esm/messages/contextPruning.mjs.map +1 -1
  373. package/dist/esm/messages/contextPruningSettings.mjs +36 -44
  374. package/dist/esm/messages/contextPruningSettings.mjs.map +1 -1
  375. package/dist/esm/messages/core.mjs +254 -393
  376. package/dist/esm/messages/core.mjs.map +1 -1
  377. package/dist/esm/messages/format.mjs +902 -1378
  378. package/dist/esm/messages/format.mjs.map +1 -1
  379. package/dist/esm/messages/ids.mjs +16 -18
  380. package/dist/esm/messages/ids.mjs.map +1 -1
  381. package/dist/esm/messages/index.mjs +13 -0
  382. package/dist/esm/messages/langchain.mjs +18 -16
  383. package/dist/esm/messages/langchain.mjs.map +1 -1
  384. package/dist/esm/messages/prune.mjs +1053 -1514
  385. package/dist/esm/messages/prune.mjs.map +1 -1
  386. package/dist/esm/messages/recency.mjs +77 -93
  387. package/dist/esm/messages/recency.mjs.map +1 -1
  388. package/dist/esm/messages/reducer.mjs +63 -76
  389. package/dist/esm/messages/reducer.mjs.map +1 -1
  390. package/dist/esm/messages/tools.mjs +49 -75
  391. package/dist/esm/messages/tools.mjs.map +1 -1
  392. package/dist/esm/openai/index.mjs +170 -215
  393. package/dist/esm/openai/index.mjs.map +1 -1
  394. package/dist/esm/responses/index.mjs +301 -389
  395. package/dist/esm/responses/index.mjs.map +1 -1
  396. package/dist/esm/run.mjs +903 -1111
  397. package/dist/esm/run.mjs.map +1 -1
  398. package/dist/esm/session/AgentSession.mjs +806 -985
  399. package/dist/esm/session/AgentSession.mjs.map +1 -1
  400. package/dist/esm/session/JsonlSessionStore.mjs +326 -407
  401. package/dist/esm/session/JsonlSessionStore.mjs.map +1 -1
  402. package/dist/esm/session/handlers.mjs +192 -206
  403. package/dist/esm/session/handlers.mjs.map +1 -1
  404. package/dist/esm/session/ids.mjs +9 -8
  405. package/dist/esm/session/ids.mjs.map +1 -1
  406. package/dist/esm/session/index.mjs +5 -0
  407. package/dist/esm/session/messageSerialization.mjs +94 -154
  408. package/dist/esm/session/messageSerialization.mjs.map +1 -1
  409. package/dist/esm/splitStream.mjs +147 -204
  410. package/dist/esm/splitStream.mjs.map +1 -1
  411. package/dist/esm/stream.mjs +854 -1341
  412. package/dist/esm/stream.mjs.map +1 -1
  413. package/dist/esm/summarization/index.mjs +57 -99
  414. package/dist/esm/summarization/index.mjs.map +1 -1
  415. package/dist/esm/summarization/node.mjs +640 -790
  416. package/dist/esm/summarization/node.mjs.map +1 -1
  417. package/dist/esm/tools/BashExecutor.mjs +103 -129
  418. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  419. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +162 -239
  420. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  421. package/dist/esm/tools/Calculator.mjs +34 -36
  422. package/dist/esm/tools/Calculator.mjs.map +1 -1
  423. package/dist/esm/tools/CodeExecutor.mjs +123 -164
  424. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  425. package/dist/esm/tools/CodeSessionFileSummary.mjs +36 -44
  426. package/dist/esm/tools/CodeSessionFileSummary.mjs.map +1 -1
  427. package/dist/esm/tools/ProgrammaticToolCalling.mjs +454 -644
  428. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  429. package/dist/esm/tools/ReadFile.mjs +17 -18
  430. package/dist/esm/tools/ReadFile.mjs.map +1 -1
  431. package/dist/esm/tools/SkillTool.mjs +26 -25
  432. package/dist/esm/tools/SkillTool.mjs.map +1 -1
  433. package/dist/esm/tools/SubagentTool.mjs +59 -59
  434. package/dist/esm/tools/SubagentTool.mjs.map +1 -1
  435. package/dist/esm/tools/ToolNode.mjs +2107 -2684
  436. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  437. package/dist/esm/tools/ToolSearch.mjs +659 -804
  438. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  439. package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs +248 -338
  440. package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs.map +1 -1
  441. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs +170 -195
  442. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs.map +1 -1
  443. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs +424 -517
  444. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs.map +1 -1
  445. package/dist/esm/tools/cloudflare/CloudflareSandboxTools.mjs +91 -122
  446. package/dist/esm/tools/cloudflare/CloudflareSandboxTools.mjs.map +1 -1
  447. package/dist/esm/tools/cloudflare/index.mjs +5 -0
  448. package/dist/esm/tools/eagerEventExecution.mjs +75 -96
  449. package/dist/esm/tools/eagerEventExecution.mjs.map +1 -1
  450. package/dist/esm/tools/handlers.mjs +200 -260
  451. package/dist/esm/tools/handlers.mjs.map +1 -1
  452. package/dist/esm/tools/local/CompileCheckTool.mjs +150 -210
  453. package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -1
  454. package/dist/esm/tools/local/FileCheckpointer.mjs +77 -83
  455. package/dist/esm/tools/local/FileCheckpointer.mjs.map +1 -1
  456. package/dist/esm/tools/local/LocalCodingTools.mjs +760 -1017
  457. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  458. package/dist/esm/tools/local/LocalExecutionEngine.mjs +663 -936
  459. package/dist/esm/tools/local/LocalExecutionEngine.mjs.map +1 -1
  460. package/dist/esm/tools/local/LocalExecutionTools.mjs +49 -90
  461. package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -1
  462. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +283 -349
  463. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -1
  464. package/dist/esm/tools/local/attachments.mjs +108 -163
  465. package/dist/esm/tools/local/attachments.mjs.map +1 -1
  466. package/dist/esm/tools/local/bashAst.mjs +99 -111
  467. package/dist/esm/tools/local/bashAst.mjs.map +1 -1
  468. package/dist/esm/tools/local/editStrategies.mjs +126 -167
  469. package/dist/esm/tools/local/editStrategies.mjs.map +1 -1
  470. package/dist/esm/tools/local/index.mjs +13 -0
  471. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +136 -216
  472. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
  473. package/dist/esm/tools/local/syntaxCheck.mjs +138 -155
  474. package/dist/esm/tools/local/syntaxCheck.mjs.map +1 -1
  475. package/dist/esm/tools/local/textEncoding.mjs +25 -21
  476. package/dist/esm/tools/local/textEncoding.mjs.map +1 -1
  477. package/dist/esm/tools/local/workspaceFS.mjs +38 -44
  478. package/dist/esm/tools/local/workspaceFS.mjs.map +1 -1
  479. package/dist/esm/tools/ptcTimeout.mjs +27 -42
  480. package/dist/esm/tools/ptcTimeout.mjs.map +1 -1
  481. package/dist/esm/tools/schema.mjs +24 -21
  482. package/dist/esm/tools/schema.mjs.map +1 -1
  483. package/dist/esm/tools/search/anthropic.mjs +24 -31
  484. package/dist/esm/tools/search/anthropic.mjs.map +1 -1
  485. package/dist/esm/tools/search/content.mjs +93 -116
  486. package/dist/esm/tools/search/content.mjs.map +1 -1
  487. package/dist/esm/tools/search/firecrawl.mjs +139 -169
  488. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  489. package/dist/esm/tools/search/format.mjs +128 -194
  490. package/dist/esm/tools/search/format.mjs.map +1 -1
  491. package/dist/esm/tools/search/highlights.mjs +165 -230
  492. package/dist/esm/tools/search/highlights.mjs.map +1 -1
  493. package/dist/esm/tools/search/index.mjs +3 -0
  494. package/dist/esm/tools/search/rerankers.mjs +149 -168
  495. package/dist/esm/tools/search/rerankers.mjs.map +1 -1
  496. package/dist/esm/tools/search/schema.mjs +39 -37
  497. package/dist/esm/tools/search/schema.mjs.map +1 -1
  498. package/dist/esm/tools/search/search.mjs +426 -528
  499. package/dist/esm/tools/search/search.mjs.map +1 -1
  500. package/dist/esm/tools/search/serper-scraper.mjs +104 -124
  501. package/dist/esm/tools/search/serper-scraper.mjs.map +1 -1
  502. package/dist/esm/tools/search/tavily-scraper.mjs +127 -178
  503. package/dist/esm/tools/search/tavily-scraper.mjs.map +1 -1
  504. package/dist/esm/tools/search/tavily-search.mjs +293 -357
  505. package/dist/esm/tools/search/tavily-search.mjs.map +1 -1
  506. package/dist/esm/tools/search/tool.mjs +259 -297
  507. package/dist/esm/tools/search/tool.mjs.map +1 -1
  508. package/dist/esm/tools/search/utils.mjs +74 -115
  509. package/dist/esm/tools/search/utils.mjs.map +1 -1
  510. package/dist/esm/tools/skillCatalog.mjs +54 -70
  511. package/dist/esm/tools/skillCatalog.mjs.map +1 -1
  512. package/dist/esm/tools/streamedToolCallSeals.mjs +19 -31
  513. package/dist/esm/tools/streamedToolCallSeals.mjs.map +1 -1
  514. package/dist/esm/tools/subagent/SubagentExecutor.mjs +612 -768
  515. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  516. package/dist/esm/tools/subagent/index.mjs +2 -0
  517. package/dist/esm/tools/toolOutputReferences.mjs +523 -624
  518. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  519. package/dist/esm/utils/callbacks.mjs +11 -19
  520. package/dist/esm/utils/callbacks.mjs.map +1 -1
  521. package/dist/esm/utils/errors.mjs +70 -93
  522. package/dist/esm/utils/errors.mjs.map +1 -1
  523. package/dist/esm/utils/events.mjs +32 -40
  524. package/dist/esm/utils/events.mjs.map +1 -1
  525. package/dist/esm/utils/graph.mjs +8 -10
  526. package/dist/esm/utils/graph.mjs.map +1 -1
  527. package/dist/esm/utils/handlers.mjs +60 -80
  528. package/dist/esm/utils/handlers.mjs.map +1 -1
  529. package/dist/esm/utils/index.mjs +10 -0
  530. package/dist/esm/utils/llm.mjs +19 -25
  531. package/dist/esm/utils/llm.mjs.map +1 -1
  532. package/dist/esm/utils/misc.mjs +30 -44
  533. package/dist/esm/utils/misc.mjs.map +1 -1
  534. package/dist/esm/utils/run.mjs +50 -64
  535. package/dist/esm/utils/run.mjs.map +1 -1
  536. package/dist/esm/utils/schema.mjs +11 -17
  537. package/dist/esm/utils/schema.mjs.map +1 -1
  538. package/dist/esm/utils/title.mjs +71 -104
  539. package/dist/esm/utils/title.mjs.map +1 -1
  540. package/dist/esm/utils/tokens.mjs +186 -281
  541. package/dist/esm/utils/tokens.mjs.map +1 -1
  542. package/dist/esm/utils/truncation.mjs +95 -112
  543. package/dist/esm/utils/truncation.mjs.map +1 -1
  544. package/dist/types/messages/format.d.ts +5 -0
  545. package/dist/types/tools/search/tool.d.ts +17 -0
  546. package/dist/types/tools/search/types.d.ts +4 -0
  547. package/package.json +11 -17
  548. package/src/llm/anthropic/llm.spec.ts +36 -0
  549. package/src/llm/anthropic/utils/message_inputs.ts +45 -3
  550. package/src/llm/anthropic/utils/message_outputs.ts +6 -2
  551. package/src/llm/anthropic/utils/streaming-tool-input.test.ts +186 -0
  552. package/src/messages/cache.test.ts +122 -0
  553. package/src/messages/cache.ts +25 -1
  554. package/src/messages/format.ts +9 -0
  555. package/src/messages/formatAgentMessages.skills.test.ts +100 -0
  556. package/src/tools/search/highlights.ts +9 -1
  557. package/src/tools/search/search.ts +41 -3
  558. package/src/tools/search/source-processing.test.ts +373 -0
  559. package/src/tools/search/tool.ts +22 -2
  560. package/src/tools/search/types.ts +4 -0
  561. package/dist/cjs/langchain/google-common.cjs.map +0 -1
  562. package/dist/cjs/langchain/index.cjs.map +0 -1
  563. package/dist/cjs/langchain/language_models/chat_models.cjs.map +0 -1
  564. package/dist/cjs/langchain/messages/tool.cjs.map +0 -1
  565. package/dist/cjs/langchain/messages.cjs.map +0 -1
  566. package/dist/cjs/langchain/openai.cjs.map +0 -1
  567. package/dist/cjs/langchain/prompts.cjs.map +0 -1
  568. package/dist/cjs/langchain/runnables.cjs.map +0 -1
  569. package/dist/cjs/langchain/tools.cjs.map +0 -1
  570. package/dist/cjs/langchain/utils/env.cjs.map +0 -1
  571. package/dist/cjs/main.cjs.map +0 -1
  572. package/dist/esm/langchain/google-common.mjs.map +0 -1
  573. package/dist/esm/langchain/index.mjs.map +0 -1
  574. package/dist/esm/langchain/language_models/chat_models.mjs.map +0 -1
  575. package/dist/esm/langchain/messages/tool.mjs.map +0 -1
  576. package/dist/esm/langchain/messages.mjs.map +0 -1
  577. package/dist/esm/langchain/openai.mjs.map +0 -1
  578. package/dist/esm/langchain/prompts.mjs.map +0 -1
  579. package/dist/esm/langchain/runnables.mjs.map +0 -1
  580. package/dist/esm/langchain/tools.mjs.map +0 -1
  581. package/dist/esm/langchain/utils/env.mjs.map +0 -1
  582. package/dist/esm/main.mjs.map +0 -1
@@ -1,968 +1,669 @@
1
- 'use strict';
2
-
3
- var _enum = require('./common/enum.cjs');
4
- var streamedToolCallSeals = require('./tools/streamedToolCallSeals.cjs');
5
- var eagerEventExecution = require('./tools/eagerEventExecution.cjs');
6
- var handlers = require('./tools/handlers.cjs');
7
- var truncation = require('./utils/truncation.cjs');
8
- var toolOutputReferences = require('./tools/toolOutputReferences.cjs');
9
- var events = require('./utils/events.cjs');
10
- var llm = require('./utils/llm.cjs');
11
- require('./messages/core.cjs');
12
- var ids = require('./messages/ids.cjs');
13
- require('@langchain/core/messages');
14
- require('node:crypto');
15
- require('uuid');
16
-
17
- const LOCAL_CODING_BUNDLE_NAME_SET = new Set(_enum.LOCAL_CODING_BUNDLE_NAMES);
1
+ const require_enum = require("./common/enum.cjs");
2
+ require("./common/index.cjs");
3
+ const require_ids = require("./messages/ids.cjs");
4
+ const require_truncation = require("./utils/truncation.cjs");
5
+ const require_events = require("./utils/events.cjs");
6
+ require("./messages/index.cjs");
7
+ const require_llm = require("./utils/llm.cjs");
8
+ const require_streamedToolCallSeals = require("./tools/streamedToolCallSeals.cjs");
9
+ const require_eagerEventExecution = require("./tools/eagerEventExecution.cjs");
10
+ const require_handlers = require("./tools/handlers.cjs");
11
+ const require_toolOutputReferences = require("./tools/toolOutputReferences.cjs");
12
+ //#region src/stream.ts
13
+ const LOCAL_CODING_BUNDLE_NAME_SET = new Set(require_enum.LOCAL_CODING_BUNDLE_NAMES);
18
14
  /**
19
- * Parses content to extract thinking sections enclosed in <think> tags using string operations
20
- * @param content The content to parse
21
- * @returns An object with separated text and thinking content
22
- */
15
+ * Parses content to extract thinking sections enclosed in <think> tags using string operations
16
+ * @param content The content to parse
17
+ * @returns An object with separated text and thinking content
18
+ */
23
19
  function parseThinkingContent(content) {
24
- // If no think tags, return the original content as text
25
- if (!content.includes('<think>')) {
26
- return { text: content, thinking: '' };
27
- }
28
- let textResult = '';
29
- const thinkingResult = [];
30
- let position = 0;
31
- while (position < content.length) {
32
- const thinkStart = content.indexOf('<think>', position);
33
- if (thinkStart === -1) {
34
- // No more think tags, add the rest and break
35
- textResult += content.slice(position);
36
- break;
37
- }
38
- // Add text before the think tag
39
- textResult += content.slice(position, thinkStart);
40
- const thinkEnd = content.indexOf('</think>', thinkStart);
41
- if (thinkEnd === -1) {
42
- // Malformed input, no closing tag
43
- textResult += content.slice(thinkStart);
44
- break;
45
- }
46
- // Add the thinking content
47
- const thinkContent = content.slice(thinkStart + 7, thinkEnd);
48
- thinkingResult.push(thinkContent);
49
- // Move position to after the think tag
50
- position = thinkEnd + 8; // 8 is the length of '</think>'
51
- }
52
- return {
53
- text: textResult.trim(),
54
- thinking: thinkingResult.join('\n').trim(),
55
- };
20
+ if (!content.includes("<think>")) return {
21
+ text: content,
22
+ thinking: ""
23
+ };
24
+ let textResult = "";
25
+ const thinkingResult = [];
26
+ let position = 0;
27
+ while (position < content.length) {
28
+ const thinkStart = content.indexOf("<think>", position);
29
+ if (thinkStart === -1) {
30
+ textResult += content.slice(position);
31
+ break;
32
+ }
33
+ textResult += content.slice(position, thinkStart);
34
+ const thinkEnd = content.indexOf("</think>", thinkStart);
35
+ if (thinkEnd === -1) {
36
+ textResult += content.slice(thinkStart);
37
+ break;
38
+ }
39
+ const thinkContent = content.slice(thinkStart + 7, thinkEnd);
40
+ thinkingResult.push(thinkContent);
41
+ position = thinkEnd + 8;
42
+ }
43
+ return {
44
+ text: textResult.trim(),
45
+ thinking: thinkingResult.join("\n").trim()
46
+ };
56
47
  }
57
48
  function getNonEmptyValue(possibleValues) {
58
- for (const value of possibleValues) {
59
- if (value && value.trim() !== '') {
60
- return value;
61
- }
62
- }
63
- return undefined;
49
+ for (const value of possibleValues) if (value && value.trim() !== "") return value;
64
50
  }
65
51
  function isBatchSensitiveToolExecution(graph) {
66
- return graph.hookRegistry != null || graph.humanInTheLoop?.enabled === true;
52
+ return graph.hookRegistry != null || graph.humanInTheLoop?.enabled === true;
67
53
  }
68
54
  function hasToolOutputReference(value) {
69
- if (typeof value === 'string') {
70
- return toolOutputReferences.TOOL_OUTPUT_REF_PATTERN.test(value);
71
- }
72
- if (Array.isArray(value)) {
73
- return value.some((item) => hasToolOutputReference(item));
74
- }
75
- if (value !== null && typeof value === 'object') {
76
- return Object.values(value).some((item) => hasToolOutputReference(item));
77
- }
78
- return false;
55
+ if (typeof value === "string") return require_toolOutputReferences.TOOL_OUTPUT_REF_PATTERN.test(value);
56
+ if (Array.isArray(value)) return value.some((item) => hasToolOutputReference(item));
57
+ if (value !== null && typeof value === "object") return Object.values(value).some((item) => hasToolOutputReference(item));
58
+ return false;
79
59
  }
80
60
  function isDirectGraphTool(name, agentContext) {
81
- if (name.startsWith(_enum.Constants.LC_TRANSFER_TO_)) {
82
- return true;
83
- }
84
- return (agentContext?.graphTools?.some((tool) => 'name' in tool && tool.name === name) === true);
61
+ if (name.startsWith("lc_transfer_to_")) return true;
62
+ return (agentContext?.graphTools)?.some((tool) => "name" in tool && tool.name === name) === true;
85
63
  }
86
64
  function isDirectLocalTool(name, graph) {
87
- const toolExecution = graph.toolExecution;
88
- const engine = toolExecution?.engine;
89
- if (toolExecution == null ||
90
- (engine !== 'local' && engine !== 'cloudflare-sandbox')) {
91
- return false;
92
- }
93
- const includeCodingTools = engine === 'cloudflare-sandbox'
94
- ? toolExecution.cloudflare?.includeCodingTools
95
- : toolExecution.local?.includeCodingTools;
96
- if (includeCodingTools === false) {
97
- return _enum.CODE_EXECUTION_TOOLS.has(name);
98
- }
99
- return LOCAL_CODING_BUNDLE_NAME_SET.has(name);
65
+ const toolExecution = graph.toolExecution;
66
+ const engine = toolExecution?.engine;
67
+ if (toolExecution == null || engine !== "local" && engine !== "cloudflare-sandbox") return false;
68
+ if ((engine === "cloudflare-sandbox" ? toolExecution.cloudflare?.includeCodingTools : toolExecution.local?.includeCodingTools) === false) return require_enum.CODE_EXECUTION_TOOLS.has(name);
69
+ return LOCAL_CODING_BUNDLE_NAME_SET.has(name);
100
70
  }
101
71
  function toCodeEnvFile(file, execSessionId) {
102
- const base = {
103
- id: file.id,
104
- resource_id: file.resource_id ?? file.id,
105
- name: file.name,
106
- storage_session_id: file.storage_session_id ?? execSessionId,
107
- };
108
- const kind = file.kind ?? 'user';
109
- if (kind === 'skill' && file.version != null) {
110
- return { ...base, kind: 'skill', version: file.version };
111
- }
112
- if (kind === 'agent') {
113
- return { ...base, kind: 'agent' };
114
- }
115
- return { ...base, kind: 'user' };
72
+ const base = {
73
+ id: file.id,
74
+ resource_id: file.resource_id ?? file.id,
75
+ name: file.name,
76
+ storage_session_id: file.storage_session_id ?? execSessionId
77
+ };
78
+ const kind = file.kind ?? "user";
79
+ if (kind === "skill" && file.version != null) return {
80
+ ...base,
81
+ kind: "skill",
82
+ version: file.version
83
+ };
84
+ if (kind === "agent") return {
85
+ ...base,
86
+ kind: "agent"
87
+ };
88
+ return {
89
+ ...base,
90
+ kind: "user"
91
+ };
116
92
  }
117
93
  function getCodeSessionContext(graph, name) {
118
- if (!_enum.CODE_EXECUTION_TOOLS.has(name) &&
119
- name !== _enum.Constants.SKILL_TOOL &&
120
- name !== _enum.Constants.READ_FILE) {
121
- return undefined;
122
- }
123
- const codeSession = graph.sessions.get(_enum.Constants.EXECUTE_CODE);
124
- if (codeSession?.session_id == null || codeSession.session_id === '') {
125
- return undefined;
126
- }
127
- return {
128
- session_id: codeSession.session_id,
129
- files: codeSession.files?.map((file) => toCodeEnvFile(file, codeSession.session_id)),
130
- };
94
+ if (!require_enum.CODE_EXECUTION_TOOLS.has(name) && name !== "skill" && name !== "read_file") return;
95
+ const codeSession = graph.sessions.get("execute_code");
96
+ if (codeSession?.session_id == null || codeSession.session_id === "") return;
97
+ return {
98
+ session_id: codeSession.session_id,
99
+ files: codeSession.files?.map((file) => toCodeEnvFile(file, codeSession.session_id))
100
+ };
131
101
  }
132
102
  function isEagerToolExecutionEnabledForBatch(args) {
133
- const { graph, metadata, agentContext } = args;
134
- if (graph.eagerEventToolExecution?.enabled !== true) {
135
- return false;
136
- }
137
- if ((agentContext?.toolDefinitions?.length ?? 0) === 0) {
138
- return false;
139
- }
140
- if (isBatchSensitiveToolExecution(graph)) {
141
- return false;
142
- }
143
- if (metadata?.[_enum.Constants.PROGRAMMATIC_TOOL_CALLING] === true ||
144
- metadata?.[_enum.Constants.BASH_PROGRAMMATIC_TOOL_CALLING] === true) {
145
- return false;
146
- }
147
- if (graph.handlerRegistry?.getHandler(_enum.GraphEvents.ON_TOOL_EXECUTE) == null &&
148
- graph.eventToolExecutionAvailable !== true) {
149
- return false;
150
- }
151
- return true;
103
+ const { graph, metadata, agentContext } = args;
104
+ if (graph.eagerEventToolExecution?.enabled !== true) return false;
105
+ if ((agentContext?.toolDefinitions?.length ?? 0) === 0) return false;
106
+ if (isBatchSensitiveToolExecution(graph)) return false;
107
+ if (metadata?.["run_tools_with_code"] === true || metadata?.["run_tools_with_bash"] === true) return false;
108
+ if (graph.handlerRegistry?.getHandler("on_tool_execute") == null && graph.eventToolExecutionAvailable !== true) return false;
109
+ return true;
152
110
  }
153
111
  function hasFinalToolCallSignal(chunk) {
154
- const metadata = chunk.response_metadata;
155
- const finishReason = metadata?.finish_reason ??
156
- metadata?.finishReason ??
157
- metadata?.stop_reason ??
158
- metadata?.stopReason;
159
- return finishReason === 'tool_calls' || finishReason === 'tool_use';
112
+ const metadata = chunk.response_metadata;
113
+ const finishReason = metadata?.finish_reason ?? metadata?.finishReason ?? metadata?.stop_reason ?? metadata?.stopReason;
114
+ return finishReason === "tool_calls" || finishReason === "tool_use";
160
115
  }
161
116
  function canPrestartSequentialStreamedToolChunks(agentContext) {
162
- // Anthropic seals each prior streamed tool-use block when the next indexed
163
- // tool-use block begins. Live Kimi/Moonshot streams can still revise prior
164
- // args after advancing to the next index, so keep those on the final
165
- // tool-call path unless they grow an explicit adapter seal.
166
- return agentContext?.provider === _enum.Providers.ANTHROPIC;
117
+ return agentContext?.provider === "anthropic";
167
118
  }
168
119
  function hasExplicitStreamedToolCallSeals(chunk) {
169
- return (streamedToolCallSeals.getStreamedToolCallAdapter(chunk.response_metadata) != null);
120
+ return require_streamedToolCallSeals.getStreamedToolCallAdapter(chunk.response_metadata) != null;
170
121
  }
171
122
  function hasDirectToolCallInBatch(args) {
172
- const { graph, agentContext, toolCalls } = args;
173
- return toolCalls.some((toolCall) => toolCall.name !== '' &&
174
- (isDirectGraphTool(toolCall.name, agentContext) ||
175
- isDirectLocalTool(toolCall.name, graph)));
123
+ const { graph, agentContext, toolCalls } = args;
124
+ return toolCalls.some((toolCall) => toolCall.name !== "" && (isDirectGraphTool(toolCall.name, agentContext) || isDirectLocalTool(toolCall.name, graph)));
176
125
  }
177
126
  function hasPotentialDirectToolInStreamContext(args) {
178
- const { graph, agentContext } = args;
179
- const engine = graph.toolExecution?.engine;
180
- if (engine === 'local' || engine === 'cloudflare-sandbox') {
181
- return true;
182
- }
183
- if ((agentContext?.graphTools?.length ?? 0) > 0) {
184
- return true;
185
- }
186
- return false;
127
+ const { graph, agentContext } = args;
128
+ const engine = graph.toolExecution?.engine;
129
+ if (engine === "local" || engine === "cloudflare-sandbox") return true;
130
+ if ((agentContext?.graphTools?.length ?? 0) > 0) return true;
131
+ return false;
187
132
  }
188
133
  function hasDirectToolCallChunkInBatch(args) {
189
- const { graph, agentContext, toolCallChunks } = args;
190
- return (toolCallChunks?.some((toolCallChunk) => toolCallChunk.name != null &&
191
- toolCallChunk.name !== '' &&
192
- (isDirectGraphTool(toolCallChunk.name, agentContext) ||
193
- isDirectLocalTool(toolCallChunk.name, graph))) === true);
134
+ const { graph, agentContext, toolCallChunks } = args;
135
+ return toolCallChunks?.some((toolCallChunk) => toolCallChunk.name != null && toolCallChunk.name !== "" && (isDirectGraphTool(toolCallChunk.name, agentContext) || isDirectLocalTool(toolCallChunk.name, graph))) === true;
194
136
  }
195
137
  function hasDirectToolCallChunkStateInStep(args) {
196
- const { graph, agentContext, stepKey } = args;
197
- const prefix = `${stepKey}\u0000`;
198
- for (const [key, state] of graph.eagerEventToolCallChunks) {
199
- if (!key.startsWith(prefix)) {
200
- continue;
201
- }
202
- const name = state.name;
203
- if (name != null &&
204
- name !== '' &&
205
- (isDirectGraphTool(name, agentContext) || isDirectLocalTool(name, graph))) {
206
- return true;
207
- }
208
- }
209
- return false;
138
+ const { graph, agentContext, stepKey } = args;
139
+ const prefix = `${stepKey}\u0000`;
140
+ for (const [key, state] of graph.eagerEventToolCallChunks) {
141
+ if (!key.startsWith(prefix)) continue;
142
+ const name = state.name;
143
+ if (name != null && name !== "" && (isDirectGraphTool(name, agentContext) || isDirectLocalTool(name, graph))) return true;
144
+ }
145
+ return false;
210
146
  }
211
147
  function isGoogleServerSideToolContentPart(contentPart) {
212
- return contentPart.type === 'toolCall' || contentPart.type === 'toolResponse';
148
+ return contentPart.type === "toolCall" || contentPart.type === "toolResponse";
213
149
  }
214
150
  function isTextContentPart(contentPart) {
215
- return contentPart.type?.startsWith(_enum.ContentTypes.TEXT) ?? false;
151
+ return contentPart.type?.startsWith("text") ?? false;
216
152
  }
217
153
  function isReasoningContentPart(contentPart) {
218
- return ((contentPart.type?.startsWith(_enum.ContentTypes.THINKING) ?? false) ||
219
- (contentPart.type?.startsWith(_enum.ContentTypes.REASONING) ?? false) ||
220
- (contentPart.type?.startsWith(_enum.ContentTypes.REASONING_CONTENT) ?? false) ||
221
- contentPart.type === 'redacted_thinking');
154
+ return (contentPart.type?.startsWith("thinking") ?? false) || (contentPart.type?.startsWith("reasoning") ?? false) || (contentPart.type?.startsWith("reasoning_content") ?? false) || contentPart.type === "redacted_thinking";
222
155
  }
223
156
  function getReasoningTextFromContentPart(contentPart) {
224
- return (contentPart.thinking ??
225
- contentPart.reasoning ??
226
- contentPart.reasoningText
227
- ?.text ??
228
- '');
157
+ return contentPart.thinking ?? contentPart.reasoning ?? contentPart.reasoningText?.text ?? "";
229
158
  }
230
159
  function getReasoningTextFromChunk(chunk, agentContext) {
231
- const reasoning = chunk.additional_kwargs?.[agentContext.reasoningKey];
232
- if (typeof reasoning === 'string') {
233
- return reasoning;
234
- }
235
- return reasoning?.summary?.[0]?.text ?? '';
160
+ const reasoning = chunk.additional_kwargs?.[agentContext.reasoningKey];
161
+ if (typeof reasoning === "string") return reasoning;
162
+ return reasoning?.summary?.[0]?.text ?? "";
236
163
  }
237
- const googleServerSideToolStepIdsByGraph = new WeakMap();
164
+ const googleServerSideToolStepIdsByGraph = /* @__PURE__ */ new WeakMap();
238
165
  function markGoogleServerSideToolMessageStep(graph, stepId) {
239
- const stepIds = googleServerSideToolStepIdsByGraph.get(graph) ?? new Set();
240
- stepIds.add(stepId);
241
- googleServerSideToolStepIdsByGraph.set(graph, stepIds);
166
+ const stepIds = googleServerSideToolStepIdsByGraph.get(graph) ?? /* @__PURE__ */ new Set();
167
+ stepIds.add(stepId);
168
+ googleServerSideToolStepIdsByGraph.set(graph, stepIds);
242
169
  }
243
170
  function isGoogleServerSideToolMessageStep(graph, stepId) {
244
- return googleServerSideToolStepIdsByGraph.get(graph)?.has(stepId) === true;
245
- }
246
- function shouldStartFreshMessageStepAfterGoogleServerSideTool({ graph, stepId, runStep, content, }) {
247
- if (runStep?.type !== _enum.StepTypes.MESSAGE_CREATION ||
248
- !isGoogleServerSideToolMessageStep(graph, stepId)) {
249
- return false;
250
- }
251
- if (typeof content === 'string') {
252
- return true;
253
- }
254
- return (content.every((c) => isTextContentPart(c)) ||
255
- content.every((c) => isReasoningContentPart(c)));
256
- }
257
- async function dispatchMessageCreationStep({ graph, stepKey, metadata, }) {
258
- const messageId = ids.getMessageId(stepKey, graph, true) ?? '';
259
- return graph.dispatchRunStep(stepKey, {
260
- type: _enum.StepTypes.MESSAGE_CREATION,
261
- message_creation: {
262
- message_id: messageId,
263
- },
264
- }, metadata);
265
- }
266
- async function dispatchMessageContentParts({ graph, stepKey, content, metadata, }) {
267
- for (const contentPart of content) {
268
- const currentStepId = await dispatchMessageCreationStep({
269
- graph,
270
- stepKey,
271
- metadata,
272
- });
273
- if (isGoogleServerSideToolContentPart(contentPart)) {
274
- markGoogleServerSideToolMessageStep(graph, currentStepId);
275
- }
276
- await graph.dispatchMessageDelta(currentStepId, {
277
- content: [contentPart],
278
- }, metadata);
279
- }
280
- }
281
- async function dispatchReasoningContentParts({ graph, stepKey, content, metadata, }) {
282
- if (content.length === 0) {
283
- return;
284
- }
285
- const currentStepId = await dispatchMessageCreationStep({
286
- graph,
287
- stepKey,
288
- metadata,
289
- });
290
- await graph.dispatchReasoningDelta(currentStepId, {
291
- content,
292
- }, metadata);
293
- }
294
- async function dispatchGoogleServerSideToolStreamContent({ graph, stepKey, chunk, agentContext, content, metadata, }) {
295
- const reasoningContent = [];
296
- const reasoningText = getReasoningTextFromChunk(chunk, agentContext);
297
- if (reasoningText !== '') {
298
- reasoningContent.push({
299
- type: _enum.ContentTypes.THINK,
300
- think: reasoningText,
301
- });
302
- }
303
- reasoningContent.push(...content
304
- .filter((contentPart) => isReasoningContentPart(contentPart))
305
- .map((contentPart) => ({
306
- type: _enum.ContentTypes.THINK,
307
- think: getReasoningTextFromContentPart(contentPart),
308
- }))
309
- .filter((contentPart) => contentPart.think !== ''));
310
- await dispatchReasoningContentParts({
311
- graph,
312
- stepKey,
313
- content: reasoningContent,
314
- metadata,
315
- });
316
- const messageContent = content.filter((contentPart) => isTextContentPart(contentPart) ||
317
- isGoogleServerSideToolContentPart(contentPart));
318
- await dispatchMessageContentParts({
319
- graph,
320
- stepKey,
321
- content: messageContent,
322
- metadata,
323
- });
171
+ return googleServerSideToolStepIdsByGraph.get(graph)?.has(stepId) === true;
172
+ }
173
+ function shouldStartFreshMessageStepAfterGoogleServerSideTool({ graph, stepId, runStep, content }) {
174
+ if (runStep?.type !== "message_creation" || !isGoogleServerSideToolMessageStep(graph, stepId)) return false;
175
+ if (typeof content === "string") return true;
176
+ return content.every((c) => isTextContentPart(c)) || content.every((c) => isReasoningContentPart(c));
177
+ }
178
+ async function dispatchMessageCreationStep({ graph, stepKey, metadata }) {
179
+ const messageId = require_ids.getMessageId(stepKey, graph, true) ?? "";
180
+ return graph.dispatchRunStep(stepKey, {
181
+ type: "message_creation",
182
+ message_creation: { message_id: messageId }
183
+ }, metadata);
184
+ }
185
+ async function dispatchMessageContentParts({ graph, stepKey, content, metadata }) {
186
+ for (const contentPart of content) {
187
+ const currentStepId = await dispatchMessageCreationStep({
188
+ graph,
189
+ stepKey,
190
+ metadata
191
+ });
192
+ if (isGoogleServerSideToolContentPart(contentPart)) markGoogleServerSideToolMessageStep(graph, currentStepId);
193
+ await graph.dispatchMessageDelta(currentStepId, { content: [contentPart] }, metadata);
194
+ }
195
+ }
196
+ async function dispatchReasoningContentParts({ graph, stepKey, content, metadata }) {
197
+ if (content.length === 0) return;
198
+ const currentStepId = await dispatchMessageCreationStep({
199
+ graph,
200
+ stepKey,
201
+ metadata
202
+ });
203
+ await graph.dispatchReasoningDelta(currentStepId, { content }, metadata);
204
+ }
205
+ async function dispatchGoogleServerSideToolStreamContent({ graph, stepKey, chunk, agentContext, content, metadata }) {
206
+ const reasoningContent = [];
207
+ const reasoningText = getReasoningTextFromChunk(chunk, agentContext);
208
+ if (reasoningText !== "") reasoningContent.push({
209
+ type: "think",
210
+ think: reasoningText
211
+ });
212
+ reasoningContent.push(...content.filter((contentPart) => isReasoningContentPart(contentPart)).map((contentPart) => ({
213
+ type: "think",
214
+ think: getReasoningTextFromContentPart(contentPart)
215
+ })).filter((contentPart) => contentPart.think !== ""));
216
+ await dispatchReasoningContentParts({
217
+ graph,
218
+ stepKey,
219
+ content: reasoningContent,
220
+ metadata
221
+ });
222
+ await dispatchMessageContentParts({
223
+ graph,
224
+ stepKey,
225
+ content: content.filter((contentPart) => isTextContentPart(contentPart) || isGoogleServerSideToolContentPart(contentPart)),
226
+ metadata
227
+ });
324
228
  }
325
229
  function createEagerToolExecutionPlan(args) {
326
- const { graph, metadata, agentContext, toolCalls, skipExisting = false, } = args;
327
- if (!isEagerToolExecutionEnabledForBatch({
328
- graph,
329
- metadata,
330
- agentContext,
331
- })) {
332
- return undefined;
333
- }
334
- if (hasDirectToolCallInBatch({ graph, agentContext, toolCalls })) {
335
- return undefined;
336
- }
337
- if (graph.toolOutputReferences?.enabled === true &&
338
- toolCalls.some((toolCall) => hasToolOutputReference(toolCall.args))) {
339
- return undefined;
340
- }
341
- const candidateToolCalls = skipExisting
342
- ? toolCalls.filter((toolCall) => {
343
- if (toolCall.id == null || toolCall.id === '') {
344
- return true;
345
- }
346
- return !graph.eagerEventToolExecutions.has(toolCall.id);
347
- })
348
- : toolCalls;
349
- if (candidateToolCalls.length === 0) {
350
- return [];
351
- }
352
- // Eager execution must preserve ToolNode batch semantics exactly for every
353
- // unstarted call. If any candidate cannot be planned, fall back for that
354
- // candidate set.
355
- if (candidateToolCalls.some((toolCall) => toolCall.id == null ||
356
- toolCall.id === '' ||
357
- toolCall.name === '' ||
358
- (!skipExisting && graph.eagerEventToolExecutions.has(toolCall.id)))) {
359
- return undefined;
360
- }
361
- const plan = eagerEventExecution.buildToolExecutionRequestPlan({
362
- toolCalls: candidateToolCalls.map((toolCall) => ({
363
- id: toolCall.id,
364
- name: toolCall.name,
365
- args: toolCall.args,
366
- stepId: graph.toolCallStepIds.get(toolCall.id) ?? '',
367
- codeSessionContext: getCodeSessionContext(graph, toolCall.name),
368
- })),
369
- usageCount: graph.getEagerEventToolUsageCount(agentContext?.agentId),
370
- });
371
- if (plan == null) {
372
- return undefined;
373
- }
374
- return plan.requests.map((request) => ({
375
- id: request.id,
376
- toolName: request.name,
377
- coercedArgs: request.args,
378
- request,
379
- }));
230
+ const { graph, metadata, agentContext, toolCalls, skipExisting = false } = args;
231
+ if (!isEagerToolExecutionEnabledForBatch({
232
+ graph,
233
+ metadata,
234
+ agentContext
235
+ })) return;
236
+ if (hasDirectToolCallInBatch({
237
+ graph,
238
+ agentContext,
239
+ toolCalls
240
+ })) return;
241
+ if (graph.toolOutputReferences?.enabled === true && toolCalls.some((toolCall) => hasToolOutputReference(toolCall.args))) return;
242
+ const candidateToolCalls = skipExisting ? toolCalls.filter((toolCall) => {
243
+ if (toolCall.id == null || toolCall.id === "") return true;
244
+ return !graph.eagerEventToolExecutions.has(toolCall.id);
245
+ }) : toolCalls;
246
+ if (candidateToolCalls.length === 0) return [];
247
+ if (candidateToolCalls.some((toolCall) => toolCall.id == null || toolCall.id === "" || toolCall.name === "" || !skipExisting && graph.eagerEventToolExecutions.has(toolCall.id))) return;
248
+ const plan = require_eagerEventExecution.buildToolExecutionRequestPlan({
249
+ toolCalls: candidateToolCalls.map((toolCall) => ({
250
+ id: toolCall.id,
251
+ name: toolCall.name,
252
+ args: toolCall.args,
253
+ stepId: graph.toolCallStepIds.get(toolCall.id) ?? "",
254
+ codeSessionContext: getCodeSessionContext(graph, toolCall.name)
255
+ })),
256
+ usageCount: graph.getEagerEventToolUsageCount(agentContext?.agentId)
257
+ });
258
+ if (plan == null) return;
259
+ return plan.requests.map((request) => ({
260
+ id: request.id,
261
+ toolName: request.name,
262
+ coercedArgs: request.args,
263
+ request
264
+ }));
380
265
  }
381
266
  function startEagerToolExecutions(args) {
382
- const { graph, metadata, agentContext, toolCalls, skipExisting } = args;
383
- const entries = createEagerToolExecutionPlan({
384
- graph,
385
- metadata,
386
- agentContext,
387
- toolCalls,
388
- skipExisting,
389
- });
390
- if (entries == null || entries.length === 0) {
391
- return;
392
- }
393
- const records = [];
394
- const promise = new Promise((resolve, reject) => {
395
- let dispatchSettled = false;
396
- let resultSettled = false;
397
- let settledResults;
398
- const maybeResolve = () => {
399
- if (dispatchSettled && resultSettled) {
400
- resolve(settledResults ?? []);
401
- }
402
- };
403
- const batchRequest = {
404
- toolCalls: entries.map((entry) => entry.request),
405
- userId: graph.config?.configurable?.user_id,
406
- agentId: agentContext?.agentId,
407
- configurable: graph.config?.configurable,
408
- metadata,
409
- resolve: (results) => {
410
- resultSettled = true;
411
- settledResults = results;
412
- maybeResolve();
413
- },
414
- reject,
415
- };
416
- void events.safeDispatchCustomEvent(_enum.GraphEvents.ON_TOOL_EXECUTE, batchRequest, graph.config)
417
- .then(() => {
418
- dispatchSettled = true;
419
- maybeResolve();
420
- })
421
- .catch(reject);
422
- }).then(async (results) => {
423
- await dispatchEagerToolCompletions({
424
- graph,
425
- agentContext,
426
- records,
427
- results,
428
- });
429
- return { results };
430
- }, (error) => ({
431
- error: eagerEventExecution.normalizeError(error),
432
- }));
433
- for (const entry of entries) {
434
- const record = {
435
- toolCallId: entry.id,
436
- toolName: entry.toolName,
437
- args: entry.coercedArgs,
438
- request: entry.request,
439
- promise,
440
- };
441
- records.push(record);
442
- graph.eagerEventToolExecutions.set(entry.id, record);
443
- }
267
+ const { graph, metadata, agentContext, toolCalls, skipExisting } = args;
268
+ const entries = createEagerToolExecutionPlan({
269
+ graph,
270
+ metadata,
271
+ agentContext,
272
+ toolCalls,
273
+ skipExisting
274
+ });
275
+ if (entries == null || entries.length === 0) return;
276
+ const records = [];
277
+ const promise = new Promise((resolve, reject) => {
278
+ let dispatchSettled = false;
279
+ let resultSettled = false;
280
+ let settledResults;
281
+ const maybeResolve = () => {
282
+ if (dispatchSettled && resultSettled) resolve(settledResults ?? []);
283
+ };
284
+ const batchRequest = {
285
+ toolCalls: entries.map((entry) => entry.request),
286
+ userId: graph.config?.configurable?.user_id,
287
+ agentId: agentContext?.agentId,
288
+ configurable: graph.config?.configurable,
289
+ metadata,
290
+ resolve: (results) => {
291
+ resultSettled = true;
292
+ settledResults = results;
293
+ maybeResolve();
294
+ },
295
+ reject
296
+ };
297
+ require_events.safeDispatchCustomEvent("on_tool_execute", batchRequest, graph.config).then(() => {
298
+ dispatchSettled = true;
299
+ maybeResolve();
300
+ }).catch(reject);
301
+ }).then(async (results) => {
302
+ await dispatchEagerToolCompletions({
303
+ graph,
304
+ agentContext,
305
+ records,
306
+ results
307
+ });
308
+ return { results };
309
+ }, (error) => ({ error: require_eagerEventExecution.normalizeError(error) }));
310
+ for (const entry of entries) {
311
+ const record = {
312
+ toolCallId: entry.id,
313
+ toolName: entry.toolName,
314
+ args: entry.coercedArgs,
315
+ request: entry.request,
316
+ promise
317
+ };
318
+ records.push(record);
319
+ graph.eagerEventToolExecutions.set(entry.id, record);
320
+ }
444
321
  }
445
322
  async function dispatchEagerToolCompletions(args) {
446
- const { graph, agentContext, records, results } = args;
447
- const recordById = new Map(records.map((record) => [record.toolCallId, record]));
448
- const maxToolResultChars = agentContext?.maxToolResultChars ??
449
- truncation.calculateMaxToolResultChars(agentContext?.maxContextTokens);
450
- for (const result of results) {
451
- const record = recordById.get(result.toolCallId);
452
- if (record == null) {
453
- continue;
454
- }
455
- if (graph.eagerEventToolExecutions.get(result.toolCallId) !== record) {
456
- continue;
457
- }
458
- const stepId = record.request.stepId ??
459
- graph.toolCallStepIds.get(result.toolCallId) ??
460
- '';
461
- if (stepId === '') {
462
- continue;
463
- }
464
- const output = result.status === 'error'
465
- ? `Error: ${result.errorMessage ?? 'Unknown error'}\n Please fix your mistakes.`
466
- : truncation.truncateToolResultContent(typeof result.content === 'string'
467
- ? result.content
468
- : JSON.stringify(result.content), maxToolResultChars);
469
- try {
470
- const dispatched = await events.safeDispatchCustomEvent(_enum.GraphEvents.ON_RUN_STEP_COMPLETED, {
471
- result: {
472
- id: stepId,
473
- index: record.request.turn ?? 0,
474
- type: 'tool_call',
475
- eager: true,
476
- tool_call: {
477
- args: JSON.stringify(record.request.args),
478
- name: record.toolName,
479
- id: result.toolCallId,
480
- output,
481
- progress: 1,
482
- },
483
- },
484
- }, graph.config);
485
- if (dispatched === false) {
486
- continue;
487
- }
488
- record.completionDispatched = true;
489
- }
490
- catch (error) {
491
- // Let ToolNode dispatch the completion through the normal path later.
492
- console.warn(`[stream] eager completion dispatch failed for toolCallId=${result.toolCallId}:`, error instanceof Error ? error.message : error);
493
- }
494
- }
323
+ const { graph, agentContext, records, results } = args;
324
+ const recordById = new Map(records.map((record) => [record.toolCallId, record]));
325
+ const maxToolResultChars = agentContext?.maxToolResultChars ?? require_truncation.calculateMaxToolResultChars(agentContext?.maxContextTokens);
326
+ for (const result of results) {
327
+ const record = recordById.get(result.toolCallId);
328
+ if (record == null) continue;
329
+ if (graph.eagerEventToolExecutions.get(result.toolCallId) !== record) continue;
330
+ const stepId = record.request.stepId ?? graph.toolCallStepIds.get(result.toolCallId) ?? "";
331
+ if (stepId === "") continue;
332
+ const output = result.status === "error" ? `Error: ${result.errorMessage ?? "Unknown error"}\n Please fix your mistakes.` : require_truncation.truncateToolResultContent(typeof result.content === "string" ? result.content : JSON.stringify(result.content), maxToolResultChars);
333
+ try {
334
+ if (await require_events.safeDispatchCustomEvent("on_run_step_completed", { result: {
335
+ id: stepId,
336
+ index: record.request.turn ?? 0,
337
+ type: "tool_call",
338
+ eager: true,
339
+ tool_call: {
340
+ args: JSON.stringify(record.request.args),
341
+ name: record.toolName,
342
+ id: result.toolCallId,
343
+ output,
344
+ progress: 1
345
+ }
346
+ } }, graph.config) === false) continue;
347
+ record.completionDispatched = true;
348
+ } catch (error) {
349
+ console.warn(`[stream] eager completion dispatch failed for toolCallId=${result.toolCallId}:`, error instanceof Error ? error.message : error);
350
+ }
351
+ }
495
352
  }
496
353
  function getEagerToolChunkKey(stepKey, toolCallChunk) {
497
- let chunkKey;
498
- if (typeof toolCallChunk.index === 'number') {
499
- chunkKey = String(toolCallChunk.index);
500
- }
501
- else if (toolCallChunk.id != null && toolCallChunk.id !== '') {
502
- chunkKey = toolCallChunk.id;
503
- }
504
- if (chunkKey == null) {
505
- return undefined;
506
- }
507
- return `${stepKey}\u0000${chunkKey}`;
354
+ let chunkKey;
355
+ if (typeof toolCallChunk.index === "number") chunkKey = String(toolCallChunk.index);
356
+ else if (toolCallChunk.id != null && toolCallChunk.id !== "") chunkKey = toolCallChunk.id;
357
+ if (chunkKey == null) return;
358
+ return `${stepKey}\u0000${chunkKey}`;
508
359
  }
509
360
  function getEagerToolChunkIndex(toolCallChunk) {
510
- return typeof toolCallChunk.index === 'number'
511
- ? toolCallChunk.index
512
- : undefined;
361
+ return typeof toolCallChunk.index === "number" ? toolCallChunk.index : void 0;
513
362
  }
514
363
  function pruneEagerToolCallChunkStates(args) {
515
- const { graph, stepKey, toolCallIds, clearStep = false } = args;
516
- const prefix = `${stepKey}\u0000`;
517
- for (const [key, state] of graph.eagerEventToolCallChunks) {
518
- if (!key.startsWith(prefix)) {
519
- continue;
520
- }
521
- if (clearStep ||
522
- (state.id != null && toolCallIds?.has(state.id) === true)) {
523
- graph.eagerEventToolCallChunks.delete(key);
524
- }
525
- }
364
+ const { graph, stepKey, toolCallIds, clearStep = false } = args;
365
+ const prefix = `${stepKey}\u0000`;
366
+ for (const [key, state] of graph.eagerEventToolCallChunks) {
367
+ if (!key.startsWith(prefix)) continue;
368
+ if (clearStep || state.id != null && toolCallIds?.has(state.id) === true) graph.eagerEventToolCallChunks.delete(key);
369
+ }
526
370
  }
527
371
  function isEagerToolChunkStateComplete(state) {
528
- return (state.id != null &&
529
- state.id !== '' &&
530
- state.name != null &&
531
- state.name !== '' &&
532
- eagerEventExecution.coerceRecordArgs(state.argsText) != null);
372
+ return state.id != null && state.id !== "" && state.name != null && state.name !== "" && require_eagerEventExecution.coerceRecordArgs(state.argsText) != null;
533
373
  }
534
374
  function mergeToolCallArgsText(existing, incoming) {
535
- if (incoming === '') {
536
- return existing;
537
- }
538
- if (existing === '') {
539
- return incoming;
540
- }
541
- if (incoming === existing) {
542
- try {
543
- JSON.parse(incoming);
544
- return incoming;
545
- }
546
- catch {
547
- return `${existing}${incoming}`;
548
- }
549
- }
550
- if (incoming.startsWith(existing)) {
551
- return incoming;
552
- }
553
- if (existing.startsWith(incoming)) {
554
- return existing;
555
- }
556
- try {
557
- JSON.parse(existing);
558
- JSON.parse(incoming);
559
- return incoming;
560
- }
561
- catch {
562
- // Fall through to delta concatenation.
563
- }
564
- for (let overlap = Math.min(existing.length, incoming.length); overlap >= 8; overlap -= 1) {
565
- if (existing.endsWith(incoming.slice(0, overlap))) {
566
- return `${existing}${incoming.slice(overlap)}`;
567
- }
568
- }
569
- return `${existing}${incoming}`;
375
+ if (incoming === "") return existing;
376
+ if (existing === "") return incoming;
377
+ if (incoming === existing) try {
378
+ JSON.parse(incoming);
379
+ return incoming;
380
+ } catch {
381
+ return `${existing}${incoming}`;
382
+ }
383
+ if (incoming.startsWith(existing)) return incoming;
384
+ if (existing.startsWith(incoming)) return existing;
385
+ try {
386
+ JSON.parse(existing);
387
+ JSON.parse(incoming);
388
+ return incoming;
389
+ } catch {}
390
+ for (let overlap = Math.min(existing.length, incoming.length); overlap >= 8; overlap -= 1) if (existing.endsWith(incoming.slice(0, overlap))) return `${existing}${incoming.slice(overlap)}`;
391
+ return `${existing}${incoming}`;
570
392
  }
571
393
  function recordEagerToolCallChunks(args) {
572
- const { graph, stepKey, toolCallChunks } = args;
573
- if (toolCallChunks == null || toolCallChunks.length === 0) {
574
- return;
575
- }
576
- // Streamed args can be cumulative and parseable before the provider has
577
- // sealed the call. Recording stays separate from dispatch so the boundary
578
- // logic can wait for either a later tool index or the final tool-call signal.
579
- for (const toolCallChunk of toolCallChunks) {
580
- const key = getEagerToolChunkKey(stepKey, toolCallChunk);
581
- if (key == null) {
582
- continue;
583
- }
584
- const incomingId = toolCallChunk.id != null && toolCallChunk.id !== ''
585
- ? toolCallChunk.id
586
- : undefined;
587
- const incomingName = toolCallChunk.name != null && toolCallChunk.name !== ''
588
- ? toolCallChunk.name
589
- : undefined;
590
- const previous = graph.eagerEventToolCallChunks.get(key);
591
- const shouldReset = previous != null &&
592
- ((incomingId != null &&
593
- previous.id != null &&
594
- incomingId !== previous.id) ||
595
- (incomingName != null &&
596
- previous.name != null &&
597
- incomingName !== previous.name));
598
- const existing = previous == null || shouldReset
599
- ? {
600
- argsText: '',
601
- }
602
- : previous;
603
- const id = incomingId ?? existing.id;
604
- const name = incomingName ?? existing.name;
605
- const incomingArgs = toolCallChunk.args ?? '';
606
- const isRepeatedObservedFragment = incomingArgs !== '' &&
607
- incomingArgs.length > 1 &&
608
- incomingArgs === existing.lastArgsFragment;
609
- const argsText = isRepeatedObservedFragment
610
- ? existing.argsText
611
- : mergeToolCallArgsText(existing.argsText, incomingArgs);
612
- const next = {
613
- id,
614
- name,
615
- argsText,
616
- index: getEagerToolChunkIndex(toolCallChunk) ?? existing.index,
617
- lastArgsFragment: incomingArgs !== '' ? incomingArgs : existing.lastArgsFragment,
618
- };
619
- graph.eagerEventToolCallChunks.set(key, next);
620
- }
394
+ const { graph, stepKey, toolCallChunks } = args;
395
+ if (toolCallChunks == null || toolCallChunks.length === 0) return;
396
+ for (const toolCallChunk of toolCallChunks) {
397
+ const key = getEagerToolChunkKey(stepKey, toolCallChunk);
398
+ if (key == null) continue;
399
+ const incomingId = toolCallChunk.id != null && toolCallChunk.id !== "" ? toolCallChunk.id : void 0;
400
+ const incomingName = toolCallChunk.name != null && toolCallChunk.name !== "" ? toolCallChunk.name : void 0;
401
+ const previous = graph.eagerEventToolCallChunks.get(key);
402
+ const shouldReset = previous != null && (incomingId != null && previous.id != null && incomingId !== previous.id || incomingName != null && previous.name != null && incomingName !== previous.name);
403
+ const existing = previous == null || shouldReset ? { argsText: "" } : previous;
404
+ const id = incomingId ?? existing.id;
405
+ const name = incomingName ?? existing.name;
406
+ const incomingArgs = toolCallChunk.args ?? "";
407
+ const next = {
408
+ id,
409
+ name,
410
+ argsText: incomingArgs !== "" && incomingArgs.length > 1 && incomingArgs === existing.lastArgsFragment ? existing.argsText : mergeToolCallArgsText(existing.argsText, incomingArgs),
411
+ index: getEagerToolChunkIndex(toolCallChunk) ?? existing.index,
412
+ lastArgsFragment: incomingArgs !== "" ? incomingArgs : existing.lastArgsFragment
413
+ };
414
+ graph.eagerEventToolCallChunks.set(key, next);
415
+ }
621
416
  }
622
417
  function getStreamedReadyToolCalls(args) {
623
- const { graph, stepKey, toolCallChunks, seal, allowSequentialSeal = false, sealAll = false, } = args;
624
- const currentIndices = new Set();
625
- for (const toolCallChunk of toolCallChunks ?? []) {
626
- const index = getEagerToolChunkIndex(toolCallChunk);
627
- if (index != null) {
628
- currentIndices.add(index);
629
- }
630
- }
631
- const highestCurrentIndex = currentIndices.size > 0 ? Math.max(...currentIndices) : undefined;
632
- const prefix = `${stepKey}\u0000`;
633
- const readyEntries = [];
634
- for (const [key, state] of graph.eagerEventToolCallChunks) {
635
- if (!key.startsWith(prefix)) {
636
- continue;
637
- }
638
- if (state.id != null && graph.eagerEventToolExecutions.has(state.id)) {
639
- graph.eagerEventToolCallChunks.delete(key);
640
- continue;
641
- }
642
- if (!isEagerToolChunkStateComplete(state)) {
643
- continue;
644
- }
645
- const isSealedByLaterChunk = allowSequentialSeal &&
646
- highestCurrentIndex != null &&
647
- state.index != null &&
648
- state.index < highestCurrentIndex &&
649
- !currentIndices.has(state.index);
650
- const isSealedExplicitly = seal?.kind === 'single' &&
651
- ((seal.id != null && state.id === seal.id) ||
652
- (seal.index != null && state.index === seal.index));
653
- if (sealAll ||
654
- seal?.kind === 'all' ||
655
- isSealedByLaterChunk ||
656
- isSealedExplicitly) {
657
- readyEntries.push({ key, state });
658
- }
659
- }
660
- pruneEagerToolCallChunkStates({
661
- graph,
662
- stepKey,
663
- toolCallIds: new Set(readyEntries
664
- .map(({ state }) => state.id)
665
- .filter((id) => id != null && id !== '')),
666
- });
667
- if (sealAll) {
668
- pruneEagerToolCallChunkStates({ graph, stepKey, clearStep: true });
669
- }
670
- return readyEntries
671
- .sort((left, right) => (left.state.index ?? 0) - (right.state.index ?? 0))
672
- .flatMap(({ state }) => {
673
- const args = eagerEventExecution.coerceRecordArgs(state.argsText);
674
- if (args == null) {
675
- return [];
676
- }
677
- return [
678
- {
679
- id: state.id,
680
- name: state.name ?? '',
681
- args,
682
- },
683
- ];
684
- });
418
+ const { graph, stepKey, toolCallChunks, seal, allowSequentialSeal = false, sealAll = false } = args;
419
+ const currentIndices = /* @__PURE__ */ new Set();
420
+ for (const toolCallChunk of toolCallChunks ?? []) {
421
+ const index = getEagerToolChunkIndex(toolCallChunk);
422
+ if (index != null) currentIndices.add(index);
423
+ }
424
+ const highestCurrentIndex = currentIndices.size > 0 ? Math.max(...currentIndices) : void 0;
425
+ const prefix = `${stepKey}\u0000`;
426
+ const readyEntries = [];
427
+ for (const [key, state] of graph.eagerEventToolCallChunks) {
428
+ if (!key.startsWith(prefix)) continue;
429
+ if (state.id != null && graph.eagerEventToolExecutions.has(state.id)) {
430
+ graph.eagerEventToolCallChunks.delete(key);
431
+ continue;
432
+ }
433
+ if (!isEagerToolChunkStateComplete(state)) continue;
434
+ const isSealedByLaterChunk = allowSequentialSeal && highestCurrentIndex != null && state.index != null && state.index < highestCurrentIndex && !currentIndices.has(state.index);
435
+ const isSealedExplicitly = seal?.kind === "single" && (seal.id != null && state.id === seal.id || seal.index != null && state.index === seal.index);
436
+ if (sealAll || seal?.kind === "all" || isSealedByLaterChunk || isSealedExplicitly) readyEntries.push({
437
+ key,
438
+ state
439
+ });
440
+ }
441
+ pruneEagerToolCallChunkStates({
442
+ graph,
443
+ stepKey,
444
+ toolCallIds: new Set(readyEntries.map(({ state }) => state.id).filter((id) => id != null && id !== ""))
445
+ });
446
+ if (sealAll) pruneEagerToolCallChunkStates({
447
+ graph,
448
+ stepKey,
449
+ clearStep: true
450
+ });
451
+ return readyEntries.sort((left, right) => (left.state.index ?? 0) - (right.state.index ?? 0)).flatMap(({ state }) => {
452
+ const args = require_eagerEventExecution.coerceRecordArgs(state.argsText);
453
+ if (args == null) return [];
454
+ return [{
455
+ id: state.id,
456
+ name: state.name ?? "",
457
+ args
458
+ }];
459
+ });
685
460
  }
686
461
  function startReadyStreamedEagerToolExecutions(args) {
687
- const { graph, metadata, agentContext, stepKey, toolCallChunks, seal, allowSequentialSeal, sealAll, } = args;
688
- if (hasPotentialDirectToolInStreamContext({ graph, agentContext }) ||
689
- hasDirectToolCallChunkInBatch({ graph, agentContext, toolCallChunks }) ||
690
- hasDirectToolCallChunkStateInStep({ graph, agentContext, stepKey }) ||
691
- !isEagerToolExecutionEnabledForBatch({ graph, metadata, agentContext })) {
692
- return;
693
- }
694
- const toolCalls = getStreamedReadyToolCalls({
695
- graph,
696
- stepKey,
697
- toolCallChunks,
698
- seal,
699
- allowSequentialSeal,
700
- sealAll,
701
- });
702
- if (toolCalls.length === 0) {
703
- return;
704
- }
705
- startEagerToolExecutions({
706
- graph,
707
- metadata,
708
- agentContext,
709
- toolCalls,
710
- skipExisting: true,
711
- });
712
- }
713
- function getChunkContent({ chunk, provider, reasoningKey, }) {
714
- if (llm.isGoogleLike(provider) &&
715
- Array.isArray(chunk?.content) &&
716
- chunk.content.some((c) => isGoogleServerSideToolContentPart(c))) {
717
- return chunk.content;
718
- }
719
- if ((provider === _enum.Providers.OPENAI || provider === _enum.Providers.AZURE) &&
720
- chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text != null &&
721
- (chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text?.length ?? 0) > 0) {
722
- return chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text;
723
- }
724
- if (provider === _enum.Providers.OPENROUTER) {
725
- // Content presence signals end of reasoning phase - prefer content over reasoning
726
- // This handles transitional chunks that may have both reasoning and content
727
- if (typeof chunk?.content === 'string' && chunk.content !== '') {
728
- return chunk.content;
729
- }
730
- const reasoning = chunk?.additional_kwargs?.reasoning;
731
- if (reasoning != null && reasoning !== '') {
732
- return reasoning;
733
- }
734
- const reasoningContent = chunk?.additional_kwargs?.reasoning_content;
735
- if (reasoningContent != null && reasoningContent !== '') {
736
- return reasoningContent;
737
- }
738
- return chunk?.content;
739
- }
740
- const keyedReasoning = chunk?.additional_kwargs?.[reasoningKey];
741
- if (typeof chunk?.content === 'string' &&
742
- chunk.content !== '' &&
743
- keyedReasoning != null &&
744
- keyedReasoning !== '') {
745
- return chunk.content;
746
- }
747
- return (keyedReasoning ?? '') || chunk?.content;
462
+ const { graph, metadata, agentContext, stepKey, toolCallChunks, seal, allowSequentialSeal, sealAll } = args;
463
+ if (hasPotentialDirectToolInStreamContext({
464
+ graph,
465
+ agentContext
466
+ }) || hasDirectToolCallChunkInBatch({
467
+ graph,
468
+ agentContext,
469
+ toolCallChunks
470
+ }) || hasDirectToolCallChunkStateInStep({
471
+ graph,
472
+ agentContext,
473
+ stepKey
474
+ }) || !isEagerToolExecutionEnabledForBatch({
475
+ graph,
476
+ metadata,
477
+ agentContext
478
+ })) return;
479
+ const toolCalls = getStreamedReadyToolCalls({
480
+ graph,
481
+ stepKey,
482
+ toolCallChunks,
483
+ seal,
484
+ allowSequentialSeal,
485
+ sealAll
486
+ });
487
+ if (toolCalls.length === 0) return;
488
+ startEagerToolExecutions({
489
+ graph,
490
+ metadata,
491
+ agentContext,
492
+ toolCalls,
493
+ skipExisting: true
494
+ });
495
+ }
496
+ function getChunkContent({ chunk, provider, reasoningKey }) {
497
+ if (require_llm.isGoogleLike(provider) && Array.isArray(chunk?.content) && chunk.content.some((c) => isGoogleServerSideToolContentPart(c))) return chunk.content;
498
+ if ((provider === "openAI" || provider === "azureOpenAI") && (chunk?.additional_kwargs?.reasoning)?.summary?.[0]?.text != null && ((chunk?.additional_kwargs?.reasoning)?.summary?.[0]?.text?.length ?? 0) > 0) return (chunk?.additional_kwargs?.reasoning)?.summary?.[0]?.text;
499
+ if (provider === "openrouter") {
500
+ if (typeof chunk?.content === "string" && chunk.content !== "") return chunk.content;
501
+ const reasoning = chunk?.additional_kwargs?.reasoning;
502
+ if (reasoning != null && reasoning !== "") return reasoning;
503
+ const reasoningContent = chunk?.additional_kwargs?.reasoning_content;
504
+ if (reasoningContent != null && reasoningContent !== "") return reasoningContent;
505
+ return chunk?.content;
506
+ }
507
+ const keyedReasoning = chunk?.additional_kwargs?.[reasoningKey];
508
+ if (typeof chunk?.content === "string" && chunk.content !== "" && keyedReasoning != null && keyedReasoning !== "") return chunk.content;
509
+ return (keyedReasoning ?? "") || chunk?.content;
748
510
  }
749
511
  function isDisableStreamingEnabled(clientOptions) {
750
- return (clientOptions != null &&
751
- 'disableStreaming' in clientOptions &&
752
- clientOptions.disableStreaming === true);
512
+ return clientOptions != null && "disableStreaming" in clientOptions && clientOptions.disableStreaming === true;
753
513
  }
754
514
  function hasReasoningContent(value) {
755
- if (typeof value === 'string') {
756
- return value !== '';
757
- }
758
- if (Array.isArray(value)) {
759
- return value.length > 0;
760
- }
761
- if (value == null) {
762
- return false;
763
- }
764
- return (value.summary?.some((summary) => summary.text != null && summary.text.length > 0) === true);
765
- }
766
- function shouldDeferMixedFinalReasoningChunk({ chunk, agentContext, }) {
767
- if ((chunk.tool_calls?.length ?? 0) > 0 ||
768
- (chunk.tool_call_chunks?.length ?? 0) > 0 ||
769
- typeof chunk.content !== 'string' ||
770
- chunk.content === '') {
771
- return false;
772
- }
773
- const additionalKwargs = chunk.additional_kwargs;
774
- if (agentContext.provider === _enum.Providers.OPENROUTER &&
775
- hasReasoningContent(additionalKwargs?.reasoning_details)) {
776
- return true;
777
- }
778
- if (!isDisableStreamingEnabled(agentContext.clientOptions)) {
779
- return false;
780
- }
781
- return (hasReasoningContent(additionalKwargs?.[agentContext.reasoningKey]) ||
782
- hasReasoningContent(additionalKwargs?.reasoning_content) ||
783
- hasReasoningContent(additionalKwargs?.reasoning) ||
784
- hasReasoningContent(additionalKwargs?.reasoning_details));
785
- }
786
- function hasCurrentTextDeltaStep({ graph, metadata, }) {
787
- if (metadata == null) {
788
- return false;
789
- }
790
- const baseStepKey = graph.getStepBaseKey(metadata);
791
- for (const [stepKey, stepIds] of graph.stepKeyIds) {
792
- if (stepKey !== baseStepKey && !stepKey.startsWith(`${baseStepKey}_`)) {
793
- continue;
794
- }
795
- if (stepIds.some((stepId) => graph.messageStepHasTextDeltas.has(stepId))) {
796
- return true;
797
- }
798
- }
799
- return false;
800
- }
801
- function shouldSkipLateOpenRouterReasoningChunk({ chunk, agentContext, graph, metadata, }) {
802
- if (agentContext.provider !== _enum.Providers.OPENROUTER ||
803
- (chunk.tool_calls?.length ?? 0) > 0 ||
804
- (chunk.tool_call_chunks?.length ?? 0) > 0 ||
805
- (chunk.content != null && chunk.content !== '')) {
806
- return false;
807
- }
808
- return ((hasReasoningContent(chunk.additional_kwargs?.reasoning) ||
809
- hasReasoningContent(chunk.additional_kwargs?.reasoning_content) ||
810
- hasReasoningContent(chunk.additional_kwargs?.reasoning_details)) &&
811
- hasCurrentTextDeltaStep({ graph, metadata }));
812
- }
813
- class ChatModelStreamHandler {
814
- async handle(event, data, metadata, graph) {
815
- if (!graph) {
816
- throw new Error('Graph not found');
817
- }
818
- if (!graph.config) {
819
- throw new Error('Config not found in graph');
820
- }
821
- if (!data.chunk) {
822
- console.warn(`No chunk found in ${event} event`);
823
- return;
824
- }
825
- const agentContext = graph.getAgentContext(metadata);
826
- const chunk = data.chunk;
827
- const content = getChunkContent({
828
- chunk,
829
- reasoningKey: agentContext.reasoningKey,
830
- provider: agentContext.provider,
831
- });
832
- const skipHandling = await handlers.handleServerToolResult({
833
- graph,
834
- content,
835
- metadata,
836
- agentContext,
837
- });
838
- if (skipHandling) {
839
- return;
840
- }
841
- if (shouldDeferMixedFinalReasoningChunk({ chunk, agentContext })) {
842
- return;
843
- }
844
- if (shouldSkipLateOpenRouterReasoningChunk({
845
- chunk,
846
- agentContext,
847
- graph,
848
- metadata,
849
- })) {
850
- return;
851
- }
852
- this.handleReasoning(chunk, agentContext);
853
- const stepKey = graph.getStepKey(metadata);
854
- let hasToolCalls = false;
855
- const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;
856
- const hasGoogleServerSideToolContent = llm.isGoogleLike(agentContext.provider) &&
857
- Array.isArray(content) &&
858
- content.some((c) => isGoogleServerSideToolContentPart(c));
859
- if (hasGoogleServerSideToolContent && Array.isArray(content)) {
860
- await dispatchGoogleServerSideToolStreamContent({
861
- graph,
862
- stepKey,
863
- chunk,
864
- agentContext,
865
- content,
866
- metadata,
867
- });
868
- }
869
- if (chunk.tool_calls &&
870
- chunk.tool_calls.length > 0 &&
871
- chunk.tool_calls.every((tc) => tc.id != null &&
872
- tc.id !== '' &&
873
- tc.name != null &&
874
- tc.name !== '')) {
875
- hasToolCalls = true;
876
- await handlers.handleToolCalls(chunk.tool_calls, metadata, graph);
877
- if (hasFinalToolCallSignal(chunk)) {
878
- startEagerToolExecutions({
879
- graph,
880
- metadata,
881
- agentContext,
882
- toolCalls: chunk.tool_calls,
883
- skipExisting: true,
884
- });
885
- if (!hasToolCallChunks) {
886
- pruneEagerToolCallChunkStates({ graph, stepKey, clearStep: true });
887
- }
888
- }
889
- }
890
- const isEmptyContent = typeof content === 'undefined' ||
891
- !content.length ||
892
- (typeof content === 'string' && !content);
893
- /** Set a preliminary message ID if found in empty chunk */
894
- const isEmptyChunk = isEmptyContent && !hasToolCallChunks;
895
- if (isEmptyChunk &&
896
- (chunk.id ?? '') !== '' &&
897
- !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')) {
898
- graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');
899
- }
900
- else if (isEmptyChunk) {
901
- return;
902
- }
903
- if (hasToolCallChunks &&
904
- chunk.tool_call_chunks &&
905
- chunk.tool_call_chunks.length &&
906
- typeof chunk.tool_call_chunks[0]?.index === 'number') {
907
- const streamedToolCallSeal = streamedToolCallSeals.getStreamedToolCallSeal(chunk.response_metadata);
908
- const allowSequentialSeal = canPrestartSequentialStreamedToolChunks(agentContext);
909
- const canStreamEager = (allowSequentialSeal || hasExplicitStreamedToolCallSeals(chunk)) &&
910
- !hasPotentialDirectToolInStreamContext({ graph, agentContext }) &&
911
- isEagerToolExecutionEnabledForBatch({ graph, metadata, agentContext });
912
- if (canStreamEager) {
913
- recordEagerToolCallChunks({
914
- graph,
915
- stepKey,
916
- toolCallChunks: chunk.tool_call_chunks,
917
- });
918
- }
919
- await handlers.handleToolCallChunks({
920
- graph,
921
- stepKey,
922
- toolCallChunks: chunk.tool_call_chunks,
923
- metadata,
924
- });
925
- if (canStreamEager) {
926
- startReadyStreamedEagerToolExecutions({
927
- graph,
928
- metadata,
929
- agentContext,
930
- stepKey,
931
- toolCallChunks: chunk.tool_call_chunks,
932
- seal: streamedToolCallSeal,
933
- allowSequentialSeal,
934
- sealAll: hasFinalToolCallSignal(chunk),
935
- });
936
- }
937
- }
938
- if (isEmptyContent) {
939
- return;
940
- }
941
- if (hasGoogleServerSideToolContent) {
942
- return;
943
- }
944
- const message_id = ids.getMessageId(stepKey, graph) ?? '';
945
- if (message_id) {
946
- await graph.dispatchRunStep(stepKey, {
947
- type: _enum.StepTypes.MESSAGE_CREATION,
948
- message_creation: {
949
- message_id,
950
- },
951
- }, metadata);
952
- }
953
- let stepId = graph.getStepIdByKey(stepKey);
954
- let runStep = graph.getRunStep(stepId);
955
- if (shouldStartFreshMessageStepAfterGoogleServerSideTool({
956
- graph,
957
- stepId,
958
- runStep,
959
- content,
960
- })) {
961
- stepId = await dispatchMessageCreationStep({ graph, stepKey, metadata });
962
- runStep = graph.getRunStep(stepId);
963
- }
964
- if (!runStep) {
965
- console.warn(`\n
515
+ if (typeof value === "string") return value !== "";
516
+ if (Array.isArray(value)) return value.length > 0;
517
+ if (value == null) return false;
518
+ return value.summary?.some((summary) => summary.text != null && summary.text.length > 0) === true;
519
+ }
520
+ function shouldDeferMixedFinalReasoningChunk({ chunk, agentContext }) {
521
+ if ((chunk.tool_calls?.length ?? 0) > 0 || (chunk.tool_call_chunks?.length ?? 0) > 0 || typeof chunk.content !== "string" || chunk.content === "") return false;
522
+ const additionalKwargs = chunk.additional_kwargs;
523
+ if (agentContext.provider === "openrouter" && hasReasoningContent(additionalKwargs?.reasoning_details)) return true;
524
+ if (!isDisableStreamingEnabled(agentContext.clientOptions)) return false;
525
+ return hasReasoningContent(additionalKwargs?.[agentContext.reasoningKey]) || hasReasoningContent(additionalKwargs?.reasoning_content) || hasReasoningContent(additionalKwargs?.reasoning) || hasReasoningContent(additionalKwargs?.reasoning_details);
526
+ }
527
+ function hasCurrentTextDeltaStep({ graph, metadata }) {
528
+ if (metadata == null) return false;
529
+ const baseStepKey = graph.getStepBaseKey(metadata);
530
+ for (const [stepKey, stepIds] of graph.stepKeyIds) {
531
+ if (stepKey !== baseStepKey && !stepKey.startsWith(`${baseStepKey}_`)) continue;
532
+ if (stepIds.some((stepId) => graph.messageStepHasTextDeltas.has(stepId))) return true;
533
+ }
534
+ return false;
535
+ }
536
+ function shouldSkipLateOpenRouterReasoningChunk({ chunk, agentContext, graph, metadata }) {
537
+ if (agentContext.provider !== "openrouter" || (chunk.tool_calls?.length ?? 0) > 0 || (chunk.tool_call_chunks?.length ?? 0) > 0 || chunk.content != null && chunk.content !== "") return false;
538
+ return (hasReasoningContent(chunk.additional_kwargs?.reasoning) || hasReasoningContent(chunk.additional_kwargs?.reasoning_content) || hasReasoningContent(chunk.additional_kwargs?.reasoning_details)) && hasCurrentTextDeltaStep({
539
+ graph,
540
+ metadata
541
+ });
542
+ }
543
+ var ChatModelStreamHandler = class {
544
+ async handle(event, data, metadata, graph) {
545
+ if (!graph) throw new Error("Graph not found");
546
+ if (!graph.config) throw new Error("Config not found in graph");
547
+ if (!data.chunk) {
548
+ console.warn(`No chunk found in ${event} event`);
549
+ return;
550
+ }
551
+ const agentContext = graph.getAgentContext(metadata);
552
+ const chunk = data.chunk;
553
+ const content = getChunkContent({
554
+ chunk,
555
+ reasoningKey: agentContext.reasoningKey,
556
+ provider: agentContext.provider
557
+ });
558
+ if (await require_handlers.handleServerToolResult({
559
+ graph,
560
+ content,
561
+ metadata,
562
+ agentContext
563
+ })) return;
564
+ if (shouldDeferMixedFinalReasoningChunk({
565
+ chunk,
566
+ agentContext
567
+ })) return;
568
+ if (shouldSkipLateOpenRouterReasoningChunk({
569
+ chunk,
570
+ agentContext,
571
+ graph,
572
+ metadata
573
+ })) return;
574
+ this.handleReasoning(chunk, agentContext);
575
+ const stepKey = graph.getStepKey(metadata);
576
+ let hasToolCalls = false;
577
+ const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;
578
+ const hasGoogleServerSideToolContent = require_llm.isGoogleLike(agentContext.provider) && Array.isArray(content) && content.some((c) => isGoogleServerSideToolContentPart(c));
579
+ if (hasGoogleServerSideToolContent && Array.isArray(content)) await dispatchGoogleServerSideToolStreamContent({
580
+ graph,
581
+ stepKey,
582
+ chunk,
583
+ agentContext,
584
+ content,
585
+ metadata
586
+ });
587
+ if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id != null && tc.id !== "" && tc.name != null && tc.name !== "")) {
588
+ hasToolCalls = true;
589
+ await require_handlers.handleToolCalls(chunk.tool_calls, metadata, graph);
590
+ if (hasFinalToolCallSignal(chunk)) {
591
+ startEagerToolExecutions({
592
+ graph,
593
+ metadata,
594
+ agentContext,
595
+ toolCalls: chunk.tool_calls,
596
+ skipExisting: true
597
+ });
598
+ if (!hasToolCallChunks) pruneEagerToolCallChunkStates({
599
+ graph,
600
+ stepKey,
601
+ clearStep: true
602
+ });
603
+ }
604
+ }
605
+ const isEmptyContent = typeof content === "undefined" || !content.length || typeof content === "string" && !content;
606
+ /** Set a preliminary message ID if found in empty chunk */
607
+ const isEmptyChunk = isEmptyContent && !hasToolCallChunks;
608
+ if (isEmptyChunk && (chunk.id ?? "") !== "" && !graph.prelimMessageIdsByStepKey.has(chunk.id ?? "")) graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? "");
609
+ else if (isEmptyChunk) return;
610
+ if (hasToolCallChunks && chunk.tool_call_chunks && chunk.tool_call_chunks.length && typeof chunk.tool_call_chunks[0]?.index === "number") {
611
+ const streamedToolCallSeal = require_streamedToolCallSeals.getStreamedToolCallSeal(chunk.response_metadata);
612
+ const allowSequentialSeal = canPrestartSequentialStreamedToolChunks(agentContext);
613
+ const canStreamEager = (allowSequentialSeal || hasExplicitStreamedToolCallSeals(chunk)) && !hasPotentialDirectToolInStreamContext({
614
+ graph,
615
+ agentContext
616
+ }) && isEagerToolExecutionEnabledForBatch({
617
+ graph,
618
+ metadata,
619
+ agentContext
620
+ });
621
+ if (canStreamEager) recordEagerToolCallChunks({
622
+ graph,
623
+ stepKey,
624
+ toolCallChunks: chunk.tool_call_chunks
625
+ });
626
+ await require_handlers.handleToolCallChunks({
627
+ graph,
628
+ stepKey,
629
+ toolCallChunks: chunk.tool_call_chunks,
630
+ metadata
631
+ });
632
+ if (canStreamEager) startReadyStreamedEagerToolExecutions({
633
+ graph,
634
+ metadata,
635
+ agentContext,
636
+ stepKey,
637
+ toolCallChunks: chunk.tool_call_chunks,
638
+ seal: streamedToolCallSeal,
639
+ allowSequentialSeal,
640
+ sealAll: hasFinalToolCallSignal(chunk)
641
+ });
642
+ }
643
+ if (isEmptyContent) return;
644
+ if (hasGoogleServerSideToolContent) return;
645
+ const message_id = require_ids.getMessageId(stepKey, graph) ?? "";
646
+ if (message_id) await graph.dispatchRunStep(stepKey, {
647
+ type: "message_creation",
648
+ message_creation: { message_id }
649
+ }, metadata);
650
+ let stepId = graph.getStepIdByKey(stepKey);
651
+ let runStep = graph.getRunStep(stepId);
652
+ if (shouldStartFreshMessageStepAfterGoogleServerSideTool({
653
+ graph,
654
+ stepId,
655
+ runStep,
656
+ content
657
+ })) {
658
+ stepId = await dispatchMessageCreationStep({
659
+ graph,
660
+ stepKey,
661
+ metadata
662
+ });
663
+ runStep = graph.getRunStep(stepId);
664
+ }
665
+ if (!runStep) {
666
+ console.warn(`\n
966
667
  ==============================================================
967
668
 
968
669
 
@@ -977,458 +678,269 @@ hasToolCallChunks: ${hasToolCallChunks}
977
678
 
978
679
  ==============================================================
979
680
  \n`);
980
- return;
981
- }
982
- /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */
983
- if (typeof content === 'string' && runStep.type === _enum.StepTypes.TOOL_CALLS) {
984
- return;
985
- }
986
- else if (hasToolCallChunks &&
987
- (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {
988
- return;
989
- }
990
- else if (typeof content === 'string') {
991
- if (agentContext.currentTokenType === _enum.ContentTypes.TEXT) {
992
- await graph.dispatchMessageDelta(stepId, {
993
- content: [
994
- {
995
- type: _enum.ContentTypes.TEXT,
996
- text: content,
997
- },
998
- ],
999
- }, metadata);
1000
- }
1001
- else if (agentContext.currentTokenType === 'think_and_text') {
1002
- const { text, thinking } = parseThinkingContent(content);
1003
- if (thinking) {
1004
- await graph.dispatchReasoningDelta(stepId, {
1005
- content: [
1006
- {
1007
- type: _enum.ContentTypes.THINK,
1008
- think: thinking,
1009
- },
1010
- ],
1011
- }, metadata);
1012
- }
1013
- if (text) {
1014
- agentContext.currentTokenType = _enum.ContentTypes.TEXT;
1015
- agentContext.tokenTypeSwitch = 'content';
1016
- const newStepKey = graph.getStepKey(metadata);
1017
- const message_id = ids.getMessageId(newStepKey, graph) ?? '';
1018
- await graph.dispatchRunStep(newStepKey, {
1019
- type: _enum.StepTypes.MESSAGE_CREATION,
1020
- message_creation: {
1021
- message_id,
1022
- },
1023
- }, metadata);
1024
- const newStepId = graph.getStepIdByKey(newStepKey);
1025
- await graph.dispatchMessageDelta(newStepId, {
1026
- content: [
1027
- {
1028
- type: _enum.ContentTypes.TEXT,
1029
- text: text,
1030
- },
1031
- ],
1032
- }, metadata);
1033
- }
1034
- }
1035
- else {
1036
- await graph.dispatchReasoningDelta(stepId, {
1037
- content: [
1038
- {
1039
- type: _enum.ContentTypes.THINK,
1040
- think: content,
1041
- },
1042
- ],
1043
- }, metadata);
1044
- }
1045
- }
1046
- else if (content.every((c) => isTextContentPart(c))) {
1047
- await graph.dispatchMessageDelta(stepId, {
1048
- content,
1049
- }, metadata);
1050
- }
1051
- else if (content.every((c) => isReasoningContentPart(c))) {
1052
- await graph.dispatchReasoningDelta(stepId, {
1053
- content: content.map((c) => ({
1054
- type: _enum.ContentTypes.THINK,
1055
- think: c.thinking ??
1056
- c.reasoning ??
1057
- c.reasoningText
1058
- ?.text ??
1059
- '',
1060
- })),
1061
- }, metadata);
1062
- }
1063
- }
1064
- handleReasoning(chunk, agentContext) {
1065
- let reasoning_content = chunk.additional_kwargs?.[agentContext.reasoningKey];
1066
- if (Array.isArray(chunk.content) &&
1067
- (chunk.content[0]?.type === _enum.ContentTypes.THINKING ||
1068
- chunk.content[0]?.type === _enum.ContentTypes.REASONING ||
1069
- chunk.content[0]?.type === _enum.ContentTypes.REASONING_CONTENT ||
1070
- chunk.content[0]?.type === 'redacted_thinking')) {
1071
- reasoning_content = 'valid';
1072
- }
1073
- else if ((agentContext.provider === _enum.Providers.OPENAI ||
1074
- agentContext.provider === _enum.Providers.AZURE) &&
1075
- reasoning_content != null &&
1076
- typeof reasoning_content !== 'string' &&
1077
- reasoning_content.summary?.[0]?.text != null &&
1078
- reasoning_content.summary[0].text) {
1079
- reasoning_content = 'valid';
1080
- }
1081
- else if (agentContext.provider === _enum.Providers.OPENROUTER &&
1082
- // Only set reasoning as valid if content is NOT present (content signals end of reasoning)
1083
- (chunk.content == null || chunk.content === '') &&
1084
- // Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)
1085
- ((chunk.additional_kwargs?.reasoning_details != null &&
1086
- Array.isArray(chunk.additional_kwargs.reasoning_details) &&
1087
- chunk.additional_kwargs.reasoning_details.length > 0) ||
1088
- (typeof chunk.additional_kwargs?.reasoning === 'string' &&
1089
- chunk.additional_kwargs.reasoning !== '') ||
1090
- (typeof chunk.additional_kwargs?.reasoning_content === 'string' &&
1091
- chunk.additional_kwargs.reasoning_content !== ''))) {
1092
- reasoning_content = 'valid';
1093
- }
1094
- if (reasoning_content != null &&
1095
- reasoning_content !== '' &&
1096
- (chunk.content == null ||
1097
- chunk.content === '' ||
1098
- reasoning_content === 'valid')) {
1099
- agentContext.currentTokenType = _enum.ContentTypes.THINK;
1100
- agentContext.tokenTypeSwitch = 'reasoning';
1101
- return;
1102
- }
1103
- else if (agentContext.tokenTypeSwitch === 'reasoning' &&
1104
- agentContext.currentTokenType !== _enum.ContentTypes.TEXT &&
1105
- ((chunk.content != null && chunk.content !== '') ||
1106
- (chunk.tool_calls?.length ?? 0) > 0 ||
1107
- (chunk.tool_call_chunks?.length ?? 0) > 0)) {
1108
- agentContext.currentTokenType = _enum.ContentTypes.TEXT;
1109
- agentContext.tokenTypeSwitch = 'content';
1110
- agentContext.reasoningTransitionCount++;
1111
- }
1112
- else if (chunk.content != null &&
1113
- typeof chunk.content === 'string' &&
1114
- chunk.content.includes('<think>') &&
1115
- chunk.content.includes('</think>')) {
1116
- agentContext.currentTokenType = 'think_and_text';
1117
- agentContext.tokenTypeSwitch = 'content';
1118
- }
1119
- else if (chunk.content != null &&
1120
- typeof chunk.content === 'string' &&
1121
- chunk.content.includes('<think>')) {
1122
- agentContext.currentTokenType = _enum.ContentTypes.THINK;
1123
- agentContext.tokenTypeSwitch = 'content';
1124
- }
1125
- else if (agentContext.lastToken != null &&
1126
- agentContext.lastToken.includes('</think>')) {
1127
- agentContext.currentTokenType = _enum.ContentTypes.TEXT;
1128
- agentContext.tokenTypeSwitch = 'content';
1129
- }
1130
- if (typeof chunk.content !== 'string') {
1131
- return;
1132
- }
1133
- agentContext.lastToken = chunk.content;
1134
- }
1135
- }
681
+ return;
682
+ }
683
+ if (typeof content === "string" && runStep.type === "tool_calls") return;
684
+ else if (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) return;
685
+ else if (typeof content === "string") if (agentContext.currentTokenType === "text") await graph.dispatchMessageDelta(stepId, { content: [{
686
+ type: "text",
687
+ text: content
688
+ }] }, metadata);
689
+ else if (agentContext.currentTokenType === "think_and_text") {
690
+ const { text, thinking } = parseThinkingContent(content);
691
+ if (thinking) await graph.dispatchReasoningDelta(stepId, { content: [{
692
+ type: "think",
693
+ think: thinking
694
+ }] }, metadata);
695
+ if (text) {
696
+ agentContext.currentTokenType = "text";
697
+ agentContext.tokenTypeSwitch = "content";
698
+ const newStepKey = graph.getStepKey(metadata);
699
+ const message_id = require_ids.getMessageId(newStepKey, graph) ?? "";
700
+ await graph.dispatchRunStep(newStepKey, {
701
+ type: "message_creation",
702
+ message_creation: { message_id }
703
+ }, metadata);
704
+ const newStepId = graph.getStepIdByKey(newStepKey);
705
+ await graph.dispatchMessageDelta(newStepId, { content: [{
706
+ type: "text",
707
+ text
708
+ }] }, metadata);
709
+ }
710
+ } else await graph.dispatchReasoningDelta(stepId, { content: [{
711
+ type: "think",
712
+ think: content
713
+ }] }, metadata);
714
+ else if (content.every((c) => isTextContentPart(c))) await graph.dispatchMessageDelta(stepId, { content }, metadata);
715
+ else if (content.every((c) => isReasoningContentPart(c))) await graph.dispatchReasoningDelta(stepId, { content: content.map((c) => ({
716
+ type: "think",
717
+ think: c.thinking ?? c.reasoning ?? c.reasoningText?.text ?? ""
718
+ })) }, metadata);
719
+ }
720
+ handleReasoning(chunk, agentContext) {
721
+ let reasoning_content = chunk.additional_kwargs?.[agentContext.reasoningKey];
722
+ if (Array.isArray(chunk.content) && (chunk.content[0]?.type === "thinking" || chunk.content[0]?.type === "reasoning" || chunk.content[0]?.type === "reasoning_content" || chunk.content[0]?.type === "redacted_thinking")) reasoning_content = "valid";
723
+ else if ((agentContext.provider === "openAI" || agentContext.provider === "azureOpenAI") && reasoning_content != null && typeof reasoning_content !== "string" && reasoning_content.summary?.[0]?.text != null && reasoning_content.summary[0].text) reasoning_content = "valid";
724
+ else if (agentContext.provider === "openrouter" && (chunk.content == null || chunk.content === "") && (chunk.additional_kwargs?.reasoning_details != null && Array.isArray(chunk.additional_kwargs.reasoning_details) && chunk.additional_kwargs.reasoning_details.length > 0 || typeof chunk.additional_kwargs?.reasoning === "string" && chunk.additional_kwargs.reasoning !== "" || typeof chunk.additional_kwargs?.reasoning_content === "string" && chunk.additional_kwargs.reasoning_content !== "")) reasoning_content = "valid";
725
+ if (reasoning_content != null && reasoning_content !== "" && (chunk.content == null || chunk.content === "" || reasoning_content === "valid")) {
726
+ agentContext.currentTokenType = "think";
727
+ agentContext.tokenTypeSwitch = "reasoning";
728
+ return;
729
+ } else if (agentContext.tokenTypeSwitch === "reasoning" && agentContext.currentTokenType !== "text" && (chunk.content != null && chunk.content !== "" || (chunk.tool_calls?.length ?? 0) > 0 || (chunk.tool_call_chunks?.length ?? 0) > 0)) {
730
+ agentContext.currentTokenType = "text";
731
+ agentContext.tokenTypeSwitch = "content";
732
+ agentContext.reasoningTransitionCount++;
733
+ } else if (chunk.content != null && typeof chunk.content === "string" && chunk.content.includes("<think>") && chunk.content.includes("</think>")) {
734
+ agentContext.currentTokenType = "think_and_text";
735
+ agentContext.tokenTypeSwitch = "content";
736
+ } else if (chunk.content != null && typeof chunk.content === "string" && chunk.content.includes("<think>")) {
737
+ agentContext.currentTokenType = "think";
738
+ agentContext.tokenTypeSwitch = "content";
739
+ } else if (agentContext.lastToken != null && agentContext.lastToken.includes("</think>")) {
740
+ agentContext.currentTokenType = "text";
741
+ agentContext.tokenTypeSwitch = "content";
742
+ }
743
+ if (typeof chunk.content !== "string") return;
744
+ agentContext.lastToken = chunk.content;
745
+ }
746
+ };
1136
747
  function createContentAggregator() {
1137
- const contentParts = [];
1138
- const stepMap = new Map();
1139
- const toolCallIdMap = new Map();
1140
- // Track agentId and groupId for each content index (applied to content parts)
1141
- const contentMetaMap = new Map();
1142
- const getFirstContentPart = (content) => {
1143
- if (content == null) {
1144
- return undefined;
1145
- }
1146
- return Array.isArray(content) ? content[0] : content;
1147
- };
1148
- const updateContent = (index, contentPart, finalUpdate = false) => {
1149
- if (!contentPart) {
1150
- console.warn('No content part found in \'updateContent\'');
1151
- return;
1152
- }
1153
- const partType = contentPart.type ?? '';
1154
- if (!partType) {
1155
- console.warn('No content type found in content part');
1156
- return;
1157
- }
1158
- if (!contentParts[index] && partType !== _enum.ContentTypes.TOOL_CALL) {
1159
- contentParts[index] = { type: partType };
1160
- }
1161
- if (!partType.startsWith(contentParts[index]?.type ?? '')) {
1162
- console.warn('Content type mismatch');
1163
- return;
1164
- }
1165
- if (partType.startsWith(_enum.ContentTypes.TEXT) &&
1166
- _enum.ContentTypes.TEXT in contentPart &&
1167
- typeof contentPart.text === 'string') {
1168
- // TODO: update this!!
1169
- const currentContent = contentParts[index];
1170
- const update = {
1171
- type: _enum.ContentTypes.TEXT,
1172
- text: (currentContent.text || '') + contentPart.text,
1173
- };
1174
- if (contentPart.tool_call_ids) {
1175
- update.tool_call_ids = contentPart.tool_call_ids;
1176
- }
1177
- contentParts[index] = update;
1178
- }
1179
- else if (partType.startsWith(_enum.ContentTypes.THINK) &&
1180
- _enum.ContentTypes.THINK in contentPart &&
1181
- typeof contentPart.think === 'string') {
1182
- const currentContent = contentParts[index];
1183
- const update = {
1184
- type: _enum.ContentTypes.THINK,
1185
- think: (currentContent.think || '') + contentPart.think,
1186
- };
1187
- contentParts[index] = update;
1188
- }
1189
- else if (partType.startsWith(_enum.ContentTypes.AGENT_UPDATE) &&
1190
- _enum.ContentTypes.AGENT_UPDATE in contentPart &&
1191
- contentPart.agent_update != null) {
1192
- const update = {
1193
- type: _enum.ContentTypes.AGENT_UPDATE,
1194
- agent_update: contentPart.agent_update,
1195
- };
1196
- contentParts[index] = update;
1197
- }
1198
- else if (partType === 'toolCall' || partType === 'toolResponse') {
1199
- contentParts[index] = contentPart;
1200
- }
1201
- else if (partType === _enum.ContentTypes.SUMMARY) {
1202
- const currentSummary = contentParts[index];
1203
- const incoming = contentPart;
1204
- contentParts[index] = {
1205
- ...incoming,
1206
- content: [
1207
- ...(currentSummary?.content ?? []),
1208
- ...(incoming.content ?? []),
1209
- ],
1210
- };
1211
- }
1212
- else if (partType === _enum.ContentTypes.IMAGE_URL &&
1213
- 'image_url' in contentPart) {
1214
- const currentContent = contentParts[index];
1215
- contentParts[index] = {
1216
- ...currentContent,
1217
- };
1218
- }
1219
- else if (partType === _enum.ContentTypes.TOOL_CALL &&
1220
- 'tool_call' in contentPart) {
1221
- const incomingName = contentPart.tool_call.name;
1222
- const incomingId = contentPart.tool_call.id;
1223
- const toolCallArgs = contentPart.tool_call.args;
1224
- // When we receive a tool call with a name, it's the complete tool call
1225
- // Consolidate with any previously accumulated args from chunks
1226
- const hasValidName = incomingName != null && incomingName !== '';
1227
- // Only process if incoming has a valid name (complete tool call)
1228
- // or if we're doing a final update with complete data
1229
- if (!hasValidName && !finalUpdate) {
1230
- return;
1231
- }
1232
- const existingContent = contentParts[index];
1233
- if (!finalUpdate && existingContent?.tool_call?.progress === 1) {
1234
- return;
1235
- }
1236
- /** When args are a valid object, they are likely already invoked */
1237
- let args = finalUpdate ||
1238
- typeof existingContent?.tool_call?.args === 'object' ||
1239
- typeof toolCallArgs === 'object'
1240
- ? contentPart.tool_call.args
1241
- : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');
1242
- if (finalUpdate &&
1243
- args == null &&
1244
- existingContent?.tool_call?.args != null) {
1245
- args = existingContent.tool_call.args;
1246
- }
1247
- const id = getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';
1248
- const name = getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??
1249
- '';
1250
- const newToolCall = {
1251
- id,
1252
- name,
1253
- args,
1254
- type: _enum.ToolCallTypes.TOOL_CALL,
1255
- };
1256
- const auth = contentPart.tool_call.auth ?? existingContent?.tool_call?.auth;
1257
- const expiresAt = contentPart.tool_call.expires_at ??
1258
- existingContent?.tool_call?.expires_at;
1259
- if (auth != null) {
1260
- newToolCall.auth = auth;
1261
- newToolCall.expires_at = expiresAt;
1262
- }
1263
- if (finalUpdate) {
1264
- newToolCall.progress = 1;
1265
- newToolCall.output = contentPart.tool_call.output;
1266
- }
1267
- contentParts[index] = {
1268
- type: _enum.ContentTypes.TOOL_CALL,
1269
- tool_call: newToolCall,
1270
- };
1271
- }
1272
- // Apply agentId (for MultiAgentGraph) and groupId (for parallel execution) to content parts
1273
- // - agentId present → MultiAgentGraph (show agent labels)
1274
- // - groupId present → parallel execution (render columns)
1275
- const meta = contentMetaMap.get(index);
1276
- if (meta?.agentId != null) {
1277
- contentParts[index].agentId = meta.agentId;
1278
- }
1279
- if (meta?.groupId != null) {
1280
- contentParts[index].groupId = meta.groupId;
1281
- }
1282
- };
1283
- const aggregateContent = ({ event, data, }) => {
1284
- if (event === _enum.GraphEvents.ON_SUMMARIZE_DELTA) {
1285
- const deltaData = data;
1286
- const runStep = stepMap.get(deltaData.id);
1287
- if (!runStep) {
1288
- console.warn('No run step found for summarize delta event');
1289
- return;
1290
- }
1291
- updateContent(runStep.index, deltaData.delta.summary);
1292
- return;
1293
- }
1294
- if (event === _enum.GraphEvents.ON_SUMMARIZE_COMPLETE) {
1295
- const completeData = data;
1296
- const summary = completeData.summary;
1297
- if (!summary?.boundary) {
1298
- return;
1299
- }
1300
- const runStep = stepMap.get(summary.boundary.messageId);
1301
- if (!runStep) {
1302
- return;
1303
- }
1304
- // Replace accumulated delta text with the authoritative final summary.
1305
- // Multi-stage summarization streams deltas from each chunk, which
1306
- // concatenate in updateContent. This event carries only the correct
1307
- // final text from the last stage.
1308
- contentParts[runStep.index] = summary;
1309
- return;
1310
- }
1311
- if (event === _enum.GraphEvents.ON_RUN_STEP) {
1312
- const runStep = data;
1313
- stepMap.set(runStep.id, runStep);
1314
- // Track agentId (MultiAgentGraph) and groupId (parallel execution) separately
1315
- // - agentId: present for all MultiAgentGraph runs (enables agent labels in UI)
1316
- // - groupId: present only for parallel execution (enables column rendering)
1317
- const hasAgentId = runStep.agentId != null && runStep.agentId !== '';
1318
- const hasGroupId = runStep.groupId != null;
1319
- if (hasAgentId || hasGroupId) {
1320
- const existingMeta = contentMetaMap.get(runStep.index) ?? {};
1321
- if (hasAgentId) {
1322
- existingMeta.agentId = runStep.agentId;
1323
- }
1324
- if (hasGroupId) {
1325
- existingMeta.groupId = runStep.groupId;
1326
- }
1327
- contentMetaMap.set(runStep.index, existingMeta);
1328
- }
1329
- if (runStep.summary != null) {
1330
- updateContent(runStep.index, runStep.summary);
1331
- }
1332
- if (runStep.stepDetails.type === _enum.StepTypes.TOOL_CALLS &&
1333
- runStep.stepDetails.tool_calls) {
1334
- runStep.stepDetails.tool_calls.forEach((toolCall) => {
1335
- const toolCallId = toolCall.id ?? '';
1336
- if ('id' in toolCall && toolCallId) {
1337
- toolCallIdMap.set(runStep.id, toolCallId);
1338
- }
1339
- const contentPart = {
1340
- type: _enum.ContentTypes.TOOL_CALL,
1341
- tool_call: {
1342
- args: toolCall.args,
1343
- name: toolCall.name,
1344
- id: toolCallId,
1345
- },
1346
- };
1347
- updateContent(runStep.index, contentPart);
1348
- });
1349
- }
1350
- }
1351
- else if (event === _enum.GraphEvents.ON_MESSAGE_DELTA) {
1352
- const messageDelta = data;
1353
- const runStep = stepMap.get(messageDelta.id);
1354
- if (!runStep) {
1355
- console.warn('No run step or runId found for message delta event');
1356
- return;
1357
- }
1358
- const contentPart = getFirstContentPart(messageDelta.delta.content);
1359
- if (contentPart != null) {
1360
- updateContent(runStep.index, contentPart);
1361
- }
1362
- }
1363
- else if (event === _enum.GraphEvents.ON_AGENT_UPDATE &&
1364
- data?.agent_update) {
1365
- const contentPart = data;
1366
- if (!contentPart) {
1367
- return;
1368
- }
1369
- updateContent(contentPart.agent_update.index, contentPart);
1370
- }
1371
- else if (event === _enum.GraphEvents.ON_REASONING_DELTA) {
1372
- const reasoningDelta = data;
1373
- const runStep = stepMap.get(reasoningDelta.id);
1374
- if (!runStep) {
1375
- console.warn('No run step or runId found for reasoning delta event');
1376
- return;
1377
- }
1378
- const contentPart = getFirstContentPart(reasoningDelta.delta.content);
1379
- if (contentPart != null) {
1380
- updateContent(runStep.index, contentPart);
1381
- }
1382
- }
1383
- else if (event === _enum.GraphEvents.ON_RUN_STEP_DELTA) {
1384
- const runStepDelta = data;
1385
- const runStep = stepMap.get(runStepDelta.id);
1386
- if (!runStep) {
1387
- console.warn('No run step or runId found for run step delta event');
1388
- return;
1389
- }
1390
- if (runStepDelta.delta.type === _enum.StepTypes.TOOL_CALLS &&
1391
- runStepDelta.delta.tool_calls) {
1392
- runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {
1393
- const toolCallId = toolCallIdMap.get(runStepDelta.id);
1394
- const contentPart = {
1395
- type: _enum.ContentTypes.TOOL_CALL,
1396
- tool_call: {
1397
- args: toolCallDelta.args ?? '',
1398
- name: toolCallDelta.name,
1399
- id: toolCallId,
1400
- auth: runStepDelta.delta.auth,
1401
- expires_at: runStepDelta.delta.expires_at,
1402
- },
1403
- };
1404
- updateContent(runStep.index, contentPart);
1405
- });
1406
- }
1407
- }
1408
- else if (event === _enum.GraphEvents.ON_RUN_STEP_COMPLETED) {
1409
- const { result } = data;
1410
- const { id: stepId } = result;
1411
- const runStep = stepMap.get(stepId);
1412
- if (!runStep) {
1413
- console.warn('No run step or runId found for completed step event');
1414
- return;
1415
- }
1416
- if (result.type === _enum.ContentTypes.SUMMARY && 'summary' in result) {
1417
- contentParts[runStep.index] = result.summary;
1418
- }
1419
- else if ('tool_call' in result) {
1420
- const contentPart = {
1421
- type: _enum.ContentTypes.TOOL_CALL,
1422
- tool_call: result.tool_call,
1423
- };
1424
- updateContent(runStep.index, contentPart, true);
1425
- }
1426
- }
1427
- };
1428
- return { contentParts, aggregateContent, stepMap };
1429
- }
1430
-
748
+ const contentParts = [];
749
+ const stepMap = /* @__PURE__ */ new Map();
750
+ const toolCallIdMap = /* @__PURE__ */ new Map();
751
+ const contentMetaMap = /* @__PURE__ */ new Map();
752
+ const getFirstContentPart = (content) => {
753
+ if (content == null) return;
754
+ return Array.isArray(content) ? content[0] : content;
755
+ };
756
+ const updateContent = (index, contentPart, finalUpdate = false) => {
757
+ if (!contentPart) {
758
+ console.warn("No content part found in 'updateContent'");
759
+ return;
760
+ }
761
+ const partType = contentPart.type ?? "";
762
+ if (!partType) {
763
+ console.warn("No content type found in content part");
764
+ return;
765
+ }
766
+ if (!contentParts[index] && partType !== "tool_call") contentParts[index] = { type: partType };
767
+ if (!partType.startsWith(contentParts[index]?.type ?? "")) {
768
+ console.warn("Content type mismatch");
769
+ return;
770
+ }
771
+ if (partType.startsWith("text") && "text" in contentPart && typeof contentPart.text === "string") {
772
+ const update = {
773
+ type: "text",
774
+ text: (contentParts[index].text || "") + contentPart.text
775
+ };
776
+ if (contentPart.tool_call_ids) update.tool_call_ids = contentPart.tool_call_ids;
777
+ contentParts[index] = update;
778
+ } else if (partType.startsWith("think") && "think" in contentPart && typeof contentPart.think === "string") contentParts[index] = {
779
+ type: "think",
780
+ think: (contentParts[index].think || "") + contentPart.think
781
+ };
782
+ else if (partType.startsWith("agent_update") && "agent_update" in contentPart && contentPart.agent_update != null) contentParts[index] = {
783
+ type: "agent_update",
784
+ agent_update: contentPart.agent_update
785
+ };
786
+ else if (partType === "toolCall" || partType === "toolResponse") contentParts[index] = contentPart;
787
+ else if (partType === "summary") {
788
+ const currentSummary = contentParts[index];
789
+ const incoming = contentPart;
790
+ contentParts[index] = {
791
+ ...incoming,
792
+ content: [...currentSummary?.content ?? [], ...incoming.content ?? []]
793
+ };
794
+ } else if (partType === "image_url" && "image_url" in contentPart) contentParts[index] = { ...contentParts[index] };
795
+ else if (partType === "tool_call" && "tool_call" in contentPart) {
796
+ const incomingName = contentPart.tool_call.name;
797
+ const incomingId = contentPart.tool_call.id;
798
+ const toolCallArgs = contentPart.tool_call.args;
799
+ if (!(incomingName != null && incomingName !== "") && !finalUpdate) return;
800
+ const existingContent = contentParts[index];
801
+ if (!finalUpdate && existingContent?.tool_call?.progress === 1) return;
802
+ /** When args are a valid object, they are likely already invoked */
803
+ let args = finalUpdate || typeof existingContent?.tool_call?.args === "object" || typeof toolCallArgs === "object" ? contentPart.tool_call.args : (existingContent?.tool_call?.args ?? "") + (toolCallArgs ?? "");
804
+ if (finalUpdate && args == null && existingContent?.tool_call?.args != null) args = existingContent.tool_call.args;
805
+ const newToolCall = {
806
+ id: getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? "",
807
+ name: getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ?? "",
808
+ args,
809
+ type: "tool_call"
810
+ };
811
+ const auth = contentPart.tool_call.auth ?? existingContent?.tool_call?.auth;
812
+ const expiresAt = contentPart.tool_call.expires_at ?? existingContent?.tool_call?.expires_at;
813
+ if (auth != null) {
814
+ newToolCall.auth = auth;
815
+ newToolCall.expires_at = expiresAt;
816
+ }
817
+ if (finalUpdate) {
818
+ newToolCall.progress = 1;
819
+ newToolCall.output = contentPart.tool_call.output;
820
+ }
821
+ contentParts[index] = {
822
+ type: "tool_call",
823
+ tool_call: newToolCall
824
+ };
825
+ }
826
+ const meta = contentMetaMap.get(index);
827
+ if (meta?.agentId != null) contentParts[index].agentId = meta.agentId;
828
+ if (meta?.groupId != null) contentParts[index].groupId = meta.groupId;
829
+ };
830
+ const aggregateContent = ({ event, data }) => {
831
+ if (event === "on_summarize_delta") {
832
+ const deltaData = data;
833
+ const runStep = stepMap.get(deltaData.id);
834
+ if (!runStep) {
835
+ console.warn("No run step found for summarize delta event");
836
+ return;
837
+ }
838
+ updateContent(runStep.index, deltaData.delta.summary);
839
+ return;
840
+ }
841
+ if (event === "on_summarize_complete") {
842
+ const summary = data.summary;
843
+ if (!summary?.boundary) return;
844
+ const runStep = stepMap.get(summary.boundary.messageId);
845
+ if (!runStep) return;
846
+ contentParts[runStep.index] = summary;
847
+ return;
848
+ }
849
+ if (event === "on_run_step") {
850
+ const runStep = data;
851
+ stepMap.set(runStep.id, runStep);
852
+ const hasAgentId = runStep.agentId != null && runStep.agentId !== "";
853
+ const hasGroupId = runStep.groupId != null;
854
+ if (hasAgentId || hasGroupId) {
855
+ const existingMeta = contentMetaMap.get(runStep.index) ?? {};
856
+ if (hasAgentId) existingMeta.agentId = runStep.agentId;
857
+ if (hasGroupId) existingMeta.groupId = runStep.groupId;
858
+ contentMetaMap.set(runStep.index, existingMeta);
859
+ }
860
+ if (runStep.summary != null) updateContent(runStep.index, runStep.summary);
861
+ if (runStep.stepDetails.type === "tool_calls" && runStep.stepDetails.tool_calls) runStep.stepDetails.tool_calls.forEach((toolCall) => {
862
+ const toolCallId = toolCall.id ?? "";
863
+ if ("id" in toolCall && toolCallId) toolCallIdMap.set(runStep.id, toolCallId);
864
+ const contentPart = {
865
+ type: "tool_call",
866
+ tool_call: {
867
+ args: toolCall.args,
868
+ name: toolCall.name,
869
+ id: toolCallId
870
+ }
871
+ };
872
+ updateContent(runStep.index, contentPart);
873
+ });
874
+ } else if (event === "on_message_delta") {
875
+ const messageDelta = data;
876
+ const runStep = stepMap.get(messageDelta.id);
877
+ if (!runStep) {
878
+ console.warn("No run step or runId found for message delta event");
879
+ return;
880
+ }
881
+ const contentPart = getFirstContentPart(messageDelta.delta.content);
882
+ if (contentPart != null) updateContent(runStep.index, contentPart);
883
+ } else if (event === "on_agent_update" && data?.agent_update) {
884
+ const contentPart = data;
885
+ if (!contentPart) return;
886
+ updateContent(contentPart.agent_update.index, contentPart);
887
+ } else if (event === "on_reasoning_delta") {
888
+ const reasoningDelta = data;
889
+ const runStep = stepMap.get(reasoningDelta.id);
890
+ if (!runStep) {
891
+ console.warn("No run step or runId found for reasoning delta event");
892
+ return;
893
+ }
894
+ const contentPart = getFirstContentPart(reasoningDelta.delta.content);
895
+ if (contentPart != null) updateContent(runStep.index, contentPart);
896
+ } else if (event === "on_run_step_delta") {
897
+ const runStepDelta = data;
898
+ const runStep = stepMap.get(runStepDelta.id);
899
+ if (!runStep) {
900
+ console.warn("No run step or runId found for run step delta event");
901
+ return;
902
+ }
903
+ if (runStepDelta.delta.type === "tool_calls" && runStepDelta.delta.tool_calls) runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {
904
+ const toolCallId = toolCallIdMap.get(runStepDelta.id);
905
+ const contentPart = {
906
+ type: "tool_call",
907
+ tool_call: {
908
+ args: toolCallDelta.args ?? "",
909
+ name: toolCallDelta.name,
910
+ id: toolCallId,
911
+ auth: runStepDelta.delta.auth,
912
+ expires_at: runStepDelta.delta.expires_at
913
+ }
914
+ };
915
+ updateContent(runStep.index, contentPart);
916
+ });
917
+ } else if (event === "on_run_step_completed") {
918
+ const { result } = data;
919
+ const { id: stepId } = result;
920
+ const runStep = stepMap.get(stepId);
921
+ if (!runStep) {
922
+ console.warn("No run step or runId found for completed step event");
923
+ return;
924
+ }
925
+ if (result.type === "summary" && "summary" in result) contentParts[runStep.index] = result.summary;
926
+ else if ("tool_call" in result) {
927
+ const contentPart = {
928
+ type: "tool_call",
929
+ tool_call: result.tool_call
930
+ };
931
+ updateContent(runStep.index, contentPart, true);
932
+ }
933
+ }
934
+ };
935
+ return {
936
+ contentParts,
937
+ aggregateContent,
938
+ stepMap
939
+ };
940
+ }
941
+ //#endregion
1431
942
  exports.ChatModelStreamHandler = ChatModelStreamHandler;
1432
943
  exports.createContentAggregator = createContentAggregator;
1433
944
  exports.getChunkContent = getChunkContent;
1434
- //# sourceMappingURL=stream.cjs.map
945
+
946
+ //# sourceMappingURL=stream.cjs.map