"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ToolExecutor = void 0;
const child_process_1 = require("child_process");
const promises_1 = require("fs/promises");
const path_1 = require("path");
/**
 * Tool executor for the agentic engine
 * Handles: read_file, write_file, run_command
 */
class ToolExecutor {
    constructor(workspaceRoot = process.cwd()) {
        this.workspaceRoot = (0, path_1.resolve)(workspaceRoot);
    }
    /**
     * Resolve a path relative to workspace root
     */
    resolvePath(filePath) {
        if ((0, path_1.isAbsolute)(filePath)) {
            // For security, only allow paths within workspace
            const resolved = (0, path_1.resolve)(filePath);
            if (resolved.startsWith(this.workspaceRoot)) {
                return resolved;
            }
            throw new Error(`Access denied: ${filePath} is outside workspace`);
        }
        return (0, path_1.resolve)(this.workspaceRoot, filePath);
    }
    /**
     * Read a file
     */
    async readFile(filePath) {
        try {
            const resolvedPath = this.resolvePath(filePath);
            await (0, promises_1.access)(resolvedPath, promises_1.constants.R_OK);
            const content = await (0, promises_1.readFile)(resolvedPath, "utf8");
            return content;
        }
        catch (error) {
            throw new Error(`Failed to read file ${filePath}: ${error.message}`);
        }
    }
    /**
     * Write a file
     */
    async writeFile(filePath, content) {
        try {
            const resolvedPath = this.resolvePath(filePath);
            // Ensure directory exists
            const dir = (0, path_1.resolve)(resolvedPath, "..");
            // In a real implementation, we would create directories here
            await (0, promises_1.writeFile)(resolvedPath, content, "utf8");
        }
        catch (error) {
            throw new Error(`Failed to write file ${filePath}: ${error.message}`);
        }
    }
    /**
     * Run a command
     */
    async runCommand(command) {
        return new Promise((resolve, reject) => {
            (0, child_process_1.exec)(command, { cwd: this.workspaceRoot, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
                if (error) {
                    resolve({
                        stdout,
                        stderr,
                        exitCode: error.code ?? 1
                    });
                }
                else {
                    resolve({
                        stdout,
                        stderr,
                        exitCode: 0
                    });
                }
            });
        });
    }
}
exports.ToolExecutor = ToolExecutor;
//# sourceMappingURL=tool-executor.js.map