116 lines
3.9 KiB
Ruby
116 lines
3.9 KiB
Ruby
# lib/tools.rb
|
|
require 'json'
|
|
require 'fileutils'
|
|
require 'open3'
|
|
require_relative 'config'
|
|
|
|
class ToolRegistry
|
|
@@tools = {}
|
|
|
|
# Registra a ferramenta guardando o bloco e uma breve descrição/esquema
|
|
def self.register(name, description = '', &block)
|
|
debug_log("register", "Registrando ferramenta: '#{name}' (Descrição: #{description.inspect})")
|
|
@@tools[name.to_s] = {
|
|
description: description,
|
|
handler: block
|
|
}
|
|
end
|
|
|
|
def self.execute(name, arguments)
|
|
debug_log("execute", "Solicitada execução da ferramenta '#{name}' com argumentos: #{arguments.inspect}")
|
|
tool = @@tools[name.to_s]
|
|
|
|
unless tool
|
|
debug_log("execute", "FALHA: Ferramenta '#{name}' não encontrada no registro.")
|
|
raise "Ferramenta '#{name}' não encontrada no registro."
|
|
end
|
|
|
|
normalized_args = arguments.is_a?(Hash) ? arguments.transform_keys(&:to_sym) : arguments
|
|
debug_log("execute", "Argumentos normalizados para a ferramenta '#{name}': #{normalized_args.inspect}")
|
|
|
|
result = tool[:handler].call(normalized_args)
|
|
debug_log("execute", "Ferramenta '#{name}' executada com sucesso.")
|
|
result
|
|
rescue => e
|
|
error_msg = "Erro ao executar a ferramenta #{name}: #{e.message}"
|
|
debug_log("execute", "FALHA na execução da ferramenta '#{name}': #{e.message}")
|
|
error_msg
|
|
end
|
|
|
|
# Retorna uma lista formatada de todas as ferramentas disponíveis para injetar no prompt
|
|
def self.definitions_summary
|
|
debug_log("definitions_summary", "Gerando sumário de definições para #{@@tools.size} ferramenta(s) registrada(s).")
|
|
@@tools.map { |name, data| "- #{name}: #{data[:description]}" }.join("\n")
|
|
end
|
|
|
|
private
|
|
|
|
def self.debug_enabled?
|
|
defined?(AgentConfig) && AgentConfig.respond_to?(:debug?) ? AgentConfig.debug? : true
|
|
end
|
|
|
|
def self.debug_log(function_name, message)
|
|
if debug_enabled?
|
|
STDERR.puts "\e[36m[DEBUG][lib/tools.rb][ToolRegistry##{function_name}] #{message}\e[0m"
|
|
end
|
|
end
|
|
end
|
|
|
|
# --- Registro das Ferramentas Nativas com Descrições Claras ---
|
|
|
|
ToolRegistry.register('read_file', 'Lê o conteúdo de um arquivo. Argumento: {"path": "caminho/arquivo"}') do |args|
|
|
path = args[:path]
|
|
raise "Argumento 'path' ausente." unless path
|
|
File.exist?(path) ? File.read(path) : "Erro: Arquivo não encontrado em '#{path}'."
|
|
end
|
|
|
|
ToolRegistry.register('write_file', 'Grava conteúdo em um arquivo. Argumento: {"path": "caminho/arquivo", "content": "conteúdo"}') do |args|
|
|
path = args[:path]
|
|
content = args[:content] || ''
|
|
raise "Argumento 'path' ausente." unless path
|
|
|
|
FileUtils.mkdir_p(File.dirname(path)) unless File.dirname(path) == '.'
|
|
File.write(path, content)
|
|
"Sucesso: Arquivo gravado em '#{path}' (#{content.bytesize} bytes)."
|
|
end
|
|
|
|
ToolRegistry.register('delete_file', 'Remove um arquivo. Argumento: {"path": "caminho/arquivo"}') do |args|
|
|
path = args[:path]
|
|
raise "Argumento 'path' ausente." unless path
|
|
|
|
if File.exist?(path)
|
|
File.delete(path)
|
|
"Sucesso: Arquivo '#{path}' removido."
|
|
else
|
|
"Erro: Arquivo não encontrado em '#{path}'."
|
|
end
|
|
end
|
|
|
|
ToolRegistry.register('create_directory', 'Cria um diretório. Argumento: {"path": "caminho/diretorio"}') do |args|
|
|
path = args[:path]
|
|
raise "Argumento 'path' ausente." unless path
|
|
|
|
FileUtils.mkdir_p(path)
|
|
"Sucesso: Diretório criado em '#{path}'."
|
|
end
|
|
|
|
ToolRegistry.register('list_directory', 'Lista arquivos de um diretório. Argumento: {"path": "caminho/diretorio"}') do |args|
|
|
dir = args[:path] || '.'
|
|
if Dir.exist?(dir)
|
|
Dir.entries(dir).reject { |f| f == '.' || f == '..' }.to_json
|
|
else
|
|
"Erro: Diretório não encontrado em '#{dir}'."
|
|
end
|
|
end
|
|
|
|
ToolRegistry.register('bash', 'Executa um comando shell no sistema operacional. Argumento: {"command": "comando"}') do |args|
|
|
command = args[:command]
|
|
raise "Argumento 'command' ausente." unless command
|
|
|
|
stdout, stderr, status = Open3.capture3(command)
|
|
{
|
|
exit_status: status.exitstatus,
|
|
stdout: stdout.strip,
|
|
stderr: stderr.strip
|
|
}.to_json
|
|
end
|