import { buildSessionStartupContextPrelude, shouldApplyStartupContext } from "./startup-context.js";
//#region src/agent/reply/apply-turn-user-enrichment.ts
function extractTextFromUserMessage(message) {
	const content = message.content;
	if (typeof content === "string") return content;
	if (Array.isArray(content)) return content.filter((block) => !!block && typeof block === "object" && block.type === "text").map((block) => block.text).join("");
	return "";
}
function prependTextToUserMessage(message, prefix) {
	const trimmedPrefix = prefix.trim();
	if (!trimmedPrefix) return message;
	const content = message.content;
	if (typeof content === "string") return {
		...message,
		content: `${trimmedPrefix}\n\n${content}`
	};
	if (Array.isArray(content)) {
		const blocks = [...content];
		const firstTextIndex = blocks.findIndex((block) => !!block && typeof block === "object" && block.type === "text");
		if (firstTextIndex >= 0) {
			const first = blocks[firstTextIndex];
			blocks[firstTextIndex] = {
				...first,
				text: `${trimmedPrefix}\n\n${first.text}`
			};
			return {
				...message,
				content: blocks
			};
		}
		return {
			...message,
			content: [{
				type: "text",
				text: trimmedPrefix
			}, ...blocks]
		};
	}
	return {
		...message,
		content: trimmedPrefix
	};
}
async function isBareSessionTurn(sessionStore, sessionKey) {
	try {
		return !(await sessionStore.loadMessages(sessionKey)).some((message) => message.role === "user");
	} catch {
		return true;
	}
}
async function applyStartupContextToUserMessage(params) {
	const action = params.startupAction ?? "new";
	if (!params.force && !await isBareSessionTurn(params.sessionStore, params.sessionKey)) return params.userMessage;
	if (!shouldApplyStartupContext({
		cfg: params.cfg,
		action
	})) return params.userMessage;
	const prelude = buildSessionStartupContextPrelude({
		workspaceDir: params.workspaceDir,
		cfg: params.cfg
	});
	if (!prelude?.trim()) return params.userMessage;
	if (extractTextFromUserMessage(params.userMessage).includes("[Startup context loaded by runtime]")) return params.userMessage;
	return prependTextToUserMessage(params.userMessage, prelude);
}
//#endregion
export { applyStartupContextToUserMessage };

//# sourceMappingURL=apply-turn-user-enrichment.js.map