"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReactLoop = void 0;
/**
 * React Loop (Reasoning and Acting) for the agentic engine
 * Implements the ReAct pattern: Reason -> Act -> Observe -> ... until completion
 */
class ReactLoop {
    constructor(toolExecutor, planner, modelRouter, maxSteps = 10) {
        this.toolExecutor = toolExecutor;
        this.planner = planner;
        this.modelRouter = modelRouter;
        this.maxSteps = maxSteps;
    }
    /**
     * Execute the ReAct loop for a given prompt
     */
    async execute(prompt) {
        console.log(`🤖 Starting agentic reasoning for: "${prompt}"`);
        // Step 1: Create a plan
        const plan = await this.planner.createPlan(prompt);
        console.log(`📋 Created plan with ${plan.length} steps`);
        let iterations = 0;
        let currentStepIndex = 0;
        let accumulatedOutput = "";
        // Step 2: Execute the loop
        while (iterations < this.maxSteps) {
            iterations++;
            console.log(`🔁 Iteration ${iterations}`);
            // Check if plan is complete
            if (this.planner.isPlanComplete(plan)) {
                console.log("✅ Plan completed successfully");
                break;
            }
            // Get next step
            const nextStep = this.planner.getNextStep(plan);
            if (!nextStep) {
                console.log("⚠️ No next step found, completing");
                break;
            }
            console.log(`🎯 Executing step ${nextStep.id}: ${nextStep.description}`);
            // Reason: Think about what we need to do (in a real implementation, this would involve the LLM)
            // For now, we'll just proceed to action
            // Act: Execute the step
            let stepResult = "";
            try {
                if (nextStep.tool) {
                    switch (nextStep.tool) {
                        case "read_file":
                            const content = await this.toolExecutor.readFile(nextStep.toolArgs.filePath);
                            stepResult = `File content:\n${content}`;
                            break;
                        case "write_file":
                            await this.toolExecutor.writeFile(nextStep.toolArgs.filePath, nextStep.toolArgs.content);
                            stepResult = `File written successfully: ${nextStep.toolArgs.filePath}`;
                            break;
                        case "run_command":
                            const { stdout, stderr, exitCode } = await this.toolExecutor.runCommand(nextStep.toolArgs.command);
                            stepResult = `Command exited with code ${exitCode}\n`;
                            if (stdout)
                                stepResult += `stdout:\n${stdout}\n`;
                            if (stderr)
                                stepResult += `stderr:\n${stderr}\n`;
                            break;
                    }
                }
                else {
                    // No tool needed, just provide reasoning
                    stepResult = "Provided answer based on reasoning";
                }
                // Observe: Process the result
                accumulatedOutput += `Step ${nextStep.id} result:\n${stepResult}\n---\n`;
                // Mark step as completed
                this.planner.markStepCompleted(plan, nextStep.id);
                console.log(`✅ Step ${nextStep.id} completed`);
            }
            catch (error) {
                console.error(`❌ Step ${nextStep.id} failed:`, error.message);
                // In a real implementation, we would retry with a different approach
                // or adjust the plan based on the error
                accumulatedOutput += `Step ${nextStep.id} failed: ${error.message}\n---\n`;
                // For now, we'll still mark it as completed to avoid infinite loops
                // but in a real system, we might want to retry or replan
                this.planner.markStepCompleted(plan, nextStep.id);
            }
            currentStepIndex++;
        }
        // Check if we exceeded max steps
        if (iterations >= this.maxSteps && !this.planner.isPlanComplete(plan)) {
            console.log(`⚠️ Reached maximum iterations (${this.maxSteps})`);
            return {
                success: false,
                output: accumulatedOutput || "Max iterations reached without completion",
                steps: plan,
                iterations
            };
        }
        // Return the final result
        const success = this.planner.isPlanComplete(plan);
        return {
            success,
            output: success
                ? accumulatedOutput || "Task completed successfully"
                : accumulatedOutput || "Task incomplete",
            steps: plan,
            iterations
        };
    }
}
exports.ReactLoop = ReactLoop;
//# sourceMappingURL=react-loop.js.map