Class: Looped::Tools::RunCommand

Inherits:
DSPy::Tools::Base
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/looped/tools/run_command.rb

Constant Summary collapse

DEFAULT_TIMEOUT =
30

Instance Method Summary collapse

Instance Method Details

#call(command:, timeout: DEFAULT_TIMEOUT) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
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
# File 'lib/looped/tools/run_command.rb', line 17

def call(command:, timeout: DEFAULT_TIMEOUT)
  # TODO: Implement Docker sandbox via trusted-sandbox gem for production
  pid = T.let(nil, T.nilable(Integer))
  output = +''

  begin
    stdin, stdout_err, wait_thr = Open3.popen2e(command)
    pid = wait_thr.pid
    stdin.close

    # Wait for process with timeout using a thread
    reader = Thread.new { stdout_err.read }

    if wait_thr.join(timeout)
      # Process completed in time
      output = reader.value
      exit_status = wait_thr.value
      "Exit code: #{exit_status.exitstatus}\n#{output}"
    else
      # Timeout - kill the process
      reader.kill
      Process.kill('TERM', pid)
      sleep 0.1
      begin
        Process.kill('KILL', pid) if wait_thr.alive?
      rescue Errno::ESRCH
        # Process already dead
      end
      wait_thr.join
      "Error: Command timed out after #{timeout} seconds"
    end
  rescue StandardError => e
    "Error: #{e.message}"
  ensure
    stdout_err&.close rescue nil
  end
end