import { b as getEnvString, d as getAjv, i as logger_default } from "./logger-BudIH0qK.js";
import { _ as renderVarsInObject, b as getNunjucksEngine, l as maybeLoadFromExternalFile } from "./util-BaEBV99n.js";
import { g as parseChatPrompt, t as fetchWithProxy } from "./fetch-D70iPJNm.js";
import Clone from "rfdc";
import { z } from "zod";
import crypto from "crypto";

//#region src/util/oauth.ts
/**
* Buffer time before token expiry to trigger proactive refresh (60 seconds)
*/
const TOKEN_REFRESH_BUFFER_MS = 6e4;
/**
* Fetch an OAuth token from a token endpoint.
* Handles both client_credentials and password grant types.
*
* @param config - OAuth configuration with rendered/resolved values
* @returns Token and expiration timestamp
*/
async function fetchOAuthToken(config) {
	const now = Date.now();
	logger_default.debug("[OAuth] Fetching new token");
	const tokenRequestBody = new URLSearchParams();
	tokenRequestBody.append("grant_type", config.grantType);
	if (config.clientId) tokenRequestBody.append("client_id", config.clientId);
	if (config.clientSecret) tokenRequestBody.append("client_secret", config.clientSecret);
	if (config.grantType === "password") {
		if (config.username) tokenRequestBody.append("username", config.username);
		if (config.password) tokenRequestBody.append("password", config.password);
	}
	if (config.scopes && config.scopes.length > 0) tokenRequestBody.append("scope", config.scopes.join(" "));
	const response = await fetchWithProxy(config.tokenUrl, {
		method: "POST",
		headers: { "Content-Type": "application/x-www-form-urlencoded" },
		body: tokenRequestBody.toString()
	});
	if (!response.ok) {
		const errorText = await response.text();
		throw new Error(`OAuth token request failed with status ${response.status} ${response.statusText}: ${errorText}`);
	}
	const tokenData = await response.json();
	if (!tokenData.access_token) throw new Error("OAuth token response missing access_token");
	const expiresAt = now + (tokenData.expires_in || 3600) * 1e3;
	logger_default.debug("[OAuth] Successfully fetched token");
	return {
		accessToken: tokenData.access_token,
		expiresAt
	};
}

//#endregion
//#region src/providers/mcp/util.ts
/**
* Render environment variables in server config auth fields.
* Supports {{VAR_NAME}} syntax for variable substitution.
*/
function renderAuthVars(server, vars) {
	if (!server.auth) return server;
	const renderVars = vars || process.env;
	return {
		...server,
		auth: renderVarsInObject(server.auth, renderVars)
	};
}
const oauthTokenCache = /* @__PURE__ */ new Map();
/**
* Get the cache key for an OAuth config
*/
function getOAuthCacheKey(auth) {
	return `${auth.tokenUrl}:${auth.grantType}:${"clientId" in auth ? auth.clientId : ""}:${"username" in auth ? auth.username : ""}`;
}
const tokenEndpointCache = /* @__PURE__ */ new Map();
/**
* Discover the OAuth token endpoint from the server's well-known metadata.
* Follows RFC 8414 OAuth 2.0 Authorization Server Metadata.
* Only requires token_endpoint from the response (unlike SDK which requires authorization_endpoint).
*/
async function discoverTokenEndpoint(serverUrl) {
	const cached = tokenEndpointCache.get(serverUrl);
	if (cached) {
		logger_default.debug(`[MCP Auth] Using cached token endpoint for ${serverUrl}`);
		return cached;
	}
	const url = new URL(serverUrl);
	const baseUrl = `${url.protocol}//${url.host}`;
	const discoveryUrls = [];
	if (url.pathname && url.pathname !== "/") {
		discoveryUrls.push(`${baseUrl}${url.pathname}/.well-known/oauth-authorization-server`);
		discoveryUrls.push(`${baseUrl}/.well-known/oauth-authorization-server${url.pathname}`);
	}
	discoveryUrls.push(`${baseUrl}/.well-known/oauth-authorization-server`);
	for (const discoveryUrl of discoveryUrls) try {
		logger_default.debug(`[MCP Auth] Trying OAuth discovery at ${discoveryUrl}`);
		const response = await fetchWithProxy(discoveryUrl);
		if (!response.ok) {
			logger_default.debug(`[MCP Auth] Discovery failed at ${discoveryUrl}: ${response.status}`);
			continue;
		}
		const metadata = await response.json();
		if (metadata.token_endpoint) {
			logger_default.debug(`[MCP Auth] Discovered token endpoint: ${metadata.token_endpoint}`);
			tokenEndpointCache.set(serverUrl, metadata.token_endpoint);
			return metadata.token_endpoint;
		}
		logger_default.debug(`[MCP Auth] No token_endpoint in metadata from ${discoveryUrl}`);
	} catch (error) {
		logger_default.debug(`[MCP Auth] Error fetching ${discoveryUrl}: ${error}`);
	}
	throw new Error(`Failed to discover OAuth token endpoint for ${serverUrl}. Please configure tokenUrl explicitly in the auth config.`);
}
/**
* Get OAuth token with expiration info, fetching a new one if needed.
* If tokenUrl is not configured, attempts OAuth discovery to find the token endpoint.
* Caches tokens and returns cached version if still valid.
*/
async function getOAuthTokenWithExpiry(auth, serverUrl) {
	let tokenUrl = auth.tokenUrl;
	if (!tokenUrl) {
		if (!serverUrl) throw new Error("Either tokenUrl or serverUrl is required for OAuth token fetching");
		tokenUrl = await discoverTokenEndpoint(serverUrl);
	}
	const cacheKey = getOAuthCacheKey(auth);
	const cached = oauthTokenCache.get(cacheKey);
	if (cached && Date.now() + TOKEN_REFRESH_BUFFER_MS < cached.expiresAt) {
		logger_default.debug("[MCP Auth] Using cached OAuth token");
		return {
			accessToken: cached.accessToken,
			expiresAt: cached.expiresAt
		};
	}
	const result = await fetchOAuthToken({
		tokenUrl,
		grantType: auth.grantType,
		clientId: auth.clientId,
		clientSecret: auth.clientSecret,
		username: "username" in auth ? auth.username : void 0,
		password: "password" in auth ? auth.password : void 0,
		scopes: auth.scopes
	});
	oauthTokenCache.set(cacheKey, {
		accessToken: result.accessToken,
		expiresAt: result.expiresAt
	});
	logger_default.debug("[MCP Auth] Cached OAuth token");
	return result;
}
/**
* Get OAuth token, fetching a new one if needed.
* Requires tokenUrl to be configured - throws if not provided.
*/
async function getOAuthToken(auth) {
	return (await getOAuthTokenWithExpiry(auth)).accessToken;
}
/**
* Get authentication headers for an MCP server configuration.
* Returns headers for bearer, basic, and api_key (header placement) auth types.
* For OAuth, use getOAuthToken() first then pass the token.
* For api_key with query placement, use getAuthQueryParams() instead.
*/
function getAuthHeaders(server, oauthToken) {
	if (!server.auth) return {};
	switch (server.auth.type) {
		case "bearer":
			if (!server.auth.token) return {};
			return { Authorization: `Bearer ${server.auth.token}` };
		case "basic": return { Authorization: `Basic ${Buffer.from(`${server.auth.username}:${server.auth.password}`).toString("base64")}` };
		case "api_key": {
			const apiKeyAuth = server.auth;
			const value = apiKeyAuth.value || apiKeyAuth.api_key;
			if (!value) return {};
			if ((apiKeyAuth.placement || "header") === "header") return { [apiKeyAuth.keyName || "X-API-Key"]: value };
			return {};
		}
		case "oauth":
			if (oauthToken) return { Authorization: `Bearer ${oauthToken}` };
			logger_default.warn("[MCP Auth] OAuth auth configured but no token provided");
			return {};
		default: return {};
	}
}
/**
* Get authentication query parameters for api_key auth with query placement.
* Returns an object with key-value pairs to be added to the URL.
*/
function getAuthQueryParams(server) {
	if (!server.auth || server.auth.type !== "api_key") return {};
	const apiKeyAuth = server.auth;
	const value = apiKeyAuth.value || apiKeyAuth.api_key;
	if (!value) return {};
	if ((apiKeyAuth.placement || "header") !== "query") return {};
	return { [apiKeyAuth.keyName || "X-API-Key"]: value };
}
/**
* Apply query parameters to a URL
*/
function applyQueryParams(url, params) {
	if (Object.keys(params).length === 0) return url;
	const urlObj = new URL(url);
	for (const [key, value] of Object.entries(params)) urlObj.searchParams.append(key, value);
	return urlObj.toString();
}
/**
* Check if auth requires async token fetching (OAuth)
*/
function requiresAsyncAuth(server) {
	return server.auth?.type === "oauth";
}

//#endregion
//#region src/util/dataUrl.ts
/**
* Check if a string is a data URL
* @param value String to check
* @returns true if value is a data URL (starts with "data:")
*
* @example
* isDataUrl("data:image/jpeg;base64,/9j/...") // true
* isDataUrl("/9j/4AAQSkZJRg...") // false
* isDataUrl("https://example.com/image.jpg") // false
*/
function isDataUrl(value) {
	return typeof value === "string" && value.startsWith("data:") && value.length > 5;
}
/**
* Parse a data URL into its components
*
* Handles data URLs with optional parameters (e.g., charset, name):
* - `data:image/jpeg;base64,<data>` - Standard format
* - `data:image/jpeg;charset=utf-8;base64,<data>` - With charset
* - `data:image/jpeg;name=photo.jpg;base64,<data>` - With filename
*
* @param dataUrl Data URL string
* @returns Parsed components (mimeType and base64Data) or null if invalid
*
* @example
* parseDataUrl("data:image/jpeg;base64,/9j/...")
* // { mimeType: "image/jpeg", base64Data: "/9j/..." }
*
* parseDataUrl("data:image/jpeg;charset=utf-8;base64,/9j/...")
* // { mimeType: "image/jpeg", base64Data: "/9j/..." }
*
* parseDataUrl("invalid") // null
*/
function parseDataUrl(dataUrl) {
	if (!isDataUrl(dataUrl)) return null;
	const match = dataUrl.match(/^data:([^;,]+)(?:;[^,]*)?;base64,(.+)$/);
	if (!match) return null;
	return {
		mimeType: match[1].trim(),
		base64Data: match[2].trim()
	};
}
/**
* Extract base64 data from a data URL or return original if not a data URL
* Useful for providers that expect raw base64 (Anthropic, Google)
*
* @param value Data URL or raw base64 string
* @returns Raw base64 string (data URL prefix stripped if present)
*
* @example
* extractBase64FromDataUrl("data:image/jpeg;base64,/9j/...")
* // "/9j/..."
*
* extractBase64FromDataUrl("/9j/...") // "/9j/..." (unchanged)
*/
function extractBase64FromDataUrl(value) {
	const parsed = parseDataUrl(value);
	return parsed ? parsed.base64Data : value;
}

//#endregion
//#region src/providers/google/auth.ts
/**
* Centralized authentication manager for Google AI providers.
*
* This module handles authentication for both Google AI Studio and Vertex AI,
* with support for API keys, OAuth/ADC, and service account credentials.
*
* Environment variable priority is aligned with the Python SDK:
* 1. config.apiKey (explicit)
* 2. VERTEX_API_KEY (Vertex mode only)
* 3. GOOGLE_API_KEY (primary - Python SDK alignment)
* 4. GEMINI_API_KEY (secondary)
*/
/**
* Centralized authentication manager for Google AI providers.
*
* Handles:
* - API key resolution with proper priority
* - OAuth client creation for Vertex AI
* - Service account credential loading
* - Conflict detection and warnings
*/
var GoogleAuthManager = class {
	/**
	* Get API key with proper priority order.
	*
	* Priority (aligned with Python SDK):
	* 1. config.apiKey (explicit)
	* 2. VERTEX_API_KEY (Vertex mode only)
	* 3. GOOGLE_API_KEY (primary - Python SDK alignment)
	* 4. GEMINI_API_KEY (secondary)
	* 5. PALM_API_KEY (legacy)
	*
	* @param config - Provider configuration
	* @param env - Environment overrides
	* @param isVertexMode - Whether in Vertex AI mode
	* @returns The resolved API key and its source
	*/
	static getApiKey(config, env, isVertexMode = false) {
		if (config.apiKey) return {
			apiKey: config.apiKey,
			source: "config"
		};
		if (isVertexMode) {
			const vertexKey = env?.VERTEX_API_KEY || getEnvString("VERTEX_API_KEY");
			if (vertexKey) {
				logger_default.warn("[Google] VERTEX_API_KEY is not a standard SDK env var. Use GOOGLE_API_KEY instead.");
				return {
					apiKey: vertexKey,
					source: "VERTEX_API_KEY"
				};
			}
		}
		const googleKey = env?.GOOGLE_API_KEY || getEnvString("GOOGLE_API_KEY");
		const geminiKey = env?.GEMINI_API_KEY || getEnvString("GEMINI_API_KEY");
		const palmKey = isVertexMode ? void 0 : env?.PALM_API_KEY || getEnvString("PALM_API_KEY");
		if (googleKey && geminiKey) logger_default.debug("[Google] Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.");
		if (googleKey) return {
			apiKey: googleKey,
			source: "GOOGLE_API_KEY"
		};
		if (geminiKey) {
			logger_default.debug("[Google] GEMINI_API_KEY is not a standard SDK env var. Consider using GOOGLE_API_KEY.");
			return {
				apiKey: geminiKey,
				source: "GEMINI_API_KEY"
			};
		}
		if (palmKey) {
			logger_default.warn("[Google] PALM_API_KEY is deprecated. Use GOOGLE_API_KEY instead.");
			return {
				apiKey: palmKey,
				source: "PALM_API_KEY"
			};
		}
		return {
			apiKey: void 0,
			source: "none"
		};
	}
	/**
	* Validate authentication configuration and emit warnings or throw errors for issues.
	*
	* @param config - Authentication configuration
	* @param env - Environment overrides
	* @throws Error if strictMutualExclusivity is true and mutual exclusivity violation detected
	*/
	static validateAndWarn(config, env) {
		const { apiKey, credentials, projectId, region, vertexai, strictMutualExclusivity } = config;
		const isStrict = strictMutualExclusivity === true;
		const useVertexEnv = getEnvString("GOOGLE_GENAI_USE_VERTEXAI");
		const cloudProject = getEnvString("GOOGLE_CLOUD_PROJECT");
		if ((projectId || region) && apiKey) {
			const message = "[Google] Project/location and API key are mutually exclusive in the client initializer. Use either apiKey for express mode OR projectId/region for OAuth mode, not both.";
			if (isStrict) throw new Error(message);
			else logger_default.warn(message);
		}
		if (useVertexEnv && vertexai === false) logger_default.warn("[Google] GOOGLE_GENAI_USE_VERTEXAI is set but vertexai: false was specified in config. Config takes precedence.");
		if (cloudProject && projectId && cloudProject !== projectId) logger_default.warn("[Google] Both GOOGLE_CLOUD_PROJECT and config.projectId are set with different values. Using config.projectId.");
		if (apiKey && credentials) logger_default.debug("[Google] Both apiKey and credentials are set. Using API key (express mode). Set expressMode: false to use OAuth/ADC instead.");
		if (vertexai && !apiKey && !projectId && !cloudProject && !credentials) {
			if (!Boolean(env?.GOOGLE_APPLICATION_CREDENTIALS || process.env.GOOGLE_APPLICATION_CREDENTIALS)) logger_default.debug("[Google] Vertex AI mode enabled but no projectId, credentials, or ADC detected. Authentication may fail.");
		}
	}
	/**
	* Determine if Vertex AI mode should be used.
	*
	* Priority:
	* 1. Explicit vertexai config flag
	* 2. GOOGLE_GENAI_USE_VERTEXAI env var (Python SDK compatibility)
	* 3. Auto-detect from projectId/credentials presence
	* 4. Default: false (Google AI Studio)
	*
	* @param config - Provider configuration
	* @param env - Environment overrides
	* @returns Whether to use Vertex AI mode
	*/
	static determineVertexMode(config, env) {
		if (config.vertexai !== void 0) return config.vertexai;
		const useVertexEnv = getEnvString("GOOGLE_GENAI_USE_VERTEXAI");
		if (useVertexEnv === "true" || useVertexEnv === "1") {
			logger_default.debug("[Google] Vertex AI mode enabled via GOOGLE_GENAI_USE_VERTEXAI");
			return true;
		}
		if (useVertexEnv === "false" || useVertexEnv === "0") return false;
		const hasProjectId = Boolean(config.projectId || env?.VERTEX_PROJECT_ID || getEnvString("VERTEX_PROJECT_ID") || env?.GOOGLE_PROJECT_ID || getEnvString("GOOGLE_PROJECT_ID") || getEnvString("GOOGLE_CLOUD_PROJECT"));
		const hasCredentials = Boolean(config.credentials);
		if (hasProjectId || hasCredentials) {
			logger_default.debug("[Google] Auto-detected Vertex AI mode from projectId/credentials. Set vertexai: true/false explicitly to suppress this message.");
			return true;
		}
		return false;
	}
	/**
	* Load credentials from file or return as-is.
	*
	* Supports:
	* - file:// prefix to load from external file
	* - Raw JSON string
	* - Pre-parsed object (from config loading pipeline)
	*
	* @param credentials - Credentials string, file path, or pre-parsed object
	* @returns Processed credentials JSON string
	*/
	static loadCredentials(credentials) {
		if (!credentials) return;
		if (typeof credentials === "object") return JSON.stringify(credentials);
		if (credentials.startsWith("file://")) try {
			const loaded = maybeLoadFromExternalFile(credentials);
			if (typeof loaded === "object") return JSON.stringify(loaded);
			return loaded;
		} catch (error) {
			throw new Error(`Failed to load credentials from file: ${error}`);
		}
		return credentials;
	}
	/**
	* Get or create a Google OAuth client.
	*
	* Supports googleAuthOptions passthrough for advanced configuration
	* like custom scopes, keyFilename, universeDomain, etc.
	*
	* @param options - OAuth client options (can also pass string for backward compatibility)
	* @returns OAuth client and detected project ID
	*/
	static async getOAuthClient(options = {}) {
		const { credentials, googleAuthOptions, scopes, keyFilename } = typeof options === "string" ? { credentials: options } : options;
		const resolvedScopes = scopes ?? googleAuthOptions?.scopes ?? "https://www.googleapis.com/auth/cloud-platform";
		const authOptions = {
			...googleAuthOptions,
			scopes: resolvedScopes
		};
		if (keyFilename && !authOptions.keyFilename) authOptions.keyFilename = keyFilename;
		let GoogleAuthClass;
		try {
			GoogleAuthClass = (await import("google-auth-library")).GoogleAuth;
		} catch {
			throw new Error("The google-auth-library package is required for Vertex AI. Please install it: npm install google-auth-library");
		}
		const auth = new GoogleAuthClass(authOptions);
		const processedCredentials = this.loadCredentials(credentials);
		let client;
		if (processedCredentials) {
			let parsedCredentials;
			try {
				parsedCredentials = JSON.parse(processedCredentials);
			} catch (parseError) {
				const errorMsg = parseError instanceof Error ? parseError.message : String(parseError);
				throw new Error(`[Google] Invalid credentials JSON format: ${errorMsg}`);
			}
			try {
				client = await auth.fromJSON(parsedCredentials);
			} catch (error) {
				const errorMsg = error instanceof Error ? error.message : String(error);
				logger_default.error(`[Google] Could not load credentials: ${errorMsg}`);
				throw new Error(`[Google] Could not load credentials: ${errorMsg}`);
			}
		} else client = await auth.getClient();
		let projectId;
		try {
			projectId = await auth.getProjectId();
		} catch {
			projectId = void 0;
		}
		return {
			client,
			projectId
		};
	}
	/**
	* Resolve project ID from multiple sources.
	*
	* Priority:
	* 1. config.projectId
	* 2. VERTEX_PROJECT_ID env var
	* 3. GOOGLE_PROJECT_ID env var
	* 4. GOOGLE_CLOUD_PROJECT env var (Python SDK compatibility)
	* 5. Auto-detected from OAuth credentials
	*
	* @param config - Provider configuration
	* @param env - Environment overrides
	* @returns Resolved project ID
	*/
	static async resolveProjectId(config, env) {
		const { projectId: authProjectId } = await this.getOAuthClient({
			credentials: config.credentials,
			googleAuthOptions: config.googleAuthOptions,
			keyFilename: config.keyFilename,
			scopes: config.scopes
		});
		const vertexProjectId = env?.VERTEX_PROJECT_ID || getEnvString("VERTEX_PROJECT_ID");
		const googleProjectId = env?.GOOGLE_PROJECT_ID || getEnvString("GOOGLE_PROJECT_ID");
		const cloudProject = getEnvString("GOOGLE_CLOUD_PROJECT");
		if (vertexProjectId && !config.projectId) logger_default.debug("[Google] VERTEX_PROJECT_ID is not a standard SDK env var. Consider using GOOGLE_CLOUD_PROJECT.");
		if (googleProjectId && !config.projectId && !vertexProjectId) logger_default.debug("[Google] GOOGLE_PROJECT_ID is not a standard SDK env var. Consider using GOOGLE_CLOUD_PROJECT.");
		return config.projectId || vertexProjectId || googleProjectId || cloudProject || authProjectId || "";
	}
	/**
	* Resolve region from multiple sources.
	*
	* Priority:
	* 1. config.region
	* 2. VERTEX_REGION env var
	* 3. GOOGLE_CLOUD_LOCATION env var (Python SDK compatibility)
	* 4. Default: 'global' for Vertex AI without API key (SDK aligned), 'us-central1' otherwise
	*
	* @param config - Provider configuration
	* @param env - Environment overrides
	* @param hasApiKey - Whether an API key is configured (affects default region)
	* @returns Resolved region
	*/
	static resolveRegion(config, env, hasApiKey) {
		const vertexRegion = env?.VERTEX_REGION || getEnvString("VERTEX_REGION");
		const cloudLocation = getEnvString("GOOGLE_CLOUD_LOCATION");
		if (vertexRegion && !config.region) logger_default.debug("[Google] VERTEX_REGION is not a standard SDK env var. Consider using GOOGLE_CLOUD_LOCATION.");
		const configuredRegion = config.region || vertexRegion || cloudLocation;
		if (configuredRegion) return configuredRegion;
		if (hasApiKey === false) return "global";
		return "us-central1";
	}
	/**
	* Check if Application Default Credentials are available.
	*
	* @returns True if ADC is available
	*/
	static async hasDefaultCredentials() {
		try {
			await this.getOAuthClient();
			return true;
		} catch {
			return false;
		}
	}
	/**
	* Clear the cached auth client (useful for testing).
	* @deprecated No longer uses instance-level caching; Google's auth library handles token caching internally.
	*/
	static clearCache() {}
};
const loadCredentials = GoogleAuthManager.loadCredentials.bind(GoogleAuthManager);
const getGoogleClient = GoogleAuthManager.getOAuthClient.bind(GoogleAuthManager);
const resolveProjectId = GoogleAuthManager.resolveProjectId.bind(GoogleAuthManager);
const hasGoogleDefaultCredentials = GoogleAuthManager.hasDefaultCredentials.bind(GoogleAuthManager);
const clearCachedAuth = GoogleAuthManager.clearCache.bind(GoogleAuthManager);

//#endregion
//#region src/providers/google/types.ts
const VALID_SCHEMA_TYPES = [
	"TYPE_UNSPECIFIED",
	"STRING",
	"NUMBER",
	"INTEGER",
	"BOOLEAN",
	"ARRAY",
	"OBJECT"
];

//#endregion
//#region src/providers/google/util.ts
const ajv = getAjv();
ajv.addKeyword("property_ordering");
const clone = Clone();
const PartSchema = z.object({
	text: z.string().optional(),
	inline_data: z.object({
		mime_type: z.string(),
		data: z.string()
	}).optional()
});
const ContentSchema = z.object({
	role: z.enum(["user", "model"]).optional(),
	parts: z.array(PartSchema)
});
const GeminiFormatSchema = z.array(ContentSchema);
function maybeCoerceToGeminiFormat(contents, options) {
	let coerced = false;
	const parseResult = GeminiFormatSchema.safeParse(contents);
	if (parseResult.success) {
		let systemInst = void 0;
		if (typeof contents === "object" && "system_instruction" in contents) {
			systemInst = contents.system_instruction;
			if (typeof contents === "object" && "contents" in contents) contents = contents.contents;
			coerced = true;
		}
		return {
			contents: parseResult.data,
			coerced,
			systemInstruction: systemInst
		};
	}
	let coercedContents;
	if (typeof contents === "object" && contents !== null && !Array.isArray(contents) && "system_instruction" in contents) {
		const systemInst = contents.system_instruction;
		if ("contents" in contents) coercedContents = contents.contents;
		else coercedContents = [];
		return {
			contents: coercedContents,
			coerced: true,
			systemInstruction: systemInst
		};
	}
	if (typeof contents === "string") {
		coercedContents = [{ parts: [{ text: contents }] }];
		coerced = true;
	} else if (Array.isArray(contents) && contents.every((item) => typeof item.content === "string")) {
		const targetRole = options?.useAssistantRole ? "assistant" : "model";
		coercedContents = contents.map((item) => ({
			role: item.role === "assistant" ? targetRole : item.role,
			parts: [{ text: item.content }]
		}));
		coerced = true;
	} else if (Array.isArray(contents) && contents.every((item) => item.role && item.content)) {
		const targetRole = options?.useAssistantRole ? "assistant" : "model";
		coercedContents = contents.map((item) => {
			const mappedRole = item.role === "assistant" ? targetRole : item.role;
			if (Array.isArray(item.content)) return {
				role: mappedRole,
				parts: item.content.map((contentItem) => {
					if (typeof contentItem === "string") return { text: contentItem };
					else if (contentItem.type === "text") return { text: contentItem.text };
					else return contentItem;
				})
			};
			else if (typeof item.content === "object") return {
				role: mappedRole,
				parts: [item.content]
			};
			else return {
				role: mappedRole,
				parts: [{ text: item.content }]
			};
		});
		coerced = true;
	} else if (typeof contents === "object" && contents !== null && "parts" in contents) {
		coercedContents = [contents];
		coerced = true;
	} else {
		logger_default.warn(`Unknown format for Gemini: ${JSON.stringify(contents)}`);
		return {
			contents: Array.isArray(contents) ? contents : [],
			coerced: false,
			systemInstruction: void 0
		};
	}
	let systemPromptParts = [];
	coercedContents = coercedContents.filter((message) => {
		if (message.role === "system" && message.parts.length > 0) {
			systemPromptParts.push(...message.parts.filter((part) => "text" in part && typeof part.text === "string"));
			return false;
		}
		return true;
	});
	if (coercedContents.length === 0 && systemPromptParts.length > 0) {
		coercedContents = [{
			role: "user",
			parts: systemPromptParts
		}];
		coerced = true;
		systemPromptParts = [];
	}
	return {
		contents: coercedContents,
		coerced,
		systemInstruction: systemPromptParts.length > 0 ? { parts: systemPromptParts } : void 0
	};
}
let cachedGenerativeLanguageAuth = null;
/**
* Gets an OAuth2 access token for Google APIs.
* Used by providers that need to authenticate via OAuth2 instead of API keys.
* @param credentials - Optional credentials JSON string or file:// path
* @param scopes - Optional scopes to use. Defaults to cloud-platform + generative-language scopes
* @returns The access token string, or undefined if authentication fails
*/
async function getGoogleAccessToken(credentials) {
	try {
		if (!cachedGenerativeLanguageAuth) {
			let GoogleAuth;
			try {
				GoogleAuth = (await import("google-auth-library")).GoogleAuth;
				cachedGenerativeLanguageAuth = new GoogleAuth({ scopes: [
					"https://www.googleapis.com/auth/cloud-platform",
					"https://www.googleapis.com/auth/generative-language.retriever",
					"https://www.googleapis.com/auth/generative-language.tuning"
				] });
			} catch {
				throw new Error("The google-auth-library package is required as a peer dependency. Please install it in your project or globally.");
			}
		}
		const processedCredentials = loadCredentials(credentials);
		let client;
		if (processedCredentials) client = await cachedGenerativeLanguageAuth.fromJSON(JSON.parse(processedCredentials));
		else client = await cachedGenerativeLanguageAuth.getClient();
		return (await client.getAccessToken()).token || void 0;
	} catch (error) {
		logger_default.debug("[GoogleAuth] Could not get access token", { error: error instanceof Error ? error.message : String(error) });
		return;
	}
}
function getCandidate(data) {
	if (!data || !data.candidates || data.candidates.length < 1) {
		let errorDetails = "No candidates returned in API response.";
		if (data?.promptFeedback?.blockReason) {
			errorDetails = `Response blocked: ${data.promptFeedback.blockReason}`;
			if (data.promptFeedback.safetyRatings) {
				const flaggedCategories = data.promptFeedback.safetyRatings.filter((rating) => rating.probability !== "NEGLIGIBLE").map((rating) => `${rating.category}: ${rating.probability}`);
				if (flaggedCategories.length > 0) errorDetails += ` (Safety ratings: ${flaggedCategories.join(", ")})`;
			}
		} else if (data?.promptFeedback?.safetyRatings) {
			const flaggedCategories = data.promptFeedback.safetyRatings.filter((rating) => rating.probability !== "NEGLIGIBLE").map((rating) => `${rating.category}: ${rating.probability}`);
			if (flaggedCategories.length > 0) errorDetails = `Response may have been blocked due to safety filters: ${flaggedCategories.join(", ")}`;
		}
		errorDetails += `\n\nGot response: ${JSON.stringify(data)}`;
		throw new Error(errorDetails);
	}
	if (data.candidates.length > 1) logger_default.debug(`Expected one candidate in AI Studio API response, but got ${data.candidates.length}: ${JSON.stringify(data)}`);
	return data.candidates[0];
}
function formatCandidateContents(candidate) {
	if (candidate.finishReason && [
		"SAFETY",
		"RECITATION",
		"PROHIBITED_CONTENT",
		"BLOCKLIST",
		"SPII"
	].includes(candidate.finishReason)) {
		let errorMessage = `Response was blocked with finish reason: ${candidate.finishReason}`;
		if (candidate.safetyRatings) {
			const flaggedCategories = candidate.safetyRatings.filter((rating) => rating.probability !== "NEGLIGIBLE" || rating.blocked).map((rating) => `${rating.category}: ${rating.probability}${rating.blocked ? " (BLOCKED)" : ""}`);
			if (flaggedCategories.length > 0) errorMessage += `\nSafety ratings: ${flaggedCategories.join(", ")}`;
		}
		if (candidate.finishReason === "RECITATION") errorMessage += "\n\nThis typically occurs when the response is too similar to content from the model's training data.";
		else if (candidate.finishReason === "SAFETY") errorMessage += "\n\nThe response was blocked due to safety filters. Consider adjusting safety settings or modifying your prompt.";
		throw new Error(errorMessage);
	}
	if (candidate.content?.parts) {
		let output = "";
		let is_text = true;
		for (const part of candidate.content.parts) if ("text" in part) output += part.text;
		else is_text = false;
		if (is_text) return output;
		else return candidate.content.parts;
	} else throw new Error(`No output found in response: ${JSON.stringify(candidate)}`);
}
function mergeParts(parts1, parts2) {
	if (parts1 === void 0) return parts2;
	if (typeof parts1 === "string" && typeof parts2 === "string") return parts1 + parts2;
	const array1 = typeof parts1 === "string" ? [{ text: parts1 }] : parts1;
	const array2 = typeof parts2 === "string" ? [{ text: parts2 }] : parts2;
	array1.push(...array2);
	return array1;
}
/**
* Normalizes and sanitizes tools configuration for Gemini API compatibility.
* - Handles snake_case to camelCase conversion for backwards compatibility
* - Sanitizes function declaration schemas to remove unsupported JSON Schema properties
*   (e.g., additionalProperties, $schema, default) that Gemini doesn't support
*/
function normalizeTools(tools) {
	return tools.map((tool) => {
		const normalizedTool = { ...tool };
		if (tool.google_search && !normalizedTool.googleSearch) normalizedTool.googleSearch = tool.google_search;
		if (tool.code_execution && !normalizedTool.codeExecution) normalizedTool.codeExecution = tool.code_execution;
		if (tool.google_search_retrieval && !normalizedTool.googleSearchRetrieval) normalizedTool.googleSearchRetrieval = tool.google_search_retrieval;
		if (normalizedTool.functionDeclarations) normalizedTool.functionDeclarations = normalizedTool.functionDeclarations.map((fd) => ({
			...fd,
			parameters: fd.parameters ? sanitizeSchemaForGemini(fd.parameters) : void 0
		}));
		return normalizedTool;
	});
}
function loadFile(config_var, context_vars) {
	const fileContents = maybeLoadFromExternalFile(renderVarsInObject(config_var, context_vars));
	if (typeof fileContents === "string") try {
		const parsedContents = JSON.parse(fileContents);
		return Array.isArray(parsedContents) ? normalizeTools(parsedContents) : parsedContents;
	} catch (err) {
		logger_default.debug(`ERROR: failed to convert file contents to JSON:\n${JSON.stringify(err)}`);
		return fileContents;
	}
	if (Array.isArray(fileContents)) return normalizeTools(fileContents);
	return fileContents;
}
function isValidBase64Image(data) {
	const base64Data = isDataUrl(data) ? extractBase64FromDataUrl(data) : data;
	if (!base64Data || base64Data.length < 20) return false;
	try {
		Buffer.from(base64Data, "base64");
		return base64Data.startsWith("/9j/") || base64Data.startsWith("iVBORw0KGgo") || base64Data.startsWith("R0lGODlh") || base64Data.startsWith("R0lGODdh") || base64Data.startsWith("UklGR") || base64Data.startsWith("Qk0") || base64Data.startsWith("Qk1") || base64Data.startsWith("SUkq") || base64Data.startsWith("TU0A") || base64Data.startsWith("AAABAA");
	} catch {
		return false;
	}
}
function getMimeTypeFromBase64(base64DataOrUrl) {
	const parsed = parseDataUrl(base64DataOrUrl);
	if (parsed) return parsed.mimeType;
	const base64Data = extractBase64FromDataUrl(base64DataOrUrl);
	if (base64Data.startsWith("/9j/")) return "image/jpeg";
	else if (base64Data.startsWith("iVBORw0KGgo")) return "image/png";
	else if (base64Data.startsWith("R0lGODlh") || base64Data.startsWith("R0lGODdh")) return "image/gif";
	else if (base64Data.startsWith("UklGR")) return "image/webp";
	else if (base64Data.startsWith("Qk0") || base64Data.startsWith("Qk1")) return "image/bmp";
	else if (base64Data.startsWith("SUkq") || base64Data.startsWith("TU0A")) return "image/tiff";
	else if (base64Data.startsWith("AAABAA")) return "image/x-icon";
	return "image/jpeg";
}
function processImagesInContents(contents, contextVars) {
	if (!contextVars) return contents;
	if (!Array.isArray(contents)) {
		logger_default.warn("[Google] contents is not an array in processImagesInContents", {
			contentsType: typeof contents,
			contentsValue: contents
		});
		return [];
	}
	const base64ToVarName = /* @__PURE__ */ new Map();
	for (const [varName, value] of Object.entries(contextVars)) if (typeof value === "string" && isValidBase64Image(value)) base64ToVarName.set(value, varName);
	return contents.map((content) => {
		if (content.parts) {
			const newParts = [];
			for (const part of content.parts) if (part.text) {
				const lines = part.text.split("\n");
				let foundValidImage = false;
				let currentTextBlock = "";
				const processedParts = [];
				for (const line of lines) {
					const trimmedLine = line.trim();
					if (base64ToVarName.has(trimmedLine) && isValidBase64Image(trimmedLine)) {
						foundValidImage = true;
						if (currentTextBlock.length > 0) {
							processedParts.push({ text: currentTextBlock });
							currentTextBlock = "";
						}
						const mimeType = getMimeTypeFromBase64(trimmedLine);
						const base64Data = isDataUrl(trimmedLine) ? extractBase64FromDataUrl(trimmedLine) : trimmedLine;
						processedParts.push({ inlineData: {
							mimeType,
							data: base64Data
						} });
					} else {
						if (currentTextBlock.length > 0) currentTextBlock += "\n";
						currentTextBlock += line;
					}
				}
				if (currentTextBlock.length > 0) processedParts.push({ text: currentTextBlock });
				if (foundValidImage) newParts.push(...processedParts);
				else newParts.push(part);
			} else newParts.push(part);
			return {
				...content,
				parts: newParts
			};
		}
		return content;
	});
}
/**
* Parses and processes config-level systemInstruction.
* Handles file loading, string-to-Content conversion, and Nunjucks template rendering.
*
* @param configSystemInstruction - The systemInstruction from config (can be string, Content, or undefined)
* @param contextVars - Variables for Nunjucks template rendering
* @returns Processed Content object or undefined
*/
function parseConfigSystemInstruction(configSystemInstruction, contextVars) {
	if (!configSystemInstruction) return;
	let configInstruction = clone(configSystemInstruction);
	if (typeof configSystemInstruction === "string") configInstruction = loadFile(configSystemInstruction, contextVars);
	if (typeof configInstruction === "string") configInstruction = { parts: [{ text: configInstruction }] };
	if (contextVars && configInstruction) {
		const nunjucks = getNunjucksEngine();
		for (const part of configInstruction.parts) if (part.text) try {
			part.text = nunjucks.renderString(part.text, contextVars);
		} catch (err) {
			throw new Error(`Unable to render nunjucks in systemInstruction: ${err}`);
		}
	}
	return configInstruction;
}
function geminiFormatAndSystemInstructions(prompt, contextVars, configSystemInstruction, options) {
	let contents = parseChatPrompt(prompt, [{
		parts: [{ text: prompt }],
		role: "user"
	}]);
	const { contents: updatedContents, coerced, systemInstruction: parsedSystemInstruction } = maybeCoerceToGeminiFormat(contents, options);
	if (coerced) {
		logger_default.debug(`Coerced JSON prompt to Gemini format: ${JSON.stringify(contents)}`);
		contents = updatedContents;
	}
	let systemInstruction = parsedSystemInstruction;
	const parsedConfigInstruction = parseConfigSystemInstruction(configSystemInstruction, contextVars);
	if (parsedConfigInstruction) systemInstruction = systemInstruction ? { parts: [...parsedConfigInstruction.parts, ...systemInstruction.parts] } : parsedConfigInstruction;
	contents = processImagesInContents(contents, contextVars);
	return {
		contents,
		systemInstruction
	};
}
/**
* Recursively traverses a JSON schema object and converts
* uppercase type keywords (string values) to lowercase.
* Handles nested objects and arrays within the schema.
* Creates a deep copy to avoid modifying the original schema.
*
* @param {object | any} schemaNode - The current node (object or value) being processed.
* @returns {object | any} - The processed node with type keywords lowercased.
*/
function normalizeSchemaTypes(schemaNode) {
	if (typeof schemaNode !== "object" || schemaNode === null) return schemaNode;
	if (Array.isArray(schemaNode)) return schemaNode.map(normalizeSchemaTypes);
	const newNode = {};
	for (const key in schemaNode) if (Object.prototype.hasOwnProperty.call(schemaNode, key)) {
		const value = schemaNode[key];
		if (key === "type") if (typeof value === "string" && VALID_SCHEMA_TYPES.includes(value)) newNode[key] = value.toLowerCase();
		else if (Array.isArray(value)) newNode[key] = value.map((t) => typeof t === "string" && VALID_SCHEMA_TYPES.includes(t) ? t.toLowerCase() : t);
		else newNode[key] = normalizeSchemaTypes(value);
		else newNode[key] = normalizeSchemaTypes(value);
	}
	return newNode;
}
function parseStringObject(input) {
	if (typeof input === "string") return JSON.parse(input);
	return input;
}
function validateFunctionCall(output, functions, vars) {
	let functionCalls;
	try {
		let parsedOutput = parseStringObject(output);
		if ("toolCall" in parsedOutput) {
			parsedOutput = parsedOutput.toolCall;
			functionCalls = parsedOutput.functionCalls;
		} else if (Array.isArray(parsedOutput)) functionCalls = parsedOutput.filter((obj) => Object.prototype.hasOwnProperty.call(obj, "functionCall")).map((obj) => obj.functionCall);
		else throw new Error("Unrecognized function call format");
	} catch {
		throw new Error(`Google did not return a valid-looking function call: ${JSON.stringify(output)}`);
	}
	const interpolatedFunctions = loadFile(functions, vars);
	for (const functionCall of functionCalls) {
		const functionName = functionCall.name;
		const functionArgs = parseStringObject(functionCall.args);
		const functionSchema = (interpolatedFunctions?.find((f) => "functionDeclarations" in f))?.functionDeclarations?.find((f) => f.name === functionName);
		if (!functionSchema) throw new Error(`Called "${functionName}", but there is no function with that name`);
		if (Object.keys(functionArgs).length !== 0 && functionSchema?.parameters) {
			const parameterSchema = normalizeSchemaTypes(functionSchema.parameters);
			let validate;
			try {
				validate = ajv.compile(parameterSchema);
			} catch (err) {
				throw new Error(`Tool schema doesn't compile with ajv: ${err}. If this is a valid tool schema you may need to reformulate your assertion without is-valid-function-call.`);
			}
			if (!validate(functionArgs)) throw new Error(`Call to "${functionName}":\n${JSON.stringify(functionCall)}\ndoes not match schema:\n${JSON.stringify(validate.errors)}`);
		} else if (!(JSON.stringify(functionArgs) === "{}" && !functionSchema?.parameters)) throw new Error(`Call to "${functionName}":\n${JSON.stringify(functionCall)}\ndoes not match schema:\n${JSON.stringify(functionSchema)}`);
	}
}
/**
* Properties supported by Gemini's function calling API.
* Based on Google's Schema type definition and API documentation.
* @see https://ai.google.dev/api/caching#Schema
*/
const GEMINI_SUPPORTED_SCHEMA_PROPERTIES = new Set([
	"type",
	"format",
	"description",
	"nullable",
	"enum",
	"maxItems",
	"minItems",
	"properties",
	"required",
	"propertyOrdering",
	"items"
]);
/**
* Valid JSON Schema types mapped to Gemini's expected format (uppercase).
*/
const JSON_SCHEMA_TYPE_MAP = {
	string: "STRING",
	number: "NUMBER",
	integer: "INTEGER",
	boolean: "BOOLEAN",
	array: "ARRAY",
	object: "OBJECT",
	null: "STRING"
};
/**
* Recursively sanitizes a JSON Schema for Gemini API compatibility.
*
* - Removes unsupported properties (additionalProperties, $schema, default, title, etc.)
* - Converts type values to uppercase (string → STRING, object → OBJECT)
* - Recursively processes nested schemas in 'properties' and 'items'
*
* @param schema - The JSON Schema object to sanitize
* @returns A sanitized schema compatible with Gemini's function calling API
*/
function sanitizeSchemaForGemini(schema) {
	if (!schema || typeof schema !== "object") return schema;
	const result = {};
	for (const [key, value] of Object.entries(schema)) {
		if (!GEMINI_SUPPORTED_SCHEMA_PROPERTIES.has(key)) continue;
		if (key === "type") if (typeof value === "string") result[key] = JSON_SCHEMA_TYPE_MAP[value.toLowerCase()] || value.toUpperCase();
		else result[key] = value;
		else if (key === "properties" && typeof value === "object" && value !== null) {
			result[key] = {};
			for (const [propName, propSchema] of Object.entries(value)) if (typeof propSchema === "object" && propSchema !== null) result[key][propName] = sanitizeSchemaForGemini(propSchema);
			else result[key][propName] = propSchema;
		} else if (key === "items" && typeof value === "object" && value !== null) result[key] = sanitizeSchemaForGemini(value);
		else result[key] = value;
	}
	return result;
}
/**
* Create a cache discriminator from auth headers.
*
* This is used to ensure different API keys/credentials don't share cached responses.
* The discriminator is included as a custom property in fetchWithCache options,
* which gets included in the cache key automatically.
*
* Security note: We hash auth headers rather than using them directly to avoid
* exposing sensitive credentials in cache keys or logs. The hash is truncated
* to 16 hex characters (64 bits) for brevity - collision probability is acceptably
* low for cache key differentiation (birthday problem: ~4 billion entries needed
* for 50% collision probability).
*
* @param headers - Request headers containing auth info
* @returns A short hash string for cache key differentiation
*/
function createAuthCacheDiscriminator(headers) {
	const authValues = [];
	for (const name of [
		"authorization",
		"x-goog-api-key",
		"x-api-key",
		"api-key",
		"x-goog-user-project"
	]) {
		const value = headers[name] || headers[name.toLowerCase()];
		if (value) authValues.push(`${name}:${value}`);
	}
	if (authValues.length === 0) return "";
	return crypto.createHash("sha256").update(authValues.join("|")).digest("hex").substring(0, 16);
}

//#endregion
//#region src/providers/mcp/transform.ts
function transformMCPToolsToOpenAi(tools) {
	return tools.map((tool) => {
		const schema = tool.inputSchema;
		let properties = {};
		let required = void 0;
		let additionalProperties = void 0;
		if (schema && typeof schema === "object" && "properties" in schema) {
			properties = schema.properties ?? {};
			required = schema.required;
			if ("additionalProperties" in schema) additionalProperties = schema.additionalProperties;
		} else if (schema && typeof schema === "object") properties = {};
		else properties = {};
		return {
			type: "function",
			function: {
				name: tool.name,
				description: tool.description,
				parameters: {
					type: "object",
					properties,
					...required && required.length > 0 ? { required } : {},
					...additionalProperties !== void 0 ? { additionalProperties } : {}
				}
			}
		};
	});
}
function transformMCPToolsToAnthropic(tools) {
	return tools.map((tool) => {
		const { $schema: _$schema, ...cleanSchema } = tool.inputSchema;
		return {
			name: tool.name,
			description: tool.description,
			input_schema: {
				type: "object",
				...cleanSchema
			}
		};
	});
}
function transformMCPToolsToGoogle(tools) {
	return [{ functionDeclarations: tools.map((tool) => {
		const schema = tool.inputSchema;
		let parameters;
		if (schema && typeof schema === "object") {
			parameters = sanitizeSchemaForGemini(schema);
			if (!parameters.type) parameters.type = "OBJECT";
			if (!parameters.properties) parameters.properties = {};
		} else parameters = {
			type: "OBJECT",
			properties: {}
		};
		return {
			name: tool.name,
			description: tool.description,
			parameters
		};
	}) }];
}
async function transformMCPConfigToClaudeCode(config) {
	const serverConfigs = config.servers ?? [];
	if (config.server) serverConfigs.push(config.server);
	return (await Promise.all(serverConfigs.map((server) => transformMCPServerConfigToClaudeCode(server)))).reduce((acc, transformed) => {
		const [key, out] = transformed;
		acc[key] = out;
		return acc;
	}, {});
}
async function transformMCPServerConfigToClaudeCode(config) {
	const key = config.name ?? config.url ?? config.command ?? "default";
	let out;
	if (config.url) {
		const renderedConfig = renderAuthVars(config);
		let oauthToken;
		if (requiresAsyncAuth(renderedConfig) && renderedConfig.auth?.type === "oauth") oauthToken = await getOAuthToken(renderedConfig.auth);
		const queryParams = getAuthQueryParams(renderedConfig);
		out = {
			type: "http",
			url: applyQueryParams(config.url, queryParams),
			headers: {
				...config.headers ?? {},
				...getAuthHeaders(renderedConfig, oauthToken)
			}
		};
	} else if (config.command && config.args) out = {
		type: "stdio",
		command: config.command,
		args: config.args
	};
	else if (config.path) out = {
		type: "stdio",
		command: config.path.endsWith(".py") ? process.platform === "win32" ? "python" : "python3" : process.execPath,
		args: [config.path]
	};
	else throw new Error("MCP configuration cannot be converted to Claude Agent SDK MCP server config");
	return [key, out];
}

//#endregion
export { renderAuthVars as C, getOAuthTokenWithExpiry as S, resolveProjectId as _, createAuthCacheDiscriminator as a, getAuthHeaders as b, getCandidate as c, normalizeTools as d, validateFunctionCall as f, loadCredentials as g, hasGoogleDefaultCredentials as h, transformMCPToolsToOpenAi as i, getGoogleAccessToken as l, getGoogleClient as m, transformMCPToolsToAnthropic as n, formatCandidateContents as o, GoogleAuthManager as p, transformMCPToolsToGoogle as r, geminiFormatAndSystemInstructions as s, transformMCPConfigToClaudeCode as t, mergeParts as u, parseDataUrl as v, TOKEN_REFRESH_BUFFER_MS as w, getAuthQueryParams as x, applyQueryParams as y };
//# sourceMappingURL=transform-kOrXspJM.js.map