Compare commits

...

33 Commits

Author SHA1 Message Date
Frederico Castro
1606efa09f Reescrever README com layout profissional e documentação completa 2026-02-28 04:42:00 -03:00
Frederico Castro
633b19f80d Integrar repositórios Git na execução de agentes e pipelines
- Módulo git-integration: clone/pull, commit/push automático, listagem de repos
- Seletor de repositório nos modais de execução (agente e pipeline)
- Seletor de branch carregado dinamicamente ao escolher repo
- Campo de diretório escondido quando repositório selecionado
- Auto-commit e push ao final da execução com mensagem descritiva
- Instrução injetada para agentes não fazerem operações git
- Rotas API: GET /repos, GET /repos/:name/branches
- Pipeline: commit automático ao final de todos os steps
2026-02-28 04:24:47 -03:00
Frederico Castro
2fae816162 Corrigir truncamento no terminal usando CSS grid 2026-02-28 04:05:07 -03:00
Frederico Castro
2201ac8699 Usar force-recreate ao reiniciar Caddy na publicação 2026-02-28 03:30:21 -03:00
Frederico Castro
a6bbe33e4b Adicionar grupo docker ao user node no Dockerfile 2026-02-28 03:18:52 -03:00
Frederico Castro
4c197eef91 Adicionar publicação automática de projetos
- Botão publicar (rocket) nas pastas raiz do explorador
- Cria repositório no Gitea, faz git init + push
- Atualiza Caddyfile com subdomínio e file_server
- Adiciona volume ao docker-compose e reinicia Caddy
- Botões lado a lado (download, publicar, excluir) no file explorer
- Dockerfile: adiciona git e docker-cli
2026-02-28 03:17:56 -03:00
Frederico Castro
e9f65c2845 Corrigir ícones e adicionar exclusão no explorador de arquivos
- Trocar ícone archive (lixeira) por download em todos os botões
- Adicionar botão de excluir com ícone trash-2 em cada entrada
- Rota DELETE /api/files com proteção contra exclusão da raiz
- Confirmação via modal antes de excluir
2026-02-28 03:00:45 -03:00
Frederico Castro
2fccaaac40 Adicionar botão de download da pasta raiz no explorador de arquivos 2026-02-28 02:42:57 -03:00
Frederico Castro
3178366e0e Corrigir truncamento de linhas longas no terminal
- Adicionar overflow-wrap: anywhere e min-width: 0 no .content
- Adicionar min-width: 0 no .terminal-line para flex shrink correto
- Definir overflow-x: hidden no .terminal-body
2026-02-28 02:27:27 -03:00
Frederico Castro
fa47538a8f Adicionar campo diretório de trabalho no modal de execução
- Campo execute-workdir no modal com valor pré-preenchido do agente
- Frontend envia workingDirectory na API de execução
- Backend aceita e aplica override de workingDirectory via metadata
- Pré-preenche com config do agente selecionado ao abrir modal
- Adiciona stopAll ao scheduler e limpa README
2026-02-28 02:20:09 -03:00
Frederico Castro
7a4ab2279d Corrigir classes CSS dos modais para convenção BEM (modal--lg) 2026-02-28 02:13:27 -03:00
Frederico Castro
7cbfcb2d0d Desabilitar cache de arquivos estáticos para evitar JS desatualizado 2026-02-28 02:10:41 -03:00
Frederico Castro
46a6ebc9dd Pré-preencher diretório de trabalho dos agentes com /home/projetos/ 2026-02-28 02:06:40 -03:00
Frederico Castro
f6bf7ce0ed Adicionar delegação automática entre agentes coordenadores 2026-02-28 01:59:38 -03:00
Frederico Castro
96733b55cd Adicionar file explorer para projetos criados pelos agentes 2026-02-28 01:38:26 -03:00
Frederico Castro
3ed285c9d1 Atualizar README com deploy automático, catálogo de tarefas e novos endpoints 2026-02-28 01:27:33 -03:00
Frederico Castro
6a21a4d711 Aumentar truncate dos cards de tarefas e adicionar margem no footer 2026-02-28 01:22:45 -03:00
Frederico Castro
bbfb9864bd Truncar textos dos cards de tarefas para layout padronizado
- Truncar descrição em 120 caracteres no JS com tooltip do texto completo
- Truncar nome com ellipsis via CSS
- Limitar descrição a 2 linhas com max-height
2026-02-28 00:59:25 -03:00
Frederico Castro
c29aa695d4 Merge branch 'main' of https://git.nitro-cloud.duckdns.org/fred/agents-orchestrator 2026-02-28 00:51:18 -03:00
Frederico Castro
4db351cb45 Truncar descrição dos cards de tarefas em 2 linhas 2026-02-28 00:47:22 -03:00
Frederico Castro
af1c59b75c Desabilitar cache HTTP para arquivos HTML 2026-02-28 00:40:48 -03:00
Frederico Castro
738ab12631 Desabilitar cache HTTP para arquivos HTML 2026-02-28 00:40:39 -03:00
Frederico Castro
46f999c676 Adicionar landing page e redirecionar rota raiz
- Landing page profissional com hero, features, pricing (Starter/Pro/Enterprise), FAQ
- Animações no scroll, parallax, contadores animados, glassmorphism
- Dashboard movido para /app.html, landing page agora é a página inicial
- CTAs direcionam para /app.html
2026-02-28 00:32:14 -03:00
Frederico Castro
39f0902a0f Rodar container como usuário node e corrigir resume do executor
- Dockerfile: usar USER node (UID 1000) para bypassPermissions funcionar
- Volumes mapeados para /home/node/ em vez de /root/
- Corrigir resume: voltar a usar -p para mensagens curtas de chat
- Manter stdin piping apenas em execute e summarize (prompts grandes)
2026-02-28 00:32:14 -03:00
Frederico Castro
fd3c2dc69a Adicionar botão Interromper no terminal e corrigir botão Retomar
- Botão Interromper na toolbar do terminal para matar execuções ativas
- Endpoint POST /executions/cancel-all para cancelar agentes e pipelines
- Botão aparece/esconde automaticamente conforme execuções ativas
- Corrigir condição do botão Retomar para pipelines antigas sem failedAtStep
2026-02-28 00:32:14 -03:00
Frederico Castro
1411c750e4 Adicionar landing page e redirecionar rota raiz
- Landing page profissional com hero, features, pricing (Starter/Pro/Enterprise), FAQ
- Animações no scroll, parallax, contadores animados, glassmorphism
- Dashboard movido para /app.html, landing page agora é a página inicial
- CTAs direcionam para /app.html
2026-02-28 00:32:05 -03:00
Frederico Castro
1ef5903da1 Rodar container como usuário node e corrigir resume do executor
- Dockerfile: usar USER node (UID 1000) para bypassPermissions funcionar
- Volumes mapeados para /home/node/ em vez de /root/
- Corrigir resume: voltar a usar -p para mensagens curtas de chat
- Manter stdin piping apenas em execute e summarize (prompts grandes)
2026-02-28 00:19:08 -03:00
Frederico Castro
d662860c61 Adicionar botão Interromper no terminal e corrigir botão Retomar
- Botão Interromper na toolbar do terminal para matar execuções ativas
- Endpoint POST /executions/cancel-all para cancelar agentes e pipelines
- Botão aparece/esconde automaticamente conforme execuções ativas
- Corrigir condição do botão Retomar para pipelines antigas sem failedAtStep
2026-02-28 00:03:44 -03:00
Fred
a1d3ce707c Corrigir E2BIG em pipelines, adicionar diretório de projeto e retomada 2026-02-27 23:46:05 -03:00
Frederico Castro
275d74b18c Corrigir E2BIG em pipelines, adicionar diretório de projeto e retomada
- Instalar Claude CLI no container Docker (npm install -g)
- Pipar prompt via stdin ao invés de argumento -p (resolve E2BIG)
- Adicionar campo workingDirectory na criação/edição de pipeline
- Pre-preencher com /home/projetos/ como base path
- Auto-criar diretório se não existir ao executar agente
- Salvar failedAtStep e lastStepInput quando pipeline falha
- Implementar retomada de pipeline a partir do passo que falhou
- Adicionar botão Retomar no histórico para pipelines com erro
- Configurar trust proxy para Express atrás de reverse proxy
2026-02-27 23:45:36 -03:00
Frederico Castro
38556f9bf5 Corrigir detecção de Tech Lead e PO nos cards de agentes
Detecção por nome do agente além das tags para garantir
destaque e ordenação corretos independente das tags usadas.
2026-02-27 22:44:36 -03:00
Frederico Castro
972ae92291 Melhorias no frontend, pipeline e executor
- Estilos CSS expandidos com novos componentes visuais
- Editor de fluxo visual para pipelines (flow-editor.js)
- Melhorias na UI de agentes e pipelines
- Sumarização automática entre steps de pipeline
- Retry com backoff no executor
- Utilitários adicionais no frontend
2026-02-27 22:39:23 -03:00
Frederico Castro
0b5a81c3e6 Atualizar README com informações de deploy e acesso remoto
- URLs de acesso público via Nitro Cloud
- Instruções de deploy, atualização e restart
- Diagrama de infraestrutura (Caddy + Docker)
- Variáveis de ambiente atualizadas para produção
2026-02-27 22:03:01 -03:00
22 changed files with 5255 additions and 1642 deletions

View File

@@ -1,9 +1,13 @@
FROM node:22-alpine FROM node:22-alpine
RUN apk add --no-cache git docker-cli
WORKDIR /app WORKDIR /app
COPY package*.json ./ COPY package*.json ./
RUN npm ci --omit=dev RUN npm ci --omit=dev
RUN npm install -g @anthropic-ai/claude-code
COPY . . COPY . .
RUN mkdir -p data RUN mkdir -p data && chown -R node:node /app
RUN addgroup -g 984 docker 2>/dev/null; addgroup node docker 2>/dev/null || true
USER node
ENV HOST=0.0.0.0 ENV HOST=0.0.0.0
ENV PORT=3000 ENV PORT=3000
EXPOSE 3000 EXPOSE 3000

530
README.md
View File

@@ -1,307 +1,373 @@
# Agents Orchestrator <p align="center">
<img src="docs/logo.svg" alt="Agents Orchestrator" width="80" />
</p>
Painel administrativo web para orquestração de agentes [Claude Code](https://docs.anthropic.com/en/docs/claude-code). Crie, configure e execute múltiplos agentes com diferentes personalidades, modelos e diretórios de trabalho — tudo a partir de uma interface visual profissional. <h1 align="center">Agents Orchestrator</h1>
![Dashboard do Agents Orchestrator — visão geral com métricas, gráficos de execuções e custos, distribuição de status, ranking de agentes e taxa de sucesso](docs/dashboard.png) <p align="center">
<strong>Plataforma de orquestração de agentes IA com interface visual, pipelines automatizados e integração Git nativa.</strong>
</p>
<p align="center">
<a href="https://agents.nitro-cloud.duckdns.org"><img src="https://img.shields.io/badge/demo-live-00d4aa?style=flat-square" alt="Live Demo" /></a>
<a href="https://git.nitro-cloud.duckdns.org/fred/agents-orchestrator"><img src="https://img.shields.io/badge/gitea-repo-6c40cc?style=flat-square" alt="Gitea" /></a>
<img src="https://img.shields.io/badge/node-%3E%3D22-339933?style=flat-square&logo=node.js&logoColor=white" alt="Node.js" />
<img src="https://img.shields.io/badge/license-MIT-blue?style=flat-square" alt="License" />
</p>
<p align="center">
<a href="#visao-geral">Visao Geral</a> &bull;
<a href="#funcionalidades">Funcionalidades</a> &bull;
<a href="#quick-start">Quick Start</a> &bull;
<a href="#arquitetura">Arquitetura</a> &bull;
<a href="#api">API</a> &bull;
<a href="#deploy">Deploy</a>
</p>
---
## Visao Geral
Agents Orchestrator e uma plataforma web para criar, configurar e executar agentes [Claude Code](https://docs.anthropic.com/en/docs/claude-code) de forma visual. Projetada para equipes de desenvolvimento e profissionais que precisam orquestrar multiplos agentes IA com diferentes especialidades, executar pipelines de trabalho automatizados e integrar com repositorios Git — tudo a partir de um painel administrativo elegante.
### Por que usar?
| Problema | Solucao |
|----------|---------|
| Gerenciar multiplos agentes via CLI e tedioso | Interface visual com cards, filtros e execucao com 1 clique |
| Saida do agente nao e visivel em tempo real | Terminal com streaming WebSocket chunk-a-chunk |
| Automatizar fluxos sequenciais e complexo | Pipelines visuais com aprovacao humana entre passos |
| Agentes nao tem acesso a repositorios remotos | Integracao Git nativa com clone, commit e push automatico |
| Deploy manual e propenso a erros | `git deploy` — um comando faz tudo |
---
## Funcionalidades ## Funcionalidades
### Gerenciamento de Agentes ### Agentes
- Crie agentes com nome, system prompt, modelo (Sonnet/Opus/Haiku), diretório de trabalho, ferramentas permitidas, modo de permissão e tags
- Ative, desative, edite, **duplique** ou exclua a qualquer momento
- Exporte/importe configurações completas em JSON
### Execução de Tarefas - Criacao com system prompt, modelo (Sonnet/Opus/Haiku), diretorio de trabalho, ferramentas permitidas e modo de permissao
- Execute tarefas sob demanda em qualquer agente ativo - Tags para organizacao e filtragem
- Templates rápidos incluídos (detecção de bugs, revisão OWASP, refatoração, testes, documentação, performance) - Duplicacao, importacao/exportacao JSON
- **Reexecute** tarefas que falharam ou foram canceladas com um clique - Delegacao automatica entre agentes (Tech Lead → PO)
- Continuação de conversa (resume session) no terminal - Agentes coordenadores recebem lista de agentes disponiveis injetada no prompt
### Terminal em Tempo Real ### Execucao
- Streaming chunk-a-chunk via WebSocket com indicador de conexão
- **Busca** no output do terminal com navegação entre ocorrências
- **Download** da saída completa como `.txt`
- **Copiar** saída para a área de transferência
- **Toggle de auto-scroll** para controle manual da rolagem
- Filtro por execução
### Dashboard com Gráficos - Modal de execucao com seletor de agente, tarefa, instrucoes adicionais e arquivos de contexto
- Métricas em tempo real (agentes, execuções, agendamentos, custo, webhooks) - **Seletor de repositorio Git** — escolha um repo do Gitea e o branch; o sistema clona/atualiza, executa e faz commit/push automatico
- **Gráfico de execuções** por dia (barras empilhadas sucesso/erro) - Templates rapidos: deteccao de bugs, revisao OWASP, refatoracao, testes, documentacao, performance
- **Gráfico de custo** por dia (linha com área preenchida) - Retry automatico configuravel por agente
- **Distribuição de status** (doughnut chart) - Continuacao de conversa (resume session)
- **Top 5 agentes** mais executados (barras horizontais) - Cancelamento individual ou em massa
- **Taxa de sucesso** geral (gauge com percentual)
- Seletor de período: 7, 14 ou 30 dias
### Agendamento Cron
- Agende tarefas recorrentes com expressões cron
- Presets incluídos (horário, diário, semanal, mensal)
- Histórico de execuções por agendamento com duração e custo
### Pipelines ### Pipelines
- Encadeie múltiplos agentes em fluxos sequenciais
- Saída de cada passo alimenta o próximo via template `{{input}}` - Encadeamento de multiplos agentes em fluxos sequenciais
- Portões de aprovação humana entre passos (human-in-the-loop) - Saida de cada passo alimenta o proximo via `{{input}}`
- Ideal para fluxos como "analisar → corrigir → testar" - **Seletor de repositorio** — todos os passos trabalham no mesmo repo com commit automatico ao final
- Portoes de aprovacao humana (human-in-the-loop)
- Retomada de pipelines falhos a partir do passo onde pararam
- Editor de fluxo visual com drag para reordenar passos
### Terminal
- Streaming em tempo real via WebSocket
- Botao Interromper para cancelar execucoes ativas
- Busca no output com navegacao entre ocorrencias
- Download como `.txt` e copia para clipboard
- Auto-scroll toggleavel
### Integração Git
- Listagem automatica de repositorios do Gitea
- Seletor de branch dinamico
- Clone/pull automatico antes da execucao
- **Commit e push automatico** ao final com mensagem descritiva
- Instrucao injetada para agentes nao fazerem operacoes git
- Publicacao de projetos: cria repo, configura subdominio, deploy com 1 clique
### Explorador de Arquivos
- Navegacao em `/home/projetos/` com breadcrumb
- Download de arquivos individuais ou pastas completas (.tar.gz)
- Exclusao com confirmacao
- Botao publicar em projetos — cria repo no Gitea, configura Caddy e faz deploy automatico em `projeto.nitro-cloud.duckdns.org`
### Dashboard
- Metricas em tempo real: agentes, execucoes, agendamentos, custo, webhooks
- Graficos: execucoes por dia, custo diario, distribuicao de status, top 5 agentes, taxa de sucesso
- Seletor de periodo: 7, 14 ou 30 dias
### Catalogo de Tarefas
- Tarefas reutilizaveis com nome, categoria e descricao
- Categorias: Code Review, Seguranca, Refatoracao, Testes, Documentacao, Performance
- Filtro por texto e categoria
- Execucao direta a partir do catalogo
### Agendamento Cron
- Expressoes cron com presets (horario, diario, semanal, mensal)
- Historico de execucoes por agendamento
- Retry automatico em caso de limite de slots
### Webhooks ### Webhooks
- Dispare execuções de agentes ou pipelines via HTTP externo
- **Edite** webhooks existentes (nome, alvo, status)
- **Teste** webhooks com um clique para verificar configuração
- Snippet cURL pronto para copiar
- Assinatura HMAC-SHA256 para validação de origem
### Notificações - Disparo de execucoes via HTTP externo
- **Centro de notificações** no header com badge de contagem - Edicao, teste com 1 clique e snippet cURL
- Notificações automáticas para execuções concluídas e com erro - Assinatura HMAC-SHA256
- **Notificações nativas do navegador** (Browser Notification API)
- Marcar como lidas / limpar todas
- Polling automático a cada 15 segundos
### Tema Claro/Escuro ### Notificacoes
- Toggle de tema no header com transições suaves
- Persistência da preferência em localStorage
- Terminal mantém fundo escuro em ambos os temas
### Exportação de Dados - Centro de notificacoes com badge de contagem
- **Exportar histórico** de execuções como CSV (UTF-8 com BOM) - Notificacoes nativas do navegador
- Exportar configuração de agentes em JSON - Polling automatico a cada 15 segundos
### Atalhos de Teclado ### Tema e UX
| Tecla | Ação |
|-------|------|
| `1``9` | Navegar entre seções |
| `N` | Novo agente |
| `Esc` | Fechar modal |
## Pré-requisitos - Tema claro/escuro com transicao suave
- Atalhos de teclado (`1`-`9` navegacao, `N` novo agente, `Esc` fechar modal)
- Exportacao de historico como CSV
- **Node.js** 18+ ---
- **Claude Code CLI** instalado e autenticado (`claude` disponível no PATH)
## Instalação ## Quick Start
### Requisitos
- Node.js >= 22
- [Claude CLI](https://docs.anthropic.com/en/docs/claude-code) instalado e autenticado
### Execucao local
```bash ```bash
git clone <repo-url> git clone https://github.com/fredac100/agents-orchestrator.git
cd agents-orchestrator cd agents-orchestrator
npm install npm install
npm start
``` ```
## Uso Acesse `http://localhost:3000`.
### Com Docker
```bash ```bash
# Produção docker build -t agents-orchestrator .
npm start docker run -p 3000:3000 \
-v $(pwd)/data:/app/data \
# Desenvolvimento (hot reload) -v ~/.claude:/home/node/.claude \
npm run dev agents-orchestrator
``` ```
Acesse **http://localhost:3000** no navegador. A porta pode ser alterada via variável de ambiente `PORT`. ---
## Variáveis de Ambiente
| Variável | Descrição | Padrão |
|----------|-----------|--------|
| `PORT` | Porta do servidor | `3000` |
| `AUTH_TOKEN` | Token Bearer para autenticação da API | _(desabilitado)_ |
| `ALLOWED_ORIGIN` | Origin permitida para CORS | `http://localhost:3000` |
| `WEBHOOK_SECRET` | Segredo HMAC para assinatura de webhooks | _(desabilitado)_ |
| `CLAUDE_BIN` | Caminho para o binário do Claude CLI | _(auto-detectado)_ |
| `REDIS_URL` | URL do Redis para cache L2 (opcional) | _(somente memória)_ |
## Como Funciona
### Criando um agente
1. Clique em **Novo Agente** no header ou na seção Agentes
2. Configure nome, system prompt, modelo e diretório de trabalho
3. Salve — o agente aparecerá como card na listagem
### Executando uma tarefa
1. No card do agente, clique em **Executar**
2. Descreva a tarefa ou use um template rápido
3. Opcionalmente adicione instruções extras
4. A execução inicia e o terminal abre automaticamente com streaming da saída
### Criando um pipeline
1. Vá em **Pipelines****Novo Pipeline**
2. Adicione pelo menos 2 passos, selecionando um agente para cada
3. Opcionalmente defina um template de input usando `{{input}}` para referenciar a saída do passo anterior
4. Marque passos que requerem aprovação humana antes de prosseguir
5. Execute o pipeline fornecendo o input inicial
### Agendando uma tarefa
1. Vá em **Agendamentos****Novo Agendamento**
2. Selecione o agente, descreva a tarefa e defina a expressão cron
3. A tarefa será executada automaticamente nos horários configurados
## Arquitetura ## Arquitetura
``` ```
server.js Express + WebSocket + rate limiting + auth HTTPS (443)
src/ |
routes/api.js API REST (/api/*) — 30+ endpoints [Caddy] ─── SSL automatico via DuckDNS
agents/ |
manager.js CRUD + orquestração + notificações *.nitro-cloud.duckdns.org
executor.js Spawna o CLI claude como child_process |
scheduler.js Agendamento cron (in-memory + persistido) ┌──────────────┼──────────────┐
pipeline.js Execução sequencial com aprovação humana | | |
store/db.js Persistência em JSON com escrita atômica [agents.*] [git.*] [projeto.*]
cache/index.js Cache em 2 níveis (memória + Redis opcional) | | |
public/ ┌──────┴──────┐ [Gitea] [Caddy file_server]
index.html SPA single-page com hash routing | |
css/styles.css Design system (dark/light themes) [Express] [WebSocket]
js/ | |
app.js Controlador principal + WebSocket + tema + routing ├── API REST (40+ endpoints)
api.js Client HTTP para a API ├── Manager (CRUD + orquestracao)
components/ UI por seção (15 módulos) ├── Executor (spawn claude CLI)
data/ ├── Pipeline (sequencial + aprovacao)
agents.json Agentes cadastrados ├── Scheduler (cron jobs)
tasks.json Templates de tarefas ├── Git Integration (clone/pull/commit/push)
pipelines.json Pipelines configurados └── Store (JSON com escrita atomica)
schedules.json Agendamentos persistidos
executions.json Histórico de execuções (max 5000)
webhooks.json Configuração de webhooks
notifications.json Notificações do sistema
settings.json Configurações globais
``` ```
O executor invoca o binário `claude` com `--output-format stream-json`, parseia o stdout linha a linha e transmite os chunks via WebSocket para o frontend em tempo real. ### Estrutura do Projeto
## API REST ```
server.js HTTP + WebSocket + rate limiting + auth
src/
routes/api.js API REST — 40+ endpoints
agents/
manager.js CRUD + orquestracao + delegacao
executor.js Spawna o CLI claude como child_process
scheduler.js Agendamento cron
pipeline.js Execucao sequencial + aprovacao humana
git-integration.js Clone, pull, commit, push automatico
store/db.js Persistencia JSON com escrita atomica
cache/index.js Cache L1 (memoria) + L2 (Redis opcional)
reports/generator.js Geracao de relatorios de execucao
public/
app.html SPA com hash routing
css/styles.css Design system (dark/light)
js/
app.js Controlador principal + WebSocket
api.js Client HTTP para a API
components/ 16 modulos UI independentes
scripts/
deploy.sh Deploy automatizado via rsync + Docker
data/ Persistencia em JSON (8 stores)
```
---
## API
### Agentes ### Agentes
| Método | Endpoint | Descrição | | Metodo | Endpoint | Descricao |
|--------|----------|-----------| |--------|----------|-----------|
| `GET` | `/api/agents` | Listar agentes | | `GET` | `/api/agents` | Listar agentes |
| `POST` | `/api/agents` | Criar agente | | `POST` | `/api/agents` | Criar agente |
| `GET` | `/api/agents/:id` | Obter agente | | `GET` | `/api/agents/:id` | Obter agente |
| `PUT` | `/api/agents/:id` | Atualizar agente | | `PUT` | `/api/agents/:id` | Atualizar agente |
| `DELETE` | `/api/agents/:id` | Excluir agente | | `DELETE` | `/api/agents/:id` | Excluir agente |
| `POST` | `/api/agents/:id/execute` | Executar tarefa no agente | | `POST` | `/api/agents/:id/execute` | Executar tarefa (aceita `repoName` e `repoBranch`) |
| `POST` | `/api/agents/:id/continue` | Continuar conversa (resume) | | `POST` | `/api/agents/:id/continue` | Continuar conversa |
| `POST` | `/api/agents/:id/cancel/:execId` | Cancelar execução | | `POST` | `/api/agents/:id/cancel/:execId` | Cancelar execucao |
| `GET` | `/api/agents/:id/export` | Exportar agente (JSON) | | `GET` | `/api/agents/:id/export` | Exportar agente |
| `POST` | `/api/agents/:id/duplicate` | Duplicar agente | | `POST` | `/api/agents/:id/duplicate` | Duplicar agente |
### Tarefas
| Método | Endpoint | Descrição |
|--------|----------|-----------|
| `GET` | `/api/tasks` | Listar tarefas |
| `POST` | `/api/tasks` | Criar tarefa |
| `PUT` | `/api/tasks/:id` | Atualizar tarefa |
| `DELETE` | `/api/tasks/:id` | Excluir tarefa |
### Agendamentos
| Método | Endpoint | Descrição |
|--------|----------|-----------|
| `GET` | `/api/schedules` | Listar agendamentos |
| `POST` | `/api/schedules` | Criar agendamento |
| `PUT` | `/api/schedules/:taskId` | Atualizar agendamento |
| `DELETE` | `/api/schedules/:taskId` | Remover agendamento |
| `GET` | `/api/schedules/history` | Histórico de execuções agendadas |
### Pipelines ### Pipelines
| Método | Endpoint | Descrição | | Metodo | Endpoint | Descricao |
|--------|----------|-----------| |--------|----------|-----------|
| `GET` | `/api/pipelines` | Listar pipelines | | `GET` | `/api/pipelines` | Listar pipelines |
| `POST` | `/api/pipelines` | Criar pipeline | | `POST` | `/api/pipelines` | Criar pipeline |
| `GET` | `/api/pipelines/:id` | Obter pipeline | | `POST` | `/api/pipelines/:id/execute` | Executar (aceita `repoName` e `repoBranch`) |
| `PUT` | `/api/pipelines/:id` | Atualizar pipeline |
| `DELETE` | `/api/pipelines/:id` | Excluir pipeline |
| `POST` | `/api/pipelines/:id/execute` | Executar pipeline |
| `POST` | `/api/pipelines/:id/cancel` | Cancelar pipeline |
| `POST` | `/api/pipelines/:id/approve` | Aprovar passo pendente | | `POST` | `/api/pipelines/:id/approve` | Aprovar passo pendente |
| `POST` | `/api/pipelines/:id/reject` | Rejeitar passo pendente | | `POST` | `/api/pipelines/:id/reject` | Rejeitar passo |
| `POST` | `/api/pipelines/resume/:execId` | Retomar pipeline falho |
### Webhooks ### Repositorios
| Método | Endpoint | Descrição | | Metodo | Endpoint | Descricao |
|--------|----------|-----------| |--------|----------|-----------|
| `GET` | `/api/webhooks` | Listar webhooks | | `GET` | `/api/repos` | Listar repositorios do Gitea |
| `POST` | `/api/webhooks` | Criar webhook | | `GET` | `/api/repos/:name/branches` | Listar branches de um repo |
| `PUT` | `/api/webhooks/:id` | Atualizar webhook |
| `DELETE` | `/api/webhooks/:id` | Excluir webhook |
| `POST` | `/api/webhooks/:id/test` | Testar webhook |
### Execuções e Histórico ### Arquivos e Publicacao
| Método | Endpoint | Descrição | | Metodo | Endpoint | Descricao |
|--------|----------|-----------| |--------|----------|-----------|
| `GET` | `/api/executions/active` | Execuções em andamento | | `GET` | `/api/files` | Listar diretorio |
| `GET` | `/api/executions/history` | Histórico paginado com filtros | | `GET` | `/api/files/download` | Download de arquivo |
| `GET` | `/api/executions/recent` | Execuções recentes | | `GET` | `/api/files/download-folder` | Download de pasta (.tar.gz) |
| `GET` | `/api/executions/export` | Exportar histórico como CSV | | `DELETE` | `/api/files` | Excluir arquivo ou pasta |
| `GET` | `/api/executions/:id` | Detalhes de uma execução | | `POST` | `/api/files/publish` | Publicar projeto (repo + deploy + subdominio) |
| `DELETE` | `/api/executions/:id` | Excluir execução do histórico |
| `POST` | `/api/executions/:id/retry` | Reexecutar execução falha |
| `DELETE` | `/api/executions` | Limpar histórico |
### Notificações
| Método | Endpoint | Descrição |
|--------|----------|-----------|
| `GET` | `/api/notifications` | Listar notificações |
| `POST` | `/api/notifications/:id/read` | Marcar como lida |
| `POST` | `/api/notifications/read-all` | Marcar todas como lidas |
| `DELETE` | `/api/notifications` | Limpar notificações |
### Sistema ### Sistema
| Método | Endpoint | Descrição | | Metodo | Endpoint | Descricao |
|--------|----------|-----------| |--------|----------|-----------|
| `GET` | `/api/health` | Health check (sem auth) | | `GET` | `/api/health` | Health check |
| `GET` | `/api/system/status` | Status geral do sistema | | `GET` | `/api/system/status` | Status geral |
| `GET` | `/api/system/info` | Informações do servidor | | `GET` | `/api/stats/costs` | Estatisticas de custo |
| `GET` | `/api/stats/costs` | Estatísticas de custo | | `GET` | `/api/stats/charts` | Dados para graficos |
| `GET` | `/api/stats/charts` | Dados para gráficos do dashboard |
| `GET/PUT` | `/api/settings` | Configurações globais | ---
## Deploy
### Deploy automatico
```bash
git deploy
```
O alias executa `scripts/deploy.sh` que automaticamente:
1. Push para GitHub e Gitea
2. Backup dos dados no VPS
3. Sincronizacao via rsync
4. Correcao de permissoes
5. Rebuild do container Docker
6. Verificacao de integridade
7. Limpeza de backups antigos (mantem 3)
```bash
# Apenas deploy sem push
bash scripts/deploy.sh --skip-push
```
### Variaveis de Ambiente
| Variavel | Descricao | Padrao |
|----------|-----------|--------|
| `PORT` | Porta do servidor | `3000` |
| `HOST` | Endereco de bind | `0.0.0.0` |
| `AUTH_TOKEN` | Bearer token para auth da API | _(desabilitado)_ |
| `ALLOWED_ORIGIN` | Origin para CORS | `http://localhost:3000` |
| `WEBHOOK_SECRET` | Segredo HMAC para webhooks | _(desabilitado)_ |
| `GITEA_URL` | URL interna do Gitea | `http://gitea:3000` |
| `GITEA_USER` | Usuario do Gitea | `fred` |
| `GITEA_PASS` | Senha do Gitea | _(obrigatorio para Git)_ |
| `DOMAIN` | Dominio base para subdominios | `nitro-cloud.duckdns.org` |
| `CLAUDE_BIN` | Caminho do CLI Claude | _(auto-detectado)_ |
| `REDIS_URL` | Redis para cache L2 | _(somente memoria)_ |
---
## Seguranca
- HTTPS via Caddy com certificado wildcard Let's Encrypt
- Autenticacao Bearer token com timing-safe comparison
- Rate limiting: 100 req/min (API), 30 req/min (webhooks)
- CORS restrito a origin configurada
- Correlation IDs em todas as requisicoes
- Escrita atomica em disco (temp + rename)
- Sanitizacao de prompts (NUL, controle, limite 50K chars)
- HMAC-SHA256 para webhooks recebidos
- Protecao contra path traversal no file explorer
---
## Eventos WebSocket ## Eventos WebSocket
O servidor envia eventos tipados via WebSocket que o frontend renderiza no terminal: | Evento | Descricao |
| Evento | Descrição |
|--------|-----------| |--------|-----------|
| `execution_output` | Chunk de texto da saída do agente | | `execution_output` | Chunk de saida do agente |
| `execution_complete` | Execução finalizada com resultado | | `execution_complete` | Execucao finalizada |
| `execution_error` | Erro durante execução | | `execution_error` | Erro durante execucao |
| `pipeline_step_start` | Início de um passo do pipeline | | `execution_retry` | Tentativa de retry |
| `pipeline_step_complete` | Passo do pipeline concluído | | `pipeline_step_start` | Inicio de passo |
| `pipeline_step_complete` | Passo concluido |
| `pipeline_complete` | Pipeline finalizado | | `pipeline_complete` | Pipeline finalizado |
| `pipeline_error` | Erro em um passo do pipeline | | `pipeline_error` | Erro no pipeline |
| `pipeline_approval_required` | Passo aguardando aprovação humana | | `pipeline_approval_required` | Aguardando aprovacao humana |
| `report_generated` | Relatorio gerado |
## Segurança ---
- **Autenticação** via Bearer token (variável `AUTH_TOKEN`)
- **Rate limiting** — 100 requisições por minuto por IP
- **CORS** restrito à origin configurada
- **Timing-safe comparison** para tokens de autenticação e webhooks
- **Correlation IDs** em todas as requisições para rastreabilidade
- **Escrita atômica** em disco (temp + rename) para integridade de dados
- **Sanitização** de prompts (NUL, caracteres de controle, limite de 50.000 chars)
- **Assinatura HMAC-SHA256** para webhooks recebidos
## Stack ## Stack
- **Backend**: Node.js, Express, WebSocket (ws), node-cron, uuid, express-rate-limit | Camada | Tecnologias |
- **Frontend**: HTML, CSS, JavaScript vanilla (sem framework, sem bundler) |--------|-------------|
- **Gráficos**: Chart.js 4.x | **Backend** | Node.js 22, Express, WebSocket (ws), node-cron, uuid |
- **Ícones**: Lucide | **Frontend** | HTML, CSS, JavaScript vanilla — sem framework, sem bundler |
- **Fontes**: Inter (UI), JetBrains Mono (código/terminal) | **Graficos** | Chart.js 4.x |
- **Persistência**: Arquivos JSON em disco com escrita atômica | **Icones** | Lucide |
- **Cache**: In-memory com suporte opcional a Redis (ioredis) | **Fontes** | Inter (UI), JetBrains Mono (terminal) |
| **Persistencia** | JSON em disco com escrita atomica |
| **Cache** | In-memory + Redis opcional (ioredis) |
| **Infra** | Docker, Caddy, DuckDNS, Let's Encrypt |
| **Git** | Gitea (self-hosted) |
## Licença ---
## Licenca
MIT MIT
---
<p align="center">
<sub>Desenvolvido por <a href="https://nitro-cloud.duckdns.org">Nitro Cloud</a></sub>
</p>

1444
public/app.html Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -542,6 +542,84 @@ textarea {
margin-left: auto; margin-left: auto;
} }
.agent-card--leader {
--leader-gold: #f59e0b;
--leader-gold-light: #fbbf24;
--leader-gold-dark: #d97706;
--leader-glow: rgba(245, 158, 11, 0.15);
--leader-glow-strong: rgba(245, 158, 11, 0.25);
border: 1px solid var(--leader-gold-dark);
background:
linear-gradient(90deg, var(--leader-gold), var(--leader-gold-light), var(--leader-gold)) 0 0 / 200% 2px no-repeat,
var(--bg-card);
background-origin: border-box;
position: relative;
}
.agent-card--leader::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 2px;
background: linear-gradient(90deg, transparent, var(--leader-gold-light), transparent);
animation: leaderShimmer 3s ease-in-out infinite;
}
@keyframes leaderShimmer {
0%, 100% { opacity: 0.4; transform: translateX(-50%); }
50% { opacity: 1; transform: translateX(50%); }
}
.agent-card--leader:hover {
border-color: var(--leader-gold);
box-shadow: 0 8px 32px var(--leader-glow-strong);
}
.agent-card--leader .agent-avatar {
box-shadow: 0 0 0 2px var(--leader-gold), 0 0 12px var(--leader-glow);
}
.agent-leader-icon {
width: 14px;
height: 14px;
color: var(--warning);
vertical-align: -1px;
margin-right: 4px;
flex-shrink: 0;
filter: drop-shadow(0 0 3px rgba(245, 158, 11, 0.4));
}
.agent-card--po {
--po-cyan: #06b6d4;
--po-cyan-dark: #0891b2;
--po-glow: rgba(6, 182, 212, 0.1);
border: 1px solid var(--po-cyan-dark);
background:
linear-gradient(90deg, var(--po-cyan-dark), var(--po-cyan), var(--po-cyan-dark)) 0 0 / 100% 1px no-repeat,
var(--bg-card);
background-origin: border-box;
}
.agent-card--po:hover {
border-color: var(--po-cyan);
box-shadow: 0 8px 24px var(--po-glow);
}
.agent-card--po .agent-avatar {
box-shadow: 0 0 0 2px var(--po-cyan-dark), 0 0 8px var(--po-glow);
}
.agent-po-icon {
width: 14px;
height: 14px;
color: var(--po-cyan);
vertical-align: -1px;
margin-right: 4px;
flex-shrink: 0;
}
.badge { .badge {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -888,15 +966,22 @@ textarea {
transform: scale(1) translateY(0); transform: scale(1) translateY(0);
} }
.modal-sm { .modal-sm,
.modal--sm {
max-width: 400px; max-width: 400px;
} }
.modal-lg { .modal--md {
max-width: 700px;
}
.modal-lg,
.modal--lg {
max-width: 800px; max-width: 800px;
} }
.modal-xl { .modal-xl,
.modal--xl {
max-width: 1000px; max-width: 1000px;
} }
@@ -1010,29 +1095,32 @@ textarea {
flex: 1; flex: 1;
padding: 16px; padding: 16px;
overflow-y: auto; overflow-y: auto;
overflow-x: hidden;
font-family: 'JetBrains Mono', monospace; font-family: 'JetBrains Mono', monospace;
font-size: 13px; font-size: 13px;
line-height: 1.7; line-height: 1.7;
min-width: 0;
} }
.terminal-line { .terminal-line {
padding: 2px 0; padding: 2px 0;
display: flex; display: grid;
align-items: flex-start; grid-template-columns: auto 1fr;
gap: 12px;
} }
.terminal-line .timestamp { .terminal-line .timestamp {
color: var(--text-muted); color: var(--text-muted);
margin-right: 12px;
flex-shrink: 0;
font-size: 12px; font-size: 12px;
padding-top: 1px; padding-top: 1px;
white-space: nowrap;
} }
.terminal-line .content { .terminal-line .content {
color: #c8c8d8; color: #c8c8d8;
word-break: break-all; word-break: break-word;
flex: 1; overflow-wrap: anywhere;
white-space: pre-wrap;
} }
.terminal-line.error .content { .terminal-line.error .content {
@@ -3292,9 +3380,14 @@ tbody tr:hover td {
font-size: 13px; font-size: 13px;
color: var(--text-secondary); color: var(--text-secondary);
line-height: 1.5; line-height: 1.5;
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
} }
.task-card-footer { .task-card-footer {
margin-top: 12px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
@@ -3411,11 +3504,30 @@ tbody tr:hover td {
} }
} }
.pipeline-workdir-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 10px;
background-color: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: 6px;
font-size: 11px;
color: var(--text-muted);
margin-bottom: 4px;
}
.pipeline-workdir-badge code {
font-family: 'JetBrains Mono', monospace;
font-size: 11px;
color: var(--text-secondary);
}
.pipeline-flow { .pipeline-flow {
display: flex; display: flex;
align-items: center; flex-direction: column;
align-items: flex-start;
gap: 4px; gap: 4px;
flex-wrap: wrap;
padding: 8px 0; padding: 8px 0;
} }
@@ -3451,6 +3563,61 @@ tbody tr:hover td {
flex-shrink: 0; flex-shrink: 0;
} }
.pipeline-step-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.pipeline-mode-toggle {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
background: none;
border: 1px solid var(--border-primary);
border-radius: 4px;
color: var(--text-muted);
font-size: 11px;
cursor: pointer;
transition: all 0.15s ease;
white-space: nowrap;
}
.pipeline-mode-toggle:hover {
color: var(--text-secondary);
border-color: var(--border-secondary);
background-color: var(--bg-secondary);
}
.pipeline-step-hints {
display: flex;
flex-direction: column;
gap: 4px;
}
.pipeline-step-hint {
display: flex;
align-items: center;
gap: 4px;
font-size: 11px;
color: var(--text-muted);
padding: 0 2px;
line-height: 1.4;
}
.pipeline-step-hint code {
background-color: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 3px;
padding: 0 4px;
font-family: 'JetBrains Mono', monospace;
font-size: 10px;
color: var(--text-secondary);
white-space: nowrap;
}
.pipeline-step-row { .pipeline-step-row {
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
@@ -4622,3 +4789,572 @@ body, .sidebar, .header, .card, .modal-content, .input, .select, textarea, .metr
gap: 4px; gap: 4px;
} }
} }
/* ─── Flow Editor ─── */
.flow-editor-overlay {
position: fixed;
inset: 0;
background-color: var(--bg-primary);
z-index: 2000;
display: flex;
flex-direction: column;
opacity: 0;
transition: opacity 0.25s ease;
}
.flow-editor-overlay.active {
opacity: 1;
}
.flow-editor {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
}
.flow-editor-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 20px;
border-bottom: 1px solid var(--border-primary);
background-color: var(--bg-secondary);
flex-shrink: 0;
gap: 16px;
z-index: 10;
}
.flow-editor-header-left {
display: flex;
align-items: center;
gap: 12px;
}
.flow-editor-title-group {
display: flex;
flex-direction: column;
}
.flow-editor-title {
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
line-height: 1.2;
}
.flow-editor-subtitle {
font-size: 11px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.flow-editor-header-actions {
display: flex;
align-items: center;
gap: 8px;
}
.flow-editor-zoom {
display: flex;
align-items: center;
gap: 4px;
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: 8px;
padding: 2px 4px;
}
.flow-zoom-label {
font-size: 12px;
color: var(--text-secondary);
min-width: 40px;
text-align: center;
font-variant-numeric: tabular-nums;
}
.flow-btn {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 8px 14px;
border-radius: 8px;
border: 1px solid transparent;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all 0.15s;
font-family: 'Inter', sans-serif;
white-space: nowrap;
}
.flow-btn--ghost {
background: transparent;
color: var(--text-secondary);
border-color: transparent;
}
.flow-btn--ghost:hover {
background: var(--bg-tertiary);
color: var(--text-primary);
}
.flow-btn--primary {
background: var(--gradient-primary);
color: #fff;
border-color: transparent;
}
.flow-btn--primary:hover {
filter: brightness(1.15);
}
.flow-btn--danger {
background: transparent;
color: var(--error);
border-color: rgba(239, 68, 68, 0.3);
}
.flow-btn--danger:hover {
background: rgba(239, 68, 68, 0.1);
}
.flow-btn--sm {
padding: 5px 10px;
font-size: 12px;
}
.flow-btn--full {
width: 100%;
justify-content: center;
}
.flow-btn--disabled {
opacity: 0.4;
pointer-events: none;
}
.flow-editor-body {
flex: 1;
display: flex;
overflow: hidden;
position: relative;
}
.flow-editor-canvas-wrap {
flex: 1;
position: relative;
overflow: hidden;
cursor: grab;
background-color: var(--bg-primary);
}
.flow-editor-canvas-wrap:active {
cursor: grabbing;
}
#flow-editor-canvas {
position: absolute;
inset: 0;
pointer-events: none;
}
.flow-editor-nodes {
position: absolute;
inset: 0;
pointer-events: none;
}
.flow-node {
position: absolute;
top: 0;
left: 0;
transform-origin: 0 0;
pointer-events: auto;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 12px;
padding: 0;
cursor: pointer;
transition: border-color 0.15s, box-shadow 0.15s;
overflow: hidden;
display: flex;
flex-direction: column;
user-select: none;
}
.flow-node:hover {
border-color: var(--border-secondary);
box-shadow: 0 0 0 1px var(--border-secondary);
}
.flow-node--selected {
border-color: var(--accent);
box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.3), 0 4px 20px rgba(99, 102, 241, 0.1);
}
.flow-node-header {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 14px 6px;
}
.flow-node-number {
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
border-radius: 50%;
background: var(--gradient-primary);
color: #fff;
font-size: 11px;
font-weight: 700;
flex-shrink: 0;
}
.flow-node-name {
font-size: 13px;
font-weight: 600;
color: var(--text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
}
.flow-node-approval {
font-size: 10px;
padding: 2px 6px;
border-radius: 4px;
background: rgba(245, 158, 11, 0.15);
color: var(--warning);
font-weight: 600;
flex-shrink: 0;
}
.flow-node-sub {
padding: 0 14px 10px;
font-size: 11px;
color: var(--text-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.flow-node-placeholder {
font-style: italic;
color: var(--text-muted);
opacity: 0.6;
}
/* ─── Flow Panel (sidebar de edição) ─── */
.flow-editor-panel {
width: 320px;
background: var(--bg-secondary);
border-left: 1px solid var(--border-primary);
display: flex;
flex-direction: column;
flex-shrink: 0;
overflow-y: auto;
animation: slideInFromRight 0.2s ease;
}
@keyframes slideInFromRight {
from { transform: translateX(20px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.flow-panel-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 16px 12px;
border-bottom: 1px solid var(--border-primary);
}
.flow-panel-title {
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
}
.flow-panel-body {
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
}
.flow-panel-field {
display: flex;
flex-direction: column;
gap: 6px;
}
.flow-panel-label {
font-size: 12px;
font-weight: 500;
color: var(--text-secondary);
}
.flow-panel-select {
width: 100%;
padding: 8px 12px;
border-radius: 8px;
border: 1px solid var(--border-primary);
background: var(--bg-input);
color: var(--text-primary);
font-size: 13px;
font-family: 'Inter', sans-serif;
outline: none;
transition: border-color 0.15s;
}
.flow-panel-select:focus {
border-color: var(--border-focus);
}
.flow-panel-textarea {
width: 100%;
padding: 8px 12px;
border-radius: 8px;
border: 1px solid var(--border-primary);
background: var(--bg-input);
color: var(--text-primary);
font-size: 13px;
font-family: 'JetBrains Mono', monospace;
resize: vertical;
min-height: 80px;
outline: none;
transition: border-color 0.15s;
}
.flow-panel-textarea:focus {
border-color: var(--border-focus);
}
.flow-panel-hint {
font-size: 11px;
color: var(--text-muted);
}
.flow-panel-hint code {
background: var(--bg-tertiary);
padding: 1px 5px;
border-radius: 4px;
font-family: 'JetBrains Mono', monospace;
font-size: 11px;
color: var(--accent);
}
.flow-panel-checkbox {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: var(--text-secondary);
cursor: pointer;
}
.flow-panel-checkbox input[type="checkbox"] {
width: 16px;
height: 16px;
accent-color: var(--accent);
cursor: pointer;
}
.flow-panel-actions-group {
display: flex;
flex-direction: column;
gap: 6px;
margin-top: 8px;
padding-top: 16px;
border-top: 1px solid var(--border-primary);
}
/* File Explorer */
#files-container {
display: flex;
flex-direction: column;
gap: 16px;
}
.files-breadcrumb {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
padding: 12px 16px;
background: var(--bg-card);
border: 1px solid var(--border-primary);
border-radius: 8px;
font-size: 13px;
}
.files-breadcrumb-link {
display: inline-flex;
align-items: center;
gap: 4px;
color: var(--accent);
text-decoration: none;
font-weight: 500;
transition: color 0.2s;
}
.files-breadcrumb-link:hover {
color: var(--accent-hover);
}
.files-breadcrumb-link:last-child {
color: var(--text-primary);
pointer-events: none;
}
.files-breadcrumb-sep {
color: var(--text-muted);
user-select: none;
}
.files-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
}
.files-count {
font-size: 13px;
color: var(--text-muted);
}
.files-table-wrapper {
background: var(--bg-card);
border: 1px solid var(--border-primary);
border-radius: 8px;
overflow: hidden;
}
.files-table {
width: 100%;
border-collapse: collapse;
}
.files-table thead {
background: var(--bg-tertiary);
}
.files-table th {
text-align: left;
padding: 10px 16px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-muted);
border-bottom: 1px solid var(--border-primary);
}
.files-table td {
padding: 10px 16px;
font-size: 13px;
color: var(--text-secondary);
border-bottom: 1px solid var(--border-primary);
}
.files-row:last-child td {
border-bottom: none;
}
.files-row:hover {
background: var(--bg-card-hover);
}
.files-td-name {
color: var(--text-primary);
}
.files-th-size,
.files-td-size {
width: 100px;
text-align: right;
}
.files-th-date,
.files-td-date {
width: 160px;
}
.files-th-actions,
.files-td-actions {
width: 120px;
text-align: right;
}
.files-td-actions {
display: flex;
gap: 4px;
justify-content: flex-end;
align-items: center;
}
.repo-selector { display: flex; gap: 8px; }
.repo-selector .select { flex: 1; }
.btn-publish { color: var(--success); }
.btn-publish:hover { background: rgba(16, 185, 129, 0.1); }
.publish-result { display: flex; flex-direction: column; gap: 12px; padding: 8px 0; }
.publish-result-item { font-size: 14px; }
.publish-result-item a { color: var(--accent); text-decoration: underline; }
.files-entry-link {
display: inline-flex;
align-items: center;
gap: 8px;
text-decoration: none;
color: inherit;
}
.files-entry-dir {
color: var(--text-primary);
font-weight: 500;
cursor: pointer;
transition: color 0.2s;
}
.files-entry-dir:hover {
color: var(--accent);
}
.files-entry-file {
color: var(--text-secondary);
}
.files-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 80px 20px;
background: var(--bg-card);
border: 1px solid var(--border-primary);
border-radius: 8px;
color: var(--text-muted);
font-size: 14px;
}
@media (max-width: 768px) {
.files-th-date,
.files-td-date {
display: none;
}
.files-th-size,
.files-td-size {
width: 70px;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -38,8 +38,10 @@ const API = {
create(data) { return API.request('POST', '/agents', data); }, create(data) { return API.request('POST', '/agents', data); },
update(id, data) { return API.request('PUT', `/agents/${id}`, data); }, update(id, data) { return API.request('PUT', `/agents/${id}`, data); },
delete(id) { return API.request('DELETE', `/agents/${id}`); }, delete(id) { return API.request('DELETE', `/agents/${id}`); },
execute(id, task, instructions, contextFiles) { execute(id, task, instructions, contextFiles, workingDirectory, repoName, repoBranch) {
const body = { task, instructions }; const body = { task, instructions };
if (repoName) { body.repoName = repoName; if (repoBranch) body.repoBranch = repoBranch; }
else if (workingDirectory) body.workingDirectory = workingDirectory;
if (contextFiles && contextFiles.length > 0) body.contextFiles = contextFiles; if (contextFiles && contextFiles.length > 0) body.contextFiles = contextFiles;
return API.request('POST', `/agents/${id}/execute`, body); return API.request('POST', `/agents/${id}/execute`, body);
}, },
@@ -82,15 +84,17 @@ const API = {
create(data) { return API.request('POST', '/pipelines', data); }, create(data) { return API.request('POST', '/pipelines', data); },
update(id, data) { return API.request('PUT', `/pipelines/${id}`, data); }, update(id, data) { return API.request('PUT', `/pipelines/${id}`, data); },
delete(id) { return API.request('DELETE', `/pipelines/${id}`); }, delete(id) { return API.request('DELETE', `/pipelines/${id}`); },
execute(id, input, workingDirectory, contextFiles) { execute(id, input, workingDirectory, contextFiles, repoName, repoBranch) {
const body = { input }; const body = { input };
if (workingDirectory) body.workingDirectory = workingDirectory; if (repoName) { body.repoName = repoName; if (repoBranch) body.repoBranch = repoBranch; }
else if (workingDirectory) body.workingDirectory = workingDirectory;
if (contextFiles && contextFiles.length > 0) body.contextFiles = contextFiles; if (contextFiles && contextFiles.length > 0) body.contextFiles = contextFiles;
return API.request('POST', `/pipelines/${id}/execute`, body); return API.request('POST', `/pipelines/${id}/execute`, body);
}, },
cancel(id) { return API.request('POST', `/pipelines/${id}/cancel`); }, cancel(id) { return API.request('POST', `/pipelines/${id}/cancel`); },
approve(id) { return API.request('POST', `/pipelines/${id}/approve`); }, approve(id) { return API.request('POST', `/pipelines/${id}/approve`); },
reject(id) { return API.request('POST', `/pipelines/${id}/reject`); }, reject(id) { return API.request('POST', `/pipelines/${id}/reject`); },
resume(executionId) { return API.request('POST', `/pipelines/resume/${executionId}`); },
}, },
webhooks: { webhooks: {
@@ -117,6 +121,7 @@ const API = {
status() { return API.request('GET', '/system/status'); }, status() { return API.request('GET', '/system/status'); },
info() { return API.request('GET', '/system/info'); }, info() { return API.request('GET', '/system/info'); },
activeExecutions() { return API.request('GET', '/executions/active'); }, activeExecutions() { return API.request('GET', '/executions/active'); },
cancelAll() { return API.request('POST', '/executions/cancel-all'); },
}, },
settings: { settings: {
@@ -139,6 +144,17 @@ const API = {
}, },
}, },
repos: {
list() { return API.request('GET', '/repos'); },
branches(name) { return API.request('GET', `/repos/${encodeURIComponent(name)}/branches`); },
},
files: {
list(path) { return API.request('GET', `/files${path ? '?path=' + encodeURIComponent(path) : ''}`); },
delete(path) { return API.request('DELETE', `/files?path=${encodeURIComponent(path)}`); },
publish(path) { return API.request('POST', '/files/publish', { path }); },
},
reports: { reports: {
list() { return API.request('GET', '/reports'); }, list() { return API.request('GET', '/reports'); },
get(filename) { return API.request('GET', `/reports/${encodeURIComponent(filename)}`); }, get(filename) { return API.request('GET', `/reports/${encodeURIComponent(filename)}`); },

View File

@@ -17,10 +17,11 @@ const App = {
webhooks: 'Webhooks', webhooks: 'Webhooks',
terminal: 'Terminal', terminal: 'Terminal',
history: 'Histórico', history: 'Histórico',
files: 'Projetos',
settings: 'Configurações', settings: 'Configurações',
}, },
sections: ['dashboard', 'agents', 'tasks', 'schedules', 'pipelines', 'webhooks', 'terminal', 'history', 'settings'], sections: ['dashboard', 'agents', 'tasks', 'schedules', 'pipelines', 'webhooks', 'terminal', 'history', 'files', 'settings'],
init() { init() {
if (App._initialized) return; if (App._initialized) return;
@@ -36,6 +37,7 @@ const App = {
App._executeDropzone = Utils.initDropzone('execute-dropzone', 'execute-files', 'execute-file-list'); App._executeDropzone = Utils.initDropzone('execute-dropzone', 'execute-files', 'execute-file-list');
App._pipelineDropzone = Utils.initDropzone('pipeline-execute-dropzone', 'pipeline-execute-files', 'pipeline-execute-file-list'); App._pipelineDropzone = Utils.initDropzone('pipeline-execute-dropzone', 'pipeline-execute-files', 'pipeline-execute-file-list');
App._initRepoSelectors();
const initialSection = location.hash.replace('#', '') || 'dashboard'; const initialSection = location.hash.replace('#', '') || 'dashboard';
App.navigateTo(App.sections.includes(initialSection) ? initialSection : 'dashboard'); App.navigateTo(App.sections.includes(initialSection) ? initialSection : 'dashboard');
@@ -113,6 +115,7 @@ const App = {
case 'pipelines': await PipelinesUI.load(); break; case 'pipelines': await PipelinesUI.load(); break;
case 'webhooks': await WebhooksUI.load(); break; case 'webhooks': await WebhooksUI.load(); break;
case 'history': await HistoryUI.load(); break; case 'history': await HistoryUI.load(); break;
case 'files': await FilesUI.load(); break;
case 'settings': await SettingsUI.load(); break; case 'settings': await SettingsUI.load(); break;
} }
} catch (err) { } catch (err) {
@@ -276,6 +279,7 @@ const App = {
case 'pipeline_step_start': case 'pipeline_step_start':
Terminal.stopProcessing(); Terminal.stopProcessing();
if (data.resumed) Terminal.addLine('(retomando execução anterior)', 'system');
Terminal.addLine(`Pipeline passo ${data.stepIndex + 1}/${data.totalSteps}: Executando agente "${data.agentName}"...`, 'system'); Terminal.addLine(`Pipeline passo ${data.stepIndex + 1}/${data.totalSteps}: Executando agente "${data.agentName}"...`, 'system');
Terminal.startProcessing(data.agentName); Terminal.startProcessing(data.agentName);
break; break;
@@ -289,6 +293,9 @@ const App = {
case 'pipeline_complete': case 'pipeline_complete':
Terminal.stopProcessing(); Terminal.stopProcessing();
Terminal.addLine('Pipeline concluído com sucesso.', 'success'); Terminal.addLine('Pipeline concluído com sucesso.', 'success');
if (data.lastSessionId && data.lastAgentId) {
Terminal.enableChat(data.lastAgentId, data.lastAgentName || 'Agente', data.lastSessionId);
}
Toast.success('Pipeline concluído'); Toast.success('Pipeline concluído');
App.refreshCurrentSection(); App.refreshCurrentSection();
break; break;
@@ -551,6 +558,18 @@ const App = {
on('pipeline-execute-submit', 'click', () => PipelinesUI._executeFromModal()); on('pipeline-execute-submit', 'click', () => PipelinesUI._executeFromModal());
on('terminal-stop-btn', 'click', async () => {
try {
await API.system.cancelAll();
Terminal.stopProcessing();
Terminal.addLine('Todas as execuções foram interrompidas.', 'error');
Toast.warning('Execuções interrompidas');
App._updateActiveBadge();
} catch (err) {
Toast.error(`Erro ao interromper: ${err.message}`);
}
});
on('terminal-clear-btn', 'click', () => { on('terminal-clear-btn', 'click', () => {
Terminal.clear(); Terminal.clear();
Terminal.disableChat(); Terminal.disableChat();
@@ -716,6 +735,7 @@ const App = {
switch (action) { switch (action) {
case 'execute-pipeline': PipelinesUI.execute(id); break; case 'execute-pipeline': PipelinesUI.execute(id); break;
case 'edit-pipeline': PipelinesUI.openEditModal(id); break; case 'edit-pipeline': PipelinesUI.openEditModal(id); break;
case 'flow-pipeline': FlowEditor.open(id); break;
case 'delete-pipeline': PipelinesUI.delete(id); break; case 'delete-pipeline': PipelinesUI.delete(id); break;
} }
}); });
@@ -728,6 +748,7 @@ const App = {
case 'view-execution': HistoryUI.viewDetail(id); break; case 'view-execution': HistoryUI.viewDetail(id); break;
case 'delete-execution': HistoryUI.deleteExecution(id); break; case 'delete-execution': HistoryUI.deleteExecution(id); break;
case 'retry': HistoryUI.retryExecution(id); break; case 'retry': HistoryUI.retryExecution(id); break;
case 'resume-pipeline': HistoryUI.resumePipeline(id); break;
} }
}); });
@@ -745,6 +766,20 @@ const App = {
} }
}); });
document.getElementById('files-container')?.addEventListener('click', (e) => {
const el = e.target.closest('[data-action]');
if (!el) return;
e.preventDefault();
const { action, path } = el.dataset;
switch (action) {
case 'navigate-files': FilesUI.navigate(path || ''); break;
case 'download-file': FilesUI.downloadFile(path); break;
case 'download-folder': FilesUI.downloadFolder(path); break;
case 'publish-project': FilesUI.publishProject(path); break;
case 'delete-entry': FilesUI.deleteEntry(path, el.dataset.entryType); break;
}
});
document.getElementById('pipeline-steps-container')?.addEventListener('click', (e) => { document.getElementById('pipeline-steps-container')?.addEventListener('click', (e) => {
const btn = e.target.closest('[data-step-action]'); const btn = e.target.closest('[data-step-action]');
if (!btn) return; if (!btn) return;
@@ -756,6 +791,7 @@ const App = {
case 'move-up': PipelinesUI.moveStep(stepIndex, -1); break; case 'move-up': PipelinesUI.moveStep(stepIndex, -1); break;
case 'move-down': PipelinesUI.moveStep(stepIndex, 1); break; case 'move-down': PipelinesUI.moveStep(stepIndex, 1); break;
case 'remove': PipelinesUI.removeStep(stepIndex); break; case 'remove': PipelinesUI.removeStep(stepIndex); break;
case 'toggle-mode': PipelinesUI.toggleMode(stepIndex); break;
} }
}); });
@@ -825,6 +861,61 @@ const App = {
}); });
}, },
_reposCache: null,
async _loadRepos(selectId) {
const select = document.getElementById(selectId);
if (!select) return;
try {
if (!App._reposCache) App._reposCache = await API.repos.list();
const current = select.value;
select.innerHTML = '<option value="">Nenhum (usar diretório manual)</option>';
App._reposCache.forEach(r => {
select.insertAdjacentHTML('beforeend',
`<option value="${Utils.escapeHtml(r.name)}">${Utils.escapeHtml(r.name)}${r.description ? ' — ' + Utils.escapeHtml(r.description.slice(0, 40)) : ''}</option>`
);
});
if (current) select.value = current;
} catch { }
},
_initRepoSelectors() {
const pairs = [
['execute-repo', 'execute-repo-branch', 'execute-workdir-group'],
['pipeline-execute-repo', 'pipeline-execute-repo-branch', 'pipeline-execute-workdir-group'],
];
pairs.forEach(([repoId, branchId, workdirGroupId]) => {
const repoSelect = document.getElementById(repoId);
const branchSelect = document.getElementById(branchId);
const workdirGroup = document.getElementById(workdirGroupId);
if (!repoSelect) return;
repoSelect.addEventListener('change', async () => {
const repoName = repoSelect.value;
if (repoName) {
if (workdirGroup) workdirGroup.style.display = 'none';
if (branchSelect) {
branchSelect.style.display = '';
branchSelect.innerHTML = '<option value="">Branch padrão</option>';
try {
const branches = await API.repos.branches(repoName);
branches.forEach(b => {
branchSelect.insertAdjacentHTML('beforeend', `<option value="${Utils.escapeHtml(b)}">${Utils.escapeHtml(b)}</option>`);
});
} catch { }
}
} else {
if (workdirGroup) workdirGroup.style.display = '';
if (branchSelect) branchSelect.style.display = 'none';
}
});
repoSelect.addEventListener('focus', () => {
if (repoSelect.options.length <= 1) App._loadRepos(repoId);
});
});
},
async _handleExecute() { async _handleExecute() {
const agentId = document.getElementById('execute-agent-select')?.value const agentId = document.getElementById('execute-agent-select')?.value
|| document.getElementById('execute-agent-id')?.value; || document.getElementById('execute-agent-id')?.value;
@@ -841,6 +932,9 @@ const App = {
} }
const instructions = document.getElementById('execute-instructions')?.value.trim() || ''; const instructions = document.getElementById('execute-instructions')?.value.trim() || '';
const workingDirectory = document.getElementById('execute-workdir')?.value.trim() || '';
const repoName = document.getElementById('execute-repo')?.value || '';
const repoBranch = document.getElementById('execute-repo-branch')?.value || '';
try { try {
const selectEl = document.getElementById('execute-agent-select'); const selectEl = document.getElementById('execute-agent-select');
@@ -857,7 +951,7 @@ const App = {
Terminal.disableChat(); Terminal.disableChat();
App._lastAgentName = agentName; App._lastAgentName = agentName;
await API.agents.execute(agentId, task, instructions, contextFiles); await API.agents.execute(agentId, task, instructions, contextFiles, workingDirectory, repoName, repoBranch);
if (dropzone) dropzone.reset(); if (dropzone) dropzone.reset();
Modal.close('execute-modal-overlay'); Modal.close('execute-modal-overlay');
@@ -953,6 +1047,9 @@ const App = {
if (countEl) countEl.textContent = count; if (countEl) countEl.textContent = count;
if (badge) badge.style.display = count > 0 ? 'flex' : 'none'; if (badge) badge.style.display = count > 0 ? 'flex' : 'none';
const stopBtn = document.getElementById('terminal-stop-btn');
if (stopBtn) stopBtn.hidden = count === 0;
const terminalSelect = document.getElementById('terminal-execution-select'); const terminalSelect = document.getElementById('terminal-execution-select');
if (terminalSelect && Array.isArray(active)) { if (terminalSelect && Array.isArray(active)) {
const existing = new Set( const existing = new Set(

View File

@@ -39,8 +39,19 @@ const AgentsUI = {
if (empty) empty.style.display = 'none'; if (empty) empty.style.display = 'none';
const sorted = [...agents].sort((a, b) => {
const rank = (agent) => {
const name = (agent.agent_name || agent.name || '').toLowerCase();
const tags = (agent.tags || []).map((t) => t.toLowerCase());
if (name === 'tech lead' || tags.includes('lider')) return 0;
if (name === 'product owner' || tags.includes('po') || tags.includes('product-owner')) return 1;
return 2;
};
return rank(a) - rank(b);
});
const fragment = document.createDocumentFragment(); const fragment = document.createDocumentFragment();
agents.forEach((agent) => { sorted.forEach((agent) => {
const wrapper = document.createElement('div'); const wrapper = document.createElement('div');
wrapper.innerHTML = AgentsUI.renderCard(agent); wrapper.innerHTML = AgentsUI.renderCard(agent);
fragment.appendChild(wrapper.firstElementChild); fragment.appendChild(wrapper.firstElementChild);
@@ -78,16 +89,26 @@ const AgentsUI = {
const tags = Array.isArray(agent.tags) && agent.tags.length > 0 const tags = Array.isArray(agent.tags) && agent.tags.length > 0
? `<div class="agent-tags">${agent.tags.map((t) => `<span class="tag-chip tag-chip--sm">${Utils.escapeHtml(t)}</span>`).join('')}</div>` ? `<div class="agent-tags">${agent.tags.map((t) => `<span class="tag-chip tag-chip--sm">${Utils.escapeHtml(t)}</span>`).join('')}</div>`
: ''; : '';
const agentNameLower = (agent.agent_name || agent.name || '').toLowerCase();
const tagsLower = Array.isArray(agent.tags) ? agent.tags.map((t) => t.toLowerCase()) : [];
const isLeader = agentNameLower === 'tech lead' || tagsLower.includes('lider');
const isPO = !isLeader && (agentNameLower === 'product owner' || tagsLower.includes('po') || tagsLower.includes('product-owner'));
const roleClass = isLeader ? ' agent-card--leader' : isPO ? ' agent-card--po' : '';
const roleBadge = isLeader
? '<i data-lucide="crown" class="agent-leader-icon"></i>'
: isPO
? '<i data-lucide="shield-check" class="agent-po-icon"></i>'
: '';
return ` return `
<div class="agent-card" data-agent-id="${agent.id}"> <div class="agent-card${roleClass}" data-agent-id="${agent.id}">
<div class="agent-card-body"> <div class="agent-card-body">
<div class="agent-card-top"> <div class="agent-card-top">
<div class="agent-avatar" style="background-color: ${color}" aria-hidden="true"> <div class="agent-avatar" style="background-color: ${color}" aria-hidden="true">
<span>${initials}</span> <span>${initials}</span>
</div> </div>
<div class="agent-info"> <div class="agent-info">
<h3 class="agent-name">${Utils.escapeHtml(name)}</h3> <h3 class="agent-name">${roleBadge}${Utils.escapeHtml(name)}</h3>
<span class="badge ${statusClass}">${statusLabel}</span> <span class="badge ${statusClass}">${statusLabel}</span>
</div> </div>
</div> </div>
@@ -159,6 +180,9 @@ const AgentsUI = {
const maxTurns = document.getElementById('agent-max-turns'); const maxTurns = document.getElementById('agent-max-turns');
if (maxTurns) maxTurns.value = '0'; if (maxTurns) maxTurns.value = '0';
const workdir = document.getElementById('agent-workdir');
if (workdir) workdir.value = '/home/projetos/';
const permissionMode = document.getElementById('agent-permission-mode'); const permissionMode = document.getElementById('agent-permission-mode');
if (permissionMode) permissionMode.value = ''; if (permissionMode) permissionMode.value = '';
@@ -171,6 +195,8 @@ const AgentsUI = {
const retryMax = document.getElementById('agent-retry-max'); const retryMax = document.getElementById('agent-retry-max');
if (retryMax) retryMax.value = '3'; if (retryMax) retryMax.value = '3';
AgentsUI._populateDelegateSelect('');
const secretsSection = document.getElementById('agent-secrets-section'); const secretsSection = document.getElementById('agent-secrets-section');
if (secretsSection) secretsSection.hidden = true; if (secretsSection) secretsSection.hidden = true;
@@ -229,6 +255,8 @@ const AgentsUI = {
const retryMax = document.getElementById('agent-retry-max'); const retryMax = document.getElementById('agent-retry-max');
if (retryMax) retryMax.value = (agent.config && agent.config.maxRetries) || '3'; if (retryMax) retryMax.value = (agent.config && agent.config.maxRetries) || '3';
AgentsUI._populateDelegateSelect(agent.config?.delegateTo || '', agent.id);
const secretsSection = document.getElementById('agent-secrets-section'); const secretsSection = document.getElementById('agent-secrets-section');
if (secretsSection) secretsSection.hidden = false; if (secretsSection) secretsSection.hidden = false;
@@ -275,6 +303,7 @@ const AgentsUI = {
permissionMode: document.getElementById('agent-permission-mode')?.value || '', permissionMode: document.getElementById('agent-permission-mode')?.value || '',
retryOnFailure: !!document.getElementById('agent-retry-toggle')?.checked, retryOnFailure: !!document.getElementById('agent-retry-toggle')?.checked,
maxRetries: parseInt(document.getElementById('agent-retry-max')?.value) || 3, maxRetries: parseInt(document.getElementById('agent-retry-max')?.value) || 3,
delegateTo: document.getElementById('agent-delegate-to')?.value || '',
}, },
}; };
@@ -337,8 +366,19 @@ const AgentsUI = {
if (App._executeDropzone) App._executeDropzone.reset(); if (App._executeDropzone) App._executeDropzone.reset();
const selectedAgent = allAgents.find(a => a.id === agentId);
const workdirEl = document.getElementById('execute-workdir');
if (workdirEl) {
workdirEl.value = (selectedAgent?.config?.workingDirectory) || '/home/projetos/';
}
AgentsUI._loadSavedTasks(); AgentsUI._loadSavedTasks();
const repoSelect = document.getElementById('execute-repo');
if (repoSelect) { repoSelect.value = ''; repoSelect.dispatchEvent(new Event('change')); }
App._reposCache = null;
App._loadRepos('execute-repo');
Modal.open('execute-modal-overlay'); Modal.open('execute-modal-overlay');
} catch (err) { } catch (err) {
Toast.error(`Erro ao abrir modal de execução: ${err.message}`); Toast.error(`Erro ao abrir modal de execução: ${err.message}`);
@@ -447,6 +487,14 @@ const AgentsUI = {
}); });
}, },
_populateDelegateSelect(currentValue, excludeId) {
const select = document.getElementById('agent-delegate-to');
if (!select) return;
const activeAgents = AgentsUI.agents.filter(a => a.status === 'active' && a.id !== excludeId);
select.innerHTML = '<option value="">Nenhum</option>' +
activeAgents.map(a => `<option value="${a.id}" ${a.id === currentValue ? 'selected' : ''}>${Utils.escapeHtml(a.agent_name || a.name)}</option>`).join('');
},
_setupModalListeners() { _setupModalListeners() {
const retryToggle = document.getElementById('agent-retry-toggle'); const retryToggle = document.getElementById('agent-retry-toggle');
const retryMaxGroup = document.getElementById('agent-retry-max-group'); const retryMaxGroup = document.getElementById('agent-retry-max-group');

View File

@@ -0,0 +1,210 @@
const FilesUI = {
currentPath: '',
async load() {
await FilesUI.navigate('');
},
async navigate(path) {
try {
const data = await API.files.list(path);
FilesUI.currentPath = data.path || '';
FilesUI.render(data);
} catch (err) {
Toast.error(`Erro ao carregar arquivos: ${err.message}`);
}
},
render(data) {
const container = document.getElementById('files-container');
if (!container) return;
const breadcrumb = FilesUI._renderBreadcrumb(data.path);
const entries = data.entries || [];
if (entries.length === 0) {
container.innerHTML = `
${breadcrumb}
<div class="files-empty">
<i data-lucide="folder-open" style="width:48px;height:48px;color:var(--text-muted)"></i>
<p>Nenhum arquivo encontrado neste diretório</p>
</div>
`;
Utils.refreshIcons(container);
return;
}
const rows = entries.map(entry => FilesUI._renderRow(entry, data.path)).join('');
container.innerHTML = `
${breadcrumb}
<div class="files-toolbar">
<span class="files-count">${entries.length} ${entries.length === 1 ? 'item' : 'itens'}</span>
<button class="btn btn--ghost btn--sm" data-action="download-folder" data-path="${Utils.escapeHtml(data.path || '')}" title="Baixar pasta como .tar.gz"><i data-lucide="download" style="width:14px;height:14px"></i> Baixar tudo</button>
</div>
<div class="files-table-wrapper">
<table class="files-table">
<thead>
<tr>
<th class="files-th-name">Nome</th>
<th class="files-th-size">Tamanho</th>
<th class="files-th-date">Modificado</th>
<th class="files-th-actions"></th>
</tr>
</thead>
<tbody>
${rows}
</tbody>
</table>
</div>
`;
Utils.refreshIcons(container);
},
_renderBreadcrumb(currentPath) {
const parts = currentPath ? currentPath.split('/').filter(Boolean) : [];
let html = `<nav class="files-breadcrumb"><a href="#" data-action="navigate-files" data-path="" class="files-breadcrumb-link"><i data-lucide="home" style="width:14px;height:14px"></i> projetos</a>`;
let accumulated = '';
for (const part of parts) {
accumulated += (accumulated ? '/' : '') + part;
html += ` <span class="files-breadcrumb-sep">/</span> <a href="#" data-action="navigate-files" data-path="${Utils.escapeHtml(accumulated)}" class="files-breadcrumb-link">${Utils.escapeHtml(part)}</a>`;
}
html += '</nav>';
return html;
},
_renderRow(entry, currentPath) {
const fullPath = currentPath ? `${currentPath}/${entry.name}` : entry.name;
const icon = entry.type === 'directory' ? 'folder' : FilesUI._fileIcon(entry.extension);
const iconColor = entry.type === 'directory' ? 'var(--warning)' : 'var(--text-muted)';
const size = entry.type === 'directory' ? '—' : FilesUI._formatSize(entry.size);
const date = FilesUI._formatDate(entry.modified);
const nameCell = entry.type === 'directory'
? `<a href="#" class="files-entry-link files-entry-dir" data-action="navigate-files" data-path="${Utils.escapeHtml(fullPath)}"><i data-lucide="${icon}" style="width:16px;height:16px;color:${iconColor};flex-shrink:0"></i> ${Utils.escapeHtml(entry.name)}</a>`
: `<span class="files-entry-link files-entry-file"><i data-lucide="${icon}" style="width:16px;height:16px;color:${iconColor};flex-shrink:0"></i> ${Utils.escapeHtml(entry.name)}</span>`;
const downloadBtn = entry.type === 'directory'
? `<button class="btn btn--ghost btn--sm" data-action="download-folder" data-path="${Utils.escapeHtml(fullPath)}" title="Baixar pasta"><i data-lucide="download" style="width:14px;height:14px"></i></button>`
: `<button class="btn btn--ghost btn--sm" data-action="download-file" data-path="${Utils.escapeHtml(fullPath)}" title="Baixar arquivo"><i data-lucide="download" style="width:14px;height:14px"></i></button>`;
const isRootDir = entry.type === 'directory' && !currentPath;
const publishBtn = isRootDir
? `<button class="btn btn--ghost btn--sm btn-publish" data-action="publish-project" data-path="${Utils.escapeHtml(fullPath)}" title="Publicar projeto"><i data-lucide="rocket" style="width:14px;height:14px"></i></button>`
: '';
const deleteBtn = `<button class="btn btn--ghost btn--sm btn-danger" data-action="delete-entry" data-path="${Utils.escapeHtml(fullPath)}" data-entry-type="${entry.type}" title="Excluir"><i data-lucide="trash-2" style="width:14px;height:14px"></i></button>`;
const actions = `${downloadBtn}${publishBtn}${deleteBtn}`;
return `
<tr class="files-row">
<td class="files-td-name">${nameCell}</td>
<td class="files-td-size">${size}</td>
<td class="files-td-date">${date}</td>
<td class="files-td-actions">${actions}</td>
</tr>
`;
},
_fileIcon(ext) {
const map = {
js: 'file-code-2', ts: 'file-code-2', jsx: 'file-code-2', tsx: 'file-code-2',
py: 'file-code-2', rb: 'file-code-2', go: 'file-code-2', rs: 'file-code-2',
java: 'file-code-2', c: 'file-code-2', cpp: 'file-code-2', h: 'file-code-2',
html: 'file-code-2', css: 'file-code-2', scss: 'file-code-2', vue: 'file-code-2',
json: 'file-json', xml: 'file-json', yaml: 'file-json', yml: 'file-json',
md: 'file-text', txt: 'file-text', log: 'file-text', csv: 'file-text',
pdf: 'file-text',
png: 'file-image', jpg: 'file-image', jpeg: 'file-image', gif: 'file-image',
svg: 'file-image', webp: 'file-image', ico: 'file-image',
zip: 'file-archive', tar: 'file-archive', gz: 'file-archive', rar: 'file-archive',
sh: 'file-terminal', bash: 'file-terminal',
sql: 'database',
env: 'file-lock',
};
return map[ext] || 'file';
},
_formatSize(bytes) {
if (bytes == null) return '—';
if (bytes === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, i)).toFixed(i > 0 ? 1 : 0) + ' ' + units[i];
},
_formatDate(isoString) {
if (!isoString) return '—';
const d = new Date(isoString);
return d.toLocaleDateString('pt-BR') + ' ' + d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
},
downloadFile(path) {
const a = document.createElement('a');
a.href = `/api/files/download?path=${encodeURIComponent(path)}`;
a.download = '';
a.click();
},
downloadFolder(path) {
const a = document.createElement('a');
a.href = `/api/files/download-folder?path=${encodeURIComponent(path)}`;
a.download = '';
a.click();
},
async publishProject(path) {
const name = path.split('/').pop();
const confirmed = await Modal.confirm(
'Publicar projeto',
`Isso irá criar o repositório "${name}" no Gitea, fazer push dos arquivos e publicar em <strong>${name}.nitro-cloud.duckdns.org</strong>. Continuar?`
);
if (!confirmed) return;
try {
Toast.info('Publicando projeto... isso pode levar alguns segundos');
const result = await API.files.publish(path);
Toast.success(`Projeto publicado com sucesso!`);
const modal = document.getElementById('execution-detail-modal-overlay');
const title = document.getElementById('execution-detail-title');
const content = document.getElementById('execution-detail-content');
if (modal && title && content) {
title.textContent = 'Projeto Publicado';
content.innerHTML = `
<div class="publish-result">
<div class="publish-result-item"><strong>Repositório:</strong> <a href="${Utils.escapeHtml(result.repoUrl)}" target="_blank">${Utils.escapeHtml(result.repoUrl)}</a></div>
<div class="publish-result-item"><strong>Site:</strong> <a href="${Utils.escapeHtml(result.siteUrl)}" target="_blank">${Utils.escapeHtml(result.siteUrl)}</a></div>
<div class="publish-result-item"><strong>Status:</strong> <span class="badge badge-active">${Utils.escapeHtml(result.status)}</span></div>
${result.message ? `<div class="publish-result-item"><em>${Utils.escapeHtml(result.message)}</em></div>` : ''}
</div>`;
Modal.open('execution-detail-modal-overlay');
}
await FilesUI.navigate(FilesUI.currentPath);
} catch (err) {
Toast.error(`Erro ao publicar: ${err.message}`);
}
},
async deleteEntry(path, entryType) {
const label = entryType === 'directory' ? 'pasta' : 'arquivo';
const name = path.split('/').pop();
const confirmed = await Modal.confirm(
`Excluir ${label}`,
`Tem certeza que deseja excluir "${name}"? Esta ação não pode ser desfeita.`
);
if (!confirmed) return;
try {
await API.files.delete(path);
Toast.success(`${label.charAt(0).toUpperCase() + label.slice(1)} excluído`);
await FilesUI.navigate(FilesUI.currentPath);
} catch (err) {
Toast.error(`Erro ao excluir: ${err.message}`);
}
},
};
window.FilesUI = FilesUI;

View File

@@ -0,0 +1,761 @@
const FlowEditor = {
_overlay: null,
_canvas: null,
_ctx: null,
_nodesContainer: null,
_pipelineId: null,
_pipeline: null,
_agents: [],
_nodes: [],
_dragState: null,
_panOffset: { x: 0, y: 0 },
_panStart: null,
_scale: 1,
_selectedNode: null,
_editingNode: null,
_resizeObserver: null,
_animFrame: null,
_dirty: false,
NODE_WIDTH: 240,
NODE_HEIGHT: 72,
NODE_GAP_Y: 100,
START_X: 0,
START_Y: 60,
async open(pipelineId) {
try {
const [pipeline, agents] = await Promise.all([
API.pipelines.get(pipelineId),
API.agents.list(),
]);
FlowEditor._pipelineId = pipelineId;
FlowEditor._pipeline = pipeline;
FlowEditor._agents = Array.isArray(agents) ? agents : [];
FlowEditor._selectedNode = null;
FlowEditor._editingNode = null;
FlowEditor._panOffset = { x: 0, y: 0 };
FlowEditor._scale = 1;
FlowEditor._dirty = false;
FlowEditor._buildNodes();
FlowEditor._show();
FlowEditor._centerView();
FlowEditor._render();
} catch (err) {
Toast.error('Erro ao abrir editor de fluxo: ' + err.message);
}
},
_buildNodes() {
const steps = Array.isArray(FlowEditor._pipeline.steps) ? FlowEditor._pipeline.steps : [];
FlowEditor._nodes = steps.map((step, i) => {
const agent = FlowEditor._agents.find((a) => a.id === step.agentId);
return {
id: step.id || 'step-' + i,
index: i,
x: 0,
y: i * (FlowEditor.NODE_HEIGHT + FlowEditor.NODE_GAP_Y),
agentId: step.agentId || '',
agentName: agent ? (agent.agent_name || agent.name) : (step.agentName || 'Agente'),
inputTemplate: step.inputTemplate || '',
requiresApproval: !!step.requiresApproval,
description: step.description || '',
};
});
},
_show() {
let overlay = document.getElementById('flow-editor-overlay');
if (!overlay) {
FlowEditor._createDOM();
overlay = document.getElementById('flow-editor-overlay');
}
FlowEditor._overlay = overlay;
FlowEditor._canvas = document.getElementById('flow-editor-canvas');
FlowEditor._ctx = FlowEditor._canvas.getContext('2d');
FlowEditor._nodesContainer = document.getElementById('flow-editor-nodes');
const titleEl = document.getElementById('flow-editor-title');
if (titleEl) titleEl.textContent = FlowEditor._pipeline.name || 'Pipeline';
const saveBtn = document.getElementById('flow-editor-save-btn');
if (saveBtn) saveBtn.classList.toggle('flow-btn--disabled', true);
overlay.hidden = false;
requestAnimationFrame(() => overlay.classList.add('active'));
FlowEditor._setupEvents();
FlowEditor._resizeCanvas();
if (!FlowEditor._resizeObserver) {
FlowEditor._resizeObserver = new ResizeObserver(() => {
FlowEditor._resizeCanvas();
FlowEditor._render();
});
}
FlowEditor._resizeObserver.observe(FlowEditor._canvas.parentElement);
},
_createDOM() {
const div = document.createElement('div');
div.innerHTML = `
<div class="flow-editor-overlay" id="flow-editor-overlay" hidden>
<div class="flow-editor">
<div class="flow-editor-header">
<div class="flow-editor-header-left">
<button class="flow-btn flow-btn--ghost" id="flow-editor-close-btn" title="Voltar">
<i data-lucide="arrow-left" style="width:18px;height:18px"></i>
</button>
<div class="flow-editor-title-group">
<h2 class="flow-editor-title" id="flow-editor-title">Pipeline</h2>
<span class="flow-editor-subtitle">Editor de Fluxo</span>
</div>
</div>
<div class="flow-editor-header-actions">
<div class="flow-editor-zoom">
<button class="flow-btn flow-btn--ghost flow-btn--sm" id="flow-zoom-out" title="Diminuir zoom">
<i data-lucide="minus" style="width:14px;height:14px"></i>
</button>
<span class="flow-zoom-label" id="flow-zoom-label">100%</span>
<button class="flow-btn flow-btn--ghost flow-btn--sm" id="flow-zoom-in" title="Aumentar zoom">
<i data-lucide="plus" style="width:14px;height:14px"></i>
</button>
<button class="flow-btn flow-btn--ghost flow-btn--sm" id="flow-zoom-fit" title="Centralizar">
<i data-lucide="maximize-2" style="width:14px;height:14px"></i>
</button>
</div>
<button class="flow-btn flow-btn--ghost flow-btn--sm" id="flow-add-node-btn" title="Adicionar passo">
<i data-lucide="plus-circle" style="width:16px;height:16px"></i>
<span>Passo</span>
</button>
<button class="flow-btn flow-btn--primary flow-btn--disabled" id="flow-editor-save-btn">
<i data-lucide="save" style="width:14px;height:14px"></i>
<span>Salvar</span>
</button>
</div>
</div>
<div class="flow-editor-body">
<div class="flow-editor-canvas-wrap" id="flow-editor-canvas-wrap">
<canvas id="flow-editor-canvas"></canvas>
<div class="flow-editor-nodes" id="flow-editor-nodes"></div>
</div>
<div class="flow-editor-panel" id="flow-editor-panel" hidden>
<div class="flow-panel-header">
<h3 class="flow-panel-title" id="flow-panel-title">Configuração</h3>
<button class="flow-btn flow-btn--ghost flow-btn--sm" id="flow-panel-close" title="Fechar painel">
<i data-lucide="x" style="width:14px;height:14px"></i>
</button>
</div>
<div class="flow-panel-body" id="flow-panel-body"></div>
</div>
</div>
</div>
</div>
`;
document.body.appendChild(div.firstElementChild);
},
_setupEvents() {
const wrap = document.getElementById('flow-editor-canvas-wrap');
if (!wrap || wrap._flowBound) return;
wrap._flowBound = true;
wrap.addEventListener('pointerdown', FlowEditor._onPointerDown);
wrap.addEventListener('pointermove', FlowEditor._onPointerMove);
wrap.addEventListener('pointerup', FlowEditor._onPointerUp);
wrap.addEventListener('wheel', FlowEditor._onWheel, { passive: false });
document.getElementById('flow-editor-close-btn')?.addEventListener('click', FlowEditor._close);
document.getElementById('flow-editor-save-btn')?.addEventListener('click', FlowEditor._save);
document.getElementById('flow-add-node-btn')?.addEventListener('click', FlowEditor._addNode);
document.getElementById('flow-zoom-in')?.addEventListener('click', () => FlowEditor._zoom(0.1));
document.getElementById('flow-zoom-out')?.addEventListener('click', () => FlowEditor._zoom(-0.1));
document.getElementById('flow-zoom-fit')?.addEventListener('click', () => FlowEditor._centerView());
document.getElementById('flow-panel-close')?.addEventListener('click', FlowEditor._closePanel);
document.addEventListener('keydown', FlowEditor._onKeyDown);
},
_resizeCanvas() {
const wrap = document.getElementById('flow-editor-canvas-wrap');
const canvas = FlowEditor._canvas;
if (!wrap || !canvas) return;
const dpr = window.devicePixelRatio || 1;
const rect = wrap.getBoundingClientRect();
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
canvas.style.width = rect.width + 'px';
canvas.style.height = rect.height + 'px';
FlowEditor._ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
},
_render() {
if (FlowEditor._animFrame) cancelAnimationFrame(FlowEditor._animFrame);
FlowEditor._animFrame = requestAnimationFrame(FlowEditor._draw);
},
_draw() {
const ctx = FlowEditor._ctx;
const canvas = FlowEditor._canvas;
if (!ctx || !canvas) return;
const dpr = window.devicePixelRatio || 1;
const w = canvas.width / dpr;
const h = canvas.height / dpr;
ctx.clearRect(0, 0, w, h);
ctx.save();
ctx.translate(FlowEditor._panOffset.x, FlowEditor._panOffset.y);
ctx.scale(FlowEditor._scale, FlowEditor._scale);
FlowEditor._drawGrid(ctx, w, h);
FlowEditor._drawConnections(ctx);
ctx.restore();
FlowEditor._renderNodes();
},
_drawGrid(ctx, w, h) {
const scale = FlowEditor._scale;
const ox = FlowEditor._panOffset.x;
const oy = FlowEditor._panOffset.y;
const gridSize = 24;
ctx.strokeStyle = 'rgba(255,255,255,0.03)';
ctx.lineWidth = 1 / scale;
const startX = Math.floor(-ox / scale / gridSize) * gridSize;
const startY = Math.floor(-oy / scale / gridSize) * gridSize;
const endX = startX + w / scale + gridSize * 2;
const endY = startY + h / scale + gridSize * 2;
ctx.beginPath();
for (let x = startX; x < endX; x += gridSize) {
ctx.moveTo(x, startY);
ctx.lineTo(x, endY);
}
for (let y = startY; y < endY; y += gridSize) {
ctx.moveTo(startX, y);
ctx.lineTo(endX, y);
}
ctx.stroke();
},
_drawConnections(ctx) {
const nodes = FlowEditor._nodes;
const nw = FlowEditor.NODE_WIDTH;
const nh = FlowEditor.NODE_HEIGHT;
for (let i = 0; i < nodes.length - 1; i++) {
const a = nodes[i];
const b = nodes[i + 1];
const ax = a.x + nw / 2;
const ay = a.y + nh;
const bx = b.x + nw / 2;
const by = b.y;
const midY = (ay + by) / 2;
const grad = ctx.createLinearGradient(ax, ay, bx, by);
grad.addColorStop(0, 'rgba(99,102,241,0.6)');
grad.addColorStop(1, 'rgba(139,92,246,0.6)');
ctx.strokeStyle = grad;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(ax, ay);
ctx.bezierCurveTo(ax, midY, bx, midY, bx, by);
ctx.stroke();
const arrowSize = 6;
const angle = Math.atan2(by - midY, bx - bx) || Math.PI / 2;
ctx.fillStyle = 'rgba(139,92,246,0.8)';
ctx.beginPath();
ctx.moveTo(bx, by);
ctx.lineTo(bx - arrowSize * Math.cos(angle - 0.4), by - arrowSize * Math.sin(angle - 0.4));
ctx.lineTo(bx - arrowSize * Math.cos(angle + 0.4), by - arrowSize * Math.sin(angle + 0.4));
ctx.closePath();
ctx.fill();
if (b.requiresApproval) {
const iconX = (ax + bx) / 2;
const iconY = midY;
ctx.fillStyle = '#0a0a0f';
ctx.beginPath();
ctx.arc(iconX, iconY, 10, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = 'rgba(245,158,11,0.8)';
ctx.lineWidth = 1.5;
ctx.stroke();
ctx.fillStyle = '#f59e0b';
ctx.font = 'bold 10px Inter, sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('!', iconX, iconY);
}
}
},
_renderNodes() {
const container = FlowEditor._nodesContainer;
if (!container) return;
const ox = FlowEditor._panOffset.x;
const oy = FlowEditor._panOffset.y;
const scale = FlowEditor._scale;
let existingEls = container.querySelectorAll('.flow-node');
const existingMap = {};
existingEls.forEach((el) => { existingMap[el.dataset.nodeId] = el; });
FlowEditor._nodes.forEach((node, i) => {
const screenX = node.x * scale + ox;
const screenY = node.y * scale + oy;
const isSelected = FlowEditor._selectedNode === i;
let el = existingMap[node.id];
if (!el) {
el = document.createElement('div');
el.className = 'flow-node';
el.dataset.nodeId = node.id;
el.dataset.nodeIndex = i;
container.appendChild(el);
}
el.dataset.nodeIndex = i;
el.style.transform = `translate(${screenX}px, ${screenY}px) scale(${scale})`;
el.style.width = FlowEditor.NODE_WIDTH + 'px';
el.style.height = FlowEditor.NODE_HEIGHT + 'px';
el.classList.toggle('flow-node--selected', isSelected);
const stepNum = i + 1;
const name = Utils.escapeHtml(node.agentName || 'Selecionar agente...');
const approvalBadge = node.requiresApproval && i > 0
? '<span class="flow-node-approval">Aprovação</span>'
: '';
el.innerHTML = `
<div class="flow-node-header">
<span class="flow-node-number">${stepNum}</span>
<span class="flow-node-name" title="${name}">${name}</span>
${approvalBadge}
</div>
<div class="flow-node-sub">
${node.inputTemplate ? Utils.escapeHtml(Utils.truncate(node.inputTemplate, 40)) : '<span class="flow-node-placeholder">Sem template de input</span>'}
</div>
`;
delete existingMap[node.id];
});
Object.values(existingMap).forEach((el) => el.remove());
},
_centerView() {
const canvas = FlowEditor._canvas;
if (!canvas || FlowEditor._nodes.length === 0) return;
const dpr = window.devicePixelRatio || 1;
const w = canvas.width / dpr;
const h = canvas.height / dpr;
const nw = FlowEditor.NODE_WIDTH;
const nh = FlowEditor.NODE_HEIGHT;
const nodes = FlowEditor._nodes;
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
nodes.forEach((n) => {
minX = Math.min(minX, n.x);
minY = Math.min(minY, n.y);
maxX = Math.max(maxX, n.x + nw);
maxY = Math.max(maxY, n.y + nh);
});
const contentW = maxX - minX;
const contentH = maxY - minY;
const padding = 80;
const scaleX = (w - padding * 2) / contentW;
const scaleY = (h - padding * 2) / contentH;
const scale = Math.min(Math.max(Math.min(scaleX, scaleY), 0.3), 1.5);
FlowEditor._scale = scale;
FlowEditor._panOffset = {
x: (w - contentW * scale) / 2 - minX * scale,
y: (h - contentH * scale) / 2 - minY * scale,
};
FlowEditor._updateZoomLabel();
FlowEditor._render();
},
_zoom(delta) {
const oldScale = FlowEditor._scale;
FlowEditor._scale = Math.min(Math.max(oldScale + delta, 0.2), 2.5);
FlowEditor._updateZoomLabel();
FlowEditor._render();
},
_updateZoomLabel() {
const el = document.getElementById('flow-zoom-label');
if (el) el.textContent = Math.round(FlowEditor._scale * 100) + '%';
},
_onPointerDown(e) {
const nodeEl = e.target.closest('.flow-node');
if (nodeEl) {
const idx = parseInt(nodeEl.dataset.nodeIndex, 10);
FlowEditor._selectedNode = idx;
if (e.detail === 2) {
FlowEditor._openNodePanel(idx);
FlowEditor._render();
return;
}
const node = FlowEditor._nodes[idx];
FlowEditor._dragState = {
type: 'node',
index: idx,
startX: e.clientX,
startY: e.clientY,
origX: node.x,
origY: node.y,
moved: false,
};
nodeEl.setPointerCapture(e.pointerId);
FlowEditor._render();
return;
}
if (e.target.closest('.flow-editor-panel') || e.target.closest('.flow-editor-header')) return;
FlowEditor._selectedNode = null;
FlowEditor._panStart = {
x: e.clientX - FlowEditor._panOffset.x,
y: e.clientY - FlowEditor._panOffset.y,
};
FlowEditor._render();
},
_onPointerMove(e) {
if (FlowEditor._dragState) {
const ds = FlowEditor._dragState;
const dx = (e.clientX - ds.startX) / FlowEditor._scale;
const dy = (e.clientY - ds.startY) / FlowEditor._scale;
if (Math.abs(dx) > 2 || Math.abs(dy) > 2) ds.moved = true;
FlowEditor._nodes[ds.index].x = ds.origX + dx;
FlowEditor._nodes[ds.index].y = ds.origY + dy;
FlowEditor._render();
return;
}
if (FlowEditor._panStart) {
FlowEditor._panOffset.x = e.clientX - FlowEditor._panStart.x;
FlowEditor._panOffset.y = e.clientY - FlowEditor._panStart.y;
FlowEditor._render();
}
},
_onPointerUp(e) {
if (FlowEditor._dragState) {
const ds = FlowEditor._dragState;
if (!ds.moved) {
FlowEditor._openNodePanel(ds.index);
} else {
FlowEditor._markDirty();
}
FlowEditor._dragState = null;
FlowEditor._render();
return;
}
FlowEditor._panStart = null;
},
_onWheel(e) {
e.preventDefault();
const delta = e.deltaY > 0 ? -0.08 : 0.08;
const oldScale = FlowEditor._scale;
const newScale = Math.min(Math.max(oldScale + delta, 0.2), 2.5);
const rect = FlowEditor._canvas.getBoundingClientRect();
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
FlowEditor._panOffset.x = mx - (mx - FlowEditor._panOffset.x) * (newScale / oldScale);
FlowEditor._panOffset.y = my - (my - FlowEditor._panOffset.y) * (newScale / oldScale);
FlowEditor._scale = newScale;
FlowEditor._updateZoomLabel();
FlowEditor._render();
},
_onKeyDown(e) {
if (!FlowEditor._overlay || FlowEditor._overlay.hidden) return;
if (e.key === 'Escape') {
if (FlowEditor._editingNode !== null) {
FlowEditor._closePanel();
} else {
FlowEditor._close();
}
e.stopPropagation();
return;
}
if (e.key === 'Delete' && FlowEditor._selectedNode !== null && FlowEditor._editingNode === null) {
FlowEditor._removeNode(FlowEditor._selectedNode);
}
},
_openNodePanel(index) {
const node = FlowEditor._nodes[index];
if (!node) return;
FlowEditor._editingNode = index;
FlowEditor._selectedNode = index;
const panel = document.getElementById('flow-editor-panel');
const title = document.getElementById('flow-panel-title');
const body = document.getElementById('flow-panel-body');
if (!panel || !body) return;
if (title) title.textContent = `Passo ${index + 1}`;
panel.hidden = false;
const agentOptions = FlowEditor._agents
.map((a) => {
const aName = Utils.escapeHtml(a.agent_name || a.name);
const selected = a.id === node.agentId ? 'selected' : '';
return `<option value="${a.id}" ${selected}>${aName}</option>`;
})
.join('');
const approvalChecked = node.requiresApproval ? 'checked' : '';
const showApproval = index > 0;
body.innerHTML = `
<div class="flow-panel-field">
<label class="flow-panel-label">Agente</label>
<select class="flow-panel-select" id="flow-panel-agent">
<option value="">Selecionar agente...</option>
${agentOptions}
</select>
</div>
<div class="flow-panel-field">
<label class="flow-panel-label">Template de Input</label>
<textarea class="flow-panel-textarea" id="flow-panel-template" rows="4" placeholder="{{input}} será substituído pelo output anterior">${Utils.escapeHtml(node.inputTemplate || '')}</textarea>
<span class="flow-panel-hint">Use <code>{{input}}</code> para referenciar o output do passo anterior</span>
</div>
${showApproval ? `
<div class="flow-panel-field">
<label class="flow-panel-checkbox">
<input type="checkbox" id="flow-panel-approval" ${approvalChecked} />
<span>Requer aprovação antes de executar</span>
</label>
</div>` : ''}
<div class="flow-panel-field flow-panel-actions-group">
<button class="flow-btn flow-btn--ghost flow-btn--sm flow-btn--full" id="flow-panel-move-up" ${index === 0 ? 'disabled' : ''}>
<i data-lucide="chevron-up" style="width:14px;height:14px"></i> Mover acima
</button>
<button class="flow-btn flow-btn--ghost flow-btn--sm flow-btn--full" id="flow-panel-move-down" ${index === FlowEditor._nodes.length - 1 ? 'disabled' : ''}>
<i data-lucide="chevron-down" style="width:14px;height:14px"></i> Mover abaixo
</button>
<button class="flow-btn flow-btn--danger flow-btn--sm flow-btn--full" id="flow-panel-delete">
<i data-lucide="trash-2" style="width:14px;height:14px"></i> Remover passo
</button>
</div>
`;
Utils.refreshIcons(body);
document.getElementById('flow-panel-agent')?.addEventListener('change', (ev) => {
const val = ev.target.value;
node.agentId = val;
const agent = FlowEditor._agents.find((a) => a.id === val);
node.agentName = agent ? (agent.agent_name || agent.name) : 'Selecionar agente...';
FlowEditor._markDirty();
FlowEditor._render();
});
document.getElementById('flow-panel-template')?.addEventListener('input', (ev) => {
node.inputTemplate = ev.target.value;
FlowEditor._markDirty();
FlowEditor._render();
});
document.getElementById('flow-panel-approval')?.addEventListener('change', (ev) => {
node.requiresApproval = ev.target.checked;
FlowEditor._markDirty();
FlowEditor._render();
});
document.getElementById('flow-panel-move-up')?.addEventListener('click', () => {
FlowEditor._swapNodes(index, index - 1);
});
document.getElementById('flow-panel-move-down')?.addEventListener('click', () => {
FlowEditor._swapNodes(index, index + 1);
});
document.getElementById('flow-panel-delete')?.addEventListener('click', () => {
FlowEditor._removeNode(index);
});
},
_closePanel() {
const panel = document.getElementById('flow-editor-panel');
if (panel) panel.hidden = true;
FlowEditor._editingNode = null;
},
_addNode() {
const lastNode = FlowEditor._nodes[FlowEditor._nodes.length - 1];
const newY = lastNode
? lastNode.y + FlowEditor.NODE_HEIGHT + FlowEditor.NODE_GAP_Y
: FlowEditor.START_Y;
const newX = lastNode ? lastNode.x : FlowEditor.START_X;
FlowEditor._nodes.push({
id: 'step-new-' + Date.now(),
index: FlowEditor._nodes.length,
x: newX,
y: newY,
agentId: '',
agentName: 'Selecionar agente...',
inputTemplate: '',
requiresApproval: false,
description: '',
});
FlowEditor._markDirty();
FlowEditor._render();
const newIdx = FlowEditor._nodes.length - 1;
FlowEditor._selectedNode = newIdx;
FlowEditor._openNodePanel(newIdx);
},
_removeNode(index) {
if (FlowEditor._nodes.length <= 2) {
Toast.warning('O pipeline precisa de pelo menos 2 passos');
return;
}
FlowEditor._nodes.splice(index, 1);
FlowEditor._nodes.forEach((n, i) => { n.index = i; });
if (FlowEditor._editingNode === index) FlowEditor._closePanel();
if (FlowEditor._selectedNode === index) FlowEditor._selectedNode = null;
FlowEditor._markDirty();
FlowEditor._render();
},
_swapNodes(a, b) {
if (b < 0 || b >= FlowEditor._nodes.length) return;
const tempX = FlowEditor._nodes[a].x;
const tempY = FlowEditor._nodes[a].y;
FlowEditor._nodes[a].x = FlowEditor._nodes[b].x;
FlowEditor._nodes[a].y = FlowEditor._nodes[b].y;
FlowEditor._nodes[b].x = tempX;
FlowEditor._nodes[b].y = tempY;
const temp = FlowEditor._nodes[a];
FlowEditor._nodes[a] = FlowEditor._nodes[b];
FlowEditor._nodes[b] = temp;
FlowEditor._nodes.forEach((n, i) => { n.index = i; });
FlowEditor._selectedNode = b;
FlowEditor._editingNode = b;
FlowEditor._markDirty();
FlowEditor._openNodePanel(b);
FlowEditor._render();
},
_markDirty() {
FlowEditor._dirty = true;
const btn = document.getElementById('flow-editor-save-btn');
if (btn) btn.classList.remove('flow-btn--disabled');
},
async _save() {
if (!FlowEditor._dirty) return;
const invalidNode = FlowEditor._nodes.find((n) => !n.agentId);
if (invalidNode) {
Toast.warning('Todos os passos devem ter um agente selecionado');
return;
}
if (FlowEditor._nodes.length < 2) {
Toast.warning('O pipeline precisa de pelo menos 2 passos');
return;
}
const steps = FlowEditor._nodes.map((n) => ({
agentId: n.agentId,
inputTemplate: n.inputTemplate || '',
requiresApproval: !!n.requiresApproval,
}));
try {
await API.pipelines.update(FlowEditor._pipelineId, {
name: FlowEditor._pipeline.name,
description: FlowEditor._pipeline.description,
steps,
});
FlowEditor._dirty = false;
const btn = document.getElementById('flow-editor-save-btn');
if (btn) btn.classList.add('flow-btn--disabled');
Toast.success('Pipeline atualizado com sucesso');
if (typeof PipelinesUI !== 'undefined') PipelinesUI.load();
} catch (err) {
Toast.error('Erro ao salvar: ' + err.message);
}
},
_close() {
if (FlowEditor._dirty) {
const leave = confirm('Existem alterações não salvas. Deseja sair mesmo assim?');
if (!leave) return;
}
const overlay = FlowEditor._overlay;
if (!overlay) return;
overlay.classList.remove('active');
setTimeout(() => { overlay.hidden = true; }, 200);
FlowEditor._closePanel();
if (FlowEditor._resizeObserver) {
FlowEditor._resizeObserver.disconnect();
}
document.removeEventListener('keydown', FlowEditor._onKeyDown);
FlowEditor._editingNode = null;
FlowEditor._selectedNode = null;
FlowEditor._dragState = null;
FlowEditor._panStart = null;
},
};
window.FlowEditor = FlowEditor;

View File

@@ -102,6 +102,11 @@ const HistoryUI = {
<i data-lucide="eye"></i> <i data-lucide="eye"></i>
Ver detalhes Ver detalhes
</button> </button>
${(exec.status === 'error' && exec.type === 'pipeline') ? `
<button class="btn btn-ghost btn-sm" data-action="resume-pipeline" data-id="${exec.id}" type="button" title="Retomar do passo ${(exec.failedAtStep || 0) + 1}">
<i data-lucide="play"></i>
Retomar
</button>` : ''}
${(exec.status === 'error' || exec.status === 'canceled') ? ` ${(exec.status === 'error' || exec.status === 'canceled') ? `
<button class="btn btn-ghost btn-sm" data-action="retry" data-id="${exec.id}" type="button" title="Reexecutar"> <button class="btn btn-ghost btn-sm" data-action="retry" data-id="${exec.id}" type="button" title="Reexecutar">
<i data-lucide="refresh-cw"></i> <i data-lucide="refresh-cw"></i>
@@ -421,6 +426,16 @@ const HistoryUI = {
Toast.success('Download iniciado'); Toast.success('Download iniciado');
}, },
async resumePipeline(executionId) {
try {
await API.pipelines.resume(executionId);
Toast.info('Pipeline retomado');
App.navigateTo('terminal');
} catch (err) {
Toast.error(`Erro ao retomar pipeline: ${err.message}`);
}
},
async retryExecution(id) { async retryExecution(id) {
try { try {
await API.executions.retry(id); await API.executions.retry(id);

View File

@@ -84,7 +84,6 @@ const PipelinesUI = {
const flowHtml = steps.map((step, index) => { const flowHtml = steps.map((step, index) => {
const agentName = Utils.escapeHtml(step.agentName || step.agentId || 'Agente'); const agentName = Utils.escapeHtml(step.agentName || step.agentId || 'Agente');
const isLast = index === steps.length - 1;
const approvalIcon = step.requiresApproval && index > 0 const approvalIcon = step.requiresApproval && index > 0
? '<i data-lucide="shield-check" style="width:10px;height:10px;color:var(--warning)"></i> ' ? '<i data-lucide="shield-check" style="width:10px;height:10px;color:var(--warning)"></i> '
: ''; : '';
@@ -93,7 +92,6 @@ const PipelinesUI = {
<span class="pipeline-step-number">${index + 1}</span> <span class="pipeline-step-number">${index + 1}</span>
${approvalIcon}${agentName} ${approvalIcon}${agentName}
</span> </span>
${!isLast ? '<span class="pipeline-flow-arrow">→</span>' : ''}
`; `;
}).join(''); }).join('');
@@ -109,6 +107,8 @@ const PipelinesUI = {
${pipeline.description ? `<p class="agent-description">${Utils.escapeHtml(pipeline.description)}</p>` : ''} ${pipeline.description ? `<p class="agent-description">${Utils.escapeHtml(pipeline.description)}</p>` : ''}
${pipeline.workingDirectory ? `<div class="pipeline-workdir-badge"><i data-lucide="folder" style="width:12px;height:12px"></i> <code>${Utils.escapeHtml(pipeline.workingDirectory)}</code></div>` : ''}
<div class="pipeline-flow"> <div class="pipeline-flow">
${flowHtml || '<span class="agent-description">Nenhum passo configurado</span>'} ${flowHtml || '<span class="agent-description">Nenhum passo configurado</span>'}
</div> </div>
@@ -120,6 +120,9 @@ const PipelinesUI = {
Executar Executar
</button> </button>
<div class="agent-actions-icons"> <div class="agent-actions-icons">
<button class="btn btn-ghost btn-icon btn-sm" data-action="flow-pipeline" data-id="${pipeline.id}" title="Editor de fluxo">
<i data-lucide="workflow"></i>
</button>
<button class="btn btn-ghost btn-icon btn-sm" data-action="edit-pipeline" data-id="${pipeline.id}" title="Editar pipeline"> <button class="btn btn-ghost btn-icon btn-sm" data-action="edit-pipeline" data-id="${pipeline.id}" title="Editar pipeline">
<i data-lucide="pencil"></i> <i data-lucide="pencil"></i>
</button> </button>
@@ -132,11 +135,13 @@ const PipelinesUI = {
`; `;
}, },
_basePath: '/home/projetos/',
openCreateModal() { openCreateModal() {
PipelinesUI._editingId = null; PipelinesUI._editingId = null;
PipelinesUI._steps = [ PipelinesUI._steps = [
{ agentId: '', inputTemplate: '', requiresApproval: false }, { agentId: '', inputTemplate: '', description: '', promptMode: 'simple', requiresApproval: false },
{ agentId: '', inputTemplate: '', requiresApproval: false }, { agentId: '', inputTemplate: '', description: '', promptMode: 'simple', requiresApproval: false },
]; ];
const titleEl = document.getElementById('pipeline-modal-title'); const titleEl = document.getElementById('pipeline-modal-title');
@@ -151,6 +156,9 @@ const PipelinesUI = {
const descEl = document.getElementById('pipeline-description'); const descEl = document.getElementById('pipeline-description');
if (descEl) descEl.value = ''; if (descEl) descEl.value = '';
const workdirEl = document.getElementById('pipeline-workdir');
if (workdirEl) workdirEl.value = PipelinesUI._basePath;
PipelinesUI.renderSteps(); PipelinesUI.renderSteps();
Modal.open('pipeline-modal-overlay'); Modal.open('pipeline-modal-overlay');
}, },
@@ -161,7 +169,13 @@ const PipelinesUI = {
PipelinesUI._editingId = pipelineId; PipelinesUI._editingId = pipelineId;
PipelinesUI._steps = Array.isArray(pipeline.steps) PipelinesUI._steps = Array.isArray(pipeline.steps)
? pipeline.steps.map((s) => ({ agentId: s.agentId || '', inputTemplate: s.inputTemplate || '', requiresApproval: !!s.requiresApproval })) ? pipeline.steps.map((s) => ({
agentId: s.agentId || '',
inputTemplate: s.inputTemplate || '',
description: s.description || '',
promptMode: s.description ? 'simple' : 'advanced',
requiresApproval: !!s.requiresApproval,
}))
: []; : [];
const titleEl = document.getElementById('pipeline-modal-title'); const titleEl = document.getElementById('pipeline-modal-title');
@@ -176,6 +190,9 @@ const PipelinesUI = {
const descEl = document.getElementById('pipeline-description'); const descEl = document.getElementById('pipeline-description');
if (descEl) descEl.value = pipeline.description || ''; if (descEl) descEl.value = pipeline.description || '';
const workdirEl = document.getElementById('pipeline-workdir');
if (workdirEl) workdirEl.value = pipeline.workingDirectory || PipelinesUI._basePath;
PipelinesUI.renderSteps(); PipelinesUI.renderSteps();
Modal.open('pipeline-modal-overlay'); Modal.open('pipeline-modal-overlay');
} catch (err) { } catch (err) {
@@ -212,6 +229,46 @@ const PipelinesUI = {
</label>` </label>`
: ''; : '';
const isSimple = step.promptMode !== 'advanced';
const inputContext = isFirst
? 'O input inicial do pipeline'
: 'O resultado (sumarizado) do passo anterior';
const promptHtml = isSimple
? `<textarea
class="textarea"
rows="2"
placeholder="Ex: Analise os requisitos e crie um plano técnico detalhado"
data-step-field="description"
data-step-index="${index}"
>${Utils.escapeHtml(step.description || '')}</textarea>
<div class="pipeline-step-hints">
<span class="pipeline-step-hint">
<i data-lucide="info" style="width:11px;height:11px"></i>
${inputContext} será injetado via <code>{{input}}</code> automaticamente no final.
</span>
<span class="pipeline-step-hint">
<i data-lucide="lightbulb" style="width:11px;height:11px"></i>
Dica: use <code>&lt;tags&gt;</code> XML para organizar melhor. Ex: <code>&lt;contexto&gt;</code> <code>&lt;regras&gt;</code> <code>&lt;formato_saida&gt;</code>
</span>
</div>`
: `<textarea
class="textarea"
rows="3"
placeholder="Use {{input}} para posicionar o output do passo anterior. Estruture com <tags> XML."
data-step-field="inputTemplate"
data-step-index="${index}"
>${Utils.escapeHtml(step.inputTemplate || '')}</textarea>
<div class="pipeline-step-hints">
<span class="pipeline-step-hint">
<i data-lucide="lightbulb" style="width:11px;height:11px"></i>
Dica: use <code>&lt;tags&gt;</code> XML para organizar. Ex: <code>&lt;contexto&gt;{{input}}&lt;/contexto&gt;</code> <code>&lt;regras&gt;</code> <code>&lt;formato_saida&gt;</code>
</span>
</div>`;
const modeIcon = isSimple ? 'code' : 'text';
const modeLabel = isSimple ? 'Avançado' : 'Simples';
return ` return `
<div class="pipeline-step-row" data-step-index="${index}"> <div class="pipeline-step-row" data-step-index="${index}">
<span class="pipeline-step-number-lg">${index + 1}</span> <span class="pipeline-step-number-lg">${index + 1}</span>
@@ -220,14 +277,14 @@ const PipelinesUI = {
<option value="">Selecionar agente...</option> <option value="">Selecionar agente...</option>
${agentOptions} ${agentOptions}
</select> </select>
<textarea ${promptHtml}
class="textarea" <div class="pipeline-step-footer">
rows="2" ${approvalHtml}
placeholder="{{input}} será substituído pelo output anterior" <button type="button" class="pipeline-mode-toggle" data-step-action="toggle-mode" data-step-index="${index}" title="Alternar entre modo simples e avançado">
data-step-field="inputTemplate" <i data-lucide="${modeIcon}" style="width:12px;height:12px"></i>
data-step-index="${index}" ${modeLabel}
>${Utils.escapeHtml(step.inputTemplate || '')}</textarea> </button>
${approvalHtml} </div>
</div> </div>
<div class="pipeline-step-actions"> <div class="pipeline-step-actions">
<button class="btn btn-ghost btn-icon btn-sm" type="button" data-step-action="move-up" data-step-index="${index}" title="Mover para cima" ${isFirst ? 'disabled' : ''}> <button class="btn btn-ghost btn-icon btn-sm" type="button" data-step-action="move-up" data-step-index="${index}" title="Mover para cima" ${isFirst ? 'disabled' : ''}>
@@ -270,9 +327,41 @@ const PipelinesUI = {
}); });
}, },
_generateTemplate(description, stepIndex) {
if (!description) return '';
if (stepIndex === 0) {
return `${description}\n\n{{input}}`;
}
return `${description}\n\nResultado do passo anterior:\n{{input}}`;
},
toggleMode(index) {
PipelinesUI._syncStepsFromDOM();
const step = PipelinesUI._steps[index];
if (!step) return;
if (step.promptMode === 'advanced') {
step.promptMode = 'simple';
if (step.inputTemplate && !step.description) {
step.description = step.inputTemplate
.replace(/\{\{input\}\}/g, '')
.replace(/Resultado do passo anterior:\s*/g, '')
.replace(/Input:\s*/g, '')
.trim();
}
} else {
step.promptMode = 'advanced';
if (step.description && !step.inputTemplate) {
step.inputTemplate = PipelinesUI._generateTemplate(step.description, index);
}
}
PipelinesUI.renderSteps();
},
addStep() { addStep() {
PipelinesUI._syncStepsFromDOM(); PipelinesUI._syncStepsFromDOM();
PipelinesUI._steps.push({ agentId: '', inputTemplate: '', requiresApproval: false }); PipelinesUI._steps.push({ agentId: '', inputTemplate: '', description: '', promptMode: 'simple', requiresApproval: false });
PipelinesUI.renderSteps(); PipelinesUI.renderSteps();
}, },
@@ -312,14 +401,29 @@ const PipelinesUI = {
return; return;
} }
const workingDirectory = document.getElementById('pipeline-workdir')?.value.trim() || '';
if (workingDirectory && !workingDirectory.startsWith('/')) {
Toast.warning('O diretório do projeto deve ser um caminho absoluto (começar com /)');
return;
}
const data = { const data = {
name, name,
description: document.getElementById('pipeline-description')?.value.trim() || '', description: document.getElementById('pipeline-description')?.value.trim() || '',
steps: PipelinesUI._steps.map((s) => ({ workingDirectory,
agentId: s.agentId, steps: PipelinesUI._steps.map((s, index) => {
inputTemplate: s.inputTemplate || '', const isSimple = s.promptMode !== 'advanced';
requiresApproval: !!s.requiresApproval, const inputTemplate = isSimple
})), ? PipelinesUI._generateTemplate(s.description, index)
: (s.inputTemplate || '');
return {
agentId: s.agentId,
inputTemplate,
description: isSimple ? (s.description || '') : '',
requiresApproval: !!s.requiresApproval,
};
}),
}; };
try { try {
@@ -368,10 +472,15 @@ const PipelinesUI = {
if (inputEl) inputEl.value = ''; if (inputEl) inputEl.value = '';
const workdirEl = document.getElementById('pipeline-execute-workdir'); const workdirEl = document.getElementById('pipeline-execute-workdir');
if (workdirEl) workdirEl.value = ''; if (workdirEl) workdirEl.value = (pipeline && pipeline.workingDirectory) || PipelinesUI._basePath;
if (App._pipelineDropzone) App._pipelineDropzone.reset(); if (App._pipelineDropzone) App._pipelineDropzone.reset();
const repoSelect = document.getElementById('pipeline-execute-repo');
if (repoSelect) { repoSelect.value = ''; repoSelect.dispatchEvent(new Event('change')); }
App._reposCache = null;
App._loadRepos('pipeline-execute-repo');
Modal.open('pipeline-execute-modal-overlay'); Modal.open('pipeline-execute-modal-overlay');
}, },
@@ -385,6 +494,11 @@ const PipelinesUI = {
return; return;
} }
if (workingDirectory && !workingDirectory.startsWith('/')) {
Toast.warning('O diretório de trabalho deve ser um caminho absoluto (começar com /)');
return;
}
try { try {
let contextFiles = null; let contextFiles = null;
const dropzone = App._pipelineDropzone; const dropzone = App._pipelineDropzone;
@@ -394,7 +508,9 @@ const PipelinesUI = {
contextFiles = uploadResult.files; contextFiles = uploadResult.files;
} }
await API.pipelines.execute(pipelineId, input, workingDirectory, contextFiles); const repoName = document.getElementById('pipeline-execute-repo')?.value || '';
const repoBranch = document.getElementById('pipeline-execute-repo-branch')?.value || '';
await API.pipelines.execute(pipelineId, input, workingDirectory, contextFiles, repoName, repoBranch);
if (dropzone) dropzone.reset(); if (dropzone) dropzone.reset();
Modal.close('pipeline-execute-modal-overlay'); Modal.close('pipeline-execute-modal-overlay');
App.navigateTo('terminal'); App.navigateTo('terminal');

View File

@@ -68,7 +68,7 @@ const TasksUI = {
<h4 class="task-card-name">${Utils.escapeHtml(task.name)}</h4> <h4 class="task-card-name">${Utils.escapeHtml(task.name)}</h4>
<span class="badge ${categoryClass}">${Utils.escapeHtml(categoryLabel)}</span> <span class="badge ${categoryClass}">${Utils.escapeHtml(categoryLabel)}</span>
</div> </div>
${task.description ? `<p class="task-card-description">${Utils.escapeHtml(task.description)}</p>` : ''} ${task.description ? `<p class="task-card-description" title="${Utils.escapeHtml(task.description)}">${Utils.escapeHtml(task.description.length > 240 ? task.description.slice(0, 240) + '…' : task.description)}</p>` : ''}
<div class="task-card-footer"> <div class="task-card-footer">
<span class="task-card-date"> <span class="task-card-date">
<i data-lucide="calendar"></i> <i data-lucide="calendar"></i>

View File

@@ -73,6 +73,14 @@ const Utils = {
render(); render();
} }
const browseBtn = zone.querySelector('.dropzone-browse');
if (browseBtn) {
browseBtn.addEventListener('click', (e) => {
e.stopPropagation();
input.click();
});
}
zone.addEventListener('click', (e) => { zone.addEventListener('click', (e) => {
if (e.target.closest('.dropzone-file-remove')) { if (e.target.closest('.dropzone-file-remove')) {
const idx = parseInt(e.target.closest('.dropzone-file-remove').dataset.index); const idx = parseInt(e.target.closest('.dropzone-file-remove').dataset.index);
@@ -80,6 +88,7 @@ const Utils = {
render(); render();
return; return;
} }
if (e.target.closest('.dropzone-browse')) return;
if (!e.target.closest('.dropzone-file')) input.click(); if (!e.target.closest('.dropzone-file')) input.click();
}); });

79
scripts/deploy.sh Executable file
View File

@@ -0,0 +1,79 @@
#!/bin/bash
set -e
VPS_HOST="fred@192.168.1.151"
VPS_PORT=2222
VPS_APP_DIR="/home/fred/vps/apps/agents-orchestrator"
VPS_COMPOSE_DIR="/home/fred/vps"
SSH="ssh -p $VPS_PORT $VPS_HOST"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
info() { echo -e "${GREEN}[deploy]${NC} $1"; }
warn() { echo -e "${YELLOW}[deploy]${NC} $1"; }
error() { echo -e "${RED}[deploy]${NC} $1"; }
SKIP_PUSH=false
for arg in "$@"; do
case "$arg" in
--skip-push) SKIP_PUSH=true ;;
esac
done
if [ "$SKIP_PUSH" = false ]; then
info "Fazendo push para origin..."
git push origin main
info "Fazendo push para nitro..."
git push nitro main 2>/dev/null || warn "Push para nitro falhou (não crítico)"
fi
info "Verificando dados no VPS antes do deploy..."
DATA_FILES=$($SSH "ls -1 $VPS_APP_DIR/data/*.json 2>/dev/null | wc -l")
info "Arquivos de dados encontrados: $DATA_FILES"
if [ "$DATA_FILES" -gt 0 ]; then
info "Criando backup dos dados..."
$SSH "cp -r $VPS_APP_DIR/data $VPS_APP_DIR/data-backup-\$(date +%Y%m%d-%H%M%S)"
fi
info "Sincronizando código com o VPS..."
rsync -avz --delete \
--exclude='node_modules' \
--exclude='data' \
--exclude='data-backup-*' \
--exclude='.git' \
--exclude='.env' \
--exclude='*.log' \
-e "ssh -p $VPS_PORT" \
./ "$VPS_HOST:$VPS_APP_DIR/"
info "Corrigindo permissões do diretório data..."
$SSH "sudo chown -R 1000:1000 $VPS_APP_DIR/data"
info "Rebuilding container..."
$SSH "cd $VPS_COMPOSE_DIR && docker compose up -d --build agents-orchestrator 2>&1 | tail -5"
info "Verificando container..."
sleep 2
STATUS=$($SSH "docker ps --filter name=agents-orchestrator --format '{{.Status}}'")
if echo "$STATUS" | grep -q "Up"; then
info "Container rodando: $STATUS"
else
error "Container não está rodando! Status: $STATUS"
exit 1
fi
DATA_AFTER=$($SSH "ls -1 $VPS_APP_DIR/data/*.json 2>/dev/null | wc -l")
info "Arquivos de dados após deploy: $DATA_AFTER"
if [ "$DATA_AFTER" -lt "$DATA_FILES" ]; then
error "ALERTA: Menos arquivos de dados após deploy! ($DATA_FILES -> $DATA_AFTER)"
error "Backup disponível em data-backup-*"
exit 1
fi
$SSH "ls -dt $VPS_APP_DIR/data-backup-* 2>/dev/null | tail -n +4 | xargs rm -rf 2>/dev/null" || true
info "Deploy concluído com sucesso!"

View File

@@ -12,6 +12,7 @@ import apiRouter, { setWsBroadcast, setWsBroadcastTo, hookRouter } from './src/r
import * as manager from './src/agents/manager.js'; import * as manager from './src/agents/manager.js';
import { setGlobalBroadcast } from './src/agents/manager.js'; import { setGlobalBroadcast } from './src/agents/manager.js';
import { cancelAllExecutions } from './src/agents/executor.js'; import { cancelAllExecutions } from './src/agents/executor.js';
import { stopAll as stopAllSchedules } from './src/agents/scheduler.js';
import { flushAllStores } from './src/store/db.js'; import { flushAllStores } from './src/store/db.js';
const __dirname = dirname(fileURLToPath(import.meta.url)); const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -63,6 +64,7 @@ function verifyWebhookSignature(req, res, next) {
} }
const app = express(); const app = express();
app.set('trust proxy', 1);
const httpServer = createServer(app); const httpServer = createServer(app);
const wss = new WebSocketServer({ server: httpServer }); const wss = new WebSocketServer({ server: httpServer });
@@ -110,7 +112,14 @@ app.use(express.json({
verify: (req, res, buf) => { req.rawBody = buf || Buffer.alloc(0); }, verify: (req, res, buf) => { req.rawBody = buf || Buffer.alloc(0); },
})); }));
app.use('/hook', hookLimiter, verifyWebhookSignature, hookRouter); app.use('/hook', hookLimiter, verifyWebhookSignature, hookRouter);
app.use(express.static(join(__dirname, 'public'), { maxAge: '1h', etag: true })); app.use(express.static(join(__dirname, 'public'), {
etag: true,
setHeaders(res, filePath) {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
},
}));
app.use('/api', apiRouter); app.use('/api', apiRouter);
const connectedClients = new Map(); const connectedClients = new Map();
@@ -165,6 +174,9 @@ setGlobalBroadcast(broadcast);
function gracefulShutdown(signal) { function gracefulShutdown(signal) {
console.log(`\nSinal ${signal} recebido. Encerrando servidor...`); console.log(`\nSinal ${signal} recebido. Encerrando servidor...`);
stopAllSchedules();
console.log('Agendamentos parados.');
cancelAllExecutions(); cancelAllExecutions();
console.log('Execuções ativas canceladas.'); console.log('Execuções ativas canceladas.');
@@ -173,15 +185,23 @@ function gracefulShutdown(signal) {
clearInterval(wsHeartbeat); clearInterval(wsHeartbeat);
httpServer.close(() => { for (const client of wss.clients) {
console.log('Servidor HTTP encerrado.'); client.close(1001, 'Servidor encerrando');
process.exit(0); }
connectedClients.clear();
wss.close(() => {
console.log('WebSocket server encerrado.');
httpServer.close(() => {
console.log('Servidor HTTP encerrado.');
process.exit(0);
});
}); });
setTimeout(() => { setTimeout(() => {
console.error('Forçando encerramento após timeout.'); console.error('Forçando encerramento após timeout.');
process.exit(1); process.exit(1);
}, 10000); }, 10000).unref();
} }
process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));

View File

@@ -1,9 +1,12 @@
import { spawn } from 'child_process'; import { spawn } from 'child_process';
import { existsSync } from 'fs'; import { existsSync, mkdirSync } from 'fs';
import path from 'path'; import path from 'path';
import { fileURLToPath } from 'url';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import { settingsStore } from '../store/db.js'; import { settingsStore } from '../store/db.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const AGENT_SETTINGS = path.resolve(__dirname, '..', '..', 'data', 'agent-settings.json');
const CLAUDE_BIN = resolveBin(); const CLAUDE_BIN = resolveBin();
const activeExecutions = new Map(); const activeExecutions = new Map();
const MAX_OUTPUT_SIZE = 512 * 1024; const MAX_OUTPUT_SIZE = 512 * 1024;
@@ -48,18 +51,20 @@ function cleanEnv(agentSecrets) {
const env = { ...process.env }; const env = { ...process.env };
delete env.CLAUDECODE; delete env.CLAUDECODE;
delete env.ANTHROPIC_API_KEY; delete env.ANTHROPIC_API_KEY;
if (!env.CLAUDE_CODE_MAX_OUTPUT_TOKENS) { env.CLAUDE_CODE_MAX_OUTPUT_TOKENS = '128000';
env.CLAUDE_CODE_MAX_OUTPUT_TOKENS = '128000';
}
if (agentSecrets && typeof agentSecrets === 'object') { if (agentSecrets && typeof agentSecrets === 'object') {
Object.assign(env, agentSecrets); Object.assign(env, agentSecrets);
} }
return env; return env;
} }
function buildArgs(agentConfig, prompt) { function buildArgs(agentConfig) {
const model = agentConfig.model || 'claude-sonnet-4-6'; const model = agentConfig.model || 'claude-sonnet-4-6';
const args = ['-p', prompt, '--output-format', 'stream-json', '--verbose', '--model', model]; const args = ['--output-format', 'stream-json', '--verbose', '--model', model];
if (existsSync(AGENT_SETTINGS)) {
args.push('--settings', AGENT_SETTINGS);
}
if (agentConfig.systemPrompt) { if (agentConfig.systemPrompt) {
args.push('--system-prompt', agentConfig.systemPrompt); args.push('--system-prompt', agentConfig.systemPrompt);
@@ -285,9 +290,13 @@ function validateWorkingDirectory(agentConfig, executionId, onError) {
} }
if (!existsSync(agentConfig.workingDirectory)) { if (!existsSync(agentConfig.workingDirectory)) {
const err = new Error(`Diretório de trabalho não encontrado: ${agentConfig.workingDirectory}`); try {
if (onError) onError(err, executionId); mkdirSync(agentConfig.workingDirectory, { recursive: true });
return false; } catch (e) {
const err = new Error(`Não foi possível criar o diretório: ${agentConfig.workingDirectory} (${e.message})`);
if (onError) onError(err, executionId);
return false;
}
} }
return true; return true;
@@ -306,11 +315,11 @@ export function execute(agentConfig, task, callbacks = {}, secrets = null) {
if (!validateWorkingDirectory(agentConfig, executionId, onError)) return null; if (!validateWorkingDirectory(agentConfig, executionId, onError)) return null;
const prompt = buildPrompt(task.description || task, task.instructions); const prompt = buildPrompt(task.description || task, task.instructions);
const args = buildArgs(agentConfig, prompt); const args = buildArgs(agentConfig);
const spawnOptions = { const spawnOptions = {
env: cleanEnv(secrets), env: cleanEnv(secrets),
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['pipe', 'pipe', 'pipe'],
}; };
if (agentConfig.workingDirectory && agentConfig.workingDirectory.trim()) { if (agentConfig.workingDirectory && agentConfig.workingDirectory.trim()) {
@@ -320,6 +329,8 @@ export function execute(agentConfig, task, callbacks = {}, secrets = null) {
console.log(`[executor] Iniciando: ${executionId} | Modelo: ${agentConfig.model || 'claude-sonnet-4-6'}`); console.log(`[executor] Iniciando: ${executionId} | Modelo: ${agentConfig.model || 'claude-sonnet-4-6'}`);
const child = spawn(CLAUDE_BIN, args, spawnOptions); const child = spawn(CLAUDE_BIN, args, spawnOptions);
child.stdin.write(prompt);
child.stdin.end();
activeExecutions.set(executionId, { activeExecutions.set(executionId, {
process: child, process: child,
@@ -358,6 +369,10 @@ export function resume(agentConfig, sessionId, message, callbacks = {}) {
'--permission-mode', agentConfig.permissionMode || 'bypassPermissions', '--permission-mode', agentConfig.permissionMode || 'bypassPermissions',
]; ];
if (existsSync(AGENT_SETTINGS)) {
args.push('--settings', AGENT_SETTINGS);
}
if (agentConfig.maxTurns && agentConfig.maxTurns > 0) { if (agentConfig.maxTurns && agentConfig.maxTurns > 0) {
args.push('--max-turns', String(agentConfig.maxTurns)); args.push('--max-turns', String(agentConfig.maxTurns));
} }
@@ -412,6 +427,66 @@ export function getActiveExecutions() {
})); }));
} }
export function summarize(text, threshold = 1500) {
return new Promise((resolve) => {
if (!text || text.length <= threshold) {
resolve(text);
return;
}
const prompt = `Resuma o conteúdo abaixo de forma estruturada e concisa. Preserve TODAS as informações críticas:
- Decisões técnicas e justificativas
- Trechos de código essenciais
- Dados, números e métricas
- Problemas encontrados e soluções
- Recomendações e próximos passos
Organize o resumo usando <tags> XML (ex: <decisoes>, <codigo>, <problemas>, <recomendacoes>).
NÃO omita informações que seriam necessárias para outro profissional continuar o trabalho.
<conteudo_para_resumir>
${text}
</conteudo_para_resumir>`;
const args = [
'--output-format', 'text',
'--model', 'claude-haiku-4-5-20251001',
'--max-turns', '1',
'--permission-mode', 'bypassPermissions',
];
if (existsSync(AGENT_SETTINGS)) {
args.push('--settings', AGENT_SETTINGS);
}
const child = spawn(CLAUDE_BIN, args, {
env: cleanEnv(),
stdio: ['pipe', 'pipe', 'pipe'],
});
child.stdin.write(prompt);
child.stdin.end();
let output = '';
const timer = setTimeout(() => {
child.kill('SIGTERM');
}, 120000);
child.stdout.on('data', (chunk) => { output += chunk.toString(); });
child.on('close', () => {
clearTimeout(timer);
const result = output.trim();
console.log(`[executor] Sumarização: ${text.length}${result.length} chars`);
resolve(result || text);
});
child.on('error', () => {
clearTimeout(timer);
resolve(text);
});
});
}
export function getBinPath() { export function getBinPath() {
return CLAUDE_BIN; return CLAUDE_BIN;
} }

View File

@@ -0,0 +1,117 @@
import { spawn } from 'child_process';
import { existsSync } from 'fs';
import { join, basename } from 'path';
const PROJECTS_DIR = '/home/projetos';
const GITEA_URL = () => process.env.GITEA_URL || 'http://gitea:3000';
const GITEA_USER = () => process.env.GITEA_USER || 'fred';
const GITEA_PASS = () => process.env.GITEA_PASS || '';
const DOMAIN = () => process.env.DOMAIN || 'nitro-cloud.duckdns.org';
function exec(cmd, cwd) {
return new Promise((resolve, reject) => {
const proc = spawn('sh', ['-c', cmd], {
cwd,
env: { ...process.env, HOME: '/tmp', GIT_TERMINAL_PROMPT: '0' },
});
let stdout = '', stderr = '';
proc.stdout.on('data', d => stdout += d);
proc.stderr.on('data', d => stderr += d);
proc.on('close', code =>
code === 0 ? resolve(stdout.trim()) : reject(new Error(stderr.trim() || `exit ${code}`))
);
});
}
function authHeader() {
return 'Basic ' + Buffer.from(`${GITEA_USER()}:${GITEA_PASS()}`).toString('base64');
}
function repoCloneUrl(repoName) {
return `${GITEA_URL().replace('://', `://${GITEA_USER()}:${GITEA_PASS()}@`)}/${GITEA_USER()}/${repoName}.git`;
}
export async function listRepos() {
const url = `${GITEA_URL()}/api/v1/user/repos?limit=50&sort=updated`;
const res = await fetch(url, { headers: { Authorization: authHeader() } });
if (!res.ok) throw new Error('Erro ao listar repositórios');
const repos = await res.json();
return repos.map(r => ({
name: r.name,
fullName: r.full_name,
description: r.description || '',
defaultBranch: r.default_branch || 'main',
updatedAt: r.updated_at,
htmlUrl: r.html_url,
cloneUrl: r.clone_url,
empty: r.empty,
}));
}
export async function listBranches(repoName) {
const url = `${GITEA_URL()}/api/v1/repos/${GITEA_USER()}/${repoName}/branches?limit=50`;
const res = await fetch(url, { headers: { Authorization: authHeader() } });
if (!res.ok) return [];
const branches = await res.json();
return branches.map(b => b.name);
}
export async function cloneOrPull(repoName, branch) {
const targetDir = join(PROJECTS_DIR, repoName);
const cloneUrl = repoCloneUrl(repoName);
if (existsSync(join(targetDir, '.git'))) {
await exec(`git remote set-url origin "${cloneUrl}"`, targetDir);
await exec('git fetch origin', targetDir);
if (branch) {
try {
await exec(`git checkout ${branch}`, targetDir);
} catch {
await exec(`git checkout -b ${branch} origin/${branch}`, targetDir);
}
await exec(`git reset --hard origin/${branch}`, targetDir);
} else {
const currentBranch = await exec('git rev-parse --abbrev-ref HEAD', targetDir);
await exec(`git reset --hard origin/${currentBranch}`, targetDir);
}
return { dir: targetDir, action: 'pull' };
}
const branchArg = branch ? `-b ${branch}` : '';
await exec(`git clone ${branchArg} "${cloneUrl}" "${targetDir}"`);
return { dir: targetDir, action: 'clone' };
}
export async function commitAndPush(repoDir, agentName, taskSummary) {
try {
const status = await exec('git status --porcelain', repoDir);
if (!status) return { changed: false };
await exec('git add -A', repoDir);
const summary = taskSummary
? taskSummary.slice(0, 100).replace(/"/g, '\\"')
: 'Alterações automáticas';
const message = `${summary}\n\nExecutado por: ${agentName}`;
await exec(
`git -c user.name="Agents Orchestrator" -c user.email="agents@${DOMAIN()}" commit -m "${message}"`,
repoDir
);
await exec('git push origin HEAD', repoDir);
const commitHash = await exec('git rev-parse --short HEAD', repoDir);
const branch = await exec('git rev-parse --abbrev-ref HEAD', repoDir);
const repoName = basename(repoDir);
const commitUrl = `https://git.${DOMAIN()}/${GITEA_USER()}/${repoName}/commit/${commitHash}`;
return { changed: true, commitHash, branch, commitUrl, filesChanged: status.split('\n').length };
} catch (err) {
return { changed: false, error: err.message };
}
}
export function getProjectDir(repoName) {
return join(PROJECTS_DIR, repoName);
}

View File

@@ -4,6 +4,7 @@ import { agentsStore, schedulesStore, executionsStore, notificationsStore, secre
import * as executor from './executor.js'; import * as executor from './executor.js';
import * as scheduler from './scheduler.js'; import * as scheduler from './scheduler.js';
import { generateAgentReport } from '../reports/generator.js'; import { generateAgentReport } from '../reports/generator.js';
import * as gitIntegration from './git-integration.js';
const DEFAULT_CONFIG = { const DEFAULT_CONFIG = {
model: 'claude-sonnet-4-6', model: 'claude-sonnet-4-6',
@@ -172,9 +173,26 @@ export function executeTask(agentId, task, instructions, wsCallback, metadata =
const agentSecrets = loadAgentSecrets(agentId); const agentSecrets = loadAgentSecrets(agentId);
let effectiveInstructions = instructions || '';
const tags = agent.tags || [];
if (tags.includes('coordinator')) {
const allAgents = agentsStore.getAll().filter(a => a.id !== agentId && a.status === 'active');
const agentList = allAgents.map(a => `- **${a.agent_name}**: ${a.description || 'Sem descrição'}`).join('\n');
effectiveInstructions += `\n\n<agentes_disponiveis>\n${agentList}\n</agentes_disponiveis>`;
}
if (metadata.repoName) {
effectiveInstructions += `\n\n<git_repository>\nVocê está trabalhando no repositório "${metadata.repoName}". NÃO faça git init, git commit, git push ou qualquer operação git. O sistema fará commit e push automaticamente ao final da execução. Foque apenas no código.\n</git_repository>`;
}
const effectiveConfig = { ...agent.config };
if (metadata.workingDirectoryOverride) {
effectiveConfig.workingDirectory = metadata.workingDirectoryOverride;
}
const executionId = executor.execute( const executionId = executor.execute(
agent.config, effectiveConfig,
{ description: task, instructions }, { description: task, instructions: effectiveInstructions },
{ {
onData: (parsed, execId) => { onData: (parsed, execId) => {
if (cb) cb({ type: 'execution_output', executionId: execId, agentId, data: parsed }); if (cb) cb({ type: 'execution_output', executionId: execId, agentId, data: parsed });
@@ -233,7 +251,50 @@ export function executeTask(agentId, task, instructions, wsCallback, metadata =
if (cb) cb({ type: 'report_generated', executionId: execId, agentId, reportFile: report.filename }); if (cb) cb({ type: 'report_generated', executionId: execId, agentId, reportFile: report.filename });
} }
} catch (e) { console.error('[manager] Erro ao gerar relatório:', e.message); } } catch (e) { console.error('[manager] Erro ao gerar relatório:', e.message); }
if (metadata.repoName && result.result) {
const repoDir = gitIntegration.getProjectDir(metadata.repoName);
gitIntegration.commitAndPush(repoDir, agent.agent_name, taskText.slice(0, 100))
.then(gitResult => {
if (gitResult.changed) {
console.log(`[manager] Auto-commit: ${gitResult.commitHash} em ${metadata.repoName}`);
if (cb) cb({
type: 'execution_output', executionId: execId, agentId,
data: { type: 'success', content: `Git: commit ${gitResult.commitHash} pushed para ${metadata.repoName} (${gitResult.filesChanged} arquivos) → ${gitResult.commitUrl}` },
});
} else if (gitResult.error) {
console.error(`[manager] Erro no auto-commit:`, gitResult.error);
}
})
.catch(err => console.error(`[manager] Erro no auto-commit:`, err.message));
}
if (cb) cb({ type: 'execution_complete', executionId: execId, agentId, data: result }); if (cb) cb({ type: 'execution_complete', executionId: execId, agentId, data: result });
const isPipelineStep = !!metadata.pipelineExecutionId;
const delegateTo = agent.config?.delegateTo;
if (!isPipelineStep && delegateTo && result.result) {
const delegateAgent = agentsStore.getById(delegateTo);
if (delegateAgent && delegateAgent.status === 'active') {
console.log(`[manager] Auto-delegando de "${agent.agent_name}" para "${delegateAgent.agent_name}"`);
if (cb) cb({
type: 'execution_output',
executionId: execId,
agentId,
data: { type: 'system', content: `Delegando para ${delegateAgent.agent_name}...` },
});
setTimeout(() => {
try {
executeTask(delegateTo, result.result, null, wsCallback, {
delegatedFrom: agent.agent_name,
originalTask: taskText,
});
} catch (delegateErr) {
console.error(`[manager] Erro ao delegar para "${delegateAgent.agent_name}":`, delegateErr.message);
if (cb) cb({ type: 'execution_error', executionId: execId, agentId: delegateTo, data: { error: delegateErr.message } });
}
}, 3000);
}
}
}, },
}, },
agentSecrets agentSecrets
@@ -273,6 +334,23 @@ export function getRecentExecutions(limit = 20) {
return recentExecBuffer.slice(0, Math.min(limit, MAX_RECENT)); return recentExecBuffer.slice(0, Math.min(limit, MAX_RECENT));
} }
async function executeWithRetry(agentId, taskDescription, metadata, maxRetries = 10, baseDelay = 30000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
executeTask(agentId, taskDescription, null, null, metadata);
return;
} catch (err) {
if (err.message.includes('Limite de execuções simultâneas') && attempt < maxRetries) {
const delay = baseDelay + Math.random() * 10000;
console.log(`[manager] Agendamento aguardando slot (tentativa ${attempt}/${maxRetries}), retry em ${(delay / 1000).toFixed(0)}s`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw err;
}
}
}
export function scheduleTask(agentId, taskDescription, cronExpression, wsCallback) { export function scheduleTask(agentId, taskDescription, cronExpression, wsCallback) {
const agent = agentsStore.getById(agentId); const agent = agentsStore.getById(agentId);
if (!agent) throw new Error(`Agente ${agentId} não encontrado`); if (!agent) throw new Error(`Agente ${agentId} não encontrado`);
@@ -296,7 +374,9 @@ export function scheduleTask(agentId, taskDescription, cronExpression, wsCallbac
schedulesStore.save(items); schedulesStore.save(items);
scheduler.schedule(scheduleId, cronExpression, () => { scheduler.schedule(scheduleId, cronExpression, () => {
executeTask(agentId, taskDescription, null, null, { source: 'schedule', scheduleId }); executeWithRetry(agentId, taskDescription, { source: 'schedule', scheduleId }).catch(err => {
console.log(`[manager] Agendamento ${scheduleId} falhou após retries: ${err.message}`);
});
}, false); }, false);
return { scheduleId, agentId, agentName: agent.agent_name, taskDescription, cronExpression }; return { scheduleId, agentId, agentName: agent.agent_name, taskDescription, cronExpression };
@@ -314,7 +394,9 @@ export function updateScheduleTask(scheduleId, data, wsCallback) {
const cronExpression = data.cronExpression || stored.cronExpression; const cronExpression = data.cronExpression || stored.cronExpression;
scheduler.updateSchedule(scheduleId, cronExpression, () => { scheduler.updateSchedule(scheduleId, cronExpression, () => {
executeTask(agentId, taskDescription, null, null, { source: 'schedule', scheduleId }); executeWithRetry(agentId, taskDescription, { source: 'schedule', scheduleId }).catch(err => {
console.log(`[manager] Agendamento ${scheduleId} falhou após retries: ${err.message}`);
});
}); });
schedulesStore.update(scheduleId, { agentId, agentName: agent.agent_name, taskDescription, cronExpression }); schedulesStore.update(scheduleId, { agentId, agentName: agent.agent_name, taskDescription, cronExpression });
@@ -424,10 +506,8 @@ export function importAgent(data) {
export function restoreSchedules() { export function restoreSchedules() {
scheduler.restoreSchedules((agentId, taskDescription, scheduleId) => { scheduler.restoreSchedules((agentId, taskDescription, scheduleId) => {
try { executeWithRetry(agentId, taskDescription, { source: 'schedule', scheduleId }).catch(err => {
executeTask(agentId, taskDescription, null, null, { source: 'schedule', scheduleId });
} catch (err) {
console.log(`[manager] Erro ao executar tarefa agendada: ${err.message}`); console.log(`[manager] Erro ao executar tarefa agendada: ${err.message}`);
} });
}); });
} }

View File

@@ -1,6 +1,7 @@
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import { pipelinesStore, agentsStore, executionsStore } from '../store/db.js'; import { pipelinesStore, agentsStore, executionsStore } from '../store/db.js';
import * as executor from './executor.js'; import * as executor from './executor.js';
import * as gitIntegration from './git-integration.js';
import { mem } from '../cache/index.js'; import { mem } from '../cache/index.js';
import { generatePipelineReport } from '../reports/generator.js'; import { generatePipelineReport } from '../reports/generator.js';
@@ -86,6 +87,7 @@ function executeStepAsPromise(agentConfig, prompt, pipelineState, wsCallback, pi
costUsd: result.costUsd || 0, costUsd: result.costUsd || 0,
durationMs: result.durationMs || 0, durationMs: result.durationMs || 0,
numTurns: result.numTurns || 0, numTurns: result.numTurns || 0,
sessionId: result.sessionId || '',
}); });
}, },
} }
@@ -213,8 +215,9 @@ export async function executePipeline(pipelineId, initialInput, wsCallback, opti
if (agent.status !== 'active') throw new Error(`Agente ${agent.agent_name} está inativo`); if (agent.status !== 'active') throw new Error(`Agente ${agent.agent_name} está inativo`);
const stepConfig = { ...agent.config }; const stepConfig = { ...agent.config };
if (options.workingDirectory) { const effectiveWorkdir = options.workingDirectory || pl.workingDirectory;
stepConfig.workingDirectory = options.workingDirectory; if (effectiveWorkdir) {
stepConfig.workingDirectory = effectiveWorkdir;
} }
const prompt = applyTemplate(step.inputTemplate, currentInput); const prompt = applyTemplate(step.inputTemplate, currentInput);
@@ -237,7 +240,7 @@ export async function executePipeline(pipelineId, initialInput, wsCallback, opti
totalCost += stepResult.costUsd; totalCost += stepResult.costUsd;
currentInput = stepResult.text; currentInput = stepResult.text;
results.push({ stepId: step.id, agentName: agent.agent_name, result: stepResult.text }); results.push({ stepId: step.id, agentId: step.agentId, agentName: agent.agent_name, result: stepResult.text, sessionId: stepResult.sessionId });
const current = executionsStore.getById(historyRecord.id); const current = executionsStore.getById(historyRecord.id);
const savedSteps = current ? (current.steps || []) : []; const savedSteps = current ? (current.steps || []) : [];
@@ -266,6 +269,19 @@ export async function executePipeline(pipelineId, initialInput, wsCallback, opti
costUsd: stepResult.costUsd, costUsd: stepResult.costUsd,
}); });
} }
if (i < steps.length - 1 && !pipelineState.canceled) {
if (wsCallback) {
wsCallback({ type: 'pipeline_summarizing', pipelineId, stepIndex: i, originalLength: currentInput.length });
}
const summarized = await executor.summarize(currentInput);
if (summarized !== currentInput) {
if (wsCallback) {
wsCallback({ type: 'pipeline_summarized', pipelineId, stepIndex: i, originalLength: currentInput.length, summarizedLength: summarized.length });
}
currentInput = summarized;
}
}
} }
activePipelines.delete(executionId); activePipelines.delete(executionId);
@@ -278,6 +294,19 @@ export async function executePipeline(pipelineId, initialInput, wsCallback, opti
}); });
if (!pipelineState.canceled) { if (!pipelineState.canceled) {
if (options.repoName) {
try {
const repoDir = gitIntegration.getProjectDir(options.repoName);
const gitResult = await gitIntegration.commitAndPush(repoDir, pl.name, `Pipeline: ${pl.name}`);
if (gitResult.changed && wsCallback) {
wsCallback({
type: 'pipeline_step_output', pipelineId, stepIndex: steps.length - 1,
data: { type: 'success', content: `Git: commit ${gitResult.commitHash} pushed para ${options.repoName} (${gitResult.filesChanged} arquivos) → ${gitResult.commitUrl}` },
});
}
} catch (e) { console.error('[pipeline] Erro no auto-commit:', e.message); }
}
try { try {
const updated = executionsStore.getById(historyRecord.id); const updated = executionsStore.getById(historyRecord.id);
if (updated) { if (updated) {
@@ -285,7 +314,17 @@ export async function executePipeline(pipelineId, initialInput, wsCallback, opti
if (wsCallback) wsCallback({ type: 'report_generated', pipelineId, reportFile: report.filename }); if (wsCallback) wsCallback({ type: 'report_generated', pipelineId, reportFile: report.filename });
} }
} catch (e) { console.error('[pipeline] Erro ao gerar relatório:', e.message); } } catch (e) { console.error('[pipeline] Erro ao gerar relatório:', e.message); }
if (wsCallback) wsCallback({ type: 'pipeline_complete', pipelineId, executionId, results, totalCostUsd: totalCost }); const lastResult = results.length > 0 ? results[results.length - 1] : null;
if (wsCallback) wsCallback({
type: 'pipeline_complete',
pipelineId,
executionId,
results,
totalCostUsd: totalCost,
lastAgentId: lastResult?.agentId || '',
lastAgentName: lastResult?.agentName || '',
lastSessionId: lastResult?.sessionId || '',
});
} }
return { executionId, results }; return { executionId, results };
@@ -294,6 +333,8 @@ export async function executePipeline(pipelineId, initialInput, wsCallback, opti
executionsStore.update(historyRecord.id, { executionsStore.update(historyRecord.id, {
status: 'error', status: 'error',
error: err.message, error: err.message,
failedAtStep: pipelineState.currentStep,
lastStepInput: currentInput.slice(0, 50000),
endedAt: new Date().toISOString(), endedAt: new Date().toISOString(),
totalCostUsd: totalCost, totalCostUsd: totalCost,
}); });
@@ -335,6 +376,175 @@ export function cancelPipeline(id) {
return true; return true;
} }
export async function resumePipeline(executionId, wsCallback, options = {}) {
const prevExec = executionsStore.getById(executionId);
if (!prevExec) throw new Error('Execução não encontrada');
if (prevExec.status !== 'error') throw new Error('Só é possível retomar execuções com erro');
if (prevExec.type !== 'pipeline') throw new Error('Execução não é de pipeline');
const pl = pipelinesStore.getById(prevExec.pipelineId);
if (!pl) throw new Error(`Pipeline ${prevExec.pipelineId} não encontrado`);
const startStep = prevExec.failedAtStep || 0;
const initialInput = prevExec.lastStepInput || prevExec.input;
const newExecId = uuidv4();
const pipelineState = { pipelineId: prevExec.pipelineId, currentExecutionId: null, currentStep: startStep, canceled: false, pendingApproval: null };
activePipelines.set(newExecId, pipelineState);
const prevSteps = Array.isArray(prevExec.steps) ? [...prevExec.steps] : [];
const prevCost = prevExec.totalCostUsd || 0;
const historyRecord = executionsStore.create({
type: 'pipeline',
pipelineId: prevExec.pipelineId,
pipelineName: pl.name,
input: prevExec.input,
resumedFrom: executionId,
resumedAtStep: startStep,
status: 'running',
startedAt: new Date().toISOString(),
steps: prevSteps,
totalCostUsd: prevCost,
});
const steps = buildSteps(pl.steps);
const results = prevSteps.map(s => ({ stepId: s.stepId, agentId: s.agentId, agentName: s.agentName, result: s.result, sessionId: '' }));
let currentInput = initialInput;
let totalCost = prevCost;
try {
for (let i = startStep; i < steps.length; i++) {
if (pipelineState.canceled) break;
const step = steps[i];
pipelineState.currentStep = i;
if (step.requiresApproval && i > 0) {
const prevAgentName = results.length > 0 ? results[results.length - 1].agentName : '';
executionsStore.update(historyRecord.id, { status: 'awaiting_approval' });
if (wsCallback) wsCallback({ type: 'pipeline_status', pipelineId: prevExec.pipelineId, status: 'awaiting_approval', stepIndex: i });
const approved = await waitForApproval(newExecId, prevExec.pipelineId, i, currentInput, prevAgentName, wsCallback);
if (!approved) {
pipelineState.canceled = true;
executionsStore.update(historyRecord.id, { status: 'rejected', endedAt: new Date().toISOString(), totalCostUsd: totalCost });
if (wsCallback) wsCallback({ type: 'pipeline_rejected', pipelineId: prevExec.pipelineId, stepIndex: i });
break;
}
executionsStore.update(historyRecord.id, { status: 'running' });
}
if (pipelineState.canceled) break;
const agent = agentsStore.getById(step.agentId);
if (!agent) throw new Error(`Agente ${step.agentId} não encontrado no passo ${i}`);
if (agent.status !== 'active') throw new Error(`Agente ${agent.agent_name} está inativo`);
const stepConfig = { ...agent.config };
const effectiveWorkdir = options.workingDirectory || pl.workingDirectory;
if (effectiveWorkdir) stepConfig.workingDirectory = effectiveWorkdir;
const prompt = applyTemplate(step.inputTemplate, currentInput);
const stepStart = new Date().toISOString();
if (wsCallback) {
wsCallback({
type: 'pipeline_step_start',
pipelineId: prevExec.pipelineId,
stepIndex: i,
stepId: step.id,
agentName: agent.agent_name,
totalSteps: steps.length,
resumed: true,
});
}
const stepResult = await executeStepAsPromise(stepConfig, prompt, pipelineState, wsCallback, prevExec.pipelineId, i);
if (pipelineState.canceled) break;
totalCost += stepResult.costUsd;
currentInput = stepResult.text;
results.push({ stepId: step.id, agentId: step.agentId, agentName: agent.agent_name, result: stepResult.text, sessionId: stepResult.sessionId });
const current = executionsStore.getById(historyRecord.id);
const savedSteps = current ? (current.steps || []) : [];
savedSteps.push({
stepIndex: i,
agentId: step.agentId,
agentName: agent.agent_name,
prompt: prompt.slice(0, 5000),
result: stepResult.text,
startedAt: stepStart,
endedAt: new Date().toISOString(),
status: 'completed',
costUsd: stepResult.costUsd,
durationMs: stepResult.durationMs,
numTurns: stepResult.numTurns,
});
executionsStore.update(historyRecord.id, { steps: savedSteps, totalCostUsd: totalCost });
if (wsCallback) {
wsCallback({
type: 'pipeline_step_complete',
pipelineId: prevExec.pipelineId,
stepIndex: i,
stepId: step.id,
result: stepResult.text.slice(0, 500),
costUsd: stepResult.costUsd,
});
}
if (i < steps.length - 1 && !pipelineState.canceled) {
if (wsCallback) wsCallback({ type: 'pipeline_summarizing', pipelineId: prevExec.pipelineId, stepIndex: i, originalLength: currentInput.length });
const summarized = await executor.summarize(currentInput);
if (summarized !== currentInput) {
if (wsCallback) wsCallback({ type: 'pipeline_summarized', pipelineId: prevExec.pipelineId, stepIndex: i, originalLength: currentInput.length, summarizedLength: summarized.length });
currentInput = summarized;
}
}
}
activePipelines.delete(newExecId);
const finalStatus = pipelineState.canceled ? 'canceled' : 'completed';
executionsStore.update(historyRecord.id, { status: finalStatus, endedAt: new Date().toISOString(), totalCostUsd: totalCost });
if (!pipelineState.canceled) {
try {
const updated = executionsStore.getById(historyRecord.id);
if (updated) {
const report = generatePipelineReport(updated);
if (wsCallback) wsCallback({ type: 'report_generated', pipelineId: prevExec.pipelineId, reportFile: report.filename });
}
} catch (e) { console.error('[pipeline] Erro ao gerar relatório:', e.message); }
const lastResult = results.length > 0 ? results[results.length - 1] : null;
if (wsCallback) wsCallback({
type: 'pipeline_complete',
pipelineId: prevExec.pipelineId,
executionId: newExecId,
results,
totalCostUsd: totalCost,
lastAgentId: lastResult?.agentId || '',
lastAgentName: lastResult?.agentName || '',
lastSessionId: lastResult?.sessionId || '',
});
}
return { executionId: newExecId, results };
} catch (err) {
activePipelines.delete(newExecId);
executionsStore.update(historyRecord.id, {
status: 'error',
error: err.message,
failedAtStep: pipelineState.currentStep,
lastStepInput: currentInput.slice(0, 50000),
endedAt: new Date().toISOString(),
totalCostUsd: totalCost,
});
if (wsCallback) wsCallback({ type: 'pipeline_error', pipelineId: prevExec.pipelineId, stepIndex: pipelineState.currentStep, error: err.message });
throw err;
}
}
export function getActivePipelines() { export function getActivePipelines() {
return Array.from(activePipelines.entries()).map(([id, state]) => ({ return Array.from(activePipelines.entries()).map(([id, state]) => ({
executionId: id, executionId: id,
@@ -351,6 +561,7 @@ export function createPipeline(data) {
return pipelinesStore.create({ return pipelinesStore.create({
name: data.name, name: data.name,
description: data.description || '', description: data.description || '',
workingDirectory: data.workingDirectory || '',
steps: buildSteps(data.steps), steps: buildSteps(data.steps),
status: data.status || 'active', status: data.status || 'active',
}); });
@@ -362,6 +573,7 @@ export function updatePipeline(id, data) {
const updateData = {}; const updateData = {};
if (data.name !== undefined) updateData.name = data.name; if (data.name !== undefined) updateData.name = data.name;
if (data.description !== undefined) updateData.description = data.description; if (data.description !== undefined) updateData.description = data.description;
if (data.workingDirectory !== undefined) updateData.workingDirectory = data.workingDirectory;
if (data.status !== undefined) updateData.status = data.status; if (data.status !== undefined) updateData.status = data.status;
if (data.steps !== undefined) updateData.steps = buildSteps(data.steps); if (data.steps !== undefined) updateData.steps = buildSteps(data.steps);
return pipelinesStore.update(id, updateData); return pipelinesStore.update(id, updateData);

View File

@@ -160,6 +160,13 @@ export function restoreSchedules(executeFn) {
if (restored > 0) console.log(`[scheduler] ${restored} agendamento(s) restaurado(s)`); if (restored > 0) console.log(`[scheduler] ${restored} agendamento(s) restaurado(s)`);
} }
export function stopAll() {
for (const [, entry] of schedules) {
entry.task.stop();
}
schedules.clear();
}
export function on(event, listener) { export function on(event, listener) {
emitter.on(event, listener); emitter.on(event, listener);
} }

View File

@@ -1,5 +1,5 @@
import { Router } from 'express'; import { Router } from 'express';
import { execFile } from 'child_process'; import { execFile, spawn as spawnProcess } from 'child_process';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import crypto from 'crypto'; import crypto from 'crypto';
import os from 'os'; import os from 'os';
@@ -8,11 +8,14 @@ import * as manager from '../agents/manager.js';
import { tasksStore, settingsStore, executionsStore, webhooksStore, notificationsStore, secretsStore, agentVersionsStore } from '../store/db.js'; import { tasksStore, settingsStore, executionsStore, webhooksStore, notificationsStore, secretsStore, agentVersionsStore } from '../store/db.js';
import * as scheduler from '../agents/scheduler.js'; import * as scheduler from '../agents/scheduler.js';
import * as pipeline from '../agents/pipeline.js'; import * as pipeline from '../agents/pipeline.js';
import { getBinPath, updateMaxConcurrent } from '../agents/executor.js'; import * as gitIntegration from '../agents/git-integration.js';
import { getBinPath, updateMaxConcurrent, cancelAllExecutions, getActiveExecutions } from '../agents/executor.js';
import { invalidateAgentMapCache } from '../agents/pipeline.js'; import { invalidateAgentMapCache } from '../agents/pipeline.js';
import { cached } from '../cache/index.js'; import { cached } from '../cache/index.js';
import { readdirSync, readFileSync, unlinkSync, existsSync, mkdirSync } from 'fs'; import { readdirSync, readFileSync, writeFileSync, unlinkSync, existsSync, mkdirSync, statSync, createReadStream, rmSync } from 'fs';
import { join, dirname, resolve as pathResolve, extname } from 'path'; import { join, dirname, resolve as pathResolve, extname, basename, relative } from 'path';
import { createGzip } from 'zlib';
import { Readable } from 'stream';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
const __apiDirname = dirname(fileURLToPath(import.meta.url)); const __apiDirname = dirname(fileURLToPath(import.meta.url));
@@ -163,14 +166,25 @@ function buildContextFilesPrompt(contextFiles) {
return `\n\nArquivos de contexto anexados (leia cada um deles antes de iniciar):\n${lines.join('\n')}`; return `\n\nArquivos de contexto anexados (leia cada um deles antes de iniciar):\n${lines.join('\n')}`;
} }
router.post('/agents/:id/execute', (req, res) => { router.post('/agents/:id/execute', async (req, res) => {
try { try {
const { task, instructions, contextFiles } = req.body; const { task, instructions, contextFiles, workingDirectory, repoName, repoBranch } = req.body;
if (!task) return res.status(400).json({ error: 'task é obrigatório' }); if (!task) return res.status(400).json({ error: 'task é obrigatório' });
const clientId = req.headers['x-client-id'] || null; const clientId = req.headers['x-client-id'] || null;
const filesPrompt = buildContextFilesPrompt(contextFiles); const filesPrompt = buildContextFilesPrompt(contextFiles);
const fullTask = task + filesPrompt; const fullTask = task + filesPrompt;
const executionId = manager.executeTask(req.params.id, fullTask, instructions, (msg) => wsCallback(msg, clientId)); const metadata = {};
if (repoName) {
const syncResult = await gitIntegration.cloneOrPull(repoName, repoBranch || null);
metadata.workingDirectoryOverride = syncResult.dir;
metadata.repoName = repoName;
metadata.repoBranch = repoBranch || null;
} else if (workingDirectory) {
metadata.workingDirectoryOverride = workingDirectory;
}
const executionId = manager.executeTask(req.params.id, fullTask, instructions, (msg) => wsCallback(msg, clientId), metadata);
res.status(202).json({ executionId, status: 'started' }); res.status(202).json({ executionId, status: 'started' });
} catch (err) { } catch (err) {
const status = err.message.includes('não encontrado') ? 404 : 400; const status = err.message.includes('não encontrado') ? 404 : 400;
@@ -460,11 +474,20 @@ router.delete('/pipelines/:id', (req, res) => {
router.post('/pipelines/:id/execute', async (req, res) => { router.post('/pipelines/:id/execute', async (req, res) => {
try { try {
const { input, workingDirectory, contextFiles } = req.body; const { input, workingDirectory, contextFiles, repoName, repoBranch } = req.body;
if (!input) return res.status(400).json({ error: 'input é obrigatório' }); if (!input) return res.status(400).json({ error: 'input é obrigatório' });
const clientId = req.headers['x-client-id'] || null; const clientId = req.headers['x-client-id'] || null;
const options = {}; const options = {};
if (workingDirectory) options.workingDirectory = workingDirectory;
if (repoName) {
const syncResult = await gitIntegration.cloneOrPull(repoName, repoBranch || null);
options.workingDirectory = syncResult.dir;
options.repoName = repoName;
options.repoBranch = repoBranch || null;
} else if (workingDirectory) {
options.workingDirectory = workingDirectory;
}
const filesPrompt = buildContextFilesPrompt(contextFiles); const filesPrompt = buildContextFilesPrompt(contextFiles);
const fullInput = input + filesPrompt; const fullInput = input + filesPrompt;
const result = pipeline.executePipeline(req.params.id, fullInput, (msg) => wsCallback(msg, clientId), options); const result = pipeline.executePipeline(req.params.id, fullInput, (msg) => wsCallback(msg, clientId), options);
@@ -506,6 +529,18 @@ router.post('/pipelines/:id/reject', (req, res) => {
} }
}); });
router.post('/pipelines/resume/:executionId', async (req, res) => {
try {
const clientId = req.headers['x-client-id'] || null;
const result = pipeline.resumePipeline(req.params.executionId, (msg) => wsCallback(msg, clientId));
result.catch(() => {});
res.status(202).json({ status: 'resumed' });
} catch (err) {
const status = err.message.includes('não encontrad') ? 404 : 400;
res.status(status).json({ error: err.message });
}
});
router.get('/webhooks', (req, res) => { router.get('/webhooks', (req, res) => {
try { try {
res.json(webhooksStore.getAll()); res.json(webhooksStore.getAll());
@@ -826,6 +861,23 @@ router.get('/executions/active', (req, res) => {
} }
}); });
router.post('/executions/cancel-all', (req, res) => {
try {
const activePipelines = pipeline.getActivePipelines();
for (const p of activePipelines) {
pipeline.cancelPipeline(p.pipelineId);
}
cancelAllExecutions();
const running = executionsStore.getAll().filter(e => e.status === 'running' || e.status === 'awaiting_approval');
for (const e of running) {
executionsStore.update(e.id, { status: 'canceled', endedAt: new Date().toISOString() });
}
res.json({ cancelled: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.get('/executions/recent', (req, res) => { router.get('/executions/recent', (req, res) => {
try { try {
const limit = parseInt(req.query.limit) || 20; const limit = parseInt(req.query.limit) || 20;
@@ -1008,4 +1060,282 @@ router.delete('/reports/:filename', (req, res) => {
} }
}); });
const PROJECTS_DIR = '/home/projetos';
function resolveProjectPath(requestedPath) {
const decoded = decodeURIComponent(requestedPath || '');
const resolved = pathResolve(PROJECTS_DIR, decoded);
if (!resolved.startsWith(PROJECTS_DIR)) return null;
return resolved;
}
router.get('/files', (req, res) => {
try {
const targetPath = resolveProjectPath(req.query.path || '');
if (!targetPath) return res.status(400).json({ error: 'Caminho inválido' });
if (!existsSync(targetPath)) return res.status(404).json({ error: 'Diretório não encontrado' });
const stat = statSync(targetPath);
if (!stat.isDirectory()) return res.status(400).json({ error: 'Caminho não é um diretório' });
const entries = readdirSync(targetPath, { withFileTypes: true })
.filter(e => !e.name.startsWith('.'))
.map(entry => {
const fullPath = join(targetPath, entry.name);
try {
const s = statSync(fullPath);
return {
name: entry.name,
type: entry.isDirectory() ? 'directory' : 'file',
size: entry.isDirectory() ? null : s.size,
modified: s.mtime.toISOString(),
extension: entry.isDirectory() ? null : extname(entry.name).slice(1).toLowerCase(),
};
} catch {
return null;
}
})
.filter(Boolean)
.sort((a, b) => {
if (a.type !== b.type) return a.type === 'directory' ? -1 : 1;
return a.name.localeCompare(b.name);
});
const relativePath = relative(PROJECTS_DIR, targetPath) || '';
res.json({
path: relativePath,
parent: relativePath ? dirname(relativePath) : null,
entries,
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.get('/files/download', (req, res) => {
try {
const targetPath = resolveProjectPath(req.query.path || '');
if (!targetPath) return res.status(400).json({ error: 'Caminho inválido' });
if (!existsSync(targetPath)) return res.status(404).json({ error: 'Arquivo não encontrado' });
const stat = statSync(targetPath);
if (!stat.isFile()) return res.status(400).json({ error: 'Caminho não é um arquivo' });
const filename = basename(targetPath);
res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(filename)}"`);
res.setHeader('Content-Length', stat.size);
createReadStream(targetPath).pipe(res);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.get('/files/download-folder', (req, res) => {
try {
const targetPath = resolveProjectPath(req.query.path || '');
if (!targetPath) return res.status(400).json({ error: 'Caminho inválido' });
if (!existsSync(targetPath)) return res.status(404).json({ error: 'Pasta não encontrada' });
const stat = statSync(targetPath);
if (!stat.isDirectory()) return res.status(400).json({ error: 'Caminho não é uma pasta' });
const folderName = basename(targetPath) || 'projetos';
res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(folderName)}.tar.gz"`);
res.setHeader('Content-Type', 'application/gzip');
const parentDir = dirname(targetPath);
const dirName = basename(targetPath);
const tar = spawnProcess('tar', ['-czf', '-', '-C', parentDir, dirName]);
tar.stdout.pipe(res);
tar.stderr.on('data', () => {});
tar.on('error', (err) => {
if (!res.headersSent) res.status(500).json({ error: err.message });
});
req.on('close', () => { try { tar.kill(); } catch {} });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.delete('/files', (req, res) => {
try {
const targetPath = resolveProjectPath(req.query.path || '');
if (!targetPath) return res.status(400).json({ error: 'Caminho inválido' });
if (targetPath === PROJECTS_DIR) return res.status(400).json({ error: 'Não é permitido excluir o diretório raiz' });
if (!existsSync(targetPath)) return res.status(404).json({ error: 'Arquivo ou pasta não encontrado' });
const stat = statSync(targetPath);
if (stat.isDirectory()) {
rmSync(targetPath, { recursive: true, force: true });
} else {
unlinkSync(targetPath);
}
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.get('/repos', async (req, res) => {
try {
const repos = await gitIntegration.listRepos();
res.json(repos);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.get('/repos/:name/branches', async (req, res) => {
try {
const branches = await gitIntegration.listBranches(req.params.name);
res.json(branches);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.post('/files/publish', async (req, res) => {
const { path: projectPath } = req.body;
if (!projectPath) return res.status(400).json({ error: 'path é obrigatório' });
const targetPath = resolveProjectPath(projectPath);
if (!targetPath) return res.status(400).json({ error: 'Caminho inválido' });
if (!existsSync(targetPath)) return res.status(404).json({ error: 'Projeto não encontrado' });
if (!statSync(targetPath).isDirectory()) return res.status(400).json({ error: 'Caminho não é uma pasta' });
const projectName = basename(targetPath).toLowerCase().replace(/[^a-z0-9-]/g, '-');
const GITEA_URL = process.env.GITEA_URL || 'http://gitea:3000';
const GITEA_USER = process.env.GITEA_USER || 'fred';
const GITEA_PASS = process.env.GITEA_PASS || '';
const DOMAIN = process.env.DOMAIN || 'nitro-cloud.duckdns.org';
const VPS_COMPOSE_DIR = process.env.VPS_COMPOSE_DIR || '/vps';
if (!GITEA_PASS) return res.status(500).json({ error: 'GITEA_PASS não configurado no servidor' });
const exec = (cmd, opts = {}) => new Promise((resolve, reject) => {
const proc = spawnProcess('sh', ['-c', cmd], { cwd: opts.cwd || targetPath, env: { ...process.env, HOME: '/tmp', GIT_TERMINAL_PROMPT: '0' } });
let stdout = '', stderr = '';
proc.stdout.on('data', d => stdout += d);
proc.stderr.on('data', d => stderr += d);
proc.on('close', code => code === 0 ? resolve(stdout.trim()) : reject(new Error(stderr.trim() || `exit ${code}`)));
});
const steps = [];
try {
const authUrl = `${GITEA_URL.replace('://', `://${GITEA_USER}:${GITEA_PASS}@`)}`;
const repoApiUrl = `${GITEA_URL}/api/v1/repos/${GITEA_USER}/${projectName}`;
const createUrl = `${GITEA_URL}/api/v1/user/repos`;
const authHeader = 'Basic ' + Buffer.from(`${GITEA_USER}:${GITEA_PASS}`).toString('base64');
let repoExists = false;
try {
const check = await fetch(repoApiUrl, { headers: { Authorization: authHeader } });
repoExists = check.ok;
} catch {}
if (!repoExists) {
const createRes = await fetch(createUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: authHeader },
body: JSON.stringify({ name: projectName, auto_init: false, private: false }),
});
if (!createRes.ok) {
const err = await createRes.json().catch(() => ({}));
throw new Error(`Erro ao criar repositório: ${err.message || createRes.statusText}`);
}
steps.push('Repositório criado no Gitea');
} else {
steps.push('Repositório já existe no Gitea');
}
const repoUrl = `${authUrl}/${GITEA_USER}/${projectName}.git`;
const gitDir = `${targetPath}/.git`;
if (!existsSync(gitDir)) {
await exec('git init');
await exec(`git remote add origin "${repoUrl}"`);
steps.push('Git inicializado');
} else {
try {
await exec('git remote get-url origin');
await exec(`git remote set-url origin "${repoUrl}"`);
} catch {
await exec(`git remote add origin "${repoUrl}"`);
}
steps.push('Remote atualizado');
}
await exec('git add -A');
try {
await exec('git -c user.name="Agents Orchestrator" -c user.email="agents@nitro-cloud" commit -m "Publicação automática"');
steps.push('Commit criado');
} catch {
steps.push('Sem alterações para commit');
}
await exec('git push -u origin HEAD:main --force');
steps.push('Push realizado');
const caddyFile = `${VPS_COMPOSE_DIR}/caddy/Caddyfile`;
if (existsSync(caddyFile)) {
const caddyContent = readFileSync(caddyFile, 'utf-8');
const marker = `@${projectName} host ${projectName}.${DOMAIN}`;
if (!caddyContent.includes(marker)) {
const block = `\n @${projectName} host ${projectName}.${DOMAIN}\n handle @${projectName} {\n root * /srv/${projectName}\n file_server\n try_files {path} /index.html\n }\n`;
const updated = caddyContent.replace(
/(\n? {4}handle \{[\s\S]*?respond.*?200[\s\S]*?\})/,
block + '$1'
);
writeFileSync(caddyFile, updated);
steps.push('Caddyfile atualizado');
} else {
steps.push('Caddyfile já configurado');
}
}
const composePath = `${VPS_COMPOSE_DIR}/docker-compose.yml`;
if (existsSync(composePath)) {
const composeContent = readFileSync(composePath, 'utf-8');
const volumeLine = `/home/projetos/${basename(targetPath)}:/srv/${projectName}:ro`;
if (!composeContent.includes(volumeLine)) {
const updated = composeContent.replace(
/(- .\/caddy\/config:\/config)/,
`$1\n - ${volumeLine}`
);
writeFileSync(composePath, updated);
steps.push('Volume adicionado ao docker-compose');
} else {
steps.push('Volume já configurado');
}
}
try {
await exec(`docker compose -f ${VPS_COMPOSE_DIR}/docker-compose.yml up -d --force-recreate --no-deps caddy`, { cwd: VPS_COMPOSE_DIR });
steps.push('Caddy reiniciado');
} catch (e) {
steps.push(`Caddy: reinício manual necessário (${e.message})`);
}
const siteUrl = `https://${projectName}.${DOMAIN}`;
const repoWebUrl = `https://git.${DOMAIN}/${GITEA_USER}/${projectName}`;
res.json({
status: 'Publicado',
siteUrl,
repoUrl: repoWebUrl,
projectName,
steps,
message: `Acesse ${siteUrl} em alguns segundos`,
});
} catch (err) {
res.status(500).json({ error: err.message, steps });
}
});
export default router; export default router;