const require_logger = require('./logger-q_xXORhb.cjs');
const require_fetch = require('./fetch--6dTWCD4.cjs');
const require_accounts = require('./accounts-DswJu0kA.cjs');
let chalk = require("chalk");
chalk = require_logger.__toESM(chalk);
require("opener");
let readline = require("readline");
readline = require_logger.__toESM(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 = require_logger.getEnvString("PROMPTFOO_REMOTE_GENERATION_URL");
	if (envUrl) return envUrl;
	const cloudConfig = new require_fetch.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 (require_logger.getEnvBool("PROMPTFOO_DISABLE_REMOTE_GENERATION")) return true;
	return require_logger.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 require_logger.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 = require_logger.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 require_fetch.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 (require_accounts.isLoggedIntoCloud()) return true;
	return !require_logger.getEnvString("OPENAI_API_KEY") || (require_logger.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 = require_logger.getEnvString("PROMPTFOO_UNALIGNED_INFERENCE_ENDPOINT");
	if (envUrl) return envUrl;
	const cloudConfig = new require_fetch.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.default.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 {
		require_logger.logger_default.debug(`[Feature Detection] Checking server support for feature: ${featureName}`);
		const versionUrl = getRemoteVersionUrl();
		if (versionUrl) {
			const data = await (await require_fetch.fetchWithProxy(versionUrl, {
				method: "GET",
				headers: { "Content-Type": "application/json" }
			})).json();
			if (data.buildDate) {
				supported = new Date(data.buildDate) >= new Date(requiredBuildDate);
				require_logger.logger_default.debug(`[Feature Detection] ${featureName}: buildDate=${data.buildDate}, required=${requiredBuildDate}, supported=${supported}`);
			} else {
				require_logger.logger_default.debug(`[Feature Detection] ${featureName}: no version info, assuming not supported`);
				supported = false;
			}
		} else {
			require_logger.logger_default.debug(`[Feature Detection] No remote URL available for ${featureName}, assuming local server supports it`);
			supported = true;
		}
	} catch (error) {
		require_logger.logger_default.debug(`[Feature Detection] Version check failed for ${featureName}, assuming not supported: ${error}`);
		supported = false;
	}
	featureCache.set(cacheKey, supported);
	return supported;
}

//#endregion
Object.defineProperty(exports, 'BrowserBehavior', {
  enumerable: true,
  get: function () {
    return BrowserBehavior;
  }
});
Object.defineProperty(exports, 'checkServerFeatureSupport', {
  enumerable: true,
  get: function () {
    return checkServerFeatureSupport;
  }
});
Object.defineProperty(exports, 'getRemoteGenerationUrl', {
  enumerable: true,
  get: function () {
    return getRemoteGenerationUrl;
  }
});
Object.defineProperty(exports, 'getRemoteGenerationUrlForUnaligned', {
  enumerable: true,
  get: function () {
    return getRemoteGenerationUrlForUnaligned;
  }
});
Object.defineProperty(exports, 'getRemoteHealthUrl', {
  enumerable: true,
  get: function () {
    return getRemoteHealthUrl;
  }
});
Object.defineProperty(exports, 'neverGenerateRemote', {
  enumerable: true,
  get: function () {
    return neverGenerateRemote;
  }
});
Object.defineProperty(exports, 'neverGenerateRemoteForRegularEvals', {
  enumerable: true,
  get: function () {
    return neverGenerateRemoteForRegularEvals;
  }
});
Object.defineProperty(exports, 'promptYesNo', {
  enumerable: true,
  get: function () {
    return promptYesNo;
  }
});
Object.defineProperty(exports, 'shouldGenerateRemote', {
  enumerable: true,
  get: function () {
    return shouldGenerateRemote;
  }
});
//# sourceMappingURL=server-_hqsw2nB.cjs.map