import { I as configureEvalRunLogs, Pt as runWithEvalRegistry, St as resolveLlmCallsConfig, _ as createBufferedCacheStore, a as isCaseChildParentMessage, d as loadEvalModule, l as registerAgentEvalsPackageResolutionHooks, p as loadConfig, q as runInEvalRuntimeScope, r as runCase, v as createFsCacheStore, xt as resolveApiCallsConfig } from "./runExecution-6lrtj48K.mjs";
//#region ../runner/src/caseChild.ts
let fatalErrorReported = false;
let disconnectExpected = false;
let runStarted = false;
const pendingMessageSends = /* @__PURE__ */ new Set();
function sendMessage(message) {
	if (process.send === void 0) return;
	const sendPromise = new Promise((resolvePromise) => {
		try {
			process.send?.(message, (error) => {
				if (error) {
					console.error("Failed to send case child message:");
					console.error(formatUnknownErrorDetails(error));
				}
				resolvePromise();
			});
		} catch (error) {
			console.error("Failed to send case child message:");
			console.error(formatUnknownErrorDetails(error));
			resolvePromise();
		}
	});
	pendingMessageSends.add(sendPromise);
	sendPromise.finally(() => {
		pendingMessageSends.delete(sendPromise);
	});
}
async function flushMessageSends() {
	while (pendingMessageSends.size > 0) await Promise.allSettled([...pendingMessageSends]);
}
function installFatalCaseChildErrorHandlers() {
	process.once("uncaughtException", (error) => {
		reportFatalCaseChildErrorAndExit(error);
	});
	process.once("unhandledRejection", (reason) => {
		reportFatalCaseChildErrorAndExit(toUnhandledRejectionError(reason));
	});
}
async function useEvalDefinition(params) {
	const entry = (await runWithEvalRegistry(async (activeRegistry) => {
		await runInEvalRuntimeScope("env", async () => {
			await loadEvalModule(params.evalFilePath, params.sourceFingerprint);
		});
		return activeRegistry;
	})).get(params.evalId);
	if (entry === void 0) throw new Error(`Eval "${params.evalId}" was not registered after importing ${params.evalFilePath}`);
	return await entry.use(async (evalDef) => await params.use(evalDef));
}
async function executeCaseChild(context) {
	process.chdir(context.workspaceRoot);
	registerAgentEvalsPackageResolutionHooks();
	const config = await loadConfig();
	configureEvalRunLogs({ captureConsole: config.runLogs?.captureConsole !== false });
	const cacheStore = createFsCacheStore({
		workspaceRoot: context.workspaceRoot,
		dir: config.cache?.dir,
		maxEntriesPerNamespace: config.cache?.maxEntriesPerNamespace ?? config.cache?.maxEntriesPerEval,
		maxEntriesByNamespace: config.cache?.maxEntriesByNamespace
	});
	const bufferedCacheStore = context.cacheEnabled && context.cacheMode !== "bypass" ? createBufferedCacheStore(cacheStore) : null;
	const llmCallsConfig = resolveLlmCallsConfig(config.llmCalls);
	const apiCallsConfig = resolveApiCallsConfig(config.apiCalls);
	const { caseDetail, caseRowUpdate } = await useEvalDefinition({
		evalId: context.evalId,
		evalFilePath: context.evalFilePath,
		sourceFingerprint: context.sourceFingerprint,
		use: async (evalDef) => await runCase({
			evalDef,
			evalId: context.evalId,
			evalKey: context.evalKey,
			evalCase: context.evalCase,
			globalTraceDisplay: context.globalTraceDisplay,
			globalColumns: config.columns,
			globalDeriveFromTracing: config.deriveFromTracing,
			llmCallsConfig,
			apiCallsConfig,
			globalRemoveDefaultConfig: config.removeDefaultConfig,
			trial: context.trial,
			startTime: context.startTime,
			cacheAdapter: bufferedCacheStore ?? (context.cacheEnabled ? cacheStore : null),
			cacheMode: context.cacheMode,
			moduleIsolation: void 0,
			evalFilePath: context.evalFilePath,
			evalFileRelativePath: context.evalFileRelativePath,
			workspaceRoot: context.workspaceRoot,
			artifactDir: context.artifactDir,
			runId: context.runId
		})
	});
	return {
		caseDetail,
		caseRow: {
			caseId: context.evalCase.id,
			evalId: context.evalId,
			evalKey: context.evalKey,
			caseKey: caseDetail.caseKey,
			tags: caseDetail.tags,
			status: caseRowUpdate.status ?? "pending",
			durationMs: caseRowUpdate.durationMs ?? null,
			cacheHits: caseRowUpdate.cacheHits ?? 0,
			cacheOperations: caseRowUpdate.cacheOperations ?? 0,
			columns: caseRowUpdate.columns ?? {},
			...caseRowUpdate.outputColumnDefs !== void 0 ? { outputColumnDefs: caseRowUpdate.outputColumnDefs } : {},
			trial: context.trial
		},
		pendingCacheWrites: bufferedCacheStore?.getPendingWrites() ?? []
	};
}
async function handleFatalCaseChildError(error) {
	if (fatalErrorReported) return;
	fatalErrorReported = true;
	const message = formatUnknownErrorDetails(error);
	process.exitCode = 1;
	console.error(message);
	sendMessage({
		type: "error",
		message
	});
	await flushMessageSends();
}
function formatUnknownErrorDetails(error) {
	if (error instanceof Error) return error.stack ?? error.message;
	if (typeof error === "string") return error;
	return String(error);
}
function toUnhandledRejectionError(reason) {
	if (reason instanceof Error) return reason;
	return /* @__PURE__ */ new Error(`Unhandled rejection: ${formatUnknownErrorDetails(reason)}`);
}
async function reportFatalCaseChildErrorAndExit(error) {
	try {
		await handleFatalCaseChildError(error);
	} catch (reportError) {
		console.error("Failed to report fatal case child error:");
		console.error(formatUnknownErrorDetails(reportError));
	} finally {
		process.exit(1);
	}
}
installFatalCaseChildErrorHandlers();
process.on("disconnect", () => {
	if (disconnectExpected) return;
	process.exit(1);
});
process.on("message", (message) => {
	if (runStarted) return;
	runStarted = true;
	if (!isCaseChildParentMessage(message)) {
		reportFatalCaseChildErrorAndExit(/* @__PURE__ */ new Error("Case child received an invalid start message"));
		return;
	}
	executeCaseChild(message.context).then(async (result) => {
		sendMessage({
			type: "done",
			result
		});
		await flushMessageSends();
		disconnectExpected = true;
		process.disconnect();
	}).catch(async (error) => {
		await handleFatalCaseChildError(error);
		disconnectExpected = true;
		process.disconnect();
	});
});
//#endregion
export {};
