const require_rolldown_runtime = require("./rolldown-runtime-D_mwlA32.cjs");
const require_logger = require("./logger-DuG3amVa.cjs");
const require_fetch = require("./fetch-Hdu2Q-w3.cjs");
const require_esm = require("./esm-4Cu04ouJ.cjs");
const require_util = require("./util-M3cOWPu3.cjs");
const require_client = require("./client-4POX6S5z.cjs");
const require_util$1 = require("./util-DtSnbKEe.cjs");
const require_transform = require("./transform-6Fcy98Wj.cjs");
let path = require("path");
path = require_rolldown_runtime.__toESM(path, 1);
//#region src/providers/google/base.ts
/**
* Base class for Google AI providers.
*
* This abstract class provides shared functionality for both Google AI Studio
* and Vertex AI providers, including:
* - MCP (Model Context Protocol) client integration
* - Function callback execution
* - Tool normalization
* - Resource cleanup
*
* Subclasses must implement:
* - getApiEndpoint(): Returns the API endpoint URL
* - getAuthHeaders(): Returns authentication headers
* - callApi(): The main API call implementation
*/
/**
* Abstract base class for Google AI providers.
*
* Provides shared functionality for Google AI Studio and Vertex AI,
* with abstract methods for endpoint and authentication that differ
* between the two services.
*/
var GoogleGenericProvider = class {
	/** The model name (e.g., 'gemini-2.5-pro') */
	modelName;
	/** Provider configuration */
	config;
	/** Environment variable overrides */
	env;
	/** Whether this provider is in Vertex AI mode */
	isVertexMode;
	/** MCP client for tool integration */
	mcpClient = null;
	/** Promise that resolves when MCP initialization is complete */
	initializationPromise = null;
	/** Cache of loaded function callbacks */
	loadedFunctionCallbacks = {};
	/** Custom provider ID function */
	customId;
	constructor(modelName, options = {}) {
		const { config, id, env } = options;
		this.env = env;
		this.modelName = modelName;
		this.config = config || {};
		this.isVertexMode = require_util$1.GoogleAuthManager.determineVertexMode(this.config, this.env);
		require_util$1.GoogleAuthManager.validateAndWarn({
			apiKey: this.config.apiKey,
			credentials: this.config.credentials,
			projectId: this.config.projectId,
			region: this.config.region,
			vertexai: this.isVertexMode,
			googleAuthOptions: this.config.googleAuthOptions,
			keyFilename: this.config.keyFilename,
			scopes: this.config.scopes,
			strictMutualExclusivity: this.config.strictMutualExclusivity
		}, this.env);
		if (id) this.customId = () => id;
		if (this.config.mcp?.enabled) this.initializationPromise = this.initializeMCP();
	}
	validateFunctionToolCall(output, vars) {
		require_util$1.validateFunctionCall(output, this.config.tools, vars);
	}
	/**
	* Get the provider ID string.
	* Format: 'google:{model}' for AI Studio, 'vertex:{model}' for Vertex AI
	*/
	id() {
		if (this.customId) return this.customId();
		return this.isVertexMode ? `vertex:${this.modelName}` : `google:${this.modelName}`;
	}
	/**
	* Get a string representation of the provider.
	*/
	toString() {
		return `[Google ${this.isVertexMode ? "Vertex AI" : "Google AI Studio"} Provider ${this.modelName}]`;
	}
	/**
	* Get the API key for this provider.
	* Applies Nunjucks rendering to support template variables.
	*
	* @returns The API key or undefined
	*/
	requiresApiKey() {
		return !this.isVertexMode;
	}
	getApiKey() {
		const { apiKey } = require_util$1.GoogleAuthManager.getApiKey(this.config, this.env, this.isVertexMode);
		if (apiKey) return require_util.getNunjucksEngine().renderString(apiKey, {});
	}
	/**
	* Get the region for Vertex AI.
	*
	* @returns The region (default: 'global' for OAuth, 'us-central1' for API key)
	*/
	getRegion() {
		const hasApiKey = Boolean(this.getApiKey());
		return require_util$1.GoogleAuthManager.resolveRegion(this.config, this.env, hasApiKey);
	}
	/**
	* Get the project ID for Vertex AI.
	*
	* @returns Promise resolving to the project ID
	*/
	async getProjectId() {
		return require_util$1.GoogleAuthManager.resolveProjectId({
			projectId: this.config.projectId,
			credentials: this.config.credentials,
			googleAuthOptions: this.config.googleAuthOptions,
			keyFilename: this.config.keyFilename,
			scopes: this.config.scopes
		}, this.env);
	}
	/**
	* Initialize the MCP client for tool integration.
	*/
	async initializeMCP() {
		if (!this.config.mcp) return;
		this.mcpClient = new require_client.MCPClient(this.config.mcp);
		await this.mcpClient.initialize();
	}
	/**
	* Get all tools for the request, combining MCP tools and config tools.
	*
	* @param context - Call context with variables
	* @returns Array of Google-format tools
	*/
	async getAllTools(context, options = {}) {
		const mcpTools = this.mcpClient ? require_transform.transformMCPToolsToGoogle(this.mcpClient.getAllTools()) : [];
		const configTools = (context?.prompt?.config)?.tools ?? this.config.tools;
		const requestTools = options.skipExecutableToolFiles ? require_util$1.stripExecutableToolFileReferences(configTools, context?.vars) : configTools;
		const loadedTools = requestTools ? await require_util.maybeLoadToolsFromExternalFile(requestTools, context?.vars) : [];
		const normalizedTools = require_util$1.normalizeTools(Array.isArray(loadedTools) ? require_fetch.transformTools(loadedTools, "google") : loadedTools ? [loadedTools] : []);
		return [...mcpTools, ...normalizedTools];
	}
	/**
	* Load a function from an external file.
	*
	* @param fileRef - File reference in format 'file://path/to/file:functionName'
	* @returns The loaded function
	*/
	async loadExternalFunction(fileRef) {
		const { filePath, functionName } = require_util.parseFileUrl(fileRef);
		try {
			const basePath = require_logger.state.basePath || process.cwd();
			const resolvedPath = path.default.resolve(basePath, filePath);
			const normalizedBase = path.default.resolve(basePath);
			const normalizedResolved = path.default.resolve(resolvedPath);
			const relativePath = path.default.relative(normalizedBase, normalizedResolved);
			if (relativePath.startsWith("..") || path.default.isAbsolute(relativePath)) throw new Error(`Path traversal detected: '${filePath}' resolves outside the base directory. Resolved path '${normalizedResolved}' is not within '${normalizedBase}'.`);
			require_logger.logger.debug(`Loading function from ${resolvedPath}${functionName ? `:${functionName}` : ""}`);
			const requiredModule = await require_esm.importModule(resolvedPath, functionName);
			if (typeof requiredModule === "function") return requiredModule;
			else if (requiredModule && typeof requiredModule === "object" && functionName && functionName in requiredModule) {
				const fn = requiredModule[functionName];
				if (typeof fn === "function") return fn;
			}
			throw new Error(`Function callback malformed: ${filePath} must export ${functionName ? `a named function '${functionName}'` : "a function or have a default export as a function"}`);
		} catch (error) {
			throw new Error(`Error loading function from ${filePath}: ${error.message || String(error)}`);
		}
	}
	/**
	* Execute a function callback with proper error handling.
	*
	* @param functionName - Name of the function to execute
	* @param args - JSON string of function arguments
	* @param config - Config containing function callbacks
	* @returns The function result
	*/
	async executeFunctionCallback(functionName, args, config) {
		try {
			let callback = this.loadedFunctionCallbacks[functionName];
			if (!callback) {
				const callbackRef = config.functionToolCallbacks?.[functionName];
				if (callbackRef && typeof callbackRef === "string") {
					const callbackStr = callbackRef;
					if (callbackStr.startsWith("file://")) callback = await this.loadExternalFunction(callbackStr);
					else {
						require_logger.logger.warn(`[GoogleProvider] Inline function string for '${functionName}' is deprecated. Use 'file://path/to/module.js:functionName' for better security.`);
						try {
							callback = new Function("return " + callbackStr)();
							if (typeof callback !== "function") throw new Error(`Expression did not return a function`);
						} catch (err) {
							throw new Error(`Failed to parse inline function for '${functionName}': ${err}. Consider using 'file://' prefix to reference an external file.`);
						}
					}
					this.loadedFunctionCallbacks[functionName] = callback;
				} else if (typeof callbackRef === "function") {
					callback = callbackRef;
					this.loadedFunctionCallbacks[functionName] = callback;
				}
			}
			if (!callback) throw new Error(`No callback found for function '${functionName}'`);
			require_logger.logger.debug(`Executing function '${functionName}' with args: ${args}`);
			return await callback(args);
		} catch (error) {
			require_logger.logger.error(`Error executing function '${functionName}': ${error.message || String(error)}`);
			throw error;
		}
	}
	/**
	* Clean up resources (MCP client, etc.).
	* Should be called when the provider is no longer needed.
	*/
	async cleanup() {
		if (this.mcpClient) {
			if (this.initializationPromise != null) await this.initializationPromise;
			await this.mcpClient.cleanup();
			this.mcpClient = null;
		}
	}
	/**
	* Get the request timeout in milliseconds.
	*/
	getTimeout() {
		return this.config.timeoutMs || require_fetch.getRequestTimeoutMs();
	}
};
//#endregion
Object.defineProperty(exports, "GoogleGenericProvider", {
	enumerable: true,
	get: function() {
		return GoogleGenericProvider;
	}
});

//# sourceMappingURL=base-Drq4pKbj.cjs.map