Class: Girb::Tools::EvaluateCode

Inherits:
Base
  • Object
show all
Defined in:
lib/girb/tools/evaluate_code.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

available?, to_gemini_tool, tool_name

Class Method Details

.descriptionObject



10
11
12
13
# File 'lib/girb/tools/evaluate_code.rb', line 10

def description
  "Execute arbitrary Ruby code in the current context and return the result. " \
  "Use this to call methods, create objects, test conditions, or perform any Ruby operation."
end

.parametersObject



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/girb/tools/evaluate_code.rb', line 15

def parameters
  {
    type: "object",
    properties: {
      code: {
        type: "string",
        description: "Ruby code to execute (e.g., 'user.valid?', 'Order.where(status: :pending).count', 'arr.map { |x| x * 2 }')"
      }
    },
    required: ["code"]
  }
end

Instance Method Details

#execute(binding, code:) ⇒ Object



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
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/girb/tools/evaluate_code.rb', line 29

def execute(binding, code:)
  captured_output = StringIO.new
  original_stdout = $stdout
  error_response = nil

  # A single ensure guarantees $stdout is restored on every exit path —
  # including exceptions we intentionally let propagate (Interrupt,
  # SignalException), which the rescue clauses below do NOT catch.
  begin
    $stdout = captured_output
    result = binding.eval(code)
  rescue SyntaxError => e
    error_response = { code: code, error: "Syntax error: #{e.message}", success: false }
  rescue ScriptError, StandardError => e
    # ScriptError (LoadError/NotImplementedError) is NOT a StandardError,
    # so without it such errors would escape and crash the tool loop.
    error_response = { code: code, error: "#{e.class}: #{e.message}", backtrace: e.backtrace&.first(5), success: false }
  ensure
    $stdout = original_stdout
  end

  stdout_str = captured_output.string
  # Also print captured output to the real console for user visibility
  # (after $stdout is restored, so it reaches the real terminal).
  print stdout_str unless stdout_str.empty?

  if error_response
    error_response[:stdout] = stdout_str unless stdout_str.empty?
    return error_response
  end

  response = {
    code: code,
    result: safe_inspect(result),
    result_class: result.class.name,
    success: true
  }
  response[:stdout] = stdout_str unless stdout_str.empty?
  response
end