import { init_providers, resolveModel } from "../../providers/index.js";
import { readAgentMessageContent } from "../memory/agent-message-access.js";
import { complete } from "@earendil-works/pi-ai";
//#region src/agent/service/btw-query.ts
init_providers();
function formatMessagesForBtw(messages) {
	return messages.map((m) => {
		const role = m.role;
		let body = "";
		const raw = readAgentMessageContent(m);
		if (typeof raw === "string") body = raw;
		else if (Array.isArray(raw)) body = raw.filter((c) => c.type === "text").map((c) => c.text || "").join("\n");
		const line = `[${role}]: ${body}`;
		return line.length > 4e3 ? `${line.slice(0, 4e3)}…` : line;
	}).join("\n\n");
}
/** One-shot LLM answer for /btw: transcript as background only; does not persist. */
async function runBtwQuery(opts) {
	const q = opts.question.trim();
	if (!q) return {
		text: "",
		error: "Empty question."
	};
	const messages = await opts.sessionStore.load(opts.sessionKey);
	const modelRef = opts.modelForSession;
	let model;
	try {
		model = resolveModel(modelRef);
	} catch (err) {
		const em = err instanceof Error ? err.message : String(err);
		opts.log.warn({
			err,
			modelRef,
			errorMessage: em
		}, "btwQuery: model resolve failed");
		return {
			text: "",
			error: `Could not resolve model: ${modelRef}`
		};
	}
	const background = formatMessagesForBtw(messages.slice(-40));
	const userMessage = {
		role: "user",
		content: [
			[
				"You are answering an ephemeral /btw side question about the current conversation.",
				"Use the conversation only as background context.",
				"Answer only the side question. Do not continue or complete any unfinished task from the conversation.",
				"Do not use tools, shell, or file writes unless the question explicitly requires a tiny code snippet.",
				"If the question can be answered briefly, answer briefly."
			].join("\n"),
			"",
			"---",
			"Conversation background (read-only):",
			background || "(empty)",
			"",
			"---",
			"Side question:",
			q
		].join("\n"),
		timestamp: Date.now()
	};
	const controller = new AbortController();
	const timeoutId = setTimeout(() => controller.abort(), 9e4);
	try {
		const out = await complete(model, { messages: [userMessage] }, {
			maxTokens: 2048,
			temperature: .4,
			signal: controller.signal
		});
		return { text: (Array.isArray(out.content) ? out.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text || "").join("") : "").trim() };
	} catch (err) {
		const em = err instanceof Error ? err.message : String(err);
		opts.log.warn({
			err,
			sessionKey: opts.sessionKey,
			errorMessage: em
		}, "btwQuery failed");
		return {
			text: "",
			error: em
		};
	} finally {
		clearTimeout(timeoutId);
	}
}
//#endregion
export { runBtwQuery };

//# sourceMappingURL=btw-query.js.map