const require_logger = require('./logger-q_xXORhb.cjs');
require('./fetch--6dTWCD4.cjs');
const require_cache = require('./cache-BrwLt6g7.cjs');
require('./accounts-DswJu0kA.cjs');
const require_telemetry = require('./telemetry-BObV6Rt3.cjs');
const require_base = require('./base-BQtJ-tFs.cjs');

//#region src/providers/bedrock/agents.ts
/**
* AWS Bedrock Agents provider for invoking deployed AI agents.
* Supports all Bedrock Agents features including memory, knowledge bases, action groups,
* guardrails, and session management.
*
* @example Basic usage
* ```yaml
* providers:
*   - bedrock-agent:AGENT_ID
*     config:
*       agentAliasId: PROD_ALIAS
*       region: us-east-1
* ```
*
* @example With memory and session
* ```yaml
* providers:
*   - bedrock-agent:AGENT_ID
*     config:
*       agentAliasId: PROD_ALIAS
*       sessionId: user-session-123
*       memoryId: LONG_TERM_MEMORY
*       enableTrace: true
* ```
*
* @example With guardrails and inference config
* ```yaml
* providers:
*   - bedrock-agent:AGENT_ID
*     config:
*       agentAliasId: PROD_ALIAS
*       guardrailConfiguration:
*         guardrailId: GUARDRAIL_ID
*         guardrailVersion: "1"
*       temperature: 0.7  # Can be specified at root level for convenience
*         topP: 0.9
*         maximumLength: 2048
* ```
*/
var AwsBedrockAgentsProvider = class extends require_base.AwsBedrockGenericProvider {
	agentRuntimeClient;
	config;
	constructor(agentId, options = {}) {
		super(agentId, options);
		if (!agentId && !options.config?.agentId) throw new Error("Agent ID is required. Provide it in the provider path (bedrock-agent:AGENT_ID) or config.");
		this.config = {
			...options.config,
			agentId: options.config?.agentId || agentId
		};
		require_telemetry.telemetry_default.record("feature_used", {
			feature: "bedrock-agents",
			provider: "bedrock"
		});
	}
	id() {
		return `bedrock-agent:${this.config.agentId}`;
	}
	toString() {
		return `[AWS Bedrock Agents Provider ${this.config.agentId}]`;
	}
	/**
	* Get or create the Bedrock Agent Runtime client
	*/
	async getAgentRuntimeClient() {
		if (!this.agentRuntimeClient) {
			let handler;
			if (require_logger.getEnvString("HTTP_PROXY") || require_logger.getEnvString("HTTPS_PROXY")) try {
				const { NodeHttpHandler } = await import("@smithy/node-http-handler");
				const { ProxyAgent } = await import("proxy-agent");
				handler = new NodeHttpHandler({ httpsAgent: new ProxyAgent() });
			} catch {
				throw new Error("The @smithy/node-http-handler package is required for proxy support. Please install it.");
			}
			try {
				const { BedrockAgentRuntimeClient } = await import("@aws-sdk/client-bedrock-agent-runtime");
				const credentials = await this.getCredentials();
				this.agentRuntimeClient = new BedrockAgentRuntimeClient({
					region: this.getRegion(),
					maxAttempts: require_logger.getEnvInt("AWS_BEDROCK_MAX_RETRIES", 10),
					retryMode: "adaptive",
					...credentials ? { credentials } : {},
					...handler ? { requestHandler: handler } : {}
				});
			} catch (err) {
				require_logger.logger_default.error(`Error creating BedrockAgentRuntimeClient: ${err}`);
				throw new Error("The @aws-sdk/client-bedrock-agent-runtime package is required. Please install it: npm install @aws-sdk/client-bedrock-agent-runtime");
			}
		}
		return this.agentRuntimeClient;
	}
	/**
	* Build the session state from configuration
	*/
	buildSessionState() {
		if (!this.config.sessionState) return;
		const sessionState = {
			sessionAttributes: this.config.sessionState.sessionAttributes,
			promptSessionAttributes: this.config.sessionState.promptSessionAttributes,
			invocationId: this.config.sessionState.invocationId
		};
		if (this.config.sessionState.returnControlInvocationResults) sessionState.returnControlInvocationResults = this.config.sessionState.returnControlInvocationResults;
		return sessionState;
	}
	/**
	* Build inference configuration from both root-level and nested parameters
	* Root-level parameters take precedence over nested ones for convenience
	*/
	buildInferenceConfig() {
		const hasRootConfig = this.config.temperature !== void 0 || this.config.topP !== void 0 || this.config.topK !== void 0 || this.config.maximumLength !== void 0 || this.config.stopSequences !== void 0;
		const hasNestedConfig = this.config.inferenceConfig !== void 0;
		if (!hasRootConfig && !hasNestedConfig) return;
		const inferenceConfig = {};
		if (this.config.inferenceConfig) {
			if (this.config.inferenceConfig.maximumLength !== void 0) inferenceConfig.maximumLength = this.config.inferenceConfig.maximumLength;
			if (this.config.inferenceConfig.stopSequences !== void 0) inferenceConfig.stopSequences = this.config.inferenceConfig.stopSequences;
			if (this.config.inferenceConfig.temperature !== void 0) inferenceConfig.temperature = this.config.inferenceConfig.temperature;
			if (this.config.inferenceConfig.topP !== void 0) inferenceConfig.topP = this.config.inferenceConfig.topP;
			if (this.config.inferenceConfig.topK !== void 0) inferenceConfig.topK = this.config.inferenceConfig.topK;
		}
		if (this.config.temperature !== void 0) inferenceConfig.temperature = this.config.temperature;
		if (this.config.topP !== void 0) inferenceConfig.topP = this.config.topP;
		if (this.config.topK !== void 0) inferenceConfig.topK = this.config.topK;
		if (this.config.maximumLength !== void 0) inferenceConfig.maximumLength = this.config.maximumLength;
		if (this.config.stopSequences !== void 0) inferenceConfig.stopSequences = this.config.stopSequences;
		return inferenceConfig;
	}
	/**
	* Process the streaming response from the agent
	*/
	async processResponse(response) {
		let output = "";
		const traces = [];
		if (response.completion) {
			const decoder = new TextDecoder();
			try {
				for await (const event of response.completion) {
					if (event.chunk?.bytes) output += decoder.decode(event.chunk.bytes, { stream: true });
					if (this.config.enableTrace && event.trace) traces.push(event.trace);
				}
				output += decoder.decode();
			} catch (error) {
				require_logger.logger_default.error(`Error processing agent response stream: ${error}`);
				throw error;
			}
		}
		return {
			output,
			trace: traces.length > 0 ? traces : void 0,
			sessionId: response.sessionId
		};
	}
	/**
	* Invoke the agent with the given prompt
	*/
	async callApi(prompt) {
		if (!this.config.agentAliasId) return { error: "Agent Alias ID is required. Set agentAliasId in the provider config." };
		const client = await this.getAgentRuntimeClient();
		const sessionId = this.config.sessionId || (typeof crypto !== "undefined" && "randomUUID" in crypto ? `session-${crypto.randomUUID()}` : `session-${Date.now()}-${process.hrtime.bigint().toString(36)}`);
		const input = {
			agentId: this.config.agentId,
			agentAliasId: this.config.agentAliasId,
			sessionId,
			inputText: prompt,
			enableTrace: this.config.enableTrace,
			endSession: this.config.endSession,
			sessionState: this.buildSessionState(),
			memoryId: this.config.memoryId,
			...this.buildInferenceConfig() && { inferenceConfig: this.buildInferenceConfig() },
			...this.config.guardrailConfiguration && { guardrailConfiguration: this.config.guardrailConfiguration },
			...this.config.promptOverrideConfiguration && { promptOverrideConfiguration: this.config.promptOverrideConfiguration },
			...this.config.knowledgeBaseConfigurations && { knowledgeBaseConfigurations: this.config.knowledgeBaseConfigurations },
			...this.config.actionGroups && { actionGroups: this.config.actionGroups },
			...this.config.inputDataConfig && { inputDataConfig: this.config.inputDataConfig }
		};
		require_logger.logger_default.debug(`Invoking Bedrock agent ${this.config.agentId} with session ${sessionId}`);
		const cache = await require_cache.getCache();
		const cacheKey = `bedrock-agent:${this.config.agentId}:${JSON.stringify({
			prompt,
			inferenceConfig: this.buildInferenceConfig(),
			knowledgeBaseConfigurations: this.config.knowledgeBaseConfigurations
		})}`;
		if (require_cache.isCacheEnabled()) {
			const cached = await cache.get(cacheKey);
			if (cached) {
				require_logger.logger_default.debug("Returning cached Bedrock Agents response");
				try {
					const parsed = JSON.parse(cached);
					if (parsed && typeof parsed === "object") return {
						...parsed,
						cached: true
					};
				} catch {
					require_logger.logger_default.warn("Failed to parse cached Bedrock Agents response, ignoring cache");
				}
			}
		}
		try {
			const { InvokeAgentCommand } = await import("@aws-sdk/client-bedrock-agent-runtime");
			const response = await client.send(new InvokeAgentCommand(input));
			const { output, trace, sessionId: responseSessionId } = await this.processResponse(response);
			const result = {
				output,
				metadata: {
					...responseSessionId && { sessionId: responseSessionId },
					...trace && { trace },
					...this.config.memoryId && { memoryId: this.config.memoryId },
					...this.config.guardrailConfiguration && { guardrails: {
						applied: true,
						guardrailId: this.config.guardrailConfiguration.guardrailId,
						guardrailVersion: this.config.guardrailConfiguration.guardrailVersion
					} }
				}
			};
			if (require_cache.isCacheEnabled()) try {
				await cache.set(cacheKey, JSON.stringify(result));
			} catch (err) {
				require_logger.logger_default.error(`Failed to cache response: ${err}`);
			}
			return result;
		} catch (error) {
			require_logger.logger_default.error(`Bedrock Agents invocation failed: ${error}`);
			if (error.name === "ResourceNotFoundException") return { error: `Agent or alias not found. Verify agentId: ${this.config.agentId} and agentAliasId: ${this.config.agentAliasId}` };
			else if (error.name === "AccessDeniedException") return { error: "Access denied. Check IAM permissions for bedrock:InvokeAgent" };
			else if (error.name === "ValidationException") return { error: `Invalid configuration: ${error.message}` };
			else if (error.name === "ThrottlingException") return { error: "Rate limit exceeded. Please retry later." };
			return { error: `Failed to invoke agent: ${error.message || String(error)}` };
		}
	}
};

//#endregion
exports.AwsBedrockAgentsProvider = AwsBedrockAgentsProvider;
//# sourceMappingURL=agents-0FTECwbV.cjs.map