Acme-Claude-Shell

 view release on metacpan or  search on metacpan

lib/Acme/Claude/Shell/Tools.pm  view on Meta::CPAN

package Acme::Claude::Shell::Tools;

use 5.020;
use strict;
use warnings;

use Exporter 'import';
our @EXPORT_OK = qw(shell_tools);

use Claude::Agent qw(tool);
use Claude::Agent::CLI qw(menu status ask_yn prompt start_spinner stop_spinner);
use IO::Async::Process;
use Future;
use Cwd qw(abs_path getcwd);
use File::Spec;
use Term::ANSIColor qw(colored);

sub shell_tools {
    my ($session) = @_;

    return [
        tool(
            'execute_command',
            'Execute a shell command and return its output. Use this for ALL shell operations including listing files, reading files, etc. The user will be prompted to approve each command.',
            {
                type       => 'object',
                properties => {
                    command => {
                        type        => 'string',
                        description => 'The shell command to execute (e.g., "ls -la", "cat file.txt", "find . -name *.pl")',
                    },
                    working_dir => {
                        type        => 'string',
                        description => 'Directory to run command in (optional, defaults to current directory)',
                    },
                },
                required => ['command'],
            },
            sub {
                my ($params, $loop) = @_;
                return _execute_command($session, $params, $loop);
            },
        ),

        tool(
            'get_working_directory',
            'Get the current working directory. This is safe and does not require user confirmation.',
            {
                type       => 'object',
                properties => {},
            },
            sub {
                my ($params, $loop) = @_;
                my $future = $loop->new_future;
                $future->done(_mcp_result(getcwd()));
                return $future;
            },
        ),

        tool(
            'read_file',
            'Read the contents of a file. Safe operation - does not require user confirmation. Use this instead of execute_command for reading files.',
            {
                type       => 'object',
                properties => {
                    path => {
                        type        => 'string',
                        description => 'Path to the file to read',
                    },
                    lines => {
                        type        => 'integer',
                        description => 'Number of lines to read from the beginning (optional)',
                    },
                    tail => {
                        type        => 'integer',
                        description => 'Number of lines to read from the end (optional)',
                    },
                },
                required => ['path'],
            },
            sub {
                my ($params, $loop) = @_;
                return _read_file_safe($session, $params, $loop);
            },
        ),

        tool(
            'list_directory',
            'List the contents of a directory. Safe operation - does not require user confirmation. Use this instead of execute_command for listing files.',
            {
                type       => 'object',
                properties => {
                    path => {
                        type        => 'string',
                        description => 'Path to the directory to list (defaults to current directory)',
                    },
                    pattern => {
                        type        => 'string',
                        description => 'Glob pattern to filter files (e.g., "*.pl", "*.txt")',
                    },
                    long_format => {
                        type        => 'boolean',
                        description => 'Show detailed file information (size, date, permissions)',
                    },
                    show_hidden => {
                        type        => 'boolean',
                        description => 'Include hidden files (starting with .)',
                    },
                },
            },
            sub {
                my ($params, $loop) = @_;
                return _list_directory_safe($session, $params, $loop);
            },
        ),

        tool(
            'search_files',
            'Search for files by name pattern or content. Safe operation - does not require user confirmation.',
            {
                type       => 'object',
                properties => {
                    pattern => {
                        type        => 'string',
                        description => 'File name pattern to search for (e.g., "*.pm", "config*")',
                    },
                    content => {
                        type        => 'string',
                        description => 'Text pattern to search for within files (grep)',
                    },
                    path => {
                        type        => 'string',
                        description => 'Directory to search in (defaults to current directory)',
                    },
                    max_depth => {
                        type        => 'integer',
                        description => 'Maximum directory depth to search',
                    },
                },
            },
            sub {
                my ($params, $loop) = @_;
                return _search_files_safe($session, $params, $loop);
            },
        ),

        tool(
            'get_system_info',
            'Get system information including OS, disk space, and memory. Safe operation - does not require user confirmation.',
            {
                type       => 'object',
                properties => {
                    info_type => {
                        type        => 'string',
                        description => 'Type of info: "all", "os", "disk", "memory", "processes" (defaults to "all")',
                        enum        => ['all', 'os', 'disk', 'memory', 'processes'],
                    },
                },
            },
            sub {
                my ($params, $loop) = @_;
                return _get_system_info($session, $params, $loop);
            },
        ),
    ];
}

sub _execute_command {
    my ($session, $params, $loop) = @_;

    my $command = $params->{command};
    my $dir = $params->{working_dir} // $session->working_dir;
    my $colorful = $session->colorful;

    if ($session->can('_spinner') && $session->_spinner) {
        stop_spinner($session->_spinner);
        $session->_spinner(undef);
    }

    my ($approved, $new_command) = _confirm_command($session, $command);

    unless ($approved) {
        my $future = $loop->new_future;
        $future->done(_mcp_result("User cancelled command", 1));
        return $future;
    }

    $command = $new_command if defined $new_command;

    if ($colorful) {
        $session->_spinner(start_spinner("Executing...", $loop));
    }

    push @{$session->_history}, {
        time    => _timestamp(),
        command => $command,
        status  => 'running',
    };

    my $future = $loop->new_future;
    my $stdout = '';
    my $stderr = '';

    my $process = IO::Async::Process->new(
        command => [ '/bin/sh', '-c', $command ],
        ($dir && -d $dir ? (setup => [ chdir => $dir ]) : ()),
        stdout => {
            into => \$stdout,
        },
        stderr => {
            into => \$stderr,
        },
        on_finish => sub {
            my ($self, $exitcode) = @_;
            my $exit_status = $exitcode >> 8;

            if ($exit_status != 0) {
                $session->_history->[-1]{status} = "exit $exit_status";
                my $output = $stderr || $stdout || "Command failed with exit code $exit_status";
                $future->done(_mcp_result($output));
            } else {
                $session->_history->[-1]{status} = 'success';
                $future->done(_mcp_result($stdout // ''));
            }
        },
        on_exception => sub {
            my ($self, $exception, $errno, $exitcode) = @_;
            $session->_history->[-1]{status} = 'error';
            $future->done(_mcp_result("Error: $exception", 1));
        },
    );

    $loop->add($process);

    return $future;
}

sub _mcp_result {
    my ($text, $is_error) = @_;
    return {
        content  => [{ type => 'text', text => $text }],
        is_error => $is_error ? 1 : 0,
    };
}

my @DANGEROUS_PATTERNS = (
    { pattern => qr/\brm\s+(-[rf]+|--recursive|--force)/i,
      reason  => 'Recursive or forced file deletion' },
    { pattern => qr/\bsudo\b/,
      reason  => 'Superuser command' },
    { pattern => qr/\bmkfs\b/,



( run in 0.855 second using v1.01-cache-2.11-cpan-234fa220139 )