"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toolsAgentExecute = toolsAgentExecute;
const n8n_workflow_1 = require("n8n-workflow");
const helpers_1 = require("./helpers");
const utils_1 = require("../../utils");
function countFailedItems(returnData) {
    let failed = 0;
    for (const { json } of returnData) {
        if (typeof json.error === 'string' && json.error.length > 0) {
            failed++;
        }
    }
    return failed;
}
async function toolsAgentExecute(response) {
    this.logger.debug('Executing Tools Agent V3');
    let request = undefined;
    const returnData = [];
    let requestedToolCalls = 0;
    const completedToolCalls = response?.actionResponses?.length ?? 0;
    let failedItems = 0;
    let iterationCount = 0;
    let itemsTotal = 0;
    let enableStreaming = true;
    let failureType;
    let memoryLoads = 0;
    let memorySaves = 0;
    try {
        const executionContext = await (0, helpers_1.buildExecutionContext)(this);
        const { items, batchSize, delayBetweenBatches, model, fallbackModel, memory } = executionContext;
        itemsTotal = items.length;
        enableStreaming = this.getNodeParameter('options.enableStreaming', 0, true);
        for (let i = 0; i < items.length; i += batchSize) {
            const batch = items.slice(i, i + batchSize);
            const { returnData: batchReturnData, request: batchRequest, memoryHits, } = await (0, helpers_1.executeBatch)(this, batch, i, model, fallbackModel, memory, response);
            memoryLoads += memoryHits.loads;
            memorySaves += memoryHits.saves;
            returnData.push.apply(returnData, batchReturnData);
            failedItems += countFailedItems(batchReturnData);
            if (batchRequest) {
                requestedToolCalls += batchRequest.actions.length;
                const currentIteration = batchRequest.metadata?.iterationCount;
                if (typeof currentIteration === 'number') {
                    iterationCount = Math.max(iterationCount, currentIteration);
                }
                if (!request) {
                    request = batchRequest;
                }
                else {
                    request.actions.push.apply(request.actions, batchRequest.actions);
                }
            }
            if (i + batchSize < items.length && delayBetweenBatches > 0) {
                await (0, n8n_workflow_1.sleep)(delayBetweenBatches);
            }
        }
        if (request) {
            if ((0, utils_1.isExecuteFunctions)(this)) {
                return request;
            }
            return await (0, helpers_1.resolveSubAgentRequest)(this, request, {
                runAgentBatch: async (engineResponse) => await toolsAgentExecute.call(this, engineResponse),
            });
        }
        if (this.getNodeParameter('options.autoSaveHighlightedData', 0, true) !== false) {
            const firstOutput = returnData[0]?.json?.output;
            if (typeof firstOutput === 'string') {
                this.customData.set((0, n8n_workflow_1.getHighlightedResponseKey)(this.getNode().name), firstOutput);
            }
        }
        return [returnData];
    }
    catch (error) {
        failureType =
            error instanceof Error ? error.name || error.constructor.name || 'Error' : typeof error;
        throw error;
    }
    finally {
        if ((0, utils_1.isExecuteFunctions)(this)) {
            const tracing = {
                'ai.agent.version': 'v3',
                'ai.agent.streaming.enabled': enableStreaming,
                'ai.agent.items.total': itemsTotal,
                'ai.agent.items.failed': failedItems,
                'ai.agent.tool_calls.requested': requestedToolCalls,
                'ai.agent.tool_calls.completed': completedToolCalls,
                'ai.agent.iteration.count': iterationCount,
                'ai.agent.memory.loads': memoryLoads,
                'ai.agent.memory.saves': memorySaves,
                'ai.agent.execution.succeeded': failureType === undefined,
            };
            if (failureType !== undefined) {
                tracing['ai.agent.failure.type'] = failureType;
            }
            this.setMetadata({ tracing });
        }
    }
}
//# sourceMappingURL=execute.js.map