"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BashTool = void 0;
const child_process_1 = require("child_process");
const util_1 = require("util");
const inquirer_1 = __importDefault(require("inquirer"));
const chalk_1 = __importDefault(require("chalk"));
const execAsync = (0, util_1.promisify)(child_process_1.exec);
class BashTool {
    name = 'bash';
    requireConfirmation;
    constructor(requireConfirmation = true) {
        this.requireConfirmation = requireConfirmation;
    }
    definition = {
        type: 'function',
        function: {
            name: 'bash',
            description: 'Execute bash commands on the local system',
            parameters: {
                type: 'object',
                properties: {
                    command: {
                        type: 'string',
                        description: 'The bash command to execute'
                    },
                    working_directory: {
                        type: 'string',
                        description: 'Optional working directory for the command'
                    },
                    timeout: {
                        type: 'number',
                        description: 'Timeout in milliseconds (default: 30000)'
                    }
                },
                required: ['command']
            }
        },
        serverInvocable: true,
        sideEffects: 'external',
        requiresConfirmation: true
    };
    async execute(args, _context) {
        const { command, working_directory, timeout = 30000 } = args;
        try {
            const options = {
                timeout,
                maxBuffer: 1024 * 1024 * 10 // 10MB
            };
            if (working_directory) {
                options.cwd = working_directory;
            }
            console.log(chalk_1.default.yellow(`\nExecuting: ${command}`));
            if (working_directory) {
                console.log(chalk_1.default.gray(`In directory: ${working_directory}`));
            }
            const { stdout, stderr } = await execAsync(command, options);
            let output = '';
            if (stdout) {
                output += stdout;
            }
            if (stderr) {
                output += '\n[stderr]\n' + stderr;
            }
            // Truncate output if too long
            const maxLength = 10000;
            if (output.length > maxLength) {
                output = output.substring(0, maxLength) + '\n...[truncated]';
            }
            return {
                success: true,
                output: {
                    stdout: stdout || '',
                    stderr: stderr || '',
                    combined: output,
                    exit_code: 0
                }
            };
        }
        catch (error) {
            let errorMessage = 'Command execution failed';
            let exitCode = -1;
            if (error.code === 'ETIMEDOUT') {
                errorMessage = `Command timed out after ${timeout}ms`;
            }
            else if (error.code) {
                errorMessage = `Command failed with code ${error.code}`;
                exitCode = error.code;
            }
            else if (error.message) {
                errorMessage = error.message;
            }
            return {
                success: false,
                error: errorMessage,
                output: {
                    stdout: error.stdout || '',
                    stderr: error.stderr || '',
                    exit_code: exitCode
                }
            };
        }
    }
    validateArgs(args) {
        if (!args || typeof args !== 'object')
            return false;
        if (!args.command || typeof args.command !== 'string')
            return false;
        if (args.working_directory && typeof args.working_directory !== 'string')
            return false;
        if (args.timeout && typeof args.timeout !== 'number')
            return false;
        return true;
    }
    async requestPermission(args, _context) {
        if (!this.requireConfirmation) {
            return true;
        }
        console.log(chalk_1.default.yellow('\n⚠️  Tool execution request:'));
        console.log(chalk_1.default.cyan('Tool:'), this.name);
        console.log(chalk_1.default.cyan('Command:'), args.command);
        if (args.working_directory) {
            console.log(chalk_1.default.cyan('Directory:'), args.working_directory);
        }
        const { confirm } = await inquirer_1.default.prompt([
            {
                type: 'confirm',
                name: 'confirm',
                message: 'Do you want to execute this command?',
                default: false
            }
        ]);
        return confirm;
    }
}
exports.BashTool = BashTool;
//# sourceMappingURL=bash.tool.js.map