//#region src/agent/orchestration/run-agent-turn-with-timeout.ts
/** Minimum per-turn timeout (1 minute). */
const MIN_AGENT_TURN_TIMEOUT_MS = 6e4;
/** Maximum per-turn timeout (4 hours), aligned with `maxTaskDurationMs` schema cap. */
const MAX_AGENT_TURN_TIMEOUT_MS = 14400 * 1e3;
/** Default when `agents.defaults.maxTaskDurationMs` is unset (30 minutes). */
const DEFAULT_AGENT_TURN_TIMEOUT_MS = 1800 * 1e3;
/**
* Effective turn timeout from config or default.
* Uses `agents.defaults.maxTaskDurationMs` when set (clamped to schema bounds).
*/
function resolveAgentTurnTimeoutMs(config) {
	const raw = config?.agents?.defaults?.maxTaskDurationMs;
	if (typeof raw === "number" && Number.isFinite(raw)) return Math.min(MAX_AGENT_TURN_TIMEOUT_MS, Math.max(MIN_AGENT_TURN_TIMEOUT_MS, Math.floor(raw)));
	return DEFAULT_AGENT_TURN_TIMEOUT_MS;
}
function isAgentTurnTimeoutError(err) {
	return err instanceof Error && err.message.startsWith("Agent turn timed out after");
}
async function runAgentTurnWithTimeout(agent, runTurn, timeoutMs) {
	let timeoutId;
	const timeoutPromise = new Promise((_, reject) => {
		timeoutId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Agent turn timed out after ${timeoutMs / 1e3}s`)), timeoutMs);
	});
	try {
		await Promise.race([runTurn().finally(() => {
			if (timeoutId !== void 0) clearTimeout(timeoutId);
		}), timeoutPromise]);
	} catch (err) {
		if (isAgentTurnTimeoutError(err)) {
			agent.abort();
			await agent.waitForIdle();
		}
		throw err;
	}
}
//#endregion
export { DEFAULT_AGENT_TURN_TIMEOUT_MS, MAX_AGENT_TURN_TIMEOUT_MS, MIN_AGENT_TURN_TIMEOUT_MS, isAgentTurnTimeoutError, resolveAgentTurnTimeoutMs, runAgentTurnWithTimeout };

//# sourceMappingURL=run-agent-turn-with-timeout.js.map