"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AwsBedrockAgentProvider = void 0;
const node_crypto_1 = require("node:crypto");
const client_bedrock_agent_runtime_1 = require("@aws-sdk/client-bedrock-agent-runtime");
const logger_1 = __importDefault(require("../../logger"));
async function collectCompletionText(completion) {
    const decoder = new TextDecoder('utf-8');
    let out = '';
    for await (const event of completion) {
        client_bedrock_agent_runtime_1.ResponseStream.visit(event, {
            chunk: (c) => {
                if (c.bytes?.length) {
                    out += decoder.decode(c.bytes, { stream: true });
                }
            },
            trace: () => undefined,
            returnControl: () => {
                throw new Error('Bedrock Agent returned control to the caller (action group). This provider only supports agents that respond with streamed text chunks.');
            },
            internalServerException: (e) => {
                throw new Error(e.message ?? 'Bedrock internalServerException');
            },
            validationException: (e) => {
                throw new Error(e.message ?? 'Bedrock validationException');
            },
            resourceNotFoundException: (e) => {
                throw new Error(e.message ?? 'Bedrock resourceNotFoundException');
            },
            serviceQuotaExceededException: (e) => {
                throw new Error(e.message ?? 'Bedrock serviceQuotaExceededException');
            },
            throttlingException: (e) => {
                throw new Error(e.message ?? 'Bedrock throttlingException');
            },
            accessDeniedException: (e) => {
                throw new Error(e.message ?? 'Bedrock accessDeniedException');
            },
            conflictException: (e) => {
                throw new Error(e.message ?? 'Bedrock conflictException');
            },
            dependencyFailedException: (e) => {
                throw new Error(e.message ?? 'Bedrock dependencyFailedException');
            },
            badGatewayException: (e) => {
                throw new Error(e.message ?? 'Bedrock badGatewayException');
            },
            modelNotReadyException: (e) => {
                throw new Error(e.message ?? 'Bedrock modelNotReadyException');
            },
            files: () => undefined,
            _: (name, val) => {
                const msg = val && typeof val === 'object' && 'message' in val && typeof val.message === 'string'
                    ? val.message
                    : name;
                throw new Error(msg);
            },
        });
    }
    out += decoder.decode();
    return out.trim();
}
class AwsBedrockAgentProvider {
    constructor(config, options = {}) {
        this.config = options.config ?? {};
        this.providerConfig = config;
        if (!config.region?.trim()) {
            throw new Error('AWS Bedrock Agent: region is required');
        }
        if (!config.accessKeyId?.trim() || !config.secretAccessKey?.trim()) {
            throw new Error('AWS Bedrock Agent: accessKeyId and secretAccessKey are required');
        }
        if (!config.agentId?.trim() || !config.agentAliasId?.trim()) {
            throw new Error('AWS Bedrock Agent: agentId and agentAliasId are required');
        }
        this.client = new client_bedrock_agent_runtime_1.BedrockAgentRuntimeClient({
            region: config.region.trim(),
            credentials: {
                accessKeyId: config.accessKeyId.trim(),
                secretAccessKey: config.secretAccessKey.trim(),
                ...(config.sessionToken?.trim() ? { sessionToken: config.sessionToken.trim() } : {}),
            },
        });
    }
    id() {
        return `aws-bedrock-agent:${this.providerConfig.agentId}:${this.providerConfig.agentAliasId}`;
    }
    async callApi(prompt, _context) {
        const sessionId = (0, node_crypto_1.randomUUID)();
        try {
            logger_1.default.debug(`[AWS Bedrock Agent]: InvokeAgent sessionId=${sessionId}`);
            const command = new client_bedrock_agent_runtime_1.InvokeAgentCommand({
                agentId: this.providerConfig.agentId.trim(),
                agentAliasId: this.providerConfig.agentAliasId.trim(),
                sessionId,
                inputText: prompt,
                enableTrace: this.providerConfig.enableTrace === true,
            });
            const response = await this.client.send(command);
            const completion = response.completion;
            if (!completion) {
                return {
                    output: '',
                    metadata: {
                        sessionId,
                        responseSessionId: response.sessionId,
                        contentType: response.contentType,
                    },
                };
            }
            const output = await collectCompletionText(completion);
            return {
                output,
                metadata: {
                    sessionId,
                    responseSessionId: response.sessionId,
                    contentType: response.contentType,
                },
            };
        }
        catch (err) {
            logger_1.default.error(`[AWS Bedrock Agent]: ${String(err)}`);
            return {
                error: `AWS Bedrock Agent error: ${err instanceof Error ? err.message : String(err)}`,
                metadata: { sessionId },
            };
        }
    }
}
exports.AwsBedrockAgentProvider = AwsBedrockAgentProvider;
//# sourceMappingURL=aws-bedrock-agent.js.map