Class: ConsoleAgent::Executor

Inherits:
Object
  • Object
show all
Defined in:
lib/console_agent/executor.rb

Constant Summary collapse

CODE_REGEX =
/```ruby\s*\n(.*?)```/m
ANY_CODE_FENCE_REGEX =

Matches any fenced code block (“‘anything … “`)

/```\w*\s*\n.*?```/m

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(binding_context, channel: nil) ⇒ Executor

Returns a new instance of Executor.



49
50
51
52
53
54
55
56
# File 'lib/console_agent/executor.rb', line 49

def initialize(binding_context, channel: nil)
  @binding_context = binding_context
  @channel = channel
  @omitted_outputs = {}
  @omitted_counter = 0
  @output_store = {}
  @output_counter = 0
end

Instance Attribute Details

#binding_contextObject (readonly)

Returns the value of attribute binding_context.



46
47
48
# File 'lib/console_agent/executor.rb', line 46

def binding_context
  @binding_context
end

#last_errorObject (readonly)

Returns the value of attribute last_error.



46
47
48
# File 'lib/console_agent/executor.rb', line 46

def last_error
  @last_error
end

#last_safety_errorObject (readonly)

Returns the value of attribute last_safety_error.



46
47
48
# File 'lib/console_agent/executor.rb', line 46

def last_safety_error
  @last_safety_error
end

#last_safety_exceptionObject (readonly)

Returns the value of attribute last_safety_exception.



46
47
48
# File 'lib/console_agent/executor.rb', line 46

def last_safety_exception
  @last_safety_exception
end

#on_promptObject

Returns the value of attribute on_prompt.



47
48
49
# File 'lib/console_agent/executor.rb', line 47

def on_prompt
  @on_prompt
end

Instance Method Details

#confirm_and_execute(code) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/console_agent/executor.rb', line 175

def confirm_and_execute(code)
  return nil if code.nil? || code.strip.empty?

  @last_cancelled = false
  @last_answer = nil
  prompt = execute_prompt

  if @channel
    answer = @channel.confirm(prompt)
  else
    $stdout.print colorize(prompt, :yellow)
    @on_prompt&.call
    answer = $stdin.gets.to_s.strip.downcase
    echo_stdin(answer)
  end
  @last_answer = answer

  loop do
    case answer
    when 'y', 'yes', 'a'
      result = execute(code)
      if @last_safety_error
        return nil unless danger_allowed?
        return offer_danger_retry(code)
      end
      return result
    when 'd', 'danger'
      unless danger_allowed?
        display_error("Safety guards cannot be disabled in this channel.")
        return nil
      end
      if @channel
        @channel.display_error("Executing with safety guards disabled.")
      else
        $stdout.puts colorize("Executing with safety guards disabled.", :red)
      end
      return execute_unsafe(code)
    when 'e', 'edit'
      edited = if @channel && @channel.supports_editing?
                 @channel.edit_code(code)
               else
                 open_in_editor(code)
               end
      if edited && edited != code
        $stdout.puts colorize("# Edited code:", :yellow)
        $stdout.puts highlight_code(edited)
        if @channel
          edit_answer = @channel.confirm("Execute edited code? [y/N] ")
        else
          $stdout.print colorize("Execute edited code? [y/N] ", :yellow)
          edit_answer = $stdin.gets.to_s.strip.downcase
          echo_stdin(edit_answer)
        end
        if edit_answer == 'y'
          return execute(edited)
        else
          $stdout.puts colorize("Cancelled.", :yellow)
          return nil
        end
      else
        return execute(code)
      end
    when 'n', 'no', ''
      $stdout.puts colorize("Cancelled.", :yellow)
      @last_cancelled = true
      return nil
    else
      if @channel
        answer = @channel.confirm(prompt)
      else
        $stdout.print colorize(prompt, :yellow)
        @on_prompt&.call
        answer = $stdin.gets.to_s.strip.downcase
        echo_stdin(answer)
      end
      @last_answer = answer
    end
  end
end

#display_response(response) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/console_agent/executor.rb', line 66

def display_response(response)
  code = extract_code(response)
  explanation = response.gsub(ANY_CODE_FENCE_REGEX, '').strip

  if @channel
    $stdout.puts
    @channel.display(explanation) unless explanation.empty?
    @channel.display_code(code) unless code.empty?
  else
    $stdout.puts
    $stdout.puts colorize(explanation, :cyan) unless explanation.empty?

    unless code.empty?
      $stdout.puts
      $stdout.puts colorize("# Generated code:", :yellow)
      $stdout.puts highlight_code(code)
      $stdout.puts
    end
  end

  code
end

#execute(code) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/console_agent/executor.rb', line 89

def execute(code)
  return nil if code.nil? || code.strip.empty?

  @last_error = nil
  @last_safety_error = false
  @last_safety_exception = nil
  captured_output = StringIO.new
  old_stdout = $stdout
  # Tee output: capture it and also print to the real stdout
  $stdout = TeeIO.new(old_stdout, captured_output)

  result = with_safety_guards do
    binding_context.eval(code, "(console_agent)", 1)
  end

  $stdout = old_stdout

  # Send captured puts output through channel before the return value
  if @channel && !captured_output.string.empty?
    @channel.display_result_output(captured_output.string)
  end

  display_result(result)

  @last_output = captured_output.string
  result
rescue ConsoleAgent::SafetyError => e
  $stdout = old_stdout if old_stdout
  @last_error = "SafetyError: #{e.message}"
  @last_safety_error = true
  @last_safety_exception = e
  display_error("Blocked: #{e.message}")
  @last_output = captured_output&.string
  nil
rescue SyntaxError => e
  $stdout = old_stdout if old_stdout
  @last_error = "SyntaxError: #{e.message}"
  display_error(@last_error)
  @last_output = nil
  nil
rescue => e
  $stdout = old_stdout if old_stdout
  # Check if a SafetyError is wrapped (e.g. ActiveRecord::StatementInvalid wrapping our error)
  if safety_error?(e)
    safety_exc = extract_safety_exception(e)
    safety_msg = safety_exc ? safety_exc.message : e.message
    @last_error = "SafetyError: #{safety_msg}"
    @last_safety_error = true
    @last_safety_exception = safety_exc
    display_error("Blocked: #{safety_msg}")
    @last_output = captured_output&.string
    return nil
  end
  @last_error = "#{e.class}: #{e.message}"
  display_error("Error: #{@last_error}")
  e.backtrace.first(3).each { |line| display_error("  #{line}") }
  @last_output = captured_output&.string
  nil
end

#expand_output(id) ⇒ Object



153
154
155
# File 'lib/console_agent/executor.rb', line 153

def expand_output(id)
  @omitted_outputs[id]
end

#extract_code(response) ⇒ Object



58
59
60
61
# File 'lib/console_agent/executor.rb', line 58

def extract_code(response)
  match = response.match(CODE_REGEX)
  match ? match[1].strip : ''
end

#last_answerObject



167
168
169
# File 'lib/console_agent/executor.rb', line 167

def last_answer
  @last_answer
end

#last_cancelled?Boolean

Returns:

  • (Boolean)


171
172
173
# File 'lib/console_agent/executor.rb', line 171

def last_cancelled?
  @last_cancelled
end

#last_outputObject



149
150
151
# File 'lib/console_agent/executor.rb', line 149

def last_output
  @last_output
end

#offer_danger_retry(code) ⇒ Object



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/console_agent/executor.rb', line 255

def offer_danger_retry(code)
  return nil unless danger_allowed?

  exc = @last_safety_exception
  blocked_key = exc&.blocked_key
  guard = exc&.guard

  if blocked_key && guard
    allow_desc = allow_description(guard, blocked_key)
    $stdout.puts colorize("  [d] re-run with all safe mode disabled", :yellow)
    $stdout.puts colorize("  [a] allow #{allow_desc} for this session", :yellow)
    $stdout.puts colorize("  [N] cancel", :yellow)
    prompt_text = "Choice: "
  else
    prompt_text = "Re-run with safe mode disabled? [y/N] "
  end

  if @channel
    answer = @channel.confirm(prompt_text)
  else
    $stdout.print colorize(prompt_text, :yellow)
    answer = $stdin.gets.to_s.strip.downcase
    echo_stdin(answer)
  end

  case answer
  when 'a', 'allow'
    if blocked_key && guard
      ConsoleAgent.configuration.safety_guards.allow(guard, blocked_key)
      allow_desc = allow_description(guard, blocked_key)
      $stdout.puts colorize("Allowed #{allow_desc} for this session.", :green)
      return execute(code)
    else
      if @channel
        answer = @channel.confirm("Nothing to allow — re-run with safe mode disabled instead? [y/N] ")
      else
        $stdout.puts colorize("Nothing to allow — re-run with safe mode disabled instead? [y/N]", :yellow)
        answer = $stdin.gets.to_s.strip.downcase
        echo_stdin(answer)
      end
    end
  when 'd', 'danger', 'y', 'yes'
    $stdout.puts colorize("Executing with safety guards disabled.", :red)
    return execute_unsafe(code)
  end

  $stdout.puts colorize("Cancelled.", :yellow)
  nil
end

#recall_output(id) ⇒ Object



163
164
165
# File 'lib/console_agent/executor.rb', line 163

def recall_output(id)
  @output_store[id]
end

#store_output(content) ⇒ Object



157
158
159
160
161
# File 'lib/console_agent/executor.rb', line 157

def store_output(content)
  @output_counter += 1
  @output_store[@output_counter] = content
  @output_counter
end