"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    formatErrorMessage: ()=>formatErrorMessage,
    parseStructuredParams: ()=>parseStructuredParams,
    validateStructuredParams: ()=>validateStructuredParams,
    validationAPIs: ()=>validationAPIs,
    executeAction: ()=>executeAction,
    dataExtractionAPIs: ()=>dataExtractionAPIs,
    noReplayAPIs: ()=>noReplayAPIs
});
const ai_model_namespaceObject = require("@midscene/core/ai-model");
const yaml_namespaceObject = require("@midscene/core/yaml");
const dataExtractionAPIs = [
    'aiQuery',
    'aiBoolean',
    'aiNumber',
    'aiString',
    'aiAsk'
];
const validationAPIs = [
    'aiAssert',
    'aiWaitFor'
];
const noReplayAPIs = [
    ...dataExtractionAPIs,
    ...validationAPIs
];
const formatErrorMessage = (e)=>{
    const errorMessage = e?.message || '';
    if (errorMessage.includes('of different extension')) return 'Conflicting extension detected. Please disable the suspicious plugins and refresh the page. Guide: https://midscenejs.com/quick-experience.html#faq';
    if (errorMessage.includes('NOT_IMPLEMENTED_AS_DESIGNED')) return 'Further actions cannot be performed in the current environment';
    return errorMessage || 'Unknown error';
};
async function parseStructuredParams(action, params, options = {}) {
    if (!action?.paramSchema || !('shape' in action.paramSchema)) return [
        params.prompt || '',
        options
    ];
    const schema = action.paramSchema;
    const keys = schema && 'shape' in schema ? Object.keys(schema.shape) : [];
    const { deviceOptions: _, ...optionsWithoutDeviceOptions } = options;
    const paramObj = {
        ...optionsWithoutDeviceOptions,
        ...options.deviceOptions || {}
    };
    keys.forEach((key)=>{
        if (void 0 !== params[key] && null !== params[key] && '' !== params[key]) paramObj[key] = params[key];
    });
    if (schema) {
        const locatorFieldKeys = (0, ai_model_namespaceObject.findAllMidsceneLocatorField)(schema);
        locatorFieldKeys.forEach((locateKey)=>{
            const locatePrompt = params[locateKey];
            if (locatePrompt && 'string' == typeof locatePrompt) {
                const detailedLocateParam = (0, yaml_namespaceObject.buildDetailedLocateParam)(locatePrompt, {
                    deepLocate: options.deepLocate,
                    cacheable: true
                });
                if (detailedLocateParam) paramObj[locateKey] = detailedLocateParam;
            }
        });
    }
    return [
        paramObj
    ];
}
function validateStructuredParams(value, action) {
    if (!value.params) return {
        valid: false,
        errorMessage: 'Parameters are required'
    };
    if (!action?.paramSchema) return {
        valid: true
    };
    try {
        const paramsForValidation = {
            ...value.params
        };
        const schema = action.paramSchema;
        if (schema) {
            const locatorFieldKeys = (0, ai_model_namespaceObject.findAllMidsceneLocatorField)(schema);
            locatorFieldKeys.forEach((key)=>{
                if ('string' == typeof paramsForValidation[key]) paramsForValidation[key] = {
                    midscene_location_field_flag: true,
                    prompt: paramsForValidation[key],
                    center: [
                        0,
                        0
                    ],
                    rect: {
                        left: 0,
                        top: 0,
                        width: 0,
                        height: 0
                    }
                };
            });
        }
        action.paramSchema?.parse(paramsForValidation);
    } catch (error) {
        const zodError = error;
        if (zodError.errors && zodError.errors.length > 0) {
            const errorMessages = zodError.errors.filter((err)=>{
                const path = err.path.join('.');
                return !path.includes('center') && !path.includes('rect') && !path.includes('midscene_location_field_flag');
            }).map((err)=>{
                const field = err.path.join('.');
                return `${field}: ${err.message}`;
            });
            if (errorMessages.length > 0) return {
                valid: false,
                errorMessage: `Validation error: ${errorMessages.join(', ')}`
            };
        } else {
            const errorMsg = error instanceof Error ? error.message : 'Unknown validation error';
            return {
                valid: false,
                errorMessage: `Parameter validation failed: ${errorMsg}`
            };
        }
    }
    return {
        valid: true
    };
}
async function executeAction(activeAgent, actionType, actionSpace, value, options) {
    const canForwardDeepThink = 'aiAct' === actionType || 'runMarkdown' === actionType;
    if (!canForwardDeepThink && void 0 !== options.deepThink) console.warn('[Playground] Received deepThink in non-aiAct action options. deepThink is expected to be used with aiAct/runMarkdown during migration.', {
        actionType,
        requestId: options.requestId,
        options
    });
    const action = actionSpace?.find((a)=>a.interfaceAlias === actionType || a.name === actionType);
    if (action && 'function' == typeof activeAgent.callActionInActionSpace) if (value.params) {
        const parsedParams = await parseStructuredParams(action, value.params, options);
        return await activeAgent.callActionInActionSpace(action.name, parsedParams[0]);
    } else {
        const detailedLocateParam = value.prompt ? (0, yaml_namespaceObject.buildDetailedLocateParam)(value.prompt, {
            deepLocate: options.deepLocate,
            cacheable: true
        }) : void 0;
        const { deviceOptions: _, ...optionsWithoutDeviceOptions } = options;
        const actionParams = {
            locate: detailedLocateParam,
            ...optionsWithoutDeviceOptions,
            ...options.deviceOptions || {}
        };
        return await activeAgent.callActionInActionSpace(action.name, actionParams);
    }
    {
        const prompt = value.prompt;
        if ('aiAssert' === actionType) {
            const { pass, thought } = await activeAgent?.aiAssert?.(prompt || '', void 0, {
                keepRawResponse: true,
                ...options
            }) || {};
            return {
                pass: pass || false,
                thought: thought || ''
            };
        }
        if (activeAgent && 'function' == typeof activeAgent[actionType]) return await activeAgent[actionType](prompt, options);
        throw new Error(`Unknown action type: ${actionType}`);
    }
}
exports.dataExtractionAPIs = __webpack_exports__.dataExtractionAPIs;
exports.executeAction = __webpack_exports__.executeAction;
exports.formatErrorMessage = __webpack_exports__.formatErrorMessage;
exports.noReplayAPIs = __webpack_exports__.noReplayAPIs;
exports.parseStructuredParams = __webpack_exports__.parseStructuredParams;
exports.validateStructuredParams = __webpack_exports__.validateStructuredParams;
exports.validationAPIs = __webpack_exports__.validationAPIs;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "dataExtractionAPIs",
    "executeAction",
    "formatErrorMessage",
    "noReplayAPIs",
    "parseStructuredParams",
    "validateStructuredParams",
    "validationAPIs"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});

//# sourceMappingURL=common.js.map