import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { resolveAgentTurnTimeoutMs } from "../orchestration/run-agent-turn-with-timeout.js";
import { runXopcEmbeddedTurn } from "./run-turn.js";
import { applyStartupContextToUserMessage } from "../reply/apply-turn-user-enrichment.js";
import { mergeTurnTools, resolveEmbeddedMcpToolsForTurn } from "../mcp/resolve-embedded-mcp-tools.js";
import crypto from "node:crypto";
//#region src/agent/embedded/run-for-session.ts
init_logger();
const log = createLogger("EmbeddedTurnForSession");
async function runEmbeddedTurnForSession(params) {
	const { sessionKey, agentManager, modelManager, sessionStore, userMessage } = params;
	const runId = params.runId ?? crypto.randomUUID();
	await params.beforeTurn?.();
	const agent = agentManager.getOrCreateAgent(sessionKey);
	const mm = modelManager;
	await mm.applyModelForSession(agent, sessionKey);
	const modelRef = String(mm.getModelForSession(sessionKey));
	const model = mm.getResolvedModelForSession(sessionKey);
	const tools = agent.state.tools;
	const systemPrompt = agent.state.systemPrompt ?? "";
	const thinkingLevel = params.thinkingOverride ?? agent.state.thinkingLevel;
	const workspaceDir = agentManager.getResolvedWorkspaceForSession(sessionKey);
	const config = params.getConfig?.();
	await maybeAutoCompactBeforeTurn({
		sessionKey,
		sessionStore,
		agentManager,
		model,
		config,
		onEvent: params.onEvent
	});
	let userMessageForTurn = userMessage;
	if (params.applyStartupContext !== false) userMessageForTurn = await applyStartupContextToUserMessage({
		userMessage,
		sessionKey,
		workspaceDir,
		cfg: config,
		sessionStore,
		startupAction: params.startupAction,
		force: params.forceStartupContext
	});
	return await (async () => {
		const mcpResolved = await resolveEmbeddedMcpToolsForTurn({
			sessionKey,
			workspaceDir,
			cfg: config,
			baseTools: tools,
			cleanupOnTurnEnd: params.cleanupBundleMcpOnRunEnd === true
		});
		const turnTools = mergeTurnTools(tools, mcpResolved.tools);
		try {
			return await runXopcEmbeddedTurn({
				sessionKey,
				runId,
				userMessage: userMessageForTurn,
				model,
				modelRef,
				tools: turnTools,
				systemPrompt,
				thinkingLevel,
				workspaceDir,
				sessionStore,
				timeoutMs: resolveAgentTurnTimeoutMs(config),
				abortSignal: params.abortSignal,
				onEvent: params.onEvent
			});
		} finally {
			await mcpResolved.dispose().catch(() => {});
		}
	})();
}
async function maybeAutoCompactBeforeTurn(opts) {
	const { sessionKey, sessionStore, agentManager, model, config, onEvent } = opts;
	if ((config?.agents?.defaults?.compaction)?.enabled === false) return;
	const contextWindow = model.contextWindow ?? 128e3;
	const messages = await sessionStore.load(sessionKey);
	const prep = sessionStore.prepareCompaction(sessionKey, messages, contextWindow);
	if (!prep.needsCompaction) return;
	log.info({
		sessionKey,
		reason: prep.stats?.reason,
		usagePercent: prep.stats?.usagePercent,
		contextWindow
	}, "Pre-turn auto-compaction triggered");
	onEvent?.({
		type: "compaction",
		status: "started",
		tokensBefore: prep.stats?.usagePercent != null ? Math.round(prep.stats.usagePercent * contextWindow) : void 0
	});
	try {
		const result = await sessionStore.compact(sessionKey, messages, contextWindow);
		if (result.compacted) {
			agentManager.removeAgent(sessionKey);
			log.info({
				sessionKey,
				tokensBefore: result.tokensBefore,
				tokensAfter: result.tokensAfter
			}, "Pre-turn auto-compaction completed");
			onEvent?.({
				type: "compaction",
				status: "completed",
				tokensBefore: result.tokensBefore,
				tokensAfter: result.tokensAfter,
				summary: result.summary.length > 200 ? `${result.summary.slice(0, 200)}…` : result.summary
			});
		} else onEvent?.({
			type: "compaction",
			status: "skipped"
		});
	} catch (err) {
		const errorMessage = err instanceof Error ? err.message : String(err);
		log.warn({
			err,
			sessionKey
		}, `Pre-turn auto-compaction failed: ${errorMessage}`);
		onEvent?.({
			type: "compaction",
			status: "skipped"
		});
	}
}
//#endregion
export { runEmbeddedTurnForSession };

//# sourceMappingURL=run-for-session.js.map