/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { HistoryService } from '../services/history/HistoryService.js';
import { createProviderAdapterFromManager, createTelemetryAdapterFromConfig, } from './runtimeAdapters.js';
import { createAgentRuntimeContext } from './createAgentRuntimeContext.js';
import { createContentGenerator, } from '../core/contentGenerator.js';
const defaultContentGeneratorFactory = (contentConfig, config, sessionId) => createContentGenerator(contentConfig, config, sessionId);
import { normalizeToolName } from '../tools/toolNameUtils.js';
function buildToolGovernance(profile) {
    const allowedRaw = Array.isArray(profile.settings.tools?.allowed)
        ? profile.settings.tools?.allowed
        : undefined;
    const disabledRaw = Array.isArray(profile.settings.tools?.disabled)
        ? profile.settings.tools?.disabled
        : undefined;
    const excludedRaw = profile.config.getExcludeTools?.() ?? [];
    return {
        allowed: new Set((allowedRaw ?? []).map((tool) => normalizeToolName(tool) || tool)),
        disabled: new Set((disabledRaw ?? []).map((tool) => normalizeToolName(tool) || tool)),
        excluded: new Set(excludedRaw.map((tool) => normalizeToolName(tool) || tool)),
    };
}
function isToolPermitted(toolName, governance) {
    const canonical = normalizeToolName(toolName) || toolName;
    if (governance.excluded.has(canonical)) {
        return false;
    }
    if (governance.disabled.has(canonical)) {
        return false;
    }
    if (governance.allowed.size > 0 && !governance.allowed.has(canonical)) {
        return false;
    }
    return true;
}
function createFilteredToolRegistryView(registry, governance) {
    if (!registry) {
        return {
            listToolNames: () => [],
            getToolMetadata: () => undefined,
        };
    }
    const getTools = () => registry.getAllTools();
    return {
        listToolNames: () => getTools()
            .filter((tool) => isToolPermitted(tool.name, governance))
            .map((tool) => tool.name),
        getToolMetadata: (name) => {
            if (!isToolPermitted(name, governance)) {
                return undefined;
            }
            const tool = getTools().find((candidate) => candidate.name === name);
            if (!tool) {
                return undefined;
            }
            const schema = tool
                .schema;
            const description = typeof schema?.description === 'string'
                ? schema.description
                : typeof tool.description === 'string'
                    ? tool.description
                    : '';
            const parameterSchema = schema?.parameters ??
                schema
                    ?.parametersJsonSchema;
            return {
                name: tool.name ?? name,
                description,
                parameterSchema,
            };
        },
    };
}
export async function loadAgentRuntime(options) {
    const { profile, overrides = {}, signal } = options;
    if (!profile) {
        throw new Error('AgentRuntimeLoader requires a profile option.');
    }
    if (signal?.aborted) {
        const error = new Error('Runtime load aborted');
        error.name = 'AbortError';
        throw error;
    }
    const history = overrides.historyService ?? new HistoryService();
    const providerAdapter = overrides.providerAdapter ??
        createProviderAdapterFromManager(profile.providerManager ?? profile.config.getProviderManager?.());
    const telemetryAdapter = overrides.telemetryAdapter ??
        createTelemetryAdapterFromConfig(profile.config);
    const governance = buildToolGovernance(profile);
    const toolsView = overrides.toolsView ??
        createFilteredToolRegistryView(profile.toolRegistry ?? profile.config.getToolRegistry?.(), governance);
    const runtimeContext = createAgentRuntimeContext({
        state: profile.state,
        settings: profile.settings,
        provider: providerAdapter,
        telemetry: telemetryAdapter,
        tools: toolsView,
        history,
        providerRuntime: profile.providerRuntime,
    });
    let contentGenerator;
    if (overrides.contentGenerator) {
        contentGenerator = overrides.contentGenerator;
    }
    else {
        const contentConfig = profile.contentGeneratorConfig;
        if (!contentConfig) {
            throw new Error('AgentRuntimeLoader requires contentGeneratorConfig when no contentGenerator override is supplied.');
        }
        const factory = overrides.contentGeneratorFactory ?? defaultContentGeneratorFactory;
        contentGenerator = await factory(contentConfig, profile.config, profile.state.sessionId);
    }
    return {
        runtimeContext,
        history,
        providerAdapter,
        telemetryAdapter,
        toolsView,
        contentGenerator,
        toolRegistry: profile.toolRegistry,
        settingsSnapshot: profile.settings,
    };
}
//# sourceMappingURL=AgentRuntimeLoader.js.map