@librechat/agents 3.4.6 → 3.5.0

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 (1027) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +0 -356
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/agents/projection.cjs +0 -9
  4. package/dist/cjs/agents/projection.cjs.map +1 -1
  5. package/dist/cjs/common/constants.cjs +0 -26
  6. package/dist/cjs/common/constants.cjs.map +1 -1
  7. package/dist/cjs/common/enum.cjs +0 -85
  8. package/dist/cjs/common/enum.cjs.map +1 -1
  9. package/dist/cjs/events.cjs +0 -14
  10. package/dist/cjs/events.cjs.map +1 -1
  11. package/dist/cjs/graphs/Graph.cjs +1 -909
  12. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  13. package/dist/cjs/graphs/MultiAgentGraph.cjs +7 -272
  14. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  15. package/dist/cjs/graphs/applyGraphRuntimeConfig.cjs.map +1 -1
  16. package/dist/cjs/graphs/createGraph.cjs.map +1 -1
  17. package/dist/cjs/hitl/askUserQuestion.cjs +0 -53
  18. package/dist/cjs/hitl/askUserQuestion.cjs.map +1 -1
  19. package/dist/cjs/hitl/askUserQuestions.cjs +0 -20
  20. package/dist/cjs/hitl/askUserQuestions.cjs.map +1 -1
  21. package/dist/cjs/hitl/askUserQuestionsInterrupt.cjs +0 -6
  22. package/dist/cjs/hitl/askUserQuestionsInterrupt.cjs.map +1 -1
  23. package/dist/cjs/hooks/HookRegistry.cjs +0 -127
  24. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  25. package/dist/cjs/hooks/createToolPolicyHook.cjs +0 -38
  26. package/dist/cjs/hooks/createToolPolicyHook.cjs.map +1 -1
  27. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +0 -77
  28. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs.map +1 -1
  29. package/dist/cjs/hooks/executeHooks.cjs +0 -79
  30. package/dist/cjs/hooks/executeHooks.cjs.map +1 -1
  31. package/dist/cjs/hooks/index.cjs +0 -16
  32. package/dist/cjs/hooks/index.cjs.map +1 -1
  33. package/dist/cjs/hooks/matchers.cjs +0 -104
  34. package/dist/cjs/hooks/matchers.cjs.map +1 -1
  35. package/dist/cjs/hooks/types.cjs +0 -8
  36. package/dist/cjs/hooks/types.cjs.map +1 -1
  37. package/dist/cjs/instrumentation.cjs +0 -14
  38. package/dist/cjs/instrumentation.cjs.map +1 -1
  39. package/dist/cjs/langfuse.cjs +0 -75
  40. package/dist/cjs/langfuse.cjs.map +1 -1
  41. package/dist/cjs/langfuseConfig.cjs.map +1 -1
  42. package/dist/cjs/langfuseRuntimeContext.cjs +0 -13
  43. package/dist/cjs/langfuseRuntimeContext.cjs.map +1 -1
  44. package/dist/cjs/langfuseRuntimeScope.cjs +0 -4
  45. package/dist/cjs/langfuseRuntimeScope.cjs.map +1 -1
  46. package/dist/cjs/langfuseSpanRegistry.cjs +0 -28
  47. package/dist/cjs/langfuseSpanRegistry.cjs.map +1 -1
  48. package/dist/cjs/langfuseToolOutputTracing.cjs +0 -3
  49. package/dist/cjs/langfuseToolOutputTracing.cjs.map +1 -1
  50. package/dist/cjs/langfuseTraceShaping.cjs +0 -74
  51. package/dist/cjs/langfuseTraceShaping.cjs.map +1 -1
  52. package/dist/cjs/llm/anthropic/index.cjs +0 -3
  53. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  54. package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
  55. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +1 -111
  56. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  57. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +0 -1
  58. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
  59. package/dist/cjs/llm/anthropic/utils/stream_events.cjs +0 -8
  60. package/dist/cjs/llm/anthropic/utils/stream_events.cjs.map +1 -1
  61. package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -1
  62. package/dist/cjs/llm/bedrock/cachePoints.cjs.map +1 -1
  63. package/dist/cjs/llm/bedrock/index.cjs +1 -95
  64. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  65. package/dist/cjs/llm/bedrock/toolCache.cjs.map +1 -1
  66. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +0 -78
  67. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  68. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +0 -24
  69. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -1
  70. package/dist/cjs/llm/contextOverflowRecovery.cjs +0 -62
  71. package/dist/cjs/llm/contextOverflowRecovery.cjs.map +1 -1
  72. package/dist/cjs/llm/fake.cjs.map +1 -1
  73. package/dist/cjs/llm/google/index.cjs +2 -21
  74. package/dist/cjs/llm/google/index.cjs.map +1 -1
  75. package/dist/cjs/llm/google/utils/common.cjs +5 -35
  76. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  77. package/dist/cjs/llm/init.cjs +0 -9
  78. package/dist/cjs/llm/init.cjs.map +1 -1
  79. package/dist/cjs/llm/invoke.cjs +1 -270
  80. package/dist/cjs/llm/invoke.cjs.map +1 -1
  81. package/dist/cjs/llm/mistral/index.cjs.map +1 -1
  82. package/dist/cjs/llm/openai/index.cjs +0 -99
  83. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  84. package/dist/cjs/llm/openai/streamMetadata.cjs +0 -21
  85. package/dist/cjs/llm/openai/streamMetadata.cjs.map +1 -1
  86. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  87. package/dist/cjs/llm/openrouter/index.cjs +0 -1
  88. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  89. package/dist/cjs/llm/openrouter/toolCache.cjs +0 -6
  90. package/dist/cjs/llm/openrouter/toolCache.cjs.map +1 -1
  91. package/dist/cjs/llm/preempt.cjs +0 -75
  92. package/dist/cjs/llm/preempt.cjs.map +1 -1
  93. package/dist/cjs/llm/providers.cjs.map +1 -1
  94. package/dist/cjs/llm/request.cjs +0 -10
  95. package/dist/cjs/llm/request.cjs.map +1 -1
  96. package/dist/cjs/llm/stream/chunkAdapters.cjs +0 -62
  97. package/dist/cjs/llm/stream/chunkAdapters.cjs.map +1 -1
  98. package/dist/cjs/llm/stream/smoother.cjs +0 -58
  99. package/dist/cjs/llm/stream/smoother.cjs.map +1 -1
  100. package/dist/cjs/llm/streamLimits.cjs +4 -293
  101. package/dist/cjs/llm/streamLimits.cjs.map +1 -1
  102. package/dist/cjs/llm/truncation.cjs +0 -36
  103. package/dist/cjs/llm/truncation.cjs.map +1 -1
  104. package/dist/cjs/llm/vertexai/index.cjs +0 -330
  105. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  106. package/dist/cjs/messages/alternation.cjs +0 -43
  107. package/dist/cjs/messages/alternation.cjs.map +1 -1
  108. package/dist/cjs/messages/anthropicToolCache.cjs +0 -45
  109. package/dist/cjs/messages/anthropicToolCache.cjs.map +1 -1
  110. package/dist/cjs/messages/assistantPhase.cjs +0 -12
  111. package/dist/cjs/messages/assistantPhase.cjs.map +1 -1
  112. package/dist/cjs/messages/budget.cjs +0 -9
  113. package/dist/cjs/messages/budget.cjs.map +1 -1
  114. package/dist/cjs/messages/cache.cjs +0 -172
  115. package/dist/cjs/messages/cache.cjs.map +1 -1
  116. package/dist/cjs/messages/content.cjs +0 -9
  117. package/dist/cjs/messages/content.cjs.map +1 -1
  118. package/dist/cjs/messages/contextPruning.cjs +0 -15
  119. package/dist/cjs/messages/contextPruning.cjs.map +1 -1
  120. package/dist/cjs/messages/contextPruningSettings.cjs +0 -3
  121. package/dist/cjs/messages/contextPruningSettings.cjs.map +1 -1
  122. package/dist/cjs/messages/core.cjs +0 -48
  123. package/dist/cjs/messages/core.cjs.map +1 -1
  124. package/dist/cjs/messages/format.cjs +1 -345
  125. package/dist/cjs/messages/format.cjs.map +1 -1
  126. package/dist/cjs/messages/handoffCue.cjs +0 -36
  127. package/dist/cjs/messages/handoffCue.cjs.map +1 -1
  128. package/dist/cjs/messages/ids.cjs.map +1 -1
  129. package/dist/cjs/messages/injected.cjs +0 -33
  130. package/dist/cjs/messages/injected.cjs.map +1 -1
  131. package/dist/cjs/messages/langchain.cjs +0 -14
  132. package/dist/cjs/messages/langchain.cjs.map +1 -1
  133. package/dist/cjs/messages/prune.cjs +1 -184
  134. package/dist/cjs/messages/prune.cjs.map +1 -1
  135. package/dist/cjs/messages/recency.cjs +0 -32
  136. package/dist/cjs/messages/recency.cjs.map +1 -1
  137. package/dist/cjs/messages/reducer.cjs +0 -30
  138. package/dist/cjs/messages/reducer.cjs.map +1 -1
  139. package/dist/cjs/messages/tools.cjs +0 -14
  140. package/dist/cjs/messages/tools.cjs.map +1 -1
  141. package/dist/cjs/openai/index.cjs.map +1 -1
  142. package/dist/cjs/prompts/activityLabel.cjs +9 -79
  143. package/dist/cjs/prompts/activityLabel.cjs.map +1 -1
  144. package/dist/cjs/responses/index.cjs.map +1 -1
  145. package/dist/cjs/run.cjs +2 -538
  146. package/dist/cjs/run.cjs.map +1 -1
  147. package/dist/cjs/session/AgentSession.cjs +1 -17
  148. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  149. package/dist/cjs/session/JsonlSessionStore.cjs.map +1 -1
  150. package/dist/cjs/session/handlers.cjs +0 -7
  151. package/dist/cjs/session/handlers.cjs.map +1 -1
  152. package/dist/cjs/session/ids.cjs.map +1 -1
  153. package/dist/cjs/session/messageSerialization.cjs +0 -4
  154. package/dist/cjs/session/messageSerialization.cjs.map +1 -1
  155. package/dist/cjs/stream.cjs +1 -93
  156. package/dist/cjs/stream.cjs.map +1 -1
  157. package/dist/cjs/summarization/index.cjs +0 -27
  158. package/dist/cjs/summarization/index.cjs.map +1 -1
  159. package/dist/cjs/summarization/node.cjs +0 -273
  160. package/dist/cjs/summarization/node.cjs.map +1 -1
  161. package/dist/cjs/tools/BashExecutor.cjs +0 -35
  162. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  163. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +0 -24
  164. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  165. package/dist/cjs/tools/Calculator.cjs.map +1 -1
  166. package/dist/cjs/tools/CodeExecutor.cjs +0 -13
  167. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  168. package/dist/cjs/tools/CodeSessionFileSummary.cjs.map +1 -1
  169. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +0 -101
  170. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  171. package/dist/cjs/tools/ReadFile.cjs.map +1 -1
  172. package/dist/cjs/tools/SkillTool.cjs +0 -5
  173. package/dist/cjs/tools/SkillTool.cjs.map +1 -1
  174. package/dist/cjs/tools/SubagentTool.cjs +0 -10
  175. package/dist/cjs/tools/SubagentTool.cjs.map +1 -1
  176. package/dist/cjs/tools/ToolNode.cjs +6 -1038
  177. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  178. package/dist/cjs/tools/ToolSearch.cjs +0 -179
  179. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  180. package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs.map +1 -1
  181. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs.map +1 -1
  182. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs +0 -39
  183. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs.map +1 -1
  184. package/dist/cjs/tools/cloudflare/CloudflareSandboxTools.cjs.map +1 -1
  185. package/dist/cjs/tools/eagerEventExecution.cjs +0 -6
  186. package/dist/cjs/tools/eagerEventExecution.cjs.map +1 -1
  187. package/dist/cjs/tools/handlers.cjs +1 -41
  188. package/dist/cjs/tools/handlers.cjs.map +1 -1
  189. package/dist/cjs/tools/intentArg.cjs +1 -132
  190. package/dist/cjs/tools/intentArg.cjs.map +1 -1
  191. package/dist/cjs/tools/local/CompileCheckTool.cjs +0 -25
  192. package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -1
  193. package/dist/cjs/tools/local/FileCheckpointer.cjs +0 -23
  194. package/dist/cjs/tools/local/FileCheckpointer.cjs.map +1 -1
  195. package/dist/cjs/tools/local/LocalCodingTools.cjs +0 -80
  196. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  197. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +0 -126
  198. package/dist/cjs/tools/local/LocalExecutionEngine.cjs.map +1 -1
  199. package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -1
  200. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +0 -12
  201. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -1
  202. package/dist/cjs/tools/local/attachments.cjs +0 -44
  203. package/dist/cjs/tools/local/attachments.cjs.map +1 -1
  204. package/dist/cjs/tools/local/bashAst.cjs +0 -16
  205. package/dist/cjs/tools/local/bashAst.cjs.map +1 -1
  206. package/dist/cjs/tools/local/editStrategies.cjs +0 -14
  207. package/dist/cjs/tools/local/editStrategies.cjs.map +1 -1
  208. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
  209. package/dist/cjs/tools/local/syntaxCheck.cjs +0 -31
  210. package/dist/cjs/tools/local/syntaxCheck.cjs.map +1 -1
  211. package/dist/cjs/tools/local/textEncoding.cjs +0 -11
  212. package/dist/cjs/tools/local/textEncoding.cjs.map +1 -1
  213. package/dist/cjs/tools/local/workspaceFS.cjs +0 -33
  214. package/dist/cjs/tools/local/workspaceFS.cjs.map +1 -1
  215. package/dist/cjs/tools/ptcTimeout.cjs.map +1 -1
  216. package/dist/cjs/tools/schema.cjs +0 -8
  217. package/dist/cjs/tools/schema.cjs.map +1 -1
  218. package/dist/cjs/tools/search/anthropic.cjs +0 -9
  219. package/dist/cjs/tools/search/anthropic.cjs.map +1 -1
  220. package/dist/cjs/tools/search/content.cjs.map +1 -1
  221. package/dist/cjs/tools/search/crw-scraper.cjs +0 -33
  222. package/dist/cjs/tools/search/crw-scraper.cjs.map +1 -1
  223. package/dist/cjs/tools/search/crw-search.cjs +0 -2
  224. package/dist/cjs/tools/search/crw-search.cjs.map +1 -1
  225. package/dist/cjs/tools/search/firecrawl.cjs +0 -25
  226. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  227. package/dist/cjs/tools/search/format.cjs +0 -30
  228. package/dist/cjs/tools/search/format.cjs.map +1 -1
  229. package/dist/cjs/tools/search/highlights.cjs +0 -16
  230. package/dist/cjs/tools/search/highlights.cjs.map +1 -1
  231. package/dist/cjs/tools/search/keenable-scraper.cjs +0 -8
  232. package/dist/cjs/tools/search/keenable-scraper.cjs.map +1 -1
  233. package/dist/cjs/tools/search/keenable-search.cjs +0 -7
  234. package/dist/cjs/tools/search/keenable-search.cjs.map +1 -1
  235. package/dist/cjs/tools/search/rerankers.cjs +0 -35
  236. package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
  237. package/dist/cjs/tools/search/schema.cjs +0 -1
  238. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  239. package/dist/cjs/tools/search/search.cjs +1 -14
  240. package/dist/cjs/tools/search/search.cjs.map +1 -1
  241. package/dist/cjs/tools/search/serper-scraper.cjs +0 -46
  242. package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -1
  243. package/dist/cjs/tools/search/tavily-scraper.cjs.map +1 -1
  244. package/dist/cjs/tools/search/tavily-search.cjs.map +1 -1
  245. package/dist/cjs/tools/search/tool.cjs +0 -25
  246. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  247. package/dist/cjs/tools/search/utils.cjs +0 -8
  248. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  249. package/dist/cjs/tools/skillCatalog.cjs +0 -6
  250. package/dist/cjs/tools/skillCatalog.cjs.map +1 -1
  251. package/dist/cjs/tools/streamedToolCallSeals.cjs +0 -6
  252. package/dist/cjs/tools/streamedToolCallSeals.cjs.map +1 -1
  253. package/dist/cjs/tools/subagent/SubagentExecutionRegistry.cjs +0 -2
  254. package/dist/cjs/tools/subagent/SubagentExecutionRegistry.cjs.map +1 -1
  255. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +3 -213
  256. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  257. package/dist/cjs/tools/subagent/SubagentReplay.cjs.map +1 -1
  258. package/dist/cjs/tools/subagent/childGraphConfig.cjs +0 -4
  259. package/dist/cjs/tools/subagent/childGraphConfig.cjs.map +1 -1
  260. package/dist/cjs/tools/subagent/runtimeLimits.cjs.map +1 -1
  261. package/dist/cjs/tools/toolOutputReferences.cjs +1 -322
  262. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  263. package/dist/cjs/types/hitl.cjs +0 -5
  264. package/dist/cjs/types/hitl.cjs.map +1 -1
  265. package/dist/cjs/utils/callbacks.cjs.map +1 -1
  266. package/dist/cjs/utils/errors.cjs +14 -165
  267. package/dist/cjs/utils/errors.cjs.map +1 -1
  268. package/dist/cjs/utils/events.cjs +0 -10
  269. package/dist/cjs/utils/events.cjs.map +1 -1
  270. package/dist/cjs/utils/graph.cjs.map +1 -1
  271. package/dist/cjs/utils/handlers.cjs +0 -3
  272. package/dist/cjs/utils/handlers.cjs.map +1 -1
  273. package/dist/cjs/utils/llm.cjs +0 -1
  274. package/dist/cjs/utils/llm.cjs.map +1 -1
  275. package/dist/cjs/utils/misc.cjs +0 -16
  276. package/dist/cjs/utils/misc.cjs.map +1 -1
  277. package/dist/cjs/utils/proxy.cjs +0 -26
  278. package/dist/cjs/utils/proxy.cjs.map +1 -1
  279. package/dist/cjs/utils/run.cjs +0 -6
  280. package/dist/cjs/utils/run.cjs.map +1 -1
  281. package/dist/cjs/utils/schema.cjs +0 -5
  282. package/dist/cjs/utils/schema.cjs.map +1 -1
  283. package/dist/cjs/utils/title.cjs +0 -6
  284. package/dist/cjs/utils/title.cjs.map +1 -1
  285. package/dist/cjs/utils/tokens.cjs +0 -113
  286. package/dist/cjs/utils/tokens.cjs.map +1 -1
  287. package/dist/cjs/utils/toolContent.cjs +0 -41
  288. package/dist/cjs/utils/toolContent.cjs.map +1 -1
  289. package/dist/cjs/utils/truncation.cjs +0 -61
  290. package/dist/cjs/utils/truncation.cjs.map +1 -1
  291. package/dist/esm/agents/AgentContext.mjs +0 -356
  292. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  293. package/dist/esm/agents/projection.mjs +0 -9
  294. package/dist/esm/agents/projection.mjs.map +1 -1
  295. package/dist/esm/common/constants.mjs +0 -26
  296. package/dist/esm/common/constants.mjs.map +1 -1
  297. package/dist/esm/common/enum.mjs +0 -85
  298. package/dist/esm/common/enum.mjs.map +1 -1
  299. package/dist/esm/events.mjs +0 -14
  300. package/dist/esm/events.mjs.map +1 -1
  301. package/dist/esm/graphs/Graph.mjs +1 -909
  302. package/dist/esm/graphs/Graph.mjs.map +1 -1
  303. package/dist/esm/graphs/MultiAgentGraph.mjs +7 -272
  304. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  305. package/dist/esm/graphs/applyGraphRuntimeConfig.mjs.map +1 -1
  306. package/dist/esm/graphs/createGraph.mjs.map +1 -1
  307. package/dist/esm/hitl/askUserQuestion.mjs +0 -53
  308. package/dist/esm/hitl/askUserQuestion.mjs.map +1 -1
  309. package/dist/esm/hitl/askUserQuestions.mjs +0 -20
  310. package/dist/esm/hitl/askUserQuestions.mjs.map +1 -1
  311. package/dist/esm/hitl/askUserQuestionsInterrupt.mjs +0 -6
  312. package/dist/esm/hitl/askUserQuestionsInterrupt.mjs.map +1 -1
  313. package/dist/esm/hooks/HookRegistry.mjs +0 -127
  314. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  315. package/dist/esm/hooks/createToolPolicyHook.mjs +0 -38
  316. package/dist/esm/hooks/createToolPolicyHook.mjs.map +1 -1
  317. package/dist/esm/hooks/createWorkspacePolicyHook.mjs +0 -77
  318. package/dist/esm/hooks/createWorkspacePolicyHook.mjs.map +1 -1
  319. package/dist/esm/hooks/executeHooks.mjs +0 -79
  320. package/dist/esm/hooks/executeHooks.mjs.map +1 -1
  321. package/dist/esm/hooks/index.mjs +0 -16
  322. package/dist/esm/hooks/index.mjs.map +1 -1
  323. package/dist/esm/hooks/matchers.mjs +0 -104
  324. package/dist/esm/hooks/matchers.mjs.map +1 -1
  325. package/dist/esm/hooks/types.mjs +0 -8
  326. package/dist/esm/hooks/types.mjs.map +1 -1
  327. package/dist/esm/instrumentation.mjs +0 -14
  328. package/dist/esm/instrumentation.mjs.map +1 -1
  329. package/dist/esm/langfuse.mjs +0 -75
  330. package/dist/esm/langfuse.mjs.map +1 -1
  331. package/dist/esm/langfuseConfig.mjs.map +1 -1
  332. package/dist/esm/langfuseRuntimeContext.mjs +0 -13
  333. package/dist/esm/langfuseRuntimeContext.mjs.map +1 -1
  334. package/dist/esm/langfuseRuntimeScope.mjs +0 -4
  335. package/dist/esm/langfuseRuntimeScope.mjs.map +1 -1
  336. package/dist/esm/langfuseSpanRegistry.mjs +0 -28
  337. package/dist/esm/langfuseSpanRegistry.mjs.map +1 -1
  338. package/dist/esm/langfuseToolOutputTracing.mjs +0 -3
  339. package/dist/esm/langfuseToolOutputTracing.mjs.map +1 -1
  340. package/dist/esm/langfuseTraceShaping.mjs +0 -74
  341. package/dist/esm/langfuseTraceShaping.mjs.map +1 -1
  342. package/dist/esm/llm/anthropic/index.mjs +0 -3
  343. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  344. package/dist/esm/llm/anthropic/types.mjs.map +1 -1
  345. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +1 -111
  346. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  347. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +0 -1
  348. package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
  349. package/dist/esm/llm/anthropic/utils/stream_events.mjs +0 -8
  350. package/dist/esm/llm/anthropic/utils/stream_events.mjs.map +1 -1
  351. package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -1
  352. package/dist/esm/llm/bedrock/cachePoints.mjs.map +1 -1
  353. package/dist/esm/llm/bedrock/index.mjs +1 -95
  354. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  355. package/dist/esm/llm/bedrock/toolCache.mjs.map +1 -1
  356. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +0 -78
  357. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  358. package/dist/esm/llm/bedrock/utils/message_outputs.mjs +0 -24
  359. package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -1
  360. package/dist/esm/llm/contextOverflowRecovery.mjs +0 -62
  361. package/dist/esm/llm/contextOverflowRecovery.mjs.map +1 -1
  362. package/dist/esm/llm/fake.mjs.map +1 -1
  363. package/dist/esm/llm/google/index.mjs +2 -21
  364. package/dist/esm/llm/google/index.mjs.map +1 -1
  365. package/dist/esm/llm/google/utils/common.mjs +5 -35
  366. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  367. package/dist/esm/llm/init.mjs +0 -9
  368. package/dist/esm/llm/init.mjs.map +1 -1
  369. package/dist/esm/llm/invoke.mjs +1 -270
  370. package/dist/esm/llm/invoke.mjs.map +1 -1
  371. package/dist/esm/llm/mistral/index.mjs.map +1 -1
  372. package/dist/esm/llm/openai/index.mjs +0 -99
  373. package/dist/esm/llm/openai/index.mjs.map +1 -1
  374. package/dist/esm/llm/openai/streamMetadata.mjs +0 -21
  375. package/dist/esm/llm/openai/streamMetadata.mjs.map +1 -1
  376. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  377. package/dist/esm/llm/openrouter/index.mjs +0 -1
  378. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  379. package/dist/esm/llm/openrouter/toolCache.mjs +0 -6
  380. package/dist/esm/llm/openrouter/toolCache.mjs.map +1 -1
  381. package/dist/esm/llm/preempt.mjs +0 -75
  382. package/dist/esm/llm/preempt.mjs.map +1 -1
  383. package/dist/esm/llm/providers.mjs.map +1 -1
  384. package/dist/esm/llm/request.mjs +0 -10
  385. package/dist/esm/llm/request.mjs.map +1 -1
  386. package/dist/esm/llm/stream/chunkAdapters.mjs +0 -62
  387. package/dist/esm/llm/stream/chunkAdapters.mjs.map +1 -1
  388. package/dist/esm/llm/stream/smoother.mjs +0 -58
  389. package/dist/esm/llm/stream/smoother.mjs.map +1 -1
  390. package/dist/esm/llm/streamLimits.mjs +4 -293
  391. package/dist/esm/llm/streamLimits.mjs.map +1 -1
  392. package/dist/esm/llm/truncation.mjs +0 -36
  393. package/dist/esm/llm/truncation.mjs.map +1 -1
  394. package/dist/esm/llm/vertexai/index.mjs +0 -330
  395. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  396. package/dist/esm/messages/alternation.mjs +0 -43
  397. package/dist/esm/messages/alternation.mjs.map +1 -1
  398. package/dist/esm/messages/anthropicToolCache.mjs +0 -45
  399. package/dist/esm/messages/anthropicToolCache.mjs.map +1 -1
  400. package/dist/esm/messages/assistantPhase.mjs +0 -12
  401. package/dist/esm/messages/assistantPhase.mjs.map +1 -1
  402. package/dist/esm/messages/budget.mjs +0 -9
  403. package/dist/esm/messages/budget.mjs.map +1 -1
  404. package/dist/esm/messages/cache.mjs +0 -172
  405. package/dist/esm/messages/cache.mjs.map +1 -1
  406. package/dist/esm/messages/content.mjs +0 -9
  407. package/dist/esm/messages/content.mjs.map +1 -1
  408. package/dist/esm/messages/contextPruning.mjs +0 -15
  409. package/dist/esm/messages/contextPruning.mjs.map +1 -1
  410. package/dist/esm/messages/contextPruningSettings.mjs +0 -3
  411. package/dist/esm/messages/contextPruningSettings.mjs.map +1 -1
  412. package/dist/esm/messages/core.mjs +0 -48
  413. package/dist/esm/messages/core.mjs.map +1 -1
  414. package/dist/esm/messages/format.mjs +1 -345
  415. package/dist/esm/messages/format.mjs.map +1 -1
  416. package/dist/esm/messages/handoffCue.mjs +0 -36
  417. package/dist/esm/messages/handoffCue.mjs.map +1 -1
  418. package/dist/esm/messages/ids.mjs.map +1 -1
  419. package/dist/esm/messages/injected.mjs +0 -33
  420. package/dist/esm/messages/injected.mjs.map +1 -1
  421. package/dist/esm/messages/langchain.mjs +0 -14
  422. package/dist/esm/messages/langchain.mjs.map +1 -1
  423. package/dist/esm/messages/prune.mjs +1 -184
  424. package/dist/esm/messages/prune.mjs.map +1 -1
  425. package/dist/esm/messages/recency.mjs +0 -32
  426. package/dist/esm/messages/recency.mjs.map +1 -1
  427. package/dist/esm/messages/reducer.mjs +0 -30
  428. package/dist/esm/messages/reducer.mjs.map +1 -1
  429. package/dist/esm/messages/tools.mjs +0 -14
  430. package/dist/esm/messages/tools.mjs.map +1 -1
  431. package/dist/esm/openai/index.mjs.map +1 -1
  432. package/dist/esm/prompts/activityLabel.mjs +9 -79
  433. package/dist/esm/prompts/activityLabel.mjs.map +1 -1
  434. package/dist/esm/responses/index.mjs.map +1 -1
  435. package/dist/esm/run.mjs +2 -538
  436. package/dist/esm/run.mjs.map +1 -1
  437. package/dist/esm/session/AgentSession.mjs +1 -17
  438. package/dist/esm/session/AgentSession.mjs.map +1 -1
  439. package/dist/esm/session/JsonlSessionStore.mjs.map +1 -1
  440. package/dist/esm/session/handlers.mjs +0 -7
  441. package/dist/esm/session/handlers.mjs.map +1 -1
  442. package/dist/esm/session/ids.mjs.map +1 -1
  443. package/dist/esm/session/messageSerialization.mjs +0 -4
  444. package/dist/esm/session/messageSerialization.mjs.map +1 -1
  445. package/dist/esm/stream.mjs +1 -93
  446. package/dist/esm/stream.mjs.map +1 -1
  447. package/dist/esm/summarization/index.mjs +0 -27
  448. package/dist/esm/summarization/index.mjs.map +1 -1
  449. package/dist/esm/summarization/node.mjs +0 -273
  450. package/dist/esm/summarization/node.mjs.map +1 -1
  451. package/dist/esm/tools/BashExecutor.mjs +0 -35
  452. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  453. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +0 -24
  454. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  455. package/dist/esm/tools/Calculator.mjs.map +1 -1
  456. package/dist/esm/tools/CodeExecutor.mjs +0 -13
  457. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  458. package/dist/esm/tools/CodeSessionFileSummary.mjs.map +1 -1
  459. package/dist/esm/tools/ProgrammaticToolCalling.mjs +0 -101
  460. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  461. package/dist/esm/tools/ReadFile.mjs.map +1 -1
  462. package/dist/esm/tools/SkillTool.mjs +0 -5
  463. package/dist/esm/tools/SkillTool.mjs.map +1 -1
  464. package/dist/esm/tools/SubagentTool.mjs +0 -10
  465. package/dist/esm/tools/SubagentTool.mjs.map +1 -1
  466. package/dist/esm/tools/ToolNode.mjs +6 -1038
  467. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  468. package/dist/esm/tools/ToolSearch.mjs +0 -179
  469. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  470. package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs.map +1 -1
  471. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs.map +1 -1
  472. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs +0 -39
  473. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs.map +1 -1
  474. package/dist/esm/tools/cloudflare/CloudflareSandboxTools.mjs.map +1 -1
  475. package/dist/esm/tools/eagerEventExecution.mjs +0 -6
  476. package/dist/esm/tools/eagerEventExecution.mjs.map +1 -1
  477. package/dist/esm/tools/handlers.mjs +1 -41
  478. package/dist/esm/tools/handlers.mjs.map +1 -1
  479. package/dist/esm/tools/intentArg.mjs +1 -132
  480. package/dist/esm/tools/intentArg.mjs.map +1 -1
  481. package/dist/esm/tools/local/CompileCheckTool.mjs +0 -25
  482. package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -1
  483. package/dist/esm/tools/local/FileCheckpointer.mjs +0 -23
  484. package/dist/esm/tools/local/FileCheckpointer.mjs.map +1 -1
  485. package/dist/esm/tools/local/LocalCodingTools.mjs +0 -80
  486. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  487. package/dist/esm/tools/local/LocalExecutionEngine.mjs +0 -126
  488. package/dist/esm/tools/local/LocalExecutionEngine.mjs.map +1 -1
  489. package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -1
  490. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +0 -12
  491. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -1
  492. package/dist/esm/tools/local/attachments.mjs +0 -44
  493. package/dist/esm/tools/local/attachments.mjs.map +1 -1
  494. package/dist/esm/tools/local/bashAst.mjs +0 -16
  495. package/dist/esm/tools/local/bashAst.mjs.map +1 -1
  496. package/dist/esm/tools/local/editStrategies.mjs +0 -14
  497. package/dist/esm/tools/local/editStrategies.mjs.map +1 -1
  498. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
  499. package/dist/esm/tools/local/syntaxCheck.mjs +0 -31
  500. package/dist/esm/tools/local/syntaxCheck.mjs.map +1 -1
  501. package/dist/esm/tools/local/textEncoding.mjs +0 -11
  502. package/dist/esm/tools/local/textEncoding.mjs.map +1 -1
  503. package/dist/esm/tools/local/workspaceFS.mjs +0 -33
  504. package/dist/esm/tools/local/workspaceFS.mjs.map +1 -1
  505. package/dist/esm/tools/ptcTimeout.mjs.map +1 -1
  506. package/dist/esm/tools/schema.mjs +0 -8
  507. package/dist/esm/tools/schema.mjs.map +1 -1
  508. package/dist/esm/tools/search/anthropic.mjs +0 -9
  509. package/dist/esm/tools/search/anthropic.mjs.map +1 -1
  510. package/dist/esm/tools/search/content.mjs.map +1 -1
  511. package/dist/esm/tools/search/crw-scraper.mjs +0 -33
  512. package/dist/esm/tools/search/crw-scraper.mjs.map +1 -1
  513. package/dist/esm/tools/search/crw-search.mjs +0 -2
  514. package/dist/esm/tools/search/crw-search.mjs.map +1 -1
  515. package/dist/esm/tools/search/firecrawl.mjs +0 -25
  516. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  517. package/dist/esm/tools/search/format.mjs +0 -30
  518. package/dist/esm/tools/search/format.mjs.map +1 -1
  519. package/dist/esm/tools/search/highlights.mjs +0 -16
  520. package/dist/esm/tools/search/highlights.mjs.map +1 -1
  521. package/dist/esm/tools/search/keenable-scraper.mjs +0 -8
  522. package/dist/esm/tools/search/keenable-scraper.mjs.map +1 -1
  523. package/dist/esm/tools/search/keenable-search.mjs +0 -7
  524. package/dist/esm/tools/search/keenable-search.mjs.map +1 -1
  525. package/dist/esm/tools/search/rerankers.mjs +0 -35
  526. package/dist/esm/tools/search/rerankers.mjs.map +1 -1
  527. package/dist/esm/tools/search/schema.mjs +0 -1
  528. package/dist/esm/tools/search/schema.mjs.map +1 -1
  529. package/dist/esm/tools/search/search.mjs +1 -14
  530. package/dist/esm/tools/search/search.mjs.map +1 -1
  531. package/dist/esm/tools/search/serper-scraper.mjs +0 -46
  532. package/dist/esm/tools/search/serper-scraper.mjs.map +1 -1
  533. package/dist/esm/tools/search/tavily-scraper.mjs.map +1 -1
  534. package/dist/esm/tools/search/tavily-search.mjs.map +1 -1
  535. package/dist/esm/tools/search/tool.mjs +0 -25
  536. package/dist/esm/tools/search/tool.mjs.map +1 -1
  537. package/dist/esm/tools/search/utils.mjs +0 -8
  538. package/dist/esm/tools/search/utils.mjs.map +1 -1
  539. package/dist/esm/tools/skillCatalog.mjs +0 -6
  540. package/dist/esm/tools/skillCatalog.mjs.map +1 -1
  541. package/dist/esm/tools/streamedToolCallSeals.mjs +0 -6
  542. package/dist/esm/tools/streamedToolCallSeals.mjs.map +1 -1
  543. package/dist/esm/tools/subagent/SubagentExecutionRegistry.mjs +0 -2
  544. package/dist/esm/tools/subagent/SubagentExecutionRegistry.mjs.map +1 -1
  545. package/dist/esm/tools/subagent/SubagentExecutor.mjs +3 -213
  546. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  547. package/dist/esm/tools/subagent/SubagentReplay.mjs.map +1 -1
  548. package/dist/esm/tools/subagent/childGraphConfig.mjs +0 -4
  549. package/dist/esm/tools/subagent/childGraphConfig.mjs.map +1 -1
  550. package/dist/esm/tools/subagent/runtimeLimits.mjs.map +1 -1
  551. package/dist/esm/tools/toolOutputReferences.mjs +1 -322
  552. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  553. package/dist/esm/types/hitl.mjs +0 -5
  554. package/dist/esm/types/hitl.mjs.map +1 -1
  555. package/dist/esm/utils/callbacks.mjs.map +1 -1
  556. package/dist/esm/utils/errors.mjs +14 -165
  557. package/dist/esm/utils/errors.mjs.map +1 -1
  558. package/dist/esm/utils/events.mjs +0 -10
  559. package/dist/esm/utils/events.mjs.map +1 -1
  560. package/dist/esm/utils/graph.mjs.map +1 -1
  561. package/dist/esm/utils/handlers.mjs +0 -3
  562. package/dist/esm/utils/handlers.mjs.map +1 -1
  563. package/dist/esm/utils/llm.mjs +0 -1
  564. package/dist/esm/utils/llm.mjs.map +1 -1
  565. package/dist/esm/utils/misc.mjs +0 -16
  566. package/dist/esm/utils/misc.mjs.map +1 -1
  567. package/dist/esm/utils/proxy.mjs +0 -26
  568. package/dist/esm/utils/proxy.mjs.map +1 -1
  569. package/dist/esm/utils/run.mjs +0 -6
  570. package/dist/esm/utils/run.mjs.map +1 -1
  571. package/dist/esm/utils/schema.mjs +0 -5
  572. package/dist/esm/utils/schema.mjs.map +1 -1
  573. package/dist/esm/utils/title.mjs +0 -6
  574. package/dist/esm/utils/title.mjs.map +1 -1
  575. package/dist/esm/utils/tokens.mjs +0 -113
  576. package/dist/esm/utils/tokens.mjs.map +1 -1
  577. package/dist/esm/utils/toolContent.mjs +0 -41
  578. package/dist/esm/utils/toolContent.mjs.map +1 -1
  579. package/dist/esm/utils/truncation.mjs +0 -61
  580. package/dist/esm/utils/truncation.mjs.map +1 -1
  581. package/dist/types/agents/AgentContext.d.ts +3 -3
  582. package/dist/types/agents/__tests__/promptCacheLiveHelpers.d.ts +3 -3
  583. package/dist/types/agents/projection.d.ts +1 -1
  584. package/dist/types/events.d.ts +2 -2
  585. package/dist/types/graphs/Graph.d.ts +11 -11
  586. package/dist/types/graphs/MultiAgentGraph.d.ts +2 -2
  587. package/dist/types/graphs/createGraph.d.ts +4 -4
  588. package/dist/types/graphs/graphFactory.d.ts +1 -1
  589. package/dist/types/hitl/askUserQuestion.d.ts +1 -1
  590. package/dist/types/hitl/askUserQuestions.d.ts +1 -1
  591. package/dist/types/hitl/askUserQuestionsInterrupt.d.ts +1 -1
  592. package/dist/types/hooks/types.d.ts +1 -1
  593. package/dist/types/instrumentation.d.ts +1 -1
  594. package/dist/types/langfuse.d.ts +3 -3
  595. package/dist/types/langfuseConfig.d.ts +2 -2
  596. package/dist/types/langfuseRuntimeContext.d.ts +1 -1
  597. package/dist/types/langfuseRuntimeScope.d.ts +2 -2
  598. package/dist/types/langfuseSpanRegistry.d.ts +1 -1
  599. package/dist/types/langfuseToolOutputTracing.d.ts +3 -3
  600. package/dist/types/llm/anthropic/index.d.ts +1 -1
  601. package/dist/types/llm/bedrock/index.d.ts +1 -1
  602. package/dist/types/llm/bedrock/toolCache.d.ts +2 -2
  603. package/dist/types/llm/contextOverflowRecovery.d.ts +2 -2
  604. package/dist/types/llm/google/index.d.ts +1 -1
  605. package/dist/types/llm/init.d.ts +2 -2
  606. package/dist/types/llm/invoke.d.ts +6 -6
  607. package/dist/types/llm/mistral/index.d.ts +1 -1
  608. package/dist/types/llm/openai/index.d.ts +2 -2
  609. package/dist/types/llm/openrouter/index.d.ts +2 -2
  610. package/dist/types/llm/openrouter/toolCache.d.ts +2 -2
  611. package/dist/types/llm/providers.d.ts +2 -2
  612. package/dist/types/llm/request.d.ts +2 -2
  613. package/dist/types/llm/stream/chunkAdapters.d.ts +1 -1
  614. package/dist/types/llm/streamLimits.d.ts +1 -1
  615. package/dist/types/llm/truncation.d.ts +1 -1
  616. package/dist/types/llm/vertexai/index.d.ts +1 -1
  617. package/dist/types/messages/alternation.d.ts +1 -1
  618. package/dist/types/messages/anthropicToolCache.d.ts +2 -2
  619. package/dist/types/messages/assistantPhase.d.ts +3 -3
  620. package/dist/types/messages/budget.d.ts +1 -1
  621. package/dist/types/messages/cache.d.ts +1 -1
  622. package/dist/types/messages/contextPruning.d.ts +2 -2
  623. package/dist/types/messages/core.d.ts +2 -2
  624. package/dist/types/messages/format.d.ts +2 -2
  625. package/dist/types/messages/ids.d.ts +2 -2
  626. package/dist/types/messages/injected.d.ts +1 -1
  627. package/dist/types/messages/langchain.d.ts +1 -1
  628. package/dist/types/messages/prune.d.ts +3 -3
  629. package/dist/types/openai/index.d.ts +1 -1
  630. package/dist/types/prompts/activityLabel.d.ts +2 -2
  631. package/dist/types/responses/index.d.ts +1 -1
  632. package/dist/types/run.d.ts +3 -3
  633. package/dist/types/session/handlers.d.ts +1 -1
  634. package/dist/types/session/types.d.ts +1 -1
  635. package/dist/types/stream.d.ts +4 -4
  636. package/dist/types/summarization/index.d.ts +1 -1
  637. package/dist/types/summarization/node.d.ts +6 -6
  638. package/dist/types/test/mockTools.d.ts +1 -1
  639. package/dist/types/tools/BashExecutor.d.ts +2 -2
  640. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +2 -2
  641. package/dist/types/tools/CodeExecutor.d.ts +3 -3
  642. package/dist/types/tools/CodeSessionFileSummary.d.ts +1 -1
  643. package/dist/types/tools/ProgrammaticToolCalling.d.ts +2 -2
  644. package/dist/types/tools/ReadFile.d.ts +1 -1
  645. package/dist/types/tools/SkillTool.d.ts +1 -1
  646. package/dist/types/tools/SubagentTool.d.ts +3 -3
  647. package/dist/types/tools/ToolNode.d.ts +5 -5
  648. package/dist/types/tools/ToolSearch.d.ts +2 -2
  649. package/dist/types/tools/cloudflare/CloudflareBridgeRuntime.d.ts +1 -1
  650. package/dist/types/tools/cloudflare/CloudflareProgrammaticToolCalling.d.ts +1 -1
  651. package/dist/types/tools/cloudflare/CloudflareSandboxExecutionEngine.d.ts +2 -2
  652. package/dist/types/tools/cloudflare/CloudflareSandboxTools.d.ts +1 -1
  653. package/dist/types/tools/eagerEventExecution.d.ts +1 -1
  654. package/dist/types/tools/handlers.d.ts +3 -3
  655. package/dist/types/tools/intentArg.d.ts +1 -1
  656. package/dist/types/tools/local/CompileCheckTool.d.ts +2 -2
  657. package/dist/types/tools/local/FileCheckpointer.d.ts +1 -1
  658. package/dist/types/tools/local/LocalCodingTools.d.ts +2 -2
  659. package/dist/types/tools/local/LocalExecutionEngine.d.ts +1 -1
  660. package/dist/types/tools/local/LocalExecutionTools.d.ts +1 -1
  661. package/dist/types/tools/local/LocalProgrammaticToolCalling.d.ts +1 -1
  662. package/dist/types/tools/local/bashAst.d.ts +1 -1
  663. package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +1 -1
  664. package/dist/types/tools/local/syntaxCheck.d.ts +1 -1
  665. package/dist/types/tools/ptcTimeout.d.ts +1 -1
  666. package/dist/types/tools/schema.d.ts +1 -1
  667. package/dist/types/tools/search/anthropic.d.ts +1 -1
  668. package/dist/types/tools/skillCatalog.d.ts +1 -1
  669. package/dist/types/tools/subagent/SubagentExecutor.d.ts +5 -5
  670. package/dist/types/tools/subagent/SubagentReplay.d.ts +3 -3
  671. package/dist/types/tools/subagent/childGraphConfig.d.ts +2 -2
  672. package/dist/types/types/activityLabel.d.ts +3 -3
  673. package/dist/types/types/graph.d.ts +7 -7
  674. package/dist/types/types/llm.d.ts +9 -9
  675. package/dist/types/types/run.d.ts +7 -7
  676. package/dist/types/types/stream.d.ts +5 -5
  677. package/dist/types/types/summarize.d.ts +2 -2
  678. package/dist/types/types/tools.d.ts +5 -5
  679. package/dist/types/utils/__tests__/fixtures/contextOverflowSignatures.d.ts +1 -1
  680. package/dist/types/utils/errors.d.ts +1 -1
  681. package/dist/types/utils/events.d.ts +1 -1
  682. package/dist/types/utils/handlers.d.ts +3 -3
  683. package/dist/types/utils/llm.d.ts +1 -1
  684. package/dist/types/utils/llmConfig.d.ts +1 -1
  685. package/dist/types/utils/title.d.ts +1 -1
  686. package/package.json +10 -3
  687. package/src/llm/google/utils/common.ts +6 -4
  688. package/src/__tests__/stream.eagerArgsDivergence.test.ts +0 -911
  689. package/src/__tests__/stream.eagerEventExecution.test.ts +0 -5046
  690. package/src/__tests__/stream.streamLimits.test.ts +0 -1982
  691. package/src/agents/__tests__/AgentContext.anthropic.live.test.ts +0 -448
  692. package/src/agents/__tests__/AgentContext.bedrock.live.test.ts +0 -655
  693. package/src/agents/__tests__/AgentContext.openrouter.live.test.ts +0 -128
  694. package/src/agents/__tests__/AgentContext.overflow.test.ts +0 -205
  695. package/src/agents/__tests__/AgentContext.test.ts +0 -2425
  696. package/src/agents/__tests__/projection.test.ts +0 -73
  697. package/src/agents/__tests__/promptCacheLiveHelpers.ts +0 -175
  698. package/src/aggregator.test.ts +0 -1214
  699. package/src/graphs/__tests__/Graph.breakerLifecycle.test.ts +0 -273
  700. package/src/graphs/__tests__/Graph.closeRunStep.test.ts +0 -385
  701. package/src/graphs/__tests__/Graph.contextOverflow.test.ts +0 -1766
  702. package/src/graphs/__tests__/Graph.preemptSignal.test.ts +0 -126
  703. package/src/graphs/__tests__/Graph.reasoning.test.ts +0 -1717
  704. package/src/graphs/__tests__/Graph.subagentResumeState.test.ts +0 -80
  705. package/src/graphs/__tests__/MultiAgentGraph.test.ts +0 -177
  706. package/src/graphs/__tests__/composition.smoke.test.ts +0 -509
  707. package/src/graphs/__tests__/createGraph.test.ts +0 -206
  708. package/src/hooks/__tests__/HookRegistry.test.ts +0 -334
  709. package/src/hooks/__tests__/compactHooks.test.ts +0 -250
  710. package/src/hooks/__tests__/createToolPolicyHook.test.ts +0 -268
  711. package/src/hooks/__tests__/createWorkspacePolicyHook.test.ts +0 -405
  712. package/src/hooks/__tests__/executeHooks.test.ts +0 -1294
  713. package/src/hooks/__tests__/integration.test.ts +0 -337
  714. package/src/hooks/__tests__/matchers.test.ts +0 -238
  715. package/src/hooks/__tests__/preemptBoundary.test.ts +0 -152
  716. package/src/hooks/__tests__/toolHooks.test.ts +0 -669
  717. package/src/llm/__tests__/contextOverflowRecovery.test.ts +0 -401
  718. package/src/llm/__tests__/fallbackOverflow.test.ts +0 -287
  719. package/src/llm/anthropic/Jacob_Lee_Resume_2023.pdf +0 -0
  720. package/src/llm/anthropic/inherited-content-utils.spec.ts +0 -249
  721. package/src/llm/anthropic/inherited-stream-events.spec.ts +0 -1259
  722. package/src/llm/anthropic/inherited-strict.spec.ts +0 -302
  723. package/src/llm/anthropic/llm.spec.ts +0 -3394
  724. package/src/llm/anthropic/utils/cross-provider-reasoning.test.ts +0 -383
  725. package/src/llm/anthropic/utils/cross-provider-server-tools.test.ts +0 -110
  726. package/src/llm/anthropic/utils/server-tool-inputs.test.ts +0 -508
  727. package/src/llm/anthropic/utils/streaming-tool-input.test.ts +0 -361
  728. package/src/llm/anthropic/utils/stripPrefillCache.test.ts +0 -111
  729. package/src/llm/anthropic/utils/tool-id-normalization.test.ts +0 -287
  730. package/src/llm/bedrock/inherited-cache.spec.ts +0 -144
  731. package/src/llm/bedrock/inherited.spec.ts +0 -724
  732. package/src/llm/bedrock/llm.spec.ts +0 -1533
  733. package/src/llm/bedrock/streamSealDispatch.test.ts +0 -331
  734. package/src/llm/bedrock/toolCache.test.ts +0 -194
  735. package/src/llm/bedrock/utils/cross-provider-reasoning.test.ts +0 -131
  736. package/src/llm/bedrock/utils/cross-provider-server-tools.test.ts +0 -122
  737. package/src/llm/bedrock/utils/message_inputs.test.ts +0 -650
  738. package/src/llm/bedrock/utils/message_outputs.test.ts +0 -85
  739. package/src/llm/bedrock/utils/toolResultCachePoint.test.ts +0 -118
  740. package/src/llm/custom-chat-models.smoke.test.ts +0 -1966
  741. package/src/llm/google/data/gettysburg10.wav +0 -0
  742. package/src/llm/google/data/hotdog.jpg +0 -0
  743. package/src/llm/google/inherited-stream-events.spec.ts +0 -350
  744. package/src/llm/google/llm.spec.ts +0 -1388
  745. package/src/llm/google/streamSmoothing.test.ts +0 -121
  746. package/src/llm/google/utils/common.test.ts +0 -185
  747. package/src/llm/invoke.alternation.test.ts +0 -87
  748. package/src/llm/invoke.handoffCue.test.ts +0 -112
  749. package/src/llm/invoke.streamLimits.test.ts +0 -142
  750. package/src/llm/invoke.test.ts +0 -1198
  751. package/src/llm/mistral/streamSmoothing.test.ts +0 -97
  752. package/src/llm/openai/cacheWriteTokens.test.ts +0 -112
  753. package/src/llm/openai/contentBlocks.test.ts +0 -381
  754. package/src/llm/openai/deepseek.test.ts +0 -747
  755. package/src/llm/openai/inherited-deepseek.spec.ts +0 -347
  756. package/src/llm/openai/inherited-xai.spec.ts +0 -416
  757. package/src/llm/openai/llm.spec.ts +0 -1774
  758. package/src/llm/openai/managedRequests.test.ts +0 -182
  759. package/src/llm/openai/sequentialToolCallSeals.test.ts +0 -199
  760. package/src/llm/openai/streamMetadata.spec.ts +0 -86
  761. package/src/llm/openai/streamMetadataDedup.spec.ts +0 -166
  762. package/src/llm/openai/utils/isReasoningModel.test.ts +0 -90
  763. package/src/llm/openai/utils/messages.test.ts +0 -488
  764. package/src/llm/openrouter/reasoning.test.ts +0 -561
  765. package/src/llm/openrouter/toolCache.test.ts +0 -134
  766. package/src/llm/preempt.test.ts +0 -323
  767. package/src/llm/stream/chunkAdapters.test.ts +0 -202
  768. package/src/llm/stream/reassembly.test.ts +0 -241
  769. package/src/llm/stream/smoother.bench.test.ts +0 -155
  770. package/src/llm/stream/smoother.test.ts +0 -519
  771. package/src/llm/streamLimits.test.ts +0 -450
  772. package/src/llm/truncation.test.ts +0 -242
  773. package/src/llm/vertexai/fixThoughtSignatures.test.ts +0 -154
  774. package/src/llm/vertexai/inherited-stream-events.spec.ts +0 -271
  775. package/src/llm/vertexai/llm.spec.ts +0 -159
  776. package/src/llm/vertexai/repairUsageMetadata.test.ts +0 -54
  777. package/src/llm/vertexai/sealStreamedToolCalls.test.ts +0 -88
  778. package/src/llm/vertexai/streamSealDispatch.test.ts +0 -148
  779. package/src/llm/vertexai/streamSmoothing.test.ts +0 -109
  780. package/src/messages/__tests__/anthropicToolCache.test.ts +0 -339
  781. package/src/messages/__tests__/observationMasking.test.ts +0 -312
  782. package/src/messages/__tests__/recency.test.ts +0 -267
  783. package/src/messages/__tests__/tools.test.ts +0 -473
  784. package/src/messages/alternation.test.ts +0 -212
  785. package/src/messages/assistantPhase.test.ts +0 -75
  786. package/src/messages/cache.tail.test.ts +0 -533
  787. package/src/messages/cache.test.ts +0 -2166
  788. package/src/messages/content.test.ts +0 -362
  789. package/src/messages/contextPruning.test.ts +0 -184
  790. package/src/messages/ensureThinkingBlock.test.ts +0 -1427
  791. package/src/messages/foldToollessToolBlocks.test.ts +0 -596
  792. package/src/messages/formatAgentMessages.reducer.test.ts +0 -162
  793. package/src/messages/formatAgentMessages.skills.test.ts +0 -513
  794. package/src/messages/formatAgentMessages.steer.test.ts +0 -598
  795. package/src/messages/formatAgentMessages.test.ts +0 -8111
  796. package/src/messages/formatAgentMessages.tools.test.ts +0 -522
  797. package/src/messages/formatMessage.test.ts +0 -693
  798. package/src/messages/handoffCue.test.ts +0 -96
  799. package/src/messages/injected.test.ts +0 -107
  800. package/src/messages/labelContentByAgent.test.ts +0 -962
  801. package/src/messages/reducer.spec.ts +0 -32
  802. package/src/messages/shiftIndexTokenCountMap.test.ts +0 -81
  803. package/src/messages/tailCacheConversion.test.ts +0 -161
  804. package/src/openai/__tests__/openai.test.ts +0 -337
  805. package/src/responses/__tests__/responses.test.ts +0 -652
  806. package/src/scripts/abort.ts +0 -157
  807. package/src/scripts/activity-labels/captured.json +0 -56
  808. package/src/scripts/activity-labels/checks.cjs +0 -205
  809. package/src/scripts/activity-labels/corpus.cjs +0 -473
  810. package/src/scripts/activity-labels/report.cjs +0 -203
  811. package/src/scripts/activity-labels/rescore.cjs +0 -102
  812. package/src/scripts/activity-labels/run.ts +0 -705
  813. package/src/scripts/activity-labels/variants.ts +0 -71
  814. package/src/scripts/ant_web_search.ts +0 -159
  815. package/src/scripts/ant_web_search_edge_case.ts +0 -163
  816. package/src/scripts/ant_web_search_error_edge_case.ts +0 -149
  817. package/src/scripts/args.ts +0 -48
  818. package/src/scripts/bedrock-cache-debug.ts +0 -250
  819. package/src/scripts/bedrock-content-aggregation-test.ts +0 -266
  820. package/src/scripts/bedrock-merge-test.ts +0 -107
  821. package/src/scripts/bedrock-parallel-tools-test.ts +0 -204
  822. package/src/scripts/bench-prompt-cache.ts +0 -479
  823. package/src/scripts/caching.ts +0 -132
  824. package/src/scripts/cli.ts +0 -172
  825. package/src/scripts/cli2.ts +0 -133
  826. package/src/scripts/cli3.ts +0 -184
  827. package/src/scripts/cli4.ts +0 -191
  828. package/src/scripts/cli5.ts +0 -191
  829. package/src/scripts/code_exec.ts +0 -214
  830. package/src/scripts/code_exec_files.ts +0 -237
  831. package/src/scripts/code_exec_multi_session.ts +0 -237
  832. package/src/scripts/code_exec_ptc.ts +0 -335
  833. package/src/scripts/code_exec_session.ts +0 -283
  834. package/src/scripts/code_exec_simple.ts +0 -148
  835. package/src/scripts/compare_pi_vs_ours.ts +0 -1259
  836. package/src/scripts/content.ts +0 -139
  837. package/src/scripts/context-overflow-probe.ts +0 -997
  838. package/src/scripts/empty_input.ts +0 -137
  839. package/src/scripts/handoff-test.ts +0 -134
  840. package/src/scripts/local_engine.ts +0 -166
  841. package/src/scripts/local_engine_checkpointer.ts +0 -205
  842. package/src/scripts/local_engine_compile.ts +0 -263
  843. package/src/scripts/local_engine_hooks.ts +0 -226
  844. package/src/scripts/local_engine_image.ts +0 -201
  845. package/src/scripts/local_engine_ptc.ts +0 -151
  846. package/src/scripts/local_engine_workspace.ts +0 -258
  847. package/src/scripts/memory.ts +0 -107
  848. package/src/scripts/multi-agent-chain.ts +0 -332
  849. package/src/scripts/multi-agent-conditional.ts +0 -222
  850. package/src/scripts/multi-agent-document-review-chain.ts +0 -198
  851. package/src/scripts/multi-agent-hybrid-flow.ts +0 -311
  852. package/src/scripts/multi-agent-parallel-start.ts +0 -265
  853. package/src/scripts/multi-agent-parallel.ts +0 -395
  854. package/src/scripts/multi-agent-sequence.ts +0 -217
  855. package/src/scripts/multi-agent-subagent.ts +0 -246
  856. package/src/scripts/multi-agent-supervisor.ts +0 -366
  857. package/src/scripts/multi-agent-test.ts +0 -187
  858. package/src/scripts/openrouter_prompt_cache_live.ts +0 -310
  859. package/src/scripts/parallel-asymmetric-tools-test.ts +0 -275
  860. package/src/scripts/parallel-full-metadata-test.ts +0 -241
  861. package/src/scripts/parallel-tools-test.ts +0 -341
  862. package/src/scripts/preempt-probe.ts +0 -330
  863. package/src/scripts/preempt-scenarios.ts +0 -388
  864. package/src/scripts/programmatic_exec.ts +0 -387
  865. package/src/scripts/programmatic_exec_agent.ts +0 -232
  866. package/src/scripts/search.ts +0 -147
  867. package/src/scripts/sequential-full-metadata-test.ts +0 -198
  868. package/src/scripts/session_live.ts +0 -548
  869. package/src/scripts/simple.ts +0 -226
  870. package/src/scripts/single-agent-metadata-test.ts +0 -196
  871. package/src/scripts/stream.ts +0 -141
  872. package/src/scripts/subagent-configurable-inheritance.ts +0 -252
  873. package/src/scripts/subagent-event-driven-debug.ts +0 -190
  874. package/src/scripts/subagent-tools-debug.ts +0 -160
  875. package/src/scripts/subagent-usage-sink.ts +0 -176
  876. package/src/scripts/summarization-recency.ts +0 -462
  877. package/src/scripts/test-custom-prompt-key.ts +0 -145
  878. package/src/scripts/test-handoff-input.ts +0 -170
  879. package/src/scripts/test-handoff-preamble.ts +0 -278
  880. package/src/scripts/test-handoff-steering.ts +0 -430
  881. package/src/scripts/test-multi-agent-list-handoff.ts +0 -418
  882. package/src/scripts/test-parallel-agent-labeling.ts +0 -327
  883. package/src/scripts/test-parallel-handoffs.ts +0 -292
  884. package/src/scripts/test-thinking-handoff-bedrock.ts +0 -154
  885. package/src/scripts/test-thinking-handoff.ts +0 -156
  886. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.ts +0 -166
  887. package/src/scripts/test-tool-before-handoff-role-order.ts +0 -276
  888. package/src/scripts/test-tools-before-handoff.ts +0 -222
  889. package/src/scripts/test_code_api.ts +0 -354
  890. package/src/scripts/thinking-bedrock.ts +0 -160
  891. package/src/scripts/thinking-vertexai.ts +0 -168
  892. package/src/scripts/thinking.ts +0 -172
  893. package/src/scripts/tool_search.ts +0 -153
  894. package/src/scripts/tools.ts +0 -163
  895. package/src/session/__tests__/JsonlSessionStore.test.ts +0 -1463
  896. package/src/session/__tests__/handlers.test.ts +0 -161
  897. package/src/specs/activity-label-observability.live.test.ts +0 -262
  898. package/src/specs/activity-label-observability.test.ts +0 -167
  899. package/src/specs/activity-label-prompt.test.ts +0 -359
  900. package/src/specs/activity-label-trace-seed.test.ts +0 -47
  901. package/src/specs/activity-phase-label.test.ts +0 -306
  902. package/src/specs/agent-handoffs.live.test.ts +0 -140
  903. package/src/specs/agent-handoffs.test.ts +0 -2465
  904. package/src/specs/anthropic.simple.test.ts +0 -453
  905. package/src/specs/ask-user-question-batch.test.ts +0 -289
  906. package/src/specs/ask-user-questions.live.test.ts +0 -185
  907. package/src/specs/ask-user-questions.test.ts +0 -293
  908. package/src/specs/azure.simple.test.ts +0 -502
  909. package/src/specs/bedrock-toolless.live.test.ts +0 -123
  910. package/src/specs/bedrock-truncation.live.test.ts +0 -191
  911. package/src/specs/cache.simple.test.ts +0 -416
  912. package/src/specs/context-accuracy.live.test.ts +0 -409
  913. package/src/specs/context-overflow-recovery.live.test.ts +0 -213
  914. package/src/specs/context-usage-event.test.ts +0 -117
  915. package/src/specs/context-usage.live.test.ts +0 -297
  916. package/src/specs/custom-event-await.test.ts +0 -304
  917. package/src/specs/deepseek.simple.test.ts +0 -290
  918. package/src/specs/deterministic-trace-id.test.ts +0 -43
  919. package/src/specs/discovered-tools.test.ts +0 -217
  920. package/src/specs/durability-checkpoint.integration.test.ts +0 -243
  921. package/src/specs/graph-subagent.live.test.ts +0 -242
  922. package/src/specs/graph-subagent.test.ts +0 -322
  923. package/src/specs/handoffCue.test.ts +0 -165
  924. package/src/specs/langfuse-callbacks.test.ts +0 -1578
  925. package/src/specs/langfuse-config.test.ts +0 -247
  926. package/src/specs/langfuse-instrumentation.test.ts +0 -393
  927. package/src/specs/langfuse-metadata.test.ts +0 -245
  928. package/src/specs/langfuse-routing.integration.test.ts +0 -844
  929. package/src/specs/langfuse-runtime-context.test.ts +0 -92
  930. package/src/specs/langfuse-span-registry.test.ts +0 -87
  931. package/src/specs/langfuse-tool-output-tracing.test.ts +0 -1858
  932. package/src/specs/langfuse-trace-shaping.test.ts +0 -591
  933. package/src/specs/moonshot.simple.test.ts +0 -367
  934. package/src/specs/multi-agent-summarization.test.ts +0 -396
  935. package/src/specs/openai.simple.test.ts +0 -315
  936. package/src/specs/openrouter.simple.test.ts +0 -275
  937. package/src/specs/preemptSeal.test.ts +0 -678
  938. package/src/specs/prune.test.ts +0 -3741
  939. package/src/specs/reasoning.test.ts +0 -201
  940. package/src/specs/run-step-timestamps.test.ts +0 -414
  941. package/src/specs/spec.utils.ts +0 -15
  942. package/src/specs/subagent.test.ts +0 -864
  943. package/src/specs/summarization-unit.test.ts +0 -973
  944. package/src/specs/summarization.test.ts +0 -3823
  945. package/src/specs/summarize-prune.test.ts +0 -376
  946. package/src/specs/thinking-handoff.test.ts +0 -621
  947. package/src/specs/thinking-prune.test.ts +0 -827
  948. package/src/specs/token-accounting-e2e.test.ts +0 -1034
  949. package/src/specs/token-accounting-pipeline.test.ts +0 -1008
  950. package/src/specs/token-distribution-edge-case.test.ts +0 -315
  951. package/src/specs/token-memoization.test.ts +0 -40
  952. package/src/specs/tokens.test.ts +0 -1000
  953. package/src/specs/tool-error-resume.test.ts +0 -194
  954. package/src/specs/tool-error.test.ts +0 -198
  955. package/src/specs/vllm-reasoning-toolcalls.test.ts +0 -340
  956. package/src/stream.dispatch.test.ts +0 -63
  957. package/src/stream.test.ts +0 -144
  958. package/src/summarization/__tests__/aggregator.test.ts +0 -236
  959. package/src/summarization/__tests__/node.test.ts +0 -1996
  960. package/src/summarization/__tests__/trigger.test.ts +0 -149
  961. package/src/summarization/chunkHandler.test.ts +0 -196
  962. package/src/test/mockTools.ts +0 -386
  963. package/src/tools/Calculator.test.ts +0 -278
  964. package/src/tools/__tests__/BashExecutor.test.ts +0 -108
  965. package/src/tools/__tests__/CloudflareSandboxExecution.test.ts +0 -939
  966. package/src/tools/__tests__/CodeApiAuthHeaders.test.ts +0 -858
  967. package/src/tools/__tests__/CodeExecutor.stateful.test.ts +0 -124
  968. package/src/tools/__tests__/LocalExecutionRoots.test.ts +0 -8
  969. package/src/tools/__tests__/LocalExecutionTools.test.ts +0 -2733
  970. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +0 -318
  971. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -1557
  972. package/src/tools/__tests__/ReadFile.test.ts +0 -44
  973. package/src/tools/__tests__/SkillTool.test.ts +0 -442
  974. package/src/tools/__tests__/SubagentExecutor.test.ts +0 -3728
  975. package/src/tools/__tests__/SubagentReplay.test.ts +0 -329
  976. package/src/tools/__tests__/SubagentTool.test.ts +0 -149
  977. package/src/tools/__tests__/ToolNode.breakerSignal.test.ts +0 -595
  978. package/src/tools/__tests__/ToolNode.eagerEventExecution.test.ts +0 -1191
  979. package/src/tools/__tests__/ToolNode.invalidToolCalls.test.ts +0 -757
  980. package/src/tools/__tests__/ToolNode.langfuse.test.ts +0 -57
  981. package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +0 -736
  982. package/src/tools/__tests__/ToolNode.outputReferences.test.ts +0 -1710
  983. package/src/tools/__tests__/ToolNode.runtimeState.test.ts +0 -120
  984. package/src/tools/__tests__/ToolNode.session.test.ts +0 -1352
  985. package/src/tools/__tests__/ToolNode.streamLimits.test.ts +0 -69
  986. package/src/tools/__tests__/ToolSearch.integration.test.ts +0 -161
  987. package/src/tools/__tests__/ToolSearch.test.ts +0 -1227
  988. package/src/tools/__tests__/annotateMessagesForLLM.test.ts +0 -561
  989. package/src/tools/__tests__/directToolHITLResumeScope.test.ts +0 -980
  990. package/src/tools/__tests__/directToolHooks.test.ts +0 -700
  991. package/src/tools/__tests__/eagerEventExecution.session.test.ts +0 -92
  992. package/src/tools/__tests__/handlers.test.ts +0 -997
  993. package/src/tools/__tests__/hitl.test.ts +0 -4663
  994. package/src/tools/__tests__/intentArg.test.ts +0 -357
  995. package/src/tools/__tests__/intentCoverage.test.ts +0 -139
  996. package/src/tools/__tests__/localToolNames.test.ts +0 -75
  997. package/src/tools/__tests__/skillCatalog.test.ts +0 -161
  998. package/src/tools/__tests__/subagentHooks.test.ts +0 -1651
  999. package/src/tools/__tests__/toolOutputReferences.test.ts +0 -515
  1000. package/src/tools/__tests__/workspaceSeam.test.ts +0 -147
  1001. package/src/tools/local/__tests__/FileCheckpointer.test.ts +0 -162
  1002. package/src/tools/local/__tests__/editStrategies.test.ts +0 -134
  1003. package/src/tools/search/content.test.ts +0 -173
  1004. package/src/tools/search/crw.test.ts +0 -836
  1005. package/src/tools/search/format.test.ts +0 -242
  1006. package/src/tools/search/http-agent.test.ts +0 -133
  1007. package/src/tools/search/jina-reranker.test.ts +0 -306
  1008. package/src/tools/search/keenable-scraper.test.ts +0 -153
  1009. package/src/tools/search/keenable.test.ts +0 -183
  1010. package/src/tools/search/outcome.test.ts +0 -90
  1011. package/src/tools/search/output.md +0 -2775
  1012. package/src/tools/search/rag-api-reranker.test.ts +0 -891
  1013. package/src/tools/search/source-processing.test.ts +0 -516
  1014. package/src/tools/search/tavily.test.ts +0 -965
  1015. package/src/tools/search/test.html +0 -884
  1016. package/src/tools/search/test.md +0 -643
  1017. package/src/tools/subagent/__tests__/SubagentExecutionRegistry.test.ts +0 -637
  1018. package/src/tools/subagent/__tests__/SubagentExecutor.lazy.test.ts +0 -3054
  1019. package/src/tools/subagent/__tests__/childGraphConfig.test.ts +0 -521
  1020. package/src/utils/__tests__/apportion.test.ts +0 -32
  1021. package/src/utils/__tests__/errors.test.ts +0 -270
  1022. package/src/utils/__tests__/fixtures/contextOverflowSignatures.ts +0 -336
  1023. package/src/utils/__tests__/redactSecrets.test.ts +0 -56
  1024. package/src/utils/__tests__/truncation.test.ts +0 -66
  1025. package/src/utils/llm.test.ts +0 -18
  1026. package/src/utils/proxy.test.ts +0 -176
  1027. package/src/utils/toolContent.test.ts +0 -1432
@@ -1,3728 +0,0 @@
1
- import { describe, it, expect, beforeEach } from '@jest/globals';
2
- import { GraphInterrupt, MemorySaver } from '@langchain/langgraph';
3
- import { AIMessage, HumanMessage, ToolMessage } from '@langchain/core/messages';
4
- import type { BaseMessage } from '@langchain/core/messages';
5
- import type {
6
- AgentInputs,
7
- GraphSubagentConfig,
8
- ResolvedSubagentConfig,
9
- ResolvedSingleAgentSubagentConfig,
10
- StandardGraphInput,
11
- SubagentUpdateEvent,
12
- SubagentUsageEvent,
13
- ToolSessionMap,
14
- ToolExecuteBatchRequest,
15
- ToolExecuteResult,
16
- } from '@/types';
17
- import type { StandardGraph } from '@/graphs/Graph';
18
- import {
19
- SubagentExecutor,
20
- filterGraphSubagentResult,
21
- filterSubagentResult,
22
- resolveSubagentConfigs,
23
- buildChildInputs,
24
- summarizeEvent,
25
- } from '../subagent';
26
- import { sanitizeForwardedSubagentUpdateData } from '../subagent/SubagentExecutor';
27
- import { SUBAGENT_PARENT_BATCH_CONFIG_KEY } from '../subagent/SubagentReplay';
28
- import { Constants, Providers, GraphEvents, StepTypes } from '@/common';
29
- import { StreamLimitExceededError } from '@/llm/streamLimits';
30
- import { AgentContext } from '@/agents/AgentContext';
31
- import { HookRegistry } from '@/hooks/HookRegistry';
32
- import { HandlerRegistry } from '@/events';
33
-
34
- jest.setTimeout(15000);
35
-
36
- const makeChildInputs = (agentId = 'child-agent'): AgentInputs => ({
37
- agentId,
38
- provider: Providers.OPENAI,
39
- clientOptions: { modelName: 'gpt-4o-mini', apiKey: 'test-key' },
40
- instructions: 'You are a helper agent.',
41
- maxContextTokens: 8000,
42
- });
43
-
44
- const makeConfig = (
45
- type = 'researcher',
46
- overrides: Partial<ResolvedSingleAgentSubagentConfig> = {}
47
- ): ResolvedSingleAgentSubagentConfig => ({
48
- type,
49
- name: 'Test Researcher',
50
- description: 'Researches things',
51
- agentInputs: makeChildInputs(),
52
- ...overrides,
53
- });
54
-
55
- describe('filterSubagentResult', () => {
56
- it('treats a result member with no new AI message as textless completion', () => {
57
- expect(
58
- filterGraphSubagentResult(
59
- {
60
- messages: [new AIMessage('worker output')],
61
- subagentResult: { agentId: 'result' },
62
- },
63
- 'result'
64
- )
65
- ).toBe('Task completed');
66
- });
67
-
68
- it('extracts text from last AIMessage string content', () => {
69
- const messages: BaseMessage[] = [
70
- new HumanMessage('task'),
71
- new AIMessage('Here is the result'),
72
- ];
73
- expect(filterSubagentResult(messages)).toBe('Here is the result');
74
- });
75
-
76
- it('extracts text blocks from array content', () => {
77
- const messages: BaseMessage[] = [
78
- new AIMessage({
79
- content: [
80
- { type: 'text', text: 'First part.' },
81
- { type: 'text', text: 'Second part.' },
82
- ],
83
- }),
84
- ];
85
- expect(filterSubagentResult(messages)).toBe('First part.\nSecond part.');
86
- });
87
-
88
- it('prefers final text_delta blocks over earlier AI text', () => {
89
- const messages: BaseMessage[] = [
90
- new AIMessage({
91
- content: [
92
- { type: 'text', text: 'Let me search.' },
93
- { type: 'tool_use', id: 'call_1', name: 'search', input: {} },
94
- ],
95
- }),
96
- new ToolMessage({ content: 'result', tool_call_id: 'call_1' }),
97
- new AIMessage({
98
- content: [
99
- { type: 'text_delta', index: 0, text: 'Streamed ' },
100
- { type: 'text_delta', index: 0, text: 'result.' },
101
- ],
102
- }),
103
- ];
104
- expect(filterSubagentResult(messages)).toBe('Streamed result.');
105
- });
106
-
107
- it('keeps annotation-only text blocks within a text_delta sequence', () => {
108
- const messages: BaseMessage[] = [
109
- new AIMessage({
110
- content: [
111
- { type: 'text_delta', index: 0, text: 'Cited ' },
112
- { type: 'text', index: 0, citations: [{ url: 'source' }] },
113
- { type: 'text_delta', index: 0, text: 'answer.' },
114
- ],
115
- }),
116
- ];
117
- expect(filterSubagentResult(messages)).toBe('Cited answer.');
118
- });
119
-
120
- it('separates text_delta blocks with different indexes', () => {
121
- const messages: BaseMessage[] = [
122
- new AIMessage({
123
- content: [
124
- { type: 'text_delta', index: 0, text: 'First.' },
125
- { type: 'text_delta', index: 1, text: 'Second.' },
126
- ],
127
- }),
128
- ];
129
- expect(filterSubagentResult(messages)).toBe('First.\nSecond.');
130
- });
131
-
132
- it('strips tool_use blocks from array content', () => {
133
- const messages: BaseMessage[] = [
134
- new AIMessage({
135
- content: [
136
- { type: 'tool_use', id: 'call_1', name: 'search', input: {} },
137
- { type: 'text', text: 'Final answer.' },
138
- ],
139
- }),
140
- ];
141
- expect(filterSubagentResult(messages)).toBe('Final answer.');
142
- });
143
-
144
- it('strips thinking blocks from array content', () => {
145
- const messages: BaseMessage[] = [
146
- new AIMessage({
147
- content: [
148
- { type: 'thinking', thinking: 'Let me think...' },
149
- { type: 'text', text: 'The result.' },
150
- ],
151
- }),
152
- ];
153
- expect(filterSubagentResult(messages)).toBe('The result.');
154
- });
155
-
156
- it('returns "Task completed" when no text blocks remain', () => {
157
- const messages: BaseMessage[] = [
158
- new AIMessage({
159
- content: [
160
- { type: 'tool_use', id: 'call_1', name: 'do_thing', input: {} },
161
- ],
162
- }),
163
- ];
164
- expect(filterSubagentResult(messages)).toBe('Task completed');
165
- });
166
-
167
- it('returns "Task completed" for empty string content', () => {
168
- const messages: BaseMessage[] = [new AIMessage('')];
169
- expect(filterSubagentResult(messages)).toBe('Task completed');
170
- });
171
-
172
- it('returns "Task completed" when no messages', () => {
173
- expect(filterSubagentResult([])).toBe('Task completed');
174
- });
175
-
176
- it('returns "Task completed" when no AIMessage found', () => {
177
- const messages: BaseMessage[] = [
178
- new HumanMessage('task'),
179
- new ToolMessage({ content: 'result', tool_call_id: 'x' }),
180
- ];
181
- expect(filterSubagentResult(messages)).toBe('Task completed');
182
- });
183
-
184
- it('uses last AIMessage, not first', () => {
185
- const messages: BaseMessage[] = [
186
- new AIMessage('First response'),
187
- new ToolMessage({ content: 'tool output', tool_call_id: 'x' }),
188
- new AIMessage('Final response'),
189
- ];
190
- expect(filterSubagentResult(messages)).toBe('Final response');
191
- });
192
-
193
- it('salvages text from an earlier AIMessage when the last has only tool_use', () => {
194
- /**
195
- * Scenario: subagent hit maxTurns mid-tool-call. The last AIMessage is
196
- * pure tool_use with no text. Partial progress from an earlier turn
197
- * should still be returned instead of "Task completed".
198
- */
199
- const messages: BaseMessage[] = [
200
- new HumanMessage('task'),
201
- new AIMessage({
202
- content: [
203
- { type: 'text', text: 'Let me search.' },
204
- { type: 'tool_use', id: 'c1', name: 'search', input: {} },
205
- ],
206
- }),
207
- new ToolMessage({ content: 'Paris.', tool_call_id: 'c1' }),
208
- new AIMessage({
209
- content: [{ type: 'tool_use', id: 'c2', name: 'search', input: {} }],
210
- }),
211
- ];
212
- expect(filterSubagentResult(messages)).toBe('Let me search.');
213
- });
214
-
215
- it('salvages from earlier AIMessage when last has empty string content', () => {
216
- const messages: BaseMessage[] = [
217
- new AIMessage('Partial answer.'),
218
- new ToolMessage({ content: 'tool out', tool_call_id: 'x' }),
219
- new AIMessage(''),
220
- ];
221
- expect(filterSubagentResult(messages)).toBe('Partial answer.');
222
- });
223
- });
224
-
225
- describe('resolveSubagentConfigs', () => {
226
- const parentInputs: AgentInputs = {
227
- agentId: 'parent',
228
- provider: Providers.OPENAI,
229
- clientOptions: { modelName: 'gpt-4o', apiKey: 'test' },
230
- instructions: 'You are a parent agent.',
231
- maxContextTokens: 16000,
232
- };
233
-
234
- it('passes through configs with explicit agentInputs', () => {
235
- const config = makeConfig();
236
- const parentContext = AgentContext.fromConfig(parentInputs);
237
- const resolved = resolveSubagentConfigs([config], parentContext);
238
- expect(resolved).toHaveLength(1);
239
- const resolvedConfig = resolved[0];
240
- expect(resolvedConfig.agentInputs.agentId).toBe('child-agent');
241
- });
242
-
243
- it('resolves self-spawn from parent _sourceInputs', () => {
244
- const selfConfig = {
245
- type: 'self',
246
- name: 'Self Spawn',
247
- description: 'Context isolation only',
248
- self: true,
249
- };
250
- const parentContext = AgentContext.fromConfig(parentInputs);
251
- const resolved = resolveSubagentConfigs([selfConfig], parentContext);
252
- expect(resolved).toHaveLength(1);
253
- const resolvedConfig = resolved[0];
254
- expect(resolvedConfig.agentInputs.provider).toBe(Providers.OPENAI);
255
- expect(resolvedConfig.agentInputs.instructions).toBe(
256
- 'You are a parent agent.'
257
- );
258
- });
259
-
260
- it('filters out configs with self=true when _sourceInputs is missing', () => {
261
- const selfConfig = {
262
- type: 'self',
263
- name: 'Self Spawn',
264
- description: 'Context isolation only',
265
- self: true,
266
- };
267
- const parentContext = new AgentContext({
268
- agentId: 'bare',
269
- provider: Providers.OPENAI,
270
- instructionTokens: 0,
271
- });
272
- const resolved = resolveSubagentConfigs([selfConfig], parentContext);
273
- expect(resolved).toHaveLength(0);
274
- });
275
-
276
- it('filters out configs without agentInputs and self=false', () => {
277
- const badConfig = {
278
- type: 'broken',
279
- name: 'Broken',
280
- description: 'Missing inputs',
281
- };
282
- const parentContext = AgentContext.fromConfig(parentInputs);
283
- const resolved = resolveSubagentConfigs([badConfig], parentContext);
284
- expect(resolved).toHaveLength(0);
285
- });
286
-
287
- it('throws on duplicate subagent types', () => {
288
- const parentContext = AgentContext.fromConfig(parentInputs);
289
- const dup1 = makeConfig('researcher');
290
- const dup2 = makeConfig('researcher');
291
- expect(() => resolveSubagentConfigs([dup1, dup2], parentContext)).toThrow(
292
- /Duplicate subagent type "researcher"/
293
- );
294
- });
295
- });
296
-
297
- describe('buildChildInputs', () => {
298
- const parentAgentInputs: AgentInputs = {
299
- agentId: 'parent',
300
- provider: Providers.OPENAI,
301
- clientOptions: { modelName: 'gpt-4o-mini', apiKey: 'test' },
302
- instructions: 'parent',
303
- maxContextTokens: 8000,
304
- subagentConfigs: [{ type: 'researcher', name: 'R', description: 'd' }],
305
- maxSubagentDepth: 3,
306
- };
307
-
308
- it('strips subagentConfigs and maxSubagentDepth when allowNested is false', () => {
309
- const config: ResolvedSubagentConfig = {
310
- type: 'researcher',
311
- name: 'R',
312
- description: 'd',
313
- agentInputs: parentAgentInputs,
314
- };
315
- const result = buildChildInputs(config, 'child', 3);
316
- expect(result.subagentConfigs).toBeUndefined();
317
- expect(result.maxSubagentDepth).toBeUndefined();
318
- });
319
-
320
- it('decrements maxSubagentDepth when allowNested is true', () => {
321
- const config: ResolvedSubagentConfig = {
322
- type: 'researcher',
323
- name: 'R',
324
- description: 'd',
325
- agentInputs: parentAgentInputs,
326
- allowNested: true,
327
- };
328
- const result = buildChildInputs(config, 'child', 3);
329
- expect(result.maxSubagentDepth).toBe(2);
330
- expect(result.subagentConfigs).toEqual(parentAgentInputs.subagentConfigs);
331
- });
332
-
333
- it('clamps decremented depth to 0 (never negative)', () => {
334
- const config: ResolvedSubagentConfig = {
335
- type: 'researcher',
336
- name: 'R',
337
- description: 'd',
338
- agentInputs: parentAgentInputs,
339
- allowNested: true,
340
- };
341
- const result = buildChildInputs(config, 'child', 0);
342
- expect(result.maxSubagentDepth).toBe(0);
343
- });
344
-
345
- it('always strips toolDefinitions (forces traditional mode)', () => {
346
- const inputsWithToolDefs: AgentInputs = {
347
- ...parentAgentInputs,
348
- toolDefinitions: [{ name: 't', description: 'x' }],
349
- };
350
- const config: ResolvedSubagentConfig = {
351
- type: 'researcher',
352
- name: 'R',
353
- description: 'd',
354
- agentInputs: inputsWithToolDefs,
355
- };
356
- const result = buildChildInputs(config, 'child', 3);
357
- expect(result.toolDefinitions).toBeUndefined();
358
- });
359
-
360
- it('scrubs INHERITED graphTools on self-spawn (parent-spread config) but keeps an explicit child config’s own', () => {
361
- const askLikeTool = { name: 'ask_user_question' } as unknown as NonNullable<
362
- AgentInputs['graphTools']
363
- >[number];
364
- const inputsWithGraphTools: AgentInputs = {
365
- ...parentAgentInputs,
366
- graphTools: [askLikeTool],
367
- };
368
-
369
- /**
370
- * Self-spawn: `resolveSubagentConfigs` fills `agentInputs` as a shallow
371
- * spread of the parent's `_sourceInputs`, so the parent-scoped direct
372
- * tool would leak into the child implicitly — it must be scrubbed.
373
- */
374
- const selfConfig: ResolvedSubagentConfig = {
375
- type: 'self',
376
- name: 'Self',
377
- description: 'd',
378
- self: true,
379
- agentInputs: { ...inputsWithGraphTools },
380
- };
381
- expect(
382
- buildChildInputs(selfConfig, 'child-self', 3).graphTools
383
- ).toBeUndefined();
384
-
385
- /**
386
- * Explicit child config: a host that deliberately attaches its own
387
- * in-process direct tools to a child keeps them (Codex #289 P2). With
388
- * HITL enabled, interrupt-capable child tools use the shared checkpointer.
389
- */
390
- const explicitConfig: ResolvedSubagentConfig = {
391
- type: 'researcher',
392
- name: 'R',
393
- description: 'd',
394
- agentInputs: inputsWithGraphTools,
395
- };
396
- expect(
397
- buildChildInputs(explicitConfig, 'child-explicit', 3).graphTools
398
- ).toEqual([askLikeTool]);
399
- expect(inputsWithGraphTools.graphTools).toHaveLength(1); // parent untouched
400
- });
401
-
402
- it('strips parent-run-scoped initialSummary and discoveredTools from child inputs', () => {
403
- /**
404
- * Codex P1: a child inheriting `initialSummary` or `discoveredTools` from
405
- * the parent's shallow-spread AgentInputs leaks unrelated conversation
406
- * context / prior tool-search state into an isolated subagent run,
407
- * defeating the context-isolation contract. Both fields must be cleared.
408
- */
409
- const inputsWithRunContext: AgentInputs = {
410
- ...parentAgentInputs,
411
- initialSummary: { text: 'prior conversation summary', tokenCount: 42 },
412
- discoveredTools: ['prior_tool_a', 'prior_tool_b'],
413
- };
414
- const config: ResolvedSubagentConfig = {
415
- type: 'researcher',
416
- name: 'R',
417
- description: 'd',
418
- agentInputs: inputsWithRunContext,
419
- };
420
- const result = buildChildInputs(config, 'child', 3);
421
- expect(result.initialSummary).toBeUndefined();
422
- expect(result.discoveredTools).toBeUndefined();
423
- });
424
-
425
- it('overrides agentId with the passed childAgentId', () => {
426
- const config: ResolvedSubagentConfig = {
427
- type: 'researcher',
428
- name: 'R',
429
- description: 'd',
430
- agentInputs: parentAgentInputs,
431
- };
432
- const result = buildChildInputs(config, 'my-child', 3);
433
- expect(result.agentId).toBe('my-child');
434
- });
435
- });
436
-
437
- describe('SubagentExecutor', () => {
438
- const config = makeConfig();
439
-
440
- /**
441
- * Build a stub `createChildGraph` factory that returns a minimal
442
- * `StandardGraph`-shaped object whose `createWorkflow().invoke()`
443
- * resolves to `invokeResult`. Avoids `jest.spyOn(StandardGraph)` so
444
- * that SubagentExecutor does not need a runtime dep on the graphs
445
- * module (circular-dep-safe).
446
- */
447
- function makeStubGraphFactory(
448
- invokeResult: { messages: BaseMessage[] },
449
- clearSpy?: jest.Mock
450
- ): { factory: () => StandardGraph; clearHeavyState: jest.Mock } {
451
- const mockClear = clearSpy ?? jest.fn();
452
- const factory = (): StandardGraph =>
453
- ({
454
- createWorkflow: (): { invoke: jest.Mock } => ({
455
- invoke: jest.fn().mockResolvedValue(invokeResult),
456
- }),
457
- clearHeavyState: mockClear,
458
- }) as unknown as StandardGraph;
459
- return { factory, clearHeavyState: mockClear };
460
- }
461
-
462
- function makeThrowingGraphFactory(error: Error): () => StandardGraph {
463
- return (): StandardGraph =>
464
- ({
465
- createWorkflow: (): { invoke: jest.Mock } => ({
466
- invoke: jest.fn().mockRejectedValue(error),
467
- }),
468
- clearHeavyState: jest.fn(),
469
- }) as unknown as StandardGraph;
470
- }
471
-
472
- /** No-op factory for tests that never reach child graph construction. */
473
- function makeNoopGraphFactory(): () => StandardGraph {
474
- return (): StandardGraph =>
475
- ({
476
- createWorkflow: (): { invoke: jest.Mock } => ({
477
- invoke: jest.fn().mockResolvedValue({ messages: [] }),
478
- }),
479
- clearHeavyState: jest.fn(),
480
- }) as unknown as StandardGraph;
481
- }
482
-
483
- function createExecutor(
484
- overrides: Partial<ConstructorParameters<typeof SubagentExecutor>[0]> = {}
485
- ): SubagentExecutor {
486
- return new SubagentExecutor({
487
- configs: new Map([[config.type, config]]),
488
- parentRunId: 'test-run',
489
- parentAgentId: 'parent-agent',
490
- createChildGraph: makeNoopGraphFactory(),
491
- ...overrides,
492
- });
493
- }
494
-
495
- it('returns error for unknown subagent type', async () => {
496
- const executor = createExecutor();
497
- const result = await executor.execute({
498
- description: 'Do something',
499
- subagentType: 'nonexistent',
500
- });
501
- expect(result.content).toContain('Unknown subagent type');
502
- expect(result.content).toContain('nonexistent');
503
- expect(result.content).toContain('researcher');
504
- expect(result.messages).toEqual([]);
505
- });
506
-
507
- it('returns error when maxDepth is 0 (nesting budget exhausted)', async () => {
508
- const executor = createExecutor({ maxDepth: 0 });
509
- const result = await executor.execute({
510
- description: 'Do something',
511
- subagentType: 'researcher',
512
- });
513
- expect(result.content).toContain('Maximum subagent nesting depth');
514
- expect(result.messages).toEqual([]);
515
- });
516
-
517
- it('fails graph HITL before factories, hooks, events, or usage can run', async () => {
518
- const graphConfig: GraphSubagentConfig = {
519
- kind: 'graph',
520
- type: 'graph-team',
521
- name: 'Graph Team',
522
- description: 'Runs a graph.',
523
- agents: [makeChildInputs('graph-member')],
524
- edges: [],
525
- entryAgentId: 'graph-member',
526
- resultAgentId: 'graph-member',
527
- };
528
- const createChildGraph = jest.fn(makeNoopGraphFactory());
529
- const createChildGraphByKind = jest.fn(
530
- (): StandardGraph => makeNoopGraphFactory()()
531
- );
532
- const hook = jest.fn(async (): Promise<Record<string, never>> => ({}));
533
- const hookRegistry = new HookRegistry();
534
- hookRegistry.register('SubagentStart', { hooks: [hook] });
535
- const update = jest.fn();
536
- const handlerRegistry = new HandlerRegistry();
537
- handlerRegistry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
538
- handle: update,
539
- });
540
- const usageSink = jest.fn();
541
- const executor = createExecutor({
542
- configs: new Map([[graphConfig.type, graphConfig]]),
543
- humanInTheLoop: { enabled: true },
544
- createChildGraph,
545
- createChildGraphByKind,
546
- hookRegistry,
547
- parentHandlerRegistry: handlerRegistry,
548
- usageSink,
549
- });
550
-
551
- const result = await executor.execute({
552
- description: 'Do not run.',
553
- subagentType: graphConfig.type,
554
- });
555
-
556
- expect(result.content).toBe(
557
- 'Error: Human-in-the-loop execution is not yet supported for graph subagents.'
558
- );
559
- expect(createChildGraph).not.toHaveBeenCalled();
560
- expect(createChildGraphByKind).not.toHaveBeenCalled();
561
- expect(hook).not.toHaveBeenCalled();
562
- expect(update).not.toHaveBeenCalled();
563
- expect(usageSink).not.toHaveBeenCalled();
564
- });
565
-
566
- it('fails closed when resumable execution has no parent tool call ID', async () => {
567
- const createChildGraph = jest.fn(makeNoopGraphFactory());
568
- const executor = createExecutor({
569
- humanInTheLoop: { enabled: true },
570
- createChildGraph,
571
- });
572
-
573
- const result = await executor.execute({
574
- description: 'Do something',
575
- subagentType: 'researcher',
576
- threadId: 'durable-thread',
577
- });
578
-
579
- expect(result.content).toContain('requires a parent tool call ID');
580
- expect(result.messages).toEqual([]);
581
- expect(createChildGraph).not.toHaveBeenCalled();
582
- });
583
-
584
- it('persists terminal replay outcomes without an active child workflow', async () => {
585
- const checkpointer = new MemorySaver();
586
- const hookRegistry = new HookRegistry();
587
- hookRegistry.registerSession('original-run', 'PreToolUse', {
588
- hooks: [async (): Promise<Record<string, never>> => ({})],
589
- });
590
- const initialExecutor = createExecutor({
591
- checkpointer,
592
- hookRegistry,
593
- humanInTheLoop: { enabled: true },
594
- parentRunId: 'original-run',
595
- });
596
- const call = {
597
- id: 'call_terminal',
598
- name: Constants.SUBAGENT,
599
- args: {
600
- description: 'blocked before execution',
601
- subagent_type: 'researcher',
602
- },
603
- type: 'tool_call' as const,
604
- };
605
- const originalConfig = {
606
- configurable: {
607
- thread_id: 'durable-parent',
608
- checkpoint_id: 'parent-fork',
609
- run_id: 'original-run',
610
- },
611
- };
612
- const settled = {
613
- output: new ToolMessage({
614
- content: 'Blocked: policy',
615
- status: 'error' as const,
616
- name: Constants.SUBAGENT,
617
- tool_call_id: call.id,
618
- }),
619
- additionalContexts: ['persisted context'],
620
- resolvedArgs: { description: 'rewritten' },
621
- };
622
-
623
- await initialExecutor.persistSettledToolOutput(
624
- call,
625
- originalConfig,
626
- settled
627
- );
628
-
629
- const rebuiltExecutor = createExecutor({
630
- checkpointer,
631
- hookRegistry,
632
- humanInTheLoop: { enabled: true },
633
- parentRunId: 'rebuilt-run',
634
- });
635
- const restored = await rebuiltExecutor.getSettledToolOutput(call, {
636
- configurable: {
637
- ...originalConfig.configurable,
638
- run_id: 'rebuilt-run',
639
- },
640
- });
641
-
642
- expect(restored?.output.content).toBe('Blocked: policy');
643
- expect(restored?.additionalContexts).toEqual(['persisted context']);
644
- expect(restored?.resolvedArgs).toEqual({ description: 'rewritten' });
645
- expect(hookRegistry.hasHookFor('PreToolUse', 'original-run')).toBe(true);
646
- expect(hookRegistry.hasHookFor('PreToolUse', 'rebuilt-run')).toBe(true);
647
- });
648
-
649
- it('persists an ordinary child error after the active workflow is released', async () => {
650
- const checkpointer = new MemorySaver();
651
- const invoke = jest.fn().mockRejectedValue(new Error('child failed'));
652
- const executor = createExecutor({
653
- checkpointer,
654
- humanInTheLoop: { enabled: true },
655
- createChildGraph: (): StandardGraph =>
656
- ({
657
- createWorkflow: () => ({
658
- getState: jest.fn().mockResolvedValue({
659
- values: {},
660
- next: ['child-agent'],
661
- tasks: [],
662
- }),
663
- invoke,
664
- }),
665
- clearHeavyState: jest.fn(),
666
- }) as unknown as StandardGraph,
667
- });
668
- const call = {
669
- id: 'call_error',
670
- name: Constants.SUBAGENT,
671
- args: { description: 'fail', subagent_type: 'researcher' },
672
- type: 'tool_call' as const,
673
- };
674
- const runnableConfig = {
675
- configurable: {
676
- thread_id: 'durable-parent',
677
- checkpoint_id: 'parent-fork',
678
- run_id: 'original-run',
679
- },
680
- };
681
- const result = await executor.execute({
682
- description: 'fail',
683
- subagentType: 'researcher',
684
- threadId: 'durable-parent',
685
- parentToolCallId: call.id,
686
- parentConfigurable: runnableConfig.configurable,
687
- });
688
- expect(result.content).toBe('Subagent error: child failed');
689
-
690
- await executor.persistSettledToolOutput(call, runnableConfig, {
691
- output: new ToolMessage({
692
- content: result.content,
693
- name: Constants.SUBAGENT,
694
- tool_call_id: call.id,
695
- }),
696
- additionalContexts: [],
697
- });
698
-
699
- const restored = await createExecutor({
700
- checkpointer,
701
- humanInTheLoop: { enabled: true },
702
- }).getSettledToolOutput(call, runnableConfig);
703
- expect(invoke).toHaveBeenCalledTimes(1);
704
- expect(restored?.output.content).toBe('Subagent error: child failed');
705
- });
706
-
707
- it('continues a recovered in-progress child without reseeding its task', async () => {
708
- const invoke = jest.fn().mockResolvedValue({
709
- messages: [new AIMessage('continued')],
710
- });
711
- const executor = createExecutor({
712
- checkpointer: new MemorySaver(),
713
- humanInTheLoop: { enabled: true },
714
- createChildGraph: (): StandardGraph =>
715
- ({
716
- createWorkflow: () => ({
717
- getState: jest.fn().mockResolvedValue({
718
- values: {},
719
- next: ['child-agent'],
720
- tasks: [],
721
- }),
722
- invoke,
723
- }),
724
- clearHeavyState: jest.fn(),
725
- }) as unknown as StandardGraph,
726
- });
727
-
728
- const result = await executor.execute({
729
- description: 'Do not duplicate this task',
730
- subagentType: 'researcher',
731
- threadId: 'durable-parent',
732
- parentToolCallId: 'call_in_progress',
733
- });
734
-
735
- expect(result.content).toBe('continued');
736
- expect(invoke).toHaveBeenCalledWith(null, expect.any(Object));
737
- });
738
-
739
- it('preserves an existing nested approval scope', async () => {
740
- const nestedScope = {
741
- run_id: 'grandchild-run',
742
- agent_id: 'grandchild-agent',
743
- subagent_type: 'grandchild',
744
- parent_tool_call_id: 'call_grandchild',
745
- };
746
- const nestedInterrupt = new GraphInterrupt([
747
- {
748
- id: 'nested-interrupt',
749
- value: {
750
- type: 'tool_approval',
751
- action_requests: [],
752
- review_configs: [],
753
- subagent: nestedScope,
754
- },
755
- },
756
- ]);
757
- const executor = createExecutor({
758
- humanInTheLoop: { enabled: true },
759
- createChildGraph: (): StandardGraph =>
760
- ({
761
- createWorkflow: () => ({
762
- getState: jest.fn().mockResolvedValue({
763
- values: {},
764
- next: ['agent'],
765
- tasks: [],
766
- }),
767
- invoke: jest.fn().mockRejectedValue(nestedInterrupt),
768
- }),
769
- clearHeavyState: jest.fn(),
770
- }) as unknown as StandardGraph,
771
- });
772
-
773
- let received: GraphInterrupt | undefined;
774
- try {
775
- await executor.execute({
776
- description: 'Delegate again',
777
- subagentType: 'researcher',
778
- threadId: 'durable-thread',
779
- parentToolCallId: 'call_child',
780
- });
781
- } catch (error) {
782
- if (error instanceof GraphInterrupt) {
783
- received = error;
784
- }
785
- }
786
-
787
- expect(received?.interrupts[0].value).toMatchObject({
788
- subagent: nestedScope,
789
- });
790
- });
791
-
792
- it('rethrows a child stream-limit trip instead of converting it to a tool result', async () => {
793
- const executor = createExecutor({
794
- createChildGraph: (): StandardGraph =>
795
- ({
796
- createWorkflow: (): { invoke: jest.Mock } => ({
797
- invoke: jest.fn().mockRejectedValue(
798
- new StreamLimitExceededError({
799
- kind: 'tool_call_args',
800
- limit: 10,
801
- observed: 11,
802
- toolName: 'db_query',
803
- })
804
- ),
805
- }),
806
- clearHeavyState: jest.fn(),
807
- }) as unknown as StandardGraph,
808
- });
809
- await expect(
810
- executor.execute({
811
- description: 'Do something',
812
- subagentType: 'researcher',
813
- })
814
- ).rejects.toBeInstanceOf(StreamLimitExceededError);
815
- });
816
-
817
- it('binds the child to the batch-captured controller, not the live scope', async () => {
818
- const batchBreaker = new AbortController();
819
- const liveBreaker = new AbortController();
820
- const executor = createExecutor({
821
- breakerScope: { controller: () => liveBreaker },
822
- createChildGraph: (): StandardGraph =>
823
- ({
824
- createWorkflow: (): { invoke: jest.Mock } => ({
825
- invoke: jest.fn().mockRejectedValue(
826
- new StreamLimitExceededError({
827
- kind: 'tool_call_args',
828
- limit: 10,
829
- observed: 11,
830
- toolName: 'db_query',
831
- })
832
- ),
833
- }),
834
- clearHeavyState: jest.fn(),
835
- }) as unknown as StandardGraph,
836
- });
837
-
838
- /** `breaker` is the controller the parent TOOL BATCH captured before
839
- * PreToolUse hooks; a reset during those hooks replaced the live
840
- * scope, and the child must not revive on — or trip — the new run's
841
- * controller. */
842
- await expect(
843
- executor.execute({
844
- description: 'Do something',
845
- subagentType: 'researcher',
846
- breaker: batchBreaker,
847
- })
848
- ).rejects.toBeInstanceOf(StreamLimitExceededError);
849
- expect(batchBreaker.signal.aborted).toBe(true);
850
- expect(liveBreaker.signal.aborted).toBe(false);
851
- });
852
-
853
- it('trips the breaker controller captured at execution start, not the current one', async () => {
854
- const oldRun = new AbortController();
855
- const newRun = new AbortController();
856
- let current = oldRun;
857
- let releaseChild: (() => void) | undefined;
858
- const executor = createExecutor({
859
- breakerScope: { controller: () => current },
860
- createChildGraph: (): StandardGraph =>
861
- ({
862
- createWorkflow: (): { invoke: jest.Mock } => ({
863
- invoke: jest.fn().mockImplementation(
864
- () =>
865
- new Promise((_resolve, reject) => {
866
- releaseChild = (): void =>
867
- reject(
868
- new StreamLimitExceededError({
869
- kind: 'tool_call_args',
870
- limit: 10,
871
- observed: 11,
872
- toolName: 'db_query',
873
- })
874
- );
875
- })
876
- ),
877
- }),
878
- clearHeavyState: jest.fn(),
879
- }) as unknown as StandardGraph,
880
- });
881
-
882
- const pending = executor.execute({
883
- description: 'Do something',
884
- subagentType: 'researcher',
885
- });
886
- while (releaseChild == null) {
887
- await new Promise((resolve) => setTimeout(resolve, 0));
888
- }
889
- /** The failed run's reset installs a fresh controller while the child
890
- * is still settling; the straggler's trip must land on the controller
891
- * captured when its execution started. */
892
- current = newRun;
893
- releaseChild();
894
- await expect(pending).rejects.toBeInstanceOf(StreamLimitExceededError);
895
- expect(oldRun.signal.aborted).toBe(true);
896
- expect(newRun.signal.aborted).toBe(false);
897
- });
898
-
899
- it('threads run-level streamLimits into every child graph input', async () => {
900
- const childGraphInputs: StandardGraphInput[] = [];
901
- const noopFactory = makeNoopGraphFactory();
902
- const executor = createExecutor({
903
- streamLimits: { maxToolCallArgBytes: 1234, maxDeltaEventsPerTurn: 9 },
904
- createChildGraph: (input: StandardGraphInput): StandardGraph => {
905
- childGraphInputs.push(input);
906
- return noopFactory();
907
- },
908
- });
909
- await executor.execute({
910
- description: 'Do something',
911
- subagentType: 'researcher',
912
- });
913
- expect(childGraphInputs).toHaveLength(1);
914
- expect(childGraphInputs[0].streamLimits).toEqual({
915
- maxToolCallArgBytes: 1234,
916
- maxDeltaEventsPerTurn: 9,
917
- });
918
- });
919
-
920
- it('executes child graph and returns filtered content', async () => {
921
- const { factory, clearHeavyState } = makeStubGraphFactory({
922
- messages: [
923
- new HumanMessage('research this topic'),
924
- new AIMessage('Here is my research summary.'),
925
- ],
926
- });
927
- const executor = createExecutor({ createChildGraph: factory });
928
-
929
- const result = await executor.execute({
930
- description: 'Research this topic',
931
- subagentType: 'researcher',
932
- });
933
-
934
- expect(result.content).toBe('Here is my research summary.');
935
- expect(result.messages).toHaveLength(2);
936
- expect(clearHeavyState).toHaveBeenCalled();
937
- });
938
-
939
- it('passes parent Langfuse config to the child graph', async () => {
940
- const langfuse = {
941
- enabled: true,
942
- publicKey: 'pk-run',
943
- secretKey: 'sk-run',
944
- baseUrl: 'https://langfuse.test',
945
- toolOutputTracing: { enabled: false },
946
- };
947
- let observedLangfuse: typeof langfuse | undefined;
948
- const executor = createExecutor({
949
- langfuse,
950
- createChildGraph: (input): StandardGraph => {
951
- observedLangfuse = input.langfuse as typeof langfuse;
952
- return {
953
- createWorkflow: (): { invoke: jest.Mock } => ({
954
- invoke: jest.fn().mockResolvedValue({
955
- messages: [new AIMessage('child done')],
956
- }),
957
- }),
958
- clearHeavyState: jest.fn(),
959
- } as unknown as StandardGraph;
960
- },
961
- });
962
-
963
- await executor.execute({
964
- description: 'Research this topic',
965
- subagentType: 'researcher',
966
- });
967
-
968
- expect(observedLangfuse).toBe(langfuse);
969
- });
970
-
971
- describe('usage sink', () => {
972
- type CapturedCallbackHandler = {
973
- handleChatModelStart?: (
974
- llm: unknown,
975
- messages: unknown,
976
- runId: string,
977
- parentRunId?: string,
978
- extraParams?: Record<string, unknown>,
979
- tags?: string[],
980
- metadata?: Record<string, unknown>
981
- ) => unknown;
982
- handleLLMEnd?: (output: unknown, runId: string) => unknown;
983
- handleLLMError?: (err: unknown, runId: string) => unknown;
984
- };
985
- type CapturedInvokeOptions = { callbacks?: CapturedCallbackHandler[] };
986
-
987
- /**
988
- * Stub factory that records the `StandardGraphInput` the executor
989
- * builds and the options passed to `workflow.invoke`, so tests can
990
- * drive the attached usage-capture callback directly (the stubbed
991
- * invoke never makes real model calls, so callbacks would otherwise
992
- * never fire).
993
- */
994
- function makeCapturingGraphFactory(driveDuringInvoke?: {
995
- drive: (handler: CapturedCallbackHandler) => void | Promise<void>;
996
- }): {
997
- factory: (input: StandardGraphInput) => StandardGraph;
998
- getInput: () => StandardGraphInput | undefined;
999
- getInvokeOptions: () => CapturedInvokeOptions | undefined;
1000
- } {
1001
- let capturedInput: StandardGraphInput | undefined;
1002
- let capturedOptions: CapturedInvokeOptions | undefined;
1003
- const factory = (input: StandardGraphInput): StandardGraph => {
1004
- capturedInput = input;
1005
- return {
1006
- createWorkflow: (): { invoke: jest.Mock } => ({
1007
- invoke: jest
1008
- .fn()
1009
- .mockImplementation(
1010
- async (_input: unknown, options: CapturedInvokeOptions) => {
1011
- capturedOptions = options;
1012
- const usageHandler = options.callbacks?.find(
1013
- (cb) => cb.handleLLMEnd != null
1014
- );
1015
- if (driveDuringInvoke && usageHandler) {
1016
- await driveDuringInvoke.drive(usageHandler);
1017
- }
1018
- return { messages: [new AIMessage('child done')] };
1019
- }
1020
- ),
1021
- }),
1022
- clearHeavyState: jest.fn(),
1023
- } as unknown as StandardGraph;
1024
- };
1025
- return {
1026
- factory,
1027
- getInput: () => capturedInput,
1028
- getInvokeOptions: () => capturedOptions,
1029
- };
1030
- }
1031
-
1032
- const makeChoice = (
1033
- usage: Record<string, number> | undefined
1034
- ): unknown => ({
1035
- text: 'ok',
1036
- message: new AIMessage({
1037
- content: 'ok',
1038
- ...(usage
1039
- ? {
1040
- usage_metadata: usage as unknown as AIMessage['usage_metadata'],
1041
- }
1042
- : {}),
1043
- }),
1044
- });
1045
-
1046
- const makeLLMEndOutput = (
1047
- usage: Record<string, number> | undefined
1048
- ): unknown => ({
1049
- generations: [[makeChoice(usage)]],
1050
- });
1051
-
1052
- it('forwards a wrapped sink into the child graph input that rewrites runId to the root run', async () => {
1053
- const events: SubagentUsageEvent[] = [];
1054
- const { factory, getInput } = makeCapturingGraphFactory();
1055
- const executor = createExecutor({
1056
- usageSink: (event) => {
1057
- events.push(event);
1058
- },
1059
- createChildGraph: factory,
1060
- });
1061
-
1062
- await executor.execute({
1063
- description: 'Research this topic',
1064
- subagentType: 'researcher',
1065
- });
1066
-
1067
- const forwarded = getInput()?.subagentUsageSink;
1068
- expect(typeof forwarded).toBe('function');
1069
- /**
1070
- * Simulate a NESTED child's emission: its executor stamps `runId`
1071
- * with its own parent (an intermediate `*_sub_*` id). The wrapper
1072
- * must rewrite it to THIS executor's parent run so the host always
1073
- * sees root-run attribution, while the emitting child's identity
1074
- * (`subagentRunId`) is preserved.
1075
- */
1076
- forwarded?.({
1077
- usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
1078
- model: 'gpt-4o-mini',
1079
- provider: Providers.OPENAI,
1080
- subagentType: 'nested-grandchild',
1081
- subagentRunId: 'test-run_sub_a_sub_b',
1082
- subagentAgentId: 'grandchild',
1083
- runId: 'test-run_sub_a',
1084
- });
1085
-
1086
- expect(events).toHaveLength(1);
1087
- expect(events[0].runId).toBe('test-run');
1088
- expect(events[0].subagentRunId).toBe('test-run_sub_a_sub_b');
1089
- expect(events[0].subagentType).toBe('nested-grandchild');
1090
- });
1091
-
1092
- it('does not attach a capture callback when no sink is provided', async () => {
1093
- const { factory, getInvokeOptions } = makeCapturingGraphFactory();
1094
- const executor = createExecutor({ createChildGraph: factory });
1095
-
1096
- await executor.execute({
1097
- description: 'Research this topic',
1098
- subagentType: 'researcher',
1099
- });
1100
-
1101
- expect(getInvokeOptions()?.callbacks).toEqual([]);
1102
- });
1103
-
1104
- it('emits tagged usage events with per-call ls_model_name', async () => {
1105
- const events: SubagentUsageEvent[] = [];
1106
- const { factory } = makeCapturingGraphFactory({
1107
- drive: async (handler) => {
1108
- await handler.handleChatModelStart?.(
1109
- {},
1110
- [[]],
1111
- 'call-1',
1112
- undefined,
1113
- undefined,
1114
- undefined,
1115
- { ls_model_name: 'gpt-4o-mini-2024-07-18' }
1116
- );
1117
- await handler.handleLLMEnd?.(
1118
- makeLLMEndOutput({
1119
- input_tokens: 11,
1120
- output_tokens: 7,
1121
- total_tokens: 18,
1122
- }),
1123
- 'call-1'
1124
- );
1125
- },
1126
- });
1127
- const executor = createExecutor({
1128
- usageSink: (event) => {
1129
- events.push(event);
1130
- },
1131
- createChildGraph: factory,
1132
- });
1133
-
1134
- await executor.execute({
1135
- description: 'Research this topic',
1136
- subagentType: 'researcher',
1137
- });
1138
-
1139
- expect(events).toHaveLength(1);
1140
- const event = events[0];
1141
- expect(event.usage).toEqual({
1142
- input_tokens: 11,
1143
- output_tokens: 7,
1144
- total_tokens: 18,
1145
- });
1146
- expect(event.model).toBe('gpt-4o-mini-2024-07-18');
1147
- expect(event.provider).toBe(Providers.OPENAI);
1148
- expect(event.subagentType).toBe('researcher');
1149
- expect(event.subagentAgentId).toBe('child-agent');
1150
- expect(event.subagentRunId).toContain('test-run_sub_');
1151
- expect(event.runId).toBe('test-run');
1152
- });
1153
-
1154
- it('falls back to the configured model when a call has no ls_model_name', async () => {
1155
- const events: SubagentUsageEvent[] = [];
1156
- const { factory } = makeCapturingGraphFactory({
1157
- drive: async (handler) => {
1158
- await handler.handleLLMEnd?.(
1159
- makeLLMEndOutput({
1160
- input_tokens: 3,
1161
- output_tokens: 2,
1162
- total_tokens: 5,
1163
- }),
1164
- 'call-1'
1165
- );
1166
- },
1167
- });
1168
- const executor = createExecutor({
1169
- usageSink: (event) => {
1170
- events.push(event);
1171
- },
1172
- createChildGraph: factory,
1173
- });
1174
-
1175
- await executor.execute({
1176
- description: 'Research this topic',
1177
- subagentType: 'researcher',
1178
- });
1179
-
1180
- expect(events).toHaveLength(1);
1181
- /** `makeChildInputs` configures `clientOptions.modelName`. */
1182
- expect(events[0].model).toBe('gpt-4o-mini');
1183
- });
1184
-
1185
- it('emits one event per generation group when a call has multiple completions (n > 1)', async () => {
1186
- const usage = { input_tokens: 10, output_tokens: 4, total_tokens: 14 };
1187
- const events: SubagentUsageEvent[] = [];
1188
- const { factory } = makeCapturingGraphFactory({
1189
- drive: async (handler) => {
1190
- /**
1191
- * One provider request with two choices — both carry the same
1192
- * request-level usage. Emitting per choice would double-bill.
1193
- */
1194
- await handler.handleLLMEnd?.(
1195
- { generations: [[makeChoice(usage), makeChoice(usage)]] },
1196
- 'call-1'
1197
- );
1198
- /** Batched prompts: two groups = two requests = two events. */
1199
- await handler.handleLLMEnd?.(
1200
- { generations: [[makeChoice(usage)], [makeChoice(usage)]] },
1201
- 'call-2'
1202
- );
1203
- },
1204
- });
1205
- const executor = createExecutor({
1206
- usageSink: (event) => {
1207
- events.push(event);
1208
- },
1209
- createChildGraph: factory,
1210
- });
1211
-
1212
- await executor.execute({
1213
- description: 'Research this topic',
1214
- subagentType: 'researcher',
1215
- });
1216
-
1217
- expect(events).toHaveLength(3);
1218
- });
1219
-
1220
- it('prefers INVOKED_PROVIDER/INVOKED_MODEL metadata for fallback-served calls', async () => {
1221
- const events: SubagentUsageEvent[] = [];
1222
- const { factory } = makeCapturingGraphFactory({
1223
- drive: async (handler) => {
1224
- /**
1225
- * Mirror a fallback-served call: `attemptInvoke` stamps the
1226
- * serving provider, `tryFallbackProviders` stamps the fallback's
1227
- * configured model, and the provider reports no `ls_model_name`.
1228
- */
1229
- await handler.handleChatModelStart?.(
1230
- {},
1231
- [[]],
1232
- 'call-1',
1233
- undefined,
1234
- undefined,
1235
- undefined,
1236
- {
1237
- [Constants.INVOKED_PROVIDER]: Providers.ANTHROPIC,
1238
- [Constants.INVOKED_MODEL]: 'claude-fallback-1',
1239
- }
1240
- );
1241
- await handler.handleLLMEnd?.(
1242
- makeLLMEndOutput({
1243
- input_tokens: 5,
1244
- output_tokens: 3,
1245
- total_tokens: 8,
1246
- }),
1247
- 'call-1'
1248
- );
1249
- },
1250
- });
1251
- const executor = createExecutor({
1252
- usageSink: (event) => {
1253
- events.push(event);
1254
- },
1255
- createChildGraph: factory,
1256
- });
1257
-
1258
- await executor.execute({
1259
- description: 'Research this topic',
1260
- subagentType: 'researcher',
1261
- });
1262
-
1263
- expect(events).toHaveLength(1);
1264
- /** Not the configured primary (openAI / gpt-4o-mini). */
1265
- expect(events[0].provider).toBe(Providers.ANTHROPIC);
1266
- expect(events[0].model).toBe('claude-fallback-1');
1267
- });
1268
-
1269
- it('prefers provider-reported ls_model_name over INVOKED_MODEL', async () => {
1270
- const events: SubagentUsageEvent[] = [];
1271
- const { factory } = makeCapturingGraphFactory({
1272
- drive: async (handler) => {
1273
- await handler.handleChatModelStart?.(
1274
- {},
1275
- [[]],
1276
- 'call-1',
1277
- undefined,
1278
- undefined,
1279
- undefined,
1280
- {
1281
- ls_model_name: 'claude-fallback-1-20260101',
1282
- [Constants.INVOKED_PROVIDER]: Providers.ANTHROPIC,
1283
- [Constants.INVOKED_MODEL]: 'claude-fallback-1',
1284
- }
1285
- );
1286
- await handler.handleLLMEnd?.(
1287
- makeLLMEndOutput({
1288
- input_tokens: 5,
1289
- output_tokens: 3,
1290
- total_tokens: 8,
1291
- }),
1292
- 'call-1'
1293
- );
1294
- },
1295
- });
1296
- const executor = createExecutor({
1297
- usageSink: (event) => {
1298
- events.push(event);
1299
- },
1300
- createChildGraph: factory,
1301
- });
1302
-
1303
- await executor.execute({
1304
- description: 'Research this topic',
1305
- subagentType: 'researcher',
1306
- });
1307
-
1308
- expect(events[0].model).toBe('claude-fallback-1-20260101');
1309
- });
1310
-
1311
- it('skips model calls that report no usage_metadata', async () => {
1312
- const events: SubagentUsageEvent[] = [];
1313
- const { factory } = makeCapturingGraphFactory({
1314
- drive: async (handler) => {
1315
- await handler.handleLLMEnd?.(makeLLMEndOutput(undefined), 'call-1');
1316
- },
1317
- });
1318
- const executor = createExecutor({
1319
- usageSink: (event) => {
1320
- events.push(event);
1321
- },
1322
- createChildGraph: factory,
1323
- });
1324
-
1325
- await executor.execute({
1326
- description: 'Research this topic',
1327
- subagentType: 'researcher',
1328
- });
1329
-
1330
- expect(events).toEqual([]);
1331
- });
1332
-
1333
- it('swallows sink errors without breaking the child run', async () => {
1334
- const { factory } = makeCapturingGraphFactory({
1335
- drive: async (handler) => {
1336
- await handler.handleLLMEnd?.(
1337
- makeLLMEndOutput({
1338
- input_tokens: 1,
1339
- output_tokens: 1,
1340
- total_tokens: 2,
1341
- }),
1342
- 'call-1'
1343
- );
1344
- },
1345
- });
1346
- const executor = createExecutor({
1347
- usageSink: () => {
1348
- throw new Error('host sink exploded');
1349
- },
1350
- createChildGraph: factory,
1351
- });
1352
-
1353
- const result = await executor.execute({
1354
- description: 'Research this topic',
1355
- subagentType: 'researcher',
1356
- });
1357
-
1358
- expect(result.content).toBe('child done');
1359
- });
1360
-
1361
- it('awaits async sinks and swallows their rejections', async () => {
1362
- const settled: string[] = [];
1363
- const { factory } = makeCapturingGraphFactory({
1364
- drive: async (handler) => {
1365
- await handler.handleLLMEnd?.(
1366
- makeLLMEndOutput({
1367
- input_tokens: 1,
1368
- output_tokens: 1,
1369
- total_tokens: 2,
1370
- }),
1371
- 'call-1'
1372
- );
1373
- await handler.handleLLMEnd?.(
1374
- makeLLMEndOutput({
1375
- input_tokens: 2,
1376
- output_tokens: 2,
1377
- total_tokens: 4,
1378
- }),
1379
- 'call-2'
1380
- );
1381
- /**
1382
- * Both sink dispatches must have settled by the time
1383
- * `handleLLMEnd` resolves — a dropped promise would leave
1384
- * `recorded` missing here and surface the second call's
1385
- * rejection as unhandled.
1386
- */
1387
- settled.push('drive-done');
1388
- },
1389
- });
1390
- const executor = createExecutor({
1391
- usageSink: async (event) => {
1392
- await new Promise((resolve) => setTimeout(resolve, 5));
1393
- if (event.usage.input_tokens === 2) {
1394
- throw new Error('async host sink rejected');
1395
- }
1396
- settled.push('recorded');
1397
- },
1398
- createChildGraph: factory,
1399
- });
1400
-
1401
- const result = await executor.execute({
1402
- description: 'Research this topic',
1403
- subagentType: 'researcher',
1404
- });
1405
-
1406
- expect(result.content).toBe('child done');
1407
- expect(settled).toEqual(['recorded', 'drive-done']);
1408
- });
1409
- });
1410
-
1411
- it('returns error message when child graph throws', async () => {
1412
- const executor = createExecutor({
1413
- createChildGraph: makeThrowingGraphFactory(
1414
- new Error('Graph recursion limit reached')
1415
- ),
1416
- });
1417
-
1418
- const result = await executor.execute({
1419
- description: 'Do something',
1420
- subagentType: 'researcher',
1421
- });
1422
-
1423
- expect(result.content).toContain('Subagent error');
1424
- expect(result.content).toContain('Graph recursion limit reached');
1425
- expect(result.messages).toEqual([]);
1426
- });
1427
-
1428
- it('truncates long error messages to 200 chars', async () => {
1429
- const longMessage = 'x'.repeat(500);
1430
- const executor = createExecutor({
1431
- createChildGraph: makeThrowingGraphFactory(new Error(longMessage)),
1432
- });
1433
-
1434
- const result = await executor.execute({
1435
- description: 'Do something',
1436
- subagentType: 'researcher',
1437
- });
1438
-
1439
- /**
1440
- * Expected composition: "Subagent error: " (16) + 200 truncated chars + "..." (3) = 219.
1441
- * Assert the exact envelope to catch regressions in the truncation constant.
1442
- */
1443
- const MAX_TRUNCATED_LENGTH = 'Subagent error: '.length + 200 + '...'.length;
1444
- expect(result.content.length).toBe(MAX_TRUNCATED_LENGTH);
1445
- expect(result.content.startsWith('Subagent error: ')).toBe(true);
1446
- expect(result.content.endsWith('...')).toBe(true);
1447
- });
1448
-
1449
- it('does not truncate short error messages', async () => {
1450
- const shortMessage = 'brief error detail';
1451
- const executor = createExecutor({
1452
- createChildGraph: makeThrowingGraphFactory(new Error(shortMessage)),
1453
- });
1454
-
1455
- const result = await executor.execute({
1456
- description: 'Do something',
1457
- subagentType: 'researcher',
1458
- });
1459
-
1460
- expect(result.content).toBe(`Subagent error: ${shortMessage}`);
1461
- expect(result.content.endsWith('...')).toBe(false);
1462
- });
1463
-
1464
- it('builds child with decremented maxSubagentDepth when allowNested=true', async () => {
1465
- const nestedConfig: ResolvedSubagentConfig = {
1466
- type: 'nested',
1467
- name: 'Nested',
1468
- description: 'allows nesting',
1469
- allowNested: true,
1470
- agentInputs: {
1471
- ...makeChildInputs('nested-child'),
1472
- subagentConfigs: [
1473
- {
1474
- type: 'nested',
1475
- name: 'Nested',
1476
- description: 'allows nesting',
1477
- allowNested: true,
1478
- },
1479
- ],
1480
- maxSubagentDepth: 3,
1481
- },
1482
- };
1483
-
1484
- let observedChildInputs: AgentInputs | undefined;
1485
- const executor = new SubagentExecutor({
1486
- configs: new Map([[nestedConfig.type, nestedConfig]]),
1487
- parentRunId: 'test-run',
1488
- parentAgentId: 'parent',
1489
- maxDepth: 3,
1490
- createChildGraph: (input): StandardGraph => {
1491
- observedChildInputs = input.agents[0];
1492
- return {
1493
- createWorkflow: (): { invoke: jest.Mock } => ({
1494
- invoke: jest.fn().mockResolvedValue({
1495
- messages: [new AIMessage('nested done')],
1496
- }),
1497
- }),
1498
- clearHeavyState: jest.fn(),
1499
- } as unknown as StandardGraph;
1500
- },
1501
- });
1502
-
1503
- await executor.execute({
1504
- description: 'nested task',
1505
- subagentType: 'nested',
1506
- });
1507
-
1508
- expect(observedChildInputs).toBeDefined();
1509
- expect(observedChildInputs!.maxSubagentDepth).toBe(2);
1510
- expect(observedChildInputs!.subagentConfigs).toBeDefined();
1511
- });
1512
-
1513
- it('strips subagentConfigs from child when allowNested is not set', async () => {
1514
- let observedChildInputs: AgentInputs | undefined;
1515
- const executor = createExecutor({
1516
- maxDepth: 3,
1517
- createChildGraph: (input): StandardGraph => {
1518
- observedChildInputs = input.agents[0];
1519
- return {
1520
- createWorkflow: (): { invoke: jest.Mock } => ({
1521
- invoke: jest.fn().mockResolvedValue({
1522
- messages: [new AIMessage('done')],
1523
- }),
1524
- }),
1525
- clearHeavyState: jest.fn(),
1526
- } as unknown as StandardGraph;
1527
- },
1528
- });
1529
-
1530
- await executor.execute({
1531
- description: 'task',
1532
- subagentType: 'researcher',
1533
- });
1534
-
1535
- expect(observedChildInputs).toBeDefined();
1536
- expect(observedChildInputs!.subagentConfigs).toBeUndefined();
1537
- expect(observedChildInputs!.maxSubagentDepth).toBeUndefined();
1538
- });
1539
-
1540
- it('seeds only the selected single-agent child before its first invocation', async () => {
1541
- const selectedSession = {
1542
- session_id: 'selected-storage',
1543
- files: [
1544
- {
1545
- id: 'selected-file',
1546
- name: 'selected.txt',
1547
- storage_session_id: 'selected-storage',
1548
- },
1549
- ],
1550
- lastUpdated: 1,
1551
- };
1552
- const siblingSession = {
1553
- session_id: 'sibling-storage',
1554
- files: [
1555
- {
1556
- id: 'sibling-file',
1557
- name: 'sibling.txt',
1558
- storage_session_id: 'sibling-storage',
1559
- },
1560
- ],
1561
- lastUpdated: 1,
1562
- };
1563
- const selected = makeConfig('selected', {
1564
- agentInputs: {
1565
- ...makeChildInputs('selected-agent'),
1566
- initialSessions: new Map([[Constants.EXECUTE_CODE, selectedSession]]),
1567
- },
1568
- });
1569
- const sibling = makeConfig('sibling', {
1570
- agentInputs: {
1571
- ...makeChildInputs('sibling-agent'),
1572
- initialSessions: new Map([[Constants.EXECUTE_CODE, siblingSession]]),
1573
- },
1574
- });
1575
- const childSessions: ToolSessionMap = new Map();
1576
- const invoke = jest.fn(async () => {
1577
- expect(childSessions.get(Constants.EXECUTE_CODE)).toEqual(
1578
- selectedSession
1579
- );
1580
- expect(childSessions.get(Constants.EXECUTE_CODE)).not.toBe(
1581
- selectedSession
1582
- );
1583
- return { messages: [new AIMessage('done')] };
1584
- });
1585
- const executor = createExecutor({
1586
- configs: new Map([
1587
- [selected.type, selected],
1588
- [sibling.type, sibling],
1589
- ]),
1590
- createChildGraph: (): StandardGraph =>
1591
- ({
1592
- sessions: childSessions,
1593
- createWorkflow: () => ({ invoke }),
1594
- clearHeavyState: jest.fn(),
1595
- }) as unknown as StandardGraph,
1596
- });
1597
-
1598
- await executor.execute({
1599
- description: 'Use the selected file.',
1600
- subagentType: selected.type,
1601
- });
1602
-
1603
- expect(invoke).toHaveBeenCalledTimes(1);
1604
- expect(
1605
- childSessions
1606
- .get(Constants.EXECUTE_CODE)
1607
- ?.files?.some((file) => file.id === 'sibling-file')
1608
- ).toBe(false);
1609
- });
1610
-
1611
- it('combines member session seeds inside a selected graph child', async () => {
1612
- const makeSession = (
1613
- storageSessionId: string,
1614
- includeFileSession = true
1615
- ) => ({
1616
- session_id: storageSessionId,
1617
- files: [
1618
- {
1619
- id: 'shared-file-id',
1620
- name: `${storageSessionId}.txt`,
1621
- ...(includeFileSession
1622
- ? { storage_session_id: storageSessionId }
1623
- : {}),
1624
- },
1625
- ],
1626
- lastUpdated: 1,
1627
- });
1628
- const first = {
1629
- ...makeChildInputs('first'),
1630
- initialSessions: new Map([
1631
- [Constants.EXECUTE_CODE, makeSession('first-storage')],
1632
- ]),
1633
- };
1634
- const second = {
1635
- ...makeChildInputs('second'),
1636
- initialSessions: new Map([
1637
- [Constants.EXECUTE_CODE, makeSession('second-storage', false)],
1638
- ]),
1639
- };
1640
- const graphConfig: GraphSubagentConfig = {
1641
- kind: 'graph',
1642
- type: 'graph-team',
1643
- name: 'Graph Team',
1644
- description: 'Runs a graph.',
1645
- agents: [first, second],
1646
- edges: [{ from: 'first', to: 'second', edgeType: 'direct' }],
1647
- entryAgentId: 'first',
1648
- resultAgentId: 'second',
1649
- };
1650
- const childSessions: ToolSessionMap = new Map();
1651
- const invoke = jest.fn(async () => {
1652
- expect(
1653
- childSessions
1654
- .get(Constants.EXECUTE_CODE)
1655
- ?.files?.map((file) => [file.id, file.storage_session_id])
1656
- ).toEqual([
1657
- ['shared-file-id', 'first-storage'],
1658
- ['shared-file-id', 'second-storage'],
1659
- ]);
1660
- return {
1661
- messages: [new AIMessage('done')],
1662
- subagentResult: { agentId: 'second' },
1663
- };
1664
- });
1665
- const childGraph = {
1666
- sessions: childSessions,
1667
- createWorkflow: () => ({ invoke }),
1668
- clearHeavyState: jest.fn(),
1669
- } as unknown as StandardGraph;
1670
- const executor = createExecutor({
1671
- configs: new Map([[graphConfig.type, graphConfig]]),
1672
- createChildGraphByKind: () => childGraph,
1673
- });
1674
-
1675
- await executor.execute({
1676
- description: 'Use both files.',
1677
- subagentType: graphConfig.type,
1678
- });
1679
-
1680
- expect(invoke).toHaveBeenCalledTimes(1);
1681
- });
1682
-
1683
- it('preserves the child session across an in-memory HITL resume', async () => {
1684
- const seededSession = {
1685
- session_id: 'seed-storage',
1686
- files: [
1687
- {
1688
- id: 'seed-file',
1689
- name: 'seed.txt',
1690
- storage_session_id: 'seed-storage',
1691
- },
1692
- ],
1693
- lastUpdated: 1,
1694
- };
1695
- const hitlConfig = makeConfig('hitl-child', {
1696
- agentInputs: {
1697
- ...makeChildInputs('hitl-child'),
1698
- initialSessions: new Map([[Constants.EXECUTE_CODE, seededSession]]),
1699
- },
1700
- });
1701
- const childSessions: ToolSessionMap = new Map();
1702
- const childInterrupt = new GraphInterrupt([
1703
- {
1704
- id: 'approval-1',
1705
- value: {
1706
- type: 'tool_approval',
1707
- action_requests: [],
1708
- review_configs: [],
1709
- },
1710
- },
1711
- ]);
1712
- const invoke = jest
1713
- .fn()
1714
- .mockImplementationOnce(async () => {
1715
- const session = childSessions.get(Constants.EXECUTE_CODE)!;
1716
- childSessions.set(Constants.EXECUTE_CODE, {
1717
- ...session,
1718
- session_id: 'live-execution',
1719
- files: [
1720
- ...(session.files ?? []),
1721
- {
1722
- id: 'generated-file',
1723
- name: 'generated.txt',
1724
- storage_session_id: 'live-execution',
1725
- },
1726
- ],
1727
- });
1728
- throw childInterrupt;
1729
- })
1730
- .mockImplementationOnce(async () => {
1731
- expect(childSessions.get(Constants.EXECUTE_CODE)).toMatchObject({
1732
- session_id: 'live-execution',
1733
- files: [{ id: 'seed-file' }, { id: 'generated-file' }],
1734
- });
1735
- return { messages: [new AIMessage('resumed')] };
1736
- });
1737
- const executor = createExecutor({
1738
- configs: new Map([[hitlConfig.type, hitlConfig]]),
1739
- humanInTheLoop: { enabled: true },
1740
- checkpointer: new MemorySaver(),
1741
- createChildGraph: (): StandardGraph =>
1742
- ({
1743
- sessions: childSessions,
1744
- createWorkflow: () => ({
1745
- getState: jest.fn().mockResolvedValue({
1746
- values: {},
1747
- next: [],
1748
- tasks: [],
1749
- }),
1750
- invoke,
1751
- }),
1752
- getChildCheckpointThreadIds: jest.fn(() => []),
1753
- createSubagentResumeState: jest.fn(() => ({
1754
- toolCallSteps: [],
1755
- toolSessions: [],
1756
- toolNodes: [],
1757
- eagerToolUsage: [],
1758
- eagerToolSuppressions: [],
1759
- })),
1760
- clearHeavyState: jest.fn(),
1761
- }) as unknown as StandardGraph,
1762
- });
1763
- const params = {
1764
- description: 'Pause and resume.',
1765
- subagentType: hitlConfig.type,
1766
- threadId: 'durable-parent',
1767
- parentToolCallId: 'call-hitl',
1768
- };
1769
-
1770
- await expect(executor.execute(params)).rejects.toBeInstanceOf(
1771
- GraphInterrupt
1772
- );
1773
- const result = await executor.execute({
1774
- ...params,
1775
- parentConfigurable: {
1776
- __pregel_resume_map: { 'approval-1': [] },
1777
- },
1778
- });
1779
-
1780
- expect(result.content).toBe('resumed');
1781
- expect(invoke).toHaveBeenCalledTimes(2);
1782
- });
1783
-
1784
- describe('parentConfigurable inheritance', () => {
1785
- type CapturingGraphFactory = {
1786
- factory: () => StandardGraph;
1787
- getInvokeConfig: () => Record<string, unknown> | undefined;
1788
- };
1789
-
1790
- /**
1791
- * Build a stub factory that captures the second argument to
1792
- * `workflow.invoke()` (the runnable config) so tests can assert on
1793
- * the `configurable` we forwarded to the child graph.
1794
- */
1795
- function makeCapturingGraphFactory(): CapturingGraphFactory {
1796
- let capturedConfig: Record<string, unknown> | undefined;
1797
- const factory = (): StandardGraph =>
1798
- ({
1799
- createWorkflow: (): { invoke: jest.Mock } => ({
1800
- invoke: jest
1801
- .fn()
1802
- .mockImplementation(
1803
- async (
1804
- _input: unknown,
1805
- config: Record<string, unknown>
1806
- ): Promise<{ messages: BaseMessage[] }> => {
1807
- capturedConfig = config;
1808
- return { messages: [new AIMessage('done')] };
1809
- }
1810
- ),
1811
- }),
1812
- clearHeavyState: jest.fn(),
1813
- }) as unknown as StandardGraph;
1814
- return { factory, getInvokeConfig: () => capturedConfig };
1815
- }
1816
-
1817
- it('forwards parentConfigurable into the child workflow.invoke configurable', async () => {
1818
- const { factory, getInvokeConfig } = makeCapturingGraphFactory();
1819
- const executor = createExecutor({ createChildGraph: factory });
1820
-
1821
- await executor.execute({
1822
- description: 'task',
1823
- subagentType: 'researcher',
1824
- parentConfigurable: {
1825
- requestBody: { messageId: 'msg-123', conversationId: 'conv-456' },
1826
- user: { id: 'user_abc' },
1827
- user_id: 'user_abc',
1828
- userMCPAuthMap: { 'mcp-github': { token: 'abc' } },
1829
- },
1830
- });
1831
-
1832
- const invokeConfig = getInvokeConfig();
1833
- expect(invokeConfig).toBeDefined();
1834
- const configurable = invokeConfig!.configurable as Record<
1835
- string,
1836
- unknown
1837
- >;
1838
- expect(configurable.requestBody).toEqual({
1839
- messageId: 'msg-123',
1840
- conversationId: 'conv-456',
1841
- });
1842
- expect(configurable.user).toEqual({ id: 'user_abc' });
1843
- expect(configurable.user_id).toBe('user_abc');
1844
- expect(configurable.userMCPAuthMap).toEqual({
1845
- 'mcp-github': { token: 'abc' },
1846
- });
1847
- });
1848
-
1849
- it('inherits parent thread_id when supplied (subagent is part of same conversation)', async () => {
1850
- const { factory, getInvokeConfig } = makeCapturingGraphFactory();
1851
- const executor = createExecutor({
1852
- createChildGraph: factory,
1853
- parentRunId: 'parent-run-xyz',
1854
- });
1855
-
1856
- await executor.execute({
1857
- description: 'task',
1858
- subagentType: 'researcher',
1859
- parentConfigurable: { thread_id: 'parent-thread-conv-abc' },
1860
- });
1861
-
1862
- const configurable = getInvokeConfig()!.configurable as Record<
1863
- string,
1864
- unknown
1865
- >;
1866
- expect(configurable.thread_id).toBe('parent-thread-conv-abc');
1867
- });
1868
-
1869
- it('falls back to childRunId for thread_id when parent did not supply one', async () => {
1870
- const { factory, getInvokeConfig } = makeCapturingGraphFactory();
1871
- const executor = createExecutor({
1872
- createChildGraph: factory,
1873
- parentRunId: 'parent-run-xyz',
1874
- });
1875
-
1876
- await executor.execute({
1877
- description: 'task',
1878
- subagentType: 'researcher',
1879
- parentConfigurable: { user_id: 'user_abc' },
1880
- });
1881
-
1882
- const configurable = getInvokeConfig()!.configurable as Record<
1883
- string,
1884
- unknown
1885
- >;
1886
- expect(configurable.thread_id as string).toMatch(/^parent-run-xyz_sub_/);
1887
- expect(configurable.user_id).toBe('user_abc');
1888
- });
1889
-
1890
- it('forwards run-identity fields verbatim into the child invoke configurable', async () => {
1891
- const { factory, getInvokeConfig } = makeCapturingGraphFactory();
1892
- const executor = createExecutor({ createChildGraph: factory });
1893
-
1894
- await executor.execute({
1895
- description: 'task',
1896
- subagentType: 'researcher',
1897
- parentConfigurable: {
1898
- run_id: 'parent-run-id',
1899
- parent_run_id: 'grandparent-run-id',
1900
- requestBody: { messageId: 'msg-1' },
1901
- },
1902
- });
1903
-
1904
- const configurable = getInvokeConfig()!.configurable as Record<
1905
- string,
1906
- unknown
1907
- >;
1908
- // The SDK forwards these fields as part of its inheritance contract.
1909
- // NOTE: the LangGraph runtime overwrites `configurable.run_id` at
1910
- // actual child-invoke time (verified empirically); this unit test
1911
- // only asserts what the SDK forwards into `workflow.invoke` — not
1912
- // what tools downstream observe. `parent_run_id` and other
1913
- // host-set keys do survive the runtime pass-through.
1914
- expect(configurable.run_id).toBe('parent-run-id');
1915
- expect(configurable.parent_run_id).toBe('grandparent-run-id');
1916
- expect(configurable.requestBody).toEqual({ messageId: 'msg-1' });
1917
- });
1918
-
1919
- it('strips LangGraph runtime fields from child workflow.invoke configurable', async () => {
1920
- const { factory, getInvokeConfig } = makeCapturingGraphFactory();
1921
- const executor = createExecutor({ createChildGraph: factory });
1922
-
1923
- await executor.execute({
1924
- description: 'task',
1925
- subagentType: 'researcher',
1926
- parentConfigurable: {
1927
- __pregel_abort_signals: { externalAbortSignal: 'parent-signal' },
1928
- __pregel_call: (): void => undefined,
1929
- __pregel_scratchpad: { currentTaskInput: 'large-payload' },
1930
- checkpoint_id: 'parent-checkpoint-id',
1931
- checkpoint_map: { parent: 'checkpoint' },
1932
- checkpoint_ns: 'parent-checkpoint-ns',
1933
- [SUBAGENT_PARENT_BATCH_CONFIG_KEY]: 'assistant-batch',
1934
- requestBody: { messageId: 'msg-1' },
1935
- thread_id: 'parent-thread',
1936
- user: { id: 'user_abc' },
1937
- },
1938
- });
1939
-
1940
- const configurable = getInvokeConfig()!.configurable as Record<
1941
- string,
1942
- unknown
1943
- >;
1944
- expect(configurable.__pregel_abort_signals).toBeUndefined();
1945
- expect(configurable.__pregel_call).toBeUndefined();
1946
- expect(configurable.__pregel_scratchpad).toBeUndefined();
1947
- expect(configurable.checkpoint_id).toBeUndefined();
1948
- expect(configurable.checkpoint_map).toBeUndefined();
1949
- expect(configurable.checkpoint_ns).toBeUndefined();
1950
- expect(configurable[SUBAGENT_PARENT_BATCH_CONFIG_KEY]).toBeUndefined();
1951
- expect(configurable.requestBody).toEqual({ messageId: 'msg-1' });
1952
- expect(configurable.thread_id).toBe('parent-thread');
1953
- expect(configurable.user).toEqual({ id: 'user_abc' });
1954
- });
1955
-
1956
- it('isolates child checkpoints created from different parent forks', async () => {
1957
- const invokedConfigs: Record<string, unknown>[] = [];
1958
- const invoke = jest
1959
- .fn()
1960
- .mockImplementation(
1961
- async (
1962
- _input: unknown,
1963
- config: Record<string, unknown>
1964
- ): Promise<{ messages: BaseMessage[] }> => {
1965
- invokedConfigs.push(config);
1966
- return { messages: [new AIMessage('done')] };
1967
- }
1968
- );
1969
- const executor = createExecutor({
1970
- humanInTheLoop: { enabled: true },
1971
- createChildGraph: (): StandardGraph =>
1972
- ({
1973
- createWorkflow: () => ({
1974
- getState: jest.fn().mockResolvedValue({
1975
- values: {},
1976
- next: [],
1977
- tasks: [],
1978
- }),
1979
- invoke,
1980
- }),
1981
- clearHeavyState: jest.fn(),
1982
- }) as unknown as StandardGraph,
1983
- });
1984
- const common = {
1985
- description: 'task',
1986
- subagentType: 'researcher',
1987
- threadId: 'parent-thread',
1988
- parentToolCallId: 'call_shared',
1989
- };
1990
-
1991
- await executor.execute({
1992
- ...common,
1993
- parentConfigurable: {
1994
- thread_id: 'parent-thread',
1995
- checkpoint_id: 'fork-a',
1996
- },
1997
- });
1998
- await executor.execute({
1999
- ...common,
2000
- parentConfigurable: {
2001
- thread_id: 'parent-thread',
2002
- checkpoint_id: 'fork-b',
2003
- },
2004
- });
2005
-
2006
- expect(invoke).toHaveBeenCalledTimes(2);
2007
- const childThreadIds = invokedConfigs.map(
2008
- (config) =>
2009
- (config.configurable as Record<string, unknown>).thread_id as string
2010
- );
2011
- expect(childThreadIds[0]).toMatch(/^subagent:/);
2012
- expect(childThreadIds[1]).toMatch(/^subagent:/);
2013
- expect(childThreadIds[0]).not.toBe(childThreadIds[1]);
2014
- });
2015
-
2016
- it('isolates reused tool-call IDs across assistant batches', async () => {
2017
- const invokedThreadIds: string[] = [];
2018
- const executor = createExecutor({
2019
- humanInTheLoop: { enabled: true },
2020
- createChildGraph: (): StandardGraph =>
2021
- ({
2022
- createWorkflow: () => ({
2023
- getState: jest.fn().mockResolvedValue({
2024
- values: {},
2025
- next: [],
2026
- tasks: [],
2027
- }),
2028
- invoke: jest
2029
- .fn()
2030
- .mockImplementation(
2031
- async (
2032
- _input: unknown,
2033
- invokeConfig: Record<string, unknown>
2034
- ): Promise<{ messages: BaseMessage[] }> => {
2035
- invokedThreadIds.push(
2036
- (invokeConfig.configurable as Record<string, unknown>)
2037
- .thread_id as string
2038
- );
2039
- return { messages: [new AIMessage('done')] };
2040
- }
2041
- ),
2042
- }),
2043
- clearHeavyState: jest.fn(),
2044
- }) as unknown as StandardGraph,
2045
- });
2046
- const common = {
2047
- description: 'task',
2048
- subagentType: 'researcher',
2049
- threadId: 'parent-thread',
2050
- parentToolCallId: 'call_reused',
2051
- };
2052
-
2053
- await executor.execute({
2054
- ...common,
2055
- parentConfigurable: {
2056
- thread_id: 'parent-thread',
2057
- [SUBAGENT_PARENT_BATCH_CONFIG_KEY]: 'assistant-batch-1',
2058
- },
2059
- });
2060
- await executor.execute({
2061
- ...common,
2062
- parentConfigurable: {
2063
- thread_id: 'parent-thread',
2064
- [SUBAGENT_PARENT_BATCH_CONFIG_KEY]: 'assistant-batch-2',
2065
- },
2066
- });
2067
-
2068
- expect(invokedThreadIds).toHaveLength(2);
2069
- expect(invokedThreadIds[0]).not.toBe(invokedThreadIds[1]);
2070
- });
2071
-
2072
- it('keeps ambiguous parent agent and tool-call components collision-free', async () => {
2073
- const invokedThreadIds: string[] = [];
2074
- const createChildGraph = (): StandardGraph =>
2075
- ({
2076
- createWorkflow: () => ({
2077
- getState: jest.fn().mockResolvedValue({
2078
- values: {},
2079
- next: [],
2080
- tasks: [],
2081
- }),
2082
- invoke: jest
2083
- .fn()
2084
- .mockImplementation(
2085
- async (
2086
- _input: unknown,
2087
- invokeConfig: Record<string, unknown>
2088
- ): Promise<{ messages: BaseMessage[] }> => {
2089
- invokedThreadIds.push(
2090
- (invokeConfig.configurable as Record<string, unknown>)
2091
- .thread_id as string
2092
- );
2093
- return { messages: [new AIMessage('done')] };
2094
- }
2095
- ),
2096
- }),
2097
- clearHeavyState: jest.fn(),
2098
- }) as unknown as StandardGraph;
2099
- const common = {
2100
- description: 'task',
2101
- subagentType: 'researcher',
2102
- threadId: 'parent',
2103
- parentConfigurable: { thread_id: 'parent' },
2104
- };
2105
-
2106
- await createExecutor({
2107
- checkpointer: new MemorySaver(),
2108
- humanInTheLoop: { enabled: true },
2109
- parentAgentId: 'a_b',
2110
- createChildGraph,
2111
- }).execute({ ...common, parentToolCallId: 'c' });
2112
- await createExecutor({
2113
- checkpointer: new MemorySaver(),
2114
- humanInTheLoop: { enabled: true },
2115
- parentAgentId: 'a',
2116
- createChildGraph,
2117
- }).execute({ ...common, parentToolCallId: 'b_c' });
2118
-
2119
- expect(invokedThreadIds).toHaveLength(2);
2120
- expect(invokedThreadIds[0]).not.toBe(invokedThreadIds[1]);
2121
- });
2122
-
2123
- it('retains owned child checkpoint threads after heavy-state cleanup', async () => {
2124
- const executor = createExecutor({
2125
- checkpointer: new MemorySaver(),
2126
- humanInTheLoop: { enabled: true },
2127
- createChildGraph: (): StandardGraph =>
2128
- ({
2129
- createWorkflow: () => ({
2130
- getState: jest.fn().mockResolvedValue({
2131
- values: {},
2132
- next: [],
2133
- tasks: [],
2134
- }),
2135
- invoke: jest.fn().mockResolvedValue({
2136
- messages: [new AIMessage('done')],
2137
- }),
2138
- }),
2139
- clearHeavyState: jest.fn(),
2140
- }) as unknown as StandardGraph,
2141
- });
2142
-
2143
- await executor.execute({
2144
- description: 'task',
2145
- subagentType: 'researcher',
2146
- threadId: 'parent',
2147
- parentToolCallId: 'call_owned',
2148
- });
2149
- const beforeCleanup = executor.getChildCheckpointThreadIds();
2150
- executor.clearHeavyState();
2151
-
2152
- expect(beforeCleanup).toHaveLength(1);
2153
- expect(executor.getChildCheckpointThreadIds()).toEqual(beforeCleanup);
2154
-
2155
- executor.resetCheckpointThreadIds();
2156
- expect(executor.getChildCheckpointThreadIds()).toEqual([]);
2157
- });
2158
-
2159
- it('includes checkpoint threads from active descendant graphs', async () => {
2160
- const grandchildThreadId = 'subagent:grandchild';
2161
- const executor = createExecutor({
2162
- checkpointer: new MemorySaver(),
2163
- humanInTheLoop: { enabled: true },
2164
- createChildGraph: (): StandardGraph =>
2165
- ({
2166
- createWorkflow: () => ({
2167
- getState: jest.fn().mockResolvedValue({
2168
- values: {},
2169
- next: ['child-agent'],
2170
- tasks: [],
2171
- }),
2172
- invoke: jest.fn().mockRejectedValue(
2173
- new GraphInterrupt([
2174
- {
2175
- id: 'grandchild-interrupt',
2176
- value: {
2177
- type: 'tool_approval',
2178
- action_requests: [],
2179
- review_configs: [],
2180
- },
2181
- },
2182
- ])
2183
- ),
2184
- }),
2185
- getChildCheckpointThreadIds: jest.fn(() => [grandchildThreadId]),
2186
- clearHeavyState: jest.fn(),
2187
- }) as unknown as StandardGraph,
2188
- });
2189
-
2190
- await expect(
2191
- executor.execute({
2192
- description: 'nested task',
2193
- subagentType: 'researcher',
2194
- threadId: 'parent',
2195
- parentToolCallId: 'call_child',
2196
- })
2197
- ).rejects.toBeInstanceOf(GraphInterrupt);
2198
-
2199
- expect(executor.getChildCheckpointThreadIds()).toEqual(
2200
- expect.arrayContaining([grandchildThreadId])
2201
- );
2202
- });
2203
-
2204
- it('does not require parentConfigurable (back-compat with hosts that omit it)', async () => {
2205
- const { factory, getInvokeConfig } = makeCapturingGraphFactory();
2206
- const executor = createExecutor({ createChildGraph: factory });
2207
-
2208
- await executor.execute({
2209
- description: 'task',
2210
- subagentType: 'researcher',
2211
- });
2212
-
2213
- const configurable = getInvokeConfig()!.configurable as Record<
2214
- string,
2215
- unknown
2216
- >;
2217
- expect(Object.keys(configurable)).toEqual(['thread_id']);
2218
- });
2219
- });
2220
-
2221
- describe('hooks', () => {
2222
- let capturedStart: unknown;
2223
- let capturedStop: unknown;
2224
-
2225
- beforeEach(() => {
2226
- capturedStart = undefined;
2227
- capturedStop = undefined;
2228
- });
2229
-
2230
- it('fires SubagentStart before execution', async () => {
2231
- const registry = new HookRegistry();
2232
- registry.register('SubagentStart', {
2233
- hooks: [
2234
- async (input): Promise<Record<string, never>> => {
2235
- capturedStart = input;
2236
- return {};
2237
- },
2238
- ],
2239
- });
2240
-
2241
- const { factory } = makeStubGraphFactory({
2242
- messages: [new AIMessage('done')],
2243
- });
2244
- const executor = createExecutor({
2245
- hookRegistry: registry,
2246
- createChildGraph: factory,
2247
- });
2248
-
2249
- await executor.execute({
2250
- description: 'Test task',
2251
- subagentType: 'researcher',
2252
- });
2253
-
2254
- expect(capturedStart).toBeDefined();
2255
- const input = capturedStart as Record<string, unknown>;
2256
- expect(input.hook_event_name).toBe('SubagentStart');
2257
- expect(input.parentAgentId).toBe('parent-agent');
2258
- expect(input.agentType).toBe('researcher');
2259
- });
2260
-
2261
- it('fires SubagentStop after execution', async () => {
2262
- const registry = new HookRegistry();
2263
- registry.register('SubagentStop', {
2264
- hooks: [
2265
- async (input): Promise<Record<string, never>> => {
2266
- capturedStop = input;
2267
- return {};
2268
- },
2269
- ],
2270
- });
2271
-
2272
- const { factory } = makeStubGraphFactory({
2273
- messages: [new AIMessage('done')],
2274
- });
2275
- const executor = createExecutor({
2276
- hookRegistry: registry,
2277
- createChildGraph: factory,
2278
- });
2279
-
2280
- await executor.execute({
2281
- description: 'Test task',
2282
- subagentType: 'researcher',
2283
- });
2284
-
2285
- expect(capturedStop).toBeDefined();
2286
- const input = capturedStop as Record<string, unknown>;
2287
- expect(input.hook_event_name).toBe('SubagentStop');
2288
- expect(input.agentType).toBe('researcher');
2289
- });
2290
-
2291
- it('finishes missing child lifecycle after recovering a completed checkpoint', async () => {
2292
- const stopHook = jest.fn().mockResolvedValue({});
2293
- const hookRegistry = new HookRegistry();
2294
- hookRegistry.register('SubagentStop', { hooks: [stopHook] });
2295
- const updates: SubagentUpdateEvent[] = [];
2296
- const handlerRegistry = new HandlerRegistry();
2297
- handlerRegistry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
2298
- handle: (_event, data): void => {
2299
- updates.push(data as SubagentUpdateEvent);
2300
- },
2301
- });
2302
- const invoke = jest.fn();
2303
- const updateState = jest.fn().mockResolvedValue({});
2304
- const executor = createExecutor({
2305
- humanInTheLoop: { enabled: true },
2306
- hookRegistry,
2307
- parentHandlerRegistry: handlerRegistry,
2308
- createChildGraph: (): StandardGraph =>
2309
- ({
2310
- createWorkflow: () => ({
2311
- getState: jest.fn().mockResolvedValue({
2312
- values: { messages: [new AIMessage('persisted result')] },
2313
- next: [],
2314
- tasks: [],
2315
- }),
2316
- invoke,
2317
- updateState,
2318
- }),
2319
- clearHeavyState: jest.fn(),
2320
- }) as unknown as StandardGraph,
2321
- });
2322
-
2323
- const result = await executor.execute({
2324
- description: 'recover me',
2325
- subagentType: 'researcher',
2326
- threadId: 'durable-thread',
2327
- parentToolCallId: 'call_recovered',
2328
- });
2329
-
2330
- expect(result.content).toBe('persisted result');
2331
- expect(invoke).not.toHaveBeenCalled();
2332
- expect(stopHook).toHaveBeenCalledTimes(1);
2333
- expect(updates.filter((update) => update.phase === 'stop')).toHaveLength(
2334
- 1
2335
- );
2336
- expect(updateState).toHaveBeenCalledTimes(1);
2337
- expect(updateState.mock.calls[0][1]).toMatchObject({
2338
- messages: [
2339
- {
2340
- additional_kwargs: {
2341
- __librechat_subagent_checkpoint: {
2342
- version: 1,
2343
- parentToolCallId: 'call_recovered',
2344
- lifecycleComplete: true,
2345
- },
2346
- },
2347
- },
2348
- ],
2349
- });
2350
- });
2351
-
2352
- it('SubagentStart deny blocks execution', async () => {
2353
- const registry = new HookRegistry();
2354
- registry.register('SubagentStart', {
2355
- hooks: [
2356
- async (): Promise<{ decision: 'deny'; reason: string }> => ({
2357
- decision: 'deny',
2358
- reason: 'Not authorized',
2359
- }),
2360
- ],
2361
- });
2362
-
2363
- const executor = createExecutor({ hookRegistry: registry });
2364
- const result = await executor.execute({
2365
- description: 'Blocked task',
2366
- subagentType: 'researcher',
2367
- });
2368
-
2369
- expect(result.content).toBe('Blocked: Not authorized');
2370
- expect(result.messages).toEqual([]);
2371
- });
2372
- });
2373
-
2374
- describe('event forwarding', () => {
2375
- it('emits start/stop ON_SUBAGENT_UPDATE envelopes when parentHandlerRegistry is provided', async () => {
2376
- const events: unknown[] = [];
2377
- const registry = new HandlerRegistry();
2378
- registry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
2379
- handle: (_event, data): void => {
2380
- events.push(data);
2381
- },
2382
- });
2383
-
2384
- const { factory } = makeStubGraphFactory({
2385
- messages: [new AIMessage('done')],
2386
- });
2387
- const executor = createExecutor({
2388
- createChildGraph: factory,
2389
- parentHandlerRegistry: registry,
2390
- });
2391
-
2392
- await executor.execute({
2393
- description: 'Test task',
2394
- subagentType: 'researcher',
2395
- });
2396
-
2397
- const phases = events.map((e) => (e as { phase: string }).phase);
2398
- expect(phases[0]).toBe('start');
2399
- expect(phases[phases.length - 1]).toBe('stop');
2400
- });
2401
-
2402
- it('attributes graph updates to validated payload and step-local member identities', async () => {
2403
- const updates: SubagentUpdateEvent[] = [];
2404
- const registry = new HandlerRegistry();
2405
- registry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
2406
- handle: (_event, data): void => {
2407
- updates.push(data as SubagentUpdateEvent);
2408
- },
2409
- });
2410
- const graphConfig: GraphSubagentConfig = {
2411
- kind: 'graph',
2412
- type: 'graph-team',
2413
- name: 'Graph Team',
2414
- description: 'Runs a graph.',
2415
- agents: [
2416
- makeChildInputs('entry'),
2417
- makeChildInputs('worker'),
2418
- makeChildInputs('result'),
2419
- ],
2420
- edges: [
2421
- { from: 'entry', to: 'worker', edgeType: 'direct' },
2422
- { from: 'worker', to: 'result', edgeType: 'direct' },
2423
- ],
2424
- entryAgentId: 'entry',
2425
- resultAgentId: 'result',
2426
- };
2427
- const graphFactory = (): StandardGraph =>
2428
- ({
2429
- createWorkflow: (): { invoke: jest.Mock } => ({
2430
- invoke: jest.fn().mockImplementation(async (_state, options) => {
2431
- const opts = options as { callbacks?: unknown[] };
2432
- const forwarder = (opts.callbacks ?? [])[0] as {
2433
- handleCustomEvent?: (
2434
- eventName: string,
2435
- data: unknown,
2436
- runId: string,
2437
- tags?: string[],
2438
- metadata?: Record<string, unknown>
2439
- ) => Promise<void> | void;
2440
- };
2441
- const emit = async (
2442
- eventName: string,
2443
- data: unknown,
2444
- agentId: string
2445
- ): Promise<void> => {
2446
- await forwarder.handleCustomEvent?.(
2447
- eventName,
2448
- data,
2449
- 'child-run',
2450
- [],
2451
- { agentId }
2452
- );
2453
- };
2454
-
2455
- await emit(
2456
- GraphEvents.ON_RUN_STEP,
2457
- {
2458
- id: 'step_entry',
2459
- type: StepTypes.MESSAGE_CREATION,
2460
- agentId: 'entry',
2461
- },
2462
- 'parent-agent'
2463
- );
2464
- await emit(
2465
- GraphEvents.ON_MESSAGE_DELTA,
2466
- { id: 'step_entry', delta: { content: 'entry' } },
2467
- 'parent-agent'
2468
- );
2469
- await emit(
2470
- GraphEvents.ON_REASONING_DELTA,
2471
- { id: 'step_entry', delta: { content: [] } },
2472
- 'parent-agent'
2473
- );
2474
- await emit(
2475
- GraphEvents.ON_RUN_STEP,
2476
- {
2477
- id: 'step_worker',
2478
- type: StepTypes.MESSAGE_CREATION,
2479
- agentId: 'worker',
2480
- },
2481
- 'entry'
2482
- );
2483
- await emit(
2484
- GraphEvents.ON_RUN_STEP,
2485
- {
2486
- id: 'step_spoofed',
2487
- type: StepTypes.MESSAGE_CREATION,
2488
- agentId: 'unknown-member',
2489
- },
2490
- 'worker'
2491
- );
2492
- await emit(
2493
- GraphEvents.ON_RUN_STEP_COMPLETED,
2494
- { result: { id: 'step_result', agentId: 'result' } },
2495
- 'parent-agent'
2496
- );
2497
- await emit(
2498
- GraphEvents.ON_MESSAGE_DELTA,
2499
- { id: 'step_metadata', delta: { content: 'worker' } },
2500
- 'worker'
2501
- );
2502
- return {
2503
- messages: [new AIMessage('ok')],
2504
- subagentResult: { agentId: 'result' },
2505
- };
2506
- }),
2507
- }),
2508
- clearHeavyState: jest.fn(),
2509
- }) as unknown as StandardGraph;
2510
- const executor = createExecutor({
2511
- configs: new Map([[graphConfig.type, graphConfig]]),
2512
- createChildGraphByKind: graphFactory,
2513
- parentHandlerRegistry: registry,
2514
- });
2515
-
2516
- await executor.execute({
2517
- description: 'Run the graph.',
2518
- subagentType: graphConfig.type,
2519
- });
2520
-
2521
- const activity = updates.filter(
2522
- (update) => update.phase !== 'start' && update.phase !== 'stop'
2523
- );
2524
- expect(
2525
- activity.map(({ phase, memberAgentId }) => ({
2526
- phase,
2527
- memberAgentId,
2528
- }))
2529
- ).toEqual([
2530
- { phase: 'run_step', memberAgentId: 'entry' },
2531
- { phase: 'message_delta', memberAgentId: 'entry' },
2532
- { phase: 'reasoning_delta', memberAgentId: 'entry' },
2533
- { phase: 'run_step', memberAgentId: 'worker' },
2534
- { phase: 'run_step', memberAgentId: undefined },
2535
- { phase: 'run_step_completed', memberAgentId: 'result' },
2536
- { phase: 'message_delta', memberAgentId: 'worker' },
2537
- ]);
2538
- expect(updates[0].memberAgentId).toBeUndefined();
2539
- expect(updates[updates.length - 1].memberAgentId).toBeUndefined();
2540
- });
2541
-
2542
- it('keeps toolDefinitions on child when registry has ON_TOOL_EXECUTE handler', async () => {
2543
- const registry = new HandlerRegistry();
2544
- registry.register(GraphEvents.ON_TOOL_EXECUTE, {
2545
- handle: (): void => {},
2546
- });
2547
- let observedChildInputs: AgentInputs | undefined;
2548
- const configWithDefs: ResolvedSubagentConfig = {
2549
- type: 'researcher',
2550
- name: 'Research Specialist',
2551
- description: 'Researches topics',
2552
- agentInputs: {
2553
- agentId: 'researcher',
2554
- provider: Providers.OPENAI,
2555
- toolDefinitions: [
2556
- { name: 'web', description: 'search', parameters: {} },
2557
- ],
2558
- } as AgentInputs,
2559
- };
2560
-
2561
- const executor = new SubagentExecutor({
2562
- configs: new Map([[configWithDefs.type, configWithDefs]]),
2563
- parentRunId: 'run',
2564
- parentAgentId: 'parent',
2565
- parentHandlerRegistry: registry,
2566
- createChildGraph: (input): StandardGraph => {
2567
- observedChildInputs = input.agents[0];
2568
- return {
2569
- createWorkflow: (): { invoke: jest.Mock } => ({
2570
- invoke: jest.fn().mockResolvedValue({
2571
- messages: [new AIMessage('ok')],
2572
- }),
2573
- }),
2574
- clearHeavyState: jest.fn(),
2575
- } as unknown as StandardGraph;
2576
- },
2577
- });
2578
-
2579
- await executor.execute({
2580
- description: 'find weather',
2581
- subagentType: 'researcher',
2582
- });
2583
-
2584
- expect(observedChildInputs?.toolDefinitions).toHaveLength(1);
2585
- expect(observedChildInputs?.toolDefinitions?.[0]?.name).toBe('web');
2586
- });
2587
-
2588
- it('strips toolDefinitions when registry is present but ON_TOOL_EXECUTE handler is absent', async () => {
2589
- const registry = new HandlerRegistry();
2590
- let observedChildInputs: AgentInputs | undefined;
2591
- const configWithDefs: ResolvedSubagentConfig = {
2592
- type: 'researcher',
2593
- name: 'Research Specialist',
2594
- description: 'Researches topics',
2595
- agentInputs: {
2596
- agentId: 'researcher',
2597
- provider: Providers.OPENAI,
2598
- toolDefinitions: [
2599
- { name: 'web', description: 'search', parameters: {} },
2600
- ],
2601
- } as AgentInputs,
2602
- };
2603
-
2604
- const executor = new SubagentExecutor({
2605
- configs: new Map([[configWithDefs.type, configWithDefs]]),
2606
- parentRunId: 'run',
2607
- parentAgentId: 'parent',
2608
- parentHandlerRegistry: registry,
2609
- createChildGraph: (input): StandardGraph => {
2610
- observedChildInputs = input.agents[0];
2611
- return {
2612
- createWorkflow: (): { invoke: jest.Mock } => ({
2613
- invoke: jest.fn().mockResolvedValue({
2614
- messages: [new AIMessage('ok')],
2615
- }),
2616
- }),
2617
- clearHeavyState: jest.fn(),
2618
- } as unknown as StandardGraph;
2619
- },
2620
- });
2621
-
2622
- await executor.execute({
2623
- description: 'find weather',
2624
- subagentType: 'researcher',
2625
- });
2626
-
2627
- expect(observedChildInputs?.toolDefinitions).toBeUndefined();
2628
- });
2629
-
2630
- it('forwards parentToolCallId from execute params to SubagentUpdateEvent envelopes', async () => {
2631
- const events: unknown[] = [];
2632
- const registry = new HandlerRegistry();
2633
- registry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
2634
- handle: (_event, data): void => {
2635
- events.push(data);
2636
- },
2637
- });
2638
-
2639
- const { factory } = makeStubGraphFactory({
2640
- messages: [new AIMessage('done')],
2641
- });
2642
- const executor = createExecutor({
2643
- createChildGraph: factory,
2644
- parentHandlerRegistry: registry,
2645
- });
2646
-
2647
- await executor.execute({
2648
- description: 'Task',
2649
- subagentType: 'researcher',
2650
- parentToolCallId: 'call_abc123',
2651
- });
2652
-
2653
- expect(events.length).toBeGreaterThan(0);
2654
- for (const e of events) {
2655
- expect((e as { parentToolCallId?: string }).parentToolCallId).toBe(
2656
- 'call_abc123'
2657
- );
2658
- }
2659
- });
2660
-
2661
- it('still strips toolDefinitions when no parentHandlerRegistry is provided (legacy isolation)', async () => {
2662
- let observedChildInputs: AgentInputs | undefined;
2663
- const configWithDefs: ResolvedSubagentConfig = {
2664
- type: 'researcher',
2665
- name: 'Research Specialist',
2666
- description: 'Researches topics',
2667
- agentInputs: {
2668
- agentId: 'researcher',
2669
- provider: Providers.OPENAI,
2670
- toolDefinitions: [
2671
- { name: 'web', description: 'search', parameters: {} },
2672
- ],
2673
- } as AgentInputs,
2674
- };
2675
-
2676
- const executor = new SubagentExecutor({
2677
- configs: new Map([[configWithDefs.type, configWithDefs]]),
2678
- parentRunId: 'run',
2679
- parentAgentId: 'parent',
2680
- createChildGraph: (input): StandardGraph => {
2681
- observedChildInputs = input.agents[0];
2682
- return {
2683
- createWorkflow: (): { invoke: jest.Mock } => ({
2684
- invoke: jest.fn().mockResolvedValue({
2685
- messages: [new AIMessage('ok')],
2686
- }),
2687
- }),
2688
- clearHeavyState: jest.fn(),
2689
- } as unknown as StandardGraph;
2690
- },
2691
- });
2692
-
2693
- await executor.execute({
2694
- description: 'find weather',
2695
- subagentType: 'researcher',
2696
- });
2697
-
2698
- expect(observedChildInputs?.toolDefinitions).toBeUndefined();
2699
- });
2700
-
2701
- it('accepts parentHandlerRegistry as a lazy getter', async () => {
2702
- const lazyHolder: { registry?: InstanceType<typeof HandlerRegistry> } =
2703
- {};
2704
- const events: unknown[] = [];
2705
- const { factory } = makeStubGraphFactory({
2706
- messages: [new AIMessage('done')],
2707
- });
2708
- const executor = createExecutor({
2709
- createChildGraph: factory,
2710
- parentHandlerRegistry: () => lazyHolder.registry,
2711
- });
2712
-
2713
- lazyHolder.registry = new HandlerRegistry();
2714
- lazyHolder.registry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
2715
- handle: (_event, data): void => {
2716
- events.push(data);
2717
- },
2718
- });
2719
-
2720
- await executor.execute({
2721
- description: 'Task',
2722
- subagentType: 'researcher',
2723
- });
2724
-
2725
- expect(events.length).toBeGreaterThan(0);
2726
- expect((events[0] as { phase: string }).phase).toBe('start');
2727
- });
2728
-
2729
- it('routes child ON_TOOL_EXECUTE dispatches through the parent registry', async () => {
2730
- /**
2731
- * Drives the forwarder callback the executor installs on the child's
2732
- * `workflow.invoke({ callbacks: [forwarder] })`. We capture that
2733
- * callback when the child workflow runs, then synthesize the same
2734
- * `handleCustomEvent` call that a real `ToolNode` would make when
2735
- * the child LLM emits a tool_call. If the forwarder routes correctly,
2736
- * the parent's `ON_TOOL_EXECUTE` handler receives the batch and
2737
- * resolves the promise with our canned results.
2738
- */
2739
-
2740
- const parentToolHandler = jest.fn(
2741
- async (_event: string, rawData: unknown): Promise<void> => {
2742
- const req = rawData as {
2743
- toolCalls: Array<{ id: string; name: string }>;
2744
- resolve: (results: unknown[]) => void;
2745
- };
2746
- req.resolve(
2747
- req.toolCalls.map((tc) => ({
2748
- toolCallId: tc.id,
2749
- status: 'success',
2750
- content: `ran ${tc.name}`,
2751
- }))
2752
- );
2753
- }
2754
- );
2755
-
2756
- const registry = new HandlerRegistry();
2757
- registry.register(GraphEvents.ON_TOOL_EXECUTE, {
2758
- handle: parentToolHandler,
2759
- });
2760
-
2761
- let capturedInvokeOptions: unknown;
2762
- const factory: () => StandardGraph = (): StandardGraph =>
2763
- ({
2764
- createWorkflow: (): { invoke: jest.Mock } => ({
2765
- invoke: jest.fn().mockImplementation(async (_state, options) => {
2766
- capturedInvokeOptions = options;
2767
- return { messages: [new AIMessage('ok')] };
2768
- }),
2769
- }),
2770
- clearHeavyState: jest.fn(),
2771
- }) as unknown as StandardGraph;
2772
-
2773
- const executor = createExecutor({
2774
- createChildGraph: factory,
2775
- parentHandlerRegistry: registry,
2776
- });
2777
-
2778
- await executor.execute({
2779
- description: 'Task',
2780
- subagentType: 'researcher',
2781
- parentToolCallId: 'call_parent_123',
2782
- });
2783
-
2784
- const opts = capturedInvokeOptions as
2785
- | { callbacks?: unknown[] }
2786
- | undefined;
2787
- expect(opts?.callbacks).toBeDefined();
2788
- const forwarder = (opts?.callbacks ?? [])[0] as {
2789
- handleCustomEvent?: (
2790
- eventName: string,
2791
- data: unknown,
2792
- runId: string,
2793
- tags?: string[],
2794
- metadata?: Record<string, unknown>
2795
- ) => Promise<void> | void;
2796
- };
2797
- expect(typeof forwarder.handleCustomEvent).toBe('function');
2798
-
2799
- /** Simulate the child's ToolNode emitting a real batch request. */
2800
- const resolvePromise = new Promise<
2801
- Array<{ toolCallId: string; status: string; content: string }>
2802
- >((resolve, reject) => {
2803
- const batchRequest = {
2804
- toolCalls: [{ id: 'call_child_xyz', name: 'calculator', args: {} }],
2805
- agentId: 'researcher',
2806
- resolve,
2807
- reject,
2808
- };
2809
- forwarder.handleCustomEvent?.(
2810
- GraphEvents.ON_TOOL_EXECUTE,
2811
- batchRequest,
2812
- 'child-run-id'
2813
- );
2814
- });
2815
-
2816
- const results = await resolvePromise;
2817
- expect(parentToolHandler).toHaveBeenCalledTimes(1);
2818
- expect(results).toEqual([
2819
- {
2820
- toolCallId: 'call_child_xyz',
2821
- status: 'success',
2822
- content: 'ran calculator',
2823
- },
2824
- ]);
2825
- });
2826
-
2827
- it('sanitizes ON_TOOL_EXECUTE before wrapping it in ON_SUBAGENT_UPDATE', async () => {
2828
- const toolRequests: ToolExecuteBatchRequest[] = [];
2829
- const subagentUpdates: SubagentUpdateEvent[] = [];
2830
- const registry = new HandlerRegistry();
2831
- registry.register(GraphEvents.ON_TOOL_EXECUTE, {
2832
- handle: (_event, rawData): void => {
2833
- const request = rawData as ToolExecuteBatchRequest;
2834
- toolRequests.push(request);
2835
- const results: ToolExecuteResult[] = request.toolCalls.map(
2836
- (call) => ({
2837
- toolCallId: call.id,
2838
- status: 'success',
2839
- content: `ran ${call.name}`,
2840
- })
2841
- );
2842
- request.resolve(results);
2843
- },
2844
- });
2845
- registry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
2846
- handle: (_event, rawData): void => {
2847
- subagentUpdates.push(rawData as SubagentUpdateEvent);
2848
- },
2849
- });
2850
-
2851
- let capturedInvokeOptions: unknown;
2852
- const factory: () => StandardGraph = (): StandardGraph =>
2853
- ({
2854
- createWorkflow: (): { invoke: jest.Mock } => ({
2855
- invoke: jest.fn().mockImplementation(async (_state, options) => {
2856
- capturedInvokeOptions = options;
2857
- return { messages: [new AIMessage('ok')] };
2858
- }),
2859
- }),
2860
- clearHeavyState: jest.fn(),
2861
- }) as unknown as StandardGraph;
2862
-
2863
- const executor = createExecutor({
2864
- createChildGraph: factory,
2865
- parentHandlerRegistry: registry,
2866
- });
2867
-
2868
- await executor.execute({
2869
- description: 'Task',
2870
- subagentType: 'researcher',
2871
- parentToolCallId: 'call_parent_123',
2872
- });
2873
-
2874
- const opts = capturedInvokeOptions as { callbacks?: unknown[] };
2875
- const forwarder = (opts.callbacks ?? [])[0] as {
2876
- handleCustomEvent?: (
2877
- eventName: string,
2878
- data: unknown
2879
- ) => Promise<void> | void;
2880
- };
2881
-
2882
- const batchRequest: ToolExecuteBatchRequest = {
2883
- toolCalls: [
2884
- {
2885
- id: 'call_child_xyz',
2886
- name: 'calculator',
2887
- args: { expression: '21 * 2' },
2888
- stepId: 'step_secret',
2889
- turn: 7,
2890
- },
2891
- ],
2892
- agentId: 'researcher',
2893
- userId: 'user_secret',
2894
- configurable: {
2895
- user: {
2896
- federatedTokens: {
2897
- access_token: 'access-secret',
2898
- id_token: 'id-secret',
2899
- refresh_token: 'refresh-secret',
2900
- },
2901
- },
2902
- requestBody: { currentTaskInput: 'sensitive task input' },
2903
- },
2904
- metadata: {
2905
- access_token: 'metadata-secret',
2906
- },
2907
- resolve: jest.fn(),
2908
- reject: jest.fn(),
2909
- };
2910
-
2911
- await forwarder.handleCustomEvent?.(
2912
- GraphEvents.ON_TOOL_EXECUTE,
2913
- batchRequest
2914
- );
2915
-
2916
- expect(toolRequests).toHaveLength(1);
2917
- expect(toolRequests[0].configurable).toBe(batchRequest.configurable);
2918
- expect(toolRequests[0].metadata).toBe(batchRequest.metadata);
2919
-
2920
- const toolUpdate = subagentUpdates.find(
2921
- (update) =>
2922
- update.phase === 'run_step' && update.label === 'Calling calculator'
2923
- );
2924
- expect(toolUpdate?.data).toEqual({
2925
- agentId: 'researcher',
2926
- toolCalls: [
2927
- {
2928
- id: 'call_child_xyz',
2929
- name: 'calculator',
2930
- args: { expression: '21 * 2' },
2931
- },
2932
- ],
2933
- });
2934
- const serializedUpdate = JSON.stringify(toolUpdate);
2935
- expect(serializedUpdate).not.toContain('configurable');
2936
- expect(serializedUpdate).not.toContain('metadata');
2937
- expect(serializedUpdate).not.toContain('access-secret');
2938
- expect(serializedUpdate).not.toContain('id-secret');
2939
- expect(serializedUpdate).not.toContain('refresh-secret');
2940
- expect(serializedUpdate).not.toContain('metadata-secret');
2941
- expect(serializedUpdate).not.toContain('sensitive task input');
2942
- expect(serializedUpdate).not.toContain('step_secret');
2943
- expect(serializedUpdate).not.toContain('user_secret');
2944
- });
2945
-
2946
- it('drains observational updates before stop without parallel handler publishes', async () => {
2947
- const phases: SubagentUpdateEvent['phase'][] = [];
2948
- let activePublishes = 0;
2949
- let maxActivePublishes = 0;
2950
- const registry = new HandlerRegistry();
2951
- registry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
2952
- handle: async (_event, rawData): Promise<void> => {
2953
- const update = rawData as SubagentUpdateEvent;
2954
- activePublishes += 1;
2955
- maxActivePublishes = Math.max(maxActivePublishes, activePublishes);
2956
- if (update.phase === 'message_delta') {
2957
- await new Promise((resolve) => setTimeout(resolve, 1));
2958
- }
2959
- phases.push(update.phase);
2960
- activePublishes -= 1;
2961
- },
2962
- });
2963
-
2964
- const factory: () => StandardGraph = (): StandardGraph =>
2965
- ({
2966
- createWorkflow: (): { invoke: jest.Mock } => ({
2967
- invoke: jest.fn().mockImplementation(async (_state, options) => {
2968
- const opts = options as { callbacks?: unknown[] };
2969
- const forwarder = (opts.callbacks ?? [])[0] as {
2970
- handleCustomEvent?: (
2971
- eventName: string,
2972
- data: unknown
2973
- ) => Promise<void> | void;
2974
- };
2975
- for (let index = 0; index < 5; index++) {
2976
- await forwarder.handleCustomEvent?.(
2977
- GraphEvents.ON_MESSAGE_DELTA,
2978
- {
2979
- id: `msg_${index}`,
2980
- delta: { content: [{ type: 'text', text: `${index}` }] },
2981
- }
2982
- );
2983
- }
2984
- return { messages: [new AIMessage('ok')] };
2985
- }),
2986
- }),
2987
- clearHeavyState: jest.fn(),
2988
- }) as unknown as StandardGraph;
2989
-
2990
- const executor = createExecutor({
2991
- createChildGraph: factory,
2992
- parentHandlerRegistry: registry,
2993
- });
2994
-
2995
- await executor.execute({
2996
- description: 'Task',
2997
- subagentType: 'researcher',
2998
- });
2999
-
3000
- expect(maxActivePublishes).toBe(1);
3001
- expect(phases[0]).toBe('start');
3002
- expect(phases.slice(1, 6)).toEqual([
3003
- 'message_delta',
3004
- 'message_delta',
3005
- 'message_delta',
3006
- 'message_delta',
3007
- 'message_delta',
3008
- ]);
3009
- expect(phases[phases.length - 1]).toBe('stop');
3010
- });
3011
-
3012
- it('does not let a stalled observational update handler block child completion', async () => {
3013
- jest.useFakeTimers();
3014
- try {
3015
- const registry = new HandlerRegistry();
3016
- const updateHandler = jest.fn(
3017
- (): Promise<void> => new Promise<void>(() => {})
3018
- );
3019
- registry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
3020
- handle: updateHandler,
3021
- });
3022
- const { factory } = makeStubGraphFactory({
3023
- messages: [new AIMessage('ok')],
3024
- });
3025
- const executor = createExecutor({
3026
- createChildGraph: factory,
3027
- parentHandlerRegistry: registry,
3028
- });
3029
-
3030
- const execution = executor.execute({
3031
- description: 'Task',
3032
- subagentType: 'researcher',
3033
- });
3034
- const outcome = Promise.race([
3035
- execution.then(({ content }) => content),
3036
- new Promise<string>((resolve) =>
3037
- setTimeout(() => resolve('stalled'), 20_000)
3038
- ),
3039
- ]);
3040
-
3041
- await jest.advanceTimersByTimeAsync(20_000);
3042
-
3043
- await expect(outcome).resolves.toBe('ok');
3044
- expect(updateHandler).toHaveBeenCalledTimes(2);
3045
- } finally {
3046
- jest.useRealTimers();
3047
- }
3048
- });
3049
-
3050
- it('does not let a stalled queued update block the terminal stop envelope', async () => {
3051
- jest.useFakeTimers();
3052
- try {
3053
- const phases: SubagentUpdateEvent['phase'][] = [];
3054
- const registry = new HandlerRegistry();
3055
- registry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
3056
- handle: (_event, rawData): void | Promise<void> => {
3057
- const update = rawData as SubagentUpdateEvent;
3058
- phases.push(update.phase);
3059
- if (update.phase === 'run_step') {
3060
- return new Promise<void>(() => {});
3061
- }
3062
- },
3063
- });
3064
- const factory: () => StandardGraph = (): StandardGraph =>
3065
- ({
3066
- createWorkflow: (): { invoke: jest.Mock } => ({
3067
- invoke: jest.fn().mockImplementation(async (_state, options) => {
3068
- const opts = options as { callbacks?: unknown[] };
3069
- const forwarder = (opts.callbacks ?? [])[0] as {
3070
- handleCustomEvent?: (
3071
- eventName: string,
3072
- data: unknown
3073
- ) => Promise<void> | void;
3074
- };
3075
- for (let index = 0; index < 80; index++) {
3076
- await forwarder.handleCustomEvent?.(GraphEvents.ON_RUN_STEP, {
3077
- id: `step_${index}`,
3078
- type: StepTypes.MESSAGE_CREATION,
3079
- agentId: 'researcher',
3080
- index,
3081
- });
3082
- }
3083
- return { messages: [new AIMessage('ok')] };
3084
- }),
3085
- }),
3086
- clearHeavyState: jest.fn(),
3087
- }) as unknown as StandardGraph;
3088
- const executor = createExecutor({
3089
- createChildGraph: factory,
3090
- parentHandlerRegistry: registry,
3091
- });
3092
-
3093
- const execution = executor.execute({
3094
- description: 'Task',
3095
- subagentType: 'researcher',
3096
- });
3097
- const outcome = Promise.race([
3098
- execution.then(({ content }) => content),
3099
- new Promise<string>((resolve) =>
3100
- setTimeout(() => resolve('stalled'), 20_000)
3101
- ),
3102
- ]);
3103
-
3104
- await jest.advanceTimersByTimeAsync(20_000);
3105
-
3106
- await expect(outcome).resolves.toBe('ok');
3107
- expect(phases).toEqual(['start', 'run_step', 'stop']);
3108
- } finally {
3109
- jest.useRealTimers();
3110
- }
3111
- });
3112
-
3113
- it('allowlists forwarded run step payloads before wrapping them in ON_SUBAGENT_UPDATE', async () => {
3114
- const subagentUpdates: SubagentUpdateEvent[] = [];
3115
- const registry = new HandlerRegistry();
3116
- registry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
3117
- handle: (_event, rawData): void => {
3118
- subagentUpdates.push(rawData as SubagentUpdateEvent);
3119
- },
3120
- });
3121
-
3122
- const output = 'tool output that should stay visible';
3123
- const factory: () => StandardGraph = (): StandardGraph =>
3124
- ({
3125
- createWorkflow: (): { invoke: jest.Mock } => ({
3126
- invoke: jest.fn().mockImplementation(async (_state, options) => {
3127
- const opts = options as { callbacks?: unknown[] };
3128
- const forwarder = (opts.callbacks ?? [])[0] as {
3129
- handleCustomEvent?: (
3130
- eventName: string,
3131
- data: unknown
3132
- ) => Promise<void> | void;
3133
- };
3134
- await forwarder.handleCustomEvent?.(GraphEvents.ON_RUN_STEP, {
3135
- id: 'step_1',
3136
- type: StepTypes.TOOL_CALLS,
3137
- agentId: 'researcher',
3138
- index: 0,
3139
- stepDetails: {
3140
- type: StepTypes.TOOL_CALLS,
3141
- tool_calls: [
3142
- {
3143
- id: 'call_1',
3144
- name: 'calculator',
3145
- args: { expression: '21 * 2' },
3146
- futureSecret: 'nested-step-secret',
3147
- },
3148
- ],
3149
- futureSecret: 'step-details-secret',
3150
- },
3151
- configurable: { access_token: 'access-secret' },
3152
- metadata: { refresh_token: 'refresh-secret' },
3153
- futureSecret: 'top-level-step-secret',
3154
- });
3155
- await forwarder.handleCustomEvent?.(
3156
- GraphEvents.ON_RUN_STEP_COMPLETED,
3157
- {
3158
- result: {
3159
- id: 'step_1',
3160
- index: 0,
3161
- type: 'tool_call',
3162
- tool_call: {
3163
- id: 'call_1',
3164
- name: 'calculator',
3165
- args: '{}',
3166
- output,
3167
- progress: 1,
3168
- futureSecret: 'nested-completed-secret',
3169
- },
3170
- futureSecret: 'completed-result-secret',
3171
- },
3172
- configurable: { access_token: 'access-secret' },
3173
- metadata: { refresh_token: 'refresh-secret' },
3174
- futureSecret: 'top-level-completed-secret',
3175
- }
3176
- );
3177
- return { messages: [new AIMessage('ok')] };
3178
- }),
3179
- }),
3180
- clearHeavyState: jest.fn(),
3181
- }) as unknown as StandardGraph;
3182
-
3183
- const executor = createExecutor({
3184
- createChildGraph: factory,
3185
- parentHandlerRegistry: registry,
3186
- });
3187
-
3188
- await executor.execute({
3189
- description: 'Task',
3190
- subagentType: 'researcher',
3191
- });
3192
-
3193
- const runStep = subagentUpdates.find(
3194
- (update) => update.phase === 'run_step'
3195
- );
3196
- const completedStep = subagentUpdates.find(
3197
- (update) => update.phase === 'run_step_completed'
3198
- );
3199
- expect(runStep?.data).toEqual({
3200
- id: 'step_1',
3201
- type: StepTypes.TOOL_CALLS,
3202
- agentId: 'researcher',
3203
- index: 0,
3204
- stepDetails: {
3205
- type: StepTypes.TOOL_CALLS,
3206
- tool_calls: [
3207
- {
3208
- id: 'call_1',
3209
- name: 'calculator',
3210
- args: { expression: '21 * 2' },
3211
- },
3212
- ],
3213
- },
3214
- });
3215
- expect(completedStep?.data).toEqual({
3216
- result: {
3217
- id: 'step_1',
3218
- index: 0,
3219
- type: 'tool_call',
3220
- tool_call: {
3221
- id: 'call_1',
3222
- name: 'calculator',
3223
- args: '{}',
3224
- output,
3225
- progress: 1,
3226
- },
3227
- },
3228
- });
3229
- const serialized = JSON.stringify([runStep, completedStep]);
3230
- expect(serialized).toContain(output);
3231
- expect(serialized).not.toContain('futureSecret');
3232
- expect(serialized).not.toContain('access-secret');
3233
- expect(serialized).not.toContain('refresh-secret');
3234
- expect(serialized).not.toContain('top-level-step-secret');
3235
- expect(serialized).not.toContain('nested-step-secret');
3236
- expect(serialized).not.toContain('top-level-completed-secret');
3237
- expect(serialized).not.toContain('nested-completed-secret');
3238
- });
3239
-
3240
- it('bounds queued updates under overload while preserving lifecycle envelopes', async () => {
3241
- const phases: SubagentUpdateEvent['phase'][] = [];
3242
- const completedIds: string[] = [];
3243
- let releaseFirstCompleted!: () => void;
3244
- const firstCompletedBlocked = new Promise<void>((resolve) => {
3245
- releaseFirstCompleted = resolve;
3246
- });
3247
- let markAllEmitted!: () => void;
3248
- const allEmitted = new Promise<void>((resolve) => {
3249
- markAllEmitted = resolve;
3250
- });
3251
- let blockedFirstCompleted = false;
3252
- const registry = new HandlerRegistry();
3253
- registry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
3254
- handle: async (_event, rawData): Promise<void> => {
3255
- const update = rawData as SubagentUpdateEvent;
3256
- phases.push(update.phase);
3257
- if (update.phase === 'run_step_completed') {
3258
- const data = update.data as { result?: { id?: string } };
3259
- if (data.result?.id != null) {
3260
- completedIds.push(data.result.id);
3261
- }
3262
- if (!blockedFirstCompleted) {
3263
- blockedFirstCompleted = true;
3264
- await firstCompletedBlocked;
3265
- }
3266
- }
3267
- },
3268
- });
3269
-
3270
- const factory: () => StandardGraph = (): StandardGraph =>
3271
- ({
3272
- createWorkflow: (): { invoke: jest.Mock } => ({
3273
- invoke: jest.fn().mockImplementation(async (_state, options) => {
3274
- const opts = options as { callbacks?: unknown[] };
3275
- const forwarder = (opts.callbacks ?? [])[0] as {
3276
- handleCustomEvent?: (
3277
- eventName: string,
3278
- data: unknown
3279
- ) => Promise<void> | void;
3280
- };
3281
- for (let index = 0; index < 80; index++) {
3282
- await forwarder.handleCustomEvent?.(
3283
- GraphEvents.ON_RUN_STEP_COMPLETED,
3284
- {
3285
- result: {
3286
- id: `step_${index}`,
3287
- index,
3288
- type: 'tool_call',
3289
- tool_call: {
3290
- id: `call_${index}`,
3291
- name: 'calculator',
3292
- args: '{}',
3293
- output: `${index}`,
3294
- progress: 1,
3295
- },
3296
- },
3297
- }
3298
- );
3299
- }
3300
- markAllEmitted();
3301
- return { messages: [new AIMessage('ok')] };
3302
- }),
3303
- }),
3304
- clearHeavyState: jest.fn(),
3305
- }) as unknown as StandardGraph;
3306
-
3307
- const executor = createExecutor({
3308
- createChildGraph: factory,
3309
- parentHandlerRegistry: registry,
3310
- });
3311
-
3312
- const execution = executor.execute({
3313
- description: 'Task',
3314
- subagentType: 'researcher',
3315
- });
3316
- await allEmitted;
3317
- releaseFirstCompleted();
3318
- await execution;
3319
-
3320
- expect(completedIds).toHaveLength(65);
3321
- expect(completedIds[0]).toBe('step_0');
3322
- expect(completedIds).not.toContain('step_1');
3323
- expect(completedIds).toContain('step_16');
3324
- expect(completedIds[completedIds.length - 1]).toBe('step_79');
3325
- expect(phases[0]).toBe('start');
3326
- expect(phases[phases.length - 1]).toBe('stop');
3327
- });
3328
-
3329
- it('does NOT forward ON_TOOL_EXECUTE when the parent registry has no handler (safe fallback)', async () => {
3330
- /**
3331
- * The executor strips `toolDefinitions` when the parent registry has
3332
- * no `ON_TOOL_EXECUTE` handler (see the companion strip-on-no-handler
3333
- * test). Defence-in-depth: if the LLM somehow still dispatches a tool
3334
- * call, the forwarder must not silently consume it without resolving;
3335
- * reject would be better than hang. This test confirms no handler
3336
- * is invoked on the parent side so it's clear a forwarded request
3337
- * would need separate treatment.
3338
- */
3339
-
3340
- const registry = new HandlerRegistry();
3341
- /** Only ON_SUBAGENT_UPDATE registered — no ON_TOOL_EXECUTE. */
3342
- registry.register(GraphEvents.ON_SUBAGENT_UPDATE, { handle: jest.fn() });
3343
-
3344
- let capturedInvokeOptions: unknown;
3345
- const factory: () => StandardGraph = (): StandardGraph =>
3346
- ({
3347
- createWorkflow: (): { invoke: jest.Mock } => ({
3348
- invoke: jest.fn().mockImplementation(async (_state, options) => {
3349
- capturedInvokeOptions = options;
3350
- return { messages: [new AIMessage('ok')] };
3351
- }),
3352
- }),
3353
- clearHeavyState: jest.fn(),
3354
- }) as unknown as StandardGraph;
3355
-
3356
- const executor = createExecutor({
3357
- createChildGraph: factory,
3358
- parentHandlerRegistry: registry,
3359
- });
3360
-
3361
- await executor.execute({
3362
- description: 'Task',
3363
- subagentType: 'researcher',
3364
- });
3365
-
3366
- const opts = capturedInvokeOptions as { callbacks?: unknown[] };
3367
- const forwarder = (opts.callbacks ?? [])[0] as {
3368
- handleCustomEvent?: (
3369
- eventName: string,
3370
- data: unknown
3371
- ) => Promise<void> | void;
3372
- };
3373
-
3374
- let resolved = false;
3375
- const batchRequest = {
3376
- toolCalls: [{ id: 'call_x', name: 'calculator', args: {} }],
3377
- agentId: 'researcher',
3378
- resolve: (): void => {
3379
- resolved = true;
3380
- },
3381
- reject: (): void => {},
3382
- };
3383
- await forwarder.handleCustomEvent?.(
3384
- GraphEvents.ON_TOOL_EXECUTE,
3385
- batchRequest
3386
- );
3387
-
3388
- /** No handler exists → nothing resolves the promise. This is the
3389
- * state that justifies the `keepToolDefinitions` gate: without the
3390
- * gate we'd deadlock here. The gate ensures the LLM never sees
3391
- * tools in the first place, making this scenario unreachable in
3392
- * practice — the test just documents the fallback. */
3393
- expect(resolved).toBe(false);
3394
- });
3395
-
3396
- it('emits an `error` phase envelope when the child graph throws', async () => {
3397
- const events: unknown[] = [];
3398
- const registry = new HandlerRegistry();
3399
- registry.register(GraphEvents.ON_SUBAGENT_UPDATE, {
3400
- handle: (_event, data): void => {
3401
- events.push(data);
3402
- },
3403
- });
3404
-
3405
- const executor = createExecutor({
3406
- createChildGraph: makeThrowingGraphFactory(
3407
- new Error('recursion limit')
3408
- ),
3409
- parentHandlerRegistry: registry,
3410
- });
3411
-
3412
- const result = await executor.execute({
3413
- description: 'Task',
3414
- subagentType: 'researcher',
3415
- parentToolCallId: 'call_err',
3416
- });
3417
-
3418
- expect(result.content).toContain('Subagent error: recursion limit');
3419
- const phases = events.map((e) => (e as { phase: string }).phase);
3420
- expect(phases).toContain('start');
3421
- expect(phases).toContain('error');
3422
- const errEvent = events.find(
3423
- (e) => (e as { phase: string }).phase === 'error'
3424
- ) as { data?: { message?: string }; parentToolCallId?: string };
3425
- expect(errEvent.data?.message).toContain('recursion limit');
3426
- expect(errEvent.parentToolCallId).toBe('call_err');
3427
- });
3428
- });
3429
- });
3430
-
3431
- describe('summarizeEvent', () => {
3432
- it('labels a run step tool_calls stepDetails by tool name', () => {
3433
- const label = summarizeEvent(GraphEvents.ON_RUN_STEP, {
3434
- stepDetails: {
3435
- type: 'tool_calls',
3436
- tool_calls: [{ name: 'calculator', id: 'c1' }],
3437
- },
3438
- });
3439
- expect(label).toBe('Using tool: calculator');
3440
- });
3441
-
3442
- it('joins multiple tool names on a single run step', () => {
3443
- const label = summarizeEvent(GraphEvents.ON_RUN_STEP, {
3444
- stepDetails: {
3445
- type: 'tool_calls',
3446
- tool_calls: [{ name: 'web' }, { name: 'calculator' }],
3447
- },
3448
- });
3449
- expect(label).toBe('Using tool: web, calculator');
3450
- });
3451
-
3452
- it('falls back to "Planning tool call" when tool_calls is empty', () => {
3453
- const label = summarizeEvent(GraphEvents.ON_RUN_STEP, {
3454
- stepDetails: { type: 'tool_calls', tool_calls: [] },
3455
- });
3456
- expect(label).toBe('Planning tool call');
3457
- });
3458
-
3459
- it('labels message_creation steps as "Thinking…"', () => {
3460
- const label = summarizeEvent(GraphEvents.ON_RUN_STEP, {
3461
- stepDetails: { type: 'message_creation' },
3462
- });
3463
- expect(label).toBe('Thinking…');
3464
- });
3465
-
3466
- it('labels ON_TOOL_EXECUTE with the batch of tool names', () => {
3467
- const label = summarizeEvent(GraphEvents.ON_TOOL_EXECUTE, {
3468
- toolCalls: [{ name: 'web' }, { name: 'calculator' }],
3469
- });
3470
- expect(label).toBe('Calling web, calculator');
3471
- });
3472
-
3473
- it('falls back to a generic "Calling tool" when toolCalls is empty', () => {
3474
- const label = summarizeEvent(GraphEvents.ON_TOOL_EXECUTE, {
3475
- toolCalls: [],
3476
- });
3477
- expect(label).toBe('Calling tool');
3478
- });
3479
-
3480
- it('labels completed run steps by completed tool name', () => {
3481
- const label = summarizeEvent(GraphEvents.ON_RUN_STEP_COMPLETED, {
3482
- result: { type: 'tool_call', tool_call: { name: 'calculator' } },
3483
- });
3484
- expect(label).toBe('Tool calculator complete');
3485
- });
3486
-
3487
- it('labels completed steps without a tool name as "Step complete"', () => {
3488
- const label = summarizeEvent(GraphEvents.ON_RUN_STEP_COMPLETED, {
3489
- result: { type: 'message_creation' },
3490
- });
3491
- expect(label).toBe('Step complete');
3492
- });
3493
-
3494
- it('labels ON_MESSAGE_DELTA as "Streaming…"', () => {
3495
- expect(summarizeEvent(GraphEvents.ON_MESSAGE_DELTA, {})).toBe('Streaming…');
3496
- });
3497
-
3498
- it('falls back to top-level `step.type` when `stepDetails` is absent', () => {
3499
- /**
3500
- * Covers the `step.stepDetails?.type ?? step.type ?? 'step'` chain
3501
- * when the payload uses the top-level form (no `stepDetails` wrapper).
3502
- * Exercises the second clause of the fallback so future changes to
3503
- * the resolution order fail fast.
3504
- */
3505
- expect(
3506
- summarizeEvent(GraphEvents.ON_RUN_STEP, { type: 'tool_calls' })
3507
- ).toBe('Planning tool call');
3508
- expect(
3509
- summarizeEvent(GraphEvents.ON_RUN_STEP, { type: 'message_creation' })
3510
- ).toBe('Thinking…');
3511
- });
3512
-
3513
- it('falls back to "Step: step" when neither `stepDetails.type` nor `step.type` is present', () => {
3514
- /** Exercises the final `?? 'step'` default plus the generic
3515
- * `Step: <detailType>` branch when a run step arrives with an
3516
- * unrecognized shape. */
3517
- expect(summarizeEvent(GraphEvents.ON_RUN_STEP, {})).toBe('Step: step');
3518
- });
3519
-
3520
- it('returns the event name for unknown events', () => {
3521
- expect(summarizeEvent('on_unknown_event', {})).toBe('on_unknown_event');
3522
- });
3523
- });
3524
-
3525
- describe('sanitizeForwardedSubagentUpdateData', () => {
3526
- it('preserves bounded assistant phase metadata on message-creation steps', () => {
3527
- const sanitized = sanitizeForwardedSubagentUpdateData(
3528
- GraphEvents.ON_RUN_STEP,
3529
- {
3530
- id: 'step_1',
3531
- stepDetails: {
3532
- type: StepTypes.MESSAGE_CREATION,
3533
- message_creation: {
3534
- message_id: 'message_1',
3535
- content_type: 'text',
3536
- phase: 'commentary',
3537
- futureSecret: 'nested-secret',
3538
- },
3539
- },
3540
- }
3541
- );
3542
-
3543
- expect(sanitized).toEqual({
3544
- id: 'step_1',
3545
- stepDetails: {
3546
- type: StepTypes.MESSAGE_CREATION,
3547
- message_creation: {
3548
- message_id: 'message_1',
3549
- content_type: 'text',
3550
- phase: 'commentary',
3551
- },
3552
- },
3553
- });
3554
-
3555
- expect(
3556
- sanitizeForwardedSubagentUpdateData(GraphEvents.ON_RUN_STEP, {
3557
- stepDetails: {
3558
- type: StepTypes.MESSAGE_CREATION,
3559
- message_creation: {
3560
- message_id: 'message_2',
3561
- content_type: 'image',
3562
- phase: 'internal',
3563
- },
3564
- },
3565
- })
3566
- ).toEqual({
3567
- stepDetails: {
3568
- type: StepTypes.MESSAGE_CREATION,
3569
- message_creation: { message_id: 'message_2' },
3570
- },
3571
- });
3572
- });
3573
-
3574
- it('uses an allowlist for run step payloads', () => {
3575
- const sanitized = sanitizeForwardedSubagentUpdateData(
3576
- GraphEvents.ON_RUN_STEP,
3577
- {
3578
- id: 'step_1',
3579
- type: StepTypes.TOOL_CALLS,
3580
- agentId: 'researcher',
3581
- index: 0,
3582
- stepDetails: {
3583
- type: StepTypes.TOOL_CALLS,
3584
- tool_calls: [
3585
- {
3586
- id: 'call_1',
3587
- name: 'calculator',
3588
- args: { expression: '21 * 2' },
3589
- futureSecret: 'nested-secret',
3590
- },
3591
- ],
3592
- futureSecret: 'details-secret',
3593
- },
3594
- configurable: { access_token: 'access-secret' },
3595
- metadata: { refresh_token: 'refresh-secret' },
3596
- futureSecret: 'top-level-secret',
3597
- }
3598
- );
3599
-
3600
- expect(sanitized).toEqual({
3601
- id: 'step_1',
3602
- type: StepTypes.TOOL_CALLS,
3603
- agentId: 'researcher',
3604
- index: 0,
3605
- stepDetails: {
3606
- type: StepTypes.TOOL_CALLS,
3607
- tool_calls: [
3608
- {
3609
- id: 'call_1',
3610
- name: 'calculator',
3611
- args: { expression: '21 * 2' },
3612
- },
3613
- ],
3614
- },
3615
- });
3616
- const serialized = JSON.stringify(sanitized);
3617
- expect(serialized).not.toContain('futureSecret');
3618
- expect(serialized).not.toContain('top-level-secret');
3619
- expect(serialized).not.toContain('details-secret');
3620
- expect(serialized).not.toContain('nested-secret');
3621
- expect(serialized).not.toContain('access-secret');
3622
- expect(serialized).not.toContain('refresh-secret');
3623
- });
3624
-
3625
- it('forwards run step lifecycle stamps and closed events via allowlists', () => {
3626
- const sanitizedStep = sanitizeForwardedSubagentUpdateData(
3627
- GraphEvents.ON_RUN_STEP,
3628
- {
3629
- id: 'step_1',
3630
- type: StepTypes.MESSAGE_CREATION,
3631
- index: 0,
3632
- created_at: 1_000,
3633
- status: 'in_progress',
3634
- stepDetails: {
3635
- type: StepTypes.MESSAGE_CREATION,
3636
- message_creation: { message_id: 'message_1' },
3637
- },
3638
- }
3639
- ) as { created_at?: number; status?: string };
3640
- expect(sanitizedStep.created_at).toBe(1_000);
3641
- expect(sanitizedStep.status).toBe('in_progress');
3642
-
3643
- const sanitizedClosed = sanitizeForwardedSubagentUpdateData(
3644
- GraphEvents.ON_RUN_STEP_CLOSED,
3645
- {
3646
- id: 'step_1',
3647
- index: 0,
3648
- type: StepTypes.MESSAGE_CREATION,
3649
- status: 'completed',
3650
- created_at: 1_000,
3651
- closed_at: 2_000,
3652
- runId: 'run_1',
3653
- agentId: 'researcher',
3654
- futureSecret: 'top-level-secret',
3655
- }
3656
- );
3657
- expect(sanitizedClosed).toEqual({
3658
- id: 'step_1',
3659
- index: 0,
3660
- type: StepTypes.MESSAGE_CREATION,
3661
- status: 'completed',
3662
- created_at: 1_000,
3663
- closed_at: 2_000,
3664
- runId: 'run_1',
3665
- agentId: 'researcher',
3666
- });
3667
- expect(JSON.stringify(sanitizedClosed)).not.toContain('top-level-secret');
3668
- });
3669
-
3670
- it('keeps completed tool output while stripping operational fields', () => {
3671
- const output = 'x'.repeat(10_000);
3672
- const sanitized = sanitizeForwardedSubagentUpdateData(
3673
- GraphEvents.ON_RUN_STEP_COMPLETED,
3674
- {
3675
- result: {
3676
- id: 'step_1',
3677
- index: 0,
3678
- type: 'tool_call',
3679
- tool_call: {
3680
- id: 'call_1',
3681
- name: 'list_tables_mcp_ClickHouse',
3682
- args: '{}',
3683
- output,
3684
- progress: 1,
3685
- futureSecret: 'nested-secret',
3686
- },
3687
- futureSecret: 'result-secret',
3688
- },
3689
- configurable: {
3690
- user: {
3691
- federatedTokens: {
3692
- access_token: 'access-secret',
3693
- },
3694
- },
3695
- },
3696
- metadata: {
3697
- refresh_token: 'refresh-secret',
3698
- },
3699
- futureSecret: 'top-level-secret',
3700
- }
3701
- );
3702
-
3703
- expect(sanitized).toEqual({
3704
- result: {
3705
- id: 'step_1',
3706
- index: 0,
3707
- type: 'tool_call',
3708
- tool_call: {
3709
- id: 'call_1',
3710
- name: 'list_tables_mcp_ClickHouse',
3711
- args: '{}',
3712
- output,
3713
- progress: 1,
3714
- },
3715
- },
3716
- });
3717
- const serialized = JSON.stringify(sanitized);
3718
- expect(serialized).toContain(output);
3719
- expect(serialized).not.toContain('futureSecret');
3720
- expect(serialized).not.toContain('top-level-secret');
3721
- expect(serialized).not.toContain('result-secret');
3722
- expect(serialized).not.toContain('nested-secret');
3723
- expect(serialized).not.toContain('configurable');
3724
- expect(serialized).not.toContain('metadata');
3725
- expect(serialized).not.toContain('access-secret');
3726
- expect(serialized).not.toContain('refresh-secret');
3727
- });
3728
- });