Class: LLM::Function::Fork::Task

Inherits:
Task
  • Object
show all
Defined in:
lib/llm/function/fork/task.rb

Overview

The Task class wraps a fork-backed function call and exchanges control and result messages with the child process.

Instance Attribute Summary

Attributes inherited from Task

#function

Instance Method Summary collapse

Constructor Details

#initialize(fn, options = {}) ⇒ LLM::Function::Fork::Task

Parameters:

Options Hash (options):



13
14
15
16
17
18
# File 'lib/llm/function/fork/task.rb', line 13

def initialize(fn, options = {})
  super
  @tracer = options.fetch(:tracer, nil)
  @spawned = false
  @waited = false
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


52
53
54
55
56
57
58
59
60
# File 'lib/llm/function/fork/task.rb', line 52

def alive?
  return false if @waited || !@pid
  result = ::Process.waitpid(@pid, ::Process::WNOHANG)
  @waited = !result.nil?
  !@waited
rescue Errno::ECHILD
  @waited = true
  false
end

#group_classClass

Returns:

  • (Class)


93
94
95
# File 'lib/llm/function/fork/task.rb', line 93

def group_class
  LLM::Function::Fork::Group
end

#interrupt!nil Also known as: cancel!

Returns:

  • (nil)


64
65
66
67
68
69
70
# File 'lib/llm/function/fork/task.rb', line 64

def interrupt!
  return nil if @waited
  @ch.control.write(:interrupt)
  nil
rescue Errno::ESRCH, IOError
  nil
end

#spawnLLM::Function::Fork::Task



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
# File 'lib/llm/function/fork/task.rb', line 22

def spawn
  return if @guarded
  @span = @tracer&.on_tool_start(
    id: @function.id, name: @function.name,
    arguments: @function.arguments, model: @function.model
  )
  @ch = LLM::Object.from(
    control: xchan(:marshal),
    result: xchan(:marshal, sock: Socket::SOCK_STREAM)
  )
  @pid = Kernel.fork do
    ##
    # The child inherits the parent's terminal. When
    # the runtime runs under a curses REPL, the forked
    # tool writing to the tty would clobber the parent's
    # display (a blank screen). Redirect the child's
    # stdout/stderr to null so it keeps off the user's
    # terminal. A tool that genuinely needs the terminal
    # can reopen it via /dev/tty; the tty fd stays
    # available to the child.
    $stdout.reopen(File::NULL)
    $stderr.reopen(File::NULL)
    Fork::Job.new(@function, @ch).call
  end
  @spawned = true
  self
end

#waitLLM::Function::Return Also known as: value



75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/llm/function/fork/task.rb', line 75

def wait
  return @guarded if @guarded
  spawn unless @spawned
  kind, data = @ch.result.recv
  raise LLM::Interrupt if kind == :interrupt
  raise ArgumentError, "Unknown fork message: #{kind.inspect}" unless kind == :result
  result = Return.new(data[:id], data[:name], data[:value])
  reap
  @tracer&.on_tool_finish(result:, span: @span)
  result
ensure
  reap
  [@ch.control, @ch.result].each { _1.close unless _1.closed? }
end