import AjvModule from 'ajv';
import addFormatsModule from 'ajv-formats';
const Ajv = (AjvModule.default ??
    AjvModule);
const addFormats = (addFormatsModule
    .default ?? addFormatsModule);
const runtimeGlobals = globalThis;
const isBrowserExtension = runtimeGlobals.chrome?.runtime?.id !== undefined;
let ajv = null;
if (!isBrowserExtension) {
    try {
        ajv = new Ajv({
            allErrors: true,
            coerceTypes: true,
            strict: false
        });
        addFormats(ajv);
    }
    catch {
        console.warn('AJV validation disabled due to CSP restrictions');
    }
}
export function validateToolArguments(tool, toolCall) {
    if (!ajv || isBrowserExtension) {
        return toolCall.arguments;
    }
    const validate = ajv.compile(tool.parameters);
    const args = structuredClone(toolCall.arguments);
    if (validate(args)) {
        return args;
    }
    const errors = validate.errors
        ?.map((err) => {
        const path = err.instancePath
            ? err.instancePath.substring(1)
            : err.params.missingProperty || 'root';
        return `  - ${path}: ${err.message}`;
    })
        .join('\n') || 'Unknown validation error';
    throw new Error(`Validation failed for tool "${toolCall.name}":\n${errors}\n\nReceived arguments:\n${JSON.stringify(toolCall.arguments, null, 2)}`);
}
//# sourceMappingURL=validation.js.map