@illuma-ai/agents 1.1.21 → 1.1.22

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 (241) hide show
  1. package/dist/cjs/graphs/Graph.cjs +12 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +85 -1
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/run.cjs +20 -9
  6. package/dist/cjs/run.cjs.map +1 -1
  7. package/dist/esm/graphs/Graph.mjs +12 -1
  8. package/dist/esm/graphs/Graph.mjs.map +1 -1
  9. package/dist/esm/graphs/MultiAgentGraph.mjs +85 -1
  10. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  11. package/dist/esm/run.mjs +20 -9
  12. package/dist/esm/run.mjs.map +1 -1
  13. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  14. package/package.json +1 -1
  15. package/src/graphs/Graph.ts +12 -1
  16. package/src/graphs/MultiAgentGraph.ts +105 -1
  17. package/src/graphs/__tests__/multi-agent-delegate.test.ts +191 -0
  18. package/src/run.ts +20 -11
  19. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  20. package/src/agents/AgentContext.js +0 -782
  21. package/src/agents/AgentContext.test.js +0 -421
  22. package/src/agents/__tests__/AgentContext.test.js +0 -678
  23. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  24. package/src/common/enum.js +0 -192
  25. package/src/common/index.js +0 -3
  26. package/src/events.js +0 -166
  27. package/src/graphs/Graph.js +0 -1857
  28. package/src/graphs/MultiAgentGraph.js +0 -1092
  29. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  30. package/src/graphs/__tests__/structured-output.test.js +0 -144
  31. package/src/graphs/contextManagement.e2e.test.js +0 -718
  32. package/src/graphs/contextManagement.test.js +0 -485
  33. package/src/graphs/handoffValidation.test.js +0 -276
  34. package/src/graphs/index.js +0 -3
  35. package/src/index.js +0 -28
  36. package/src/instrumentation.js +0 -21
  37. package/src/llm/anthropic/index.js +0 -319
  38. package/src/llm/anthropic/types.js +0 -46
  39. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  40. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  41. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  42. package/src/llm/anthropic/utils/tools.js +0 -25
  43. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  44. package/src/llm/bedrock/index.js +0 -303
  45. package/src/llm/bedrock/types.js +0 -2
  46. package/src/llm/bedrock/utils/index.js +0 -6
  47. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  48. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  49. package/src/llm/fake.js +0 -92
  50. package/src/llm/google/index.js +0 -215
  51. package/src/llm/google/types.js +0 -12
  52. package/src/llm/google/utils/common.js +0 -670
  53. package/src/llm/google/utils/tools.js +0 -111
  54. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  55. package/src/llm/openai/index.js +0 -1033
  56. package/src/llm/openai/types.js +0 -2
  57. package/src/llm/openai/utils/index.js +0 -756
  58. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  59. package/src/llm/openrouter/index.js +0 -261
  60. package/src/llm/openrouter/reasoning.test.js +0 -181
  61. package/src/llm/providers.js +0 -36
  62. package/src/llm/text.js +0 -65
  63. package/src/llm/vertexai/index.js +0 -402
  64. package/src/messages/__tests__/tools.test.js +0 -392
  65. package/src/messages/cache.js +0 -404
  66. package/src/messages/cache.test.js +0 -1167
  67. package/src/messages/content.js +0 -48
  68. package/src/messages/content.test.js +0 -314
  69. package/src/messages/core.js +0 -359
  70. package/src/messages/ensureThinkingBlock.test.js +0 -997
  71. package/src/messages/format.js +0 -973
  72. package/src/messages/formatAgentMessages.test.js +0 -2278
  73. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  74. package/src/messages/formatMessage.test.js +0 -608
  75. package/src/messages/ids.js +0 -18
  76. package/src/messages/index.js +0 -9
  77. package/src/messages/labelContentByAgent.test.js +0 -725
  78. package/src/messages/prune.js +0 -438
  79. package/src/messages/reducer.js +0 -60
  80. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  81. package/src/messages/summarize.js +0 -146
  82. package/src/messages/summarize.test.js +0 -332
  83. package/src/messages/tools.js +0 -90
  84. package/src/mockStream.js +0 -81
  85. package/src/prompts/collab.js +0 -7
  86. package/src/prompts/index.js +0 -3
  87. package/src/prompts/taskmanager.js +0 -58
  88. package/src/run.js +0 -427
  89. package/src/schemas/index.js +0 -3
  90. package/src/schemas/schema-preparation.test.js +0 -370
  91. package/src/schemas/validate.js +0 -314
  92. package/src/schemas/validate.test.js +0 -264
  93. package/src/scripts/abort.js +0 -127
  94. package/src/scripts/ant_web_search.js +0 -130
  95. package/src/scripts/ant_web_search_edge_case.js +0 -133
  96. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  97. package/src/scripts/args.js +0 -41
  98. package/src/scripts/bedrock-cache-debug.js +0 -186
  99. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  100. package/src/scripts/bedrock-merge-test.js +0 -80
  101. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  102. package/src/scripts/caching.js +0 -106
  103. package/src/scripts/cli.js +0 -152
  104. package/src/scripts/cli2.js +0 -119
  105. package/src/scripts/cli3.js +0 -163
  106. package/src/scripts/cli4.js +0 -165
  107. package/src/scripts/cli5.js +0 -165
  108. package/src/scripts/code_exec.js +0 -171
  109. package/src/scripts/code_exec_files.js +0 -180
  110. package/src/scripts/code_exec_multi_session.js +0 -185
  111. package/src/scripts/code_exec_ptc.js +0 -265
  112. package/src/scripts/code_exec_session.js +0 -217
  113. package/src/scripts/code_exec_simple.js +0 -120
  114. package/src/scripts/content.js +0 -111
  115. package/src/scripts/empty_input.js +0 -125
  116. package/src/scripts/handoff-test.js +0 -96
  117. package/src/scripts/image.js +0 -138
  118. package/src/scripts/memory.js +0 -83
  119. package/src/scripts/multi-agent-chain.js +0 -271
  120. package/src/scripts/multi-agent-conditional.js +0 -185
  121. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  122. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  123. package/src/scripts/multi-agent-parallel-start.js +0 -214
  124. package/src/scripts/multi-agent-parallel.js +0 -346
  125. package/src/scripts/multi-agent-sequence.js +0 -184
  126. package/src/scripts/multi-agent-supervisor.js +0 -324
  127. package/src/scripts/multi-agent-test.js +0 -147
  128. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  129. package/src/scripts/parallel-full-metadata-test.js +0 -176
  130. package/src/scripts/parallel-tools-test.js +0 -256
  131. package/src/scripts/programmatic_exec.js +0 -277
  132. package/src/scripts/programmatic_exec_agent.js +0 -168
  133. package/src/scripts/search.js +0 -118
  134. package/src/scripts/sequential-full-metadata-test.js +0 -143
  135. package/src/scripts/simple.js +0 -174
  136. package/src/scripts/single-agent-metadata-test.js +0 -152
  137. package/src/scripts/stream.js +0 -113
  138. package/src/scripts/test-custom-prompt-key.js +0 -132
  139. package/src/scripts/test-handoff-input.js +0 -143
  140. package/src/scripts/test-handoff-preamble.js +0 -227
  141. package/src/scripts/test-handoff-steering.js +0 -353
  142. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  143. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  144. package/src/scripts/test-parallel-handoffs.js +0 -229
  145. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  146. package/src/scripts/test-thinking-handoff.js +0 -132
  147. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  148. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  149. package/src/scripts/test-tools-before-handoff.js +0 -187
  150. package/src/scripts/test_code_api.js +0 -263
  151. package/src/scripts/thinking-bedrock.js +0 -128
  152. package/src/scripts/thinking-vertexai.js +0 -130
  153. package/src/scripts/thinking.js +0 -134
  154. package/src/scripts/tool_search.js +0 -114
  155. package/src/scripts/tools.js +0 -125
  156. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  157. package/src/specs/agent-handoffs.test.js +0 -924
  158. package/src/specs/anthropic.simple.test.js +0 -287
  159. package/src/specs/azure.simple.test.js +0 -381
  160. package/src/specs/cache.simple.test.js +0 -282
  161. package/src/specs/custom-event-await.test.js +0 -148
  162. package/src/specs/deepseek.simple.test.js +0 -189
  163. package/src/specs/emergency-prune.test.js +0 -308
  164. package/src/specs/moonshot.simple.test.js +0 -237
  165. package/src/specs/observability.integration.test.js +0 -1337
  166. package/src/specs/openai.simple.test.js +0 -233
  167. package/src/specs/openrouter.simple.test.js +0 -202
  168. package/src/specs/prune.test.js +0 -733
  169. package/src/specs/reasoning.test.js +0 -144
  170. package/src/specs/spec.utils.js +0 -4
  171. package/src/specs/thinking-handoff.test.js +0 -486
  172. package/src/specs/thinking-prune.test.js +0 -600
  173. package/src/specs/token-distribution-edge-case.test.js +0 -246
  174. package/src/specs/token-memoization.test.js +0 -32
  175. package/src/specs/tokens.test.js +0 -49
  176. package/src/specs/tool-error.test.js +0 -139
  177. package/src/splitStream.js +0 -204
  178. package/src/splitStream.test.js +0 -504
  179. package/src/stream.js +0 -650
  180. package/src/stream.test.js +0 -225
  181. package/src/test/mockTools.js +0 -340
  182. package/src/tools/BrowserTools.js +0 -245
  183. package/src/tools/Calculator.js +0 -38
  184. package/src/tools/Calculator.test.js +0 -225
  185. package/src/tools/CodeExecutor.js +0 -233
  186. package/src/tools/ProgrammaticToolCalling.js +0 -602
  187. package/src/tools/StreamingToolCallBuffer.js +0 -179
  188. package/src/tools/ToolNode.js +0 -930
  189. package/src/tools/ToolSearch.js +0 -904
  190. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  191. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  192. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  193. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  194. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  195. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  196. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  197. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  198. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  199. package/src/tools/__tests__/handlers.test.js +0 -799
  200. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  201. package/src/tools/handlers.js +0 -306
  202. package/src/tools/schema.js +0 -25
  203. package/src/tools/search/anthropic.js +0 -34
  204. package/src/tools/search/content.js +0 -116
  205. package/src/tools/search/content.test.js +0 -133
  206. package/src/tools/search/firecrawl.js +0 -173
  207. package/src/tools/search/format.js +0 -198
  208. package/src/tools/search/highlights.js +0 -241
  209. package/src/tools/search/index.js +0 -3
  210. package/src/tools/search/jina-reranker.test.js +0 -106
  211. package/src/tools/search/rerankers.js +0 -165
  212. package/src/tools/search/schema.js +0 -102
  213. package/src/tools/search/search.js +0 -561
  214. package/src/tools/search/serper-scraper.js +0 -126
  215. package/src/tools/search/test.js +0 -129
  216. package/src/tools/search/tool.js +0 -453
  217. package/src/tools/search/types.js +0 -2
  218. package/src/tools/search/utils.js +0 -59
  219. package/src/types/graph.js +0 -24
  220. package/src/types/graph.test.js +0 -192
  221. package/src/types/index.js +0 -7
  222. package/src/types/llm.js +0 -2
  223. package/src/types/messages.js +0 -2
  224. package/src/types/run.js +0 -2
  225. package/src/types/stream.js +0 -2
  226. package/src/types/tools.js +0 -2
  227. package/src/utils/contextAnalytics.js +0 -79
  228. package/src/utils/contextAnalytics.test.js +0 -166
  229. package/src/utils/events.js +0 -26
  230. package/src/utils/graph.js +0 -11
  231. package/src/utils/handlers.js +0 -65
  232. package/src/utils/index.js +0 -10
  233. package/src/utils/llm.js +0 -21
  234. package/src/utils/llmConfig.js +0 -205
  235. package/src/utils/logging.js +0 -37
  236. package/src/utils/misc.js +0 -51
  237. package/src/utils/run.js +0 -69
  238. package/src/utils/schema.js +0 -21
  239. package/src/utils/title.js +0 -119
  240. package/src/utils/tokens.js +0 -92
  241. package/src/utils/toonFormat.js +0 -379
@@ -1,930 +0,0 @@
1
- import { ToolMessage, isAIMessage, isBaseMessage, } from '@langchain/core/messages';
2
- import { END, Send, Command, isCommand, isGraphInterrupt, } from '@langchain/langgraph';
3
- import { RunnableCallable } from '@/utils';
4
- import { processToolOutput } from '@/utils/toonFormat';
5
- import { safeDispatchCustomEvent } from '@/utils/events';
6
- import { Constants, GraphEvents } from '@/common';
7
- /**
8
- * Helper to check if a value is a Send object
9
- */
10
- function isSend(value) {
11
- return value instanceof Send;
12
- }
13
- /**
14
- * Extract text content from a ToolMessage content field.
15
- * Handles both string and MessageContentComplex[] formats.
16
- * For array content (e.g., from content_and_artifact tools), extracts text from text blocks.
17
- */
18
- function extractStringContent(content) {
19
- // Already a string - return as is
20
- if (typeof content === 'string') {
21
- return content;
22
- }
23
- // Array of content blocks - extract text from each
24
- if (Array.isArray(content)) {
25
- const textParts = [];
26
- for (const block of content) {
27
- if (typeof block === 'string') {
28
- textParts.push(block);
29
- }
30
- else if (block != null && typeof block === 'object') {
31
- // Handle {type: 'text', text: '...'} format
32
- const obj = block;
33
- if (obj.type === 'text' && typeof obj.text === 'string') {
34
- textParts.push(obj.text);
35
- }
36
- else if (typeof obj.text === 'string') {
37
- // Just has 'text' property
38
- textParts.push(obj.text);
39
- }
40
- }
41
- }
42
- if (textParts.length > 0) {
43
- return textParts.join('\n');
44
- }
45
- }
46
- // Fallback: stringify whatever it is
47
- return JSON.stringify(content);
48
- }
49
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
50
- export class ToolNode extends RunnableCallable {
51
- toolMap;
52
- loadRuntimeTools;
53
- handleToolErrors = true;
54
- trace = false;
55
- toolCallStepIds;
56
- errorHandler;
57
- toolUsageCount;
58
- /** Maps toolCallId → turn captured in runTool, used by handleRunToolCompletions */
59
- toolCallTurns = new Map();
60
- /** Tool registry for filtering (lazy computation of programmatic maps) */
61
- toolRegistry;
62
- /** Cached programmatic tools (computed once on first PTC call) */
63
- programmaticCache;
64
- /** Reference to Graph's sessions map for automatic session injection */
65
- sessions;
66
- /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */
67
- eventDrivenMode = false;
68
- /** Agent ID for event-driven mode */
69
- agentId;
70
- /** Tool names that bypass event dispatch and execute directly (e.g., graph-managed handoff tools) */
71
- directToolNames;
72
- /** HITL tool approval configuration */
73
- toolApprovalConfig;
74
- /** Buffer for recovering truncated tool call arguments from streaming data */
75
- streamingToolCallBuffer;
76
- constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, agentId, directToolNames, streamingToolCallBuffer, toolApprovalConfig, }) {
77
- super({ name, tags, func: (input, config) => this.run(input, config) });
78
- this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));
79
- this.toolCallStepIds = toolCallStepIds;
80
- this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;
81
- this.loadRuntimeTools = loadRuntimeTools;
82
- this.errorHandler = errorHandler;
83
- this.toolUsageCount = new Map();
84
- this.toolRegistry = toolRegistry;
85
- this.sessions = sessions;
86
- this.eventDrivenMode = eventDrivenMode ?? false;
87
- this.agentId = agentId;
88
- this.directToolNames = directToolNames;
89
- this.streamingToolCallBuffer = streamingToolCallBuffer;
90
- this.toolApprovalConfig = toolApprovalConfig;
91
- }
92
- /**
93
- * Returns cached programmatic tools, computing once on first access.
94
- * Single iteration builds both toolMap and toolDefs simultaneously.
95
- */
96
- getProgrammaticTools() {
97
- if (this.programmaticCache)
98
- return this.programmaticCache;
99
- const toolMap = new Map();
100
- const toolDefs = [];
101
- if (this.toolRegistry) {
102
- for (const [name, toolDef] of this.toolRegistry) {
103
- if ((toolDef.allowed_callers ?? ['direct']).includes('code_execution')) {
104
- toolDefs.push(toolDef);
105
- const tool = this.toolMap.get(name);
106
- if (tool)
107
- toolMap.set(name, tool);
108
- }
109
- }
110
- }
111
- this.programmaticCache = { toolMap, toolDefs };
112
- return this.programmaticCache;
113
- }
114
- /**
115
- * Returns a snapshot of the current tool usage counts.
116
- * @returns A ReadonlyMap where keys are tool names and values are their usage counts.
117
- */
118
- getToolUsageCounts() {
119
- return new Map(this.toolUsageCount); // Return a copy
120
- }
121
- /**
122
- * Evaluates whether a tool call requires human approval.
123
- * Returns true if approval is needed, false otherwise.
124
- * Does NOT perform the actual approval flow - that's handled by requestApproval().
125
- */
126
- requiresApproval(toolName, args) {
127
- if (!this.toolApprovalConfig) {
128
- return false;
129
- }
130
- const { defaultPolicy, overrides, executionContext } = this.toolApprovalConfig;
131
- // Scheduled and browser extension executions bypass all approval checks
132
- // Browser extension has no HITL UI — approval is handled by the extension's own UX
133
- if (executionContext === 'scheduled' || executionContext === 'browser') {
134
- return false;
135
- }
136
- // Determine the effective policy for this tool
137
- const toolOverride = overrides?.[toolName];
138
- const effectivePolicy = toolOverride ?? defaultPolicy ?? 'always';
139
- // Evaluate whether approval is required
140
- if (effectivePolicy === 'always') {
141
- return true;
142
- }
143
- else if (effectivePolicy === 'never') {
144
- return false;
145
- }
146
- else {
147
- // Custom function - evaluate with tool name and args
148
- return effectivePolicy(toolName, args);
149
- }
150
- }
151
- /**
152
- * Requests human approval for a tool call via event dispatch.
153
- * Dispatches an ON_TOOL_APPROVAL_REQUIRED event and waits for the host
154
- * to resolve the promise with an approval response.
155
- *
156
- * This uses the same pattern as ON_TOOL_EXECUTE: a promise-based event
157
- * dispatch where the host calls resolve/reject when the human responds.
158
- *
159
- * @param call - The tool call requiring approval
160
- * @param config - The runnable config for event dispatch
161
- * @returns The approval response from the human
162
- */
163
- async requestApproval(call, config) {
164
- const approvalRequest = {
165
- type: 'tool_approval_required',
166
- toolCallId: call.id ?? '',
167
- toolName: call.name,
168
- toolArgs: call.args,
169
- agentId: this.agentId,
170
- description: `Tool "${call.name}" wants to execute with the provided arguments.`,
171
- };
172
- return new Promise((resolve, reject) => {
173
- safeDispatchCustomEvent(GraphEvents.ON_TOOL_APPROVAL_REQUIRED, {
174
- ...approvalRequest,
175
- resolve,
176
- reject,
177
- }, config);
178
- });
179
- }
180
- /**
181
- * Runs a single tool call with error handling
182
- */
183
- async runTool(call, config) {
184
- const tool = this.toolMap.get(call.name);
185
- try {
186
- if (tool === undefined) {
187
- throw new Error(`Tool "${call.name}" not found.`);
188
- }
189
- const turn = this.toolUsageCount.get(call.name) ?? 0;
190
- this.toolUsageCount.set(call.name, turn + 1);
191
- if (call.id != null && call.id !== '') {
192
- this.toolCallTurns.set(call.id, turn);
193
- }
194
- let args = call.args;
195
- const stepId = this.toolCallStepIds?.get(call.id);
196
- // Recover truncated tool call arguments from the streaming buffer.
197
- // When max_tokens truncates a tool call mid-JSON, parsePartialJson may lose
198
- // content that was already streamed to the UI. The buffer has the raw accumulated
199
- // arg string, so we can extract field values that were dropped.
200
- if (call.id && this.streamingToolCallBuffer?.has(call.id)) {
201
- args = this.recoverTruncatedArgs(call.name, call.id, args);
202
- this.streamingToolCallBuffer.clear(call.id);
203
- }
204
- // Build invoke params - LangChain extracts non-schema fields to config.toolCall
205
- let invokeParams = {
206
- ...call,
207
- args,
208
- type: 'tool_call',
209
- stepId,
210
- turn,
211
- };
212
- // Inject runtime data for special tools (becomes available at config.toolCall)
213
- if (call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {
214
- const { toolMap, toolDefs } = this.getProgrammaticTools();
215
- invokeParams = {
216
- ...invokeParams,
217
- toolMap,
218
- toolDefs,
219
- };
220
- }
221
- else if (call.name === Constants.TOOL_SEARCH) {
222
- invokeParams = {
223
- ...invokeParams,
224
- toolRegistry: this.toolRegistry,
225
- };
226
- }
227
- /**
228
- * Inject session context for code execution tools when available.
229
- * Each file uses its own session_id (supporting multi-session file tracking).
230
- * Both session_id and _injected_files are injected directly to invokeParams
231
- * (not inside args) so they bypass Zod schema validation and reach config.toolCall.
232
- *
233
- * session_id is always injected when available (even without tracked files)
234
- * so the CodeExecutor can fall back to the /files endpoint for session continuity.
235
- */
236
- if (call.name === Constants.EXECUTE_CODE ||
237
- call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {
238
- const codeSession = this.sessions?.get(Constants.EXECUTE_CODE);
239
- if (codeSession != null && codeSession.session_id !== '') {
240
- /**
241
- * Always inject session_id so retries reuse the same workspace.
242
- * Also inject file refs when files exist from previous executions.
243
- */
244
- invokeParams = {
245
- ...invokeParams,
246
- session_id: codeSession.session_id,
247
- };
248
- if (codeSession.files != null && codeSession.files.length > 0) {
249
- /**
250
- * Convert tracked files to CodeEnvFile format for the API.
251
- * Each file uses its own session_id (set when file was created).
252
- * This supports files from multiple parallel/sequential executions.
253
- */
254
- const fileRefs = codeSession.files.map((file) => ({
255
- session_id: file.session_id ?? codeSession.session_id,
256
- id: file.id,
257
- name: file.name,
258
- }));
259
- invokeParams = {
260
- ...invokeParams,
261
- _injected_files: fileRefs,
262
- };
263
- }
264
- }
265
- }
266
- // ========================================================================
267
- // HITL: Check if this tool requires human approval before execution.
268
- // Uses event-driven pattern: dispatches ON_TOOL_APPROVAL_REQUIRED event
269
- // and waits for the host to resolve/reject with a ToolApprovalResponse.
270
- // ========================================================================
271
- if (this.requiresApproval(call.name, call.args)) {
272
- const approvalResponse = await this.requestApproval(call, config);
273
- if (!approvalResponse.approved) {
274
- // Human denied the tool call - return a denial message
275
- return new ToolMessage({
276
- status: 'error',
277
- content: `Tool call "${call.name}" was denied by the user.${approvalResponse.feedback != null && approvalResponse.feedback !== '' ? ` Reason: ${approvalResponse.feedback}` : ''} Please acknowledge the denial and proceed without executing this tool.`,
278
- name: call.name,
279
- tool_call_id: call.id ?? '',
280
- });
281
- }
282
- // Human approved - optionally use modified args
283
- if (approvalResponse.modifiedArgs) {
284
- invokeParams = {
285
- ...invokeParams,
286
- args: approvalResponse.modifiedArgs,
287
- };
288
- }
289
- }
290
- const output = await tool.invoke(invokeParams, config);
291
- // Handle Command outputs directly
292
- if (isCommand(output)) {
293
- return output;
294
- }
295
- // ========================================================================
296
- // TOOL OUTPUT PROCESSING - Single point for all tools (MCP and non-MCP)
297
- // 1. Extract string content from any output format
298
- // 2. Apply TOON conversion if content contains JSON
299
- // 3. Apply truncation if still too large
300
- // 4. Return ToolMessage with processed string content
301
- // ========================================================================
302
- // Step 1: Extract string content from the output
303
- let rawContent;
304
- if (isBaseMessage(output) && output._getType() === 'tool') {
305
- const toolMsg = output;
306
- rawContent = extractStringContent(toolMsg.content);
307
- }
308
- else {
309
- rawContent = extractStringContent(output);
310
- }
311
- // Step 2 & 3: Apply TOON conversion and truncation
312
- // Skip TOON for content_tool — its output is line-numbered source code.
313
- // TOON corrupts embedded JSON in source files, causing edit (str_replace) failures
314
- // because the agent sees TOON-transformed content but strReplace matches original.
315
- const isContentTool = call.name === 'content_tool';
316
- const processed = processToolOutput(rawContent, {
317
- maxLength: 100000, // 100K char limit
318
- enableToon: !isContentTool,
319
- minSizeForToon: 1000,
320
- minReductionPercent: 10, // Only apply TOON when clearly beneficial
321
- });
322
- // Step 4: Return ToolMessage with processed string content
323
- if (isBaseMessage(output) && output._getType() === 'tool') {
324
- const toolMsg = output;
325
- return new ToolMessage({
326
- status: toolMsg.status,
327
- name: toolMsg.name,
328
- content: processed.content,
329
- tool_call_id: toolMsg.tool_call_id,
330
- });
331
- }
332
- else {
333
- return new ToolMessage({
334
- status: 'success',
335
- name: tool.name,
336
- content: processed.content,
337
- tool_call_id: call.id,
338
- });
339
- }
340
- }
341
- catch (_e) {
342
- const e = _e;
343
- if (!this.handleToolErrors) {
344
- throw e;
345
- }
346
- if (isGraphInterrupt(e)) {
347
- throw e;
348
- }
349
- if (this.errorHandler) {
350
- try {
351
- await this.errorHandler({
352
- error: e,
353
- id: call.id,
354
- name: call.name,
355
- input: call.args,
356
- }, config.metadata);
357
- }
358
- catch (handlerError) {
359
- // eslint-disable-next-line no-console
360
- console.error('Error in errorHandler:', {
361
- toolName: call.name,
362
- toolCallId: call.id,
363
- toolArgs: call.args,
364
- stepId: this.toolCallStepIds?.get(call.id),
365
- turn: this.toolUsageCount.get(call.name),
366
- originalError: {
367
- message: e.message,
368
- stack: e.stack ?? undefined,
369
- },
370
- handlerError: handlerError instanceof Error
371
- ? {
372
- message: handlerError.message,
373
- stack: handlerError.stack ?? undefined,
374
- }
375
- : {
376
- message: String(handlerError),
377
- stack: undefined,
378
- },
379
- });
380
- }
381
- }
382
- return new ToolMessage({
383
- status: 'error',
384
- content: `Error: ${e.message}\n Please fix your mistakes.`,
385
- name: call.name,
386
- tool_call_id: call.id ?? '',
387
- });
388
- }
389
- }
390
- /**
391
- * Recover truncated tool call arguments using the raw streaming buffer.
392
- *
393
- * When parsePartialJson drops content (e.g., a large "content" field truncated
394
- * at max_tokens), this method extracts the field value from the raw accumulated
395
- * arg string and merges it back into the parsed args object.
396
- *
397
- * This is generic — it checks ALL string fields in the raw buffer, not just
398
- * content_tool fields. Any tool with a truncated string value benefits.
399
- */
400
- /**
401
- * Recover truncated tool call arguments using the raw streaming buffer.
402
- *
403
- * Strategy:
404
- * 1. If args are completely empty → try parsePartialJson on the raw buffer
405
- * 2. Otherwise → field-level recovery: extract missing fields from raw buffer
406
- *
407
- * @param toolName - Tool name (for logging)
408
- * @param toolCallId - The tool call ID
409
- * @param args - The parsed args (potentially incomplete from parsePartialJson)
410
- * @returns The args with recovered fields merged in
411
- */
412
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
413
- recoverTruncatedArgs(toolName, toolCallId, args) {
414
- if (!this.streamingToolCallBuffer)
415
- return args;
416
- const rawArgs = this.streamingToolCallBuffer.getRawArgs(toolCallId);
417
- if (!rawArgs)
418
- return args;
419
- const rawLen = rawArgs.length;
420
- // If args is completely empty (JSON parsing aborted before any key),
421
- // attempt to parse the raw accumulated string
422
- if (args == null || (typeof args === 'object' && Object.keys(args).length === 0)) {
423
- try {
424
- const { parsePartialJson } = require('@langchain/core/utils/json');
425
- const recovered = parsePartialJson(rawArgs);
426
- if (recovered != null && typeof recovered === 'object' && Object.keys(recovered).length > 0) {
427
- // eslint-disable-next-line no-console
428
- console.warn(`[TruncationRecovery] Tool=${toolName}, callId=${toolCallId}, rawBufferLen=${rawLen}, ` +
429
- `parsedFields=[], recoveredFields=[${Object.keys(recovered).join(',')}] (full parse)`);
430
- return recovered;
431
- }
432
- }
433
- catch {
434
- // parsePartialJson failed — fall through to field-level extraction
435
- }
436
- }
437
- // Field-level recovery: extract missing fields from the raw buffer
438
- const parsedArgs = typeof args === 'object' ? { ...args } : {};
439
- const recoveredFields = [];
440
- // Extract field names from the raw JSON string
441
- const fieldPattern = /"([^"]+)"\s*:/g;
442
- let match;
443
- const rawFieldNames = [];
444
- while ((match = fieldPattern.exec(rawArgs)) !== null) {
445
- rawFieldNames.push(match[1]);
446
- }
447
- for (const fieldName of rawFieldNames) {
448
- if (parsedArgs[fieldName] == null ||
449
- parsedArgs[fieldName] === '' ||
450
- parsedArgs[fieldName] === undefined) {
451
- const rawValue = this.streamingToolCallBuffer.extractFieldValue(toolCallId, fieldName);
452
- if (rawValue != null && rawValue !== '') {
453
- parsedArgs[fieldName] = rawValue;
454
- recoveredFields.push(fieldName);
455
- }
456
- }
457
- }
458
- if (recoveredFields.length > 0) {
459
- // eslint-disable-next-line no-console
460
- console.warn(`[TruncationRecovery] Tool=${toolName}, callId=${toolCallId}, rawBufferLen=${rawLen}, ` +
461
- `parsedFields=[${Object.keys(args ?? {}).join(',')}], recoveredFields=[${recoveredFields.join(',')}]`);
462
- }
463
- return parsedArgs;
464
- }
465
- /**
466
- * Builds code session context for injection into event-driven tool calls.
467
- * Mirrors the session injection logic in runTool() for direct execution.
468
- */
469
- getCodeSessionContext() {
470
- if (!this.sessions) {
471
- return undefined;
472
- }
473
- const codeSession = this.sessions.get(Constants.EXECUTE_CODE);
474
- if (!codeSession) {
475
- return undefined;
476
- }
477
- const context = {
478
- session_id: codeSession.session_id,
479
- };
480
- if (codeSession.files && codeSession.files.length > 0) {
481
- context.files = codeSession.files.map((file) => ({
482
- session_id: file.session_id ?? codeSession.session_id,
483
- id: file.id,
484
- name: file.name,
485
- }));
486
- }
487
- return context;
488
- }
489
- /**
490
- * Extracts code execution session context from tool results and stores in Graph.sessions.
491
- * Mirrors the session storage logic in handleRunToolCompletions for direct execution.
492
- */
493
- storeCodeSessionFromResults(results, requests) {
494
- if (!this.sessions) {
495
- return;
496
- }
497
- for (let i = 0; i < results.length; i++) {
498
- const result = results[i];
499
- if (result.status !== 'success' || result.artifact == null) {
500
- continue;
501
- }
502
- const request = requests.find((r) => r.id === result.toolCallId);
503
- if (request?.name !== Constants.EXECUTE_CODE &&
504
- request?.name !== Constants.PROGRAMMATIC_TOOL_CALLING) {
505
- continue;
506
- }
507
- const artifact = result.artifact;
508
- if (artifact?.session_id == null || artifact.session_id === '') {
509
- continue;
510
- }
511
- const newFiles = artifact.files ?? [];
512
- const existingSession = this.sessions.get(Constants.EXECUTE_CODE);
513
- const existingFiles = existingSession?.files ?? [];
514
- if (newFiles.length > 0) {
515
- const filesWithSession = newFiles.map((file) => ({
516
- ...file,
517
- session_id: artifact.session_id,
518
- }));
519
- const newFileNames = new Set(filesWithSession.map((f) => f.name));
520
- const filteredExisting = existingFiles.filter((f) => !newFileNames.has(f.name));
521
- this.sessions.set(Constants.EXECUTE_CODE, {
522
- session_id: artifact.session_id,
523
- files: [...filteredExisting, ...filesWithSession],
524
- lastUpdated: Date.now(),
525
- });
526
- }
527
- else {
528
- this.sessions.set(Constants.EXECUTE_CODE, {
529
- session_id: artifact.session_id,
530
- files: existingFiles,
531
- lastUpdated: Date.now(),
532
- });
533
- }
534
- }
535
- }
536
- /**
537
- * Post-processes standard runTool outputs: dispatches ON_RUN_STEP_COMPLETED
538
- * and stores code session context. Mirrors the completion handling in
539
- * dispatchToolEvents for the event-driven path.
540
- *
541
- * By handling completions here in graph context (rather than in the
542
- * stream consumer via ToolEndHandler), the race between the stream
543
- * consumer and graph execution is eliminated.
544
- */
545
- handleRunToolCompletions(calls, outputs, config) {
546
- for (let i = 0; i < calls.length; i++) {
547
- const call = calls[i];
548
- const output = outputs[i];
549
- const turn = this.toolCallTurns.get(call.id) ?? 0;
550
- if (isCommand(output)) {
551
- continue;
552
- }
553
- const toolMessage = output;
554
- const toolCallId = call.id ?? '';
555
- // Skip error ToolMessages when errorHandler already dispatched ON_RUN_STEP_COMPLETED
556
- // via handleToolCallErrorStatic. Without this check, errors would be double-dispatched.
557
- if (toolMessage.status === 'error' && this.errorHandler != null) {
558
- continue;
559
- }
560
- // Store code session context from tool results
561
- if (this.sessions &&
562
- (call.name === Constants.EXECUTE_CODE ||
563
- call.name === Constants.PROGRAMMATIC_TOOL_CALLING)) {
564
- const artifact = toolMessage.artifact;
565
- if (artifact?.session_id != null && artifact.session_id !== '') {
566
- const newFiles = artifact.files ?? [];
567
- const existingSession = this.sessions.get(Constants.EXECUTE_CODE);
568
- const existingFiles = existingSession?.files ?? [];
569
- if (newFiles.length > 0) {
570
- const filesWithSession = newFiles.map((file) => ({
571
- ...file,
572
- session_id: artifact.session_id,
573
- }));
574
- const newFileNames = new Set(filesWithSession.map((f) => f.name));
575
- const filteredExisting = existingFiles.filter((f) => !newFileNames.has(f.name));
576
- this.sessions.set(Constants.EXECUTE_CODE, {
577
- session_id: artifact.session_id,
578
- files: [...filteredExisting, ...filesWithSession],
579
- lastUpdated: Date.now(),
580
- });
581
- }
582
- else {
583
- this.sessions.set(Constants.EXECUTE_CODE, {
584
- session_id: artifact.session_id,
585
- files: existingFiles,
586
- lastUpdated: Date.now(),
587
- });
588
- }
589
- }
590
- }
591
- // Dispatch ON_RUN_STEP_COMPLETED via custom event (same path as dispatchToolEvents)
592
- const stepId = this.toolCallStepIds?.get(toolCallId) ?? '';
593
- if (!stepId) {
594
- continue;
595
- }
596
- const contentString = typeof toolMessage.content === 'string'
597
- ? toolMessage.content
598
- : JSON.stringify(toolMessage.content);
599
- const tool_call = {
600
- args: typeof call.args === 'string'
601
- ? call.args
602
- : JSON.stringify(call.args ?? {}),
603
- name: call.name,
604
- id: toolCallId,
605
- output: contentString,
606
- progress: 1,
607
- };
608
- safeDispatchCustomEvent(GraphEvents.ON_RUN_STEP_COMPLETED, {
609
- result: {
610
- id: stepId,
611
- index: turn,
612
- type: 'tool_call',
613
- tool_call,
614
- },
615
- }, config);
616
- }
617
- }
618
- /**
619
- * Dispatches tool calls to the host via ON_TOOL_EXECUTE event and returns raw ToolMessages.
620
- * Core logic for event-driven execution, separated from output shaping.
621
- */
622
- async dispatchToolEvents(toolCalls, config) {
623
- const requests = toolCalls.map((call) => {
624
- const turn = this.toolUsageCount.get(call.name) ?? 0;
625
- this.toolUsageCount.set(call.name, turn + 1);
626
- // Recover truncated args from streaming buffer (same as runTool path)
627
- let args = call.args;
628
- if (call.id && this.streamingToolCallBuffer?.has(call.id)) {
629
- args = this.recoverTruncatedArgs(call.name, call.id, args);
630
- this.streamingToolCallBuffer.clear(call.id);
631
- }
632
- const request = {
633
- id: call.id,
634
- name: call.name,
635
- args,
636
- stepId: this.toolCallStepIds?.get(call.id),
637
- turn,
638
- };
639
- if (call.name === Constants.EXECUTE_CODE ||
640
- call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {
641
- request.codeSessionContext = this.getCodeSessionContext();
642
- }
643
- return request;
644
- });
645
- const results = await new Promise((resolve, reject) => {
646
- const request = {
647
- toolCalls: requests,
648
- userId: config.configurable?.user_id,
649
- agentId: this.agentId,
650
- configurable: config.configurable,
651
- metadata: config.metadata,
652
- resolve,
653
- reject,
654
- };
655
- safeDispatchCustomEvent(GraphEvents.ON_TOOL_EXECUTE, request, config);
656
- });
657
- this.storeCodeSessionFromResults(results, requests);
658
- return results.map((result) => {
659
- const request = requests.find((r) => r.id === result.toolCallId);
660
- const toolName = request?.name ?? 'unknown';
661
- const stepId = this.toolCallStepIds?.get(result.toolCallId) ?? '';
662
- if (!stepId) {
663
- // eslint-disable-next-line no-console
664
- console.warn(`[ToolNode] toolCallStepIds missing entry for toolCallId=${result.toolCallId} (tool=${toolName}). ` +
665
- 'This indicates a race between the stream consumer and graph execution. ' +
666
- `Map size: ${this.toolCallStepIds?.size ?? 0}`);
667
- }
668
- let toolMessage;
669
- let contentString;
670
- if (result.status === 'error') {
671
- contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\n Please fix your mistakes.`;
672
- toolMessage = new ToolMessage({
673
- status: 'error',
674
- content: contentString,
675
- name: toolName,
676
- tool_call_id: result.toolCallId,
677
- });
678
- }
679
- else {
680
- contentString =
681
- typeof result.content === 'string'
682
- ? result.content
683
- : JSON.stringify(result.content);
684
- toolMessage = new ToolMessage({
685
- status: 'success',
686
- name: toolName,
687
- content: contentString,
688
- artifact: result.artifact,
689
- tool_call_id: result.toolCallId,
690
- });
691
- }
692
- const tool_call = {
693
- args: typeof request?.args === 'string'
694
- ? request.args
695
- : JSON.stringify(request?.args ?? {}),
696
- name: toolName,
697
- id: result.toolCallId,
698
- output: contentString,
699
- progress: 1,
700
- };
701
- const runStepCompletedData = {
702
- result: {
703
- id: stepId,
704
- index: request?.turn ?? 0,
705
- type: 'tool_call',
706
- tool_call,
707
- },
708
- };
709
- safeDispatchCustomEvent(GraphEvents.ON_RUN_STEP_COMPLETED, runStepCompletedData, config);
710
- return toolMessage;
711
- });
712
- }
713
- /**
714
- * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.
715
- * Used in event-driven mode where the host handles actual tool execution.
716
- */
717
- async executeViaEvent(toolCalls, config,
718
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
719
- input) {
720
- const outputs = await this.dispatchToolEvents(toolCalls, config);
721
- return (Array.isArray(input) ? outputs : { messages: outputs });
722
- }
723
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
724
- async run(input, config) {
725
- const _toolNodeStart = Date.now();
726
- this.toolCallTurns.clear();
727
- let outputs;
728
- if (this.isSendInput(input)) {
729
- const isDirectTool = this.directToolNames?.has(input.lg_tool_call.name);
730
- if (this.eventDrivenMode && isDirectTool !== true) {
731
- return this.executeViaEvent([input.lg_tool_call], config, input);
732
- }
733
- outputs = [await this.runTool(input.lg_tool_call, config)];
734
- this.handleRunToolCompletions([input.lg_tool_call], outputs, config);
735
- }
736
- else {
737
- let messages;
738
- if (Array.isArray(input)) {
739
- messages = input;
740
- }
741
- else if (this.isMessagesState(input)) {
742
- messages = input.messages;
743
- }
744
- else {
745
- throw new Error('ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.');
746
- }
747
- const toolMessageIds = new Set(messages
748
- .filter((msg) => msg._getType() === 'tool')
749
- .map((msg) => msg.tool_call_id));
750
- let aiMessage;
751
- for (let i = messages.length - 1; i >= 0; i--) {
752
- const message = messages[i];
753
- if (isAIMessage(message)) {
754
- aiMessage = message;
755
- break;
756
- }
757
- }
758
- if (aiMessage == null || !isAIMessage(aiMessage)) {
759
- throw new Error('ToolNode only accepts AIMessages as input.');
760
- }
761
- if (this.loadRuntimeTools) {
762
- const { tools, toolMap } = this.loadRuntimeTools(aiMessage.tool_calls ?? []);
763
- this.toolMap =
764
- toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));
765
- this.programmaticCache = undefined; // Invalidate cache on toolMap change
766
- }
767
- const filteredCalls = aiMessage.tool_calls?.filter((call) => {
768
- /**
769
- * Filter out:
770
- * 1. Already processed tool calls (present in toolMessageIds)
771
- * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')
772
- * which are executed by the provider's API and don't require invocation
773
- */
774
- return ((call.id == null || !toolMessageIds.has(call.id)) &&
775
- !(call.id?.startsWith('srvtoolu_') ?? false));
776
- }) ?? [];
777
- if (this.eventDrivenMode && filteredCalls.length > 0) {
778
- if (!this.directToolNames || this.directToolNames.size === 0) {
779
- return this.executeViaEvent(filteredCalls, config, input);
780
- }
781
- const directCalls = filteredCalls.filter((c) => this.directToolNames.has(c.name));
782
- const eventCalls = filteredCalls.filter((c) => !this.directToolNames.has(c.name));
783
- const directOutputs = directCalls.length > 0
784
- ? await Promise.all(directCalls.map((call) => this.runTool(call, config)))
785
- : [];
786
- if (directCalls.length > 0 && directOutputs.length > 0) {
787
- this.handleRunToolCompletions(directCalls, directOutputs, config);
788
- }
789
- const eventOutputs = eventCalls.length > 0
790
- ? await this.dispatchToolEvents(eventCalls, config)
791
- : [];
792
- outputs = [...directOutputs, ...eventOutputs];
793
- }
794
- else {
795
- outputs = await Promise.all(filteredCalls.map((call) => this.runTool(call, config)));
796
- this.handleRunToolCompletions(filteredCalls, outputs, config);
797
- }
798
- }
799
- console.info(`[TIMING] ToolNode.run total: ${Date.now() - _toolNodeStart}ms`);
800
- if (!outputs.some(isCommand)) {
801
- return (Array.isArray(input) ? outputs : { messages: outputs });
802
- }
803
- const combinedOutputs = [];
804
- let parentCommand = null;
805
- /**
806
- * Collect handoff commands (Commands with string goto and Command.PARENT)
807
- * for potential parallel handoff aggregation
808
- */
809
- const handoffCommands = [];
810
- const nonCommandOutputs = [];
811
- for (const output of outputs) {
812
- if (isCommand(output)) {
813
- if (output.graph === Command.PARENT &&
814
- Array.isArray(output.goto) &&
815
- output.goto.every((send) => isSend(send))) {
816
- /** Aggregate Send-based commands */
817
- if (parentCommand) {
818
- parentCommand.goto.push(...output.goto);
819
- }
820
- else {
821
- parentCommand = new Command({
822
- graph: Command.PARENT,
823
- goto: output.goto,
824
- });
825
- }
826
- }
827
- else if (output.graph === Command.PARENT) {
828
- /**
829
- * Handoff Command with destination.
830
- * Handle both string ('agent') and array (['agent']) formats.
831
- * Collect for potential parallel aggregation.
832
- */
833
- const goto = output.goto;
834
- const isSingleStringDest = typeof goto === 'string';
835
- const isSingleArrayDest = Array.isArray(goto) &&
836
- goto.length === 1 &&
837
- typeof goto[0] === 'string';
838
- if (isSingleStringDest || isSingleArrayDest) {
839
- handoffCommands.push(output);
840
- }
841
- else {
842
- /** Multi-destination or other command - pass through */
843
- combinedOutputs.push(output);
844
- }
845
- }
846
- else {
847
- /** Other commands - pass through */
848
- combinedOutputs.push(output);
849
- }
850
- }
851
- else {
852
- nonCommandOutputs.push(output);
853
- combinedOutputs.push(Array.isArray(input) ? [output] : { messages: [output] });
854
- }
855
- }
856
- /**
857
- * Handle handoff commands - convert to Send objects for parallel execution
858
- * when multiple handoffs are requested
859
- */
860
- if (handoffCommands.length > 1) {
861
- /**
862
- * Multiple parallel handoffs - convert to Send objects.
863
- * Each Send carries its own state with the appropriate messages.
864
- * This enables LLM-initiated parallel execution when calling multiple
865
- * transfer tools simultaneously.
866
- */
867
- /** Collect all destinations for sibling tracking */
868
- const allDestinations = handoffCommands.map((cmd) => {
869
- const goto = cmd.goto;
870
- return typeof goto === 'string' ? goto : goto[0];
871
- });
872
- const sends = handoffCommands.map((cmd, idx) => {
873
- const destination = allDestinations[idx];
874
- /** Get siblings (other destinations, not this one) */
875
- const siblings = allDestinations.filter((d) => d !== destination);
876
- /** Add siblings to ToolMessage additional_kwargs */
877
- const update = cmd.update;
878
- if (update && update.messages) {
879
- for (const msg of update.messages) {
880
- if (msg.getType() === 'tool') {
881
- msg.additional_kwargs.handoff_parallel_siblings =
882
- siblings;
883
- }
884
- }
885
- }
886
- return new Send(destination, cmd.update);
887
- });
888
- const parallelCommand = new Command({
889
- graph: Command.PARENT,
890
- goto: sends,
891
- });
892
- combinedOutputs.push(parallelCommand);
893
- }
894
- else if (handoffCommands.length === 1) {
895
- /** Single handoff - pass through as-is */
896
- combinedOutputs.push(handoffCommands[0]);
897
- }
898
- if (parentCommand) {
899
- combinedOutputs.push(parentCommand);
900
- }
901
- return combinedOutputs;
902
- }
903
- isSendInput(input) {
904
- return (typeof input === 'object' && input != null && 'lg_tool_call' in input);
905
- }
906
- isMessagesState(input) {
907
- return (typeof input === 'object' &&
908
- input != null &&
909
- 'messages' in input &&
910
- Array.isArray(input.messages) &&
911
- input.messages.every(isBaseMessage));
912
- }
913
- }
914
- function areToolCallsInvoked(message, invokedToolIds) {
915
- if (!invokedToolIds || invokedToolIds.size === 0)
916
- return false;
917
- return (message.tool_calls?.every((toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)) ?? false);
918
- }
919
- export function toolsCondition(state, toolNode, invokedToolIds) {
920
- const messages = Array.isArray(state) ? state : state.messages;
921
- const message = messages[messages.length - 1];
922
- if (message &&
923
- 'tool_calls' in message &&
924
- (message.tool_calls?.length ?? 0) > 0 &&
925
- !areToolCallsInvoked(message, invokedToolIds)) {
926
- return toolNode;
927
- }
928
- return END;
929
- }
930
- //# sourceMappingURL=ToolNode.js.map