"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.runAgent = runAgent;
const agent_execution_1 = require("../../../../../../../utils/agent-execution");
const buildResponseMetadata_1 = require("../../../../../../../utils/agent-execution/buildResponseMetadata");
const tracing_1 = require("../../../../../../../utils/tracing");
const utils_1 = require("../../../utils");
const prompt_1 = require("../../prompt");
async function runAgent(ctx, executor, itemContext, model, memory, response, memoryHits) {
    const { itemIndex, input, steps, tools, options } = itemContext;
    const invokeParams = {
        steps,
        input,
        system_message: options.systemMessage ?? prompt_1.SYSTEM_MESSAGE,
        formatting_instructions: 'IMPORTANT: For your response to user, you MUST use the `format_final_json_response` tool with your complete answer formatted according to the required schema. Do not attempt to format the JSON manually - always use this tool. Your response will be rejected if it is not properly formatted through this tool. Only use this tool once you are ready to provide your final answer.',
    };
    const executeOptions = { signal: ctx.getExecutionCancelSignal() };
    const logger = 'logger' in ctx ? ctx.logger : undefined;
    const additionalMetadata = (0, tracing_1.buildTracingMetadata)(options.tracingMetadata?.values, logger);
    if (Object.keys(additionalMetadata).length > 0 && logger) {
        ctx.logger.debug('Tracing metadata', { additionalMetadata });
    }
    const tracingConfig = (0, utils_1.isExecuteFunctions)(ctx)
        ? (0, tracing_1.getTracingConfig)(ctx, { additionalMetadata })
        : undefined;
    const executorWithTracing = tracingConfig ? executor.withConfig(tracingConfig) : executor;
    const isStreamingAvailable = 'isStreaming' in ctx ? ctx.isStreaming?.() : undefined;
    if ('isStreaming' in ctx &&
        options.enableStreaming &&
        isStreamingAvailable &&
        ctx.getNode().typeVersion >= 2.1) {
        const chatHistory = await (0, agent_execution_1.loadMemory)(memory, model, options.maxTokensFromMemory);
        if (memory && memoryHits) {
            memoryHits.loads++;
        }
        const eventStream = executorWithTracing.streamEvents({
            ...invokeParams,
            chat_history: chatHistory,
        }, {
            version: 'v2',
            ...executeOptions,
        });
        const result = await (0, agent_execution_1.processEventStream)(ctx, eventStream, itemIndex);
        if (result.toolCalls && result.toolCalls.length > 0) {
            const actions = (0, agent_execution_1.createEngineRequests)(result.toolCalls, itemIndex, tools);
            return {
                actions,
                metadata: (0, buildResponseMetadata_1.buildResponseMetadata)(response, itemIndex),
            };
        }
        if (memory && input && result?.output) {
            const previousCount = response?.metadata?.previousRequests?.length;
            await (0, agent_execution_1.saveToMemory)(input, result.output, memory, steps, previousCount);
            if (memoryHits) {
                memoryHits.saves++;
            }
        }
        if (options.returnIntermediateSteps && steps.length > 0) {
            result.intermediateSteps = steps;
        }
        return result;
    }
    else {
        const chatHistory = await (0, agent_execution_1.loadMemory)(memory, model, options.maxTokensFromMemory);
        if (memory && memoryHits) {
            memoryHits.loads++;
        }
        const modelResponse = await executorWithTracing.invoke({
            ...invokeParams,
            chat_history: chatHistory,
        }, executeOptions);
        if ('returnValues' in modelResponse) {
            if (memory && input && modelResponse.returnValues.output) {
                const previousCount = response?.metadata?.previousRequests?.length;
                await (0, agent_execution_1.saveToMemory)(input, modelResponse.returnValues.output, memory, steps, previousCount);
                if (memoryHits) {
                    memoryHits.saves++;
                }
            }
            const result = { ...modelResponse.returnValues };
            if (options.returnIntermediateSteps && steps.length > 0) {
                result.intermediateSteps = steps;
            }
            return result;
        }
        const actions = (0, agent_execution_1.createEngineRequests)(modelResponse, itemIndex, tools);
        return {
            actions,
            metadata: (0, buildResponseMetadata_1.buildResponseMetadata)(response, itemIndex),
        };
    }
}
//# sourceMappingURL=runAgent.js.map