import { basename } from "node:path";
import { createAgentSessionRuntime, } from "../../core/agent-session-runtime.js";
import { RpcClient } from "../rpc/rpc-client.js";
import { buildInteractiveEngineArgs } from "./engine-args.js";
import { IsolatedInteractiveRuntime } from "./isolated-runtime.js";
export async function createIsolatedInteractiveRuntime(options) {
    const executableName = basename(process.execPath).toLowerCase();
    const launchedByRuntime = ["bun", "bun.exe", "node", "node.exe"].includes(executableName);
    const cliPath = launchedByRuntime ? process.argv[1] : "";
    if (launchedByRuntime && !cliPath)
        throw new Error("Cannot start isolated interactive engine: Atomic entrypoint is unavailable");
    let isolatedRuntime;
    const pendingDiagnostics = [];
    let callbackActive = false;
    const client = new RpcClient({
        cliPath,
        cwd: options.sessionManager.getCwd(),
        runtimeExecutable: process.execPath,
        args: buildInteractiveEngineArgs(options.parsed, options.sessionManager, options.resources),
        env: {
            ATOMIC_CODING_AGENT_DIR: options.localRuntime.services.agentDir,
            ...(options.parsed.apiKey ? { ATOMIC_INTERACTIVE_ENGINE_API_KEY: options.parsed.apiKey } : {}),
        },
        interactiveEngine: {
            onDiagnostic: (diagnostic) => isolatedRuntime
                ? isolatedRuntime.emitDiagnostic(diagnostic)
                : pendingDiagnostics.push(diagnostic),
            onActivityChange: (active) => {
                callbackActive = active;
                isolatedRuntime?.setEngineCallbackActive(active);
            },
        },
    });
    try {
        await client.start();
    }
    catch (error) {
        await client.stop();
        throw error;
    }
    isolatedRuntime = new IsolatedInteractiveRuntime(options.localRuntime, options.createRuntime, client);
    isolatedRuntime.setEngineCallbackActive(callbackActive);
    for (const diagnostic of pendingDiagnostics)
        isolatedRuntime.emitDiagnostic(diagnostic);
    return isolatedRuntime;
}
export async function createRuntimeForMode(createRuntime, cwd, agentDir, sessionManager, isolateInteractiveHost, hasInlineExtensionFactories, parsed, resources) {
    if (isolateInteractiveHost && hasInlineExtensionFactories) {
        throw new Error("Interactive engine isolation cannot serialize inline extension factories; load the extension from a module path instead.");
    }
    const localRuntime = await createAgentSessionRuntime(createRuntime, { cwd, agentDir, sessionManager });
    if (!isolateInteractiveHost)
        return localRuntime;
    return createIsolatedInteractiveRuntime({ localRuntime, createRuntime, parsed, sessionManager, resources });
}
//# sourceMappingURL=create-isolated-runtime.js.map