illuma-agents 1.0.37 → 1.0.38

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 (125) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +69 -14
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +3 -1
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +50 -8
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/graphs/MultiAgentGraph.cjs +277 -11
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  9. package/dist/cjs/llm/bedrock/index.cjs +128 -61
  10. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  11. package/dist/cjs/main.cjs +16 -7
  12. package/dist/cjs/main.cjs.map +1 -1
  13. package/dist/cjs/messages/cache.cjs +1 -0
  14. package/dist/cjs/messages/cache.cjs.map +1 -1
  15. package/dist/cjs/messages/core.cjs +1 -1
  16. package/dist/cjs/messages/core.cjs.map +1 -1
  17. package/dist/cjs/messages/tools.cjs +2 -2
  18. package/dist/cjs/messages/tools.cjs.map +1 -1
  19. package/dist/cjs/stream.cjs +4 -2
  20. package/dist/cjs/stream.cjs.map +1 -1
  21. package/dist/cjs/tools/BrowserTools.cjs.map +1 -1
  22. package/dist/cjs/tools/CodeExecutor.cjs +22 -21
  23. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  24. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +14 -11
  25. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  26. package/dist/cjs/tools/ToolNode.cjs +101 -2
  27. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  28. package/dist/cjs/tools/ToolSearch.cjs +862 -0
  29. package/dist/cjs/tools/ToolSearch.cjs.map +1 -0
  30. package/dist/esm/agents/AgentContext.mjs +69 -14
  31. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  32. package/dist/esm/common/enum.mjs +3 -1
  33. package/dist/esm/common/enum.mjs.map +1 -1
  34. package/dist/esm/graphs/Graph.mjs +51 -9
  35. package/dist/esm/graphs/Graph.mjs.map +1 -1
  36. package/dist/esm/graphs/MultiAgentGraph.mjs +278 -12
  37. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  38. package/dist/esm/llm/bedrock/index.mjs +127 -60
  39. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  40. package/dist/esm/main.mjs +1 -1
  41. package/dist/esm/messages/cache.mjs +1 -0
  42. package/dist/esm/messages/cache.mjs.map +1 -1
  43. package/dist/esm/messages/core.mjs +1 -1
  44. package/dist/esm/messages/core.mjs.map +1 -1
  45. package/dist/esm/messages/tools.mjs +2 -2
  46. package/dist/esm/messages/tools.mjs.map +1 -1
  47. package/dist/esm/stream.mjs +4 -2
  48. package/dist/esm/stream.mjs.map +1 -1
  49. package/dist/esm/tools/BrowserTools.mjs.map +1 -1
  50. package/dist/esm/tools/CodeExecutor.mjs +22 -21
  51. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  52. package/dist/esm/tools/ProgrammaticToolCalling.mjs +14 -11
  53. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  54. package/dist/esm/tools/ToolNode.mjs +102 -3
  55. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  56. package/dist/esm/tools/ToolSearch.mjs +827 -0
  57. package/dist/esm/tools/ToolSearch.mjs.map +1 -0
  58. package/dist/types/agents/AgentContext.d.ts +33 -1
  59. package/dist/types/common/enum.d.ts +4 -2
  60. package/dist/types/graphs/Graph.d.ts +6 -0
  61. package/dist/types/graphs/MultiAgentGraph.d.ts +16 -0
  62. package/dist/types/index.d.ts +1 -1
  63. package/dist/types/llm/bedrock/index.d.ts +89 -11
  64. package/dist/types/llm/bedrock/types.d.ts +27 -0
  65. package/dist/types/llm/bedrock/utils/index.d.ts +5 -0
  66. package/dist/types/llm/bedrock/utils/message_inputs.d.ts +31 -0
  67. package/dist/types/llm/bedrock/utils/message_outputs.d.ts +33 -0
  68. package/dist/types/tools/CodeExecutor.d.ts +0 -3
  69. package/dist/types/tools/ProgrammaticToolCalling.d.ts +0 -3
  70. package/dist/types/tools/ToolNode.d.ts +3 -1
  71. package/dist/types/tools/ToolSearch.d.ts +148 -0
  72. package/dist/types/types/graph.d.ts +2 -0
  73. package/dist/types/types/llm.d.ts +3 -1
  74. package/dist/types/types/tools.d.ts +42 -2
  75. package/package.json +12 -5
  76. package/src/agents/AgentContext.ts +88 -16
  77. package/src/common/enum.ts +3 -1
  78. package/src/graphs/Graph.ts +64 -13
  79. package/src/graphs/MultiAgentGraph.ts +350 -13
  80. package/src/index.ts +1 -1
  81. package/src/llm/bedrock/index.ts +221 -99
  82. package/src/llm/bedrock/llm.spec.ts +616 -0
  83. package/src/llm/bedrock/types.ts +51 -0
  84. package/src/llm/bedrock/utils/index.ts +18 -0
  85. package/src/llm/bedrock/utils/message_inputs.ts +563 -0
  86. package/src/llm/bedrock/utils/message_outputs.ts +310 -0
  87. package/src/messages/__tests__/tools.test.ts +21 -21
  88. package/src/messages/cache.test.ts +259 -0
  89. package/src/messages/cache.ts +104 -1
  90. package/src/messages/core.ts +1 -1
  91. package/src/messages/tools.ts +2 -2
  92. package/src/scripts/caching.ts +27 -19
  93. package/src/scripts/code_exec_files.ts +58 -15
  94. package/src/scripts/code_exec_multi_session.ts +241 -0
  95. package/src/scripts/code_exec_session.ts +282 -0
  96. package/src/scripts/multi-agent-conditional.ts +1 -0
  97. package/src/scripts/multi-agent-supervisor.ts +1 -0
  98. package/src/scripts/programmatic_exec_agent.ts +4 -4
  99. package/src/scripts/test-handoff-preamble.ts +277 -0
  100. package/src/scripts/test-parallel-handoffs.ts +291 -0
  101. package/src/scripts/test-tools-before-handoff.ts +8 -4
  102. package/src/scripts/test_code_api.ts +361 -0
  103. package/src/scripts/thinking-bedrock.ts +159 -0
  104. package/src/scripts/thinking.ts +39 -18
  105. package/src/scripts/{tool_search_regex.ts → tool_search.ts} +5 -5
  106. package/src/scripts/tools.ts +7 -3
  107. package/src/stream.ts +4 -2
  108. package/src/tools/BrowserTools.ts +39 -17
  109. package/src/tools/CodeExecutor.ts +26 -23
  110. package/src/tools/ProgrammaticToolCalling.ts +18 -14
  111. package/src/tools/ToolNode.ts +114 -1
  112. package/src/tools/ToolSearch.ts +1041 -0
  113. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -2
  114. package/src/tools/__tests__/{ToolSearchRegex.integration.test.ts → ToolSearch.integration.test.ts} +6 -6
  115. package/src/tools/__tests__/ToolSearch.test.ts +1003 -0
  116. package/src/types/graph.ts +2 -0
  117. package/src/types/llm.ts +3 -1
  118. package/src/types/tools.ts +51 -2
  119. package/dist/cjs/tools/ToolSearchRegex.cjs +0 -455
  120. package/dist/cjs/tools/ToolSearchRegex.cjs.map +0 -1
  121. package/dist/esm/tools/ToolSearchRegex.mjs +0 -448
  122. package/dist/esm/tools/ToolSearchRegex.mjs.map +0 -1
  123. package/dist/types/tools/ToolSearchRegex.d.ts +0 -80
  124. package/src/tools/ToolSearchRegex.ts +0 -535
  125. package/src/tools/__tests__/ToolSearchRegex.test.ts +0 -232
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Test script for multi-turn handoff behavior.
3
+ *
4
+ * This tests the fix for the issue where receiving agents would see transfer messages
5
+ * and prematurely produce end tokens, thinking the work was already done.
6
+ *
7
+ * The fix:
8
+ * 1. Filters out transfer tool calls and ToolMessages from the receiving agent's context
9
+ * 2. Injects any passthrough instructions as a HumanMessage to ground the receiving agent
10
+ */
11
+ import { config } from 'dotenv';
12
+ config();
13
+
14
+ import { HumanMessage, BaseMessage } from '@langchain/core/messages';
15
+ import type { RunnableConfig } from '@langchain/core/runnables';
16
+ import type * as t from '@/types';
17
+ import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
18
+ import { ToolEndHandler, ModelEndHandler } from '@/events';
19
+ import { getLLMConfig } from '@/utils/llmConfig';
20
+ import { GraphEvents, Providers } from '@/common';
21
+ import { Run } from '@/run';
22
+
23
+ const conversationHistory: BaseMessage[] = [];
24
+
25
+ /**
26
+ * Test multi-turn handoff between a coordinator and a specialist
27
+ */
28
+ async function testHandoffPreamble(): Promise<void> {
29
+ console.log('='.repeat(60));
30
+ console.log('Testing Multi-Turn Handoff with Preamble Injection');
31
+ console.log('='.repeat(60));
32
+ console.log('\nThis test verifies that:');
33
+ console.log('1. Transfer messages are filtered from receiving agent context');
34
+ console.log('2. Passthrough instructions are injected as a HumanMessage');
35
+ console.log('3. Multi-turn conversations work correctly after handoffs\n');
36
+
37
+ const { contentParts, aggregateContent } = createContentAggregator();
38
+
39
+ /** Track which agent is responding */
40
+ let currentAgent = '';
41
+
42
+ const customHandlers = {
43
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
44
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
45
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
46
+ [GraphEvents.ON_RUN_STEP]: {
47
+ handle: (
48
+ event: GraphEvents.ON_RUN_STEP,
49
+ data: t.StreamEventData
50
+ ): void => {
51
+ const runStep = data as t.RunStep;
52
+ if (runStep.agentId) {
53
+ currentAgent = runStep.agentId;
54
+ console.log(`\n[Agent: ${currentAgent}] Processing...`);
55
+ }
56
+ aggregateContent({ event, data: runStep });
57
+ },
58
+ },
59
+ [GraphEvents.ON_RUN_STEP_COMPLETED]: {
60
+ handle: (
61
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
62
+ data: t.StreamEventData
63
+ ): void => {
64
+ aggregateContent({
65
+ event,
66
+ data: data as unknown as { result: t.ToolEndEvent },
67
+ });
68
+ },
69
+ },
70
+ [GraphEvents.ON_MESSAGE_DELTA]: {
71
+ handle: (
72
+ event: GraphEvents.ON_MESSAGE_DELTA,
73
+ data: t.StreamEventData
74
+ ): void => {
75
+ console.log('====== ON_MESSAGE_DELTA ======');
76
+ console.dir(data, { depth: null });
77
+ aggregateContent({ event, data: data as t.MessageDeltaEvent });
78
+ },
79
+ },
80
+ [GraphEvents.TOOL_START]: {
81
+ handle: (
82
+ _event: string,
83
+ data: t.StreamEventData,
84
+ _metadata?: Record<string, unknown>
85
+ ): void => {
86
+ const toolData = data as { name?: string };
87
+ if (toolData?.name?.includes('transfer_to_')) {
88
+ const specialist = toolData.name.replace('lc_transfer_to_', '');
89
+ console.log(`\n🔀 Handing off to: ${specialist}`);
90
+ }
91
+ },
92
+ },
93
+ };
94
+
95
+ /**
96
+ * Create agents:
97
+ * - coordinator: Decides when to hand off to specialist
98
+ * - specialist: Handles specific tasks delegated by coordinator
99
+ */
100
+ const agents: t.AgentInputs[] = [
101
+ {
102
+ agentId: 'coordinator',
103
+ provider: Providers.OPENAI,
104
+ clientOptions: {
105
+ modelName: 'gpt-4.1-mini',
106
+ apiKey: process.env.OPENAI_API_KEY,
107
+ },
108
+ instructions: `You are a Task Coordinator. Your role is to:
109
+ 1. Understand user requests
110
+ 2. If the request involves technical analysis, use the transfer_to_specialist tool to hand off
111
+ 3. When handing off, provide clear instructions about what needs to be done
112
+
113
+ IMPORTANT: When using the handoff tool, include specific instructions for the specialist.`,
114
+ maxContextTokens: 8000,
115
+ },
116
+ {
117
+ agentId: 'specialist',
118
+ provider: Providers.OPENAI,
119
+ clientOptions: {
120
+ modelName: 'gpt-4.1-mini',
121
+ apiKey: process.env.OPENAI_API_KEY,
122
+ },
123
+ instructions: `You are a Technical Specialist. When you receive a request:
124
+ 1. Carefully read any instructions provided
125
+ 2. Provide a detailed technical response
126
+ 3. Do NOT just acknowledge - provide substantive help
127
+
128
+ IMPORTANT: You are the specialist - provide a complete, helpful response to the task.`,
129
+ maxContextTokens: 8000,
130
+ },
131
+ ];
132
+
133
+ /** Create handoff edge with passthrough instructions */
134
+ const edges: t.GraphEdge[] = [
135
+ {
136
+ from: 'coordinator',
137
+ to: 'specialist',
138
+ description: 'Transfer to technical specialist for analysis',
139
+ edgeType: 'handoff',
140
+ prompt: 'Specific instructions for the specialist about what to analyze',
141
+ promptKey: 'instructions',
142
+ },
143
+ ];
144
+
145
+ const runConfig: t.RunConfig = {
146
+ runId: `handoff-test-${Date.now()}`,
147
+ graphConfig: {
148
+ type: 'multi-agent',
149
+ agents,
150
+ edges,
151
+ },
152
+ customHandlers,
153
+ returnContent: true,
154
+ };
155
+
156
+ const run = await Run.create(runConfig);
157
+
158
+ const config: Partial<RunnableConfig> & {
159
+ version: 'v1' | 'v2';
160
+ streamMode: string;
161
+ } = {
162
+ configurable: {
163
+ thread_id: 'handoff-test-conversation-1',
164
+ },
165
+ streamMode: 'values',
166
+ version: 'v2' as const,
167
+ };
168
+
169
+ /** TURN 1: Initial request that triggers handoff */
170
+ console.log('\n' + '─'.repeat(60));
171
+ console.log('TURN 1: Initial request (should trigger handoff)');
172
+ console.log('─'.repeat(60));
173
+
174
+ const userMessage1 = `
175
+ Hi! Can you help me understand the time complexity of quicksort?
176
+ I need a technical explanation.
177
+ `;
178
+
179
+ conversationHistory.push(new HumanMessage(userMessage1));
180
+ console.log('\nUser:', userMessage1.trim());
181
+ console.log('\nResponse:');
182
+
183
+ let inputs = { messages: conversationHistory };
184
+ await run.processStream(inputs, config);
185
+ const messages1 = run.getRunMessages();
186
+ if (messages1) {
187
+ conversationHistory.push(...messages1);
188
+ }
189
+
190
+ console.log('\n');
191
+
192
+ /** TURN 2: Follow-up question to test multi-turn after handoff */
193
+ console.log('\n' + '─'.repeat(60));
194
+ console.log('TURN 2: Follow-up question (tests context after handoff)');
195
+ console.log('─'.repeat(60));
196
+
197
+ const userMessage2 = `
198
+ Thanks! Can you also explain the space complexity and when quicksort
199
+ might not be the best choice?
200
+ `;
201
+
202
+ conversationHistory.push(new HumanMessage(userMessage2));
203
+ console.log('\nUser:', userMessage2.trim());
204
+ console.log('\nResponse:');
205
+
206
+ inputs = { messages: conversationHistory };
207
+ await run.processStream(inputs, config);
208
+ const messages2 = run.getRunMessages();
209
+ if (messages2) {
210
+ conversationHistory.push(...messages2);
211
+ }
212
+
213
+ console.log('\n');
214
+
215
+ /** TURN 3: Another follow-up to verify sustained conversation */
216
+ console.log('\n' + '─'.repeat(60));
217
+ console.log('TURN 3: Third turn (tests sustained multi-turn)');
218
+ console.log('─'.repeat(60));
219
+
220
+ const userMessage3 = `
221
+ Great explanation! One more question - how does quicksort compare
222
+ to mergesort in practice?
223
+ `;
224
+
225
+ conversationHistory.push(new HumanMessage(userMessage3));
226
+ console.log('\nUser:', userMessage3.trim());
227
+ console.log('\nResponse:');
228
+
229
+ inputs = { messages: conversationHistory };
230
+ await run.processStream(inputs, config);
231
+ const messages3 = run.getRunMessages();
232
+ if (messages3) {
233
+ conversationHistory.push(...messages3);
234
+ }
235
+
236
+ /** Summary */
237
+ console.log('\n\n' + '='.repeat(60));
238
+ console.log('TEST SUMMARY');
239
+ console.log('='.repeat(60));
240
+ console.log('\nTotal messages in conversation:', conversationHistory.length);
241
+ console.log('\nMessage types:');
242
+
243
+ for (let i = 0; i < conversationHistory.length; i++) {
244
+ const msg = conversationHistory[i];
245
+ const type = msg.getType();
246
+ const preview =
247
+ typeof msg.content === 'string'
248
+ ? msg.content.slice(0, 50).replace(/\n/g, ' ')
249
+ : '[complex content]';
250
+ console.log(` ${i + 1}. [${type}] ${preview}...`);
251
+ }
252
+
253
+ console.log('\n✅ Test completed. Review the output above to verify:');
254
+ console.log(' - Specialist received and acted on instructions');
255
+ console.log(' - No premature end tokens after handoff');
256
+ console.log(' - Multi-turn conversation continued smoothly');
257
+
258
+ console.dir(contentParts, { depth: null });
259
+ }
260
+
261
+ process.on('unhandledRejection', (reason, promise) => {
262
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
263
+ console.log('\nConversation history at failure:');
264
+ console.dir(conversationHistory, { depth: null });
265
+ process.exit(1);
266
+ });
267
+
268
+ process.on('uncaughtException', (err) => {
269
+ console.error('Uncaught Exception:', err);
270
+ });
271
+
272
+ testHandoffPreamble().catch((err) => {
273
+ console.error('Test failed:', err);
274
+ console.log('\nConversation history at failure:');
275
+ console.dir(conversationHistory, { depth: null });
276
+ process.exit(1);
277
+ });
@@ -0,0 +1,291 @@
1
+ import { config } from 'dotenv';
2
+ config();
3
+
4
+ import { HumanMessage, BaseMessage } from '@langchain/core/messages';
5
+ import type * as t from '@/types';
6
+ import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
7
+ import { ToolEndHandler } from '@/events';
8
+ import { Providers, GraphEvents } from '@/common';
9
+ import { sleep } from '@/utils/run';
10
+ import { Run } from '@/run';
11
+
12
+ const conversationHistory: BaseMessage[] = [];
13
+
14
+ /**
15
+ * Test parallel handoffs - where an LLM calls multiple transfer tools simultaneously
16
+ *
17
+ * Graph structure:
18
+ * coordinator -> [researcher, writer] (via parallel handoff tools)
19
+ *
20
+ * The coordinator agent has two transfer tools:
21
+ * - transfer_to_researcher
22
+ * - transfer_to_writer
23
+ *
24
+ * When given a task that needs both, it should call both tools in parallel.
25
+ */
26
+ async function testParallelHandoffs() {
27
+ console.log(
28
+ 'Testing Parallel Handoffs (LLM calling multiple transfers)...\n'
29
+ );
30
+
31
+ const { contentParts, aggregateContent } = createContentAggregator();
32
+
33
+ const agents: t.AgentInputs[] = [
34
+ {
35
+ agentId: 'coordinator',
36
+ provider: Providers.OPENAI,
37
+ clientOptions: {
38
+ modelName: 'gpt-4o-mini',
39
+ apiKey: process.env.OPENAI_API_KEY,
40
+ },
41
+ instructions: `You are a COORDINATOR agent. Your job is to delegate tasks to specialized agents.
42
+
43
+ You have access to two transfer tools:
44
+ - transfer_to_researcher: For research and fact-finding tasks
45
+ - transfer_to_writer: For content creation and writing tasks
46
+
47
+ IMPORTANT: When a task requires BOTH research AND writing, you MUST call BOTH transfer tools SIMULTANEOUSLY in the same response. Do not call them sequentially.
48
+
49
+ For example, if asked to "research and write about X", call both transfers at once to enable parallel work.
50
+
51
+ When delegating, provide clear instructions to each agent about what they should do.`,
52
+ },
53
+ {
54
+ agentId: 'researcher',
55
+ provider: Providers.ANTHROPIC,
56
+ clientOptions: {
57
+ modelName: 'claude-haiku-4-5',
58
+ apiKey: process.env.ANTHROPIC_API_KEY,
59
+ },
60
+ instructions: `You are a RESEARCHER. When you receive a task:
61
+ 1. Provide concise research findings (100-150 words)
62
+ 2. Start your response with "📚 RESEARCH FINDINGS:"`,
63
+ },
64
+ {
65
+ agentId: 'writer',
66
+ provider: Providers.ANTHROPIC,
67
+ clientOptions: {
68
+ modelName: 'claude-haiku-4-5',
69
+ apiKey: process.env.ANTHROPIC_API_KEY,
70
+ },
71
+ instructions: `You are a WRITER. When you receive a task:
72
+ 1. Provide creative content (100-150 words)
73
+ 2. Start your response with "✍️ WRITTEN CONTENT:"`,
74
+ },
75
+ ];
76
+
77
+ /**
78
+ * Create handoff edges from coordinator to both researcher and writer.
79
+ * These are separate edges so the LLM sees both transfer tools.
80
+ */
81
+ const edges: t.GraphEdge[] = [
82
+ {
83
+ from: 'coordinator',
84
+ to: 'researcher',
85
+ edgeType: 'handoff',
86
+ description: 'Transfer to researcher for research and fact-finding tasks',
87
+ prompt: 'Research task instructions',
88
+ },
89
+ {
90
+ from: 'coordinator',
91
+ to: 'writer',
92
+ edgeType: 'handoff',
93
+ description: 'Transfer to writer for content creation and writing tasks',
94
+ prompt: 'Writing task instructions',
95
+ },
96
+ ];
97
+
98
+ /** Track which agents are active and their timing */
99
+ const activeAgents = new Set<string>();
100
+ const agentTimings: Record<string, { start?: number; end?: number }> = {};
101
+ const startTime = Date.now();
102
+
103
+ const customHandlers = {
104
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
105
+ [GraphEvents.CHAT_MODEL_END]: {
106
+ handle: (
107
+ _event: string,
108
+ _data: t.StreamEventData,
109
+ metadata?: Record<string, unknown>
110
+ ): void => {
111
+ const nodeName = metadata?.langgraph_node as string;
112
+ if (nodeName) {
113
+ const elapsed = Date.now() - startTime;
114
+ agentTimings[nodeName] = agentTimings[nodeName] || {};
115
+ agentTimings[nodeName].end = elapsed;
116
+ activeAgents.delete(nodeName);
117
+ console.log(`\n⏱️ [${nodeName}] COMPLETED at ${elapsed}ms`);
118
+ }
119
+ },
120
+ },
121
+ [GraphEvents.CHAT_MODEL_START]: {
122
+ handle: (
123
+ _event: string,
124
+ _data: t.StreamEventData,
125
+ metadata?: Record<string, unknown>
126
+ ): void => {
127
+ const nodeName = metadata?.langgraph_node as string;
128
+ if (nodeName) {
129
+ const elapsed = Date.now() - startTime;
130
+ /** Store first start time for parallel overlap calculation */
131
+ if (!agentTimings[nodeName]?.start) {
132
+ agentTimings[nodeName] = agentTimings[nodeName] || {};
133
+ agentTimings[nodeName].start = elapsed;
134
+ }
135
+ activeAgents.add(nodeName);
136
+ console.log(`\n⏱️ [${nodeName}] STARTED at ${elapsed}ms`);
137
+ console.log(
138
+ ` Active agents: ${Array.from(activeAgents).join(', ')}`
139
+ );
140
+ }
141
+ },
142
+ },
143
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
144
+ [GraphEvents.ON_RUN_STEP_COMPLETED]: {
145
+ handle: (
146
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
147
+ data: t.StreamEventData
148
+ ): void => {
149
+ aggregateContent({
150
+ event,
151
+ data: data as unknown as { result: t.ToolEndEvent },
152
+ });
153
+ },
154
+ },
155
+ [GraphEvents.ON_RUN_STEP]: {
156
+ handle: (
157
+ event: GraphEvents.ON_RUN_STEP,
158
+ data: t.StreamEventData
159
+ ): void => {
160
+ aggregateContent({ event, data: data as t.RunStep });
161
+ },
162
+ },
163
+ [GraphEvents.ON_RUN_STEP_DELTA]: {
164
+ handle: (
165
+ event: GraphEvents.ON_RUN_STEP_DELTA,
166
+ data: t.StreamEventData
167
+ ): void => {
168
+ aggregateContent({ event, data: data as t.RunStepDeltaEvent });
169
+ },
170
+ },
171
+ [GraphEvents.ON_MESSAGE_DELTA]: {
172
+ handle: (
173
+ event: GraphEvents.ON_MESSAGE_DELTA,
174
+ data: t.StreamEventData
175
+ ): void => {
176
+ aggregateContent({ event, data: data as t.MessageDeltaEvent });
177
+ },
178
+ },
179
+ };
180
+
181
+ const runConfig: t.RunConfig = {
182
+ runId: `parallel-handoffs-${Date.now()}`,
183
+ graphConfig: {
184
+ type: 'multi-agent',
185
+ agents,
186
+ edges,
187
+ },
188
+ customHandlers,
189
+ returnContent: true,
190
+ };
191
+
192
+ try {
193
+ const run = await Run.create(runConfig);
194
+
195
+ /** Prompt designed to trigger parallel handoffs without confusing language */
196
+ const userMessage = `Help me with two topics:
197
+ 1. The history of the internet
198
+ 2. A short poem about technology
199
+
200
+ I need information on both topics.`;
201
+
202
+ conversationHistory.push(new HumanMessage(userMessage));
203
+
204
+ console.log('User message:', userMessage);
205
+ console.log(
206
+ '\nInvoking multi-agent graph with parallel handoff request...\n'
207
+ );
208
+
209
+ const config = {
210
+ configurable: {
211
+ thread_id: 'parallel-handoffs-test-1',
212
+ },
213
+ streamMode: 'values',
214
+ version: 'v2' as const,
215
+ };
216
+
217
+ const inputs = {
218
+ messages: conversationHistory,
219
+ };
220
+
221
+ await run.processStream(inputs, config);
222
+ const finalMessages = run.getRunMessages();
223
+
224
+ if (finalMessages) {
225
+ conversationHistory.push(...finalMessages);
226
+ }
227
+
228
+ /** Analyze parallel execution */
229
+ console.log('\n\n========== TIMING SUMMARY ==========');
230
+ console.log('Available timing keys:', Object.keys(agentTimings));
231
+ for (const [agent, timing] of Object.entries(agentTimings)) {
232
+ const duration =
233
+ timing.end && timing.start ? timing.end - timing.start : 'N/A';
234
+ console.log(
235
+ `${agent}: started=${timing.start}ms, ended=${timing.end}ms, duration=${duration}ms`
236
+ );
237
+ }
238
+
239
+ /** Check if researcher and writer ran in parallel (handle key variations) */
240
+ const researcherKey = Object.keys(agentTimings).find((k) =>
241
+ k.includes('researcher')
242
+ );
243
+ const writerKey = Object.keys(agentTimings).find((k) =>
244
+ k.includes('writer')
245
+ );
246
+ const researcherTiming = researcherKey
247
+ ? agentTimings[researcherKey]
248
+ : undefined;
249
+ const writerTiming = writerKey ? agentTimings[writerKey] : undefined;
250
+
251
+ if (researcherTiming && writerTiming) {
252
+ const bothStarted = researcherTiming.start && writerTiming.start;
253
+ const bothEnded = researcherTiming.end && writerTiming.end;
254
+
255
+ if (bothStarted && bothEnded) {
256
+ const overlap =
257
+ Math.min(researcherTiming.end!, writerTiming.end!) -
258
+ Math.max(researcherTiming.start!, writerTiming.start!);
259
+
260
+ if (overlap > 0) {
261
+ console.log(
262
+ `\n✅ PARALLEL HANDOFFS SUCCESSFUL: ${overlap}ms overlap between researcher and writer`
263
+ );
264
+ } else {
265
+ console.log(
266
+ `\n⚠️ SEQUENTIAL EXECUTION: researcher and writer did not overlap`
267
+ );
268
+ console.log(
269
+ ` This may indicate the LLM called transfers sequentially, not in parallel`
270
+ );
271
+ }
272
+ }
273
+ } else {
274
+ console.log(
275
+ '\n⚠️ Not all agents were invoked. Check if handoffs occurred.'
276
+ );
277
+ console.log(' researcher timing:', researcherTiming);
278
+ console.log(' writer timing:', writerTiming);
279
+ }
280
+ console.log('====================================\n');
281
+
282
+ console.log('Final content parts:', contentParts.length, 'parts');
283
+ console.dir(contentParts, { depth: null });
284
+ await sleep(3000);
285
+ } catch (error) {
286
+ console.error('Error in parallel handoffs test:', error);
287
+ throw error;
288
+ }
289
+ }
290
+
291
+ testParallelHandoffs();
@@ -28,10 +28,14 @@ async function testToolsBeforeHandoff() {
28
28
 
29
29
  // Create custom handlers
30
30
  const customHandlers = {
31
- [GraphEvents.TOOL_END]: new ToolEndHandler(undefined, (name?: string) => {
32
- console.log(`\n✅ Tool completed: ${name}`);
33
- return true;
34
- }),
31
+ [GraphEvents.TOOL_END]: new ToolEndHandler(
32
+ undefined,
33
+ undefined,
34
+ (name?: string) => {
35
+ console.log(`\n✅ Tool completed: ${name}`);
36
+ return true;
37
+ }
38
+ ),
35
39
  [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
36
40
  [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
37
41
  [GraphEvents.ON_RUN_STEP]: {