"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LmChatAwsBedrock = void 0;
const client_bedrock_runtime_1 = require("@aws-sdk/client-bedrock-runtime");
const aws_1 = require("@langchain/aws");
const ai_utilities_1 = require("@n8n/ai-utilities");
const node_http_handler_1 = require("@smithy/node-http-handler");
const n8n_workflow_1 = require("n8n-workflow");
class LmChatAwsBedrock {
    constructor() {
        this.description = {
            displayName: 'AWS Bedrock Chat Model',
            name: 'lmChatAwsBedrock',
            icon: 'file:bedrock.svg',
            group: ['transform'],
            version: [1, 1.1],
            description: 'Language Model AWS Bedrock',
            defaults: {
                name: 'AWS Bedrock Chat Model',
            },
            codex: {
                categories: ['AI'],
                subcategories: {
                    AI: ['Language Models', 'Root Nodes'],
                    'Language Models': ['Chat Models (Recommended)'],
                },
                resources: {
                    primaryDocumentation: [
                        {
                            url: 'https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.lmchatawsbedrock/',
                        },
                    ],
                },
            },
            inputs: [],
            outputs: [n8n_workflow_1.NodeConnectionTypes.AiLanguageModel],
            outputNames: ['Model'],
            credentials: [
                {
                    name: 'aws',
                    required: true,
                },
            ],
            requestDefaults: {
                ignoreHttpStatusErrors: true,
                baseURL: '=https://bedrock.{{$credentials?.region ?? "eu-central-1"}}.amazonaws.com',
            },
            properties: [
                (0, ai_utilities_1.getConnectionHintNoticeField)([n8n_workflow_1.NodeConnectionTypes.AiChain, n8n_workflow_1.NodeConnectionTypes.AiChain]),
                {
                    displayName: 'Model Source',
                    name: 'modelSource',
                    type: 'options',
                    displayOptions: {
                        show: {
                            '@version': [{ _cnd: { gte: 1.1 } }],
                        },
                    },
                    options: [
                        {
                            name: 'On-Demand Models',
                            value: 'onDemand',
                            description: 'Standard foundation models with on-demand pricing',
                        },
                        {
                            name: 'Inference Profiles',
                            value: 'inferenceProfile',
                            description: 'Cross-region inference profiles (required for models like Claude Sonnet 4 and others)',
                        },
                    ],
                    default: 'onDemand',
                    description: 'Choose between on-demand foundation models or inference profiles',
                },
                {
                    displayName: 'Model',
                    name: 'model',
                    type: 'options',
                    allowArbitraryValues: true,
                    description: 'The model which will generate the completion. <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/foundation-models.html">Learn more</a>.',
                    displayOptions: {
                        hide: {
                            modelSource: ['inferenceProfile'],
                        },
                    },
                    typeOptions: {
                        loadOptionsDependsOn: ['modelSource'],
                        loadOptions: {
                            routing: {
                                request: {
                                    method: 'GET',
                                    url: '/foundation-models?&byOutputModality=TEXT&byInferenceType=ON_DEMAND',
                                },
                                output: {
                                    postReceive: [
                                        {
                                            type: 'rootProperty',
                                            properties: {
                                                property: 'modelSummaries',
                                            },
                                        },
                                        {
                                            type: 'setKeyValue',
                                            properties: {
                                                name: '={{$responseItem.modelName}}',
                                                description: '={{$responseItem.modelArn}}',
                                                value: '={{$responseItem.modelId}}',
                                            },
                                        },
                                        {
                                            type: 'sort',
                                            properties: {
                                                key: 'name',
                                            },
                                        },
                                    ],
                                },
                            },
                        },
                    },
                    routing: {
                        send: {
                            type: 'body',
                            property: 'model',
                        },
                    },
                    default: '',
                    builderHint: {
                        propertyHint: 'Default to the latest Claude Sonnet on Bedrock (anthropic.claude-sonnet-4-6 family). For Claude Sonnet 4+, switch Model Source to Inference Profiles. Avoid claude-sonnet-4-5, claude-3.x, and non-Claude legacy models unless requested.',
                    },
                },
                {
                    displayName: 'Model',
                    name: 'model',
                    type: 'options',
                    allowArbitraryValues: true,
                    description: 'The inference profile which will generate the completion. <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-use.html">Learn more</a>.',
                    displayOptions: {
                        show: {
                            modelSource: ['inferenceProfile'],
                        },
                    },
                    typeOptions: {
                        loadOptionsDependsOn: ['modelSource'],
                        loadOptions: {
                            routing: {
                                request: {
                                    method: 'GET',
                                    url: '/inference-profiles?maxResults=1000',
                                },
                                output: {
                                    postReceive: [
                                        {
                                            type: 'rootProperty',
                                            properties: {
                                                property: 'inferenceProfileSummaries',
                                            },
                                        },
                                        {
                                            type: 'setKeyValue',
                                            properties: {
                                                name: '={{$responseItem.inferenceProfileName}}',
                                                description: '={{$responseItem.description || $responseItem.inferenceProfileArn}}',
                                                value: '={{$responseItem.inferenceProfileId}}',
                                            },
                                        },
                                        {
                                            type: 'sort',
                                            properties: {
                                                key: 'name',
                                            },
                                        },
                                    ],
                                },
                            },
                        },
                    },
                    routing: {
                        send: {
                            type: 'body',
                            property: 'model',
                        },
                    },
                    default: '',
                    builderHint: {
                        propertyHint: 'Default to the latest Claude Sonnet inference profile (anthropic.claude-sonnet-4-6 family). Avoid claude-sonnet-4-5 and claude-3.x profiles unless specifically requested.',
                    },
                },
                {
                    displayName: 'Options',
                    name: 'options',
                    placeholder: 'Add Option',
                    description: 'Additional options to add',
                    type: 'collection',
                    default: {},
                    options: [
                        {
                            displayName: 'Maximum Number of Tokens',
                            name: 'maxTokensToSample',
                            default: 2000,
                            description: 'The maximum number of tokens to generate in the completion',
                            type: 'number',
                        },
                        {
                            displayName: 'Sampling Temperature',
                            name: 'temperature',
                            default: 0.7,
                            typeOptions: { maxValue: 1, minValue: 0, numberPrecision: 1 },
                            description: 'Controls randomness: Lowering results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive.',
                            type: 'number',
                        },
                    ],
                },
            ],
        };
    }
    async supplyData(itemIndex) {
        const credentials = await this.getCredentials('aws');
        const modelName = this.getNodeParameter('model', itemIndex);
        const options = this.getNodeParameter('options', itemIndex, {});
        let region = credentials.region;
        const arnMatch = modelName.match(/^arn:aws:bedrock:([a-z0-9-]+):/);
        if (arnMatch) {
            region = arnMatch[1];
        }
        const proxyAgent = (0, ai_utilities_1.getNodeProxyAgent)();
        const clientConfig = {
            region,
            credentials: {
                secretAccessKey: credentials.secretAccessKey,
                accessKeyId: credentials.accessKeyId,
                ...(credentials.sessionToken && { sessionToken: credentials.sessionToken }),
            },
        };
        if (proxyAgent) {
            clientConfig.requestHandler = new node_http_handler_1.NodeHttpHandler({
                httpAgent: proxyAgent,
                httpsAgent: proxyAgent,
            });
        }
        const client = new client_bedrock_runtime_1.BedrockRuntimeClient(clientConfig);
        const model = new aws_1.ChatBedrockConverse({
            client,
            model: modelName,
            region,
            temperature: options.temperature,
            maxTokens: options.maxTokensToSample,
            callbacks: [new ai_utilities_1.N8nLlmTracing(this)],
            onFailedAttempt: (0, ai_utilities_1.makeN8nLlmFailedAttemptHandler)(this),
        });
        return {
            response: model,
        };
    }
}
exports.LmChatAwsBedrock = LmChatAwsBedrock;
//# sourceMappingURL=LmChatAwsBedrock.node.js.map