Class: Legate::CLI::ToolCommands

Inherits:
BaseCommand show all
Includes:
OutputHelper
Defined in:
lib/legate/cli/tool_commands.rb

Overview

CLI commands for tool management using ToolRegistry

Instance Method Summary collapse

Methods included from OutputHelper

#output_error, #output_result, #status_message

Methods inherited from BaseCommand

#tree

Instance Method Details

#ai_generateObject



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
254
255
256
257
258
# File 'lib/legate/cli/tool_commands.rb', line 192

def ai_generate
  require_relative '../generators'

  description = nil
  from_stdin = false

  # Priority: --description > --prompt-file > stdin
  if options[:description] && !options[:description].strip.empty?
    description = options[:description].strip
  elsif options[:prompt_file]
    unless File.exist?(options[:prompt_file])
      say "Error: Prompt file '#{options[:prompt_file]}' not found.", :red
      exit(1)
    end
    description = File.read(options[:prompt_file]).strip
  elsif !$stdin.tty?
    # Reading from stdin (piped input)
    description = $stdin.read.strip
    from_stdin = true
  end

  if description.nil? || description.empty?
    say 'Error: No description provided. Use --description, --prompt-file, or pipe via stdin.', :red
    exit(1)
  end

  # Determine output mode
  output_to_stdout = options[:stdout] || from_stdin

  say 'Generating tool code via AI...', :cyan unless output_to_stdout

  begin
    result = Legate::Generators::ToolGenerator.generate(description: description)
    code = result[:code]
    suggested_name = result[:suggested_name]
    tool_type = result[:tool_type]

    if output_to_stdout
      puts code
    else
      # Write to file
      file_path = options[:output] || "./#{suggested_name}.rb"

      if File.exist?(file_path) && !options[:force] && !yes?("File '#{file_path}' already exists. Overwrite? [y/N]", :yellow)
        say 'Generation cancelled.', :yellow
        exit(0)
      end

      File.write(file_path, code)
      say "Tool code generated and saved to '#{file_path}'", :green
      say "  Suggested name: #{suggested_name}", :cyan
      say "  Tool type: #{tool_type}", :cyan
    end
  rescue Legate::Generators::ToolGenerator::ApiKeyMissingError => e
    say "Error: #{e.message}", :red
    exit(1)
  rescue Legate::Generators::ToolGenerator::ApiError => e
    say "Error: #{e.message}", :red
    exit(1)
  rescue Legate::Generators::ToolGenerator::GenerationError => e
    say "Error: #{e.message}", :red
    exit(1)
  rescue StandardError => e
    say "Unexpected error: #{e.class} - #{e.message}", :red
    exit(1)
  end
end

#execute(name, *args) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
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
# File 'lib/legate/cli/tool_commands.rb', line 77

def execute(name, *args)
  # Suppress all logging in JSON mode for clean output
  Legate.logger.level = Logger::FATAL if json_mode?

  tool_name_sym = name.to_sym
  tool = Legate::GlobalToolManager.create_instance(tool_name_sym)

  unless tool
    output_error("Tool '#{name}' not found in registry.", metadata: { tool: name })
    exit(1)
  end

  params_to_execute = {}
  valid_param_names = tool.parameters.keys.map(&:to_s)

  args.each do |arg|
    parts = arg.split('=', 2)
    if parts.length == 2
      key = parts[0].strip
      value = parts[1]

      unless valid_param_names.include?(key)
        status_message("Warning: Provided parameter '#{key}' is not defined for tool '#{name}'. Ignoring.", :yellow)
        next
      end

      params_to_execute[key.to_sym] = value # Store as symbol key
      status_message("  Parsed: #{key} = '#{value}'")
    elsif args.length == 1 && tool.parameters.length == 1 && tool.parameters.values.first[:required]
      # Simplified single arg handling
      single_key = tool.parameters.keys.first
      status_message("Info: Assuming single argument '#{arg}' maps to required parameter '#{single_key}'.", :cyan)
      params_to_execute[single_key] = arg
    elsif !args.empty?
      status_message("Warning: Argument '#{arg}' ignored. Please use 'key=value' format for parameters.", :yellow)
    end
  end

  begin
    status_message("Executing tool '#{name}' with parsed params: #{params_to_execute.inspect}")
    # --- Create a dummy context for direct tool execution ---
    dummy_context = Legate::ToolContext.new(session_id: "cli_direct_#{SecureRandom.hex(4)}", user_id: options[:user_id],
                                            app_name: 'cli_tool_exec')

    # --- Call execute with context ---
    result_hash = tool.execute(params_to_execute, dummy_context)

    status_message("\nResult:", :bold)
    output_result(result_hash, metadata: { tool: name }, format_method: :format_tool_result)
  rescue Legate::Error, ArgumentError => e
    output_error(e, metadata: { tool: name })
    exit(1)
  rescue StandardError => e
    output_error(e, metadata: { tool: name })
    puts e.backtrace.first(5).join("\n") unless json_mode?
    exit(1)
  end
end

#info(name) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/legate/cli/tool_commands.rb', line 35

def info(name)
  tool_name_sym = name.to_sym
  tool = Legate::GlobalToolManager.create_instance(tool_name_sym) # Create instance to get params

  if tool
    say "Tool: #{tool.name}"
    say "Description: #{tool.description}"
    if tool.parameters.empty?
      say "\nParameters: None"
    else
      say "\nParameters:"
      tool.parameters.each do |param_name, param_info|
        required = param_info[:required] ? 'required' : 'optional'
        type = param_info[:type] || 'any'
        say "  - #{param_name} (#{type}, #{required})"
        say "    #{param_info[:description]}"
      end
    end
  else
    say "Tool '#{name}' not found in registry.", :red
  end
end

#listObject



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/legate/cli/tool_commands.rb', line 20

def list
  tools = Legate::GlobalToolManager.list_all_tools
  if json_mode?
    puts JSON.generate({ tools: tools.map { |t| { name: t[:name].to_s, description: t[:description] } } })
  elsif tools.empty?
    say 'No tools registered.'
  else
    say 'Available tools:', :bold
    tools.each do |tool_info|
      say "- #{tool_info[:name]}: #{tool_info[:description]}"
    end
  end
end