import { _ as getEnvBool, b as getEnvString, i as logger_default, w as cliState_default } from "./logger-CATn0kWr.js";
import { s as CloudConfig, t as fetchWithProxy } from "./fetch-BhuDaSn5.js";
import { o as isLoggedIntoCloud } from "./accounts-D2MbUY7o.js";
import chalk from "chalk";
import "opener";
import readline from "readline";

//#region src/redteam/remoteGeneration.ts
/**
* Gets the remote generation API endpoint URL.
* Prioritizes: env var > cloud config > default endpoint.
* @returns The remote generation URL
*/
function getRemoteGenerationUrl() {
	const envUrl = getEnvString("PROMPTFOO_REMOTE_GENERATION_URL");
	if (envUrl) return envUrl;
	const cloudConfig = new CloudConfig();
	if (cloudConfig.isEnabled()) return cloudConfig.getApiHost() + "/api/v1/task";
	return "https://api.promptfoo.app/api/v1/task";
}
/**
* Check if remote generation should never be used.
* Respects both the general and redteam-specific disable flags.
* @returns true if remote generation is disabled
*/
function neverGenerateRemote() {
	if (getEnvBool("PROMPTFOO_DISABLE_REMOTE_GENERATION")) return true;
	return getEnvBool("PROMPTFOO_DISABLE_REDTEAM_REMOTE_GENERATION");
}
/**
* Check if remote generation should never be used for non-redteam features.
* This allows granular control: disable redteam remote generation while allowing
* regular SimulatedUser to use remote generation.
* @returns true if ALL remote generation is disabled
*/
function neverGenerateRemoteForRegularEvals() {
	return getEnvBool("PROMPTFOO_DISABLE_REMOTE_GENERATION");
}
/**
* Builds a remote URL with a substituted pathname, honoring env vars / cloud config.
*/
function buildRemoteUrl(pathname, fallback) {
	if (neverGenerateRemote()) return null;
	const envUrl = getEnvString("PROMPTFOO_REMOTE_GENERATION_URL");
	if (envUrl) try {
		const url = new URL(envUrl);
		url.pathname = pathname;
		return url.toString();
	} catch {
		return fallback;
	}
	const cloudConfig = new CloudConfig();
	if (cloudConfig.isEnabled()) return `${cloudConfig.getApiHost()}${pathname}`;
	return fallback;
}
/**
* Gets the URL for checking remote API health based on configuration.
* @returns The health check URL, or null if remote generation is disabled.
*/
function getRemoteHealthUrl() {
	return buildRemoteUrl("/health", "https://api.promptfoo.app/health");
}
/**
* Gets the URL for checking remote API version based on configuration.
* @returns The version check URL, or null if remote generation is disabled.
*/
function getRemoteVersionUrl() {
	return buildRemoteUrl("/version", "https://api.promptfoo.app/version");
}
/**
* Determines if remote generation should be used based on configuration.
* @returns true if remote generation should be used
*/
function shouldGenerateRemote() {
	if (neverGenerateRemote()) return false;
	if (isLoggedIntoCloud()) return true;
	return !getEnvString("OPENAI_API_KEY") || (cliState_default.remote ?? false);
}
/**
* Gets the URL for unaligned model inference (harmful content generation).
* Prioritizes: env var > cloud config > default endpoint.
* @returns The unaligned inference URL
*/
function getRemoteGenerationUrlForUnaligned() {
	const envUrl = getEnvString("PROMPTFOO_UNALIGNED_INFERENCE_ENDPOINT");
	if (envUrl) return envUrl;
	const cloudConfig = new CloudConfig();
	if (cloudConfig.isEnabled()) return cloudConfig.getApiHost() + "/api/v1/task/harmful";
	return "https://api.promptfoo.app/api/v1/task/harmful";
}

//#endregion
//#region src/util/readline.ts
/**
* Factory function for creating readline interface.
* This abstraction makes it easier to mock in tests and prevents open handles.
*/
function createReadlineInterface() {
	return readline.createInterface({
		input: process.stdin,
		output: process.stdout
	});
}
/**
* Prompts the user with a question and returns their answer.
* Automatically handles cleanup of the readline interface.
*/
async function promptUser(question) {
	return new Promise((resolve, reject) => {
		let rl = null;
		try {
			rl = createReadlineInterface();
			rl.on("error", (err) => {
				if (rl) rl.close();
				reject(err);
			});
			rl.question(question, (answer) => {
				if (rl) rl.close();
				resolve(answer);
			});
		} catch (err) {
			if (rl) rl.close();
			reject(err);
		}
	});
}
/**
* Prompts the user with a yes/no question and returns a boolean.
* @param question The question to ask
* @param defaultYes If true, empty response defaults to yes. If false, defaults to no.
*/
async function promptYesNo(question, defaultYes = false) {
	const answer = await promptUser(`${question} ${defaultYes ? "(Y/n): " : "(y/N): "}`);
	if (defaultYes) return !answer.trim().toLowerCase().startsWith("n");
	return answer.trim().toLowerCase().startsWith("y");
}

//#endregion
//#region src/util/server.ts
const BrowserBehavior = {
	ASK: 0,
	OPEN: 1,
	SKIP: 2,
	OPEN_TO_REPORT: 3,
	OPEN_TO_REDTEAM_CREATE: 4
};
const BrowserBehaviorNames = {
	[BrowserBehavior.ASK]: "ASK",
	[BrowserBehavior.OPEN]: "OPEN",
	[BrowserBehavior.SKIP]: "SKIP",
	[BrowserBehavior.OPEN_TO_REPORT]: "OPEN_TO_REPORT",
	[BrowserBehavior.OPEN_TO_REDTEAM_CREATE]: "OPEN_TO_REDTEAM_CREATE"
};
const featureCache = /* @__PURE__ */ new Map();
/**
* Checks if a server supports a specific feature based on build date
* @param featureName - Name of the feature (for caching and logging)
* @param requiredBuildDate - Minimum build date when feature was added (ISO string)
* @returns Promise<boolean> - true if server supports the feature
*/
async function checkServerFeatureSupport(featureName, requiredBuildDate) {
	const cacheKey = `${featureName}`;
	if (featureCache.has(cacheKey)) return featureCache.get(cacheKey);
	let supported = false;
	try {
		logger_default.debug(`[Feature Detection] Checking server support for feature: ${featureName}`);
		const versionUrl = getRemoteVersionUrl();
		if (versionUrl) {
			const data = await (await fetchWithProxy(versionUrl, {
				method: "GET",
				headers: { "Content-Type": "application/json" }
			})).json();
			if (data.buildDate) {
				supported = new Date(data.buildDate) >= new Date(requiredBuildDate);
				logger_default.debug(`[Feature Detection] ${featureName}: buildDate=${data.buildDate}, required=${requiredBuildDate}, supported=${supported}`);
			} else {
				logger_default.debug(`[Feature Detection] ${featureName}: no version info, assuming not supported`);
				supported = false;
			}
		} else {
			logger_default.debug(`[Feature Detection] No remote URL available for ${featureName}, assuming local server supports it`);
			supported = true;
		}
	} catch (error) {
		logger_default.debug(`[Feature Detection] Version check failed for ${featureName}, assuming not supported: ${error}`);
		supported = false;
	}
	featureCache.set(cacheKey, supported);
	return supported;
}

//#endregion
export { getRemoteGenerationUrlForUnaligned as a, neverGenerateRemoteForRegularEvals as c, getRemoteGenerationUrl as i, shouldGenerateRemote as l, checkServerFeatureSupport as n, getRemoteHealthUrl as o, promptYesNo as r, neverGenerateRemote as s, BrowserBehavior as t };
//# sourceMappingURL=server-BsA7InQY.js.map