import { Et as getCaseRowCaseKey, Ot as caseRowSchema, dt as getEvalTitle, nt as updateManualScoreRequestSchema, rt as extractCacheEntries, tt as createRunRequestSchema } from "./runExecution-CjWJUUZ5.mjs";
import { o as stageManualInputFile } from "./cli-CVBSlTD8.mjs";
import "./src-DjOTPnDz.mjs";
import { t as getRunnerInstance } from "./runner-DzDRasWV.mjs";
import { z } from "zod";
import { resultify } from "t-result";
import { readFile } from "node:fs/promises";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { existsSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono";
import { cors } from "hono/cors";
import { logger } from "hono/logger";
import { streamSSE } from "hono/streaming";
import launch from "launch-editor";
import { zValidator } from "@hono/zod-validator";
//#region ../../apps/server/src/routes/assets.ts
const assetsRoutes = new Hono().get("/repo-file", async (c) => {
	const filePath = c.req.query("path");
	if (!filePath) return c.json({ error: "Missing path parameter" }, 400);
	const workspaceRoot = getRunnerInstance().getWorkspaceRoot();
	const resolved = resolve(workspaceRoot, filePath);
	const rel = relative(workspaceRoot, resolved);
	if (rel.startsWith("..") || resolve(rel) !== resolved) return c.json({ error: "Path traversal not allowed" }, 403);
	try {
		const content = await readFile(resolved);
		const mimeType = c.req.query("mimeType") ?? "application/octet-stream";
		return c.body(content, 200, { "Content-Type": mimeType });
	} catch {
		return c.json({ error: "File not found" }, 404);
	}
}).get("/artifacts/:artifactId", async (c) => {
	const artifactId = c.req.param("artifactId");
	const mimeType = c.req.query("mimeType") ?? "application/octet-stream";
	const fileName = c.req.query("fileName");
	const artifactPath = getRunnerInstance().getArtifactPath(artifactId);
	if (!artifactPath) return c.json({ error: "Artifact not found" }, 404);
	try {
		const content = await readFile(artifactPath);
		const headers = { "Content-Type": mimeType };
		if (fileName) headers["Content-Disposition"] = `inline; filename="${fileName}"`;
		return c.body(content, 200, headers);
	} catch {
		return c.json({ error: "Artifact not found" }, 404);
	}
});
//#endregion
//#region ../../apps/server/src/routes/cache.ts
/**
* Cache management routes.
*
* - `GET /` lists persisted cache entries in the workspace.
* - `GET /:namespace/:key` returns the full cache entry (including its
*   recording / return value) for a single namespace+key pair.
* - `DELETE /` clears the entire cache directory.
* - `DELETE /actions/eval?evalKey=<key>` clears entries recorded by saved runs
*   for one exact eval identity.
* - `DELETE /actions/run-history/:runId` clears entries recorded by the run
*   and all earlier saved runs.
* - `DELETE /:namespace` clears one namespace.
* - `DELETE /:namespace/:key` clears a single entry by its key hash.
*/
const cacheRoutes = new Hono().get("/", async (c) => {
	const entries = await getRunnerInstance().listCache();
	return c.json(entries, 200);
}).get("/:namespace/:key", async (c) => {
	const namespace = c.req.param("namespace");
	const key = c.req.param("key");
	const entry = await getRunnerInstance().getCacheEntry(namespace, key);
	if (!entry) return c.json({ error: "cache entry not found" }, 404);
	return c.json(entry, 200);
}).delete("/", async (c) => {
	await getRunnerInstance().clearCache();
	return c.json({ ok: true }, 200);
}).delete("/actions/eval", async (c) => {
	const evalKey = c.req.query("evalKey");
	if (evalKey === void 0 || evalKey.length === 0) return c.json({ error: "evalKey query param is required" }, 400);
	const runner = getRunnerInstance();
	const entries = getCacheEntriesForEvalRuns(runner, evalKey);
	await Promise.all(entries.map((entry) => runner.clearCache({
		namespace: entry.namespace,
		key: entry.key
	})));
	return c.json({
		ok: true,
		deletedEntries: entries.length
	}, 200);
}).delete("/actions/run-history/:runId", async (c) => {
	const runId = c.req.param("runId");
	const runner = getRunnerInstance();
	const entries = getCacheEntriesForRunAndPrevious(runner, runId);
	if (entries === null) return c.json({ error: "Run not found" }, 404);
	await Promise.all(entries.map((entry) => runner.clearCache({
		namespace: entry.namespace,
		key: entry.key
	})));
	return c.json({
		ok: true,
		deletedEntries: entries.length,
		entries
	}, 200);
}).delete("/:namespace", async (c) => {
	const namespace = c.req.param("namespace");
	await getRunnerInstance().clearCache({ namespace });
	return c.json({ ok: true }, 200);
}).delete("/:namespace/:key", async (c) => {
	const namespace = c.req.param("namespace");
	const key = c.req.param("key");
	await getRunnerInstance().clearCache({
		namespace,
		key
	});
	return c.json({ ok: true }, 200);
});
function getCacheEntriesForEvalRuns(runner, evalKey) {
	const entries = /* @__PURE__ */ new Map();
	for (const manifest of runner.getRuns()) {
		const run = runner.getRun(manifest.id);
		if (run === void 0) continue;
		for (const caseRow of run.cases) {
			if (caseRow.evalKey !== evalKey) continue;
			const caseDetail = runner.getCaseDetail(manifest.id, caseRow.caseId);
			if (caseDetail === void 0) continue;
			for (const entry of getStoredCacheEntriesForCase(caseDetail)) entries.set(`${entry.namespace}\u0000${entry.key}`, {
				namespace: entry.namespace,
				key: entry.key
			});
		}
	}
	return [...entries.values()];
}
function getCacheEntriesForRunAndPrevious(runner, runId) {
	const selectedRun = runner.getRun(runId);
	if (selectedRun === void 0) return null;
	const entries = /* @__PURE__ */ new Map();
	for (const manifest of runner.getRuns()) {
		const run = runner.getRun(manifest.id);
		if (run === void 0) continue;
		if (!runIsSelectedOrPrevious(run.manifest, selectedRun.manifest)) continue;
		for (const caseRow of run.cases) {
			const caseDetail = runner.getCaseDetail(manifest.id, caseRow.caseId);
			if (caseDetail === void 0) continue;
			for (const entry of getStoredCacheEntriesForCase(caseDetail)) entries.set(`${entry.namespace}\u0000${entry.key}`, {
				namespace: entry.namespace,
				key: entry.key
			});
		}
	}
	return [...entries.values()];
}
function getStoredCacheEntriesForCase(caseDetail) {
	const entries = extractCacheEntries(caseDetail.trace, caseDetail.cacheRefs);
	for (const scoreTrace of Object.values(caseDetail.scoringTraces ?? {})) entries.push(...extractCacheEntries(scoreTrace.trace, scoreTrace.cacheRefs));
	return entries.filter((entry) => entry.stored);
}
function runIsSelectedOrPrevious(manifest, selectedManifest) {
	if (manifest.id === selectedManifest.id) return true;
	const runSequence = readRunSequence(manifest.shortId);
	const selectedSequence = readRunSequence(selectedManifest.shortId);
	if (runSequence !== void 0 && selectedSequence !== void 0) return runSequence <= selectedSequence;
	const runStartedAt = Date.parse(manifest.startedAt);
	const selectedStartedAt = Date.parse(selectedManifest.startedAt);
	if (!Number.isFinite(runStartedAt) || !Number.isFinite(selectedStartedAt)) return false;
	return runStartedAt <= selectedStartedAt;
}
function readRunSequence(shortId) {
	if (!shortId.startsWith("r")) return void 0;
	const value = Number(shortId.slice(1));
	return Number.isInteger(value) && value >= 0 ? value : void 0;
}
//#endregion
//#region ../../apps/server/src/routes/evals.ts
const evalsRoutes = new Hono().get("/", (c) => {
	const evals = getRunnerInstance().getEvals();
	return c.json(evals, 200);
}).post("/refresh", async (c) => {
	const runner = getRunnerInstance();
	await runner.refreshDiscovery();
	const evals = runner.getEvals();
	return c.json(evals, 200);
}).get("/discovery-issues", (c) => {
	const runner = getRunnerInstance();
	return c.json(runner.getDiscoveryIssues(), 200);
}).get("/events", (c) => {
	const runner = getRunnerInstance();
	return streamSSE(c, async (stream) => {
		const cleanup = runner.subscribeDiscovery((event) => {
			stream.writeSSE({
				event: event.type,
				data: JSON.stringify(event)
			});
		});
		stream.onAbort(() => {
			cleanup();
		});
		await new Promise((resolve) => {
			stream.onAbort(() => {
				resolve();
			});
		});
	});
}).get("/:evalId", (c) => {
	const runner = getRunnerInstance();
	const evalId = c.req.param("evalId");
	const evalData = runner.getEval(evalId);
	if (!evalData) return c.json({ error: "Eval not found" }, 404);
	return c.json(evalData, 200);
}).post("/:evalId/open-in-editor", (c) => {
	const runner = getRunnerInstance();
	const evalId = c.req.param("evalId");
	const evalData = runner.getEval(evalId);
	if (!evalData) return c.json({ error: "Eval not found" }, 404);
	const workspaceRoot = runner.getWorkspaceRoot();
	const absolutePath = resolve(workspaceRoot, evalData.filePath);
	if (!absolutePath.startsWith(workspaceRoot + sep)) return c.json({ error: "Resolved path escapes workspace" }, 400);
	if (!existsSync(absolutePath)) return c.json({ error: "Source file not found on disk" }, 404);
	launch(absolutePath, (_fileName, errorMessage) => {
		if (errorMessage) console.error(`[open-in-editor] failed for ${absolutePath}: ${errorMessage}`);
	});
	return c.json({ ok: true }, 200);
});
//#endregion
//#region ../../apps/server/src/routes/manualInputFiles.ts
const manualInputFilesRoutes = new Hono().post("/", async (c) => {
	const uploaded = (await c.req.parseBody())["file"];
	if (!(uploaded instanceof File)) return c.json({ error: "Missing file upload" }, 400);
	const value = await stageManualInputFile({
		workspaceRoot: getRunnerInstance().getWorkspaceRoot(),
		bytes: new Uint8Array(await uploaded.arrayBuffer()),
		name: uploaded.name,
		mimeType: uploaded.type
	});
	return c.json(value, 201);
});
//#endregion
//#region ../../apps/server/src/routes/runs.ts
const openRunLocationRequestSchema = z.object({
	file: z.string().min(1),
	line: z.number().int().min(1),
	column: z.number().int().min(1)
});
const importQuerySeparatorRegex = /[?#]/;
function escapeRegex(value) {
	return value.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
}
function globToRegex(pattern) {
	const normalized = pattern.replaceAll("\\", "/");
	let regex = "^";
	for (let i = 0; i < normalized.length; i++) {
		const char = normalized[i];
		const next = normalized[i + 1];
		if (char === "*" && next === "*") {
			regex += ".*";
			i++;
		} else if (char === "*") regex += "[^/]*";
		else if (char === "?") regex += "[^/]";
		else regex += escapeRegex(char ?? "");
	}
	return new RegExp(`${regex}$`);
}
function fileMatches(pattern, filePath) {
	const normalizedPattern = pattern.replaceAll("\\", "/");
	if (normalizedPattern === filePath) return true;
	return globToRegex(normalizedPattern).test(filePath);
}
function matchesRunTarget(ev, target) {
	if (target.evalKeys !== void 0 && target.evalKeys.length > 0) {
		if (!target.evalKeys.includes(ev.key)) return false;
	}
	if (target.evalIds !== void 0 && target.evalIds.length > 0) {
		if (!target.evalIds.includes(ev.id)) return false;
	}
	if (target.files !== void 0 && target.files.length > 0) {
		if (!target.files.some((file) => fileMatches(file, ev.filePath))) return false;
	}
	return true;
}
function getRunTargetEvalSummaries(evals, target) {
	return evals.filter((ev) => matchesRunTarget(ev, target)).toSorted((left, right) => left.filePath.localeCompare(right.filePath) || left.id.localeCompare(right.id));
}
function logStartedAppRunEvals(params) {
	const targetEvals = getRunTargetEvalSummaries(params.evals, params.target);
	if (targetEvals.length === 0) return;
	const label = targetEvals.length === 1 ? "eval" : "evals";
	console.info(`[agent-evals] Queued app run ${params.shortId} (${params.runId}) with ${String(targetEvals.length)} ${label}; concurrency ${String(params.concurrency)}:`);
	for (const ev of targetEvals) console.info(`  - ${getEvalTitle(ev)} (${ev.filePath}#${ev.id})`);
}
function getEvalSummaryLabel(evalsByKey, evalsById, evalKey, evalId) {
	const summary = (evalKey === void 0 ? void 0 : evalsByKey.get(evalKey)) ?? evalsById.get(evalId);
	if (summary === void 0) return evalId;
	return `${getEvalTitle(summary)} (${summary.filePath}#${summary.id})`;
}
function getRunCaseLabel(caseId, caseKey) {
	return caseKey === void 0 || caseKey === caseId ? caseId : `${caseId} [${caseKey}]`;
}
function formatCaseStartedLog(params) {
	return [
		`[agent-evals] Run ${params.shortId} started `,
		`${String(params.activeCount)}/${String(params.concurrency)}: `,
		`${params.evalLabel} / ${params.caseLabel}`
	].join("");
}
function formatDurationMs(durationMs) {
	if (durationMs === null) return "";
	if (durationMs < 1e3) return ` in ${String(durationMs)}ms`;
	return ` in ${(durationMs / 1e3).toFixed(1)}s`;
}
function formatRunResultSummary(summary) {
	const cancelled = summary.cancelledCases > 0 ? `, ${String(summary.cancelledCases)} cancelled` : "";
	return `${summary.status}: ${String(summary.totalCases)} total, ${String(summary.passedCases)} passed, ${String(summary.failedCases)} failed, ${String(summary.errorCases)} errors${cancelled}${formatDurationMs(summary.totalDurationMs)}`;
}
function isTerminalRunEvent(eventType) {
	return eventType === "run.finished" || eventType === "run.error" || eventType === "run.cancelled";
}
function subscribeToAppRunResultLog(params) {
	const evalsByKey = new Map(params.evals.map((ev) => [ev.key, ev]));
	const evalsById = new Map(params.evals.map((ev) => [ev.id, ev]));
	const activeCases = /* @__PURE__ */ new Set();
	const loggedStarts = /* @__PURE__ */ new Set();
	let unsubscribe;
	unsubscribe = params.runner.subscribe(params.runId, (event) => {
		if (event.type === "case.started") {
			const parsed = caseRowSchema.safeParse(event.payload);
			if (!parsed.success) return;
			const caseRow = parsed.data;
			const caseKey = `${getCaseRowCaseKey(caseRow)}:${String(caseRow.trial)}`;
			activeCases.add(caseKey);
			if (loggedStarts.has(caseKey)) return;
			loggedStarts.add(caseKey);
			console.info(formatCaseStartedLog({
				shortId: params.shortId,
				activeCount: activeCases.size,
				concurrency: params.concurrency,
				evalLabel: getEvalSummaryLabel(evalsByKey, evalsById, caseRow.evalKey, caseRow.evalId),
				caseLabel: getRunCaseLabel(caseRow.caseId, caseRow.caseKey)
			}));
			return;
		}
		if (event.type === "case.finished") {
			const parsed = caseRowSchema.safeParse(event.payload);
			if (parsed.success) activeCases.delete(`${getCaseRowCaseKey(parsed.data)}:${String(parsed.data.trial)}`);
			return;
		}
		if (!isTerminalRunEvent(event.type)) return;
		unsubscribe?.();
		unsubscribe = void 0;
		const run = params.runner.getRun(params.runId);
		if (run === void 0) {
			console.info(`[agent-evals] Run ${params.shortId} (${params.runId}) finished.`);
			return;
		}
		console.info(`[agent-evals] Run ${params.shortId} (${params.runId}) ${formatRunResultSummary(run.summary)}`);
	});
}
function isInsideWorkspace(path, workspaceRoot) {
	return path === workspaceRoot || path.startsWith(workspaceRoot + sep);
}
function stripImportQuery(path) {
	return path.split(importQuerySeparatorRegex, 1)[0] ?? path;
}
function formatUnknownErrorDetails(error) {
	if (error instanceof Error) return error.stack ?? error.message;
	if (typeof error === "string") return error;
	return String(error);
}
const runsRoutes = new Hono().get("/", (c) => {
	const runs = getRunnerInstance().getRuns();
	return c.json(runs, 200);
}).get("/history", (c) => {
	const runner = getRunnerInstance();
	const runs = runner.getRuns().map((manifest) => runner.getRun(manifest.id)).filter((run) => run !== void 0);
	return c.json(runs, 200);
}).post("/actions/recompute-status/:evalId", async (c) => {
	const evalId = c.req.param("evalId");
	const result = await getRunnerInstance().recomputeStatusesForEval(evalId);
	return c.json(result, 200);
}).post("/actions/clean/:evalId", async (c) => {
	const evalId = c.req.param("evalId");
	const result = await getRunnerInstance().cleanRunsForEval(evalId);
	return c.json(result, 200);
}).post("/", zValidator("json", createRunRequestSchema), async (c) => {
	const body = c.req.valid("json");
	const runner = getRunnerInstance();
	const configReload = runner.getConfigReloadState();
	if (configReload.status !== "idle") return c.json({
		code: "CONFIG_RELOAD_PENDING",
		error: "agent-evals.config.ts changed and the app is reloading before new runs can start.",
		configReload
	}, 409);
	const validation = runner.validateManualInputs(body);
	if (!validation.ok) return c.json({
		error: "Manual input validation failed",
		failures: validation.failures
	}, 400);
	const evalsForTerminalLog = runner.getEvals();
	const concurrency = runner.getConfiguredConcurrency();
	const runResult = await resultify(() => runner.startRun(body));
	if (runResult.error) return c.json({
		error: "Failed to start run",
		message: formatUnknownErrorDetails(runResult.error)
	}, 500);
	logStartedAppRunEvals({
		runId: runResult.value.manifest.id,
		shortId: runResult.value.manifest.shortId,
		evals: evalsForTerminalLog,
		target: body.target,
		concurrency
	});
	subscribeToAppRunResultLog({
		runner,
		runId: runResult.value.manifest.id,
		shortId: runResult.value.manifest.shortId,
		evals: evalsForTerminalLog,
		concurrency
	});
	return c.json(runResult.value, 201);
}).post("/actions/open-location", zValidator("json", openRunLocationRequestSchema), (c) => {
	const body = c.req.valid("json");
	const workspaceRoot = getRunnerInstance().getWorkspaceRoot();
	const file = stripImportQuery(body.file);
	const absolutePath = isAbsolute(file) ? resolve(file) : resolve(workspaceRoot, file);
	if (!isInsideWorkspace(absolutePath, workspaceRoot)) return c.json({ error: "Resolved path escapes workspace" }, 400);
	if (!existsSync(absolutePath)) return c.json({ error: "Source file not found on disk" }, 404);
	const target = `${absolutePath}:${String(body.line)}:${String(body.column)}`;
	launch(target, (_fileName, errorMessage) => {
		if (errorMessage) console.error(`[open-in-editor] failed for ${target}: ${errorMessage}`);
	});
	return c.json({ ok: true }, 200);
}).get("/:runId", (c) => {
	const runId = c.req.param("runId");
	const run = getRunnerInstance().getRun(runId);
	if (!run) return c.json({ error: "Run not found" }, 404);
	return c.json(run, 200);
}).post("/:runId/cancel", async (c) => {
	const runId = c.req.param("runId");
	await getRunnerInstance().cancelRun(runId);
	return c.json({ ok: true }, 200);
}).post("/:runId/promote", async (c) => {
	const runId = c.req.param("runId");
	const result = await getRunnerInstance().promoteRun(runId);
	if (!("run" in result)) return c.json({
		error: "Run not found",
		promoted: false
	}, 404);
	return c.json(result, 200);
}).delete("/:runId", async (c) => {
	const runId = c.req.param("runId");
	const result = await getRunnerInstance().deleteRun(runId);
	if (!result.deleted) return c.json({
		error: "Run not found or still running",
		deleted: false
	}, 404);
	return c.json(result, 200);
}).get("/:runId/cases/:caseId", (c) => {
	const runId = c.req.param("runId");
	const caseId = c.req.param("caseId");
	const caseDetail = getRunnerInstance().getCaseDetail(runId, caseId);
	if (!caseDetail) return c.json({ error: "Case not found" }, 404);
	return c.json(caseDetail, 200);
}).post("/:runId/cases/:caseId/actions/recalculate-derived-attributes", async (c) => {
	const runId = c.req.param("runId");
	const caseId = c.req.param("caseId");
	const result = await getRunnerInstance().recalculateDerivedAttributesForCase({
		runId,
		caseId
	});
	if (!result.updated) return c.json({
		error: result.reason,
		updated: false
	}, 404);
	return c.json(result, 200);
}).patch("/:runId/cases/:caseId/manual-scores/:scoreKey", zValidator("json", updateManualScoreRequestSchema), async (c) => {
	const runId = c.req.param("runId");
	const caseId = c.req.param("caseId");
	const scoreKey = c.req.param("scoreKey");
	const body = c.req.valid("json");
	const result = await getRunnerInstance().updateManualScore({
		runId,
		caseId,
		scoreKey,
		value: body.value
	});
	if (!result.updated) return c.json({ error: result.reason }, 404);
	return c.json(result, 200);
}).get("/:runId/events", (c) => {
	const runId = c.req.param("runId");
	const runner = getRunnerInstance();
	return streamSSE(c, async (stream) => {
		const writeEvent = async (event) => {
			await stream.writeSSE({
				event: event.type,
				data: JSON.stringify(event)
			});
		};
		const cleanup = runner.subscribe(runId, (event) => {
			writeEvent(event);
		});
		stream.onAbort(() => {
			cleanup();
		});
		const initial = runner.getRun(runId);
		if (initial) {
			const status = initial.manifest.status;
			if (status === "completed" || status === "cancelled" || status === "error") {
				const now = (/* @__PURE__ */ new Date()).toISOString();
				for (const caseRow of initial.cases) await writeEvent({
					type: "case.updated",
					runId,
					timestamp: now,
					payload: caseRow
				});
				await writeEvent({
					type: "run.summary",
					runId,
					timestamp: now,
					payload: initial.summary
				});
				const terminalType = status === "completed" ? "run.finished" : status === "cancelled" ? "run.cancelled" : "run.error";
				await writeEvent({
					type: terminalType,
					runId,
					timestamp: now,
					payload: terminalType === "run.error" ? { message: initial.summary.errorMessage ?? "Run ended with error" } : initial.summary
				});
				return;
			}
		}
		await new Promise((resolve) => {
			const checkInterval = setInterval(() => {
				const run = runner.getRun(runId);
				if (!run || run.manifest.status === "completed" || run.manifest.status === "cancelled" || run.manifest.status === "error") {
					clearInterval(checkInterval);
					resolve();
				}
			}, 250);
		});
	});
});
//#endregion
//#region ../../apps/server/src/packageManager.ts
const packageJsonSchema = z.object({ packageManager: z.string().optional() });
const packageManagerNameSeparatorRegex = /[ @/]/;
function normalizePackageManager(value) {
	if (!value) return void 0;
	const name = value.split(packageManagerNameSeparatorRegex)[0];
	if (name === "npm" || name === "pnpm" || name === "yarn" || name === "bun") return name;
}
async function readPackageManagerField(workspaceRoot) {
	const packageJson = await resultify(() => readFile(join(workspaceRoot, "package.json"), "utf8"));
	if (packageJson.error) return void 0;
	const parsedJson = resultify(() => JSON.parse(packageJson.value));
	if (parsedJson.error) return void 0;
	const parsedPackage = resultify(() => packageJsonSchema.parse(parsedJson.value));
	if (parsedPackage.error) return void 0;
	return normalizePackageManager(parsedPackage.value.packageManager);
}
function detectFromLockfile(workspaceRoot) {
	if (existsSync(join(workspaceRoot, "pnpm-lock.yaml"))) return "pnpm";
	if (existsSync(join(workspaceRoot, "yarn.lock"))) return "yarn";
	if (existsSync(join(workspaceRoot, "bun.lock")) || existsSync(join(workspaceRoot, "bun.lockb"))) return "bun";
	if (existsSync(join(workspaceRoot, "package-lock.json"))) return "npm";
}
/** Detect the package manager users should use when running workspace CLI commands. */
async function detectWorkspacePackageManager(workspaceRoot) {
	return await readPackageManagerField(workspaceRoot) ?? detectFromLockfile(workspaceRoot) ?? normalizePackageManager(process.env.npm_config_user_agent) ?? "pnpm";
}
//#endregion
//#region ../../apps/server/src/routes/workspace.ts
const workspaceRoutes = new Hono().get("/", async (c) => {
	const runner = getRunnerInstance();
	const packageManager = await detectWorkspacePackageManager(runner.getWorkspaceRoot());
	return c.json({
		workspaceRoot: runner.getWorkspaceRoot(),
		packageManager,
		llmCalls: runner.getLlmCallsConfig(),
		apiCalls: runner.getApiCallsConfig(),
		configReload: runner.getConfigReloadState()
	}, 200);
});
//#endregion
//#region ../../apps/server/src/app.ts
const baseApp = new Hono();
baseApp.use("/*", cors());
if (process.env.PORT === "5100") baseApp.use("/*", logger());
baseApp.route("/api/evals", evalsRoutes).route("/api/runs", runsRoutes).route("/api/manual-input-files", manualInputFilesRoutes).route("/api/cache", cacheRoutes).route("/api/workspace", workspaceRoutes).route("/api", assetsRoutes);
const serverDir = dirname(fileURLToPath(import.meta.url));
const webDist = process.env.AGENT_EVALS_WEB_DIST ? resolve(process.env.AGENT_EVALS_WEB_DIST) : resolve(serverDir, "../../web/dist");
if (existsSync(webDist)) {
	baseApp.use("/*", serveStatic({ root: webDist }));
	baseApp.get("/*", serveStatic({
		root: webDist,
		path: "index.html"
	}));
} else baseApp.get("/*", (c) => c.text(`Web UI not built. Run "pnpm --filter @agent-evals/web build" first.\nExpected: ${webDist}`, 503));
const app = baseApp;
//#endregion
export { app };
