From 6509536d12a34378530dfc5dabf28cac1d4000ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Carlos=20Machado=20de=20Paiva=20Ara=C3=BAjo?= Date: Sat, 10 Oct 2026 13:59:17 -0300 Subject: [PATCH] Adicionando arquivos --- agent_rules.yml | 14 +++++++ bin/agent | 92 +++++++++++++++++++++++++++++++++++++++++++ config/agent.yml | 24 +++++++++++ lib/backends/base.rb | 18 +++++++++ lib/backends/llama.rb | 58 +++++++++++++++++++++++++++ lib/config.rb | 28 +++++++++++++ lib/orchestrator.rb | 70 ++++++++++++++++++++++++++++++++ lib/registry.rb | 23 +++++++++++ lib/tools.rb | 82 ++++++++++++++++++++++++++++++++++++++ 9 files changed, 409 insertions(+) create mode 100644 agent_rules.yml create mode 100644 bin/agent create mode 100644 config/agent.yml create mode 100644 lib/backends/base.rb create mode 100644 lib/backends/llama.rb create mode 100644 lib/config.rb create mode 100644 lib/orchestrator.rb create mode 100644 lib/registry.rb create mode 100644 lib/tools.rb diff --git a/agent_rules.yml b/agent_rules.yml new file mode 100644 index 0000000..31fc42f --- /dev/null +++ b/agent_rules.yml @@ -0,0 +1,14 @@ +rules: + - "NUNCA execute comandos contendo 'git merge' ou 'git pull' sem autorização explícita e manual." + - "Ao criar arquivos em C ou C++, utilize padrões modernos e mantenha o código limpo e documentado." + +templates: + c_header: | + /* + * ===================================================================================== + * Projeto: Sistemas Embarcados / Automação + * Arquivo: {filename} + * Autor: Agente Local Ruby (llama.cpp) + * ===================================================================================== + */ + diff --git a/bin/agent b/bin/agent new file mode 100644 index 0000000..e76b7ac --- /dev/null +++ b/bin/agent @@ -0,0 +1,92 @@ +#!/usr/bin/env ruby +require 'fileutils' +require 'json' +require_relative '../lib/config' +require_relative '../lib/registry' +require_relative '../lib/backends/llama' +require_relative '../lib/orchestrator' +require_relative '../lib/tools' + +# Carrega as configurações do projeto +config = AgentConfig.load + +# Configuração e Registro do Backend de Texto +text_section = config.dig('backends', 'text') || {} +default_provider = text_section['default']&.to_sym || :llama +providers = text_section['providers'] || {} + +BackendRegistry.register(:text, :llama, LlamaBackend) +provider_config = providers[default_provider.to_s] || {} + +begin + llm_client = BackendRegistry.create(:text, default_provider, provider_config) +rescue => e + puts "\e[31m[!] Erro ao carregar backend #{default_provider}: #{e.message}\e[0m" + exit 1 +end + +# Inicializa o Orquestrador +orchestrator = Orchestrator.new(llm_client) + +puts "\e[32m=== Ruby Local AI Code Agent (Modular & Orchestrated) ===\e[0m" +puts "\e[32m[✓] Pronto usando [text:#{default_provider}] com suporte a ferramentas e shell.\e[0m" +puts "Digite 'sair' ou 'exit' para encerrar.\n\n" + +# Loop principal do chat +loop do + print "\e[36mvocê > \e[0m" + input = $stdin.gets&.strip + break if input.nil? || %w[sair exit].include?(input.downcase) + next if input.empty? + + print "\e[33m[orquestrador] Analisando plano...\e[0m\r" + + begin + plan = orchestrator.plan(input) + tasks = plan['tasks'] || [] + + print "\e[33m[orquestrador] Plano gerado com #{tasks.size} tarefa(s). Executando...\e[0m\n" + + execution_context = [] + + # 1. Executa todas as tarefas (ferramentas ou prompts) + tasks.each_with_index do |task, index| + type = task['type'] + name = task['name'] || 'direto' + puts "\e[34m -> [Tarefa #{index + 1}] Tipo: #{type} (#{name})\e[0m" + + case type + when 'tool' + args = task['arguments'] || {} + result = ToolRegistry.execute(name, args) + execution_context << "Resultado da ferramenta #{name} com args #{args.to_json}:\n#{result}" + + # Mostra o resultado detalhado da ferramenta no terminal + puts "\e[90m Saída:\n#{result}\e[0m" + + when 'text' + prompt = task['prompt'] || input + execution_context << prompt + end + end + + # 2. SE houver contexto de ferramentas ou se o plano foi apenas de ferramentas, + # faz uma chamada final ao modelo para ele interpretar e responder ao usuário. + unless execution_context.empty? + messages = [ + { role: 'system', content: "Você é um assistente técnico em desenvolvimento de software. Resuma ou responda ao usuário com base nos resultados das ferramentas executadas no sistema." }, + { role: 'user', content: "Solicitação original: #{input}\n\nContexto e resultados obtidos:\n#{execution_context.join("\n\n")}" } + ] + + print "\e[35magente > \e[0m" + response = llm_client.process(messages: messages) + reply = response.dig('choices', 0, 'message', 'content')&.strip || "Concluído sem resposta textual." + puts reply + end + + rescue => e + puts "\e[31m[!] Erro durante o processamento do fluxo: #{e.message}\e[0m" + end + + puts "\n" +end diff --git a/config/agent.yml b/config/agent.yml new file mode 100644 index 0000000..f4e3c31 --- /dev/null +++ b/config/agent.yml @@ -0,0 +1,24 @@ +# config/agent.yml +backends: + text: + default: llama + providers: + llama: + endpoint: "http://127.0.0.1:8080/v1/chat/completions" + model: "local-model" + timeout: 120 + + # Preparado para futuras expansões + image: + default: stable_diffusion + providers: + stable_diffusion: + endpoint: "http://127.0.0.1:8081/v1/generation" + timeout: 180 + + audio: + default: local_tts + providers: + local_tts: + endpoint: "http://127.0.0.1:8082/v1/audio" + timeout: 60 diff --git a/lib/backends/base.rb b/lib/backends/base.rb new file mode 100644 index 0000000..e434a4f --- /dev/null +++ b/lib/backends/base.rb @@ -0,0 +1,18 @@ +# lib/backends/base.rb +# Classe abstrata que define o contrato padrão para todos os backends do sistema. +class BaseBackend + # Retorna o identificador simbólico curto do backend (ex: :llama) + def name + raise NotImplementedError, "#{self.class} deve implementar o método #name" + end + + # Retorna uma descrição amigável da modalidade e do provedor + def description + raise NotImplementedError, "#{self.class} deve implementar o método #description" + end + + # Processa o payload específico da modalidade (mensagens, prompts ou parâmetros) + def process(payload) + raise NotImplementedError, "#{self.class} deve implementar o método #process" + end +end diff --git a/lib/backends/llama.rb b/lib/backends/llama.rb new file mode 100644 index 0000000..d8deb68 --- /dev/null +++ b/lib/backends/llama.rb @@ -0,0 +1,58 @@ +# lib/backends/llama.rb +require_relative 'base' +require 'net/http' +require 'json' +require 'uri' + +# Backend de texto e raciocínio baseado no llama.cpp (compatível com API OpenAI) +class LlamaBackend < BaseBackend + def initialize(config = {}) + @endpoint = config['endpoint'] || 'http://127.0.0.1:8080/v1/chat/completions' + @model = config['model'] || 'local-model' + @timeout = config['timeout'] || 120 + @uri = URI(@endpoint) + end + + # Identificador curto do backend + def name + :llama + end + + # Descrição amigável para exibição no CLI + def description + 'Backend local de linguagem natural via llama.cpp (OpenAI-compatible)' + end + + # Processa mensagens de texto e ferramentas opcionais enviadas ao modelo + def process(messages:, tools: nil) + http = Net::HTTP.new(@uri.host, @uri.port) + http.use_ssl = (@uri.scheme == 'https') + http.open_timeout = 10 + http.read_timeout = @timeout + + request = Net::HTTP::Post.new(@uri, { + 'Content-Type' => 'application/json', + 'Connection' => 'keep-alive' + }) + + payload = { + model: @model, + messages: messages, + temperature: 0.2 + } + payload[:tools] = tools if tools && !tools.empty? + + request.body = payload.to_json + response = http.request(request) + + unless response.is_a?(Net::HTTPSuccess) + raise "Erro no llama.cpp: #{response.code} #{response.body}" + end + + JSON.parse(response.body) + rescue Net::OpenTimeout, Net::ReadTimeout + raise "Erro: Timeout na conexão com o llama.cpp." + rescue Errno::ECONNRESET => e + raise "Erro: Conexão resetada pelo servidor llama.cpp (ECONNRESET)." + end +end diff --git a/lib/config.rb b/lib/config.rb new file mode 100644 index 0000000..be179d7 --- /dev/null +++ b/lib/config.rb @@ -0,0 +1,28 @@ +# lib/config.rb +require 'yaml' +require 'fileutils' + +class AgentConfig + DEFAULT_PATH = 'config/agent.yml' + + # Carrega o arquivo de configuração ou usa um fallback padrão se não existir + def self.load(path = DEFAULT_PATH) + if File.exist?(path) + YAML.load_file(path) rescue {} + else + { + 'backends' => { + 'text' => { + 'default' => 'llama', + 'providers' => { + 'llama' => { + 'endpoint' => ENV.fetch('LLAMA_CPP_ENDPOINT', 'http://127.0.0.1:8080/v1/chat/completions'), + 'model' => 'local-model' + } + } + } + } + } + end + end +end diff --git a/lib/orchestrator.rb b/lib/orchestrator.rb new file mode 100644 index 0000000..dbae105 --- /dev/null +++ b/lib/orchestrator.rb @@ -0,0 +1,70 @@ +# lib/orchestrator.rb +require 'json' + +class Orchestrator + SYSTEM_PROMPT = <<~PROMPT.freeze + Você é um planejador e orquestrador estrito de tarefas. Sua ÚNICA função é analisar a mensagem do usuário e retornar um objeto JSON contendo o plano de execução. + NÃO responda à pergunta do usuário e NÃO crie textos de conversação no plano. Apenas categorize o pedido em tarefas. + + REGRA CRÍTICA PARA O CAMPO "arguments": + O campo "arguments" DEVE SER SEMPRE UM OBJETO (hash com chaves e valores). NUNCA envie uma string solta ou um array simples. + + EXEMPLOS DE PLANOS CORRETOS: + - Para saudação ou conversa geral: + {"tasks": [{"type": "text", "prompt": "bom dia"}]} <-- (Repasse exatamente o que o usuário disse) + + - Para listar diretório: + {"tasks": [{"type": "tool", "name": "list_directory", "arguments": {"path": "."}}]} + + - Para comandos bash: + {"tasks": [{"type": "tool", "name": "bash", "arguments": {"command": "git status"}}]} + + Retorne APENAS o JSON válido, sem blocos de markdown e sem texto adicional. + PROMPT + + def initialize(llm_client) + @llm_client = llm_client + end + + def plan(user_message) + messages = [ + { role: 'system', content: SYSTEM_PROMPT }, + { role: 'user', content: user_message } + ] + + # --- LOG DE ENVIO --- + puts "\n\e[33m[DEBUG] === ORCHESTRATOR REQUEST (Enviado ao LLM) ===\e[0m" + puts JSON.pretty_generate(messages) + puts "\e[33m[DEBUG] ================================================\e[0m" + + response = @llm_client.process(messages: messages) + raw_content = response.dig('choices', 0, 'message', 'content')&.strip + + # --- LOG DE RESPOSTA BRUTA --- + puts "\n\e[35m[DEBUG] === ORCHESTRATOR RAW RESPONSE (Recebido do LLM) ===\e[0m" + p raw_content + puts "\e[35m[DEBUG] ===================================================\e[0m" + + raise "Orquestrador não retornou conteúdo." unless raw_content + + cleaned_content = raw_content.gsub(/^```json\s*/, '').gsub(/^```\s*/, '').sub(/\s*```$/, '').strip + + parsed = JSON.parse(cleaned_content) + + # --- LOG DO JSON PARSEADO --- + puts "\n\e[32m[DEBUG] === ORCHESTRATOR PARSED JSON (Estrutura final) ===\e[0m" + puts JSON.pretty_generate(parsed) + puts "\e[32m[DEBUG] ===================================================\e[0m\n" + + parsed + rescue JSON::ParserError => e + puts "\e[31m[DEBUG] Erro de Parse JSON: #{e.message}\e[0m" + { + "tasks" => [ + { "type" => "text", "prompt" => user_message } + ] + } + rescue => e + raise "Erro na pré-análise do orquestrador: #{e.message}" + end +end diff --git a/lib/registry.rb b/lib/registry.rb new file mode 100644 index 0000000..4b25f90 --- /dev/null +++ b/lib/registry.rb @@ -0,0 +1,23 @@ +# lib/registry.rb +# Gerencia o registro centralizado e a instanciação de backends por modalidade (tipo). +class BackendRegistry + @@backends = {} + + # Registra um backend associado a um tipo (ex: :text => { llama: LlamaBackend }) + def self.register(type, key, klass) + @@backends[type.to_sym] ||= {} + @@backends[type.to_sym][key.to_sym] = klass + end + + # Retorna todos os backends disponíveis agrupados por tipo + def self.available + @@backends + end + + # Instancia e retorna um backend específico pelo tipo e chave com opções de configuração + def self.create(type, key, config = {}) + klass = @@backends.dig(type.to_sym, key.to_sym) + raise "Backend '#{key}' para o tipo '#{type}' não encontrado no registro." unless klass + klass.new(config) + end +end diff --git a/lib/tools.rb b/lib/tools.rb new file mode 100644 index 0000000..cf29951 --- /dev/null +++ b/lib/tools.rb @@ -0,0 +1,82 @@ +# 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