"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Chat = void 0;
const highlightedData_1 = require("n8n-nodes-base/dist/utils/highlightedData");
const descriptions_1 = require("n8n-nodes-base/dist/utils/sendAndWait/descriptions");
const utils_1 = require("n8n-nodes-base/dist/utils/sendAndWait/utils");
const n8n_workflow_1 = require("n8n-workflow");
const util_1 = require("./util");
class Chat {
    constructor() {
        this.description = {
            usableAsTool: true,
            displayName: 'Chat',
            name: 'chat',
            icon: 'node:chat-trigger',
            iconColor: 'black',
            group: ['input'],
            version: [1, 1.1, 1.2, 1.3],
            defaultVersion: 1.3,
            description: 'Send a message into the chat',
            defaults: {
                name: 'Chat',
            },
            builderHint: {
                relatedNodes: [
                    {
                        nodeType: '@n8n/n8n-nodes-langchain.chatTrigger',
                        relationHint: 'Required trigger for this node to work - must set responseMode to "responseNodes"',
                    },
                ],
            },
            codex: {
                categories: ['Core Nodes', 'HITL'],
                subcategories: {
                    HITL: ['Human in the Loop'],
                },
                alias: ['human', 'wait', 'hitl', 'respond', 'approve', 'confirm', 'send', 'message'],
                resources: {
                    primaryDocumentation: [
                        {
                            url: 'https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-langchain.respondtochat/',
                        },
                    ],
                },
            },
            inputs: `={{ (${util_1.configureInputs})($parameter) }}`,
            outputs: [n8n_workflow_1.NodeConnectionTypes.Main],
            waitingNodeTooltip: utils_1.SEND_AND_WAIT_WAITING_TOOLTIP,
            webhooks: descriptions_1.sendAndWaitWebhooksDescription,
            properties: [
                {
                    displayName: "Verify you're using a chat trigger with the 'Response Mode' option set to 'Using Response Nodes'",
                    name: 'generalNotice',
                    type: 'notice',
                    default: '',
                },
                {
                    displayName: 'Operation',
                    name: 'operation',
                    type: 'options',
                    default: 'send',
                    noDataExpression: true,
                    options: [
                        {
                            name: 'Send Message',
                            value: 'send',
                            action: 'Send a message',
                        },
                        {
                            name: 'Send and Wait for Response',
                            value: n8n_workflow_1.SEND_AND_WAIT_OPERATION,
                            action: 'Send message and wait for response',
                        },
                    ],
                    displayOptions: {
                        show: {
                            '@version': [{ _cnd: { gte: 1.1 } }],
                        },
                    },
                },
                {
                    displayName: 'Message',
                    name: 'message',
                    type: 'string',
                    default: '',
                    required: true,
                    typeOptions: {
                        rows: 4,
                    },
                },
                {
                    displayName: 'Wait for User Reply',
                    name: n8n_workflow_1.CHAT_WAIT_USER_REPLY,
                    type: 'boolean',
                    default: true,
                    noDataExpression: true,
                    displayOptions: {
                        show: {
                            '@version': [{ _cnd: { lt: 1.1 } }],
                        },
                    },
                },
                ...(0, util_1.getSendAndWaitPropertiesForChatNode)(),
                {
                    displayName: 'Options',
                    name: 'options',
                    type: 'collection',
                    placeholder: 'Add Option',
                    default: {},
                    displayOptions: {
                        hide: {
                            '@tool': [true],
                        },
                    },
                    options: [
                        {
                            displayName: 'Add Memory Input Connection',
                            name: 'memoryConnection',
                            type: 'boolean',
                            default: false,
                            displayOptions: {
                                hide: {
                                    '/responseType': ['approval'],
                                },
                            },
                        },
                        {
                            ...descriptions_1.limitWaitTimeOption,
                            displayOptions: {
                                show: {
                                    [`/${n8n_workflow_1.CHAT_WAIT_USER_REPLY}`]: [true],
                                },
                            },
                        },
                        {
                            ...descriptions_1.limitWaitTimeOption,
                            displayOptions: {
                                show: {
                                    '/operation': [n8n_workflow_1.SEND_AND_WAIT_OPERATION],
                                },
                            },
                        },
                        highlightedData_1.autoSaveHighlightedDataProperty,
                    ],
                },
                {
                    displayName: 'Options',
                    name: 'options',
                    type: 'collection',
                    placeholder: 'Add Option',
                    default: {},
                    options: [descriptions_1.limitWaitTimeOption, highlightedData_1.autoSaveHighlightedDataProperty],
                    displayOptions: {
                        show: {
                            '@tool': [true],
                            [`/${n8n_workflow_1.CHAT_WAIT_USER_REPLY}`]: [true],
                        },
                    },
                },
                {
                    displayName: 'Options',
                    name: 'options',
                    type: 'collection',
                    placeholder: 'Add Option',
                    default: {},
                    options: [descriptions_1.limitWaitTimeOption, highlightedData_1.autoSaveHighlightedDataProperty],
                    displayOptions: {
                        show: {
                            '@tool': [true],
                            '/operation': [n8n_workflow_1.SEND_AND_WAIT_OPERATION],
                        },
                    },
                },
            ],
        };
        this.webhook = utils_1.sendAndWaitWebhook;
    }
    async onMessage(context, data) {
        const options = context.getNodeParameter('options', 0, {});
        const nodeVersion = context.getNode().typeVersion;
        let waitForReply;
        if (nodeVersion >= 1.1) {
            const operation = context.getNodeParameter('operation', 0, 'sendMessage');
            waitForReply = operation === n8n_workflow_1.SEND_AND_WAIT_OPERATION;
        }
        else {
            waitForReply = context.getNodeParameter(n8n_workflow_1.CHAT_WAIT_USER_REPLY, 0, true);
        }
        if (!waitForReply) {
            if (nodeVersion >= 1.3)
                return [[data]];
            const inputData = context.getInputData();
            return [inputData];
        }
        const message = data.json?.chatInput;
        if (context.getNodeParameter('options.autoSaveHighlightedData', 0, true) !== false) {
            context.customData.set((0, n8n_workflow_1.getHighlightedInputKey)(context.getNode().name), message);
        }
        if (options.memoryConnection) {
            const memory = (await context.getInputConnectionData(n8n_workflow_1.NodeConnectionTypes.AiMemory, 0));
            if (memory && message) {
                await memory.chatHistory.addUserMessage(message);
            }
        }
        if (nodeVersion < 1.1) {
            return [[data]];
        }
        const responseType = context.getNodeParameter('responseType', 0, n8n_workflow_1.FREE_TEXT_CHAT_RESPONSE_TYPE);
        const isFreeText = responseType === n8n_workflow_1.FREE_TEXT_CHAT_RESPONSE_TYPE;
        if (nodeVersion <= 1.1) {
            return [
                [
                    {
                        ...data,
                        json: {
                            data: {
                                ...data.json,
                                approved: isFreeText ? undefined : false,
                            },
                        },
                    },
                ],
            ];
        }
        let nestedData = {};
        if (typeof data.json.data === 'object') {
            nestedData = {
                ...data.json.data,
            };
        }
        if (!isFreeText) {
            nestedData.approved = false;
        }
        return [
            [
                {
                    ...data,
                    json: {
                        ...data.json,
                        data: Object.keys(nestedData).length > 0 ? nestedData : undefined,
                    },
                },
            ],
        ];
    }
    async execute() {
        const connectedNodes = this.getParentNodes(this.getNode().name, {
            includeNodeParameters: true,
        });
        let chatTrigger = connectedNodes.find((node) => node.type === n8n_workflow_1.CHAT_TRIGGER_NODE_TYPE && !node.disabled);
        if (!chatTrigger) {
            try {
                chatTrigger = this.getChatTrigger();
            }
            catch (error) { }
        }
        if (!chatTrigger) {
            throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Workflow must be started from a chat trigger node');
        }
        const parameters = chatTrigger.parameters;
        if (parameters.mode === 'webhook') {
            throw new n8n_workflow_1.NodeOperationError(this.getNode(), '"Embedded chat" is not supported, change the "Mode" in the chat trigger node to the "Hosted Chat"');
        }
        if (parameters.options.responseMode !== 'responseNodes') {
            throw new n8n_workflow_1.NodeOperationError(this.getNode(), '"Response Mode" in the chat trigger node must be set to "Using Response Nodes"');
        }
        const message = (0, util_1.getChatMessage)(this);
        const options = this.getNodeParameter('options', 0, {});
        if (this.getNodeParameter('options.autoSaveHighlightedData', 0, true) !== false) {
            const responseText = typeof message === 'string' ? message : message.text;
            this.customData.set((0, n8n_workflow_1.getHighlightedResponseKey)(this.getNode().name), responseText);
        }
        if (options.memoryConnection) {
            const memory = (await this.getInputConnectionData(n8n_workflow_1.NodeConnectionTypes.AiMemory, 0));
            if (memory) {
                const text = typeof message === 'string' ? message : message.text;
                await memory.chatHistory.addAIMessage(text);
            }
        }
        const waitTill = (0, util_1.configureWaitTillDate)(this);
        await this.putExecutionToWait(waitTill);
        return [[{ json: {}, sendMessage: message }]];
    }
}
exports.Chat = Chat;
//# sourceMappingURL=Chat.node.js.map