"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.orchestrateTestCorrectInvalidRequest = void 0;
const __typia_transform__validateReport = __importStar(require("typia/lib/internal/_validateReport.js"));
const utils_1 = require("@autobe/utils");
const typia_1 = __importDefault(require("typia"));
const uuid_1 = require("uuid");
const assertSchemaModel_1 = require("../../context/assertSchemaModel");
const transformTestCorrectInvalidRequestHistories_1 = require("./histories/transformTestCorrectInvalidRequestHistories");
const orchestrateTestCorrectInvalidRequest = (ctx, compile, write) => __awaiter(void 0, void 0, void 0, function* () {
    const event = yield compile(write.script);
    return yield predicate(ctx, compile, write, event, ctx.retry);
});
exports.orchestrateTestCorrectInvalidRequest = orchestrateTestCorrectInvalidRequest;
const predicate = (ctx, compile, write, event, life) => __awaiter(void 0, void 0, void 0, function* () {
    if (event.result.type === "failure") {
        ctx.dispatch(event);
        return yield correct(ctx, compile, write, event, life - 1);
    }
    return event;
});
const correct = (ctx, compile, write, event, life) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b, _c, _d, _e, _f;
    if (event.result.type !== "failure")
        return event;
    else if (life < 0)
        return event;
    const pointer = {
        value: null,
    };
    const { tokenUsage } = yield ctx.conversate({
        source: "testCorrect",
        histories: yield (0, transformTestCorrectInvalidRequestHistories_1.transformTestCorrectInvalidRequestHistories)(null, event.result.diagnostics),
        controller: createController({
            model: ctx.model,
            then: (next) => {
                pointer.value = next;
            },
            reject: () => {
                pointer.value = false;
            },
        }),
        enforceFunctionCall: true,
        message: utils_1.StringUtil.trim `
      Fix the AutoBeTest.IFunction data to resolve the compilation error.

      You don't need to explain me anything, but just fix or give it up 
      immediately without any hesitation, explanation, and questions.
    `,
    });
    if (pointer.value === null)
        throw new Error("Failed to correct test code.");
    else if (pointer.value === false)
        return event; // other's responsibility
    ctx.dispatch({
        type: "testCorrect",
        id: (0, uuid_1.v7)(),
        created_at: new Date().toISOString(),
        file: {
            scenario: write.scenario,
            location: write.location,
            content: write.script,
        },
        result: event.result,
        tokenUsage,
        step: (_b = (_a = ctx.state().analyze) === null || _a === void 0 ? void 0 : _a.step) !== null && _b !== void 0 ? _b : 0,
        think: pointer.value.think,
        draft: pointer.value.draft,
        review: (_c = pointer.value.revise) === null || _c === void 0 ? void 0 : _c.review,
        final: (_d = pointer.value.revise) === null || _d === void 0 ? void 0 : _d.final,
    });
    const newWrite = {
        artifacts: write.artifacts,
        scenario: write.scenario,
        location: write.location,
        script: (_f = (_e = pointer.value.revise) === null || _e === void 0 ? void 0 : _e.final) !== null && _f !== void 0 ? _f : pointer.value.draft,
    };
    const newEvent = yield compile(newWrite.script);
    return yield predicate(ctx, compile, newWrite, newEvent, life - 1);
});
const createController = (props) => {
    (0, assertSchemaModel_1.assertSchemaModel)(props.model);
    const application = collection[props.model === "chatgpt" ? "chatgpt" : "claude"];
    return {
        protocol: "class",
        name: "correctInvalidRequest",
        application,
        execute: {
            rewrite: (next) => {
                props.then(next);
            },
            reject: () => {
                props.reject();
            },
        },
    };
};
const collection = {
    chatgpt: {
        model: "chatgpt",
        options: {
            reference: true,
            strict: false,
            separate: null
        },
        functions: [
            {
                name: "rewrite",
                parameters: {
                    description: " - The analysis and correction properties\n\n------------------------------\n\nDescription of the current {@link IAutoBeTestCorrectInvalidRequestApplication.IProps} type:\n\n> Properties for the rewrite function containing the analysis and correction\n> workflow.\n> \n> This follows a three-phase approach: think \u2192 draft \u2192 revise, ensuring\n> systematic removal of invalid type testing code while maintaining the\n> integrity of valid E2E tests.\n\n### Description of {@link revise} property:\n\n> Review and finalization phase.\n> \n> Contains the review of changes made and the final cleaned code that\n> should compile without the invalid API request errors. This ensures the\n> correction is complete and accurate.",
                    type: "object",
                    properties: {
                        think: {
                            description: "Initial analysis phase.\n\nContains the agent's analysis of what specific invalid request pattern\nwas found in the code and how it's causing the compilation error. This\nshould identify:\n\n- The exact pattern (as any, satisfies, TestValidator.error, etc.)\n- Line numbers and locations of violations\n- The TypeScript error codes being triggered\n- Why this constitutes invalid type testing\n\nExample: \"Detected TestValidator.error() call at line 45 with 'as any'\ncasting on request body containing deliberately wrong types (number for\nemail field). This is causing TS2345 compilation error.\"",
                            type: "string"
                        },
                        draft: {
                            description: "Draft correction phase.\n\nThe initial corrected code with the problematic API request sections\ncompletely removed while preserving all valid test code.\n\nRules for drafting:\n\n- Remove entire test functions containing type violations\n- Do not comment out code - delete it completely\n- Preserve test suite structure and valid tests\n- Maintain proper indentation and formatting\n- Keep imports that are still needed by remaining code",
                            type: "string"
                        },
                        revise: {
                            $ref: "#/$defs/IAutoBeTestCorrectInvalidRequestApplication.IReviseProps"
                        }
                    },
                    required: [
                        "think",
                        "draft",
                        "revise"
                    ],
                    additionalProperties: false,
                    $defs: {
                        "IAutoBeTestCorrectInvalidRequestApplication.IReviseProps": {
                            description: "Properties for the revision phase of the correction process.\n\nThis phase ensures that the removal was complete and the remaining code is\nvalid and compilable.",
                            type: "object",
                            properties: {
                                review: {
                                    description: "Review of the changes made.\n\nBrief explanation of what invalid API request code was removed and\nverification that valid test code was preserved. Should confirm:\n\n- Which patterns were found and removed\n- Line ranges that were deleted\n- Verification that valid tests remain intact\n- Confirmation that no partial fixes were applied\n\nExample: \"Removed lines 43-52 containing TestValidator.error with invalid\ntype casting. Verified remaining tests are valid and unaffected.\"",
                                    type: "string"
                                },
                                final: {
                                    description: "Final corrected code.\n\nThe complete, cleaned test code with all invalid API request sections\nremoved, ready for compilation.\n\nThis code must:\n\n- Compile without TypeScript errors\n- Contain only valid business logic tests\n- Have no `as any` or similar type violations\n- Maintain the original file structure\n- Be production-ready E2E test code",
                                    type: "string"
                                }
                            },
                            required: [
                                "review",
                                "final"
                            ]
                        }
                    }
                },
                description: "Rewrite function to remove code containing invalid type API requests.\n\nThis function is called when the agent detects code that attempts to send\nAPI requests with deliberately wrong types, causing TypeScript compilation\nerrors. The agent will remove the problematic code sections while\npreserving valid test code.\n\nCommon patterns that trigger this function:\n\n- TestValidator.error calls testing type violations\n- Missing required fields with type assertions\n- Wrong type assignments with satisfies operator\n- Nested type violations in complex objects\n- Partial type testing with invalid structures\n\nThe rationale for deletion:\n\n- Type validation is the server's responsibility, not E2E tests\n- TypeScript compiler should enforce type safety at compile time\n- Invalid type testing breaks the entire test suite compilation\n- E2E tests should focus on business logic, not type system violations",
                validate: (() => { const _io0 = input => "string" === typeof input.think && "string" === typeof input.draft && ("object" === typeof input.revise && null !== input.revise && _io1(input.revise)); const _io1 = input => "string" === typeof input.review && "string" === typeof input.final; const _vo0 = (input, _path, _exceptionable = true) => ["string" === typeof input.think || _report(_exceptionable, {
                        path: _path + ".think",
                        expected: "string",
                        value: input.think
                    }), "string" === typeof input.draft || _report(_exceptionable, {
                        path: _path + ".draft",
                        expected: "string",
                        value: input.draft
                    }), ("object" === typeof input.revise && null !== input.revise || _report(_exceptionable, {
                        path: _path + ".revise",
                        expected: "IAutoBeTestCorrectInvalidRequestApplication.IReviseProps",
                        value: input.revise
                    })) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, {
                        path: _path + ".revise",
                        expected: "IAutoBeTestCorrectInvalidRequestApplication.IReviseProps",
                        value: input.revise
                    })].every(flag => flag); const _vo1 = (input, _path, _exceptionable = true) => ["string" === typeof input.review || _report(_exceptionable, {
                        path: _path + ".review",
                        expected: "string",
                        value: input.review
                    }), "string" === typeof input.final || _report(_exceptionable, {
                        path: _path + ".final",
                        expected: "string",
                        value: input.final
                    })].every(flag => flag); const __is = input => "object" === typeof input && null !== input && _io0(input); let errors; let _report; return input => {
                    if (false === __is(input)) {
                        errors = [];
                        _report = __typia_transform__validateReport._validateReport(errors);
                        ((input, _path, _exceptionable = true) => ("object" === typeof input && null !== input || _report(true, {
                            path: _path + "",
                            expected: "IAutoBeTestCorrectInvalidRequestApplication.IProps",
                            value: input
                        })) && _vo0(input, _path + "", true) || _report(true, {
                            path: _path + "",
                            expected: "IAutoBeTestCorrectInvalidRequestApplication.IProps",
                            value: input
                        }))(input, "$input", true);
                        const success = 0 === errors.length;
                        return success ? {
                            success,
                            data: input
                        } : {
                            success,
                            errors,
                            data: input
                        };
                    }
                    return {
                        success: true,
                        data: input
                    };
                }; })()
            },
            {
                name: "reject",
                parameters: {
                    type: "object",
                    properties: {},
                    additionalProperties: false,
                    required: [],
                    $defs: {}
                },
                description: "Reject function when no invalid type API requests are detected.\n\nThis function is called when the compilation error is not related to\ninvalid API request types, indicating the agent should not intervene.\n\nCommon scenarios for rejection:\n\n- Syntax errors unrelated to type violations\n- Legitimate type mismatches that need fixing (not deletion)\n- Framework-specific compilation issues\n- Configuration or environment problems\n\nWhen called, this indicates that another specialized agent should handle\nthe compilation error, as it's outside this agent's domain.",
                validate: (() => { const __is = input => true; let errors; let _report; return input => {
                    if (false === __is(input)) {
                        errors = [];
                        _report = __typia_transform__validateReport._validateReport(errors);
                        ((input, _path, _exceptionable = true) => true)(input, "$input", true);
                        const success = 0 === errors.length;
                        return success ? {
                            success,
                            data: input
                        } : {
                            success,
                            errors,
                            data: input
                        };
                    }
                    return {
                        success: true,
                        data: input
                    };
                }; })()
            }
        ]
    },
    claude: {
        model: "claude",
        options: {
            reference: true,
            separate: null
        },
        functions: [
            {
                name: "rewrite",
                parameters: {
                    description: " - The analysis and correction properties\n\n------------------------------\n\nDescription of the current {@link IAutoBeTestCorrectInvalidRequestApplication.IProps} type:\n\n> Properties for the rewrite function containing the analysis and correction\n> workflow.\n> \n> This follows a three-phase approach: think \u2192 draft \u2192 revise, ensuring\n> systematic removal of invalid type testing code while maintaining the\n> integrity of valid E2E tests.",
                    type: "object",
                    properties: {
                        think: {
                            description: "Initial analysis phase.\n\nContains the agent's analysis of what specific invalid request pattern\nwas found in the code and how it's causing the compilation error. This\nshould identify:\n\n- The exact pattern (as any, satisfies, TestValidator.error, etc.)\n- Line numbers and locations of violations\n- The TypeScript error codes being triggered\n- Why this constitutes invalid type testing\n\nExample: \"Detected TestValidator.error() call at line 45 with 'as any'\ncasting on request body containing deliberately wrong types (number for\nemail field). This is causing TS2345 compilation error.\"",
                            type: "string"
                        },
                        draft: {
                            description: "Draft correction phase.\n\nThe initial corrected code with the problematic API request sections\ncompletely removed while preserving all valid test code.\n\nRules for drafting:\n\n- Remove entire test functions containing type violations\n- Do not comment out code - delete it completely\n- Preserve test suite structure and valid tests\n- Maintain proper indentation and formatting\n- Keep imports that are still needed by remaining code",
                            type: "string"
                        },
                        revise: {
                            description: "Review and finalization phase.\n\nContains the review of changes made and the final cleaned code that\nshould compile without the invalid API request errors. This ensures the\ncorrection is complete and accurate.",
                            $ref: "#/$defs/IAutoBeTestCorrectInvalidRequestApplication.IReviseProps"
                        }
                    },
                    required: [
                        "think",
                        "draft",
                        "revise"
                    ],
                    additionalProperties: false,
                    $defs: {
                        "IAutoBeTestCorrectInvalidRequestApplication.IReviseProps": {
                            description: "Properties for the revision phase of the correction process.\n\nThis phase ensures that the removal was complete and the remaining code is\nvalid and compilable.",
                            type: "object",
                            properties: {
                                review: {
                                    description: "Review of the changes made.\n\nBrief explanation of what invalid API request code was removed and\nverification that valid test code was preserved. Should confirm:\n\n- Which patterns were found and removed\n- Line ranges that were deleted\n- Verification that valid tests remain intact\n- Confirmation that no partial fixes were applied\n\nExample: \"Removed lines 43-52 containing TestValidator.error with invalid\ntype casting. Verified remaining tests are valid and unaffected.\"",
                                    type: "string"
                                },
                                final: {
                                    description: "Final corrected code.\n\nThe complete, cleaned test code with all invalid API request sections\nremoved, ready for compilation.\n\nThis code must:\n\n- Compile without TypeScript errors\n- Contain only valid business logic tests\n- Have no `as any` or similar type violations\n- Maintain the original file structure\n- Be production-ready E2E test code",
                                    type: "string"
                                }
                            },
                            required: [
                                "review",
                                "final"
                            ]
                        }
                    }
                },
                description: "Rewrite function to remove code containing invalid type API requests.\n\nThis function is called when the agent detects code that attempts to send\nAPI requests with deliberately wrong types, causing TypeScript compilation\nerrors. The agent will remove the problematic code sections while\npreserving valid test code.\n\nCommon patterns that trigger this function:\n\n- TestValidator.error calls testing type violations\n- Missing required fields with type assertions\n- Wrong type assignments with satisfies operator\n- Nested type violations in complex objects\n- Partial type testing with invalid structures\n\nThe rationale for deletion:\n\n- Type validation is the server's responsibility, not E2E tests\n- TypeScript compiler should enforce type safety at compile time\n- Invalid type testing breaks the entire test suite compilation\n- E2E tests should focus on business logic, not type system violations",
                validate: (() => { const _io0 = input => "string" === typeof input.think && "string" === typeof input.draft && ("object" === typeof input.revise && null !== input.revise && _io1(input.revise)); const _io1 = input => "string" === typeof input.review && "string" === typeof input.final; const _vo0 = (input, _path, _exceptionable = true) => ["string" === typeof input.think || _report(_exceptionable, {
                        path: _path + ".think",
                        expected: "string",
                        value: input.think
                    }), "string" === typeof input.draft || _report(_exceptionable, {
                        path: _path + ".draft",
                        expected: "string",
                        value: input.draft
                    }), ("object" === typeof input.revise && null !== input.revise || _report(_exceptionable, {
                        path: _path + ".revise",
                        expected: "IAutoBeTestCorrectInvalidRequestApplication.IReviseProps",
                        value: input.revise
                    })) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, {
                        path: _path + ".revise",
                        expected: "IAutoBeTestCorrectInvalidRequestApplication.IReviseProps",
                        value: input.revise
                    })].every(flag => flag); const _vo1 = (input, _path, _exceptionable = true) => ["string" === typeof input.review || _report(_exceptionable, {
                        path: _path + ".review",
                        expected: "string",
                        value: input.review
                    }), "string" === typeof input.final || _report(_exceptionable, {
                        path: _path + ".final",
                        expected: "string",
                        value: input.final
                    })].every(flag => flag); const __is = input => "object" === typeof input && null !== input && _io0(input); let errors; let _report; return input => {
                    if (false === __is(input)) {
                        errors = [];
                        _report = __typia_transform__validateReport._validateReport(errors);
                        ((input, _path, _exceptionable = true) => ("object" === typeof input && null !== input || _report(true, {
                            path: _path + "",
                            expected: "IAutoBeTestCorrectInvalidRequestApplication.IProps",
                            value: input
                        })) && _vo0(input, _path + "", true) || _report(true, {
                            path: _path + "",
                            expected: "IAutoBeTestCorrectInvalidRequestApplication.IProps",
                            value: input
                        }))(input, "$input", true);
                        const success = 0 === errors.length;
                        return success ? {
                            success,
                            data: input
                        } : {
                            success,
                            errors,
                            data: input
                        };
                    }
                    return {
                        success: true,
                        data: input
                    };
                }; })()
            },
            {
                name: "reject",
                parameters: {
                    type: "object",
                    properties: {},
                    additionalProperties: false,
                    required: [],
                    $defs: {}
                },
                description: "Reject function when no invalid type API requests are detected.\n\nThis function is called when the compilation error is not related to\ninvalid API request types, indicating the agent should not intervene.\n\nCommon scenarios for rejection:\n\n- Syntax errors unrelated to type violations\n- Legitimate type mismatches that need fixing (not deletion)\n- Framework-specific compilation issues\n- Configuration or environment problems\n\nWhen called, this indicates that another specialized agent should handle\nthe compilation error, as it's outside this agent's domain.",
                validate: (() => { const __is = input => true; let errors; let _report; return input => {
                    if (false === __is(input)) {
                        errors = [];
                        _report = __typia_transform__validateReport._validateReport(errors);
                        ((input, _path, _exceptionable = true) => true)(input, "$input", true);
                        const success = 0 === errors.length;
                        return success ? {
                            success,
                            data: input
                        } : {
                            success,
                            errors,
                            data: input
                        };
                    }
                    return {
                        success: true,
                        data: input
                    };
                }; })()
            }
        ]
    },
};
//# sourceMappingURL=orchestrateTestCorrectInvalidRequest.js.map