@librechat/agents 3.3.0 → 3.3.1
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.
- package/dist/cjs/agents/AgentContext.cjs +116 -2
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +229 -48
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +102 -27
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +11 -2
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/contextOverflowRecovery.cjs +132 -0
- package/dist/cjs/llm/contextOverflowRecovery.cjs.map +1 -0
- package/dist/cjs/llm/google/index.cjs +1 -1
- package/dist/cjs/llm/invoke.cjs +60 -3
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/main.cjs +20 -7
- package/dist/cjs/messages/prune.cjs +16 -5
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/messages/recency.cjs +2 -0
- package/dist/cjs/messages/recency.cjs.map +1 -1
- package/dist/cjs/run.cjs +15 -2
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/stream.cjs +205 -49
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +55 -7
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +2 -2
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +2 -2
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +69 -8
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +19 -15
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +32 -3
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/utils/errors.cjs +317 -52
- package/dist/cjs/utils/errors.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +117 -3
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +227 -46
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +102 -27
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +11 -2
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/contextOverflowRecovery.mjs +130 -0
- package/dist/esm/llm/contextOverflowRecovery.mjs.map +1 -0
- package/dist/esm/llm/google/index.mjs +1 -1
- package/dist/esm/llm/invoke.mjs +59 -4
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/main.mjs +9 -9
- package/dist/esm/messages/prune.mjs +14 -6
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/messages/recency.mjs +2 -1
- package/dist/esm/messages/recency.mjs.map +1 -1
- package/dist/esm/run.mjs +15 -2
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/stream.mjs +205 -49
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +55 -7
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +3 -3
- package/dist/esm/tools/BashExecutor.mjs.map +1 -1
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +3 -3
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +62 -9
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +20 -16
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +32 -3
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/utils/errors.mjs +317 -53
- package/dist/esm/utils/errors.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +62 -3
- package/dist/types/common/enum.d.ts +2 -0
- package/dist/types/graphs/Graph.d.ts +16 -2
- package/dist/types/graphs/MultiAgentGraph.d.ts +1 -0
- package/dist/types/llm/contextOverflowRecovery.d.ts +85 -0
- package/dist/types/llm/invoke.d.ts +35 -6
- package/dist/types/messages/prune.d.ts +10 -2
- package/dist/types/messages/recency.d.ts +1 -0
- package/dist/types/run.d.ts +2 -0
- package/dist/types/tools/CodeExecutor.d.ts +14 -1
- package/dist/types/types/llm.d.ts +7 -4
- package/dist/types/types/stream.d.ts +5 -4
- package/dist/types/types/summarize.d.ts +22 -0
- package/dist/types/utils/__tests__/fixtures/contextOverflowSignatures.d.ts +40 -0
- package/dist/types/utils/errors.d.ts +65 -16
- package/dist/types/utils/redactSecrets.d.ts +3 -0
- package/package.json +7 -8
- package/src/agents/AgentContext.ts +188 -7
- package/src/agents/__tests__/AgentContext.overflow.test.ts +205 -0
- package/src/common/enum.ts +2 -0
- package/src/graphs/Graph.ts +389 -58
- package/src/graphs/MultiAgentGraph.ts +184 -46
- package/src/graphs/__tests__/Graph.contextOverflow.test.ts +631 -0
- package/src/llm/__tests__/contextOverflowRecovery.test.ts +401 -0
- package/src/llm/__tests__/fallbackOverflow.test.ts +287 -0
- package/src/llm/bedrock/index.ts +25 -12
- package/src/llm/contextOverflowRecovery.ts +292 -0
- package/src/llm/invoke.ts +119 -4
- package/src/messages/prune.ts +24 -11
- package/src/messages/recency.ts +3 -1
- package/src/run.ts +24 -1
- package/src/scripts/context-overflow-probe.ts +997 -0
- package/src/specs/agent-handoffs.test.ts +903 -1
- package/src/specs/context-overflow-recovery.live.test.ts +213 -0
- package/src/splitStream.test.ts +882 -0
- package/src/stream.ts +315 -51
- package/src/summarization/__tests__/aggregator.test.ts +83 -0
- package/src/summarization/__tests__/node.test.ts +139 -0
- package/src/summarization/node.ts +99 -14
- package/src/tools/BashExecutor.ts +4 -2
- package/src/tools/BashProgrammaticToolCalling.ts +4 -7
- package/src/tools/CodeExecutor.ts +119 -8
- package/src/tools/ProgrammaticToolCalling.ts +29 -27
- package/src/tools/ToolNode.ts +50 -8
- package/src/tools/__tests__/CodeApiAuthHeaders.test.ts +297 -3
- package/src/types/llm.ts +8 -1
- package/src/types/stream.ts +5 -4
- package/src/types/summarize.ts +22 -0
- package/src/utils/__tests__/errors.test.ts +270 -0
- package/src/utils/__tests__/fixtures/contextOverflowSignatures.ts +336 -0
- package/src/utils/__tests__/redactSecrets.test.ts +56 -0
- package/src/utils/errors.ts +484 -66
- package/src/utils/redactSecrets.ts +61 -0
|
@@ -8,6 +8,41 @@ let _langchain_core_tools = require("@langchain/core/tools");
|
|
|
8
8
|
//#region src/graphs/MultiAgentGraph.ts
|
|
9
9
|
/** Pattern to extract instructions from transfer ToolMessage content */
|
|
10
10
|
const HANDOFF_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\s*(.+)/is;
|
|
11
|
+
const HANDOFF_INSTRUCTIONS_KEY = "handoff_instructions";
|
|
12
|
+
function getHandoffInstructions(input, promptKey, hasHandoffInput) {
|
|
13
|
+
if (!hasHandoffInput || !Object.prototype.hasOwnProperty.call(input, promptKey)) return null;
|
|
14
|
+
const value = input[promptKey];
|
|
15
|
+
return typeof value === "string" ? value : null;
|
|
16
|
+
}
|
|
17
|
+
function formatHandoffPromptLabel(promptKey) {
|
|
18
|
+
return promptKey.charAt(0).toUpperCase() + promptKey.slice(1);
|
|
19
|
+
}
|
|
20
|
+
function extractLegacyHandoffInstructions(content, promptLabels) {
|
|
21
|
+
let markerIndex = -1;
|
|
22
|
+
let markerLength = 0;
|
|
23
|
+
for (const label of promptLabels ?? []) {
|
|
24
|
+
const marker = `\n\n${label}:`;
|
|
25
|
+
const index = content.indexOf(marker);
|
|
26
|
+
if (index >= 0 && (markerIndex < 0 || index < markerIndex)) {
|
|
27
|
+
markerIndex = index;
|
|
28
|
+
markerLength = marker.length;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (markerIndex >= 0) return content.slice(markerIndex + markerLength).trim();
|
|
32
|
+
return content.match(HANDOFF_INSTRUCTIONS_PATTERN)?.[1]?.trim() ?? null;
|
|
33
|
+
}
|
|
34
|
+
function isValidHandoffGroupId(value) {
|
|
35
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
36
|
+
}
|
|
37
|
+
function withHandoffGroupMetadata(config, groupId) {
|
|
38
|
+
return {
|
|
39
|
+
...config,
|
|
40
|
+
metadata: {
|
|
41
|
+
...config?.metadata,
|
|
42
|
+
["__handoff_group_id"]: groupId ?? null
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
11
46
|
/**
|
|
12
47
|
* MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows
|
|
13
48
|
* with handoffs, fan-in/fan-out, and other composable patterns.
|
|
@@ -27,6 +62,7 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
27
62
|
startingNodes = /* @__PURE__ */ new Set();
|
|
28
63
|
directEdges = [];
|
|
29
64
|
handoffEdges = [];
|
|
65
|
+
handoffPromptLabels = /* @__PURE__ */ new Map();
|
|
30
66
|
/**
|
|
31
67
|
* Map of agentId to parallel group info.
|
|
32
68
|
* Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.
|
|
@@ -160,10 +196,21 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
160
196
|
*/
|
|
161
197
|
createHandoffTools() {
|
|
162
198
|
const handoffsByAgent = /* @__PURE__ */ new Map();
|
|
163
|
-
for (const edge of this.handoffEdges)
|
|
164
|
-
if (
|
|
165
|
-
|
|
166
|
-
|
|
199
|
+
for (const edge of this.handoffEdges) {
|
|
200
|
+
if (typeof edge.prompt === "string") {
|
|
201
|
+
const label = formatHandoffPromptLabel(edge.promptKey ?? "instructions");
|
|
202
|
+
const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];
|
|
203
|
+
for (const destination of destinations) {
|
|
204
|
+
const labels = this.handoffPromptLabels.get(destination) ?? /* @__PURE__ */ new Set();
|
|
205
|
+
labels.add(label);
|
|
206
|
+
this.handoffPromptLabels.set(destination, labels);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
(Array.isArray(edge.from) ? edge.from : [edge.from]).forEach((source) => {
|
|
210
|
+
if (!handoffsByAgent.has(source)) handoffsByAgent.set(source, []);
|
|
211
|
+
handoffsByAgent.get(source).push(edge);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
167
214
|
for (const [agentId, edges] of handoffsByAgent) {
|
|
168
215
|
const agentContext = this.agentContexts.get(agentId);
|
|
169
216
|
if (!agentContext) continue;
|
|
@@ -206,8 +253,9 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
206
253
|
else
|
|
207
254
|
/** Array of destinations - for now, use the first */
|
|
208
255
|
destination = Array.isArray(result) ? result[0] : destinations[0];
|
|
256
|
+
const handoffInstructions = getHandoffInstructions(input, promptKey, hasHandoffInput);
|
|
209
257
|
let content = `Conditionally transferred to ${destination}`;
|
|
210
|
-
if (
|
|
258
|
+
if (handoffInstructions !== null) content += `\n\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;
|
|
211
259
|
const toolMessage = new _langchain_core_messages.ToolMessage({
|
|
212
260
|
content,
|
|
213
261
|
name: toolName,
|
|
@@ -216,7 +264,8 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
216
264
|
/** Store destination for programmatic access in handoff detection */
|
|
217
265
|
handoff_destination: destination,
|
|
218
266
|
/** Store source agent name for receiving agent to know who handed off */
|
|
219
|
-
handoff_source_name: sourceAgentName
|
|
267
|
+
handoff_source_name: sourceAgentName,
|
|
268
|
+
...handoffInstructions !== null && { [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions }
|
|
220
269
|
}
|
|
221
270
|
});
|
|
222
271
|
return new _langchain_langgraph.Command({
|
|
@@ -252,15 +301,18 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
252
301
|
tools.push((0, _langchain_core_tools.tool)(async (rawInput, runtime) => {
|
|
253
302
|
const input = rawInput;
|
|
254
303
|
const toolCallId = runtime.toolCall?.id ?? "unknown";
|
|
304
|
+
const handoffInstructions = getHandoffInstructions(input, promptKey, hasHandoffInput);
|
|
255
305
|
let content = `Successfully transferred to ${destination}`;
|
|
256
|
-
if (
|
|
306
|
+
if (handoffInstructions !== null) content += `\n\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;
|
|
257
307
|
const toolMessage = new _langchain_core_messages.ToolMessage({
|
|
258
308
|
content,
|
|
259
309
|
name: toolName,
|
|
260
310
|
tool_call_id: toolCallId,
|
|
261
|
-
additional_kwargs: {
|
|
262
|
-
|
|
263
|
-
handoff_source_name: sourceAgentName
|
|
311
|
+
additional_kwargs: {
|
|
312
|
+
/** Store source agent name for receiving agent to know who handed off */
|
|
313
|
+
handoff_source_name: sourceAgentName,
|
|
314
|
+
...handoffInstructions !== null && { [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions }
|
|
315
|
+
}
|
|
264
316
|
});
|
|
265
317
|
/**
|
|
266
318
|
* For parallel handoff support:
|
|
@@ -356,18 +408,37 @@ handoff_source_name: sourceAgentName }
|
|
|
356
408
|
processHandoffReception(messages, agentId) {
|
|
357
409
|
if (messages.length === 0) return null;
|
|
358
410
|
/**
|
|
411
|
+
* A handoff is active only while resolving the most recent assistant
|
|
412
|
+
* tool-call round. Older transfer results remain in conversation history,
|
|
413
|
+
* but must not be reused when this agent is reached later through a direct
|
|
414
|
+
* edge or cycle.
|
|
415
|
+
*/
|
|
416
|
+
const activeTransferToolCallIds = /* @__PURE__ */ new Set();
|
|
417
|
+
let activeToolMessageStartIndex = messages.length;
|
|
418
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
419
|
+
const msg = messages[i];
|
|
420
|
+
if (msg.getType() === "tool") continue;
|
|
421
|
+
if (msg.getType() === "ai") {
|
|
422
|
+
const aiMsg = msg;
|
|
423
|
+
for (const toolCall of aiMsg.tool_calls ?? []) if (toolCall.id != null && (toolCall.name.startsWith("lc_transfer_to_") || toolCall.name === "conditional_transfer")) activeTransferToolCallIds.add(toolCall.id);
|
|
424
|
+
activeToolMessageStartIndex = i + 1;
|
|
425
|
+
}
|
|
426
|
+
break;
|
|
427
|
+
}
|
|
428
|
+
if (activeTransferToolCallIds.size === 0) return null;
|
|
429
|
+
/**
|
|
359
430
|
* Search for a transfer ToolMessage targeting this agent.
|
|
360
431
|
* For parallel handoffs, multiple transfer messages may exist - find ours.
|
|
361
432
|
* Search backwards from the end to find the most recent transfer to this agent.
|
|
362
433
|
*/
|
|
363
434
|
let toolMessage = null;
|
|
364
435
|
let toolMessageIndex = -1;
|
|
365
|
-
for (let i = messages.length - 1; i >=
|
|
436
|
+
for (let i = messages.length - 1; i >= activeToolMessageStartIndex; i--) {
|
|
366
437
|
const msg = messages[i];
|
|
367
438
|
if (msg.getType() !== "tool") continue;
|
|
368
439
|
const candidateMsg = msg;
|
|
369
440
|
const toolName = candidateMsg.name;
|
|
370
|
-
if (typeof toolName !== "string") continue;
|
|
441
|
+
if (typeof toolName !== "string" || !activeTransferToolCallIds.has(candidateMsg.tool_call_id)) continue;
|
|
371
442
|
/** Check for standard transfer pattern */
|
|
372
443
|
const isTransferMessage = toolName.startsWith("lc_transfer_to_");
|
|
373
444
|
const isConditionalTransfer = toolName === "conditional_transfer";
|
|
@@ -388,7 +459,10 @@ handoff_source_name: sourceAgentName }
|
|
|
388
459
|
}
|
|
389
460
|
/** No transfer targeting this agent found */
|
|
390
461
|
if (toolMessage === null || toolMessageIndex < 0) return null;
|
|
391
|
-
|
|
462
|
+
/** Extract instructions from the ToolMessage content */
|
|
463
|
+
const contentStr = typeof toolMessage.content === "string" ? toolMessage.content : JSON.stringify(toolMessage.content);
|
|
464
|
+
const structuredInstructions = toolMessage.additional_kwargs[HANDOFF_INSTRUCTIONS_KEY];
|
|
465
|
+
const instructions = typeof structuredInstructions === "string" ? structuredInstructions.trim() : extractLegacyHandoffInstructions(contentStr, this.handoffPromptLabels.get(agentId));
|
|
392
466
|
/** Extract source agent name from additional_kwargs */
|
|
393
467
|
const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;
|
|
394
468
|
const sourceAgentName = typeof handoffSourceName === "string" ? handoffSourceName : null;
|
|
@@ -398,6 +472,8 @@ handoff_source_name: sourceAgentName }
|
|
|
398
472
|
const parallelSiblings = (Array.isArray(rawSiblings) ? rawSiblings.filter((s) => typeof s === "string") : []).map((id) => {
|
|
399
473
|
return this.agentContexts.get(id)?.name ?? id;
|
|
400
474
|
});
|
|
475
|
+
const storedParallelGroupId = toolMessage.additional_kwargs["__handoff_group_id"];
|
|
476
|
+
const parallelGroupId = isValidHandoffGroupId(storedParallelGroupId) ? storedParallelGroupId : void 0;
|
|
401
477
|
/** Get the tool_call_id to find and filter the AI message's tool call */
|
|
402
478
|
const toolCallId = toolMessage.tool_call_id;
|
|
403
479
|
/**
|
|
@@ -406,12 +482,13 @@ handoff_source_name: sourceAgentName }
|
|
|
406
482
|
* to give the receiving agent a clean context without handoff noise.
|
|
407
483
|
*/
|
|
408
484
|
const transferToolCallIds = new Set([toolCallId]);
|
|
409
|
-
for (const msg of messages) {
|
|
410
|
-
if (msg.getType() !== "tool") continue;
|
|
485
|
+
for (const msg of messages) if (msg.getType() === "tool") {
|
|
411
486
|
const tm = msg;
|
|
412
487
|
const tName = tm.name;
|
|
413
|
-
if (typeof tName
|
|
414
|
-
|
|
488
|
+
if (typeof tName === "string" && (tName.startsWith("lc_transfer_to_") || tName === "conditional_transfer")) transferToolCallIds.add(tm.tool_call_id);
|
|
489
|
+
} else if (msg.getType() === "ai") {
|
|
490
|
+
const aiMsg = msg;
|
|
491
|
+
for (const toolCall of aiMsg.tool_calls ?? []) if (toolCall.id != null && (toolCall.name.startsWith("lc_transfer_to_") || toolCall.name === "conditional_transfer")) transferToolCallIds.add(toolCall.id);
|
|
415
492
|
}
|
|
416
493
|
/** Filter out all transfer messages */
|
|
417
494
|
const filteredMessages = [];
|
|
@@ -452,13 +529,15 @@ handoff_source_name: sourceAgentName }
|
|
|
452
529
|
filteredMessages,
|
|
453
530
|
instructions,
|
|
454
531
|
sourceAgentName,
|
|
455
|
-
parallelSiblings
|
|
532
|
+
parallelSiblings,
|
|
533
|
+
parallelGroupId
|
|
456
534
|
};
|
|
457
535
|
}
|
|
458
536
|
/**
|
|
459
537
|
* Create the multi-agent workflow with dynamic handoffs
|
|
460
538
|
*/
|
|
461
539
|
createWorkflow() {
|
|
540
|
+
this.hasCompiledCheckpointer = this.compileOptions?.checkpointer != null;
|
|
462
541
|
const builder = new _langchain_langgraph.StateGraph(_langchain_langgraph.Annotation.Root({
|
|
463
542
|
messages: (0, _langchain_langgraph.Annotation)({
|
|
464
543
|
reducer: (a, b) => {
|
|
@@ -500,14 +579,11 @@ handoff_source_name: sourceAgentName }
|
|
|
500
579
|
* and prematurely producing an end token.
|
|
501
580
|
*/
|
|
502
581
|
const handoffContext = this.processHandoffReception(state.messages, agentId);
|
|
582
|
+
const agentContext = this.agentContexts.get(agentId);
|
|
583
|
+
if (handoffContext?.sourceAgentName != null && handoffContext.sourceAgentName !== "") agentContext?.setHandoffContext(handoffContext.sourceAgentName, handoffContext.parallelSiblings);
|
|
584
|
+
else agentContext?.clearHandoffContext();
|
|
503
585
|
if (handoffContext !== null) {
|
|
504
|
-
const { filteredMessages, instructions,
|
|
505
|
-
/**
|
|
506
|
-
* Set handoff context on the receiving agent.
|
|
507
|
-
* Uses pre-computed graph position for depth and parallel info.
|
|
508
|
-
*/
|
|
509
|
-
const agentContext = this.agentContexts.get(agentId);
|
|
510
|
-
if (agentContext && sourceAgentName != null && sourceAgentName !== "") agentContext.setHandoffContext(sourceAgentName, parallelSiblings);
|
|
586
|
+
const { filteredMessages, instructions, parallelGroupId } = handoffContext;
|
|
511
587
|
/** Build messages for the receiving agent */
|
|
512
588
|
let messagesForAgent = filteredMessages;
|
|
513
589
|
/**
|
|
@@ -547,7 +623,7 @@ handoff_source_name: sourceAgentName }
|
|
|
547
623
|
...state,
|
|
548
624
|
messages: messagesForAgent
|
|
549
625
|
};
|
|
550
|
-
result = await agentSubgraph.invoke(transformedState, config);
|
|
626
|
+
result = await agentSubgraph.invoke(transformedState, withHandoffGroupMetadata(config, parallelGroupId));
|
|
551
627
|
result = {
|
|
552
628
|
...result,
|
|
553
629
|
agentMessages: []
|
|
@@ -557,7 +633,6 @@ handoff_source_name: sourceAgentName }
|
|
|
557
633
|
* When using agentMessages (excludeResults=true), we need to update
|
|
558
634
|
* the token map to account for the new prompt message
|
|
559
635
|
*/
|
|
560
|
-
const agentContext = this.agentContexts.get(agentId);
|
|
561
636
|
if (agentContext && agentContext.tokenCounter) {
|
|
562
637
|
/** The agentMessages contains:
|
|
563
638
|
* 1. Filtered messages (0 to startIndex) - already have token counts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultiAgentGraph.cjs","names":["StandardGraph","ToolMessage","Command","aiMsg","AIMessage","StateGraph","Annotation","END","HumanMessage","START","PromptTemplate"],"sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { ToolRuntime } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst HANDOFF_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\\s*(.+)/is;\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns.\n *\n * Key behavior:\n * - Agents with ONLY handoff edges: Can dynamically route to any handoff destination\n * - Agents with ONLY direct edges: Always follow their direct edges\n * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)\n * - If handoff occurs: Only the handoff destination executes\n * - If no handoff: Direct edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either delegates (handoff)\n * OR continues its workflow (direct edges), but not both simultaneously.\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.validateEdgeAgents();\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Fails fast when an edge references an agent that is not in\n * `agentContexts`. Without this check, the underlying LangGraph\n * `StateGraph.compile()` would throw the opaque\n * `Found edge ending at unknown node \"<id>\"` error after graph\n * construction — far from the true root cause.\n *\n * This catches the common misuse of passing `edges` into a multi-agent\n * config without also passing the corresponding sub-agent configs in\n * `agents` (e.g. a host that forgot to pre-load handoff targets).\n */\n private validateEdgeAgents(): void {\n const known = new Set(this.agentContexts.keys());\n const unknown = new Set<string>();\n for (const edge of this.edges) {\n const participants = [\n ...(Array.isArray(edge.from) ? edge.from : [edge.from]),\n ...(Array.isArray(edge.to) ? edge.to : [edge.to]),\n ];\n for (const id of participants) {\n if (typeof id === 'string' && !known.has(id)) {\n unknown.add(id);\n }\n }\n }\n if (unknown.size === 0) {\n return;\n }\n const missing = Array.from(unknown)\n .map((id) => `\"${id}\"`)\n .join(', ');\n throw new Error(\n `MultiAgentGraph: edges reference agent(s) not present in agents: [${missing}]. ` +\n 'Ensure every agent referenced by an edge is also included in the `agents` array, ' +\n 'or filter orphaned edges before constructing the graph.'\n );\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\n }\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n\n // Determine if graph has parallel execution capability\n this.computeParallelCapability();\n }\n\n /**\n * Compute parallel groups by traversing the graph in execution order.\n * Assigns incrementing group IDs that reflect the sequential order of execution.\n *\n * For: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: no group (first sequential node)\n * - analyst1, analyst2, analyst3: groupId 1 (first parallel group)\n * - summarizer: no group (next sequential node)\n *\n * This allows frontend to render in order:\n * Row 0: researcher\n * Row 1: [analyst1, analyst2, analyst3] (grouped)\n * Row 2: summarizer\n */\n private computeParallelCapability(): void {\n let groupCounter = 1; // Start at 1, 0 reserved for \"no group\"\n\n // Check 1: Multiple starting nodes means parallel from the start (group 1)\n if (this.startingNodes.size > 1) {\n for (const agentId of this.startingNodes) {\n this.agentParallelGroups.set(agentId, groupCounter);\n }\n groupCounter++;\n }\n\n // Check 2: Traverse direct edges in order to find fan-out patterns\n // Build a simple execution order by following edges from starting nodes\n const visited = new Set<string>();\n const queue: string[] = [...this.startingNodes];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n // Find direct edges from this node\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n // Fan-out: multiple destinations = parallel group\n if (destinations.length > 1) {\n for (const dest of destinations) {\n // Only set if not already in a group (first group wins)\n if (!this.agentParallelGroups.has(dest)) {\n this.agentParallelGroups.set(dest, groupCounter);\n }\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n groupCounter++;\n } else {\n // Single destination - add to queue for traversal\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n\n // Also follow handoff edges for traversal (but they don't create parallel groups)\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Returns undefined if the agent is not part of a parallel group.\n * Group IDs are incrementing numbers reflecting execution order.\n */\n getParallelGroupId(agentId: string): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Override to indicate this is a multi-agent graph.\n * Enables agentId to be included in RunStep for frontend agent labeling.\n */\n protected override isMultiAgentGraph(): boolean {\n return true;\n }\n\n /**\n * Override base class method to provide parallel group IDs for run steps.\n */\n protected override getParallelGroupIdForAgent(\n agentId: string\n ): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Create handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n const sourceAgentName = agentContext.name ?? agentId;\n for (const edge of edges) {\n handoffTools.push(\n ...this.createHandoffToolsForEdge(edge, agentId, sourceAgentName)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...handoffTools);\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n * @param edge - The graph edge defining the handoff\n * @param sourceAgentId - The ID of the agent that will perform the handoff\n * @param sourceAgentName - The human-readable name of the source agent\n */\n private createHandoffToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string,\n sourceAgentName: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const state = runtime.state as t.BaseGraphState;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n let content = `Conditionally transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store destination for programmatic access in handoff detection */\n handoff_destination: destination,\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n let content = `Successfully transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n const state = runtime.state as t.BaseGraphState;\n\n /**\n * For parallel handoff support:\n * Build messages that include ONLY this tool call's context.\n * This prevents errors when LLM calls multiple transfers simultaneously -\n * each destination gets a valid AIMessage with matching tool_call and tool_result.\n *\n * Strategy:\n * 1. Find the AIMessage containing this tool call\n * 2. Create a filtered AIMessage with ONLY this tool_call\n * 3. Include all messages before the AIMessage plus the filtered pair\n */\n const messages = state.messages;\n let filteredMessages = messages;\n let aiMessageIndex = -1;\n\n /** Find the AIMessage containing this tool call */\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage;\n const hasThisCall = aiMsg.tool_calls?.some(\n (tc) => tc.id === toolCallId\n );\n if (hasThisCall === true) {\n aiMessageIndex = i;\n break;\n }\n }\n }\n\n if (aiMessageIndex >= 0) {\n const originalAiMsg = messages[aiMessageIndex] as AIMessage;\n const thisToolCall = originalAiMsg.tool_calls?.find(\n (tc) => tc.id === toolCallId\n );\n\n if (\n thisToolCall != null &&\n (originalAiMsg.tool_calls?.length ?? 0) > 1\n ) {\n /**\n * Multiple tool calls - create filtered AIMessage with ONLY this call.\n * This ensures valid message structure for parallel handoffs.\n */\n const filteredAiMsg = new AIMessage({\n content: originalAiMsg.content,\n tool_calls: [thisToolCall],\n id: originalAiMsg.id,\n });\n\n filteredMessages = [\n ...messages.slice(0, aiMessageIndex),\n filteredAiMsg,\n toolMessage,\n ];\n } else {\n /** Single tool call - use messages as-is */\n filteredMessages = messages.concat(toolMessage);\n }\n } else {\n /** Fallback - append tool message */\n filteredMessages = messages.concat(toolMessage);\n }\n\n return new Command({\n goto: destination,\n update: { messages: filteredMessages },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * Search for a transfer ToolMessage targeting this agent.\n * For parallel handoffs, multiple transfer messages may exist - find ours.\n * Search backwards from the end to find the most recent transfer to this agent.\n */\n let toolMessage: ToolMessage | null = null;\n let toolMessageIndex = -1;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'tool') continue;\n\n const candidateMsg = msg as ToolMessage;\n const toolName = candidateMsg.name;\n\n if (typeof toolName !== 'string') continue;\n\n /** Check for standard transfer pattern */\n const isTransferMessage = toolName.startsWith(Constants.LC_TRANSFER_TO_);\n const isConditionalTransfer = toolName === 'conditional_transfer';\n\n if (!isTransferMessage && !isConditionalTransfer) continue;\n\n /** Extract destination from tool name or additional_kwargs */\n let destinationAgent: string | null = null;\n\n if (isTransferMessage) {\n destinationAgent = toolName.replace(Constants.LC_TRANSFER_TO_, '');\n } else if (isConditionalTransfer) {\n const handoffDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof handoffDest === 'string' ? handoffDest : null;\n }\n\n /** Check if this transfer targets our agent */\n if (destinationAgent === agentId) {\n toolMessage = candidateMsg;\n toolMessageIndex = i;\n break;\n }\n }\n\n /** No transfer targeting this agent found */\n if (toolMessage === null || toolMessageIndex < 0) return null;\n\n /** Extract instructions from the ToolMessage content */\n const contentStr =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n const instructionsMatch = contentStr.match(HANDOFF_INSTRUCTIONS_PATTERN);\n const instructions = instructionsMatch?.[1]?.trim() ?? null;\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n\n /** Get the tool_call_id to find and filter the AI message's tool call */\n const toolCallId = toolMessage.tool_call_id;\n\n /**\n * Collect all transfer tool_call_ids to filter out.\n * For parallel handoffs, we filter ALL transfer messages (not just ours)\n * to give the receiving agent a clean context without handoff noise.\n */\n const transferToolCallIds = new Set<string>([toolCallId]);\n for (const msg of messages) {\n if (msg.getType() !== 'tool') continue;\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (typeof tName !== 'string') continue;\n if (\n tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer'\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n }\n\n /** Filter out all transfer messages */\n const filteredMessages: BaseMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const msgType = msg.getType();\n\n /** Skip transfer ToolMessages */\n if (msgType === 'tool') {\n const tm = msg as ToolMessage;\n if (transferToolCallIds.has(tm.tool_call_id)) {\n continue;\n }\n }\n\n if (msgType === 'ai') {\n /** Check if this AI message contains any transfer tool calls */\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Filter out all transfer tool calls */\n const remainingToolCalls = toolCalls.filter(\n (tc) => tc.id == null || !transferToolCallIds.has(tc.id)\n );\n\n const hasTransferCalls = remainingToolCalls.length < toolCalls.length;\n\n if (hasTransferCalls) {\n if (\n remainingToolCalls.length > 0 ||\n (typeof aiMsg.content === 'string' && aiMsg.content.trim())\n ) {\n /** Keep the message but without transfer tool calls */\n const filteredAiMsg = new AIMessage({\n content: aiMsg.content,\n tool_calls: remainingToolCalls,\n id: aiMsg.id,\n });\n filteredMessages.push(filteredAiMsg);\n }\n /** If no remaining content or tool calls, skip this message entirely */\n continue;\n }\n }\n }\n\n /** Keep all other messages */\n filteredMessages.push(msg);\n }\n\n return {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n // Add all agents as complete subgraphs\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => directDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH handoff and direct edges */\n const hasHandoffEdges = handoffDestinations.size > 0;\n const hasDirectEdges = directDestinations.size > 0;\n const needsCommandRouting = hasHandoffEdges && hasDirectEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...handoffDestinations,\n ...directDestinations,\n ]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState,\n config?: LangGraphRunnableConfig\n ): Promise<t.MultiAgentGraphState | Command> => {\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a handoff.\n * If so, filter out the transfer messages and inject instructions as preamble.\n * This prevents the receiving agent from seeing the transfer as \"completed work\"\n * and prematurely producing an end token.\n */\n const handoffContext = this.processHandoffReception(\n state.messages,\n agentId\n );\n\n if (handoffContext !== null) {\n const {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n } = handoffContext;\n\n /**\n * Set handoff context on the receiving agent.\n * Uses pre-computed graph position for depth and parallel info.\n */\n const agentContext = this.agentContexts.get(agentId);\n if (\n agentContext &&\n sourceAgentName != null &&\n sourceAgentName !== ''\n ) {\n agentContext.setHandoffContext(sourceAgentName, parallelSiblings);\n }\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n new HumanMessage(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n new HumanMessage(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n agentMessages: [],\n };\n } else if (\n state.agentMessages != null &&\n state.agentMessages.length > 0\n ) {\n /**\n * When using agentMessages (excludeResults=true), we need to update\n * the token map to account for the new prompt message\n */\n const agentContext = this.agentContexts.get(agentId);\n if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** If agent has both handoff and direct edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a handoff occurred */\n const lastMessage = result.messages[\n result.messages.length - 1\n ] as BaseMessage | null;\n if (\n lastMessage != null &&\n lastMessage.getType() === 'tool' &&\n typeof lastMessage.name === 'string' &&\n lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) {\n /** Handoff occurred - extract destination and navigate there exclusively */\n const handoffDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n return new Command({\n update: result,\n goto: handoffDest,\n });\n } else {\n /** No handoff - proceed with direct edges */\n const directDests = Array.from(directDestinations);\n if (directDests.length === 1) {\n return new Command({\n update: result,\n goto: directDests[0],\n });\n } else if (directDests.length > 1) {\n /** Multiple direct destinations - they'll run in parallel */\n return new Command({\n update: result,\n goto: directDests,\n });\n }\n }\n }\n\n /** No special routing needed - return state normally */\n return result;\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(allDestinations),\n });\n }\n\n // Add starting edges for all starting nodes\n for (const startNode of this.startingNodes) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(START, startNode);\n }\n\n /**\n * Add direct edges for automatic transitions\n * Group edges by destination to handle fan-in scenarios\n */\n const edgesByDestination = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.directEdges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n if (!edgesByDestination.has(destination)) {\n edgesByDestination.set(destination, []);\n }\n edgesByDestination.get(destination)!.push(edge);\n }\n }\n\n for (const [destination, edges] of edgesByDestination) {\n /** Checks if this is a fan-in scenario with prompt instructions */\n const edgesWithPrompt = edges.filter(\n (edge) => edge.prompt != null && edge.prompt !== ''\n );\n\n if (edgesWithPrompt.length > 0) {\n /**\n * Single wrapper node for destination (Fan-in with prompt)\n */\n const wrapperNodeId = `fan_in_${destination}_prompt`;\n /**\n * First edge's `prompt`\n * (they should all be the same for fan-in)\n */\n const prompt = edgesWithPrompt[0].prompt;\n /**\n * First edge's `excludeResults` flag\n * (they should all be the same for fan-in)\n */\n const excludeResults = edgesWithPrompt[0].excludeResults;\n\n builder.addNode(wrapperNodeId, async (state: t.BaseGraphState) => {\n let promptText: string | undefined;\n let effectiveExcludeResults = excludeResults;\n\n if (typeof prompt === 'function') {\n promptText = await prompt(state.messages, this.startIndex);\n } else if (prompt != null) {\n if (prompt.includes('{results}')) {\n const resultsMessages = state.messages.slice(this.startIndex);\n const resultsString = getBufferString(resultsMessages);\n const promptTemplate = PromptTemplate.fromTemplate(prompt);\n const result = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = result.value;\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [new HumanMessage(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n const promptMessage = new HumanMessage(promptText);\n return {\n messages: [promptMessage],\n agentMessages: messagesStateReducer(filteredMessages, [\n promptMessage,\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges (skip if source uses Command routing) */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n /** Check if this source node has both handoff and direct edges */\n const sourceHandoffEdges = this.handoffEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceDirectEdges = this.directEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n\n /** Skip adding edge if source uses Command routing (has both types) */\n if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n }\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"mappings":";;;;;;;;;AAwBA,MAAM,+BAA+B;;;;;;;;;;;;;;;AAgBrC,IAAa,kBAAb,cAAqCA,cAAAA,cAAc;CACjD;CACA,gCAAqC,IAAI,IAAI;CAC7C,cAAqC,CAAC;CACtC,eAAsC,CAAC;;;;;;;;;;;CAWvC,sCAAmD,IAAI,IAAI;CAE3D,YAAY,OAA+B;EACzC,MAAM,KAAK;EACX,KAAK,QAAQ,MAAM;EACnB,KAAK,mBAAmB;EACxB,KAAK,gBAAgB;EACrB,KAAK,aAAa;EAClB,KAAK,mBAAmB;CAC1B;;;;;;;;;;;;CAaA,qBAAmC;EACjC,MAAM,QAAQ,IAAI,IAAI,KAAK,cAAc,KAAK,CAAC;EAC/C,MAAM,0BAAU,IAAI,IAAY;EAChC,KAAK,MAAM,QAAQ,KAAK,OAAO;GAC7B,MAAM,eAAe,CACnB,GAAI,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI,GACrD,GAAI,MAAM,QAAQ,KAAK,EAAE,IAAI,KAAK,KAAK,CAAC,KAAK,EAAE,CACjD;GACA,KAAK,MAAM,MAAM,cACf,IAAI,OAAO,OAAO,YAAY,CAAC,MAAM,IAAI,EAAE,GACzC,QAAQ,IAAI,EAAE;EAGpB;EACA,IAAI,QAAQ,SAAS,GACnB;EAEF,MAAM,UAAU,MAAM,KAAK,OAAO,CAAC,CAChC,KAAK,OAAO,IAAI,GAAG,EAAE,CAAC,CACtB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KF,QAAQ,QAAQ,QAAQ,WAAW;IACrC;GACF;EAEJ;EAEA,OAAO,QAAQ,QAAQ,KAAK,cAAkC;CAChE;AACF"}
|
|
1
|
+
{"version":3,"file":"MultiAgentGraph.cjs","names":["StandardGraph","ToolMessage","Command","aiMsg","AIMessage","StateGraph","Annotation","END","HumanMessage","START","PromptTemplate"],"sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { ToolRuntime } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst HANDOFF_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\\s*(.+)/is;\nconst HANDOFF_INSTRUCTIONS_KEY = 'handoff_instructions';\n\nfunction getHandoffInstructions(\n input: Record<string, unknown>,\n promptKey: string,\n hasHandoffInput: boolean\n): string | null {\n if (\n !hasHandoffInput ||\n !Object.prototype.hasOwnProperty.call(input, promptKey)\n ) {\n return null;\n }\n const value = input[promptKey];\n return typeof value === 'string' ? value : null;\n}\n\nfunction formatHandoffPromptLabel(promptKey: string): string {\n return promptKey.charAt(0).toUpperCase() + promptKey.slice(1);\n}\n\nfunction extractLegacyHandoffInstructions(\n content: string,\n promptLabels: Set<string> | undefined\n): string | null {\n let markerIndex = -1;\n let markerLength = 0;\n for (const label of promptLabels ?? []) {\n const marker = `\\n\\n${label}:`;\n const index = content.indexOf(marker);\n if (index >= 0 && (markerIndex < 0 || index < markerIndex)) {\n markerIndex = index;\n markerLength = marker.length;\n }\n }\n if (markerIndex >= 0) {\n return content.slice(markerIndex + markerLength).trim();\n }\n return content.match(HANDOFF_INSTRUCTIONS_PATTERN)?.[1]?.trim() ?? null;\n}\n\nfunction isValidHandoffGroupId(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction withHandoffGroupMetadata(\n config: LangGraphRunnableConfig | undefined,\n groupId: number | undefined\n): LangGraphRunnableConfig {\n return {\n ...config,\n metadata: {\n ...config?.metadata,\n [Constants.HANDOFF_GROUP_ID]: groupId ?? null,\n },\n };\n}\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns.\n *\n * Key behavior:\n * - Agents with ONLY handoff edges: Can dynamically route to any handoff destination\n * - Agents with ONLY direct edges: Always follow their direct edges\n * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)\n * - If handoff occurs: Only the handoff destination executes\n * - If no handoff: Direct edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either delegates (handoff)\n * OR continues its workflow (direct edges), but not both simultaneously.\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n private handoffPromptLabels: Map<string, Set<string>> = new Map();\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.validateEdgeAgents();\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Fails fast when an edge references an agent that is not in\n * `agentContexts`. Without this check, the underlying LangGraph\n * `StateGraph.compile()` would throw the opaque\n * `Found edge ending at unknown node \"<id>\"` error after graph\n * construction — far from the true root cause.\n *\n * This catches the common misuse of passing `edges` into a multi-agent\n * config without also passing the corresponding sub-agent configs in\n * `agents` (e.g. a host that forgot to pre-load handoff targets).\n */\n private validateEdgeAgents(): void {\n const known = new Set(this.agentContexts.keys());\n const unknown = new Set<string>();\n for (const edge of this.edges) {\n const participants = [\n ...(Array.isArray(edge.from) ? edge.from : [edge.from]),\n ...(Array.isArray(edge.to) ? edge.to : [edge.to]),\n ];\n for (const id of participants) {\n if (typeof id === 'string' && !known.has(id)) {\n unknown.add(id);\n }\n }\n }\n if (unknown.size === 0) {\n return;\n }\n const missing = Array.from(unknown)\n .map((id) => `\"${id}\"`)\n .join(', ');\n throw new Error(\n `MultiAgentGraph: edges reference agent(s) not present in agents: [${missing}]. ` +\n 'Ensure every agent referenced by an edge is also included in the `agents` array, ' +\n 'or filter orphaned edges before constructing the graph.'\n );\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\n }\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n\n // Determine if graph has parallel execution capability\n this.computeParallelCapability();\n }\n\n /**\n * Compute parallel groups by traversing the graph in execution order.\n * Assigns incrementing group IDs that reflect the sequential order of execution.\n *\n * For: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: no group (first sequential node)\n * - analyst1, analyst2, analyst3: groupId 1 (first parallel group)\n * - summarizer: no group (next sequential node)\n *\n * This allows frontend to render in order:\n * Row 0: researcher\n * Row 1: [analyst1, analyst2, analyst3] (grouped)\n * Row 2: summarizer\n */\n private computeParallelCapability(): void {\n let groupCounter = 1; // Start at 1, 0 reserved for \"no group\"\n\n // Check 1: Multiple starting nodes means parallel from the start (group 1)\n if (this.startingNodes.size > 1) {\n for (const agentId of this.startingNodes) {\n this.agentParallelGroups.set(agentId, groupCounter);\n }\n groupCounter++;\n }\n\n // Check 2: Traverse direct edges in order to find fan-out patterns\n // Build a simple execution order by following edges from starting nodes\n const visited = new Set<string>();\n const queue: string[] = [...this.startingNodes];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n // Find direct edges from this node\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n // Fan-out: multiple destinations = parallel group\n if (destinations.length > 1) {\n for (const dest of destinations) {\n // Only set if not already in a group (first group wins)\n if (!this.agentParallelGroups.has(dest)) {\n this.agentParallelGroups.set(dest, groupCounter);\n }\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n groupCounter++;\n } else {\n // Single destination - add to queue for traversal\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n\n // Also follow handoff edges for traversal (but they don't create parallel groups)\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Returns undefined if the agent is not part of a parallel group.\n * Group IDs are incrementing numbers reflecting execution order.\n */\n getParallelGroupId(agentId: string): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Override to indicate this is a multi-agent graph.\n * Enables agentId to be included in RunStep for frontend agent labeling.\n */\n protected override isMultiAgentGraph(): boolean {\n return true;\n }\n\n /**\n * Override base class method to provide parallel group IDs for run steps.\n */\n protected override getParallelGroupIdForAgent(\n agentId: string\n ): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Create handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\n for (const edge of this.handoffEdges) {\n if (typeof edge.prompt === 'string') {\n const label = formatHandoffPromptLabel(\n edge.promptKey ?? 'instructions'\n );\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n const labels =\n this.handoffPromptLabels.get(destination) ?? new Set<string>();\n labels.add(label);\n this.handoffPromptLabels.set(destination, labels);\n }\n }\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n const sourceAgentName = agentContext.name ?? agentId;\n for (const edge of edges) {\n handoffTools.push(\n ...this.createHandoffToolsForEdge(edge, agentId, sourceAgentName)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...handoffTools);\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n * @param edge - The graph edge defining the handoff\n * @param sourceAgentId - The ID of the agent that will perform the handoff\n * @param sourceAgentName - The human-readable name of the source agent\n */\n private createHandoffToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string,\n sourceAgentName: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const state = runtime.state as t.BaseGraphState;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n const handoffInstructions = getHandoffInstructions(\n input,\n promptKey,\n hasHandoffInput\n );\n let content = `Conditionally transferred to ${destination}`;\n if (handoffInstructions !== null) {\n content += `\\n\\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store destination for programmatic access in handoff detection */\n handoff_destination: destination,\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n ...(handoffInstructions !== null && {\n [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions,\n }),\n },\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n const handoffInstructions = getHandoffInstructions(\n input,\n promptKey,\n hasHandoffInput\n );\n let content = `Successfully transferred to ${destination}`;\n if (handoffInstructions !== null) {\n content += `\\n\\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n ...(handoffInstructions !== null && {\n [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions,\n }),\n },\n });\n\n const state = runtime.state as t.BaseGraphState;\n\n /**\n * For parallel handoff support:\n * Build messages that include ONLY this tool call's context.\n * This prevents errors when LLM calls multiple transfers simultaneously -\n * each destination gets a valid AIMessage with matching tool_call and tool_result.\n *\n * Strategy:\n * 1. Find the AIMessage containing this tool call\n * 2. Create a filtered AIMessage with ONLY this tool_call\n * 3. Include all messages before the AIMessage plus the filtered pair\n */\n const messages = state.messages;\n let filteredMessages = messages;\n let aiMessageIndex = -1;\n\n /** Find the AIMessage containing this tool call */\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage;\n const hasThisCall = aiMsg.tool_calls?.some(\n (tc) => tc.id === toolCallId\n );\n if (hasThisCall === true) {\n aiMessageIndex = i;\n break;\n }\n }\n }\n\n if (aiMessageIndex >= 0) {\n const originalAiMsg = messages[aiMessageIndex] as AIMessage;\n const thisToolCall = originalAiMsg.tool_calls?.find(\n (tc) => tc.id === toolCallId\n );\n\n if (\n thisToolCall != null &&\n (originalAiMsg.tool_calls?.length ?? 0) > 1\n ) {\n /**\n * Multiple tool calls - create filtered AIMessage with ONLY this call.\n * This ensures valid message structure for parallel handoffs.\n */\n const filteredAiMsg = new AIMessage({\n content: originalAiMsg.content,\n tool_calls: [thisToolCall],\n id: originalAiMsg.id,\n });\n\n filteredMessages = [\n ...messages.slice(0, aiMessageIndex),\n filteredAiMsg,\n toolMessage,\n ];\n } else {\n /** Single tool call - use messages as-is */\n filteredMessages = messages.concat(toolMessage);\n }\n } else {\n /** Fallback - append tool message */\n filteredMessages = messages.concat(toolMessage);\n }\n\n return new Command({\n goto: destination,\n update: { messages: filteredMessages },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n parallelGroupId?: number;\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * A handoff is active only while resolving the most recent assistant\n * tool-call round. Older transfer results remain in conversation history,\n * but must not be reused when this agent is reached later through a direct\n * edge or cycle.\n */\n const activeTransferToolCallIds = new Set<string>();\n let activeToolMessageStartIndex = messages.length;\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'tool') continue;\n\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n for (const toolCall of aiMsg.tool_calls ?? []) {\n if (\n toolCall.id != null &&\n (toolCall.name.startsWith(Constants.LC_TRANSFER_TO_) ||\n toolCall.name === 'conditional_transfer')\n ) {\n activeTransferToolCallIds.add(toolCall.id);\n }\n }\n activeToolMessageStartIndex = i + 1;\n }\n break;\n }\n\n if (activeTransferToolCallIds.size === 0) return null;\n\n /**\n * Search for a transfer ToolMessage targeting this agent.\n * For parallel handoffs, multiple transfer messages may exist - find ours.\n * Search backwards from the end to find the most recent transfer to this agent.\n */\n let toolMessage: ToolMessage | null = null;\n let toolMessageIndex = -1;\n\n for (let i = messages.length - 1; i >= activeToolMessageStartIndex; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'tool') continue;\n\n const candidateMsg = msg as ToolMessage;\n const toolName = candidateMsg.name;\n\n if (\n typeof toolName !== 'string' ||\n !activeTransferToolCallIds.has(candidateMsg.tool_call_id)\n ) {\n continue;\n }\n\n /** Check for standard transfer pattern */\n const isTransferMessage = toolName.startsWith(Constants.LC_TRANSFER_TO_);\n const isConditionalTransfer = toolName === 'conditional_transfer';\n\n if (!isTransferMessage && !isConditionalTransfer) continue;\n\n /** Extract destination from tool name or additional_kwargs */\n let destinationAgent: string | null = null;\n\n if (isTransferMessage) {\n destinationAgent = toolName.replace(Constants.LC_TRANSFER_TO_, '');\n } else if (isConditionalTransfer) {\n const handoffDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof handoffDest === 'string' ? handoffDest : null;\n }\n\n /** Check if this transfer targets our agent */\n if (destinationAgent === agentId) {\n toolMessage = candidateMsg;\n toolMessageIndex = i;\n break;\n }\n }\n\n /** No transfer targeting this agent found */\n if (toolMessage === null || toolMessageIndex < 0) return null;\n\n /** Extract instructions from the ToolMessage content */\n const contentStr =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n const structuredInstructions =\n toolMessage.additional_kwargs[HANDOFF_INSTRUCTIONS_KEY];\n const instructions =\n typeof structuredInstructions === 'string'\n ? structuredInstructions.trim()\n : extractLegacyHandoffInstructions(\n contentStr,\n this.handoffPromptLabels.get(agentId)\n );\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n const storedParallelGroupId =\n toolMessage.additional_kwargs[Constants.HANDOFF_GROUP_ID];\n const parallelGroupId = isValidHandoffGroupId(storedParallelGroupId)\n ? storedParallelGroupId\n : undefined;\n\n /** Get the tool_call_id to find and filter the AI message's tool call */\n const toolCallId = toolMessage.tool_call_id;\n\n /**\n * Collect all transfer tool_call_ids to filter out.\n * For parallel handoffs, we filter ALL transfer messages (not just ours)\n * to give the receiving agent a clean context without handoff noise.\n */\n const transferToolCallIds = new Set<string>([toolCallId]);\n for (const msg of messages) {\n if (msg.getType() === 'tool') {\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (\n typeof tName === 'string' &&\n (tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer')\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n } else if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n for (const toolCall of aiMsg.tool_calls ?? []) {\n if (\n toolCall.id != null &&\n (toolCall.name.startsWith(Constants.LC_TRANSFER_TO_) ||\n toolCall.name === 'conditional_transfer')\n ) {\n transferToolCallIds.add(toolCall.id);\n }\n }\n }\n }\n\n /** Filter out all transfer messages */\n const filteredMessages: BaseMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const msgType = msg.getType();\n\n /** Skip transfer ToolMessages */\n if (msgType === 'tool') {\n const tm = msg as ToolMessage;\n if (transferToolCallIds.has(tm.tool_call_id)) {\n continue;\n }\n }\n\n if (msgType === 'ai') {\n /** Check if this AI message contains any transfer tool calls */\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Filter out all transfer tool calls */\n const remainingToolCalls = toolCalls.filter(\n (tc) => tc.id == null || !transferToolCallIds.has(tc.id)\n );\n\n const hasTransferCalls = remainingToolCalls.length < toolCalls.length;\n\n if (hasTransferCalls) {\n if (\n remainingToolCalls.length > 0 ||\n (typeof aiMsg.content === 'string' && aiMsg.content.trim())\n ) {\n /** Keep the message but without transfer tool calls */\n const filteredAiMsg = new AIMessage({\n content: aiMsg.content,\n tool_calls: remainingToolCalls,\n id: aiMsg.id,\n });\n filteredMessages.push(filteredAiMsg);\n }\n /** If no remaining content or tool calls, skip this message entirely */\n continue;\n }\n }\n }\n\n /** Keep all other messages */\n filteredMessages.push(msg);\n }\n\n return {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n parallelGroupId,\n };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n this.hasCompiledCheckpointer = this.compileOptions?.checkpointer != null;\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n // Add all agents as complete subgraphs\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => directDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH handoff and direct edges */\n const hasHandoffEdges = handoffDestinations.size > 0;\n const hasDirectEdges = directDestinations.size > 0;\n const needsCommandRouting = hasHandoffEdges && hasDirectEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...handoffDestinations,\n ...directDestinations,\n ]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState,\n config?: LangGraphRunnableConfig\n ): Promise<t.MultiAgentGraphState | Command> => {\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a handoff.\n * If so, filter out the transfer messages and inject instructions as preamble.\n * This prevents the receiving agent from seeing the transfer as \"completed work\"\n * and prematurely producing an end token.\n */\n const handoffContext = this.processHandoffReception(\n state.messages,\n agentId\n );\n const agentContext = this.agentContexts.get(agentId);\n\n if (\n handoffContext?.sourceAgentName != null &&\n handoffContext.sourceAgentName !== ''\n ) {\n agentContext?.setHandoffContext(\n handoffContext.sourceAgentName,\n handoffContext.parallelSiblings\n );\n } else {\n agentContext?.clearHandoffContext();\n }\n\n if (handoffContext !== null) {\n const { filteredMessages, instructions, parallelGroupId } =\n handoffContext;\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n new HumanMessage(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n new HumanMessage(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(\n transformedState,\n withHandoffGroupMetadata(config, parallelGroupId)\n );\n result = {\n ...result,\n agentMessages: [],\n };\n } else if (\n state.agentMessages != null &&\n state.agentMessages.length > 0\n ) {\n /**\n * When using agentMessages (excludeResults=true), we need to update\n * the token map to account for the new prompt message\n */\n if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** If agent has both handoff and direct edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a handoff occurred */\n const lastMessage = result.messages[\n result.messages.length - 1\n ] as BaseMessage | null;\n if (\n lastMessage != null &&\n lastMessage.getType() === 'tool' &&\n typeof lastMessage.name === 'string' &&\n lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) {\n /** Handoff occurred - extract destination and navigate there exclusively */\n const handoffDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n return new Command({\n update: result,\n goto: handoffDest,\n });\n } else {\n /** No handoff - proceed with direct edges */\n const directDests = Array.from(directDestinations);\n if (directDests.length === 1) {\n return new Command({\n update: result,\n goto: directDests[0],\n });\n } else if (directDests.length > 1) {\n /** Multiple direct destinations - they'll run in parallel */\n return new Command({\n update: result,\n goto: directDests,\n });\n }\n }\n }\n\n /** No special routing needed - return state normally */\n return result;\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(allDestinations),\n });\n }\n\n // Add starting edges for all starting nodes\n for (const startNode of this.startingNodes) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(START, startNode);\n }\n\n /**\n * Add direct edges for automatic transitions\n * Group edges by destination to handle fan-in scenarios\n */\n const edgesByDestination = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.directEdges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n if (!edgesByDestination.has(destination)) {\n edgesByDestination.set(destination, []);\n }\n edgesByDestination.get(destination)!.push(edge);\n }\n }\n\n for (const [destination, edges] of edgesByDestination) {\n /** Checks if this is a fan-in scenario with prompt instructions */\n const edgesWithPrompt = edges.filter(\n (edge) => edge.prompt != null && edge.prompt !== ''\n );\n\n if (edgesWithPrompt.length > 0) {\n /**\n * Single wrapper node for destination (Fan-in with prompt)\n */\n const wrapperNodeId = `fan_in_${destination}_prompt`;\n /**\n * First edge's `prompt`\n * (they should all be the same for fan-in)\n */\n const prompt = edgesWithPrompt[0].prompt;\n /**\n * First edge's `excludeResults` flag\n * (they should all be the same for fan-in)\n */\n const excludeResults = edgesWithPrompt[0].excludeResults;\n\n builder.addNode(wrapperNodeId, async (state: t.BaseGraphState) => {\n let promptText: string | undefined;\n let effectiveExcludeResults = excludeResults;\n\n if (typeof prompt === 'function') {\n promptText = await prompt(state.messages, this.startIndex);\n } else if (prompt != null) {\n if (prompt.includes('{results}')) {\n const resultsMessages = state.messages.slice(this.startIndex);\n const resultsString = getBufferString(resultsMessages);\n const promptTemplate = PromptTemplate.fromTemplate(prompt);\n const result = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = result.value;\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [new HumanMessage(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n const promptMessage = new HumanMessage(promptText);\n return {\n messages: [promptMessage],\n agentMessages: messagesStateReducer(filteredMessages, [\n promptMessage,\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges (skip if source uses Command routing) */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n /** Check if this source node has both handoff and direct edges */\n const sourceHandoffEdges = this.handoffEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceDirectEdges = this.directEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n\n /** Skip adding edge if source uses Command routing (has both types) */\n if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n }\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"mappings":";;;;;;;;;AAwBA,MAAM,+BAA+B;AACrC,MAAM,2BAA2B;AAEjC,SAAS,uBACP,OACA,WACA,iBACe;CACf,IACE,CAAC,mBACD,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,SAAS,GAEtD,OAAO;CAET,MAAM,QAAQ,MAAM;CACpB,OAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;AAEA,SAAS,yBAAyB,WAA2B;CAC3D,OAAO,UAAU,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,UAAU,MAAM,CAAC;AAC9D;AAEA,SAAS,iCACP,SACA,cACe;CACf,IAAI,cAAc;CAClB,IAAI,eAAe;CACnB,KAAK,MAAM,SAAS,gBAAgB,CAAC,GAAG;EACtC,MAAM,SAAS,OAAO,MAAM;E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C,CAAC;KACD,MAAM,oBAAoB,KAAK,YAAY,QAAQ,MAAM;MAEvD,QADiB,MAAM,QAAQ,EAAE,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,CAAC;;KAGD,IAAI,mBAAmB,SAAS,KAAK,kBAAkB,SAAS,GAC9D;;KAKF,QAAQ,QAAQ,QAAQ,WAAW;IACrC;GACF;EAEJ;EAEA,OAAO,QAAQ,QAAQ,KAAK,cAAkC;CAChE;AACF"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
const require_cache = require("../../messages/cache.cjs");
|
|
2
|
-
const require_toolCache = require("./toolCache.cjs");
|
|
3
2
|
const require_message_inputs = require("./utils/message_inputs.cjs");
|
|
4
3
|
const require_message_outputs = require("./utils/message_outputs.cjs");
|
|
5
4
|
require("./utils/index.cjs");
|
|
6
5
|
const require_cachePoints = require("./cachePoints.cjs");
|
|
6
|
+
const require_toolCache = require("./toolCache.cjs");
|
|
7
7
|
let _langchain_core_messages = require("@langchain/core/messages");
|
|
8
8
|
let _langchain_core_outputs = require("@langchain/core/outputs");
|
|
9
9
|
let _langchain_aws = require("@langchain/aws");
|
|
@@ -58,6 +58,15 @@ function splitStreamToken(text) {
|
|
|
58
58
|
}
|
|
59
59
|
return chunks;
|
|
60
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Resolves the text a delta contributes to the smoothing cadence, preferring a
|
|
63
|
+
* text delta over a reasoning delta and ignoring non-string payloads.
|
|
64
|
+
*/
|
|
65
|
+
function resolveVisibleText(text, reasoningText) {
|
|
66
|
+
if (typeof text === "string") return text;
|
|
67
|
+
if (typeof reasoningText === "string") return reasoningText;
|
|
68
|
+
return "";
|
|
69
|
+
}
|
|
61
70
|
function getCadencedStreamDelay({ targetDelay, lastVisibleContentAt, now }) {
|
|
62
71
|
if (targetDelay <= 0 || lastVisibleContentAt == null) return 0;
|
|
63
72
|
return Math.max(0, targetDelay - (now - lastVisibleContentAt));
|
|
@@ -274,7 +283,7 @@ var CustomChatBedrockConverse = class extends _langchain_aws.ChatBedrockConverse
|
|
|
274
283
|
const text = delta.text;
|
|
275
284
|
const reasoningContent = delta.reasoningContent;
|
|
276
285
|
const reasoningText = reasoningContent?.text;
|
|
277
|
-
const visibleText =
|
|
286
|
+
const visibleText = resolveVisibleText(text, reasoningText);
|
|
278
287
|
const smooth = this._lc_stream_delay > 0 && visibleText !== "";
|
|
279
288
|
const tokenChunks = smooth ? splitStreamToken(visibleText) : [visibleText];
|
|
280
289
|
for (const token of tokenChunks) {
|