82 lines
2.1 KiB
Ruby
82 lines
2.1 KiB
Ruby
# lib/tools.rb
|
|
require 'json'
|
|
require 'fileutils'
|
|
require 'open3'
|
|
|
|
class ToolRegistry
|
|
@@tools = {}
|
|
|
|
def self.register(name, &block)
|
|
@@tools[name.to_s] = block
|
|
end
|
|
|
|
def self.execute(name, arguments)
|
|
tool = @@tools[name.to_s]
|
|
raise "Ferramenta '#{name}' não encontrada no registro." unless tool
|
|
|
|
# Exige estritamente um Hash com chaves simbolizadas
|
|
normalized_args = arguments.is_a?(Hash) ? arguments.transform_keys(&:to_sym) : arguments
|
|
tool.call(normalized_args)
|
|
rescue => e
|
|
"Erro ao executar a ferramenta #{name}: #{e.message}"
|
|
end
|
|
end
|
|
|
|
# --- Ferramentas ---
|
|
|
|
ToolRegistry.register('read_file') do |args|
|
|
path = args[:path]
|
|
raise "Argumento 'path' ausente ou inválido." unless path
|
|
File.exist?(path) ? File.read(path) : "Erro: Arquivo não encontrado em '#{path}'."
|
|
end
|
|
|
|
ToolRegistry.register('write_file') 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') 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') 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') 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') 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
|