"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__, {
    LocalExecutionAdapter: ()=>LocalExecutionAdapter
});
const core_namespaceObject = require("@midscene/core");
const env_namespaceObject = require("@midscene/shared/env");
const utils_namespaceObject = require("@midscene/shared/utils");
const external_common_js_namespaceObject = require("../common.js");
const external_runtime_metadata_js_namespaceObject = require("../runtime-metadata.js");
const external_base_js_namespaceObject = require("./base.js");
function _define_property(obj, key, value) {
    if (key in obj) Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
    });
    else obj[key] = value;
    return obj;
}
class LocalExecutionAdapter extends external_base_js_namespaceObject.BasePlaygroundAdapter {
    get id() {
        return this._id;
    }
    onDumpUpdate(callback) {
        this.dumpUpdateCallback = void 0;
        this.dumpUpdateCallback = callback;
    }
    setProgressCallback(callback) {
        this.progressCallback = void 0;
        this.progressCallback = callback;
    }
    async parseStructuredParams(action, params, options) {
        return await (0, external_common_js_namespaceObject.parseStructuredParams)(action, params, options);
    }
    formatErrorMessage(error) {
        const errorMessage = error?.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';
        return this.formatBasicErrorMessage(error);
    }
    async getActionSpace(context) {
        if (!this.agent && this.agentFactory) try {
            this.agent = await this.agentFactory();
        } catch (error) {
            console.warn('Failed to create agent for actionSpace:', error);
            return [];
        }
        if (this.agent?.getActionSpace) return await this.agent.getActionSpace();
        if (this.agent && 'interface' in this.agent && 'object' == typeof this.agent.interface) {
            const page = this.agent.interface;
            if (page?.actionSpace) return page.actionSpace();
        }
        if (context && 'object' == typeof context && 'actionSpace' in context) {
            const contextPage = context;
            return contextPage.actionSpace();
        }
        return [];
    }
    async checkStatus() {
        return true;
    }
    async overrideConfig(aiConfig) {
        (0, env_namespaceObject.overrideAIConfig)(aiConfig);
        console.log('Config updated. Agent will be recreated on next execution.');
    }
    async runConnectivityTest() {
        return (0, core_namespaceObject.runConnectivityTest)({
            defaultModelConfig: env_namespaceObject.globalModelConfigManager.getModelConfig('default'),
            planningModelConfig: env_namespaceObject.globalModelConfigManager.getModelConfig('planning'),
            insightModelConfig: env_namespaceObject.globalModelConfigManager.getModelConfig('insight')
        });
    }
    async detachDebuggerSafely() {
        try {
            const page = this.agent?.interface;
            await page?.detachDebugger?.();
        } catch (error) {
            console.warn('Failed to detach debugger:', error);
        }
    }
    async executeAction(actionType, value, options) {
        if (this.agentFactory) {
            if (this.agent) {
                console.log('Destroying old agent before execution...');
                try {
                    await this.agent.destroy?.();
                } catch (error) {
                    console.warn('Failed to destroy old agent:', error);
                }
                this.agent = null;
            }
            await this.recreateAgent();
        }
        if (!this.agent) throw new Error('No agent available. Please provide either an agent instance or agentFactory.');
        const agent = this.agent;
        const actionSpace = await this.getActionSpace();
        let removeListener;
        try {
            agent.resetDump?.();
        } catch (error) {
            console.warn('Failed to reset dump before execution:', error);
        }
        if (options.requestId) {
            this.currentRequestId = options.requestId;
            removeListener = agent.addDumpUpdateListener((dump, executionDump)=>{
                if (this.currentRequestId !== options.requestId) return;
                if (this.dumpUpdateCallback) this.dumpUpdateCallback(dump, executionDump);
            });
        }
        try {
            let result = null;
            let executionError = null;
            try {
                result = await (0, external_common_js_namespaceObject.executeAction)(agent, actionType, actionSpace, value, options);
            } catch (error) {
                executionError = error;
            }
            const response = {
                result,
                dump: null,
                reportHTML: null,
                error: executionError ? executionError instanceof Error ? executionError.message : String(executionError) : null
            };
            try {
                if (agent.dumpDataString) {
                    const dumpString = agent.dumpDataString();
                    if (dumpString) {
                        const groupedDump = core_namespaceObject.ReportActionDump.fromSerializedString(dumpString);
                        response.dump = groupedDump.executions?.[0] || null;
                    }
                }
            } catch (error) {
                console.warn('Failed to get dump from agent:', error);
            }
            try {
                if (agent.reportHTMLString) response.reportHTML = agent.reportHTMLString() || null;
            } catch (error) {}
            try {
                if (agent.writeOutActionDumps) agent.writeOutActionDumps();
            } catch (error) {}
            return response;
        } finally{
            if (removeListener) removeListener();
        }
    }
    async recreateAgent() {
        if (!this.agentFactory) throw new Error('Cannot recreate agent: factory function not provided. Please provide agentFactory in PlaygroundConfig to enable agent recreation.');
        console.log('Creating new agent with latest config...');
        try {
            this.agent = await this.agentFactory();
            console.log('Agent created successfully');
        } catch (error) {
            console.error('Failed to create agent:', error);
            throw error;
        }
    }
    async cancelTask(_requestId) {
        if (!this.agent) return {
            error: 'No active agent found for this requestId'
        };
        let dump = null;
        let reportHTML = null;
        try {
            if ('function' == typeof this.agent.dumpDataString) {
                const dumpString = this.agent.dumpDataString();
                if (dumpString) {
                    const groupedDump = core_namespaceObject.ReportActionDump.fromSerializedString(dumpString);
                    dump = groupedDump.executions?.[0] ?? null;
                }
            }
        } catch (error) {
            console.warn('[LocalExecutionAdapter] Failed to get dump data before cancel:', error);
        }
        try {
            if ('function' == typeof this.agent.reportHTMLString) {
                const html = this.agent.reportHTMLString();
                if (html && 'string' == typeof html && !html.includes('REPLACE_ME_WITH_REPORT_HTML')) reportHTML = html;
            }
        } catch (error) {
            console.warn('[LocalExecutionAdapter] reportHTMLString not available in this environment');
        }
        try {
            await this.agent.destroy?.();
            this.agent = null;
            return {
                success: true,
                dump,
                reportHTML
            };
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Unknown error';
            console.error(`[LocalExecutionAdapter] Failed to cancel agent: ${errorMessage}`);
            return {
                error: `Failed to cancel: ${errorMessage}`,
                dump,
                reportHTML
            };
        }
    }
    async getCurrentExecutionData() {
        const response = {
            dump: null,
            reportHTML: null
        };
        try {
            if (this.agent?.dumpDataString) {
                const dumpString = this.agent.dumpDataString();
                if (dumpString) {
                    const groupedDump = core_namespaceObject.ReportActionDump.fromSerializedString(dumpString);
                    response.dump = groupedDump.executions?.[0] || null;
                }
            }
            if (this.agent?.reportHTMLString) response.reportHTML = this.agent.reportHTMLString() || null;
        } catch (error) {
            console.error('Failed to get current execution data:', error);
        }
        return response;
    }
    async getInterfaceInfo() {
        if (!this.agent?.interface) return null;
        try {
            const type = this.agent.interface.interfaceType || 'Unknown';
            const description = this.agent.interface.describe?.() || void 0;
            const size = 'function' == typeof this.agent.interface.size ? await this.agent.interface.size() : void 0;
            const actionTypes = 'function' == typeof this.agent.interface.actionSpace ? this.agent.interface.actionSpace().map((action)=>action?.name).filter((name)=>'string' == typeof name) : void 0;
            return {
                type,
                description,
                ...size ? {
                    size
                } : {},
                ...actionTypes ? {
                    actionTypes
                } : {}
            };
        } catch (error) {
            console.error('Failed to get interface info:', error);
            return null;
        }
    }
    async getRuntimeInfo() {
        if (!this.agent?.interface) return null;
        try {
            return (0, external_runtime_metadata_js_namespaceObject.buildRuntimeInfo)({
                interfaceType: this.agent.interface.interfaceType || 'Unknown',
                interfaceDescription: this.agent.interface.describe?.() || void 0,
                supportsScreenshot: 'function' == typeof this.agent.interface.screenshotBase64,
                mjpegStreamUrl: this.agent.interface.mjpegStreamUrl
            });
        } catch (error) {
            console.error('Failed to get runtime info:', error);
            return null;
        }
    }
    constructor(agent, agentFactory){
        super(), _define_property(this, "agent", void 0), _define_property(this, "agentFactory", void 0), _define_property(this, "dumpUpdateCallback", void 0), _define_property(this, "progressCallback", void 0), _define_property(this, "_id", void 0), _define_property(this, "currentRequestId", void 0);
        this.agent = agent ?? null;
        this.agentFactory = agentFactory;
        this._id = (0, utils_namespaceObject.uuid)();
    }
}
exports.LocalExecutionAdapter = __webpack_exports__.LocalExecutionAdapter;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "LocalExecutionAdapter"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});

//# sourceMappingURL=local-execution.js.map