import { E as state, o as logger } from "./logger-CfDSdx1q.js";
import { r as importModule } from "./esm-B1AS3f6u.js";
import path from "path";
import { Agent, MemorySession, OpenAIConversationsSession, OpenAIResponsesCompactionSession, handoff, retryPolicies, tool } from "@openai/agents";
import { Manifest, SandboxAgent } from "@openai/agents/sandbox";
import { DockerSandboxClient, UnixLocalSandboxClient } from "@openai/agents/sandbox/local";
//#region src/providers/openai/agents-model-settings.ts
function resolveModelSettings(modelSettings) {
	if (!modelSettings) return;
	const retry = modelSettings.retry ? {
		...modelSettings.retry,
		policy: resolveRetryPolicy(modelSettings.retry.policy)
	} : void 0;
	return {
		...modelSettings,
		retry
	};
}
function resolveRetryPolicy(policy) {
	if (!policy) return;
	if (typeof policy === "function") return policy;
	if (typeof policy === "string") switch (policy) {
		case "never": return retryPolicies.never();
		case "providerSuggested": return retryPolicies.providerSuggested();
		case "networkError": return retryPolicies.networkError();
		case "retryAfter": return retryPolicies.retryAfter();
		default: return;
	}
	if ("httpStatus" in policy) return retryPolicies.httpStatus(policy.httpStatus);
	if ("any" in policy) {
		const policies = policy.any.map((nestedPolicy) => resolveRetryPolicy(nestedPolicy)).filter((nestedPolicy) => !!nestedPolicy);
		return policies.length ? retryPolicies.any(...policies) : void 0;
	}
	if ("all" in policy) {
		const policies = policy.all.map((nestedPolicy) => resolveRetryPolicy(nestedPolicy)).filter((nestedPolicy) => !!nestedPolicy);
		return policies.length ? retryPolicies.all(...policies) : void 0;
	}
}
//#endregion
//#region src/providers/openai/agents-loader.ts
/**
* Load agent definition from file path or return inline definition
*/
async function loadAgentDefinition(agentConfig) {
	if (isAgentInstance(agentConfig)) {
		logger.debug("[AgentsLoader] Using provided Agent instance");
		return agentConfig;
	}
	if (typeof agentConfig === "string" && agentConfig.startsWith("file://")) {
		logger.debug("[AgentsLoader] Loading agent from file", { path: agentConfig });
		return await loadAgentFromFile(agentConfig);
	}
	if (agentConfig !== null && typeof agentConfig === "object" && !Array.isArray(agentConfig)) {
		logger.debug("[AgentsLoader] Creating agent from inline definition");
		return await createAgentFromDefinition(agentConfig);
	}
	logger.debug("[AgentsLoader] Invalid agent configuration", {
		type: typeof agentConfig,
		keys: typeof agentConfig === "object" && agentConfig !== null ? Object.keys(agentConfig).slice(0, 5) : void 0
	});
	throw new Error("Invalid agent configuration: expected Agent instance, file:// URL, or inline definition");
}
/**
* Load tools from file path or return inline definitions
*/
async function loadTools(toolsConfig) {
	if (!toolsConfig) return;
	if (typeof toolsConfig === "string" && toolsConfig.startsWith("file://")) {
		logger.debug("[AgentsLoader] Loading tools from file", { path: toolsConfig });
		return await loadToolsFromFile(toolsConfig);
	}
	if (Array.isArray(toolsConfig)) {
		logger.debug("[AgentsLoader] Using inline tool definitions");
		return normalizeTools(toolsConfig);
	}
	logger.debug("[AgentsLoader] Invalid tools configuration", {
		type: typeof toolsConfig,
		isArray: Array.isArray(toolsConfig)
	});
	throw new Error("Invalid tools configuration: expected file:// URL or array");
}
/**
* Load handoffs from file path or return inline definitions
*/
async function loadHandoffs(handoffsConfig) {
	if (!handoffsConfig) return;
	if (typeof handoffsConfig === "string" && handoffsConfig.startsWith("file://")) {
		logger.debug("[AgentsLoader] Loading handoffs from file", { path: handoffsConfig });
		return await loadHandoffsFromFile(handoffsConfig);
	}
	if (Array.isArray(handoffsConfig)) {
		logger.debug("[AgentsLoader] Using inline handoff definitions");
		return normalizeHandoffs(handoffsConfig);
	}
	logger.debug("[AgentsLoader] Invalid handoffs configuration", {
		type: typeof handoffsConfig,
		isArray: Array.isArray(handoffsConfig)
	});
	throw new Error("Invalid handoffs configuration: expected file:// URL or array");
}
/**
* Load input guardrails from file path or return inline definitions
*/
async function loadInputGuardrails(guardrailsConfig) {
	if (!guardrailsConfig) return;
	if (typeof guardrailsConfig === "string" && guardrailsConfig.startsWith("file://")) {
		logger.debug("[AgentsLoader] Loading input guardrails from file", { path: guardrailsConfig });
		return await loadArrayFromFile(guardrailsConfig, "input guardrails");
	}
	if (Array.isArray(guardrailsConfig)) {
		logger.debug("[AgentsLoader] Using inline input guardrails");
		return guardrailsConfig;
	}
	logger.debug("[AgentsLoader] Invalid input guardrails configuration", {
		type: typeof guardrailsConfig,
		isArray: Array.isArray(guardrailsConfig)
	});
	throw new Error("Invalid input guardrails configuration: expected file:// URL or array");
}
/**
* Load output guardrails from file path or return inline definitions
*/
async function loadOutputGuardrails(guardrailsConfig) {
	if (!guardrailsConfig) return;
	if (typeof guardrailsConfig === "string" && guardrailsConfig.startsWith("file://")) {
		logger.debug("[AgentsLoader] Loading output guardrails from file", { path: guardrailsConfig });
		return await loadArrayFromFile(guardrailsConfig, "output guardrails");
	}
	if (Array.isArray(guardrailsConfig)) {
		logger.debug("[AgentsLoader] Using inline output guardrails");
		return guardrailsConfig;
	}
	logger.debug("[AgentsLoader] Invalid output guardrails configuration", {
		type: typeof guardrailsConfig,
		isArray: Array.isArray(guardrailsConfig)
	});
	throw new Error("Invalid output guardrails configuration: expected file:// URL or array");
}
/**
* Load a persistent conversation session from config, file export, or factory.
*/
async function loadSessionDefinition(sessionConfig, context) {
	if (!sessionConfig) return;
	const resolved = await resolveConfigValue(sessionConfig, "session", context);
	if (isSessionInstance(resolved)) return resolved;
	if (isSessionDefinition(resolved)) return createSessionFromDefinition(resolved, context);
	throw new Error("Invalid session configuration: expected Session instance, file:// URL, factory, or supported inline definition");
}
/**
* Load sandbox runtime config from config, file export, or factory.
*/
async function loadSandboxConfig(sandboxConfig, context) {
	if (!sandboxConfig) return;
	const resolved = await resolveConfigValue(sandboxConfig, "sandbox config", context);
	if (!resolved || typeof resolved !== "object") throw new Error("Invalid sandbox configuration: expected SandboxRunConfig, file:// URL, factory, or supported inline definition");
	if (isSandboxDefinition(resolved)) return createSandboxConfigFromDefinition(resolved);
	return normalizeSandboxRunConfig(resolved);
}
/**
* Load agent from file
*/
async function loadAgentFromFile(filePath) {
	const resolvedPath = resolveFilePath(filePath);
	logger.debug("[AgentsLoader] Loading agent from resolved path", { path: resolvedPath });
	try {
		const module = await importModule(resolvedPath);
		const agent = module.default || module;
		if (!isAgentInstance(agent)) throw new Error(`File ${resolvedPath} does not export an Agent instance`);
		return agent;
	} catch (error) {
		logger.error("[AgentsLoader] Failed to load agent from file", {
			path: resolvedPath,
			error
		});
		throw new Error(`Failed to load agent from ${resolvedPath}: ${error}`);
	}
}
/**
* Load tools from file
*/
async function loadToolsFromFile(filePath) {
	return await normalizeTools(await loadArrayFromFile(filePath, "tools")) ?? [];
}
/**
* Load handoffs from file
*/
async function loadHandoffsFromFile(filePath) {
	return await normalizeHandoffs(await loadArrayFromFile(filePath, "handoffs")) ?? [];
}
/**
* Create an Agent instance from an inline definition
*/
async function createAgentFromDefinition(definition) {
	try {
		const tools = await normalizeTools(definition.tools);
		const handoffs = await normalizeHandoffs(definition.handoffs);
		const baseConfig = {
			name: definition.name,
			instructions: definition.instructions,
			prompt: definition.prompt,
			model: definition.model,
			modelSettings: resolveModelSettings(definition.modelSettings),
			handoffDescription: definition.handoffDescription,
			handoffOutputTypeWarningEnabled: definition.handoffOutputTypeWarningEnabled,
			outputType: definition.outputType,
			tools,
			handoffs,
			inputGuardrails: definition.inputGuardrails,
			outputGuardrails: definition.outputGuardrails,
			mcpServers: definition.mcpServers,
			toolUseBehavior: definition.toolUseBehavior,
			resetToolChoice: definition.resetToolChoice
		};
		return definition.type === "sandbox" ? new SandboxAgent({
			...baseConfig,
			defaultManifest: normalizeManifest(definition.defaultManifest),
			baseInstructions: definition.baseInstructions,
			capabilities: definition.capabilities,
			runAs: definition.runAs
		}) : new Agent(baseConfig);
	} catch (error) {
		logger.error("[AgentsLoader] Failed to create agent from definition", {
			name: definition?.name,
			model: definition?.model,
			toolCount: definition?.tools?.length,
			handoffCount: definition?.handoffs?.length,
			error
		});
		throw new Error(`Failed to create agent from definition: ${error}`);
	}
}
/**
* Check if a value is an Agent instance
*/
function isAgentInstance(value) {
	return value instanceof Agent;
}
function isToolInstance(value) {
	return !!value && typeof value === "object" && "type" in value && typeof value.type === "string";
}
function isHandoffInstance(value) {
	return !!value && typeof value === "object" && "agent" in value && "getHandoffAsFunctionTool" in value && typeof value.getHandoffAsFunctionTool === "function";
}
async function normalizeTools(definitions) {
	if (!definitions?.length) return;
	return definitions.map((definition) => {
		if (isToolInstance(definition)) return definition;
		return tool({
			name: definition.name,
			description: definition.description,
			parameters: definition.parameters,
			strict: definition.strict ?? true,
			deferLoading: definition.deferLoading,
			execute: typeof definition.execute === "function" ? definition.execute : async () => definition.execute
		});
	});
}
async function normalizeHandoffs(definitions) {
	if (!definitions?.length) return;
	return Promise.all(definitions.map(async (definition) => {
		if (isAgentInstance(definition) || isHandoffInstance(definition)) return definition;
		const agent = await loadAgentDefinition(definition.agent);
		if (!definition.description) return agent;
		return handoff(agent, { toolDescriptionOverride: definition.description });
	}));
}
async function loadArrayFromFile(filePath, label) {
	const resolvedPath = resolveFilePath(filePath);
	logger.debug(`[AgentsLoader] Loading ${label} from resolved path`, { path: resolvedPath });
	try {
		const module = await importModule(resolvedPath);
		const exported = module.default || module;
		if (!Array.isArray(exported)) throw new Error(`File ${resolvedPath} does not export an array of ${label}`);
		return exported;
	} catch (error) {
		logger.error(`[AgentsLoader] Failed to load ${label} from file`, {
			path: resolvedPath,
			error
		});
		throw new Error(`Failed to load ${label} from ${resolvedPath}: ${error}`);
	}
}
async function loadValueFromFile(filePath, label) {
	const resolvedPath = resolveFilePath(filePath);
	logger.debug(`[AgentsLoader] Loading ${label} from resolved path`, { path: resolvedPath });
	try {
		const module = await importModule(resolvedPath);
		return module.default || module;
	} catch (error) {
		logger.error(`[AgentsLoader] Failed to load ${label} from file`, {
			path: resolvedPath,
			error
		});
		throw new Error(`Failed to load ${label} from ${resolvedPath}: ${error}`);
	}
}
/**
* Resolve file:// path to absolute file system path
*/
function resolveFilePath(filePath) {
	const cleanPath = filePath.replace(/^file:\/\//, "");
	if (path.isAbsolute(cleanPath)) return cleanPath;
	const basePath = state.basePath || process.cwd();
	const resolvedPath = path.resolve(basePath, cleanPath);
	logger.debug("[AgentsLoader] Resolved file path", {
		original: filePath,
		basePath,
		resolved: resolvedPath
	});
	return resolvedPath;
}
async function resolveConfigValue(config, label, context) {
	let resolved = config;
	if (typeof resolved === "string" && resolved.startsWith("file://")) resolved = await loadValueFromFile(resolved, label);
	if (typeof resolved === "function") return await resolved(context);
	return resolved;
}
function isSessionInstance(value) {
	return !!value && typeof value === "object" && typeof value.getSessionId === "function" && typeof value.getItems === "function" && typeof value.addItems === "function" && typeof value.popItem === "function" && typeof value.clearSession === "function";
}
function isSessionDefinition(value) {
	return !!value && typeof value === "object" && "type" in value && [
		"memory",
		"openai-conversations",
		"openai-responses-compaction"
	].includes(String(value.type));
}
async function createSessionFromDefinition(definition, context) {
	switch (definition.type) {
		case "memory": {
			const { type: _type, ...options } = definition;
			return new MemorySession(options);
		}
		case "openai-conversations": {
			const { type: _type, ...options } = definition;
			return new OpenAIConversationsSession(options);
		}
		case "openai-responses-compaction": {
			const { type: _type, underlyingSession, ...options } = definition;
			const resolvedUnderlyingSession = await loadSessionDefinition(underlyingSession, context);
			return new OpenAIResponsesCompactionSession({
				...options,
				...resolvedUnderlyingSession ? { underlyingSession: resolvedUnderlyingSession } : {}
			});
		}
	}
	throw new Error(`Unsupported session type: ${definition.type}`);
}
function isSandboxDefinition(value) {
	return !!value && typeof value === "object" && "type" in value && ["unix-local", "docker"].includes(String(value.type));
}
function createSandboxConfigFromDefinition(definition) {
	const { type, clientOptions, manifest, ...runConfig } = definition;
	const client = type === "docker" ? new DockerSandboxClient(clientOptions) : new UnixLocalSandboxClient(clientOptions);
	return {
		...runConfig,
		client,
		...manifest ? { manifest: normalizeManifest(manifest) } : {}
	};
}
function normalizeSandboxRunConfig(config) {
	return {
		...config,
		...config.manifest ? { manifest: normalizeManifest(config.manifest) } : {}
	};
}
function normalizeManifest(manifest) {
	if (!manifest) return;
	return manifest instanceof Manifest ? manifest : new Manifest(manifest);
}
//#endregion
export { loadAgentDefinition, loadHandoffs, loadInputGuardrails, loadOutputGuardrails, loadSandboxConfig, loadSessionDefinition, loadTools, loadValueFromFile, resolveModelSettings as t };

//# sourceMappingURL=agents-loader-Dfu6h5CD.js.map