@n8n/ai-workflow-builder 0.32.1 → 0.33.0-exp.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/dist/agents/responder.agent.d.ts +21 -0
  2. package/dist/agents/responder.agent.js +102 -0
  3. package/dist/agents/responder.agent.js.map +1 -0
  4. package/dist/agents/supervisor.agent.d.ts +31 -0
  5. package/dist/agents/supervisor.agent.js +104 -0
  6. package/dist/agents/supervisor.agent.js.map +1 -0
  7. package/dist/ai-workflow-builder-agent.service.d.ts +2 -1
  8. package/dist/ai-workflow-builder-agent.service.js +13 -4
  9. package/dist/ai-workflow-builder-agent.service.js.map +1 -1
  10. package/dist/build.tsbuildinfo +1 -1
  11. package/dist/chains/prompts/examples/basic/switch-node-examples.d.ts +1 -0
  12. package/dist/chains/prompts/examples/basic/switch-node-examples.js +128 -0
  13. package/dist/chains/prompts/examples/basic/switch-node-examples.js.map +1 -0
  14. package/dist/chains/prompts/node-types/switch-node.d.ts +1 -0
  15. package/dist/chains/prompts/node-types/switch-node.js +72 -0
  16. package/dist/chains/prompts/node-types/switch-node.js.map +1 -0
  17. package/dist/chains/prompts/prompt-builder.d.ts +1 -0
  18. package/dist/chains/prompts/prompt-builder.js +12 -0
  19. package/dist/chains/prompts/prompt-builder.js.map +1 -1
  20. package/dist/chains/prompts/prompt-config.js +1 -0
  21. package/dist/chains/prompts/prompt-config.js.map +1 -1
  22. package/dist/constants.d.ts +6 -0
  23. package/dist/constants.js +7 -1
  24. package/dist/constants.js.map +1 -1
  25. package/dist/llm-config.d.ts +1 -0
  26. package/dist/llm-config.js +20 -1
  27. package/dist/llm-config.js.map +1 -1
  28. package/dist/multi-agent-workflow-subgraphs.d.ts +122 -0
  29. package/dist/multi-agent-workflow-subgraphs.js +153 -0
  30. package/dist/multi-agent-workflow-subgraphs.js.map +1 -0
  31. package/dist/parent-graph-state.d.ts +27 -0
  32. package/dist/parent-graph-state.js +47 -0
  33. package/dist/parent-graph-state.js.map +1 -0
  34. package/dist/subgraphs/builder.subgraph.d.ts +122 -0
  35. package/dist/subgraphs/builder.subgraph.js +384 -0
  36. package/dist/subgraphs/builder.subgraph.js.map +1 -0
  37. package/dist/subgraphs/configurator.subgraph.d.ts +132 -0
  38. package/dist/subgraphs/configurator.subgraph.js +272 -0
  39. package/dist/subgraphs/configurator.subgraph.js.map +1 -0
  40. package/dist/subgraphs/discovery.subgraph.d.ts +158 -0
  41. package/dist/subgraphs/discovery.subgraph.js +487 -0
  42. package/dist/subgraphs/discovery.subgraph.js.map +1 -0
  43. package/dist/subgraphs/subgraph-interface.d.ts +23 -0
  44. package/dist/subgraphs/subgraph-interface.js +7 -0
  45. package/dist/subgraphs/subgraph-interface.js.map +1 -0
  46. package/dist/tools/best-practices/content-generation.js +38 -2
  47. package/dist/tools/best-practices/content-generation.js.map +1 -1
  48. package/dist/tools/builder-tools.d.ts +5 -2
  49. package/dist/tools/builder-tools.js +15 -25
  50. package/dist/tools/builder-tools.js.map +1 -1
  51. package/dist/tools/get-best-practices.tool.d.ts +1 -1
  52. package/dist/tools/get-workflow-examples.tool.d.ts +34 -0
  53. package/dist/tools/get-workflow-examples.tool.js +172 -0
  54. package/dist/tools/get-workflow-examples.tool.js.map +1 -0
  55. package/dist/tools/node-details.tool.d.ts +4 -4
  56. package/dist/tools/node-details.tool.js +30 -2
  57. package/dist/tools/node-details.tool.js.map +1 -1
  58. package/dist/tools/node-search.tool.d.ts +1 -1
  59. package/dist/tools/prompts/main-agent.prompt.d.ts +4 -0
  60. package/dist/tools/prompts/main-agent.prompt.js +113 -57
  61. package/dist/tools/prompts/main-agent.prompt.js.map +1 -1
  62. package/dist/tools/utils/markdown-workflow.utils.d.ts +14 -0
  63. package/dist/tools/utils/markdown-workflow.utils.js +174 -0
  64. package/dist/tools/utils/markdown-workflow.utils.js.map +1 -0
  65. package/dist/tools/utils/test/workflows/ai-assistant.workflow.d.ts +2 -0
  66. package/dist/tools/utils/test/workflows/ai-assistant.workflow.js +541 -0
  67. package/dist/tools/utils/test/workflows/ai-assistant.workflow.js.map +1 -0
  68. package/dist/tools/validate-configuration.tool.d.ts +4 -0
  69. package/dist/tools/validate-configuration.tool.js +70 -0
  70. package/dist/tools/validate-configuration.tool.js.map +1 -0
  71. package/dist/tools/validate-structure.tool.d.ts +4 -0
  72. package/dist/tools/validate-structure.tool.js +66 -0
  73. package/dist/tools/validate-structure.tool.js.map +1 -0
  74. package/dist/tools/web/templates.d.ts +7 -0
  75. package/dist/tools/web/templates.js +71 -0
  76. package/dist/tools/web/templates.js.map +1 -0
  77. package/dist/types/config.d.ts +1 -0
  78. package/dist/types/coordination.d.ts +42 -0
  79. package/dist/types/coordination.js +23 -0
  80. package/dist/types/coordination.js.map +1 -0
  81. package/dist/types/discovery-types.d.ts +14 -0
  82. package/dist/types/discovery-types.js +3 -0
  83. package/dist/types/discovery-types.js.map +1 -0
  84. package/dist/types/index.d.ts +1 -0
  85. package/dist/types/index.js +15 -0
  86. package/dist/types/index.js.map +1 -1
  87. package/dist/types/langchain.d.ts +1 -0
  88. package/dist/types/langchain.js +8 -0
  89. package/dist/types/langchain.js.map +1 -1
  90. package/dist/types/tools.d.ts +20 -0
  91. package/dist/types/web/templates.d.ts +44 -0
  92. package/dist/types/web/templates.js +37 -0
  93. package/dist/types/web/templates.js.map +1 -0
  94. package/dist/utils/cache-control/helpers.d.ts +1 -0
  95. package/dist/utils/cache-control/helpers.js +36 -0
  96. package/dist/utils/cache-control/helpers.js.map +1 -1
  97. package/dist/utils/cache-control/index.d.ts +1 -1
  98. package/dist/utils/cache-control/index.js +2 -1
  99. package/dist/utils/cache-control/index.js.map +1 -1
  100. package/dist/utils/context-builders.d.ts +10 -0
  101. package/dist/utils/context-builders.js +71 -0
  102. package/dist/utils/context-builders.js.map +1 -0
  103. package/dist/utils/coordination-log.d.ts +15 -0
  104. package/dist/utils/coordination-log.js +75 -0
  105. package/dist/utils/coordination-log.js.map +1 -0
  106. package/dist/utils/operations-processor.d.ts +4 -2
  107. package/dist/utils/operations-processor.js.map +1 -1
  108. package/dist/utils/state-modifier.d.ts +32 -0
  109. package/dist/utils/state-modifier.js +112 -0
  110. package/dist/utils/state-modifier.js.map +1 -0
  111. package/dist/utils/state-reducers.d.ts +4 -0
  112. package/dist/utils/state-reducers.js +25 -0
  113. package/dist/utils/state-reducers.js.map +1 -0
  114. package/dist/utils/stream-processor.d.ts +6 -2
  115. package/dist/utils/stream-processor.js +138 -83
  116. package/dist/utils/stream-processor.js.map +1 -1
  117. package/dist/utils/subgraph-helpers.d.ts +16 -0
  118. package/dist/utils/subgraph-helpers.js +118 -0
  119. package/dist/utils/subgraph-helpers.js.map +1 -0
  120. package/dist/utils/token-usage.js +4 -1
  121. package/dist/utils/token-usage.js.map +1 -1
  122. package/dist/utils/tool-executor.js +55 -38
  123. package/dist/utils/tool-executor.js.map +1 -1
  124. package/dist/utils/workflow-validation.js +1 -0
  125. package/dist/utils/workflow-validation.js.map +1 -1
  126. package/dist/validation/checks/connections.js +6 -14
  127. package/dist/validation/checks/connections.js.map +1 -1
  128. package/dist/validation/checks/index.d.ts +2 -1
  129. package/dist/validation/checks/index.js +3 -1
  130. package/dist/validation/checks/index.js.map +1 -1
  131. package/dist/validation/checks/nodes.d.ts +4 -0
  132. package/dist/validation/checks/nodes.js +36 -0
  133. package/dist/validation/checks/nodes.js.map +1 -0
  134. package/dist/validation/checks/tools.js +0 -10
  135. package/dist/validation/checks/tools.js.map +1 -1
  136. package/dist/validation/checks/trigger.js +0 -6
  137. package/dist/validation/checks/trigger.js.map +1 -1
  138. package/dist/validation/programmatic.js +2 -0
  139. package/dist/validation/programmatic.js.map +1 -1
  140. package/dist/validation/types.d.ts +5 -1
  141. package/dist/validation/types.js +8 -0
  142. package/dist/validation/types.js.map +1 -1
  143. package/dist/workflow-builder-agent.d.ts +9 -0
  144. package/dist/workflow-builder-agent.js +44 -10
  145. package/dist/workflow-builder-agent.js.map +1 -1
  146. package/dist/workflow-state.d.ts +4 -2
  147. package/dist/workflow-state.js +9 -0
  148. package/dist/workflow-state.js.map +1 -1
  149. package/package.json +9 -8
@@ -0,0 +1,487 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DiscoverySubgraph = exports.DiscoverySubgraphState = void 0;
4
+ const messages_1 = require("@langchain/core/messages");
5
+ const prompts_1 = require("@langchain/core/prompts");
6
+ const tools_1 = require("@langchain/core/tools");
7
+ const langgraph_1 = require("@langchain/langgraph");
8
+ const zod_1 = require("zod");
9
+ const errors_1 = require("../errors");
10
+ const categorization_1 = require("../types/categorization");
11
+ const subgraph_interface_1 = require("./subgraph-interface");
12
+ const get_best_practices_tool_1 = require("../tools/get-best-practices.tool");
13
+ const get_workflow_examples_tool_1 = require("../tools/get-workflow-examples.tool");
14
+ const node_details_tool_1 = require("../tools/node-details.tool");
15
+ const node_search_tool_1 = require("../tools/node-search.tool");
16
+ const coordination_1 = require("../types/coordination");
17
+ const cache_control_1 = require("../utils/cache-control");
18
+ const context_builders_1 = require("../utils/context-builders");
19
+ const state_reducers_1 = require("../utils/state-reducers");
20
+ const subgraph_helpers_1 = require("../utils/subgraph-helpers");
21
+ const exampleCategorizations = [
22
+ {
23
+ prompt: 'Monitor social channels for product mentions and auto-respond with campaign messages',
24
+ techniques: [
25
+ categorization_1.WorkflowTechnique.MONITORING,
26
+ categorization_1.WorkflowTechnique.CHATBOT,
27
+ categorization_1.WorkflowTechnique.CONTENT_GENERATION,
28
+ ],
29
+ },
30
+ {
31
+ prompt: 'Collect partner referral submissions and verify client instances via BigQuery',
32
+ techniques: [
33
+ categorization_1.WorkflowTechnique.FORM_INPUT,
34
+ categorization_1.WorkflowTechnique.HUMAN_IN_THE_LOOP,
35
+ categorization_1.WorkflowTechnique.NOTIFICATION,
36
+ ],
37
+ },
38
+ {
39
+ prompt: 'Scrape competitor pricing pages weekly and generate a summary report of changes',
40
+ techniques: [
41
+ categorization_1.WorkflowTechnique.SCHEDULING,
42
+ categorization_1.WorkflowTechnique.SCRAPING_AND_RESEARCH,
43
+ categorization_1.WorkflowTechnique.DATA_EXTRACTION,
44
+ categorization_1.WorkflowTechnique.DATA_ANALYSIS,
45
+ ],
46
+ },
47
+ {
48
+ prompt: 'Process uploaded PDF contracts to extract client details and update CRM records',
49
+ techniques: [
50
+ categorization_1.WorkflowTechnique.DOCUMENT_PROCESSING,
51
+ categorization_1.WorkflowTechnique.DATA_EXTRACTION,
52
+ categorization_1.WorkflowTechnique.DATA_TRANSFORMATION,
53
+ categorization_1.WorkflowTechnique.ENRICHMENT,
54
+ ],
55
+ },
56
+ {
57
+ prompt: 'Build a searchable internal knowledge base from past support tickets',
58
+ techniques: [
59
+ categorization_1.WorkflowTechnique.DATA_TRANSFORMATION,
60
+ categorization_1.WorkflowTechnique.DATA_ANALYSIS,
61
+ categorization_1.WorkflowTechnique.KNOWLEDGE_BASE,
62
+ ],
63
+ },
64
+ {
65
+ prompt: 'Create an AI agent that writes and sends personalized emails to leads',
66
+ techniques: [categorization_1.WorkflowTechnique.CONTENT_GENERATION, categorization_1.WorkflowTechnique.NOTIFICATION],
67
+ },
68
+ {
69
+ prompt: 'Fetch trending topics from Google Trends and Reddit, select the best ones, and create social posts',
70
+ techniques: [
71
+ categorization_1.WorkflowTechnique.SCRAPING_AND_RESEARCH,
72
+ categorization_1.WorkflowTechnique.TRIAGE,
73
+ categorization_1.WorkflowTechnique.CONTENT_GENERATION,
74
+ ],
75
+ },
76
+ {
77
+ prompt: 'Trigger when a new contact is created in HubSpot and enrich their profile with LinkedIn data',
78
+ techniques: [categorization_1.WorkflowTechnique.MONITORING, categorization_1.WorkflowTechnique.ENRICHMENT],
79
+ },
80
+ {
81
+ prompt: 'Get stock prices from financial APIs and analyze volatility patterns',
82
+ techniques: [categorization_1.WorkflowTechnique.SCRAPING_AND_RESEARCH, categorization_1.WorkflowTechnique.DATA_ANALYSIS],
83
+ },
84
+ {
85
+ prompt: 'Generate video reels from templates and auto-post to social media on schedule',
86
+ techniques: [
87
+ categorization_1.WorkflowTechnique.SCHEDULING,
88
+ categorization_1.WorkflowTechnique.DOCUMENT_PROCESSING,
89
+ categorization_1.WorkflowTechnique.CONTENT_GENERATION,
90
+ ],
91
+ },
92
+ {
93
+ prompt: 'Receive news from Telegram channels, filter relevant ones, and forward to my channel',
94
+ techniques: [
95
+ categorization_1.WorkflowTechnique.MONITORING,
96
+ categorization_1.WorkflowTechnique.TRIAGE,
97
+ categorization_1.WorkflowTechnique.NOTIFICATION,
98
+ ],
99
+ },
100
+ {
101
+ prompt: 'Analyze YouTube video performance data and generate a weekly report',
102
+ techniques: [
103
+ categorization_1.WorkflowTechnique.SCRAPING_AND_RESEARCH,
104
+ categorization_1.WorkflowTechnique.DATA_ANALYSIS,
105
+ categorization_1.WorkflowTechnique.DATA_TRANSFORMATION,
106
+ ],
107
+ },
108
+ {
109
+ prompt: 'Create a chatbot that answers questions using data from a Google Sheet as knowledge base',
110
+ techniques: [categorization_1.WorkflowTechnique.CHATBOT, categorization_1.WorkflowTechnique.KNOWLEDGE_BASE],
111
+ },
112
+ {
113
+ prompt: 'Form submission with file upload triggers document extraction and approval workflow',
114
+ techniques: [
115
+ categorization_1.WorkflowTechnique.FORM_INPUT,
116
+ categorization_1.WorkflowTechnique.DOCUMENT_PROCESSING,
117
+ categorization_1.WorkflowTechnique.HUMAN_IN_THE_LOOP,
118
+ ],
119
+ },
120
+ ];
121
+ function formatTechniqueList() {
122
+ return Object.entries(categorization_1.TechniqueDescription)
123
+ .map(([key, description]) => `- **${key}**: ${description}`)
124
+ .join('\n');
125
+ }
126
+ function formatExampleCategorizations() {
127
+ return exampleCategorizations
128
+ .map((example) => `- ${example.prompt} → ${example.techniques.join(', ')}`)
129
+ .join('\n');
130
+ }
131
+ const discoveryOutputSchema = zod_1.z.object({
132
+ nodesFound: zod_1.z
133
+ .array(zod_1.z.object({
134
+ nodeName: zod_1.z.string().describe('The internal name of the node (e.g., n8n-nodes-base.gmail)'),
135
+ version: zod_1.z
136
+ .number()
137
+ .describe('The version number of the node (e.g., 1, 1.1, 2, 3, 3.2, etc.)'),
138
+ reasoning: zod_1.z.string().describe('Why this node is relevant for the workflow'),
139
+ connectionChangingParameters: zod_1.z
140
+ .array(zod_1.z.object({
141
+ name: zod_1.z
142
+ .string()
143
+ .describe('Parameter name (e.g., "mode", "operation", "hasOutputParser")'),
144
+ possibleValues: zod_1.z
145
+ .array(zod_1.z.union([zod_1.z.string(), zod_1.z.boolean(), zod_1.z.number()]))
146
+ .describe('Possible values this parameter can take'),
147
+ }))
148
+ .describe('Parameters that affect node connections (inputs/outputs). ONLY include if parameter appears in <input> or <output> expressions'),
149
+ }))
150
+ .describe('List of n8n nodes identified as necessary for the workflow'),
151
+ });
152
+ function generateProcessSteps(options) {
153
+ const { includeExamples } = options;
154
+ const steps = [
155
+ '**Analyze user prompt** - Extract services, models, and technologies mentioned',
156
+ '**Call get_best_practices** with identified techniques (internal context)',
157
+ ];
158
+ if (includeExamples) {
159
+ steps.push('**Call get_workflow_examples** with search queries for mentioned services/models');
160
+ }
161
+ const examplesContext = includeExamples ? ', and examples' : '';
162
+ steps.push(`**Identify workflow components** from user request, best practices${examplesContext}`, '**Call search_nodes IN PARALLEL** for all components (e.g., "Gmail", "OpenAI", "Schedule")', '**Call get_node_details IN PARALLEL** for ALL promising nodes (batch multiple calls)', `**Extract node information** from each node_details response:
163
+ - Node name from <name> tag
164
+ - Version number from <version> tag (required - extract the number)
165
+ - Connection-changing parameters from <connections> section`, '**Call submit_discovery_results** with complete nodesFound array');
166
+ return steps.map((step, index) => `${index + 1}. ${step}`).join('\n');
167
+ }
168
+ function generateAvailableToolsList(options) {
169
+ const { includeExamples } = options;
170
+ const tools = [
171
+ '- get_best_practices: Retrieve best practices (internal context)',
172
+ '- search_nodes: Find n8n nodes by keyword',
173
+ '- get_node_details: Get complete node information including <connections>',
174
+ ];
175
+ if (includeExamples) {
176
+ tools.push('- get_workflow_examples: Search for workflow examples as reference');
177
+ }
178
+ tools.push('- submit_discovery_results: Submit final results');
179
+ return tools.join('\n');
180
+ }
181
+ function generateDiscoveryPrompt(options) {
182
+ const availableTools = generateAvailableToolsList(options);
183
+ const processSteps = generateProcessSteps(options);
184
+ return `You are a Discovery Agent for n8n AI Workflow Builder.
185
+
186
+ YOUR ROLE: Identify relevant n8n nodes and their connection-changing parameters.
187
+
188
+ AVAILABLE TOOLS:
189
+ ${availableTools}
190
+
191
+ PROCESS:
192
+ ${processSteps}
193
+
194
+ TECHNIQUE CATEGORIZATION:
195
+ When calling get_best_practices, select techniques that match the user's workflow intent.
196
+
197
+ <available_techniques>
198
+ {techniques}
199
+ </available_techniques>
200
+
201
+ <example_categorizations>
202
+ {exampleCategorizations}
203
+ </example_categorizations>
204
+
205
+ <technique_clarifications>
206
+ Common distinctions to get right:
207
+ - **NOTIFICATION vs CHATBOT**: Use NOTIFICATION when SENDING emails/messages/alerts (including to Telegram CHANNELS which are broadcast-only). Use CHATBOT only when RECEIVING and REPLYING to direct messages in a conversation.
208
+ - **MONITORING**: Use when workflow TRIGGERS on external events (new record created, status changed, incoming webhook, new message in channel). NOT just scheduled runs.
209
+ - **SCRAPING_AND_RESEARCH vs DATA_EXTRACTION**: Use SCRAPING when fetching from EXTERNAL sources (APIs, websites, social media). Use DATA_EXTRACTION for parsing INTERNAL data you already have.
210
+ - **TRIAGE**: Use when SELECTING, PRIORITIZING, ROUTING, or QUALIFYING items (e.g., "pick the best", "route to correct team", "qualify leads").
211
+ - **DOCUMENT_PROCESSING**: Use for ANY file handling - PDFs, images, videos, Excel, Google Sheets, audio files, file uploads in forms.
212
+ - **HUMAN_IN_THE_LOOP**: Use when workflow PAUSES for human approval, review, signing documents, responding to polls, or any manual input before continuing.
213
+ - **DATA_ANALYSIS**: Use when ANALYZING, CLASSIFYING, IDENTIFYING PATTERNS, or UNDERSTANDING data (e.g., "analyze outcomes", "learn from previous", "classify by type", "identify trends").
214
+ - **KNOWLEDGE_BASE**: Use when storing/retrieving from a DATA SOURCE for Q&A - includes vector DBs, spreadsheets used as databases, document collections.
215
+ - **DATA_TRANSFORMATION**: Use when CONVERTING data format, creating REPORTS/SUMMARIES from analyzed data, or restructuring output.
216
+ </technique_clarifications>
217
+
218
+ Technique selection rules:
219
+ - Select ALL techniques that apply (most workflows use 2-4)
220
+ - Maximum 5 techniques
221
+ - Only select techniques you're confident apply
222
+
223
+ CONNECTION-CHANGING PARAMETERS - CRITICAL RULES:
224
+
225
+ A parameter is connection-changing ONLY IF it appears in <input> or <output> expressions within <node_details>.
226
+
227
+ **How to identify:**
228
+ 1. Look at the <connections> section in node details
229
+ 2. Check if <input> or <output> uses expressions like: ={{...parameterName...}}
230
+ 3. If a parameter is referenced in these expressions, it IS connection-changing
231
+ 4. If a parameter is NOT in <input>/<output> expressions, it is NOT connection-changing
232
+
233
+ **Example from AI Agent:**
234
+ \`\`\`xml
235
+ <input>={{...hasOutputParser, needsFallback...}}</input>
236
+ \`\`\`
237
+ → hasOutputParser and needsFallback ARE connection-changing (they control which inputs appear)
238
+
239
+ **Counter-example:**
240
+ \`\`\`xml
241
+ <properties>
242
+ <property name="promptType">...</property> <!-- NOT in <input>/<output> -->
243
+ <property name="systemMessage">...</property> <!-- NOT in <input>/<output> -->
244
+ </properties>
245
+ \`\`\`
246
+ → promptType and systemMessage are NOT connection-changing (they don't affect connections)
247
+
248
+ **Common connection-changing parameters:**
249
+ - Vector Store: mode (appears in <input>/<output> expressions)
250
+ - AI Agent: hasOutputParser, needsFallback (appears in <input> expression)
251
+ - Merge: numberInputs (appears in <input> expression)
252
+ - Webhook: responseMode (appears in <output> expression)
253
+
254
+ <dynamic_output_nodes>
255
+ Some nodes have DYNAMIC outputs that depend on parameter values:
256
+
257
+ **Switch Node** (n8n-nodes-base.switch):
258
+ - When mode is "rules", the number of outputs equals the number of routing rules
259
+ - Connection parameter: mode: "rules" - CRITICAL for enabling rule-based routing
260
+ - Each rule in rules.values[] creates one output
261
+ - The rules parameter uses the same filter structure as IF node conditions
262
+ - ALWAYS flag mode as connection-changing with possibleValues: ["rules", "expression"]
263
+
264
+ **Merge Node** (n8n-nodes-base.merge):
265
+ - numberInputs parameter controls how many inputs the node accepts
266
+
267
+ When you find these nodes, ALWAYS flag mode/numberInputs as connection-changing parameters with possibleValues.
268
+ </dynamic_output_nodes>
269
+
270
+ SUB-NODES SEARCHES:
271
+ When searching for AI nodes, ALSO search for their required sub-nodes:
272
+ - "AI Agent" → also search for "Chat Model", "Memory", "Output Parser"
273
+ - "Basic LLM Chain" → also search for "Chat Model", "Output Parser"
274
+ - "Vector Store" → also search for "Embeddings", "Document Loader"
275
+
276
+ STRUCTURED OUTPUT PARSER - WHEN TO INCLUDE:
277
+ Search for "Structured Output Parser" (@n8n/n8n-nodes-langchain.outputParserStructured) when:
278
+ - AI output will be used programmatically (conditions, formatting, database storage, API calls)
279
+ - AI needs to extract specific fields (e.g., score, category, priority, action items)
280
+ - AI needs to classify/categorize data into defined categories
281
+ - Downstream nodes need to access specific fields from AI response (e.g., $json.score, $json.category)
282
+ - Output will be displayed in a formatted way (e.g., HTML email with specific sections)
283
+ - Data needs validation against a schema before processing
284
+
285
+
286
+ - Always use search_nodes to find the exact node names and versions - NEVER guess versions
287
+
288
+ CRITICAL RULES:
289
+ - NEVER ask clarifying questions
290
+ - ALWAYS call get_best_practices first
291
+ - THEN Call search_nodes to learn about available nodes and their inputs and outputs
292
+ - FINALLY call get_node_details IN PARALLEL for speed to get more details about RELVANT node
293
+ - ALWAYS extract version number from <version> tag in node details
294
+ - NEVER guess node versions - always use search_nodes to find exact versions
295
+ - ONLY flag connectionChangingParameters if they appear in <input> or <output> expressions
296
+ - If no parameters appear in connection expressions, return empty array []
297
+ - Output ONLY: nodesFound with {{ nodeName, version, reasoning, connectionChangingParameters }}
298
+
299
+ DO NOT:
300
+ - Output text commentary between tool calls
301
+ - Include bestPractices or categorization in submit_discovery_results
302
+ - Flag parameters that don't affect connections
303
+ - Stop without calling submit_discovery_results
304
+ `;
305
+ }
306
+ exports.DiscoverySubgraphState = langgraph_1.Annotation.Root({
307
+ userRequest: (0, langgraph_1.Annotation)({
308
+ reducer: (x, y) => y ?? x,
309
+ default: () => '',
310
+ }),
311
+ messages: (0, langgraph_1.Annotation)({
312
+ reducer: (x, y) => x.concat(y),
313
+ default: () => [],
314
+ }),
315
+ nodesFound: (0, langgraph_1.Annotation)({
316
+ reducer: (x, y) => y ?? x,
317
+ default: () => [],
318
+ }),
319
+ bestPractices: (0, langgraph_1.Annotation)({
320
+ reducer: (x, y) => y ?? x,
321
+ }),
322
+ templateIds: (0, langgraph_1.Annotation)({
323
+ reducer: state_reducers_1.appendArrayReducer,
324
+ default: () => [],
325
+ }),
326
+ nodeConfigurations: (0, langgraph_1.Annotation)({
327
+ reducer: state_reducers_1.nodeConfigurationsReducer,
328
+ default: () => ({}),
329
+ }),
330
+ });
331
+ class DiscoverySubgraph extends subgraph_interface_1.BaseSubgraph {
332
+ name = 'discovery_subgraph';
333
+ description = 'Discovers nodes and context for the workflow';
334
+ agent;
335
+ toolMap;
336
+ logger;
337
+ create(config) {
338
+ this.logger = config.logger;
339
+ const includeExamples = config.featureFlags?.templateExamples === true;
340
+ const baseTools = [
341
+ (0, get_best_practices_tool_1.createGetBestPracticesTool)(),
342
+ (0, node_search_tool_1.createNodeSearchTool)(config.parsedNodeTypes),
343
+ (0, node_details_tool_1.createNodeDetailsTool)(config.parsedNodeTypes),
344
+ ];
345
+ const tools = includeExamples
346
+ ? [...baseTools, (0, get_workflow_examples_tool_1.createGetWorkflowExamplesTool)(config.logger)]
347
+ : baseTools;
348
+ this.toolMap = new Map(tools.map((bt) => [bt.tool.name, bt.tool]));
349
+ const submitTool = (0, tools_1.tool)(() => { }, {
350
+ name: 'submit_discovery_results',
351
+ description: 'Submit the final discovery results',
352
+ schema: discoveryOutputSchema,
353
+ });
354
+ const discoveryPrompt = generateDiscoveryPrompt({ includeExamples });
355
+ const systemPrompt = prompts_1.ChatPromptTemplate.fromMessages([
356
+ [
357
+ 'system',
358
+ [
359
+ {
360
+ type: 'text',
361
+ text: discoveryPrompt,
362
+ cache_control: { type: 'ephemeral' },
363
+ },
364
+ ],
365
+ ],
366
+ ['human', '{prompt}'],
367
+ ['placeholder', '{messages}'],
368
+ ]);
369
+ if (typeof config.llm.bindTools !== 'function') {
370
+ throw new errors_1.LLMServiceError('LLM does not support tools', {
371
+ llmModel: config.llm._llmType(),
372
+ });
373
+ }
374
+ const allTools = [...tools.map((bt) => bt.tool), submitTool];
375
+ this.agent = systemPrompt.pipe(config.llm.bindTools(allTools));
376
+ const subgraph = new langgraph_1.StateGraph(exports.DiscoverySubgraphState)
377
+ .addNode('agent', this.callAgent.bind(this))
378
+ .addNode('tools', async (state) => await (0, subgraph_helpers_1.executeSubgraphTools)(state, this.toolMap))
379
+ .addNode('format_output', this.formatOutput.bind(this))
380
+ .addEdge('__start__', 'agent')
381
+ .addConditionalEdges('agent', this.shouldContinue.bind(this), {
382
+ tools: 'tools',
383
+ format_output: 'format_output',
384
+ end: langgraph_1.END,
385
+ })
386
+ .addEdge('tools', 'agent')
387
+ .addEdge('format_output', langgraph_1.END);
388
+ return subgraph.compile();
389
+ }
390
+ async callAgent(state) {
391
+ if (state.messages.length > 0) {
392
+ (0, cache_control_1.applySubgraphCacheMarkers)(state.messages);
393
+ }
394
+ const response = (await this.agent.invoke({
395
+ messages: state.messages,
396
+ prompt: state.userRequest,
397
+ techniques: formatTechniqueList(),
398
+ exampleCategorizations: formatExampleCategorizations(),
399
+ }));
400
+ return { messages: [response] };
401
+ }
402
+ formatOutput(state) {
403
+ const lastMessage = state.messages.at(-1);
404
+ let output;
405
+ if (lastMessage && (0, messages_1.isAIMessage)(lastMessage) && lastMessage.tool_calls) {
406
+ const submitCall = lastMessage.tool_calls.find((tc) => tc.name === 'submit_discovery_results');
407
+ if (submitCall) {
408
+ output = submitCall.args;
409
+ }
410
+ }
411
+ if (!output) {
412
+ this.logger?.error('[Discovery] No submit tool call found in last message');
413
+ return {
414
+ nodesFound: [],
415
+ templateIds: [],
416
+ };
417
+ }
418
+ const bestPracticesTool = state.messages.find((m) => m.getType() === 'tool' && m?.text?.startsWith('<best_practices>'));
419
+ return {
420
+ nodesFound: output.nodesFound,
421
+ bestPractices: bestPracticesTool?.text,
422
+ templateIds: state.templateIds ?? [],
423
+ nodeConfigurations: state.nodeConfigurations ?? {},
424
+ };
425
+ }
426
+ shouldContinue(state) {
427
+ const lastMessage = state.messages[state.messages.length - 1];
428
+ if (lastMessage &&
429
+ (0, messages_1.isAIMessage)(lastMessage) &&
430
+ lastMessage.tool_calls &&
431
+ lastMessage.tool_calls.length > 0) {
432
+ const submitCall = lastMessage.tool_calls.find((tc) => tc.name === 'submit_discovery_results');
433
+ if (submitCall) {
434
+ return 'format_output';
435
+ }
436
+ return 'tools';
437
+ }
438
+ this.logger?.warn('[Discovery Subgraph] Agent stopped without submitting results');
439
+ return 'end';
440
+ }
441
+ transformInput(parentState) {
442
+ const userRequest = (0, subgraph_helpers_1.extractUserRequest)(parentState.messages, 'Build a workflow');
443
+ const contextParts = [];
444
+ contextParts.push('<user_request>');
445
+ contextParts.push(userRequest);
446
+ contextParts.push('</user_request>');
447
+ if (parentState.workflowJSON.nodes.length > 0) {
448
+ contextParts.push('<existing_workflow_summary>');
449
+ contextParts.push((0, context_builders_1.buildWorkflowSummary)(parentState.workflowJSON));
450
+ contextParts.push('</existing_workflow_summary>');
451
+ }
452
+ const contextMessage = (0, context_builders_1.createContextMessage)(contextParts);
453
+ return {
454
+ userRequest,
455
+ messages: [contextMessage],
456
+ };
457
+ }
458
+ transformOutput(subgraphOutput, _parentState) {
459
+ const nodesFound = subgraphOutput.nodesFound || [];
460
+ const templateIds = subgraphOutput.templateIds || [];
461
+ const nodeConfigurations = subgraphOutput.nodeConfigurations || {};
462
+ const discoveryContext = {
463
+ nodesFound,
464
+ bestPractices: subgraphOutput.bestPractices,
465
+ nodeConfigurations,
466
+ };
467
+ const logEntry = {
468
+ phase: 'discovery',
469
+ status: 'completed',
470
+ timestamp: Date.now(),
471
+ summary: `Discovered ${nodesFound.length} nodes`,
472
+ metadata: (0, coordination_1.createDiscoveryMetadata)({
473
+ nodesFound: nodesFound.length,
474
+ nodeTypes: nodesFound.map((n) => n.nodeName),
475
+ hasBestPractices: !!subgraphOutput.bestPractices,
476
+ }),
477
+ };
478
+ return {
479
+ discoveryContext,
480
+ coordinationLog: [logEntry],
481
+ templateIds,
482
+ nodeConfigurations,
483
+ };
484
+ }
485
+ }
486
+ exports.DiscoverySubgraph = DiscoverySubgraph;
487
+ //# sourceMappingURL=discovery.subgraph.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discovery.subgraph.js","sourceRoot":"","sources":["../../src/subgraphs/discovery.subgraph.ts"],"names":[],"mappings":";;;AAEA,uDAAuD;AACvD,qDAA6D;AAE7D,iDAAkE;AAClE,oDAAmE;AAGnE,6BAAwB;AAExB,qCAA2C;AAC3C,2DAIgC;AAGhC,6DAAoD;AAEpD,8EAA8E;AAC9E,oFAAoF;AACpF,kEAAmE;AACnE,gEAAiE;AAEjE,wDAAgE;AAEhE,0DAAmE;AACnE,gEAAuF;AACvF,4DAAwF;AACxF,gEAAqF;AAMrF,MAAM,sBAAsB,GAGvB;IACJ;QACC,MAAM,EAAE,sFAAsF;QAC9F,UAAU,EAAE;YACX,kCAAiB,CAAC,UAAU;YAC5B,kCAAiB,CAAC,OAAO;YACzB,kCAAiB,CAAC,kBAAkB;SACpC;KACD;IACD;QACC,MAAM,EAAE,+EAA+E;QACvF,UAAU,EAAE;YACX,kCAAiB,CAAC,UAAU;YAC5B,kCAAiB,CAAC,iBAAiB;YACnC,kCAAiB,CAAC,YAAY;SAC9B;KACD;IACD;QACC,MAAM,EAAE,iFAAiF;QACzF,UAAU,EAAE;YACX,kCAAiB,CAAC,UAAU;YAC5B,kCAAiB,CAAC,qBAAqB;YACvC,kCAAiB,CAAC,eAAe;YACjC,kCAAiB,CAAC,aAAa;SAC/B;KACD;IACD;QACC,MAAM,EAAE,iFAAiF;QACz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,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC;gBAC5C,gBAAgB,EAAE,CAAC,CAAC,cAAc,CAAC,aAAa;aAChD,CAAC;SACF,CAAC;QAEF,OAAO;YACN,gBAAgB;YAChB,eAAe,EAAE,CAAC,QAAQ,CAAC;YAE3B,WAAW;YAEX,kBAAkB;SAClB,CAAC;IACH,CAAC;CACD;AA7OD,8CA6OC"}
@@ -0,0 +1,23 @@
1
+ type StateRecord = Record<string, unknown>;
2
+ interface InvokeConfig {
3
+ recursionLimit?: number;
4
+ }
5
+ export interface ISubgraph<TConfig = unknown, TChildState extends StateRecord = StateRecord, TParentState extends StateRecord = StateRecord> {
6
+ name: string;
7
+ description: string;
8
+ create(config: TConfig): {
9
+ invoke: (input: Partial<TChildState>, config?: InvokeConfig) => Promise<TChildState>;
10
+ };
11
+ transformInput: (parentState: TParentState) => Partial<TChildState>;
12
+ transformOutput: (childOutput: TChildState, parentState: TParentState) => Partial<TParentState>;
13
+ }
14
+ export declare abstract class BaseSubgraph<TConfig = unknown, TChildState extends StateRecord = StateRecord, TParentState extends StateRecord = StateRecord> implements ISubgraph<TConfig, TChildState, TParentState> {
15
+ abstract name: string;
16
+ abstract description: string;
17
+ abstract create(config: TConfig): {
18
+ invoke: (input: Partial<TChildState>, config?: InvokeConfig) => Promise<TChildState>;
19
+ };
20
+ abstract transformInput(parentState: TParentState): Partial<TChildState>;
21
+ abstract transformOutput(childOutput: TChildState, parentState: TParentState): Partial<TParentState>;
22
+ }
23
+ export {};
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseSubgraph = void 0;
4
+ class BaseSubgraph {
5
+ }
6
+ exports.BaseSubgraph = BaseSubgraph;
7
+ //# sourceMappingURL=subgraph-interface.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subgraph-interface.js","sourceRoot":"","sources":["../../src/subgraphs/subgraph-interface.ts"],"names":[],"mappings":";;;AAoBA,MAAsB,YAAY;CA2BjC;AA3BD,oCA2BC"}
@@ -11,6 +11,42 @@ class ContentGenerationBestPractices {
11
11
 
12
12
  Break complex tasks into sequential steps (e.g., generate text, create image, compose video) for modularity and easier troubleshooting.
13
13
 
14
+ ## Node Selection Guidelines
15
+
16
+ Always prefer built-in n8n nodes over HTTP Request nodes when a dedicated node exists for the service or API you need to integrate with. Built-in nodes provide:
17
+ - Pre-configured authentication handling
18
+ - Optimized data structures and field mappings
19
+ - Better error handling and user experience
20
+ - Simplified setup without manual API configuration
21
+
22
+ Only use HTTP Request nodes when no built-in node exists for the service, or when you need to access an API endpoint not covered by the built-in node's operations.
23
+
24
+ ## Multi-Modal Content Generation - MANDATORY
25
+
26
+ When the user's request involves specific generative AI models or media-focused platforms, the workflow MUST include the appropriate media generation node from a
27
+ provider-specific node. The finished workflow MUST contain the relevant video, audio, or image generation capability.
28
+
29
+ Prompts that require multi-modal generation nodes:
30
+
31
+ Video Generation:
32
+ - Model mentions: Sora, Nano Banana, Veo, Runway, Pika
33
+ - Platform mentions: YouTube content, TikTok videos, Instagram Reels, video ads, short-form video
34
+ - Task mentions: generate video, create video, video from text, animate
35
+
36
+ Image Generation:
37
+ - Model mentions: DALL-E, Midjourney, Stable Diffusion, Imagen
38
+ - Platform mentions: thumbnails, social media graphics, product images, marketing visuals
39
+ - Task mentions: generate image, create artwork, design graphic, visualize
40
+
41
+ Audio Generation:
42
+ - Model mentions: ElevenLabs, text-to-speech, TTS
43
+ - Platform mentions: podcast audio, voiceovers, narration, audio content
44
+ - Task mentions: generate voice, create audio, synthesize speech, clone voice
45
+
46
+ If anything like the examples above are mentioned in the prompt, include the appropriate
47
+ provider node (OpenAI for DALL-E/Sora, Google Gemini for Nano Banana/Imagen, etc.)
48
+ with the media generation operation configured.
49
+
14
50
  ## Content-Specific Guidance
15
51
 
16
52
  For text generation, validate and sanitize input/output to avoid malformed data. When generating images, prefer binary data over URLs for uploads to avoid media type errors.
@@ -19,7 +55,7 @@ For text generation, validate and sanitize input/output to avoid malformed data.
19
55
 
20
56
  ### OpenAI (@n8n/n8n-nodes-langchain.openAi)
21
57
 
22
- Purpose: GPT-based text generation, DALL-E image generation, text-to-speech (TTS), and audio transcription
58
+ Purpose: GPT-based text generation, DALL-E image generation, text-to-speech (TTS), and audio transcription, SORA for video generation
23
59
 
24
60
  ### xAI Grok Chat Model (@n8n/n8n-nodes-langchain.lmChatXAiGrok)
25
61
 
@@ -27,7 +63,7 @@ Purpose: Conversational AI and text generation
27
63
 
28
64
  ### Google Gemini Chat Model (@n8n/n8n-nodes-langchain.lmChatGoogleGemini)
29
65
 
30
- Purpose: Image analysis and generation, video generation from text prompts, multimodal content creation
66
+ Purpose: Image analysis and generation, video generation from text prompts using nano banana, multimodal content creation
31
67
 
32
68
  ### ElevenLabs
33
69
 
@@ -1 +1 @@
1
- {"version":3,"file":"content-generation.js","sourceRoot":"","sources":["../../../src/tools/best-practices/content-generation.ts"],"names":[],"mappings":";;;AACA,2DAA2D;AAE3D,MAAa,8BAA8B;IACjC,SAAS,GAAG,kCAAiB,CAAC,kBAAkB,CAAC;IACjD,OAAO,GAAG,OAAO,CAAC;IAEV,aAAa,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiEjC,CAAC;IAED,gBAAgB;QACf,OAAO,IAAI,CAAC,aAAa,CAAC;IAC3B,CAAC;CACD;AA1ED,wEA0EC"}
1
+ {"version":3,"file":"content-generation.js","sourceRoot":"","sources":["../../../src/tools/best-practices/content-generation.ts"],"names":[],"mappings":";;;AACA,2DAA2D;AAE3D,MAAa,8BAA8B;IACjC,SAAS,GAAG,kCAAiB,CAAC,kBAAkB,CAAC;IACjD,OAAO,GAAG,OAAO,CAAC;IAEV,aAAa,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqGjC,CAAC;IAED,gBAAgB;QACf,OAAO,IAAI,CAAC,aAAa,CAAC;IAC3B,CAAC;CACD;AA9GD,wEA8GC"}
@@ -2,12 +2,15 @@ import type { BaseChatModel } from '@langchain/core/language_models/chat_models'
2
2
  import type { Logger } from '@n8n/backend-common';
3
3
  import type { INodeTypeDescription } from 'n8n-workflow';
4
4
  import type { BuilderTool, BuilderToolBase } from '../utils/stream-processor';
5
- export declare function getBuilderTools({ parsedNodeTypes, logger, llmComplexTask, instanceUrl, }: {
5
+ import type { BuilderFeatureFlags } from '../workflow-builder-agent';
6
+ export declare function getBuilderTools({ parsedNodeTypes, logger, llmComplexTask, instanceUrl, featureFlags, }: {
6
7
  parsedNodeTypes: INodeTypeDescription[];
7
8
  llmComplexTask: BaseChatModel;
8
9
  logger?: Logger;
9
10
  instanceUrl?: string;
11
+ featureFlags?: BuilderFeatureFlags;
10
12
  }): BuilderTool[];
11
- export declare function getBuilderToolsForDisplay({ nodeTypes, }: {
13
+ export declare function getBuilderToolsForDisplay({ nodeTypes, featureFlags, }: {
12
14
  nodeTypes: INodeTypeDescription[];
15
+ featureFlags?: BuilderFeatureFlags;
13
16
  }): BuilderToolBase[];