summerize this main idea (not the code itself) behind : 
const dockerService = require('../services/dockerService');
const createLogger = require('../utils/logger');
const logger = createLogger('agent.js');
const openai = require('../config/openai');
const {
    Machine,
    interpret,
    setup,
    createActor,
    assign,
    createMachine,
    withConfig,
    log,
    fromPromise,
    not
} = require('xstate');

const fs = require('fs').promises;
const path = require('path');
const {
    readFile
} = require('fs/promises');

const machine = createMachine({
    /** @xstate-layout N4IgpgJg5mDOIC5QEEYDsAuA6AlmghgMYY4BuYAxMgMIAqAkgGrK0CiA2gAwC6ioADgHtYOEoLR8QAD0QBGAMycs8lfIAsAVgDsagJycNG3QBoQAT0TrdWXQCZZWgByct+tbYBssgL7fTqMEwsIhJyLAAnMABHAFc4DAACAFtBCBiAGzAEwlTKCHEwXDRSQQBrQoAlaLjYDABZVIywalyuXiQQIRExCQ6ZBFlOWw1lBw8h53G1R1tTCwQ1LSVF3S1BvTV5D1dff3RsELJCgHdw0SyciDyCopLyrAB1M4xm3NpBFsx8PDBwtskuqIcOJJP1ZB5FFhOGptqtdIt5LZHHNEBpbGobJwPEiVFp7GjdiAAkFDmEckl+DhMtlchR8mhCng7oUAEIxKkQAAK4UEACswMR-h1AT1QYhsfIsB44dCsbZdB4NGoUQgnJLXIjFo5HK41oTiQdiEcsOTKdTLtcGbcyqz2ekuTz+YLZO0BMIgSC+uKPI4sPLwTDZNNZOCTOY5IibFpFXYFENo44PPr9sEjWTBBSqRdab8eeEsPx0vgMAAzQThJJYNkc7l8gUYIVu7rA3qgMHwpSceSyJHY7ZrBQq6OyKEeMe6DQ6ycadTJwKG0KFEs4KQ0q50m5Mm1YKqxeItK4AMRXjc67tFXoGOiUuhD7hmOjUIZVKmsWlU00T8jWjgVc5JaaFJEe61MkjTUi8tQblaW73LuNT1OBYC0PurQ8AC54tmKAycD2WBqO4Y4OA+6jIuGCCKB4frYvo2KOO4CqOP+C7GuEMRoAkkEYLA0GMsU24VOxKG1LAp4ilhl49jCUJOJwqxBrYKgwiqAC0vq6Bp8mOGi3Y9tizGpouETsZx8Q8bm5YFkWpblpWgloMJ3FiZhnptnIwwjNozgJjCCrRiq4IjFoGicC42rgoi6LyL4fggGguTwB0BoYc2rnSIgKmDBoqmyI4kqaasBEOJwiYwgZeCkmAKUeq26UICp2gqk+tjKLYri6DMYzTgZlXVRebkLNKfq5V4uWJiVWjvqpCr4Zp74KL52oaD1gERNU8RgWk5q5H1EkDYM8i+ps0yeMF2gaGOKrjC1Oq9nYwwETqK1Gac5xrlVwoubVYKaFoNj2ImF0zgYF1NT6fpYt2ckQre0bPcappZu9u1pWCY4tYx0YhdpXayEOk5YBqwxTooDi2PDYTLquFoo99cj3RD0I6GiXbomG8wERikWrDjfmzrFBqGax62gSkW1ZFxtPYRoDjDYmIbauMOpaC+XY2L+8i6Jr0Y+vo0UCymlXGRxXGJU2NXYYMuVQnliibEiOIeCqzj4Tr0JW4MBjkwb85C+mFKZC8EBS5JMItcMskhl2nUq+RgxRoq9FbIpOlPhTS7fJkwefaldMDDCR0zlbMLYmoLgBdphOeBCIWKB110xd4QA */
    id: 'Agent',
    initial: 'inactive',
    context: {
        lastGeneratedCode: '',
        errorRetryCounter: 0,
        requestedTestCode: false,
    },
    states: {
        inactive: {
            on: {
                ACTIVATE: {
                    target: 'active',
                    actions: ['AssignContainerID', 'AssignModuleContext', 'AssignGeneratedCode', 'AssignRequestCode'],
                },
            },
        },
        active: {
            initial: 'request module code',
            states: {
                'request module code': {
                    invoke: {
                        id: 'RequestModuleCode',
                        src: fromPromise(async ({
                            input
                        }) => {
                            return await RequestModuleCodeInternal(input.moduleText);
                        }),
                        input: ({
                            context
                        }) => ({
                            moduleText: context.moduleText
                        }),
                        onDone: {
                            target: 'write code',
                            actions: assign({
                                generatedCode: ({
                                    event
                                }) => event.output,
                            }),
                        },
                    }
                },
                "write code": {
                    invoke: {
                        // TODO: Implement a param for the code to implement instead of global context
                        // Or maybe have two Actors to send events
                        id: 'WriteCodeToContainer',
                        src: fromPromise(async ({
                            input
                        }) => {
                            return await WriteCodeToContainerInternal(input.containerId, input.generatedCode);
                        }),
                        input: ({
                            context
                        }) => ({
                            generatedCode: context.generatedCode,
                            containerId: context.containerId
                        }),
                        onDone: {
                            target: 'compile code',
                        },
                    }
                },
                "compile code": {
                    invoke: {
                        id: "BuildProject",
                        src: fromPromise(async ({
                            input
                        }) => {
                            return await BuildProjectInternal(input.containerId);
                        }),
                        input: ({
                            context
                        }) => ({
                            containerId: context.containerId
                        }),
                        onDone: [{
                                target: 'request module test',
                                guard: 'needsToRequestTestCode',
                            },
                            {
                                target: 'run tests',
                                guard: not('needsToRequestTestCode')
                            }
                        ],
                        onError: {
                            target: 'fix code',
                            actions: [
                                assign({
                                    generatedErrorLogs: ({
                                        event
                                    }) => event.error,
                                    errorRetryCounter: ({
                                        context
                                    }) => context.errorRetryCounter + 1,
                                })
                            ]
                        }
                    },
                },
                "fix code": {
                    invoke: {
                        id: 'RequestCodeFix',
                        src: fromPromise(async ({
                            input
                        }) => {
                            logger.info(JSON.stringify(input, null, 2))
                            return await RequestCodeFixInternal(input.containerId, input.generatedCode, input.generatedErrorLogs);
                        }),
                        input: ({
                            context
                        }) => ({
                            containerId: context.containerId,
                            generatedCode: context.generatedCode,
                            generatedErrorLogs: context.generatedErrorLogs
                        }),
                        onDone: {
                            target: 'write code',
                            actions: assign({
                                generatedCode: ({
                                    event
                                }) => event.output,
                            }),
                        }
                    }
                },
                "request module test": {
                    invoke: {
                        id: 'RequestModuleTestCode',
                        src: fromPromise(async ({
                            input
                        }) => {
                            return await RequestModuleTestCodeInternal(input.generatedCode);
                        }),
                        input: ({
                            context
                        }) => ({
                            generatedCode: context.generatedCode
                        }),
                        onDone: {
                            target: 'write code',
                            actions: assign({
                                generatedCode: ({
                                    event
                                }) => event.output,
                                requestedTestCode: true
                            }),
                        },
                    }
                },
                "run tests": {
                    invoke: {
                        id: 'RunTests',
                        src: fromPromise(async ({
                            input
                        }) => {
                            return await RunTestsInternal(input.containerId);
                        }),
                        input: ({
                            context
                        }) => ({
                            containerId: context.containerId
                        }),
                        onDone: {
                            target: 'completed',
                            actions: assign({
                                testsResults: ({
                                    event
                                }) => event.output,
                            })
                        },
                        onError: {
                            target: 'failed',
                            actions: assign({
                                testsResults: ({
                                    event
                                }) => event.error,
                            })
                        }
                    },
                },
                completed: {
                    type: "final",
                },
                failed: {
                    type: "final",
                },
            },
        },
    },
}, {
    actions: {
        AssignContainerID: assign(({
            event
        }) => ({
            containerId: event.containerId,
        })),
        AssignModuleContext: assign(({
            event
        }) => ({
            moduleText: event.moduleText,
        })),
        AssignGeneratedCode: assign(({
            event
        }) => ({
            generatedCode: event.generatedCode
        })),
        AssignRequestCode: assign(({
            event
        }) => ({
            requestedTestCode: event.requestedTestCode
        }))
    },
    actors: {},
    guards: {
        'needsToRequestTestCode': ({
            context,
            event
        }, params) => {
            return !context.requestedTestCode;
        },
        'code compiles correctly AND WROTE_TEST': ({
            context,
            event
        }, params) => {
            return false;
        },
        TestsRanSuccessfully: ({
            context,
            event
        }, params) => {
            return false;
        },
    },
    delays: {},
}, );

async function RunTestsInternal(containerId) {
    return await dockerService.executeCommand(
        containerId,
        'cd ./app && npm run test',
        false
    );
}

async function RequestModuleTestCodeInternal(generatedCode) {
    const response = await RequestOpenAILLM(generatedCode, process.env.TESTER_V1);
    logger.info(response);
    return response;
}

async function RequestModuleCodeInternal(message) {
    logger.info("Called RequestModuleCode");
    const response = await RequestOpenAILLM(message, process.env.IMPLEMENTOR_V1);
    return response;
}

function extractErrorDetails(text) {
    const errorBlockRegex = /✘ \[ERROR\] (.*?): (.*?) \[plugin angular-compiler\]\s*\n\s*([^:]+):(\d+):(\d+):\s*\n\s*\d+\s*\│\s*(.+?)\n/gs;

    let errorDetailsArray = [];

    let match;
    while ((match = errorBlockRegex.exec(text)) !== null) {
        const [_, errorCode, errorMessage, filePath, line, column, lineContent] = match;

        const errorDetails = {
            filePath: filePath.trim(),
            error: `${errorCode}: ${errorMessage} in line: ${lineContent.trim()}`
        };

        errorDetailsArray.push(errorDetails);
    }

    return errorDetailsArray;
}

function extractUniqueFilePaths(errors) {
    const filePaths = new Set();

    errors.forEach(error => {
        filePaths.add(error.filePath);
    });

    return Array.from(filePaths);
}

async function RequestCodeFixInternal(containerId, generatedCode, generatedErrorLogs) {
    const extractErrors = extractErrorDetails(generatedErrorLogs);
    logger.info("extractErrors: " + JSON.stringify(extractErrors, null, 2));
    const filesToImport = extractUniqueFilePaths(extractErrors);
    logger.info("filesToImport: " + JSON.stringify(filesToImport, null, 2));

    if (generatedCode === undefined) {
        logger.info("generatedCode is empty");
        const importFiles = async (filePath) => {
            await dockerService.copyFilesFromContainer(
                containerId,
                '/app/' + filePath,
                path.join(__dirname, 'app_files')
            );
        };

        if (Array.isArray(filesToImport)) {
            for (const filePath of filesToImport) {
                await importFiles(filePath);
            }
        } else {
            await importFiles(filesToImport);
        }

        if (Array.isArray(filesToImport)) {
            for (const filePath of filesToImport) {
                logger.info(path.basename(filePath));
                generatedCode += await _readFile((path.join(__dirname, "app_files", path.basename(filePath))));
            }
        } else {
            logger.info(path.basename(filesToImport));
            generatedCode = await _readFile((path.join(__dirname, "app_files", path.basename(filesToImport))));
        }
    }

    const message = 'Here is script in path ' + filesToImport + ':\n' + generatedCode + '\n Here are the errors when compiling :\n' + JSON.stringify(extractErrors, null, 2);
    logger.info(message);
    const response = await RequestOpenAILLM(message, process.env.FIXER_V1);
    logger.info(response);
    return response;
}

async function _readFile(filePath) {
    try {
        const data = await fs.readFile(filePath, 'utf-8');
        return data;
    } catch (error) {
        logger.error(`Error reading file: ${error.message}`);
        throw error;
    }
}

async function RequestOpenAILLM(message, assistant_id) {
    let threadID;
    let response = '';
    const thread = await openai.beta.threads.create();
    await openai.beta.threads.messages.create(thread.id, {
        role: 'user',
        content: message,
    });

    let run = await openai.beta.threads.runs.create(thread.id, {
        assistant_id: assistant_id,
    });

    while (['queued', 'in_progress', 'cancelling'].includes(run.status)) {
        await new Promise((resolve) => setTimeout(resolve, 1000));
        run = await openai.beta.threads.runs.retrieve(run.thread_id, run.id);
    }

    if (run.status === 'completed') {
        const messages = await openai.beta.threads.messages.list(run.thread_id);
        const assistantResponse = messages.data.find(
            (message) => message.role === 'assistant',
        );

        responseText = assistantResponse.content[0].text.value;
        return responseText;
    }

    return response;
}

function parseSelectors(inputText) {
    const regex = /__(\w+)_START__([\s\S]*?)__\1_END__/g;
    let match;
    const results = {};

    while ((match = regex.exec(inputText)) !== null) {
        const key = match[1];
        const content = match[2].trim();
        results[key] = content;
    }

    return results;
}

function extractFileInfo(inputText) {
    const filePathRegex = /\/\/\s*(.+\.ts)\s*\n/;

    const match = filePathRegex.exec(inputText);

    if (match && match[1]) {
        const fullPath = match[1].trim();
        const fileName = fullPath.split('/').pop();

        return {
            "FILE_NAME": fileName,
            "RELATIVE_PATH": fullPath
        };
    } else {
        return null;
    }
}

async function writeFile(filePath, content) {
    try {
        await fs.writeFile(filePath, content, 'utf-8');
        logger.info(`File written successfully: ${filePath}`);
    } catch (error) {
        logger.error(`Error writing file: ${error.message}`);
        throw error;
    }
}

async function WriteCodeToContainerInternal(containerId, code) {
    logger.info(
        `Will write the code : \n` + code + " to the container : " + containerId,
    );

    const parsedBlocks = parseSelectors(code);
    const fileInfo = extractFileInfo(parsedBlocks.TS);
    const fileName = fileInfo.FILE_NAME;
    const filePathInHost = path.join(__dirname, 'app_files', fileName);

    await writeFile(filePathInHost, parsedBlocks.TS);

    await dockerService.copyFileToContainer(
        containerId,
        filePathInHost,
        '/app/' + fileName
    );
}

async function BuildProjectInternal(containerId) {
    await dockerService.checkAndStartContainer(containerId);
    logger.info(
        `Container is ready, will compile the project.`,
    );

    const output = await dockerService.executeCommand(
        containerId,
        'cd ./app && npm run build',
        false
    );

    logger.info("Project compiled here is the output : " + JSON.stringify(output));
}

async function RunWatch(containerId) {
    logger.info(
        `Will start watching the project in the container : ` + containerId,
    );
    await dockerService.executeCommand(
        containerId,
        'cd ./app && npm run watch',
        false,
    );
}

async function RunServe(containerId) {
    logger.info(`Will serve the project in the container : ` + containerId);
    await dockerService.executeCommand(
        containerId,
        'cd ./app && npm run serve:ssr:ssr_app',
        false,
        'serve',
    );
}

function handleWatchOutput(output, restartServeCallback) {
    if (output.includes('Application bundle generation complete.')) {
        restartServeCallback();
    }
}

module.exports = machine;