@librechat/agents 3.4.1 → 3.4.2
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.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +57 -33
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +81 -33
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/graphs/applyGraphRuntimeConfig.cjs +14 -0
- package/dist/cjs/graphs/applyGraphRuntimeConfig.cjs.map +1 -0
- package/dist/cjs/graphs/createGraph.cjs +15 -0
- package/dist/cjs/graphs/createGraph.cjs.map +1 -0
- package/dist/cjs/graphs/index.cjs +1 -0
- package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +1 -1
- package/dist/cjs/main.cjs +20 -11
- package/dist/cjs/run.cjs +48 -38
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/session/JsonlSessionStore.cjs +2 -2
- package/dist/cjs/tools/SubagentTool.cjs +4 -4
- package/dist/cjs/tools/SubagentTool.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +13 -9
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/eagerEventExecution.cjs +1 -0
- package/dist/cjs/tools/local/LocalExecutionEngine.cjs +3 -3
- package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +2 -2
- package/dist/cjs/tools/search/rerankers.cjs +154 -1
- package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs +4 -1
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentExecutionRegistry.cjs +601 -0
- package/dist/cjs/tools/subagent/SubagentExecutionRegistry.cjs.map +1 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +672 -343
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentReplay.cjs +3 -1
- package/dist/cjs/tools/subagent/SubagentReplay.cjs.map +1 -1
- package/dist/cjs/tools/subagent/childGraphConfig.cjs +278 -0
- package/dist/cjs/tools/subagent/childGraphConfig.cjs.map +1 -0
- package/dist/cjs/tools/subagent/index.cjs +1 -0
- package/dist/cjs/tools/subagent/runtimeLimits.cjs +5 -0
- package/dist/cjs/tools/subagent/runtimeLimits.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +57 -33
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +81 -33
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/graphs/applyGraphRuntimeConfig.mjs +14 -0
- package/dist/esm/graphs/applyGraphRuntimeConfig.mjs.map +1 -0
- package/dist/esm/graphs/createGraph.mjs +15 -0
- package/dist/esm/graphs/createGraph.mjs.map +1 -0
- package/dist/esm/graphs/index.mjs +1 -0
- package/dist/esm/hooks/createWorkspacePolicyHook.mjs +1 -1
- package/dist/esm/main.mjs +12 -10
- package/dist/esm/run.mjs +48 -38
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/session/JsonlSessionStore.mjs +2 -2
- package/dist/esm/tools/SubagentTool.mjs +4 -4
- package/dist/esm/tools/SubagentTool.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +13 -9
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/eagerEventExecution.mjs +1 -1
- package/dist/esm/tools/local/LocalExecutionEngine.mjs +3 -3
- package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +2 -2
- package/dist/esm/tools/search/rerankers.mjs +154 -1
- package/dist/esm/tools/search/rerankers.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs +4 -1
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentExecutionRegistry.mjs +597 -0
- package/dist/esm/tools/subagent/SubagentExecutionRegistry.mjs.map +1 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +672 -343
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentReplay.mjs +3 -1
- package/dist/esm/tools/subagent/SubagentReplay.mjs.map +1 -1
- package/dist/esm/tools/subagent/childGraphConfig.mjs +272 -0
- package/dist/esm/tools/subagent/childGraphConfig.mjs.map +1 -0
- package/dist/esm/tools/subagent/index.mjs +1 -0
- package/dist/esm/tools/subagent/runtimeLimits.mjs +5 -0
- package/dist/esm/tools/subagent/runtimeLimits.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +1 -1
- package/dist/types/graphs/Graph.d.ts +7 -2
- package/dist/types/graphs/MultiAgentGraph.d.ts +7 -1
- package/dist/types/graphs/applyGraphRuntimeConfig.d.ts +3 -0
- package/dist/types/graphs/createGraph.d.ts +13 -0
- package/dist/types/graphs/graphFactory.d.ts +13 -0
- package/dist/types/graphs/index.d.ts +2 -0
- package/dist/types/run.d.ts +2 -2
- package/dist/types/tools/SubagentTool.d.ts +1 -1
- package/dist/types/tools/search/rerankers.d.ts +28 -0
- package/dist/types/tools/search/types.d.ts +38 -1
- package/dist/types/tools/subagent/SubagentExecutionRegistry.d.ts +171 -0
- package/dist/types/tools/subagent/SubagentExecutor.d.ts +32 -37
- package/dist/types/tools/subagent/SubagentReplay.d.ts +5 -1
- package/dist/types/tools/subagent/childGraphConfig.d.ts +37 -0
- package/dist/types/tools/subagent/index.d.ts +1 -1
- package/dist/types/tools/subagent/runtimeLimits.d.ts +4 -0
- package/dist/types/types/graph.d.ts +184 -19
- package/package.json +3 -1
- package/src/agents/AgentContext.ts +1 -1
- package/src/graphs/Graph.ts +111 -60
- package/src/graphs/MultiAgentGraph.ts +149 -47
- package/src/graphs/__tests__/MultiAgentGraph.test.ts +86 -0
- package/src/graphs/__tests__/composition.smoke.test.ts +152 -0
- package/src/graphs/__tests__/createGraph.test.ts +206 -0
- package/src/graphs/applyGraphRuntimeConfig.ts +25 -0
- package/src/graphs/createGraph.ts +32 -0
- package/src/graphs/graphFactory.ts +12 -0
- package/src/graphs/index.ts +2 -0
- package/src/run.ts +50 -38
- package/src/specs/graph-subagent.live.test.ts +242 -0
- package/src/specs/graph-subagent.test.ts +322 -0
- package/src/specs/langfuse-routing.integration.test.ts +120 -1
- package/src/specs/subagent.test.ts +130 -4
- package/src/tools/SubagentTool.ts +4 -4
- package/src/tools/ToolNode.ts +22 -10
- package/src/tools/__tests__/SubagentExecutor.test.ts +198 -9
- package/src/tools/__tests__/SubagentReplay.test.ts +29 -0
- package/src/tools/__tests__/directToolHITLResumeScope.test.ts +28 -2
- package/src/tools/__tests__/subagentHooks.test.ts +90 -3
- package/src/tools/search/rag-api-reranker.test.ts +891 -0
- package/src/tools/search/rerankers.ts +260 -0
- package/src/tools/search/tool.ts +6 -0
- package/src/tools/search/types.ts +45 -1
- package/src/tools/subagent/SubagentExecutionRegistry.ts +1159 -0
- package/src/tools/subagent/SubagentExecutor.ts +1245 -563
- package/src/tools/subagent/SubagentReplay.ts +10 -1
- package/src/tools/subagent/__tests__/SubagentExecutionRegistry.test.ts +637 -0
- package/src/tools/subagent/__tests__/SubagentExecutor.lazy.test.ts +3054 -0
- package/src/tools/subagent/__tests__/childGraphConfig.test.ts +521 -0
- package/src/tools/subagent/childGraphConfig.ts +694 -0
- package/src/tools/subagent/index.ts +6 -0
- package/src/tools/subagent/runtimeLimits.ts +7 -0
- package/src/types/graph.ts +217 -19
|
@@ -75,6 +75,15 @@ function filterTransferToolUseBlocks(content, transferToolCallIds) {
|
|
|
75
75
|
function isValidHandoffGroupId(value) {
|
|
76
76
|
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
77
77
|
}
|
|
78
|
+
function getLastNewAiMessage(messages, previousMessages) {
|
|
79
|
+
const previousMessageObjects = new Set(previousMessages);
|
|
80
|
+
const previousMessageIds = /* @__PURE__ */ new Set();
|
|
81
|
+
for (const message of previousMessages) if (message.id != null) previousMessageIds.add(message.id);
|
|
82
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
83
|
+
const message = messages[index];
|
|
84
|
+
if (message.getType() === "ai" && !previousMessageObjects.has(message) && (message.id == null || !previousMessageIds.has(message.id))) return message;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
78
87
|
function withHandoffGroupMetadata(config, groupId) {
|
|
79
88
|
return {
|
|
80
89
|
...config,
|
|
@@ -103,6 +112,9 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
103
112
|
startingNodes = /* @__PURE__ */ new Set();
|
|
104
113
|
directEdges = [];
|
|
105
114
|
handoffEdges = [];
|
|
115
|
+
handoffSourceIds = /* @__PURE__ */ new Set();
|
|
116
|
+
resultAgentId;
|
|
117
|
+
memberRecursionLimit;
|
|
106
118
|
handoffPromptLabels = /* @__PURE__ */ new Map();
|
|
107
119
|
/**
|
|
108
120
|
* Map of agentId to parallel group info.
|
|
@@ -115,11 +127,16 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
115
127
|
* - summarizer: undefined (sequential, order 2)
|
|
116
128
|
*/
|
|
117
129
|
agentParallelGroups = /* @__PURE__ */ new Map();
|
|
118
|
-
constructor(input) {
|
|
119
|
-
super(input);
|
|
130
|
+
constructor(input, dependencies) {
|
|
131
|
+
super(input, dependencies);
|
|
120
132
|
this.edges = input.edges;
|
|
133
|
+
this.resultAgentId = input.resultAgentId;
|
|
134
|
+
this.memberRecursionLimit = input.memberRecursionLimit;
|
|
135
|
+
if (this.memberRecursionLimit != null && (!Number.isSafeInteger(this.memberRecursionLimit) || this.memberRecursionLimit <= 0)) throw new Error("MultiAgentGraph: memberRecursionLimit must be a positive safe integer.");
|
|
136
|
+
if (this.resultAgentId != null && !this.agentContexts.has(this.resultAgentId)) throw new Error(`MultiAgentGraph: resultAgentId "${this.resultAgentId}" is not present in agents.`);
|
|
121
137
|
this.validateEdgeAgents();
|
|
122
138
|
this.categorizeEdges();
|
|
139
|
+
this.validateCommandRoutedDirectEdges();
|
|
123
140
|
this.analyzeGraph();
|
|
124
141
|
this.createHandoffTools();
|
|
125
142
|
}
|
|
@@ -149,12 +166,37 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
149
166
|
* Categorize edges into handoff and direct types
|
|
150
167
|
*/
|
|
151
168
|
categorizeEdges() {
|
|
152
|
-
for (const edge of this.edges)
|
|
153
|
-
|
|
154
|
-
else {
|
|
169
|
+
for (const edge of this.edges) {
|
|
170
|
+
const sources = Array.isArray(edge.from) ? edge.from : [edge.from];
|
|
155
171
|
const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];
|
|
156
|
-
|
|
157
|
-
|
|
172
|
+
const isDefaultDirect = edge.edgeType == null && edge.condition == null && sources.length === 1 && destinations.length > 1;
|
|
173
|
+
if (edge.edgeType === "direct" || isDefaultDirect) {
|
|
174
|
+
this.directEdges.push(edge);
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
this.handoffEdges.push(edge);
|
|
178
|
+
for (const source of sources) this.handoffSourceIds.add(source);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** Static waiting/prompt edges cannot also be driven by Command routing. */
|
|
182
|
+
validateCommandRoutedDirectEdges() {
|
|
183
|
+
const destinationGroups = /* @__PURE__ */ new Map();
|
|
184
|
+
for (const edge of this.directEdges) {
|
|
185
|
+
const sources = Array.isArray(edge.from) ? edge.from : [edge.from];
|
|
186
|
+
const commandSource = sources.find((source) => this.handoffSourceIds.has(source));
|
|
187
|
+
if (commandSource != null && sources.length > 1) throw new Error(`MultiAgentGraph: grouped direct edge cannot include command-routed source "${commandSource}". Split handoff routing from all-of fan-in.`);
|
|
188
|
+
const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];
|
|
189
|
+
const hasPrompt = edge.prompt != null && edge.prompt !== "";
|
|
190
|
+
for (const destination of destinations) {
|
|
191
|
+
const group = destinationGroups.get(destination) ?? { hasPrompt: false };
|
|
192
|
+
group.hasPrompt ||= hasPrompt;
|
|
193
|
+
group.commandSource ??= commandSource;
|
|
194
|
+
destinationGroups.set(destination, group);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
for (const { hasPrompt, commandSource } of destinationGroups.values()) {
|
|
198
|
+
if (!hasPrompt || commandSource == null) continue;
|
|
199
|
+
throw new Error(`MultiAgentGraph: prompted direct edge cannot include command-routed source "${commandSource}". Move the prompt into the routed node.`);
|
|
158
200
|
}
|
|
159
201
|
}
|
|
160
202
|
/**
|
|
@@ -367,7 +409,7 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
367
409
|
* 3. Include all messages before the AIMessage plus the filtered pair
|
|
368
410
|
*/
|
|
369
411
|
const messages = runtime.state.messages;
|
|
370
|
-
let filteredMessages
|
|
412
|
+
let filteredMessages;
|
|
371
413
|
let aiMessageIndex = -1;
|
|
372
414
|
/** Find the AIMessage containing this tool call */
|
|
373
415
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
@@ -605,8 +647,18 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
605
647
|
/** Replaces state entirely */
|
|
606
648
|
reducer: (a, b) => b,
|
|
607
649
|
default: () => []
|
|
650
|
+
}),
|
|
651
|
+
subagentResult: (0, _langchain_langgraph.Annotation)({
|
|
652
|
+
reducer: (_current, update) => update,
|
|
653
|
+
default: () => void 0
|
|
608
654
|
})
|
|
609
655
|
}));
|
|
656
|
+
const addDirectEdge = (sources, destination) => {
|
|
657
|
+
if (sources.length === 0) return;
|
|
658
|
+
const source = sources.length === 1 ? sources[0] : sources;
|
|
659
|
+
/** @ts-ignore */
|
|
660
|
+
builder.addEdge(source, destination);
|
|
661
|
+
};
|
|
610
662
|
for (const [agentId] of this.agentContexts) {
|
|
611
663
|
const handoffDestinations = /* @__PURE__ */ new Set();
|
|
612
664
|
const directDestinations = /* @__PURE__ */ new Set();
|
|
@@ -624,6 +676,11 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
624
676
|
/** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */
|
|
625
677
|
const agentWrapper = async (state, config) => {
|
|
626
678
|
let result;
|
|
679
|
+
let inputMessages = state.messages;
|
|
680
|
+
const memberConfig = this.memberRecursionLimit == null ? config : {
|
|
681
|
+
...config,
|
|
682
|
+
recursionLimit: this.memberRecursionLimit
|
|
683
|
+
};
|
|
627
684
|
/**
|
|
628
685
|
* Check if this agent is receiving a handoff.
|
|
629
686
|
* If so, filter out the transfer messages and inject instructions as preamble.
|
|
@@ -675,7 +732,8 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
675
732
|
...state,
|
|
676
733
|
messages: messagesForAgent
|
|
677
734
|
};
|
|
678
|
-
|
|
735
|
+
inputMessages = messagesForAgent;
|
|
736
|
+
result = await agentSubgraph.invoke(transformedState, withHandoffGroupMetadata(memberConfig, parallelGroupId));
|
|
679
737
|
result = {
|
|
680
738
|
...result,
|
|
681
739
|
agentMessages: []
|
|
@@ -710,13 +768,21 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
710
768
|
...state,
|
|
711
769
|
messages: state.agentMessages
|
|
712
770
|
};
|
|
713
|
-
|
|
771
|
+
inputMessages = state.agentMessages;
|
|
772
|
+
result = await agentSubgraph.invoke(transformedState, memberConfig);
|
|
714
773
|
result = {
|
|
715
774
|
...result,
|
|
716
775
|
/** Clear agentMessages for next agent */
|
|
717
776
|
agentMessages: []
|
|
718
777
|
};
|
|
719
|
-
} else result = await agentSubgraph.invoke(state,
|
|
778
|
+
} else result = await agentSubgraph.invoke(state, memberConfig);
|
|
779
|
+
if (this.resultAgentId === agentId) result = {
|
|
780
|
+
...result,
|
|
781
|
+
subagentResult: {
|
|
782
|
+
agentId,
|
|
783
|
+
message: getLastNewAiMessage(result.messages, inputMessages)
|
|
784
|
+
}
|
|
785
|
+
};
|
|
720
786
|
/** If agent has both handoff and direct edges, use Command for exclusive routing */
|
|
721
787
|
if (needsCommandRouting) {
|
|
722
788
|
/** Check if a handoff occurred */
|
|
@@ -807,33 +873,15 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
|
|
|
807
873
|
return {};
|
|
808
874
|
});
|
|
809
875
|
/** Add edges from all sources to the wrapper, then wrapper to destination */
|
|
810
|
-
for (const edge of edges)
|
|
811
|
-
const sources = Array.isArray(edge.from) ? edge.from : [edge.from];
|
|
812
|
-
for (const source of sources)
|
|
813
|
-
/** @ts-ignore */
|
|
814
|
-
builder.addEdge(source, wrapperNodeId);
|
|
815
|
-
}
|
|
876
|
+
for (const edge of edges) addDirectEdge(Array.isArray(edge.from) ? edge.from : [edge.from], wrapperNodeId);
|
|
816
877
|
/** Single edge from wrapper to destination */
|
|
817
878
|
/** @ts-ignore */
|
|
818
879
|
builder.addEdge(wrapperNodeId, destination);
|
|
819
880
|
} else
|
|
820
881
|
/** No prompt instructions, add direct edges (skip if source uses Command routing) */
|
|
821
|
-
for (const edge of edges) {
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
/** Check if this source node has both handoff and direct edges */
|
|
825
|
-
const sourceHandoffEdges = this.handoffEdges.filter((e) => {
|
|
826
|
-
return (Array.isArray(e.from) ? e.from : [e.from]).includes(source);
|
|
827
|
-
});
|
|
828
|
-
const sourceDirectEdges = this.directEdges.filter((e) => {
|
|
829
|
-
return (Array.isArray(e.from) ? e.from : [e.from]).includes(source);
|
|
830
|
-
});
|
|
831
|
-
/** Skip adding edge if source uses Command routing (has both types) */
|
|
832
|
-
if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) continue;
|
|
833
|
-
/** @ts-ignore */
|
|
834
|
-
builder.addEdge(source, destination);
|
|
835
|
-
}
|
|
836
|
-
}
|
|
882
|
+
for (const edge of edges) addDirectEdge((Array.isArray(edge.from) ? edge.from : [edge.from]).filter((source) => !this.handoffEdges.some((handoffEdge) => {
|
|
883
|
+
return (Array.isArray(handoffEdge.from) ? handoffEdge.from : [handoffEdge.from]).includes(source);
|
|
884
|
+
})), destination);
|
|
837
885
|
}
|
|
838
886
|
return builder.compile(this.compileOptions);
|
|
839
887
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultiAgentGraph.cjs","names":["HumanMessage","StandardGraph","ToolMessage","Command","aiMsg","AIMessage","serializeToolContentBounded","HARD_MAX_TOOL_RESULT_CHARS","StateGraph","Annotation","END","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 { serializeToolContentBounded } from '@/utils/toolContent';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\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\n/**\n * Handoff and fan-in prompts that route work between agents. Built in-run and\n * never persisted as standalone payload entries, so they are marked synthetic:\n * `messagesStateReducer` would otherwise give them a plain UUID and downstream\n * consumers — compaction coverage anchors — could not tell them apart from a\n * message replayed out of the payload.\n */\nfunction buildRoutingPrompt(content: string): HumanMessage {\n return new HumanMessage({\n content,\n additional_kwargs: { role: 'user', isMeta: true, source: 'routing' },\n });\n}\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\n/** Whether a tool name marks a handoff transfer (static or conditional). */\nfunction isTransferToolName(name: unknown): boolean {\n return (\n typeof name === 'string' &&\n (name.startsWith(Constants.LC_TRANSFER_TO_) ||\n name === 'conditional_transfer')\n );\n}\n\n/**\n * Drop transfer `tool_use` content blocks from an AI message's array content.\n * Companion to the reception's tool-call filtering: array-content providers\n * (Anthropic) serialize retained blocks verbatim, so a transfer block whose\n * call/result the reception stripped — or a parallel sibling's transfer block,\n * whose result never reaches this recipient's state — would replay as an\n * unmatched `tool_use`. Matched by the gathered ids AND by transfer name\n * (sibling blocks have no collectable id here). String content passes through.\n */\nfunction filterTransferToolUseBlocks(\n content: AIMessage['content'],\n transferToolCallIds: ReadonlySet<string>\n): AIMessage['content'] {\n if (!Array.isArray(content)) {\n return content;\n }\n return content.filter((block) => {\n if (\n typeof block !== 'object' ||\n (block as { type?: string } | null)?.type !== 'tool_use'\n ) {\n return true;\n }\n const toolUse = block as { id?: string; name?: string };\n if (toolUse.id != null && transferToolCallIds.has(toolUse.id)) {\n return false;\n }\n return !isTransferToolName(toolUse.name);\n });\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 : serializeToolContentBounded(\n toolMessage.content,\n HARD_MAX_TOOL_RESULT_CHARS\n );\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 /**\n * Keep the message but without transfer tool calls — AND\n * without their `tool_use` content blocks. Array-content\n * providers (Anthropic) serialize the retained blocks\n * verbatim, so a transfer block whose call/result this\n * filter just stripped would reach the receiving agent as\n * an unmatched `tool_use` and the provider rejects the\n * request. Filtered by transfer NAME as well as the\n * gathered ids: a parallel sibling's transfer block has no\n * result in THIS recipient's state, so its id is never\n * collected, but its name still marks it.\n */\n const filteredAiMsg = new AIMessage({\n content: filterTransferToolUseBlocks(\n aiMsg.content,\n transferToolCallIds\n ),\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 buildRoutingPrompt(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n buildRoutingPrompt(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: [buildRoutingPrompt(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 = buildRoutingPrompt(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":";;;;;;;;;;;AA0BA,MAAM,+BAA+B;AACrC,MAAM,2BAA2B;;;;;;;;AASjC,SAAS,mBAAmB,SAA+B;CACzD,OAAO,IAAIA,yBAAAA,aAAa;EACtB;EACA,mBAAmB;GAAE,MAAM;GAAQ,QAAQ;GAAM,QAAQ;EAAU;CACrE,CAAC;AACH;AAEA,SAAS,uBACP,OACA,WACA,iBACe;CACf,IACE,CAAC,mBACD,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,SAAS,GAEtD,OAAO;C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mB,MAAM,SAAS,MAAM,GAAG,KAAK,UAAU;MAChE,MAAM,gBAAgB,mBAAmB,UAAU;MACnD,OAAO;OACL,UAAU,CAAC,aAAa;OACxB,gBAAA,GAAA,qBAAA,qBAAA,CAAoC,kBAAkB,CACpD,aACF,CAAC;MACH;KACF;;KAGA,OAAO,CAAC;IACV,CAAC;;IAGD,KAAK,MAAM,QAAQ,OAAO;KACxB,MAAM,UAAU,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;KACjE,KAAK,MAAM,UAAU;;KAGnB,QAAQ,QAAQ,QAAQ,aAAa;IAEzC;;;IAKA,QAAQ,QAAQ,eAAe,WAAW;GAC5C;;GAEE,KAAK,MAAM,QAAQ,OAAO;IACxB,MAAM,UAAU,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;IACjE,KAAK,MAAM,UAAU,SAAS;;KAE5B,MAAM,qBAAqB,KAAK,aAAa,QAAQ,MAAM;MAEzD,QADiB,MAAM,QAAQ,EAAE,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,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
|
+
{"version":3,"file":"MultiAgentGraph.cjs","names":["HumanMessage","StandardGraph","ToolMessage","Command","aiMsg","AIMessage","serializeToolContentBounded","HARD_MAX_TOOL_RESULT_CHARS","StateGraph","Annotation","END","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 { GraphFactoryDependencies } from '@/graphs/graphFactory';\nimport type * as t from '@/types';\nimport { serializeToolContentBounded } from '@/utils/toolContent';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\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\n/**\n * Handoff and fan-in prompts that route work between agents. Built in-run and\n * never persisted as standalone payload entries, so they are marked synthetic:\n * `messagesStateReducer` would otherwise give them a plain UUID and downstream\n * consumers — compaction coverage anchors — could not tell them apart from a\n * message replayed out of the payload.\n */\nfunction buildRoutingPrompt(content: string): HumanMessage {\n return new HumanMessage({\n content,\n additional_kwargs: { role: 'user', isMeta: true, source: 'routing' },\n });\n}\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\n/** Whether a tool name marks a handoff transfer (static or conditional). */\nfunction isTransferToolName(name: unknown): boolean {\n return (\n typeof name === 'string' &&\n (name.startsWith(Constants.LC_TRANSFER_TO_) ||\n name === 'conditional_transfer')\n );\n}\n\n/**\n * Drop transfer `tool_use` content blocks from an AI message's array content.\n * Companion to the reception's tool-call filtering: array-content providers\n * (Anthropic) serialize retained blocks verbatim, so a transfer block whose\n * call/result the reception stripped — or a parallel sibling's transfer block,\n * whose result never reaches this recipient's state — would replay as an\n * unmatched `tool_use`. Matched by the gathered ids AND by transfer name\n * (sibling blocks have no collectable id here). String content passes through.\n */\nfunction filterTransferToolUseBlocks(\n content: AIMessage['content'],\n transferToolCallIds: ReadonlySet<string>\n): AIMessage['content'] {\n if (!Array.isArray(content)) {\n return content;\n }\n return content.filter((block) => {\n if (\n typeof block !== 'object' ||\n (block as { type?: string } | null)?.type !== 'tool_use'\n ) {\n return true;\n }\n const toolUse = block as { id?: string; name?: string };\n if (toolUse.id != null && transferToolCallIds.has(toolUse.id)) {\n return false;\n }\n return !isTransferToolName(toolUse.name);\n });\n}\n\nfunction isValidHandoffGroupId(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction getLastNewAiMessage(\n messages: BaseMessage[],\n previousMessages: BaseMessage[]\n): BaseMessage | undefined {\n const previousMessageObjects = new Set(previousMessages);\n const previousMessageIds = new Set<string>();\n for (const message of previousMessages) {\n if (message.id != null) {\n previousMessageIds.add(message.id);\n }\n }\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (\n message.getType() === 'ai' &&\n !previousMessageObjects.has(message) &&\n (message.id == null || !previousMessageIds.has(message.id))\n ) {\n return message;\n }\n }\n return undefined;\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 handoffSourceIds = new Set<string>();\n private readonly resultAgentId?: string;\n private readonly memberRecursionLimit?: number;\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(\n input: t.MultiAgentGraphInput,\n dependencies?: GraphFactoryDependencies\n ) {\n super(input, dependencies);\n this.edges = input.edges;\n this.resultAgentId = input.resultAgentId;\n this.memberRecursionLimit = input.memberRecursionLimit;\n if (\n this.memberRecursionLimit != null &&\n (!Number.isSafeInteger(this.memberRecursionLimit) ||\n this.memberRecursionLimit <= 0)\n ) {\n throw new Error(\n 'MultiAgentGraph: memberRecursionLimit must be a positive safe integer.'\n );\n }\n if (\n this.resultAgentId != null &&\n !this.agentContexts.has(this.resultAgentId)\n ) {\n throw new Error(\n `MultiAgentGraph: resultAgentId \"${this.resultAgentId}\" is not present in agents.`\n );\n }\n this.validateEdgeAgents();\n this.categorizeEdges();\n this.validateCommandRoutedDirectEdges();\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 const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const isDefaultDirect =\n edge.edgeType == null &&\n edge.condition == null &&\n sources.length === 1 &&\n destinations.length > 1;\n if (edge.edgeType === 'direct' || isDefaultDirect) {\n this.directEdges.push(edge);\n continue;\n }\n this.handoffEdges.push(edge);\n for (const source of sources) {\n this.handoffSourceIds.add(source);\n }\n }\n }\n\n /** Static waiting/prompt edges cannot also be driven by Command routing. */\n private validateCommandRoutedDirectEdges(): void {\n const destinationGroups = new Map<\n string,\n { hasPrompt: boolean; commandSource?: string }\n >();\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n const commandSource = sources.find((source) =>\n this.handoffSourceIds.has(source)\n );\n if (commandSource != null && sources.length > 1) {\n throw new Error(\n 'MultiAgentGraph: grouped direct edge cannot include command-routed ' +\n `source \"${commandSource}\". Split handoff routing from all-of fan-in.`\n );\n }\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const hasPrompt = edge.prompt != null && edge.prompt !== '';\n for (const destination of destinations) {\n const group = destinationGroups.get(destination) ?? {\n hasPrompt: false,\n };\n group.hasPrompt ||= hasPrompt;\n group.commandSource ??= commandSource;\n destinationGroups.set(destination, group);\n }\n }\n for (const { hasPrompt, commandSource } of destinationGroups.values()) {\n if (!hasPrompt || commandSource == null) {\n continue;\n }\n throw new Error(\n 'MultiAgentGraph: prompted direct edge cannot include command-routed ' +\n `source \"${commandSource}\". Move the prompt into the routed node.`\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: BaseMessage[];\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 : serializeToolContentBounded(\n toolMessage.content,\n HARD_MAX_TOOL_RESULT_CHARS\n );\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 /**\n * Keep the message but without transfer tool calls — AND\n * without their `tool_use` content blocks. Array-content\n * providers (Anthropic) serialize the retained blocks\n * verbatim, so a transfer block whose call/result this\n * filter just stripped would reach the receiving agent as\n * an unmatched `tool_use` and the provider rejects the\n * request. Filtered by transfer NAME as well as the\n * gathered ids: a parallel sibling's transfer block has no\n * result in THIS recipient's state, so its id is never\n * collected, but its name still marks it.\n */\n const filteredAiMsg = new AIMessage({\n content: filterTransferToolUseBlocks(\n aiMsg.content,\n transferToolCallIds\n ),\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 subagentResult: Annotation<t.SubagentGraphResult | undefined>({\n reducer: (_current, update) => update,\n default: () => undefined,\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n const addDirectEdge = (sources: string[], destination: string): void => {\n if (sources.length === 0) {\n return;\n }\n const source = sources.length === 1 ? sources[0] : sources;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n };\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 let inputMessages = state.messages;\n const memberConfig =\n this.memberRecursionLimit == null\n ? config\n : { ...config, recursionLimit: this.memberRecursionLimit };\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 buildRoutingPrompt(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n buildRoutingPrompt(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 inputMessages = messagesForAgent;\n result = await agentSubgraph.invoke(\n transformedState,\n withHandoffGroupMetadata(memberConfig, 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 inputMessages = state.agentMessages;\n result = await agentSubgraph.invoke(transformedState, memberConfig);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, memberConfig);\n }\n\n if (this.resultAgentId === agentId) {\n result = {\n ...result,\n subagentResult: {\n agentId,\n message: getLastNewAiMessage(result.messages, inputMessages),\n },\n };\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: [buildRoutingPrompt(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 = buildRoutingPrompt(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 addDirectEdge(sources, wrapperNodeId);\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 const staticSources = sources.filter(\n (source) =>\n !this.handoffEdges.some((handoffEdge) => {\n const handoffSources = Array.isArray(handoffEdge.from)\n ? handoffEdge.from\n : [handoffEdge.from];\n return handoffSources.includes(source);\n })\n );\n addDirectEdge(staticSources, destination);\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"mappings":";;;;;;;;;;;AA2BA,MAAM,+BAA+B;AACrC,MAAM,2BAA2B;;;;;;;;AASjC,SAAS,mBAAmB,SAA+B;CACzD,OAAO,IAAIA,yBAAAA,aAAa;EACtB;EACA,mBAAmB;GAAE,MAAM;GAAQ,QAAQ;GAAM,QAAQ;EAAU;CACrE,CAAC;AACH;AAEA,SAAS,uBACP,OACA,WACA,iBACe;CACf,IACE,CAAC,mBACD,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,SAAS,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AAe,WAAW;GAC5C;;GAEE,KAAK,MAAM,QAAQ,OAWjB,eAVgB,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI,EAAA,CACnC,QAC3B,WACC,CAAC,KAAK,aAAa,MAAM,gBAAgB;IAIvC,QAHuB,MAAM,QAAQ,YAAY,IAAI,IACjD,YAAY,OACZ,CAAC,YAAY,IAAI,EAAA,CACC,SAAS,MAAM;GACvC,CAAC,CAEqB,GAAG,WAAW;EAG9C;EAEA,OAAO,QAAQ,QAAQ,KAAK,cAAkC;CAChE;AACF"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/graphs/applyGraphRuntimeConfig.ts
|
|
2
|
+
function applyGraphRuntimeConfig(graph, config) {
|
|
3
|
+
graph.hookRegistry = config.hookRegistry;
|
|
4
|
+
graph.humanInTheLoop = config.humanInTheLoop;
|
|
5
|
+
graph.toolOutputReferences = config.toolOutputReferences;
|
|
6
|
+
graph.eagerEventToolExecution = config.eagerEventToolExecution;
|
|
7
|
+
graph.codeSessionToolNames = config.codeSessionToolNames;
|
|
8
|
+
graph.interruptingToolNames = config.interruptingToolNames;
|
|
9
|
+
graph.toolExecution = config.toolExecution;
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
12
|
+
exports.applyGraphRuntimeConfig = applyGraphRuntimeConfig;
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=applyGraphRuntimeConfig.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"applyGraphRuntimeConfig.cjs","names":[],"sources":["../../../src/graphs/applyGraphRuntimeConfig.ts"],"sourcesContent":["import type { StandardGraph } from './Graph';\n\nexport type GraphRuntimeConfig = Pick<\n StandardGraph,\n | 'hookRegistry'\n | 'humanInTheLoop'\n | 'toolOutputReferences'\n | 'eagerEventToolExecution'\n | 'codeSessionToolNames'\n | 'interruptingToolNames'\n | 'toolExecution'\n>;\n\nexport function applyGraphRuntimeConfig(\n graph: StandardGraph,\n config: GraphRuntimeConfig\n): void {\n graph.hookRegistry = config.hookRegistry;\n graph.humanInTheLoop = config.humanInTheLoop;\n graph.toolOutputReferences = config.toolOutputReferences;\n graph.eagerEventToolExecution = config.eagerEventToolExecution;\n graph.codeSessionToolNames = config.codeSessionToolNames;\n graph.interruptingToolNames = config.interruptingToolNames;\n graph.toolExecution = config.toolExecution;\n}\n"],"mappings":";AAaA,SAAgB,wBACd,OACA,QACM;CACN,MAAM,eAAe,OAAO;CAC5B,MAAM,iBAAiB,OAAO;CAC9B,MAAM,uBAAuB,OAAO;CACpC,MAAM,0BAA0B,OAAO;CACvC,MAAM,uBAAuB,OAAO;CACpC,MAAM,wBAAwB,OAAO;CACrC,MAAM,gBAAgB,OAAO;AAC/B"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const require_Graph = require("./Graph.cjs");
|
|
2
|
+
const require_MultiAgentGraph = require("./MultiAgentGraph.cjs");
|
|
3
|
+
//#region src/graphs/createGraph.ts
|
|
4
|
+
const createGraphByKind = (request) => {
|
|
5
|
+
if (request.kind === "multi-agent") return new require_MultiAgentGraph.MultiAgentGraph(request.input, dependencies);
|
|
6
|
+
return new require_Graph.StandardGraph(request.input, dependencies);
|
|
7
|
+
};
|
|
8
|
+
const dependencies = { graphFactory: createGraphByKind };
|
|
9
|
+
function createGraph(request) {
|
|
10
|
+
return createGraphByKind(request);
|
|
11
|
+
}
|
|
12
|
+
//#endregion
|
|
13
|
+
exports.createGraph = createGraph;
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=createGraph.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createGraph.cjs","names":["MultiAgentGraph","StandardGraph"],"sources":["../../../src/graphs/createGraph.ts"],"sourcesContent":["import type {\n GraphFactory,\n GraphFactoryDependencies,\n GraphFactoryRequest,\n} from '@/graphs/graphFactory';\nimport type { MultiAgentGraphInput, StandardGraphInput } from '@/types';\nimport { MultiAgentGraph } from '@/graphs/MultiAgentGraph';\nimport { StandardGraph } from '@/graphs/Graph';\n\nconst createGraphByKind: GraphFactory = (request) => {\n if (request.kind === 'multi-agent') {\n return new MultiAgentGraph(request.input, dependencies);\n }\n return new StandardGraph(request.input, dependencies);\n};\n\nconst dependencies: GraphFactoryDependencies = {\n graphFactory: createGraphByKind,\n};\n\nexport function createGraph(request: {\n kind: 'standard';\n input: StandardGraphInput;\n}): StandardGraph;\nexport function createGraph(request: {\n kind: 'multi-agent';\n input: MultiAgentGraphInput;\n}): MultiAgentGraph;\nexport function createGraph(request: GraphFactoryRequest): StandardGraph;\nexport function createGraph(request: GraphFactoryRequest): StandardGraph {\n return createGraphByKind(request);\n}\n"],"mappings":";;;AASA,MAAM,qBAAmC,YAAY;CACnD,IAAI,QAAQ,SAAS,eACnB,OAAO,IAAIA,wBAAAA,gBAAgB,QAAQ,OAAO,YAAY;CAExD,OAAO,IAAIC,cAAAA,cAAc,QAAQ,OAAO,YAAY;AACtD;AAEA,MAAM,eAAyC,EAC7C,cAAc,kBAChB;AAWA,SAAgB,YAAY,SAA6C;CACvE,OAAO,kBAAkB,OAAO;AAClC"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
require("../common/enum.cjs");
|
|
2
2
|
require("../common/index.cjs");
|
|
3
|
-
let path = require("path");
|
|
4
3
|
let os = require("os");
|
|
5
4
|
let fs_promises = require("fs/promises");
|
|
5
|
+
let path = require("path");
|
|
6
6
|
//#region src/hooks/createWorkspacePolicyHook.ts
|
|
7
7
|
/**
|
|
8
8
|
* Workspace boundary policy as a `PreToolUse` hook.
|