97 lines
3.4 KiB
Python
97 lines
3.4 KiB
Python
import os
|
|
import json
|
|
import redis
|
|
import argparse
|
|
import subprocess
|
|
from anthropic import Anthropic
|
|
from key_manager import KeyManager
|
|
|
|
# Configurações de Caminho
|
|
BASE_DIR = "/home/deploy/projetos"
|
|
INSTRUCOES_DIR = "/home/deploy/instrucoes"
|
|
|
|
class SwarmAgent:
|
|
def __init__(self, task_data):
|
|
self.data = task_data
|
|
self.repo_name = task_data.get('repository')
|
|
self.repo_url = f"http://10.99.0.3:3000/{self.repo_name}.git"
|
|
self.local_path = os.path.join(BASE_DIR, self.repo_name.split('/')[-1])
|
|
self.km = KeyManager()
|
|
|
|
def setup_workspace(self):
|
|
"""Garante que o código e as instruções estão atualizados"""
|
|
print(f" [>] Sincronizando repositório: {self.repo_name}")
|
|
os.makedirs(BASE_DIR, exist_ok=True)
|
|
|
|
if not os.path.exists(self.local_path):
|
|
subprocess.run(["git", "clone", self.repo_url, self.local_path])
|
|
else:
|
|
subprocess.run(["git", "-C", self.local_path, "pull"])
|
|
|
|
# Sincroniza instruções globais
|
|
subprocess.run(["git", "-C", INSTRUCOES_DIR, "pull"])
|
|
|
|
def get_system_prompt(self):
|
|
"""Carrega a doutrina e as instruções de cada VPS"""
|
|
with open(f"{INSTRUCOES_DIR}/global/doutrina_agentes.md", "r") as f:
|
|
doutrina = f.read()
|
|
with open(f"{INSTRUCOES_DIR}/global/claude.md", "r") as f:
|
|
especifico = f.read()
|
|
|
|
ip_vps = subprocess.getoutput("hostname -I").split()[0]
|
|
|
|
return f"""
|
|
{doutrina}
|
|
{especifico}
|
|
|
|
CONTEXTO ATUAL:
|
|
- Você está na VPS com IP: {ip_vps}
|
|
- Projeto: {self.repo_name}
|
|
- Tarefa (Issue): {json.dumps(self.data.get('data', {}).get('issue', {}))}
|
|
"""
|
|
|
|
def post_comment(self, message):
|
|
"""Posta um comentário de feedback na Issue do Gitea"""
|
|
issue_id = self.data.get('data', {}).get('issue', {}).get('number')
|
|
if not issue_id:
|
|
return
|
|
|
|
url = f"http://10.99.0.3:3000/api/v1/repos/{self.repo_name}/issues/{issue_id}/comments"
|
|
auth = ('ruicesar', 'h$tg@g5aga$ra1E3$C-yHW$-BA@DF2@Grfa!3#')
|
|
|
|
try:
|
|
import requests
|
|
response = requests.post(url, auth=auth, json={"body": message})
|
|
if response.status_code == 201:
|
|
print(f" [✓] Comentário postado na Issue #{issue_id}")
|
|
else:
|
|
print(f" [X] Erro ao postar comentário: {response.status_code}")
|
|
except Exception as e:
|
|
print(f" [E] Falha na comunicação com Gitea: {e}")
|
|
|
|
def execute(self):
|
|
self.setup_workspace()
|
|
|
|
api_key = self.km.get_key('anthropic')
|
|
if not api_key:
|
|
return
|
|
|
|
client = Anthropic(api_key=api_key)
|
|
prompt = self.get_system_prompt()
|
|
|
|
print(" [!] IA Pensando na solução...")
|
|
|
|
# Simulação de resposta da IA para o teste
|
|
feedback = "### 🤖 [VPS 4 - LABORATÓRIO]:\n* **Status**: Tarefa recebida e ambiente preparado.\n* **Ação**: Sincronização de arquivos concluída.\n* **Próximo**: Iniciando correção do erro de regressão de versão."
|
|
|
|
self.post_comment(feedback)
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--data", help="Dados do Webhook JSON")
|
|
args = parser.parse_args()
|
|
|
|
if args.data:
|
|
agent = SwarmAgent(json.loads(args.data))
|
|
agent.execute()
|