Class: SharedTools::Tools::Eval::ShellEvalTool

Inherits:
RubyLLM::Tool
  • Object
show all
Defined in:
lib/shared_tools/tools/eval/shell_eval_tool.rb

Overview

Examples:

tool = SharedTools::Tools::Eval::ShellEvalTool.new
tool.execute(command: "ls -la")
tool.execute(command: "ls -la", workdir: "/tmp")

Constant Summary collapse

STDOUT_MAX =
5000
STDERR_MAX =
2000

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger: nil) ⇒ ShellEvalTool

Returns a new instance of ShellEvalTool.

Parameters:

  • logger (Logger) (defaults to: nil)

    optional logger



26
27
28
# File 'lib/shared_tools/tools/eval/shell_eval_tool.rb', line 26

def initialize(logger: nil)
  @logger = logger || RubyLLM.logger
end

Class Method Details

.nameObject



16
# File 'lib/shared_tools/tools/eval/shell_eval_tool.rb', line 16

def self.name = 'eval_shell'

Instance Method Details

#execute(command:, workdir: nil) ⇒ Hash

Returns execution result.

Parameters:

  • command (String)

    shell command to execute

  • workdir (String, nil) (defaults to: nil)

    working directory for the command

Returns:

  • (Hash)

    execution result



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/shared_tools/tools/eval/shell_eval_tool.rb', line 34

def execute(command:, workdir: nil)
  @logger.info("Requesting permission to execute command: '#{command}'")

  if command.strip.empty?
    error_msg = "Command cannot be empty"
    @logger.error(error_msg)
    return { error: error_msg }
  end

  if workdir
    unless File.directory?(workdir)
      return { error: "Working directory not found: #{workdir}" }
    end
  end

  allowed = SharedTools.execute?(tool: self.class.to_s, stuff: command)

  unless allowed
    @logger.warn("User declined to execute the command: '#{command}'")
    return { error: "User declined to execute the command" }
  end

  @logger.info("Executing command: '#{command}'")

  opts = workdir ? { chdir: workdir } : {}
  stdout, stderr, status = Open3.capture3(command, **opts)

  stdout = truncate(stdout, STDOUT_MAX)
  stderr = truncate(stderr, STDERR_MAX)

  if status.success?
    @logger.debug("Command execution completed successfully with #{stdout.bytesize} bytes of output")
    { stdout: stdout, exit_status: status.exitstatus }
  else
    @logger.warn("Command execution failed with exit code #{status.exitstatus}: #{stderr}")
    { error: "Command failed with exit code #{status.exitstatus}", stderr: stderr, exit_status: status.exitstatus }
  end
rescue => e
  @logger.error("Command execution failed: #{e.message}")
  { error: e.message }
end