@librechat/agents 3.2.32 → 3.2.34

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 (597) 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 -731
  53. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  54. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +171 -256
  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 +214 -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 +141 -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 +404 -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 +1035 -1273
  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 +446 -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 +305 -418
  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 -1387
  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 +874 -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 +2146 -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 +46 -34
  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 -725
  324. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  325. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +171 -253
  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 +214 -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 +140 -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 +403 -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 +1035 -1268
  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 +446 -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 +305 -416
  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 -1383
  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 +872 -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 +2144 -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 +42 -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/llm/bedrock/utils/index.d.ts +1 -1
  545. package/dist/types/llm/bedrock/utils/message_outputs.d.ts +9 -0
  546. package/dist/types/llm/vertexai/index.d.ts +10 -0
  547. package/dist/types/tools/ToolNode.d.ts +8 -0
  548. package/dist/types/tools/search/tool.d.ts +17 -0
  549. package/dist/types/tools/search/types.d.ts +4 -0
  550. package/dist/types/tools/streamedToolCallSeals.d.ts +5 -1
  551. package/dist/types/types/tools.d.ts +10 -0
  552. package/package.json +4 -10
  553. package/src/__tests__/stream.eagerEventExecution.test.ts +703 -0
  554. package/src/llm/bedrock/index.ts +40 -0
  555. package/src/llm/bedrock/streamSealDispatch.test.ts +158 -0
  556. package/src/llm/bedrock/utils/index.ts +1 -0
  557. package/src/llm/bedrock/utils/message_outputs.test.ts +85 -0
  558. package/src/llm/bedrock/utils/message_outputs.ts +43 -0
  559. package/src/llm/google/utils/common.test.ts +64 -0
  560. package/src/llm/google/utils/common.ts +18 -0
  561. package/src/llm/openai/index.ts +95 -1
  562. package/src/llm/openai/sequentialToolCallSeals.test.ts +199 -0
  563. package/src/llm/vertexai/index.ts +31 -0
  564. package/src/llm/vertexai/sealStreamedToolCalls.test.ts +88 -0
  565. package/src/llm/vertexai/streamSealDispatch.test.ts +148 -0
  566. package/src/stream.ts +40 -6
  567. package/src/tools/ToolNode.ts +85 -3
  568. package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +368 -0
  569. package/src/tools/search/highlights.ts +9 -1
  570. package/src/tools/search/search.ts +41 -3
  571. package/src/tools/search/source-processing.test.ts +373 -0
  572. package/src/tools/search/tool.ts +22 -2
  573. package/src/tools/search/types.ts +4 -0
  574. package/src/tools/streamedToolCallSeals.ts +37 -9
  575. package/src/types/tools.ts +10 -0
  576. package/dist/cjs/langchain/google-common.cjs.map +0 -1
  577. package/dist/cjs/langchain/index.cjs.map +0 -1
  578. package/dist/cjs/langchain/language_models/chat_models.cjs.map +0 -1
  579. package/dist/cjs/langchain/messages/tool.cjs.map +0 -1
  580. package/dist/cjs/langchain/messages.cjs.map +0 -1
  581. package/dist/cjs/langchain/openai.cjs.map +0 -1
  582. package/dist/cjs/langchain/prompts.cjs.map +0 -1
  583. package/dist/cjs/langchain/runnables.cjs.map +0 -1
  584. package/dist/cjs/langchain/tools.cjs.map +0 -1
  585. package/dist/cjs/langchain/utils/env.cjs.map +0 -1
  586. package/dist/cjs/main.cjs.map +0 -1
  587. package/dist/esm/langchain/google-common.mjs.map +0 -1
  588. package/dist/esm/langchain/index.mjs.map +0 -1
  589. package/dist/esm/langchain/language_models/chat_models.mjs.map +0 -1
  590. package/dist/esm/langchain/messages/tool.mjs.map +0 -1
  591. package/dist/esm/langchain/messages.mjs.map +0 -1
  592. package/dist/esm/langchain/openai.mjs.map +0 -1
  593. package/dist/esm/langchain/prompts.mjs.map +0 -1
  594. package/dist/esm/langchain/runnables.mjs.map +0 -1
  595. package/dist/esm/langchain/tools.mjs.map +0 -1
  596. package/dist/esm/langchain/utils/env.mjs.map +0 -1
  597. package/dist/esm/main.mjs.map +0 -1
@@ -1,968 +1,687 @@
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;
121
+ }
122
+ /**
123
+ * True when a provider adapter marked every tool call on this chunk as
124
+ * complete on arrival (seal kind `all`), e.g. Google GenAI / Vertex AI, whose
125
+ * protocol delivers function calls as whole objects rather than arg deltas.
126
+ */
127
+ function hasOnArrivalToolCallSeal(chunk) {
128
+ const metadata = chunk.response_metadata;
129
+ return require_streamedToolCallSeals.getStreamedToolCallAdapter(metadata) != null && require_streamedToolCallSeals.getStreamedToolCallSeal(metadata)?.kind === "all";
170
130
  }
171
131
  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)));
132
+ const { graph, agentContext, toolCalls } = args;
133
+ return toolCalls.some((toolCall) => toolCall.name !== "" && (isDirectGraphTool(toolCall.name, agentContext) || isDirectLocalTool(toolCall.name, graph)));
176
134
  }
177
135
  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;
136
+ const { graph, agentContext } = args;
137
+ const engine = graph.toolExecution?.engine;
138
+ if (engine === "local" || engine === "cloudflare-sandbox") return true;
139
+ if ((agentContext?.graphTools?.length ?? 0) > 0) return true;
140
+ return false;
187
141
  }
188
142
  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);
143
+ const { graph, agentContext, toolCallChunks } = args;
144
+ return toolCallChunks?.some((toolCallChunk) => toolCallChunk.name != null && toolCallChunk.name !== "" && (isDirectGraphTool(toolCallChunk.name, agentContext) || isDirectLocalTool(toolCallChunk.name, graph))) === true;
194
145
  }
195
146
  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;
147
+ const { graph, agentContext, stepKey } = args;
148
+ const prefix = `${stepKey}\u0000`;
149
+ for (const [key, state] of graph.eagerEventToolCallChunks) {
150
+ if (!key.startsWith(prefix)) continue;
151
+ const name = state.name;
152
+ if (name != null && name !== "" && (isDirectGraphTool(name, agentContext) || isDirectLocalTool(name, graph))) return true;
153
+ }
154
+ return false;
210
155
  }
211
156
  function isGoogleServerSideToolContentPart(contentPart) {
212
- return contentPart.type === 'toolCall' || contentPart.type === 'toolResponse';
157
+ return contentPart.type === "toolCall" || contentPart.type === "toolResponse";
213
158
  }
214
159
  function isTextContentPart(contentPart) {
215
- return contentPart.type?.startsWith(_enum.ContentTypes.TEXT) ?? false;
160
+ return contentPart.type?.startsWith("text") ?? false;
216
161
  }
217
162
  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');
163
+ return (contentPart.type?.startsWith("thinking") ?? false) || (contentPart.type?.startsWith("reasoning") ?? false) || (contentPart.type?.startsWith("reasoning_content") ?? false) || contentPart.type === "redacted_thinking";
222
164
  }
223
165
  function getReasoningTextFromContentPart(contentPart) {
224
- return (contentPart.thinking ??
225
- contentPart.reasoning ??
226
- contentPart.reasoningText
227
- ?.text ??
228
- '');
166
+ return contentPart.thinking ?? contentPart.reasoning ?? contentPart.reasoningText?.text ?? "";
229
167
  }
230
168
  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 ?? '';
169
+ const reasoning = chunk.additional_kwargs?.[agentContext.reasoningKey];
170
+ if (typeof reasoning === "string") return reasoning;
171
+ return reasoning?.summary?.[0]?.text ?? "";
236
172
  }
237
- const googleServerSideToolStepIdsByGraph = new WeakMap();
173
+ const googleServerSideToolStepIdsByGraph = /* @__PURE__ */ new WeakMap();
238
174
  function markGoogleServerSideToolMessageStep(graph, stepId) {
239
- const stepIds = googleServerSideToolStepIdsByGraph.get(graph) ?? new Set();
240
- stepIds.add(stepId);
241
- googleServerSideToolStepIdsByGraph.set(graph, stepIds);
175
+ const stepIds = googleServerSideToolStepIdsByGraph.get(graph) ?? /* @__PURE__ */ new Set();
176
+ stepIds.add(stepId);
177
+ googleServerSideToolStepIdsByGraph.set(graph, stepIds);
242
178
  }
243
179
  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
- });
180
+ return googleServerSideToolStepIdsByGraph.get(graph)?.has(stepId) === true;
181
+ }
182
+ function shouldStartFreshMessageStepAfterGoogleServerSideTool({ graph, stepId, runStep, content }) {
183
+ if (runStep?.type !== "message_creation" || !isGoogleServerSideToolMessageStep(graph, stepId)) return false;
184
+ if (typeof content === "string") return true;
185
+ return content.every((c) => isTextContentPart(c)) || content.every((c) => isReasoningContentPart(c));
186
+ }
187
+ async function dispatchMessageCreationStep({ graph, stepKey, metadata }) {
188
+ const messageId = require_ids.getMessageId(stepKey, graph, true) ?? "";
189
+ return graph.dispatchRunStep(stepKey, {
190
+ type: "message_creation",
191
+ message_creation: { message_id: messageId }
192
+ }, metadata);
193
+ }
194
+ async function dispatchMessageContentParts({ graph, stepKey, content, metadata }) {
195
+ for (const contentPart of content) {
196
+ const currentStepId = await dispatchMessageCreationStep({
197
+ graph,
198
+ stepKey,
199
+ metadata
200
+ });
201
+ if (isGoogleServerSideToolContentPart(contentPart)) markGoogleServerSideToolMessageStep(graph, currentStepId);
202
+ await graph.dispatchMessageDelta(currentStepId, { content: [contentPart] }, metadata);
203
+ }
204
+ }
205
+ async function dispatchReasoningContentParts({ graph, stepKey, content, metadata }) {
206
+ if (content.length === 0) return;
207
+ const currentStepId = await dispatchMessageCreationStep({
208
+ graph,
209
+ stepKey,
210
+ metadata
211
+ });
212
+ await graph.dispatchReasoningDelta(currentStepId, { content }, metadata);
213
+ }
214
+ async function dispatchGoogleServerSideToolStreamContent({ graph, stepKey, chunk, agentContext, content, metadata }) {
215
+ const reasoningContent = [];
216
+ const reasoningText = getReasoningTextFromChunk(chunk, agentContext);
217
+ if (reasoningText !== "") reasoningContent.push({
218
+ type: "think",
219
+ think: reasoningText
220
+ });
221
+ reasoningContent.push(...content.filter((contentPart) => isReasoningContentPart(contentPart)).map((contentPart) => ({
222
+ type: "think",
223
+ think: getReasoningTextFromContentPart(contentPart)
224
+ })).filter((contentPart) => contentPart.think !== ""));
225
+ await dispatchReasoningContentParts({
226
+ graph,
227
+ stepKey,
228
+ content: reasoningContent,
229
+ metadata
230
+ });
231
+ await dispatchMessageContentParts({
232
+ graph,
233
+ stepKey,
234
+ content: content.filter((contentPart) => isTextContentPart(contentPart) || isGoogleServerSideToolContentPart(contentPart)),
235
+ metadata
236
+ });
324
237
  }
325
238
  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
- }));
239
+ const { graph, metadata, agentContext, toolCalls, skipExisting = false } = args;
240
+ if (!isEagerToolExecutionEnabledForBatch({
241
+ graph,
242
+ metadata,
243
+ agentContext
244
+ })) return;
245
+ if (hasDirectToolCallInBatch({
246
+ graph,
247
+ agentContext,
248
+ toolCalls
249
+ })) return;
250
+ if (graph.toolOutputReferences?.enabled === true && toolCalls.some((toolCall) => hasToolOutputReference(toolCall.args))) return;
251
+ const candidateToolCalls = skipExisting ? toolCalls.filter((toolCall) => {
252
+ if (toolCall.id == null || toolCall.id === "") return true;
253
+ return !graph.eagerEventToolExecutions.has(toolCall.id);
254
+ }) : toolCalls;
255
+ if (candidateToolCalls.length === 0) return [];
256
+ if (candidateToolCalls.some((toolCall) => toolCall.id == null || toolCall.id === "" || toolCall.name === "" || !skipExisting && graph.eagerEventToolExecutions.has(toolCall.id))) return;
257
+ const plan = require_eagerEventExecution.buildToolExecutionRequestPlan({
258
+ toolCalls: candidateToolCalls.map((toolCall) => ({
259
+ id: toolCall.id,
260
+ name: toolCall.name,
261
+ args: toolCall.args,
262
+ stepId: graph.toolCallStepIds.get(toolCall.id) ?? "",
263
+ codeSessionContext: getCodeSessionContext(graph, toolCall.name)
264
+ })),
265
+ usageCount: graph.getEagerEventToolUsageCount(agentContext?.agentId)
266
+ });
267
+ if (plan == null) return;
268
+ return plan.requests.map((request) => ({
269
+ id: request.id,
270
+ toolName: request.name,
271
+ coercedArgs: request.args,
272
+ request
273
+ }));
380
274
  }
381
275
  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
- }
276
+ const { graph, metadata, agentContext, toolCalls, skipExisting } = args;
277
+ const entries = createEagerToolExecutionPlan({
278
+ graph,
279
+ metadata,
280
+ agentContext,
281
+ toolCalls,
282
+ skipExisting
283
+ });
284
+ if (entries == null || entries.length === 0) return;
285
+ const records = [];
286
+ const promise = new Promise((resolve, reject) => {
287
+ let dispatchSettled = false;
288
+ let resultSettled = false;
289
+ let settledResults;
290
+ const maybeResolve = () => {
291
+ if (dispatchSettled && resultSettled) resolve(settledResults ?? []);
292
+ };
293
+ const batchRequest = {
294
+ toolCalls: entries.map((entry) => entry.request),
295
+ userId: graph.config?.configurable?.user_id,
296
+ agentId: agentContext?.agentId,
297
+ configurable: graph.config?.configurable,
298
+ metadata,
299
+ resolve: (results) => {
300
+ resultSettled = true;
301
+ settledResults = results;
302
+ maybeResolve();
303
+ },
304
+ reject
305
+ };
306
+ require_events.safeDispatchCustomEvent("on_tool_execute", batchRequest, graph.config).then(() => {
307
+ dispatchSettled = true;
308
+ maybeResolve();
309
+ }).catch(reject);
310
+ }).then(async (results) => {
311
+ await dispatchEagerToolCompletions({
312
+ graph,
313
+ agentContext,
314
+ records,
315
+ results
316
+ });
317
+ return { results };
318
+ }, (error) => ({ error: require_eagerEventExecution.normalizeError(error) }));
319
+ for (const entry of entries) {
320
+ const record = {
321
+ toolCallId: entry.id,
322
+ toolName: entry.toolName,
323
+ args: entry.coercedArgs,
324
+ request: entry.request,
325
+ promise
326
+ };
327
+ records.push(record);
328
+ graph.eagerEventToolExecutions.set(entry.id, record);
329
+ }
444
330
  }
445
331
  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
- }
332
+ const { graph, agentContext, records, results } = args;
333
+ const recordById = new Map(records.map((record) => [record.toolCallId, record]));
334
+ const maxToolResultChars = agentContext?.maxToolResultChars ?? require_truncation.calculateMaxToolResultChars(agentContext?.maxContextTokens);
335
+ for (const result of results) {
336
+ const record = recordById.get(result.toolCallId);
337
+ if (record == null) continue;
338
+ if (graph.eagerEventToolExecutions.get(result.toolCallId) !== record) continue;
339
+ const stepId = record.request.stepId ?? graph.toolCallStepIds.get(result.toolCallId) ?? "";
340
+ if (stepId === "") continue;
341
+ 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);
342
+ try {
343
+ if (await require_events.safeDispatchCustomEvent("on_run_step_completed", { result: {
344
+ id: stepId,
345
+ index: record.request.turn ?? 0,
346
+ type: "tool_call",
347
+ eager: true,
348
+ tool_call: {
349
+ args: JSON.stringify(record.request.args),
350
+ name: record.toolName,
351
+ id: result.toolCallId,
352
+ output,
353
+ progress: 1
354
+ }
355
+ } }, graph.config) === false) continue;
356
+ record.completionDispatched = true;
357
+ } catch (error) {
358
+ console.warn(`[stream] eager completion dispatch failed for toolCallId=${result.toolCallId}:`, error instanceof Error ? error.message : error);
359
+ }
360
+ }
495
361
  }
496
362
  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}`;
363
+ let chunkKey;
364
+ if (typeof toolCallChunk.index === "number") chunkKey = String(toolCallChunk.index);
365
+ else if (toolCallChunk.id != null && toolCallChunk.id !== "") chunkKey = toolCallChunk.id;
366
+ if (chunkKey == null) return;
367
+ return `${stepKey}\u0000${chunkKey}`;
508
368
  }
509
369
  function getEagerToolChunkIndex(toolCallChunk) {
510
- return typeof toolCallChunk.index === 'number'
511
- ? toolCallChunk.index
512
- : undefined;
370
+ return typeof toolCallChunk.index === "number" ? toolCallChunk.index : void 0;
513
371
  }
514
372
  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
- }
373
+ const { graph, stepKey, toolCallIds, clearStep = false } = args;
374
+ const prefix = `${stepKey}\u0000`;
375
+ for (const [key, state] of graph.eagerEventToolCallChunks) {
376
+ if (!key.startsWith(prefix)) continue;
377
+ if (clearStep || state.id != null && toolCallIds?.has(state.id) === true) graph.eagerEventToolCallChunks.delete(key);
378
+ }
526
379
  }
527
380
  function isEagerToolChunkStateComplete(state) {
528
- return (state.id != null &&
529
- state.id !== '' &&
530
- state.name != null &&
531
- state.name !== '' &&
532
- eagerEventExecution.coerceRecordArgs(state.argsText) != null);
381
+ return state.id != null && state.id !== "" && state.name != null && state.name !== "" && require_eagerEventExecution.coerceRecordArgs(state.argsText) != null;
533
382
  }
534
383
  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}`;
384
+ if (incoming === "") return existing;
385
+ if (existing === "") return incoming;
386
+ if (incoming === existing) try {
387
+ JSON.parse(incoming);
388
+ return incoming;
389
+ } catch {
390
+ return `${existing}${incoming}`;
391
+ }
392
+ if (incoming.startsWith(existing)) return incoming;
393
+ if (existing.startsWith(incoming)) return existing;
394
+ try {
395
+ JSON.parse(existing);
396
+ JSON.parse(incoming);
397
+ return incoming;
398
+ } catch {}
399
+ 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)}`;
400
+ return `${existing}${incoming}`;
570
401
  }
571
402
  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
- }
403
+ const { graph, stepKey, toolCallChunks } = args;
404
+ if (toolCallChunks == null || toolCallChunks.length === 0) return;
405
+ for (const toolCallChunk of toolCallChunks) {
406
+ const key = getEagerToolChunkKey(stepKey, toolCallChunk);
407
+ if (key == null) continue;
408
+ const incomingId = toolCallChunk.id != null && toolCallChunk.id !== "" ? toolCallChunk.id : void 0;
409
+ const incomingName = toolCallChunk.name != null && toolCallChunk.name !== "" ? toolCallChunk.name : void 0;
410
+ const previous = graph.eagerEventToolCallChunks.get(key);
411
+ const shouldReset = previous != null && (incomingId != null && previous.id != null && incomingId !== previous.id || incomingName != null && previous.name != null && incomingName !== previous.name);
412
+ const existing = previous == null || shouldReset ? { argsText: "" } : previous;
413
+ const id = incomingId ?? existing.id;
414
+ const name = incomingName ?? existing.name;
415
+ const incomingArgs = toolCallChunk.args ?? "";
416
+ const next = {
417
+ id,
418
+ name,
419
+ argsText: incomingArgs !== "" && incomingArgs.length > 1 && incomingArgs === existing.lastArgsFragment ? existing.argsText : mergeToolCallArgsText(existing.argsText, incomingArgs),
420
+ index: getEagerToolChunkIndex(toolCallChunk) ?? existing.index,
421
+ lastArgsFragment: incomingArgs !== "" ? incomingArgs : existing.lastArgsFragment
422
+ };
423
+ graph.eagerEventToolCallChunks.set(key, next);
424
+ }
621
425
  }
622
426
  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
- });
427
+ const { graph, stepKey, toolCallChunks, seal, allowSequentialSeal = false, sealAll = false } = args;
428
+ const currentIndices = /* @__PURE__ */ new Set();
429
+ for (const toolCallChunk of toolCallChunks ?? []) {
430
+ const index = getEagerToolChunkIndex(toolCallChunk);
431
+ if (index != null) currentIndices.add(index);
432
+ }
433
+ const highestCurrentIndex = currentIndices.size > 0 ? Math.max(...currentIndices) : void 0;
434
+ const prefix = `${stepKey}\u0000`;
435
+ const readyEntries = [];
436
+ for (const [key, state] of graph.eagerEventToolCallChunks) {
437
+ if (!key.startsWith(prefix)) continue;
438
+ if (state.id != null && graph.eagerEventToolExecutions.has(state.id)) {
439
+ graph.eagerEventToolCallChunks.delete(key);
440
+ continue;
441
+ }
442
+ if (!isEagerToolChunkStateComplete(state)) continue;
443
+ const isSealedByLaterChunk = allowSequentialSeal && highestCurrentIndex != null && state.index != null && state.index < highestCurrentIndex && !currentIndices.has(state.index);
444
+ const isSealedExplicitly = seal?.kind === "single" && (seal.id != null && state.id === seal.id || seal.index != null && state.index === seal.index);
445
+ if (sealAll || seal?.kind === "all" || isSealedByLaterChunk || isSealedExplicitly) readyEntries.push({
446
+ key,
447
+ state
448
+ });
449
+ }
450
+ pruneEagerToolCallChunkStates({
451
+ graph,
452
+ stepKey,
453
+ toolCallIds: new Set(readyEntries.map(({ state }) => state.id).filter((id) => id != null && id !== ""))
454
+ });
455
+ if (sealAll) pruneEagerToolCallChunkStates({
456
+ graph,
457
+ stepKey,
458
+ clearStep: true
459
+ });
460
+ return readyEntries.sort((left, right) => (left.state.index ?? 0) - (right.state.index ?? 0)).flatMap(({ state }) => {
461
+ const args = require_eagerEventExecution.coerceRecordArgs(state.argsText);
462
+ if (args == null) return [];
463
+ return [{
464
+ id: state.id,
465
+ name: state.name ?? "",
466
+ args
467
+ }];
468
+ });
685
469
  }
686
470
  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;
471
+ const { graph, metadata, agentContext, stepKey, toolCallChunks, seal, allowSequentialSeal, sealAll } = args;
472
+ if (hasPotentialDirectToolInStreamContext({
473
+ graph,
474
+ agentContext
475
+ }) || hasDirectToolCallChunkInBatch({
476
+ graph,
477
+ agentContext,
478
+ toolCallChunks
479
+ }) || hasDirectToolCallChunkStateInStep({
480
+ graph,
481
+ agentContext,
482
+ stepKey
483
+ }) || !isEagerToolExecutionEnabledForBatch({
484
+ graph,
485
+ metadata,
486
+ agentContext
487
+ })) return;
488
+ const toolCalls = getStreamedReadyToolCalls({
489
+ graph,
490
+ stepKey,
491
+ toolCallChunks,
492
+ seal,
493
+ allowSequentialSeal,
494
+ sealAll
495
+ });
496
+ if (toolCalls.length === 0) return;
497
+ startEagerToolExecutions({
498
+ graph,
499
+ metadata,
500
+ agentContext,
501
+ toolCalls,
502
+ skipExisting: true
503
+ });
504
+ }
505
+ function getChunkContent({ chunk, provider, reasoningKey }) {
506
+ if (require_llm.isGoogleLike(provider) && Array.isArray(chunk?.content) && chunk.content.some((c) => isGoogleServerSideToolContentPart(c))) return chunk.content;
507
+ 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;
508
+ if (provider === "openrouter") {
509
+ if (typeof chunk?.content === "string" && chunk.content !== "") return chunk.content;
510
+ const reasoning = chunk?.additional_kwargs?.reasoning;
511
+ if (reasoning != null && reasoning !== "") return reasoning;
512
+ const reasoningContent = chunk?.additional_kwargs?.reasoning_content;
513
+ if (reasoningContent != null && reasoningContent !== "") return reasoningContent;
514
+ return chunk?.content;
515
+ }
516
+ const keyedReasoning = chunk?.additional_kwargs?.[reasoningKey];
517
+ if (typeof chunk?.content === "string" && chunk.content !== "" && keyedReasoning != null && keyedReasoning !== "") return chunk.content;
518
+ return (keyedReasoning ?? "") || chunk?.content;
748
519
  }
749
520
  function isDisableStreamingEnabled(clientOptions) {
750
- return (clientOptions != null &&
751
- 'disableStreaming' in clientOptions &&
752
- clientOptions.disableStreaming === true);
521
+ return clientOptions != null && "disableStreaming" in clientOptions && clientOptions.disableStreaming === true;
753
522
  }
754
523
  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
524
+ if (typeof value === "string") return value !== "";
525
+ if (Array.isArray(value)) return value.length > 0;
526
+ if (value == null) return false;
527
+ return value.summary?.some((summary) => summary.text != null && summary.text.length > 0) === true;
528
+ }
529
+ function shouldDeferMixedFinalReasoningChunk({ chunk, agentContext }) {
530
+ if ((chunk.tool_calls?.length ?? 0) > 0 || (chunk.tool_call_chunks?.length ?? 0) > 0 || typeof chunk.content !== "string" || chunk.content === "") return false;
531
+ const additionalKwargs = chunk.additional_kwargs;
532
+ if (agentContext.provider === "openrouter" && hasReasoningContent(additionalKwargs?.reasoning_details)) return true;
533
+ if (!isDisableStreamingEnabled(agentContext.clientOptions)) return false;
534
+ return hasReasoningContent(additionalKwargs?.[agentContext.reasoningKey]) || hasReasoningContent(additionalKwargs?.reasoning_content) || hasReasoningContent(additionalKwargs?.reasoning) || hasReasoningContent(additionalKwargs?.reasoning_details);
535
+ }
536
+ function hasCurrentTextDeltaStep({ graph, metadata }) {
537
+ if (metadata == null) return false;
538
+ const baseStepKey = graph.getStepBaseKey(metadata);
539
+ for (const [stepKey, stepIds] of graph.stepKeyIds) {
540
+ if (stepKey !== baseStepKey && !stepKey.startsWith(`${baseStepKey}_`)) continue;
541
+ if (stepIds.some((stepId) => graph.messageStepHasTextDeltas.has(stepId))) return true;
542
+ }
543
+ return false;
544
+ }
545
+ function shouldSkipLateOpenRouterReasoningChunk({ chunk, agentContext, graph, metadata }) {
546
+ if (agentContext.provider !== "openrouter" || (chunk.tool_calls?.length ?? 0) > 0 || (chunk.tool_call_chunks?.length ?? 0) > 0 || chunk.content != null && chunk.content !== "") return false;
547
+ return (hasReasoningContent(chunk.additional_kwargs?.reasoning) || hasReasoningContent(chunk.additional_kwargs?.reasoning_content) || hasReasoningContent(chunk.additional_kwargs?.reasoning_details)) && hasCurrentTextDeltaStep({
548
+ graph,
549
+ metadata
550
+ });
551
+ }
552
+ var ChatModelStreamHandler = class {
553
+ async handle(event, data, metadata, graph) {
554
+ if (!graph) throw new Error("Graph not found");
555
+ if (!graph.config) throw new Error("Config not found in graph");
556
+ if (!data.chunk) {
557
+ console.warn(`No chunk found in ${event} event`);
558
+ return;
559
+ }
560
+ const agentContext = graph.getAgentContext(metadata);
561
+ const chunk = data.chunk;
562
+ const content = getChunkContent({
563
+ chunk,
564
+ reasoningKey: agentContext.reasoningKey,
565
+ provider: agentContext.provider
566
+ });
567
+ if (await require_handlers.handleServerToolResult({
568
+ graph,
569
+ content,
570
+ metadata,
571
+ agentContext
572
+ })) return;
573
+ if (shouldDeferMixedFinalReasoningChunk({
574
+ chunk,
575
+ agentContext
576
+ })) return;
577
+ if (shouldSkipLateOpenRouterReasoningChunk({
578
+ chunk,
579
+ agentContext,
580
+ graph,
581
+ metadata
582
+ })) return;
583
+ this.handleReasoning(chunk, agentContext);
584
+ const stepKey = graph.getStepKey(metadata);
585
+ let hasToolCalls = false;
586
+ const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;
587
+ const hasGoogleServerSideToolContent = require_llm.isGoogleLike(agentContext.provider) && Array.isArray(content) && content.some((c) => isGoogleServerSideToolContentPart(c));
588
+ if (hasGoogleServerSideToolContent && Array.isArray(content)) await dispatchGoogleServerSideToolStreamContent({
589
+ graph,
590
+ stepKey,
591
+ chunk,
592
+ agentContext,
593
+ content,
594
+ metadata
595
+ });
596
+ if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id != null && tc.id !== "" && tc.name != null && tc.name !== "")) {
597
+ hasToolCalls = true;
598
+ await require_handlers.handleToolCalls(chunk.tool_calls, metadata, graph);
599
+ if (hasFinalToolCallSignal(chunk)) {
600
+ startEagerToolExecutions({
601
+ graph,
602
+ metadata,
603
+ agentContext,
604
+ toolCalls: chunk.tool_calls,
605
+ skipExisting: true
606
+ });
607
+ if (!hasToolCallChunks) pruneEagerToolCallChunkStates({
608
+ graph,
609
+ stepKey,
610
+ clearStep: true
611
+ });
612
+ } else if (hasOnArrivalToolCallSeal(chunk) && !hasPotentialDirectToolInStreamContext({
613
+ graph,
614
+ agentContext
615
+ })) startEagerToolExecutions({
616
+ graph,
617
+ metadata,
618
+ agentContext,
619
+ toolCalls: chunk.tool_calls,
620
+ skipExisting: true
621
+ });
622
+ }
623
+ const isEmptyContent = typeof content === "undefined" || !content.length || typeof content === "string" && !content;
624
+ /** Set a preliminary message ID if found in empty chunk */
625
+ const isEmptyChunk = isEmptyContent && !hasToolCallChunks;
626
+ if (isEmptyChunk && (chunk.id ?? "") !== "" && !graph.prelimMessageIdsByStepKey.has(chunk.id ?? "")) graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? "");
627
+ else if (isEmptyChunk) return;
628
+ if (hasToolCallChunks && chunk.tool_call_chunks && chunk.tool_call_chunks.length && typeof chunk.tool_call_chunks[0]?.index === "number") {
629
+ const streamedToolCallSeal = require_streamedToolCallSeals.getStreamedToolCallSeal(chunk.response_metadata);
630
+ const allowSequentialSeal = canPrestartSequentialStreamedToolChunks(agentContext) || require_streamedToolCallSeals.streamedToolCallAdapterAllowsSequentialSeal(chunk.response_metadata);
631
+ const canStreamEager = (allowSequentialSeal || hasExplicitStreamedToolCallSeals(chunk)) && !hasPotentialDirectToolInStreamContext({
632
+ graph,
633
+ agentContext
634
+ }) && isEagerToolExecutionEnabledForBatch({
635
+ graph,
636
+ metadata,
637
+ agentContext
638
+ });
639
+ if (canStreamEager) recordEagerToolCallChunks({
640
+ graph,
641
+ stepKey,
642
+ toolCallChunks: chunk.tool_call_chunks
643
+ });
644
+ await require_handlers.handleToolCallChunks({
645
+ graph,
646
+ stepKey,
647
+ toolCallChunks: chunk.tool_call_chunks,
648
+ metadata
649
+ });
650
+ if (canStreamEager) startReadyStreamedEagerToolExecutions({
651
+ graph,
652
+ metadata,
653
+ agentContext,
654
+ stepKey,
655
+ toolCallChunks: chunk.tool_call_chunks,
656
+ seal: streamedToolCallSeal,
657
+ allowSequentialSeal,
658
+ sealAll: hasFinalToolCallSignal(chunk)
659
+ });
660
+ }
661
+ if (isEmptyContent) return;
662
+ if (hasGoogleServerSideToolContent) return;
663
+ const message_id = require_ids.getMessageId(stepKey, graph) ?? "";
664
+ if (message_id) await graph.dispatchRunStep(stepKey, {
665
+ type: "message_creation",
666
+ message_creation: { message_id }
667
+ }, metadata);
668
+ let stepId = graph.getStepIdByKey(stepKey);
669
+ let runStep = graph.getRunStep(stepId);
670
+ if (shouldStartFreshMessageStepAfterGoogleServerSideTool({
671
+ graph,
672
+ stepId,
673
+ runStep,
674
+ content
675
+ })) {
676
+ stepId = await dispatchMessageCreationStep({
677
+ graph,
678
+ stepKey,
679
+ metadata
680
+ });
681
+ runStep = graph.getRunStep(stepId);
682
+ }
683
+ if (!runStep) {
684
+ console.warn(`\n
966
685
  ==============================================================
967
686
 
968
687
 
@@ -977,458 +696,269 @@ hasToolCallChunks: ${hasToolCallChunks}
977
696
 
978
697
  ==============================================================
979
698
  \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
- }
699
+ return;
700
+ }
701
+ if (typeof content === "string" && runStep.type === "tool_calls") return;
702
+ else if (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) return;
703
+ else if (typeof content === "string") if (agentContext.currentTokenType === "text") await graph.dispatchMessageDelta(stepId, { content: [{
704
+ type: "text",
705
+ text: content
706
+ }] }, metadata);
707
+ else if (agentContext.currentTokenType === "think_and_text") {
708
+ const { text, thinking } = parseThinkingContent(content);
709
+ if (thinking) await graph.dispatchReasoningDelta(stepId, { content: [{
710
+ type: "think",
711
+ think: thinking
712
+ }] }, metadata);
713
+ if (text) {
714
+ agentContext.currentTokenType = "text";
715
+ agentContext.tokenTypeSwitch = "content";
716
+ const newStepKey = graph.getStepKey(metadata);
717
+ const message_id = require_ids.getMessageId(newStepKey, graph) ?? "";
718
+ await graph.dispatchRunStep(newStepKey, {
719
+ type: "message_creation",
720
+ message_creation: { message_id }
721
+ }, metadata);
722
+ const newStepId = graph.getStepIdByKey(newStepKey);
723
+ await graph.dispatchMessageDelta(newStepId, { content: [{
724
+ type: "text",
725
+ text
726
+ }] }, metadata);
727
+ }
728
+ } else await graph.dispatchReasoningDelta(stepId, { content: [{
729
+ type: "think",
730
+ think: content
731
+ }] }, metadata);
732
+ else if (content.every((c) => isTextContentPart(c))) await graph.dispatchMessageDelta(stepId, { content }, metadata);
733
+ else if (content.every((c) => isReasoningContentPart(c))) await graph.dispatchReasoningDelta(stepId, { content: content.map((c) => ({
734
+ type: "think",
735
+ think: c.thinking ?? c.reasoning ?? c.reasoningText?.text ?? ""
736
+ })) }, metadata);
737
+ }
738
+ handleReasoning(chunk, agentContext) {
739
+ let reasoning_content = chunk.additional_kwargs?.[agentContext.reasoningKey];
740
+ 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";
741
+ 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";
742
+ 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";
743
+ if (reasoning_content != null && reasoning_content !== "" && (chunk.content == null || chunk.content === "" || reasoning_content === "valid")) {
744
+ agentContext.currentTokenType = "think";
745
+ agentContext.tokenTypeSwitch = "reasoning";
746
+ return;
747
+ } 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)) {
748
+ agentContext.currentTokenType = "text";
749
+ agentContext.tokenTypeSwitch = "content";
750
+ agentContext.reasoningTransitionCount++;
751
+ } else if (chunk.content != null && typeof chunk.content === "string" && chunk.content.includes("<think>") && chunk.content.includes("</think>")) {
752
+ agentContext.currentTokenType = "think_and_text";
753
+ agentContext.tokenTypeSwitch = "content";
754
+ } else if (chunk.content != null && typeof chunk.content === "string" && chunk.content.includes("<think>")) {
755
+ agentContext.currentTokenType = "think";
756
+ agentContext.tokenTypeSwitch = "content";
757
+ } else if (agentContext.lastToken != null && agentContext.lastToken.includes("</think>")) {
758
+ agentContext.currentTokenType = "text";
759
+ agentContext.tokenTypeSwitch = "content";
760
+ }
761
+ if (typeof chunk.content !== "string") return;
762
+ agentContext.lastToken = chunk.content;
763
+ }
764
+ };
1136
765
  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
-
766
+ const contentParts = [];
767
+ const stepMap = /* @__PURE__ */ new Map();
768
+ const toolCallIdMap = /* @__PURE__ */ new Map();
769
+ const contentMetaMap = /* @__PURE__ */ new Map();
770
+ const getFirstContentPart = (content) => {
771
+ if (content == null) return;
772
+ return Array.isArray(content) ? content[0] : content;
773
+ };
774
+ const updateContent = (index, contentPart, finalUpdate = false) => {
775
+ if (!contentPart) {
776
+ console.warn("No content part found in 'updateContent'");
777
+ return;
778
+ }
779
+ const partType = contentPart.type ?? "";
780
+ if (!partType) {
781
+ console.warn("No content type found in content part");
782
+ return;
783
+ }
784
+ if (!contentParts[index] && partType !== "tool_call") contentParts[index] = { type: partType };
785
+ if (!partType.startsWith(contentParts[index]?.type ?? "")) {
786
+ console.warn("Content type mismatch");
787
+ return;
788
+ }
789
+ if (partType.startsWith("text") && "text" in contentPart && typeof contentPart.text === "string") {
790
+ const update = {
791
+ type: "text",
792
+ text: (contentParts[index].text || "") + contentPart.text
793
+ };
794
+ if (contentPart.tool_call_ids) update.tool_call_ids = contentPart.tool_call_ids;
795
+ contentParts[index] = update;
796
+ } else if (partType.startsWith("think") && "think" in contentPart && typeof contentPart.think === "string") contentParts[index] = {
797
+ type: "think",
798
+ think: (contentParts[index].think || "") + contentPart.think
799
+ };
800
+ else if (partType.startsWith("agent_update") && "agent_update" in contentPart && contentPart.agent_update != null) contentParts[index] = {
801
+ type: "agent_update",
802
+ agent_update: contentPart.agent_update
803
+ };
804
+ else if (partType === "toolCall" || partType === "toolResponse") contentParts[index] = contentPart;
805
+ else if (partType === "summary") {
806
+ const currentSummary = contentParts[index];
807
+ const incoming = contentPart;
808
+ contentParts[index] = {
809
+ ...incoming,
810
+ content: [...currentSummary?.content ?? [], ...incoming.content ?? []]
811
+ };
812
+ } else if (partType === "image_url" && "image_url" in contentPart) contentParts[index] = { ...contentParts[index] };
813
+ else if (partType === "tool_call" && "tool_call" in contentPart) {
814
+ const incomingName = contentPart.tool_call.name;
815
+ const incomingId = contentPart.tool_call.id;
816
+ const toolCallArgs = contentPart.tool_call.args;
817
+ if (!(incomingName != null && incomingName !== "") && !finalUpdate) return;
818
+ const existingContent = contentParts[index];
819
+ if (!finalUpdate && existingContent?.tool_call?.progress === 1) return;
820
+ /** When args are a valid object, they are likely already invoked */
821
+ let args = finalUpdate || typeof existingContent?.tool_call?.args === "object" || typeof toolCallArgs === "object" ? contentPart.tool_call.args : (existingContent?.tool_call?.args ?? "") + (toolCallArgs ?? "");
822
+ if (finalUpdate && args == null && existingContent?.tool_call?.args != null) args = existingContent.tool_call.args;
823
+ const newToolCall = {
824
+ id: getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? "",
825
+ name: getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ?? "",
826
+ args,
827
+ type: "tool_call"
828
+ };
829
+ const auth = contentPart.tool_call.auth ?? existingContent?.tool_call?.auth;
830
+ const expiresAt = contentPart.tool_call.expires_at ?? existingContent?.tool_call?.expires_at;
831
+ if (auth != null) {
832
+ newToolCall.auth = auth;
833
+ newToolCall.expires_at = expiresAt;
834
+ }
835
+ if (finalUpdate) {
836
+ newToolCall.progress = 1;
837
+ newToolCall.output = contentPart.tool_call.output;
838
+ }
839
+ contentParts[index] = {
840
+ type: "tool_call",
841
+ tool_call: newToolCall
842
+ };
843
+ }
844
+ const meta = contentMetaMap.get(index);
845
+ if (meta?.agentId != null) contentParts[index].agentId = meta.agentId;
846
+ if (meta?.groupId != null) contentParts[index].groupId = meta.groupId;
847
+ };
848
+ const aggregateContent = ({ event, data }) => {
849
+ if (event === "on_summarize_delta") {
850
+ const deltaData = data;
851
+ const runStep = stepMap.get(deltaData.id);
852
+ if (!runStep) {
853
+ console.warn("No run step found for summarize delta event");
854
+ return;
855
+ }
856
+ updateContent(runStep.index, deltaData.delta.summary);
857
+ return;
858
+ }
859
+ if (event === "on_summarize_complete") {
860
+ const summary = data.summary;
861
+ if (!summary?.boundary) return;
862
+ const runStep = stepMap.get(summary.boundary.messageId);
863
+ if (!runStep) return;
864
+ contentParts[runStep.index] = summary;
865
+ return;
866
+ }
867
+ if (event === "on_run_step") {
868
+ const runStep = data;
869
+ stepMap.set(runStep.id, runStep);
870
+ const hasAgentId = runStep.agentId != null && runStep.agentId !== "";
871
+ const hasGroupId = runStep.groupId != null;
872
+ if (hasAgentId || hasGroupId) {
873
+ const existingMeta = contentMetaMap.get(runStep.index) ?? {};
874
+ if (hasAgentId) existingMeta.agentId = runStep.agentId;
875
+ if (hasGroupId) existingMeta.groupId = runStep.groupId;
876
+ contentMetaMap.set(runStep.index, existingMeta);
877
+ }
878
+ if (runStep.summary != null) updateContent(runStep.index, runStep.summary);
879
+ if (runStep.stepDetails.type === "tool_calls" && runStep.stepDetails.tool_calls) runStep.stepDetails.tool_calls.forEach((toolCall) => {
880
+ const toolCallId = toolCall.id ?? "";
881
+ if ("id" in toolCall && toolCallId) toolCallIdMap.set(runStep.id, toolCallId);
882
+ const contentPart = {
883
+ type: "tool_call",
884
+ tool_call: {
885
+ args: toolCall.args,
886
+ name: toolCall.name,
887
+ id: toolCallId
888
+ }
889
+ };
890
+ updateContent(runStep.index, contentPart);
891
+ });
892
+ } else if (event === "on_message_delta") {
893
+ const messageDelta = data;
894
+ const runStep = stepMap.get(messageDelta.id);
895
+ if (!runStep) {
896
+ console.warn("No run step or runId found for message delta event");
897
+ return;
898
+ }
899
+ const contentPart = getFirstContentPart(messageDelta.delta.content);
900
+ if (contentPart != null) updateContent(runStep.index, contentPart);
901
+ } else if (event === "on_agent_update" && data?.agent_update) {
902
+ const contentPart = data;
903
+ if (!contentPart) return;
904
+ updateContent(contentPart.agent_update.index, contentPart);
905
+ } else if (event === "on_reasoning_delta") {
906
+ const reasoningDelta = data;
907
+ const runStep = stepMap.get(reasoningDelta.id);
908
+ if (!runStep) {
909
+ console.warn("No run step or runId found for reasoning delta event");
910
+ return;
911
+ }
912
+ const contentPart = getFirstContentPart(reasoningDelta.delta.content);
913
+ if (contentPart != null) updateContent(runStep.index, contentPart);
914
+ } else if (event === "on_run_step_delta") {
915
+ const runStepDelta = data;
916
+ const runStep = stepMap.get(runStepDelta.id);
917
+ if (!runStep) {
918
+ console.warn("No run step or runId found for run step delta event");
919
+ return;
920
+ }
921
+ if (runStepDelta.delta.type === "tool_calls" && runStepDelta.delta.tool_calls) runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {
922
+ const toolCallId = toolCallIdMap.get(runStepDelta.id);
923
+ const contentPart = {
924
+ type: "tool_call",
925
+ tool_call: {
926
+ args: toolCallDelta.args ?? "",
927
+ name: toolCallDelta.name,
928
+ id: toolCallId,
929
+ auth: runStepDelta.delta.auth,
930
+ expires_at: runStepDelta.delta.expires_at
931
+ }
932
+ };
933
+ updateContent(runStep.index, contentPart);
934
+ });
935
+ } else if (event === "on_run_step_completed") {
936
+ const { result } = data;
937
+ const { id: stepId } = result;
938
+ const runStep = stepMap.get(stepId);
939
+ if (!runStep) {
940
+ console.warn("No run step or runId found for completed step event");
941
+ return;
942
+ }
943
+ if (result.type === "summary" && "summary" in result) contentParts[runStep.index] = result.summary;
944
+ else if ("tool_call" in result) {
945
+ const contentPart = {
946
+ type: "tool_call",
947
+ tool_call: result.tool_call
948
+ };
949
+ updateContent(runStep.index, contentPart, true);
950
+ }
951
+ }
952
+ };
953
+ return {
954
+ contentParts,
955
+ aggregateContent,
956
+ stepMap
957
+ };
958
+ }
959
+ //#endregion
1431
960
  exports.ChatModelStreamHandler = ChatModelStreamHandler;
1432
961
  exports.createContentAggregator = createContentAggregator;
1433
962
  exports.getChunkContent = getChunkContent;
1434
- //# sourceMappingURL=stream.cjs.map
963
+
964
+ //# sourceMappingURL=stream.cjs.map