import { At as evalStatsConfigSchema, L as configureEvalRunLogs, Mt as evalChartsConfigSchema, Nt as columnDefSchema, Tt as buildEvalKey, bt as runManifestSchema, jt as manualInputDescriptorSchema, kt as evalStatAggregateSchema, l as registerAgentEvalsPackageResolutionHooks, p as loadConfig, tt as createRunRequestSchema, v as createFsCacheStore, xt as runSummarySchema, y as getCacheRetentionOptions } from "./runExecution-CjWJUUZ5.mjs";
import { S as parseEvalDiscovery, m as persistRunState, r as getTargetEvals$1, t as executeRun } from "./runOrchestration-DE2TFAS6.mjs";
import { z } from "zod";
import { readFile } from "node:fs/promises";
import { relative } from "node:path";
import { createHash } from "node:crypto";
import { glob } from "glob";
//#region ../runner/src/runChild.ts
const evalMetaSchema = z.object({
	key: z.string(),
	id: z.string(),
	title: z.string().optional(),
	filePath: z.string(),
	tags: z.array(z.string()).default([]),
	sourceFilePath: z.string(),
	sourceFingerprint: z.string().nullable(),
	columnDefs: z.array(columnDefSchema),
	caseCount: z.number().nullable(),
	caseIds: z.array(z.string()).optional(),
	stats: evalStatsConfigSchema.optional(),
	defaultStatAggregate: evalStatAggregateSchema.optional(),
	charts: evalChartsConfigSchema.optional(),
	manualInputDescriptor: manualInputDescriptorSchema.optional(),
	requiresManualInput: z.boolean().optional()
});
const runChildContextSchema = z.object({
	request: createRunRequestSchema,
	workspaceRoot: z.string(),
	runDir: z.string(),
	manifest: runManifestSchema,
	summary: runSummarySchema,
	evals: z.array(evalMetaSchema).optional()
});
let activeContext;
let fatalErrorReported = false;
let disconnectExpected = 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 run child message:");
					console.error(formatUnknownErrorDetails(error));
				}
				resolvePromise();
			});
		} catch (error) {
			console.error("Failed to send run 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 installFatalRunChildErrorHandlers() {
	process.once("uncaughtException", (error) => {
		reportFatalRunChildErrorAndExit(error);
	});
	process.once("unhandledRejection", (reason) => {
		reportFatalRunChildErrorAndExit(toUnhandledRejectionError(reason));
	});
}
function getSourceFingerprint(source) {
	return createHash("sha256").update(source).digest("hex");
}
function getConfiguredConcurrency(configConcurrency) {
	if (typeof configConcurrency !== "number" || !Number.isFinite(configConcurrency)) return 1;
	return Math.max(1, Math.floor(configConcurrency));
}
function getTargetEvals(params) {
	return getTargetEvals$1({
		evals: params.evals.values(),
		request: params.request
	});
}
function toWorkspaceRelativePath(params) {
	return relative(params.workspaceRoot, params.filePath).replaceAll("\\", "/");
}
async function discoverRunEvals(params) {
	const discovered = [];
	for (const pattern of params.config.include) {
		const files = await glob(pattern, {
			cwd: params.workspaceRoot,
			absolute: true
		});
		discovered.push(...files);
	}
	const evals = /* @__PURE__ */ new Map();
	for (const filePath of discovered) {
		const source = await readFile(filePath, "utf-8");
		const sourceFingerprint = getSourceFingerprint(source);
		const metas = parseEvalDiscovery(filePath, source).metas;
		for (const meta of metas) {
			const relativeFilePath = toWorkspaceRelativePath({
				filePath: meta.filePath,
				workspaceRoot: params.workspaceRoot
			});
			const key = buildEvalKey({
				filePath: relativeFilePath,
				evalId: meta.id
			});
			evals.set(key, {
				key,
				id: meta.id,
				title: meta.title,
				filePath: relativeFilePath,
				tags: [],
				sourceFilePath: meta.filePath,
				sourceFingerprint,
				columnDefs: [],
				caseCount: null
			});
		}
	}
	return [...evals.values()].toSorted((a, b) => a.filePath.localeCompare(b.filePath) || a.id.localeCompare(b.id));
}
async function readContext(contextPath) {
	if (contextPath === void 0) throw new Error("Missing run child context path");
	return runChildContextSchema.parse(JSON.parse(await readFile(contextPath, "utf-8")));
}
async function main() {
	process.on("disconnect", () => {
		if (disconnectExpected) return;
		process.exit(1);
	});
	const context = await readContext(process.argv[2]);
	activeContext = context;
	process.chdir(context.workspaceRoot);
	registerAgentEvalsPackageResolutionHooks();
	const config = await loadConfig();
	configureEvalRunLogs({ captureConsole: config.runLogs?.captureConsole !== false });
	const cacheRetentionOptions = getCacheRetentionOptions(config.cache);
	const cacheStore = createFsCacheStore({
		workspaceRoot: context.workspaceRoot,
		dir: config.cache?.dir,
		maxEntriesPerNamespace: cacheRetentionOptions.maxEntriesPerNamespace,
		maxEntriesByNamespace: cacheRetentionOptions.maxEntriesByNamespace,
		lastAccessedAtUpdateIntervalMs: config.cache?.lastAccessedAtUpdateIntervalMs
	});
	const evalMetas = await discoverRunEvals({
		config,
		workspaceRoot: context.workspaceRoot
	});
	const evals = new Map(evalMetas.map((evalMeta) => [evalMeta.key, evalMeta]));
	const lastRunStatusMap = /* @__PURE__ */ new Map();
	const latestRunInfoMap = /* @__PURE__ */ new Map();
	await executeRun({
		runState: {
			runDir: context.runDir,
			manifest: context.manifest,
			summary: context.summary,
			cases: [],
			caseDetails: /* @__PURE__ */ new Map(),
			listeners: /* @__PURE__ */ new Set()
		},
		request: context.request,
		runDir: context.runDir,
		config,
		cacheStore,
		lastRunStatusMap,
		latestRunInfoMap,
		emitEvent(_runState, event) {
			if (event.type === "case.finished") return;
			sendMessage({
				type: "event",
				event
			});
		},
		emitDiscoveryEvent() {},
		workspaceRoot: context.workspaceRoot,
		getSourceFingerprint,
		getConfiguredConcurrency: () => getConfiguredConcurrency(config.concurrency),
		getSortedEvalMetas: () => [...evals.values()].toSorted((a, b) => a.filePath.localeCompare(b.filePath) || a.id.localeCompare(b.id)),
		getTargetEvals: (request) => getTargetEvals({
			evals,
			request
		}),
		onCaseFinished(caseDetail, caseRow) {
			sendMessage({
				type: "case.finished",
				caseDetail,
				caseRow
			});
		}
	});
	sendMessage({
		type: "done",
		evals: [...evals.values()]
	});
	await flushMessageSends();
}
async function handleFatalRunChildError(error) {
	if (fatalErrorReported) return;
	fatalErrorReported = true;
	const message = formatUnknownErrorDetails(error);
	process.exitCode = 1;
	console.error(message);
	if (activeContext === void 0) return;
	const endedAt = (/* @__PURE__ */ new Date()).toISOString();
	await persistRunState({
		runDir: activeContext.runDir,
		manifest: {
			...activeContext.manifest,
			status: "error",
			endedAt
		},
		summary: {
			...activeContext.summary,
			status: "error",
			errorMessage: message
		},
		cases: [],
		caseDetails: /* @__PURE__ */ new Map(),
		listeners: /* @__PURE__ */ new Set()
	});
	sendMessage({
		type: "event",
		event: {
			type: "run.error",
			runId: activeContext.manifest.id,
			timestamp: endedAt,
			payload: { 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 reportFatalRunChildErrorAndExit(error) {
	try {
		await handleFatalRunChildError(error);
	} catch (reportError) {
		console.error("Failed to report fatal run child error:");
		console.error(formatUnknownErrorDetails(reportError));
	} finally {
		process.exit(1);
	}
}
installFatalRunChildErrorHandlers();
await main().catch(async (error) => {
	await handleFatalRunChildError(error);
});
await flushMessageSends();
disconnectExpected = true;
process.disconnect();
//#endregion
export {};
