Class: RSmolagent::Tools::RubyExecutorTool

Inherits:
RSmolagent::Tool show all
Defined in:
lib/rsmolagent/tools/ruby_executor.rb

Instance Attribute Summary

Attributes inherited from RSmolagent::Tool

#description, #input_schema, #name

Instance Method Summary collapse

Methods inherited from RSmolagent::Tool

#call, #to_json_schema

Constructor Details

#initialize(name: "ruby_executor", description: nil) ⇒ RubyExecutorTool

Returns a new instance of RubyExecutorTool.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rsmolagent/tools/ruby_executor.rb', line 6

def initialize(name: "ruby_executor", description: nil)
  description ||= "Executes Ruby code in a controlled environment. Use this to run custom Ruby code."
  
  super(
    name: name,
    description: description,
    input_schema: {
      code: {
        type: "string",
        description: "The Ruby code to execute. Can include class and method definitions."
      }
    }
  )
  
  # Set of allowed classes/modules to access
  @allowed_constants = [
    'Array', 'Hash', 'String', 'Integer', 'Float', 'Time', 'Date',
    'Enumerable', 'Math', 'JSON', 'CSV', 'URI', 'Net', 'File', 'Dir',
    'StringIO', 'Regexp'
  ]
end

Instance Method Details

#execute(args) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rsmolagent/tools/ruby_executor.rb', line 28

def execute(args)
  code = args[:code]
  return "Error: No code provided" if code.nil? || code.strip.empty?
  
  # Capture stdout to return it along with the result
  original_stdout = $stdout
  captured_stdout = StringIO.new
  $stdout = captured_stdout
  
  result = nil
  begin
    # Execute the code in the current binding with security limitations
    result = execute_with_safety(code)
    
    # Format the output
    stdout_content = captured_stdout.string.strip
    
    if stdout_content.empty?
      "Result: #{result.inspect}"
    else
      "Output:\n#{stdout_content}\n\nResult: #{result.inspect}"
    end
  rescue => e
    "Error: #{e.message}\n#{e.backtrace.first(3).join("\n")}"
  ensure
    # Restore stdout
    $stdout = original_stdout
  end
end