"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 ("u" > 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__, {
    PlaygroundIpcBase: ()=>PlaygroundIpcBase,
    default: ()=>ipc,
    serializeZodField: ()=>serializeZodField
});
const external_node_fs_namespaceObject = require("node:fs");
const external_node_path_namespaceObject = require("node:path");
const core_namespaceObject = require("@godscene/core");
const utils_namespaceObject = require("@godscene/core/utils");
const env_namespaceObject = require("@godscene/shared/env");
const shared_utils_namespaceObject = require("@godscene/shared/utils");
const external_common_js_namespaceObject = require("./common.js");
const external_runtime_metadata_js_namespaceObject = require("./runtime-metadata.js");
require("dotenv/config");
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;
}
function serializeAiConfigSignature(aiConfig) {
    return JSON.stringify(Object.entries(aiConfig).sort(([leftKey], [rightKey])=>leftKey.localeCompare(rightKey)));
}
function serializeZodField(field) {
    if (!field || 'object' != typeof field) return field;
    const def = field._def;
    if (!def || 'object' != typeof def) return field;
    const typeName = def.typeName;
    const result = {
        _def: {
            typeName
        }
    };
    if (def.description) result._def.description = def.description;
    if (def.innerType) result._def.innerType = serializeZodField(def.innerType);
    if ('ZodDefault' === typeName && 'function' == typeof def.defaultValue) try {
        result._def._serializedDefaultValue = def.defaultValue();
    } catch  {}
    if ('ZodEnum' === typeName && Array.isArray(def.values)) result._def.values = def.values;
    if ('ZodObject' === typeName) {
        const rawShape = 'function' == typeof def.shape ? def.shape() : def.shape;
        if (rawShape && 'object' == typeof rawShape) {
            const serializedShape = {};
            for (const [k, v] of Object.entries(rawShape))serializedShape[k] = serializeZodField(v);
            result._def.shape = serializedShape;
            result.shape = serializedShape;
        }
    }
    if (field.description) result.description = field.description;
    return result;
}
class PlaygroundIpcBase {
    get agent() {
        return this._activeConnection.agent;
    }
    assertNoActiveSessionForBaseStateUpdate(methodName) {
        if (this._activeConnection.session) throw new Error(`${methodName} cannot update prepared state while a session is active`);
    }
    buildBaseRuntimeState() {
        if (!this._baseRuntimeState) return;
        return {
            ...this._baseRuntimeState,
            metadata: this.buildSessionMetadata()
        };
    }
    resetConnectionToBaseState() {
        this._activeConnection = {
            session: null,
            agent: this._activeConnection.agent,
            agentFactory: this._activeConnection.agentFactory,
            runtime: this.buildBaseRuntimeState(),
            executionHooks: this._baseExecutionHooks,
            sidecars: this._baseSidecars
        };
    }
    syncRuntimeState() {
        this._baseRuntimeState = {
            ...this._baseRuntimeState || {},
            metadata: this.buildSessionMetadata()
        };
        if (this._activeConnection.session) {
            this._activeConnection = {
                ...this._activeConnection,
                runtime: this._activeConnection.runtime ? {
                    ...this._activeConnection.runtime,
                    metadata: this.buildSessionMetadata()
                } : this.buildBaseRuntimeState()
            };
            return;
        }
        this.resetConnectionToBaseState();
    }
    restoreBaseSessionState() {
        this.taskExecutionDumps = {};
        this.currentTaskId = null;
        this.sessionSetupState = 'blocked' === this.sessionSetupState ? 'blocked' : 'required';
        this._activeConnection = {
            session: null,
            agent: null,
            agentFactory: null,
            runtime: this.buildBaseRuntimeState(),
            executionHooks: this._baseExecutionHooks,
            sidecars: this._baseSidecars
        };
        this.syncRuntimeState();
    }
    setPreparedPlatform(prepared) {
        if (this._activeConnection.session && this._activeConnection.agentFactory) this._activeConnection.session = null;
        this.assertNoActiveSessionForBaseStateUpdate('setPreparedPlatform');
        this.sessionManager = prepared.sessionManager;
        this._basePreparedMetadata = prepared.metadata ? {
            ...prepared.metadata
        } : void 0;
        this._baseRuntimeState = {
            platformId: prepared.platformId,
            title: prepared.title,
            description: prepared.description,
            preview: prepared.preview,
            metadata: this.buildSessionMetadata()
        };
        this._baseExecutionHooks = prepared.executionHooks;
        this._baseSidecars = prepared.sidecars;
        this.resetConnectionToBaseState();
        if (this.sessionManager && !this._activeConnection.agent && !this._activeConnection.session) {
            this.sessionSetupState = this._basePreparedMetadata?.setupState === 'blocked' ? 'blocked' : 'required';
            this.sessionSetupBlockingReason = 'string' == typeof this._basePreparedMetadata?.setupBlockingReason ? this._basePreparedMetadata.setupBlockingReason : void 0;
        }
    }
    setPreviewDescriptor(preview) {
        this.assertNoActiveSessionForBaseStateUpdate("setPreviewDescriptor");
        this._baseRuntimeState = {
            ...this._baseRuntimeState || {},
            preview
        };
        this.resetConnectionToBaseState();
    }
    setRuntimeMetadata(metadata) {
        this.assertNoActiveSessionForBaseStateUpdate('setRuntimeMetadata');
        this._basePreparedMetadata = metadata ? {
            ...metadata
        } : void 0;
        this.syncRuntimeState();
    }
    getRuntimeInfo() {
        return (0, external_runtime_metadata_js_namespaceObject.buildRuntimeInfo)({
            platformId: this._activeConnection.runtime?.platformId,
            title: this._activeConnection.runtime?.title,
            platformDescription: this._activeConnection.runtime?.description,
            interfaceType: this._activeConnection.agent?.interface?.interfaceType || 'Unknown',
            interfaceDescription: this._activeConnection.agent?.interface?.describe?.() || void 0,
            preview: this._activeConnection.runtime?.preview,
            metadata: this.buildSessionMetadata(),
            supportsScreenshot: 'function' == typeof this._activeConnection.agent?.interface?.screenshotBase64,
            mjpegStreamUrl: this._activeConnection.agent?.interface?.mjpegStreamUrl
        });
    }
    getSessionInfo() {
        const connected = this.sessionManager ? Boolean(this._activeConnection.session?.connected && this._activeConnection.agent) : Boolean(this._activeConnection.agent);
        return {
            connected,
            displayName: this._activeConnection.session?.displayName,
            metadata: {
                ...this._activeConnection.session?.metadata || {}
            },
            setupState: this.sessionSetupState,
            setupBlockingReason: this.sessionSetupBlockingReason
        };
    }
    buildSessionMetadata() {
        const sessionConnected = this.sessionManager ? Boolean(this._activeConnection.session?.connected && this._activeConnection.agent) : Boolean(this._activeConnection.agent);
        return {
            ...this._basePreparedMetadata || {},
            ...this._activeConnection.session?.metadata || {},
            sessionConnected,
            sessionDisplayName: this._activeConnection.session?.displayName,
            setupState: this.sessionSetupState,
            ...this.sessionSetupBlockingReason ? {
                setupBlockingReason: this.sessionSetupBlockingReason
            } : {}
        };
    }
    async startSidecars(sidecars) {
        for (const sidecar of sidecars || [])await sidecar.start();
    }
    async stopSidecars(sidecars) {
        for (const sidecar of sidecars || [])await sidecar.stop?.();
    }
    getActiveAgentOrThrow() {
        if (!this._activeConnection.agent) throw new Error('No active session');
        return this._activeConnection.agent;
    }
    async destroyCurrentAgent() {
        if (!this._activeConnection.agent) return;
        try {
            if ('function' == typeof this._activeConnection.agent.destroy) await this._activeConnection.agent.destroy();
        } catch (error) {
            console.warn('Failed to destroy old agent:', error);
        } finally{
            this._activeConnection.agent = null;
            this._configDirty = false;
        }
    }
    async destroyCurrentSession() {
        const previousSession = this._activeConnection.session;
        const previousSidecars = this._activeConnection.sidecars;
        await this.destroyCurrentAgent();
        await this.stopSidecars(previousSidecars);
        if (this.sessionManager?.destroySession) await this.sessionManager.destroySession(previousSession || void 0);
        this.restoreBaseSessionState();
    }
    async applyCreatedSession(session) {
        if (!session.agent && !session.agentFactory) throw new Error('Session creation must provide either an agent or agentFactory');
        const sessionSidecars = session.sidecars || this._baseSidecars;
        await this.startSidecars(sessionSidecars);
        try {
            this._activeConnection = {
                session: {
                    connected: true,
                    displayName: session.displayName,
                    metadata: session.metadata ? {
                        ...session.metadata
                    } : {}
                },
                agent: session.agent || null,
                agentFactory: session.agentFactory || null,
                runtime: {
                    platformId: session.platformId ?? this._baseRuntimeState?.platformId,
                    title: session.title ?? this._baseRuntimeState?.title,
                    description: session.platformDescription ?? this._baseRuntimeState?.description,
                    preview: session.preview ?? this._baseRuntimeState?.preview,
                    metadata: session.metadata ? {
                        ...session.metadata
                    } : {}
                },
                executionHooks: session.executionHooks || this._baseExecutionHooks,
                sidecars: sessionSidecars
            };
            this.sessionSetupState = 'ready';
            this.sessionSetupBlockingReason = void 0;
            this.syncRuntimeState();
        } catch (error) {
            await this.stopSidecars(sessionSidecars).catch(()=>{});
            this.restoreBaseSessionState();
            throw error;
        }
    }
    async getSessionSetupSchema(input) {
        if (!this.sessionManager) return null;
        return this.sessionManager.getSetupSchema ? this.sessionManager.getSetupSchema(input) : null;
    }
    async getSessionTargets() {
        if (!this.sessionManager?.listTargets) return [];
        return this.sessionManager.listTargets();
    }
    updateContext(context) {
        if (this._activeConnection.agent && context && 'updateContext' in this._activeConnection.agent.interface && 'function' == typeof this._activeConnection.agent.interface.updateContext) {
            this._activeConnection.agent.interface.updateContext(context);
            console.log('Context updated by PlaygroundServer middleware');
        }
    }
    initializeApp(ipcMain) {
        if (this._initialized) return;
        this.setupRoutes(ipcMain);
        this._initialized = true;
    }
    filePathForUuid(uuid) {
        if (!/^[a-zA-Z0-9-]+$/.test(uuid)) throw new Error('Invalid uuid format');
        const filePath = (0, external_node_path_namespaceObject.join)(this.tmpDir, `${uuid}.json`);
        const resolvedPath = (0, external_node_path_namespaceObject.resolve)(filePath);
        const resolvedTmpDir = (0, external_node_path_namespaceObject.resolve)(this.tmpDir);
        if (!resolvedPath.startsWith(resolvedTmpDir)) throw new Error('Invalid path');
        return filePath;
    }
    saveContextFile(uuid, context) {
        const tmpFile = this.filePathForUuid(uuid);
        console.log(`save context file: ${tmpFile}`);
        (0, external_node_fs_namespaceObject.writeFileSync)(tmpFile, context);
        return tmpFile;
    }
    async recreateAgent() {
        this._agentReady = false;
        console.log('Recreating agent to cancel current task...');
        await this.destroyCurrentAgent();
        if (this._activeConnection.agentFactory) try {
            this._activeConnection.agent = await this._activeConnection.agentFactory();
            this._agentReady = true;
            console.log('Agent recreated successfully');
        } catch (error) {
            this._agentReady = true;
            console.error('Failed to recreate agent:', error);
            throw error;
        }
        else {
            this._agentReady = true;
            console.warn('Agent destroyed but cannot recreate: no factory function provided. Next /execute call will fail.');
        }
    }
    setupRoutes(ipcMain) {
        ipcMain.handle('playground:status', async ()=>({
                status: 'ok',
                id: this.id
            }));
        ipcMain.handle('playground:session', async ()=>this.getSessionInfo());
        ipcMain.handle('playground:session-setup', async (event, query)=>{
            try {
                const setup = await this.getSessionSetupSchema(Object.fromEntries(Object.entries(query).filter(([, value])=>'string' == typeof value)));
                if (!setup) return {
                    status: 404,
                    error: 'Session setup is not available for this playground'
                };
                const targets = await this.getSessionTargets();
                return {
                    ...setup,
                    targets: targets.length > 0 ? targets : setup.targets
                };
            } catch (error) {
                return {
                    status: 500,
                    error: error instanceof Error ? error.message : 'Failed to load session setup'
                };
            }
        });
        ipcMain.handle('playground:session-targets', async ()=>{
            try {
                return await this.getSessionTargets();
            } catch (error) {
                return {
                    status: 500,
                    error: error instanceof Error ? error.message : 'Failed to load session targets'
                };
            }
        });
        ipcMain.handle('playground:session-create', async (event, body)=>{
            if (!this.sessionManager) return {
                status: 404,
                error: 'Session creation is not available for this playground'
            };
            if (this.currentTaskId) return {
                status: 409,
                error: 'Cannot replace session while a task is running'
            };
            try {
                await this.destroyCurrentSession();
                const created = await this.sessionManager.createSession(body || {});
                await this.applyCreatedSession(created);
                if (!this._activeConnection.agent && this._activeConnection.agentFactory) this._activeConnection.agent = await this._activeConnection.agentFactory();
                if (this._configDirty && this._activeConnection.agentFactory) {
                    this._configDirty = false;
                    await this.recreateAgent();
                }
                return {
                    session: this.getSessionInfo(),
                    runtimeInfo: this.getRuntimeInfo()
                };
            } catch (error) {
                const failedSessionSidecars = this._activeConnection.session ? this._activeConnection.sidecars : void 0;
                await this.destroyCurrentAgent();
                await this.stopSidecars(failedSessionSidecars).catch(()=>{});
                this.restoreBaseSessionState();
                return {
                    status: 400,
                    error: error instanceof Error ? error.message : 'Failed to create session'
                };
            }
        });
        ipcMain.handle('playground:session-delete', async ()=>{
            if (this.currentTaskId) return {
                status: 409,
                error: 'Cannot destroy session while a task is running'
            };
            try {
                await this.destroyCurrentSession();
                return {
                    session: this.getSessionInfo(),
                    runtimeInfo: this.getRuntimeInfo()
                };
            } catch (error) {
                return {
                    status: 500,
                    error: error instanceof Error ? error.message : 'Failed to destroy session'
                };
            }
        });
        ipcMain.handle('playground:context', async (event, { uuid })=>{
            let contextFile;
            try {
                contextFile = this.filePathForUuid(uuid);
            } catch  {
                return {
                    status: 400,
                    error: 'Invalid uuid format'
                };
            }
            if (!(0, external_node_fs_namespaceObject.existsSync)(contextFile)) return {
                status: 400,
                error: 'Context not found'
            };
            const context = (0, external_node_fs_namespaceObject.readFileSync)(contextFile, 'utf8');
            return {
                context
            };
        });
        ipcMain.handle('playground:task-progress', async (event, requestId)=>{
            const executionDump = this.taskExecutionDumps[requestId] || null;
            return {
                executionDump: JSON.parse(JSON.stringify(executionDump))
            };
        });
        ipcMain.handle('playground:action-space', async (event, { context })=>{
            try {
                this.updateContext(context);
                const agent = this.getActiveAgentOrThrow();
                let actionSpace = [];
                actionSpace = agent.interface.actionSpace();
                const processedActionSpace = actionSpace.map((action)=>{
                    if (action && 'object' == typeof action && 'paramSchema' in action) {
                        const typedAction = action;
                        if (typedAction.paramSchema && 'object' == typeof typedAction.paramSchema) {
                            let processedSchema = null;
                            try {
                                if (typedAction.paramSchema.shape && 'object' == typeof typedAction.paramSchema.shape) {
                                    const rawShape = typedAction.paramSchema.shape;
                                    const serializedShape = {};
                                    for (const [key, field] of Object.entries(rawShape))serializedShape[key] = serializeZodField(field);
                                    processedSchema = {
                                        type: 'ZodObject',
                                        shape: serializedShape
                                    };
                                }
                            } catch (e) {
                                const actionName = 'name' in typedAction && 'string' == typeof typedAction.name ? typedAction.name : 'unknown';
                                console.warn('Failed to process paramSchema for action:', actionName, e);
                            }
                            return {
                                ...typedAction,
                                paramSchema: processedSchema
                            };
                        }
                    }
                    return action;
                });
                return processedActionSpace;
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : 'Unknown error';
                console.error('Failed to get action space:', error);
                return {
                    status: 'No active session' === errorMessage ? 409 : 500,
                    error: errorMessage
                };
            }
        });
        ipcMain.handle('playground:playground-with-context', async (event, { context })=>{
            this.updateContext(context);
            if (!context) return {
                status: 400,
                error: 'context is required'
            };
            const requestId = (0, shared_utils_namespaceObject.uuid)();
            this.saveContextFile(requestId, context);
            return {
                location: `/playground/${requestId}`,
                uuid: requestId
            };
        });
        ipcMain.handle('playground:execute', async (event, body)=>{
            let agent;
            try {
                agent = this.getActiveAgentOrThrow();
            } catch (error) {
                return {
                    status: 409,
                    error: error instanceof Error ? error.message : 'No active session'
                };
            }
            const { type, prompt, params, requestId, deepLocate, deepThink, screenshotIncluded, domIncluded, deviceOptions } = body;
            if (!type) return {
                status: 400,
                error: 'type is required'
            };
            if (this._activeConnection.agentFactory && this._configDirty) {
                this._configDirty = false;
                this._agentReady = false;
                console.log('AI config changed, recreating agent...');
                try {
                    await this.destroyCurrentAgent();
                    this._activeConnection.agent = await this._activeConnection.agentFactory();
                    agent = this.getActiveAgentOrThrow();
                    this._agentReady = true;
                    console.log('Agent recreated with new config');
                } catch (error) {
                    this._agentReady = true;
                    console.error('Failed to recreate agent:', error);
                    return {
                        status: 500,
                        error: `Failed to create agent: ${error instanceof Error ? error.message : 'Unknown error'}`
                    };
                }
            }
            if (deviceOptions) {
                const iface = agent.interface;
                iface.options = {
                    ...iface.options || {},
                    ...deviceOptions
                };
            }
            if (this.currentTaskId) return {
                status: 409,
                error: 'Another task is already running',
                currentTaskId: this.currentTaskId
            };
            if (requestId) {
                this.currentTaskId = requestId;
                this.taskExecutionDumps[requestId] = null;
                agent.onDumpUpdate = (_dump, executionDump)=>{
                    if (executionDump) {
                        this.taskExecutionDumps[requestId] = executionDump;
                        event.sender.send('progress-chunk', JSON.parse(JSON.stringify(executionDump)));
                    }
                };
            }
            const response = {
                result: null,
                dump: null,
                error: null,
                reportHTML: null,
                requestId
            };
            const startTime = Date.now();
            try {
                await this._activeConnection.executionHooks?.beforeExecute?.();
                const actionSpace = agent.interface.actionSpace();
                const value = {
                    type,
                    prompt,
                    params
                };
                response.result = await (0, external_common_js_namespaceObject.executeAction)(agent, type, actionSpace, value, {
                    deepLocate,
                    deepThink,
                    screenshotIncluded,
                    domIncluded,
                    deviceOptions
                });
            } catch (error) {
                response.error = (0, external_common_js_namespaceObject.formatErrorMessage)(error);
            } finally{
                try {
                    await this._activeConnection.executionHooks?.afterExecute?.();
                } catch (hookError) {
                    console.error('Failed to run execution after hook:', hookError);
                }
            }
            try {
                const dumpString = agent.dumpDataString({
                    inlineScreenshots: true
                });
                if (dumpString) {
                    const groupedDump = core_namespaceObject.ReportActionDump.fromSerializedString(dumpString);
                    response.dump = groupedDump.executions?.[0] || null;
                } else response.dump = null;
                response.reportHTML = agent.reportHTMLString({
                    inlineScreenshots: true
                }) || null;
                agent.writeOutActionDumps();
                agent.resetDump();
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : 'Unknown error';
                console.error(`write out dump failed: requestId: ${requestId}, ${errorMessage}`);
            } finally{}
            const timeCost = Date.now() - startTime;
            if (response.error) console.error(`handle request failed after ${timeCost}ms: requestId: ${requestId}, ${response.error}`);
            else console.log(`handle request done after ${timeCost}ms: requestId: ${requestId}`);
            if (requestId) {
                delete this.taskExecutionDumps[requestId];
                if (this.currentTaskId === requestId) this.currentTaskId = null;
            }
            return response;
        });
        ipcMain.handle('playground:cancel', async (event, requestId)=>{
            if (!requestId) return {
                status: 400,
                error: 'requestId is required'
            };
            try {
                const agent = this.getActiveAgentOrThrow();
                if (this.currentTaskId !== requestId) return {
                    status: 'not_found',
                    message: 'Task not found or already completed'
                };
                console.log(`Cancelling task: ${requestId}`);
                let dump = null;
                let reportHTML = null;
                try {
                    const dumpString = agent.dumpDataString?.({
                        inlineScreenshots: true
                    });
                    if (dumpString) {
                        const groupedDump = core_namespaceObject.ReportActionDump.fromSerializedString(dumpString);
                        dump = groupedDump.executions?.[0] || null;
                    }
                    reportHTML = agent.reportHTMLString?.({
                        inlineScreenshots: true
                    }) || null;
                } catch (error) {
                    console.warn('Failed to get execution data before cancel:', error);
                }
                try {
                    await this.recreateAgent();
                } catch (error) {
                    console.warn('Failed to recreate agent during cancel:', error);
                }
                delete this.taskExecutionDumps[requestId];
                this.currentTaskId = null;
                return {
                    status: 'cancelled',
                    message: 'Task cancelled successfully',
                    dump,
                    reportHTML
                };
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : 'Unknown error';
                console.error(`Failed to cancel: ${errorMessage}`);
                return {
                    status: 'No active session' === errorMessage ? 409 : 500,
                    error: `Failed to cancel: ${errorMessage}`
                };
            }
        });
        ipcMain.handle('playground:screenshot', async ()=>{
            try {
                const agent = this.getActiveAgentOrThrow();
                if ('function' != typeof agent.interface.screenshotBase64) return {
                    status: 500,
                    error: 'Screenshot method not available on current interface'
                };
                const base64Screenshot = await agent.interface.screenshotBase64();
                return {
                    screenshot: base64Screenshot,
                    timestamp: Date.now()
                };
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : 'Unknown error';
                const statusCode = 'No active session' === errorMessage ? 409 : 500;
                if (409 !== statusCode) console.error(`Failed to take screenshot: ${errorMessage}`);
                return {
                    status: statusCode,
                    error: `Failed to take screenshot: ${errorMessage}`
                };
            }
        });
        ipcMain.handle('playground:interface-info', async ()=>{
            try {
                const runtimeInfo = this.getRuntimeInfo();
                return {
                    type: runtimeInfo.interface.type,
                    description: runtimeInfo.interface.description
                };
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : 'Unknown error';
                console.error(`Failed to get interface info: ${errorMessage}`);
                return {
                    status: 500,
                    error: `Failed to get interface info: ${errorMessage}`
                };
            }
        });
        ipcMain.handle('playground:runtime-info', async ()=>{
            try {
                return this.getRuntimeInfo();
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : 'Unknown error';
                console.error(`Failed to get runtime info: ${errorMessage}`);
                return {
                    status: 500,
                    error: `Failed to get runtime info: ${errorMessage}`
                };
            }
        });
        ipcMain.handle('playground:config', async (event, { aiConfig })=>{
            if (!aiConfig || 'object' != typeof aiConfig) return {
                status: 400,
                error: 'aiConfig is required and must be an object'
            };
            if (0 === Object.keys(aiConfig).length) return {
                status: 'ok',
                message: 'AI config not changed due to empty object'
            };
            const nextConfigSignature = serializeAiConfigSignature(aiConfig);
            const configChanged = nextConfigSignature !== this._lastAiConfigSignature;
            try {
                if (configChanged) {
                    (0, env_namespaceObject.overrideAIConfig)(aiConfig);
                    this._lastAiConfigSignature = nextConfigSignature;
                    this._configDirty = Boolean(this._activeConnection.agent);
                }
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : 'Unknown error';
                console.error(`Failed to update AI config: ${errorMessage}`);
                return {
                    status: 500,
                    error: `Failed to update AI config: ${errorMessage}`
                };
            }
            if (!configChanged) return {
                status: 'ok',
                message: 'AI config not changed because it is identical to current'
            };
            try {
                env_namespaceObject.globalModelConfigManager.getModelConfig('default');
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : 'Unknown error';
                console.error(`AI config validation failed: ${errorMessage}`);
                return {
                    status: 400,
                    error: errorMessage
                };
            }
            return {
                status: 'ok',
                message: this._configDirty ? 'AI config updated. Agent will be recreated on next execution.' : 'AI config updated. New sessions will use it immediately.'
            };
        });
        ipcMain.handle('playground:connectivity-test', async ()=>{
            try {
                return await (0, core_namespaceObject.runConnectivityTest)({
                    defaultModelConfig: env_namespaceObject.globalModelConfigManager.getModelConfig('default'),
                    planningModelConfig: env_namespaceObject.globalModelConfigManager.getModelConfig('planning'),
                    insightModelConfig: env_namespaceObject.globalModelConfigManager.getModelConfig('insight')
                });
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : 'Unknown error';
                console.error(`Connectivity test failed: ${errorMessage}`);
                return {
                    status: 500,
                    error: errorMessage
                };
            }
        });
    }
    async launch(ipcMain) {
        if (this._activeConnection.agentFactory && !this.sessionManager) {
            console.log('Initializing agent from factory function...');
            this._activeConnection.agent = await this._activeConnection.agentFactory();
            this._activeConnection.session = {
                connected: true,
                metadata: {}
            };
            this.sessionSetupState = 'ready';
            this.syncRuntimeState();
            console.log('Agent initialized successfully');
        }
        this.initializeApp(ipcMain);
    }
    async close(ipcMain) {
        await this.destroyCurrentSession().catch((error)=>{
            console.warn('Failed to destroy current session during shutdown:', error);
        });
        return new Promise((resolve, reject)=>{
            if (this.server) {
                this.taskExecutionDumps = {};
                ipcMain.removeHandler('playground:status');
                ipcMain.removeHandler('playground:connectivity-test');
                ipcMain.removeHandler('playground:runtime-info');
                ipcMain.removeHandler('playground:session');
                ipcMain.removeHandler('playground:session-setup');
                ipcMain.removeHandler('playground:session-targets');
                ipcMain.removeHandler('playground:session-create');
                ipcMain.removeHandler('playground:session-delete');
                ipcMain.removeHandler('playground:task-progress');
                ipcMain.removeHandler('playground:action-space');
                ipcMain.removeHandler('playground:execute');
                ipcMain.removeHandler('playground:cancel');
                ipcMain.removeHandler('playground:screenshot');
                ipcMain.removeHandler('playground:interface-info');
                ipcMain.removeHandler('playground:config');
                ipcMain.removeHandler('playground:context');
                ipcMain.removeHandler('playground:playground-with-context');
                resolve();
            } else resolve();
        });
    }
    constructor(agent, id){
        _define_property(this, "tmpDir", void 0);
        _define_property(this, "server", void 0);
        _define_property(this, "taskExecutionDumps", void 0);
        _define_property(this, "id", void 0);
        _define_property(this, "_initialized", false);
        _define_property(this, "sessionManager", void 0);
        _define_property(this, "sessionSetupState", 'ready');
        _define_property(this, "sessionSetupBlockingReason", void 0);
        _define_property(this, "currentTaskId", null);
        _define_property(this, "_agentReady", true);
        _define_property(this, "_configDirty", false);
        _define_property(this, "_lastAiConfigSignature", null);
        _define_property(this, "_baseRuntimeState", void 0);
        _define_property(this, "_basePreparedMetadata", void 0);
        _define_property(this, "_baseExecutionHooks", void 0);
        _define_property(this, "_baseSidecars", void 0);
        _define_property(this, "_activeConnection", {
            session: null,
            agent: null,
            agentFactory: null,
            runtime: void 0,
            executionHooks: void 0,
            sidecars: void 0
        });
        this.tmpDir = (0, utils_namespaceObject.getTmpDir)();
        this.taskExecutionDumps = {};
        this.id = id || (0, shared_utils_namespaceObject.uuid)();
        if ('function' == typeof agent) this._activeConnection.agentFactory = agent;
        else this._activeConnection.agent = agent || null;
    }
}
const ipc = PlaygroundIpcBase;
exports.PlaygroundIpcBase = __webpack_exports__.PlaygroundIpcBase;
exports["default"] = __webpack_exports__["default"];
exports.serializeZodField = __webpack_exports__.serializeZodField;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "PlaygroundIpcBase",
    "default",
    "serializeZodField"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
