Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/@n8n/api-types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,9 @@ export type {
InstanceAiAgentNode,
InstanceAiTimelineEntry,
InstanceAiMessage,
InstanceAiReferencedDataTable,
InstanceAiAppliedCredential,
InstanceAiWorkflowReferences,
InstanceAiThreadSummary,
InstanceAiSSEConnectionState,
InstanceAiThreadInfo,
Expand Down
22 changes: 22 additions & 0 deletions packages/@n8n/api-types/src/schemas/instance-ai.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1030,6 +1030,28 @@ export class InstanceAiEvalExecutionRequest extends Z.class({
scenarioHints: z.string().max(2000).optional(),
}) {}

// ---------------------------------------------------------------------------
// Workflow references
// ---------------------------------------------------------------------------

export interface InstanceAiReferencedDataTable {
id: string;
name: string;
projectId: string;
}

export interface InstanceAiAppliedCredential {
id: string;
name: string;
credentialType: string;
}

export interface InstanceAiWorkflowReferences {
workflowId: string;
referencedDataTables: InstanceAiReferencedDataTable[];
appliedCredentials: InstanceAiAppliedCredential[];
}

// ---------------------------------------------------------------------------
// Sub-agent evaluation endpoint
// ---------------------------------------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ function createMockContext(overrides?: Partial<InstanceAiContext>): InstanceAiCo
listSearchable: jest.fn(),
},
dataTableService: {
get: jest.fn(),
list: jest.fn(),
create: jest.fn(),
delete: jest.fn(),
Expand Down
8 changes: 8 additions & 0 deletions packages/@n8n/instance-ai/src/tools/workflows.tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { z } from 'zod';
import { sanitizeInputSchema } from '../agent/sanitize-mcp-schemas';
import type { InstanceAiContext } from '../types';
import { formatTimestamp } from '../utils/format-timestamp';
import { resolveReferences } from './workflows/resolve-references';
import { setupSuspendSchema, setupResumeSchema } from './workflows/setup-workflow.schema';
import {
analyzeWorkflow,
Expand Down Expand Up @@ -401,6 +402,11 @@ async function handleSetup(
const allFailedNodes = [...(failedNodes ?? []), ...credTestFailures];
const mergedFailedNodes = allFailedNodes.length > 0 ? allFailedNodes : undefined;

const references = await resolveReferences(context, input.workflowId, {
excludeNodeNames: credFailedNodeNames,
nodes: updatedWorkflow.nodes,
});

if (pendingRequests.length > 0) {
const skippedNodes = pendingRequests.map((r) => ({
nodeName: r.node.name,
Expand All @@ -415,6 +421,7 @@ async function handleSetup(
failedNodes: mergedFailedNodes,
updatedNodes,
updatedConnections,
...(references ? { references } : {}),
};
}

Expand All @@ -424,6 +431,7 @@ async function handleSetup(
failedNodes: mergedFailedNodes,
updatedNodes,
updatedConnections,
...(references ? { references } : {}),
};
} catch (error) {
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ function createMockContext(overrides?: Partial<InstanceAiContext>): InstanceAiCo
listSearchable: jest.fn(),
},
dataTableService: {
get: jest.fn(),
list: jest.fn(),
create: jest.fn(),
delete: jest.fn(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { generateWorkflowCode, layoutWorkflowJSON } from '@n8n/workflow-sdk';
import { z } from 'zod';

import { buildCredentialMap, resolveCredentials } from './resolve-credentials';
import { resolveReferences } from './resolve-references';
import { stripStaleCredentialsFromWorkflow } from './setup-workflow.service';
import { ensureWebhookIds } from './submit-workflow.tool';
import type { InstanceAiContext } from '../../types';
Expand Down Expand Up @@ -65,6 +66,17 @@ export function createBuildWorkflowTool(context: InstanceAiContext) {
workflowId: z.string().optional(),
errors: z.array(z.string()).optional(),
warnings: z.array(z.string()).optional(),
references: z
.object({
workflowId: z.string(),
referencedDataTables: z.array(
z.object({ id: z.string(), name: z.string(), projectId: z.string() }),
),
appliedCredentials: z.array(
z.object({ id: z.string(), name: z.string(), credentialType: z.string() }),
),
})
.optional(),
}),
execute: async (input: z.infer<typeof buildWorkflowInputSchema>) => {
const permKey = input.workflowId ? 'updateWorkflow' : 'createWorkflow';
Expand Down Expand Up @@ -182,27 +194,31 @@ export function createBuildWorkflowTool(context: InstanceAiContext) {
json,
projectId ? { projectId } : undefined,
);
const references = await resolveReferences(context, updated.id);
return {
success: true,
workflowId: updated.id,
warnings:
informational.length > 0
? informational.map((w) => `[${w.code}]: ${w.message}`)
: undefined,
...(references ? { references } : {}),
};
} else {
const created = await context.workflowService.createFromWorkflowJSON(json, {
...(projectId ? { projectId } : {}),
markAsAiTemporary: true,
});
(context.aiCreatedWorkflowIds ??= new Set<string>()).add(created.id);
const references = await resolveReferences(context, created.id);
return {
success: true,
workflowId: created.id,
warnings:
informational.length > 0
? informational.map((w) => `[${w.code}]: ${w.message}`)
: undefined,
...(references ? { references } : {}),
};
}
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { InstanceAiWorkflowReferences } from '@n8n/api-types';
import type { WorkflowJSON } from '@n8n/workflow-sdk';

import type { InstanceAiContext } from '../../types';

export async function resolveReferences(
context: InstanceAiContext,
workflowId: string,
options?: { excludeNodeNames?: Set<string>; nodes?: WorkflowJSON['nodes'] },
): Promise<InstanceAiWorkflowReferences | undefined> {
if (!context.getWorkflowReferences) return undefined;
try {
const references = await context.getWorkflowReferences(workflowId);
const exclude = options?.excludeNodeNames;
const nodes = options?.nodes;
if (!exclude || exclude.size === 0 || !nodes) return references;

const validCredIds = new Set<string>();
for (const node of nodes) {
if (node.name && exclude.has(node.name)) continue;
for (const cred of Object.values(node.credentials ?? {})) {
if (cred?.id) validCredIds.add(cred.id);
}
}
return {
...references,
appliedCredentials: references.appliedCredentials.filter((c) => validCredIds.has(c.id)),
};
} catch (error) {
context.logger?.warn?.('getWorkflowReferences failed', { error });
return undefined;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { createHash, randomUUID } from 'node:crypto';
import { z } from 'zod';

import { resolveCredentials, type CredentialMap } from './resolve-credentials';
import { resolveReferences } from './resolve-references';
import { stripStaleCredentialsFromWorkflow } from './setup-workflow.service';
import type { InstanceAiContext } from '../../types';
import type { ValidationWarning } from '../../workflow-builder';
Expand Down Expand Up @@ -162,6 +163,17 @@ export const submitWorkflowOutputSchema = z.object({
verificationPinData: z.record(z.array(z.record(z.unknown()))).optional(),
errors: z.array(z.string()).optional(),
warnings: z.array(z.string()).optional(),
references: z
.object({
workflowId: z.string(),
referencedDataTables: z.array(
z.object({ id: z.string(), name: z.string(), projectId: z.string() }),
),
appliedCredentials: z.array(
z.object({ id: z.string(), name: z.string(), credentialType: z.string() }),
),
})
.optional(),
});

export type SubmitWorkflowInput = z.infer<typeof submitWorkflowInputSchema>;
Expand Down Expand Up @@ -401,6 +413,7 @@ export function createSubmitWorkflowTool(
: undefined,
hasUnresolvedPlaceholders: hasPlaceholders || undefined,
});
const references = await resolveReferences(context, savedId);
return {
success: true,
workflowId: savedId,
Expand All @@ -418,6 +431,7 @@ export function createSubmitWorkflowTool(
informational.length > 0
? informational.map((w) => `[${w.code}]: ${w.message}`)
: undefined,
...(references ? { references } : {}),
};
},
});
Expand Down
3 changes: 3 additions & 0 deletions packages/@n8n/instance-ai/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
TaskList,
InstanceAiAttachment,
InstanceAiPermissions,
InstanceAiWorkflowReferences,
McpTool,
McpToolCallRequest,
McpToolCallResult,
Expand Down Expand Up @@ -371,6 +372,7 @@ export interface DataTableFilterInput {
// ── Data table service ───────────────────────────────────────────────────────

export interface InstanceAiDataTableService {
get(dataTableId: string): Promise<DataTableSummary>;
list(options?: { projectId?: string }): Promise<DataTableSummary[]>;
create(
name: string,
Expand Down Expand Up @@ -565,6 +567,7 @@ export interface InstanceAiContext {
currentUserAttachments?: InstanceAiAttachment[];
/** Optional logger for diagnostics from domain tools. */
logger?: Logger;
getWorkflowReferences?(workflowId: string): Promise<InstanceAiWorkflowReferences>;
}

// ── Task storage ─────────────────────────────────────────────────────────────
Expand Down
Loading
Loading