From b86da0b8053776b77dc55b88a37a0b9cd6da27c6 Mon Sep 17 00:00:00 2001 From: Enmanuel Date: Fri, 6 Mar 2026 09:06:11 +0000 Subject: [PATCH] refactor: update dev-scripts for unified launcher model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Actualiza todos los scripts de desarrollo para el modelo de launcher unificado. Ya no se inician procesos individuales por agente — un solo proceso corre todos. _common.sh: helpers para launcher unificado (is_launcher_running, read_launcher_pid, launcher_pid_file/log_file), agent_status() ahora deriva estado del launcher start.sh: inicia el launcher unificado (sin -c flag, descubre todos los agentes) stop.sh: detiene el launcher unificado restart.sh: stop + start del launcher ps.sh: muestra stats del proceso launcher + lista de agentes enabled/disabled logs.sh: tail -f del log unificado del launcher server.sh: añade comandos enable/disable para gestionar agentes, elimina start/stop por agente remove.sh: simplificado a toggle enabled:false + sugerencia de restart Co-Authored-By: Claude Opus 4.6 --- dev-scripts/_common.sh | 29 +++++++- dev-scripts/logs.sh | 28 +++---- dev-scripts/ps.sh | 163 +++++++++++++++++++---------------------- dev-scripts/remove.sh | 15 +--- dev-scripts/restart.sh | 15 ++-- dev-scripts/server.sh | 159 ++++++++++++++++++++++------------------ dev-scripts/start.sh | 94 +++++++++--------------- dev-scripts/stop.sh | 69 ++++++----------- 8 files changed, 265 insertions(+), 307 deletions(-) diff --git a/dev-scripts/_common.sh b/dev-scripts/_common.sh index c94621b..00ce6da 100755 --- a/dev-scripts/_common.sh +++ b/dev-scripts/_common.sh @@ -114,13 +114,40 @@ agent_status() { local id="$1" enabled="$2" if [[ "$enabled" != "true" ]]; then echo "disabled" - elif is_running "$id"; then + elif is_launcher_running; then echo "running" else echo "stopped" fi } +# ── Unified launcher helpers ─────────────────────────────────────────────── +LAUNCHER_ID="launcher" + +launcher_pid_file() { echo "$RUN_DIR/$LAUNCHER_ID.pid"; } +launcher_log_file() { echo "$RUN_DIR/$LAUNCHER_ID.log"; } + +read_launcher_pid() { + local f; f="$(launcher_pid_file)" + [[ -f "$f" ]] && cat "$f" || echo 0 +} + +is_launcher_running() { + local pid; pid="$(read_launcher_pid)" + if [[ "$pid" -gt 0 ]] && kill -0 "$pid" 2>/dev/null; then + return 0 + fi + # Fallback: search for launcher process without -c flag + local pids; pids="$(pgrep -f 'launcher.*--log-level' 2>/dev/null || true)" + if [[ -n "$pids" ]]; then + local first_pid; first_pid="$(echo "$pids" | head -1)" + echo "$first_pid" > "$(launcher_pid_file)" + return 0 + fi + [[ "$pid" -gt 0 ]] && rm -f "$(launcher_pid_file)" + return 1 +} + # ── Agent discovery ──────────────────────────────────────────────────────── # Prints: id|version|enabled|description (one line per agent) list_agents_raw() { diff --git a/dev-scripts/logs.sh b/dev-scripts/logs.sh index 11f4b88..ad467fc 100755 --- a/dev-scripts/logs.sh +++ b/dev-scripts/logs.sh @@ -1,31 +1,21 @@ #!/usr/bin/env bash -# logs.sh — sigue los logs de uno o todos los agentes +# logs.sh — sigue los logs del launcher unificado # # Uso: -# ./dev-scripts/logs.sh # tail -f de todos los logs activos -# ./dev-scripts/logs.sh assistant-bot # solo ese agente -# ./dev-scripts/logs.sh assistant-bot 100 # últimas 100 líneas +# ./dev-scripts/logs.sh # tail -f del launcher log +# ./dev-scripts/logs.sh 100 # últimas 100 líneas source "$(dirname "$0")/_common.sh" -TARGET="${1:-}" -LINES="${2:-50}" +LINES="${1:-50}" +LOG="$(launcher_log_file)" -log_files=() - -while IFS='|' read -r id _version _enabled _desc _cfg; do - [[ -n "$TARGET" && "$id" != "$TARGET" ]] && continue - local_log="$(log_file "$id")" - [[ -f "$local_log" ]] && log_files+=("$local_log") -done < <(list_agents_raw) - -if [[ "${#log_files[@]}" -eq 0 ]]; then - [[ -n "$TARGET" ]] && fail "No hay logs para '$TARGET' (¿ha sido iniciado alguna vez?)" - fail "No hay logs todavía — inicia algún agente primero" +if [[ ! -f "$LOG" ]]; then + fail "No hay logs todavía — inicia el launcher primero" fi -info "Siguiendo logs: ${log_files[*]}" +info "Siguiendo logs: $LOG" dim " Ctrl+C para salir" echo "" -tail -n "$LINES" -f "${log_files[@]}" +tail -n "$LINES" -f "$LOG" diff --git a/dev-scripts/ps.sh b/dev-scripts/ps.sh index 82f932f..399c513 100755 --- a/dev-scripts/ps.sh +++ b/dev-scripts/ps.sh @@ -1,96 +1,85 @@ #!/usr/bin/env bash -# ps.sh — muestra procesos de agentes con detalles (PID, uptime, memoria, CPU) +# ps.sh — muestra el estado del launcher unificado y agentes # # Uso: -# ./dev-scripts/ps.sh # todos los agentes corriendo -# ./dev-scripts/ps.sh assistant-bot # uno específico +# ./dev-scripts/ps.sh source "$(dirname "$0")/_common.sh" -TARGET="${1:-}" -found=0 - -# Cabecera -printf "%-22s %-8s %-12s %-10s %-8s %s\n" \ - "AGENT" "PID" "UPTIME" "MEM (RSS)" "CPU %" "LOG SIZE" -printf '%s\n' "$(printf '─%.0s' {1..78})" - -while IFS='|' read -r id _version _enabled _desc _cfg; do - [[ -n "$TARGET" && "$id" != "$TARGET" ]] && continue - - if ! is_running "$id"; then - if [[ -n "$TARGET" ]]; then - printf "%-22s ${DIM}%-8s${RST}\n" "$id" "stopped" - fi - continue - fi - - pid="$(read_pid "$id")" - instance_count="$(count_instances "$id")" - ((found++)) || true - - # Uptime: calcular desde el inicio del proceso - if [[ -f /proc/$pid/stat ]]; then - start_ticks=$(awk '{print $22}' /proc/$pid/stat 2>/dev/null || echo 0) - clk_tck=$(getconf CLK_TCK) - boot_time=$(awk '/btime/{print $2}' /proc/stat) - proc_start=$((boot_time + start_ticks / clk_tck)) - now=$(date +%s) - elapsed=$((now - proc_start)) - days=$((elapsed / 86400)) - hours=$(( (elapsed % 86400) / 3600 )) - mins=$(( (elapsed % 3600) / 60 )) - if [[ $days -gt 0 ]]; then - uptime="${days}d ${hours}h" - elif [[ $hours -gt 0 ]]; then - uptime="${hours}h ${mins}m" +if ! is_launcher_running; then + echo "" + dim " Launcher no está corriendo." + echo "" + echo " Agentes:" + while IFS='|' read -r id _v enabled _d _c; do + if [[ "$enabled" == "true" ]]; then + echo -e " ${GRN}●${RST} $id (enabled)" else - uptime="${mins}m" + echo -e " ${DIM}○ $id (disabled)${RST}" fi - else - uptime="n/a" - fi - - # Memoria RSS y CPU desde ps - read -r mem_kb cpu_pct < <(ps -p "$pid" -o rss=,pcpu= 2>/dev/null || echo "0 0") - if [[ "$mem_kb" -gt 1048576 ]]; then - mem="$(( mem_kb / 1048576 )) GB" - elif [[ "$mem_kb" -gt 1024 ]]; then - mem="$(( mem_kb / 1024 )) MB" - else - mem="${mem_kb} KB" - fi - - # Tamaño del log - log="$(log_file "$id")" - if [[ -f "$log" ]]; then - log_bytes=$(stat -c%s "$log" 2>/dev/null || echo 0) - if [[ "$log_bytes" -gt 1048576 ]]; then - log_size="$(( log_bytes / 1048576 )) MB" - elif [[ "$log_bytes" -gt 1024 ]]; then - log_size="$(( log_bytes / 1024 )) KB" - else - log_size="${log_bytes} B" - fi - else - log_size="-" - fi - - printf "%-22s ${GRN}%-8s${RST} %-12s %-10s %-8s %s\n" \ - "$id" "$pid" "$uptime" "$mem" "${cpu_pct}%" "$log_size" - - # Warn about duplicate instances - if [[ "$instance_count" -gt 1 ]]; then - printf " ${RED}⚠ WARNING: %d instances running!${RST} PIDs: %s\n" \ - "$instance_count" "$(find_agent_pids "$id" | tr '\n' ' ')" - fi - -done < <(list_agents_raw) - -if [[ "$found" -eq 0 ]]; then - if [[ -n "$TARGET" ]]; then - fail "Agente '$TARGET' no está corriendo." - else - dim " No hay agentes corriendo." - fi + done < <(list_agents_raw) + exit 0 fi + +pid="$(read_launcher_pid)" + +# Uptime +if [[ -f /proc/$pid/stat ]]; then + start_ticks=$(awk '{print $22}' /proc/$pid/stat 2>/dev/null || echo 0) + clk_tck=$(getconf CLK_TCK) + boot_time=$(awk '/btime/{print $2}' /proc/stat) + proc_start=$((boot_time + start_ticks / clk_tck)) + now=$(date +%s) + elapsed=$((now - proc_start)) + days=$((elapsed / 86400)) + hours=$(( (elapsed % 86400) / 3600 )) + mins=$(( (elapsed % 3600) / 60 )) + if [[ $days -gt 0 ]]; then + uptime="${days}d ${hours}h" + elif [[ $hours -gt 0 ]]; then + uptime="${hours}h ${mins}m" + else + uptime="${mins}m" + fi +else + uptime="n/a" +fi + +# Memory and CPU +read -r mem_kb cpu_pct < <(ps -p "$pid" -o rss=,pcpu= 2>/dev/null || echo "0 0") +if [[ "$mem_kb" -gt 1048576 ]]; then + mem="$(( mem_kb / 1048576 )) GB" +elif [[ "$mem_kb" -gt 1024 ]]; then + mem="$(( mem_kb / 1024 )) MB" +else + mem="${mem_kb} KB" +fi + +# Log size +log="$(launcher_log_file)" +if [[ -f "$log" ]]; then + log_bytes=$(stat -c%s "$log" 2>/dev/null || echo 0) + if [[ "$log_bytes" -gt 1048576 ]]; then + log_size="$(( log_bytes / 1048576 )) MB" + elif [[ "$log_bytes" -gt 1024 ]]; then + log_size="$(( log_bytes / 1024 )) KB" + else + log_size="${log_bytes} B" + fi +else + log_size="-" +fi + +echo "" +echo -e " ${GRN}● Launcher running${RST} PID $pid" +echo -e " uptime: $uptime mem: $mem cpu: ${cpu_pct}% log: $log_size" +echo "" +echo " Agentes:" + +while IFS='|' read -r id _v enabled _d _c; do + if [[ "$enabled" == "true" ]]; then + echo -e " ${GRN}●${RST} $id (enabled, running in launcher)" + else + echo -e " ${DIM}○ $id (disabled)${RST}" + fi +done < <(list_agents_raw) diff --git a/dev-scripts/remove.sh b/dev-scripts/remove.sh index 897b03b..581d486 100755 --- a/dev-scripts/remove.sh +++ b/dev-scripts/remove.sh @@ -14,22 +14,11 @@ while IFS='|' read -r id _version _enabled _desc cfg; do [[ "$id" != "$TARGET" ]] && continue found=true - # Detener si está corriendo - if is_running "$id"; then - local_pid="$(read_pid "$id")" - info "Deteniendo $id (PID $local_pid)..." - kill -TERM "$local_pid" 2>/dev/null || true - sleep 1 - kill -0 "$local_pid" 2>/dev/null && kill -9 "$local_pid" 2>/dev/null || true - rm -f "$(pid_file "$id")" - ok "$id detenido" - fi - - # Marcar como disabled en el config (reemplaza solo la primera ocurrencia) + # Marcar como disabled en el config if grep -q 'enabled: true' "$cfg"; then - # sed compatible con Linux y macOS sed -i 's/enabled: true/enabled: false/' "$cfg" ok "$id marcado como disabled en $cfg" + info "Reinicia el launcher para aplicar: ./dev-scripts/server.sh restart" else warn "$id ya estaba marcado como disabled" fi diff --git a/dev-scripts/restart.sh b/dev-scripts/restart.sh index c6f6db4..90a41ed 100755 --- a/dev-scripts/restart.sh +++ b/dev-scripts/restart.sh @@ -1,17 +1,14 @@ #!/usr/bin/env bash -# restart.sh — reinicia uno o todos los agentes +# restart.sh — reinicia el launcher unificado # # Uso: -# ./dev-scripts/restart.sh # reinicia todos los habilitados -# ./dev-scripts/restart.sh assistant-bot # reinicia uno específico +# ./dev-scripts/restart.sh source "$(dirname "$0")/_common.sh" -TARGET="${1:-}" - -info "Deteniendo agentes..." -"$REPO_ROOT/dev-scripts/stop.sh" ${TARGET:+"$TARGET"} +info "Deteniendo launcher..." +"$REPO_ROOT/dev-scripts/stop.sh" echo "" -info "Iniciando agentes..." -"$REPO_ROOT/dev-scripts/start.sh" ${TARGET:+"$TARGET"} +info "Iniciando launcher..." +"$REPO_ROOT/dev-scripts/start.sh" diff --git a/dev-scripts/server.sh b/dev-scripts/server.sh index 9fde507..b35a977 100755 --- a/dev-scripts/server.sh +++ b/dev-scripts/server.sh @@ -2,123 +2,138 @@ # server.sh — gestión unificada del servidor de bots # # Uso: -# ./dev-scripts/server.sh start [agent-id] # iniciar uno o todos -# ./dev-scripts/server.sh stop [agent-id] # detener uno o todos -# ./dev-scripts/server.sh restart [agent-id] # reiniciar uno o todos -# ./dev-scripts/server.sh status # resumen general del servidor -# ./dev-scripts/server.sh ps [agent-id] # procesos con detalle -# ./dev-scripts/server.sh logs [agent-id] # tail -f de logs -# ./dev-scripts/server.sh kill [agent-id] # SIGKILL forzado (emergencia) -# ./dev-scripts/server.sh dashboard # TUI interactivo +# ./dev-scripts/server.sh start # iniciar el launcher +# ./dev-scripts/server.sh stop # detener el launcher +# ./dev-scripts/server.sh restart # reiniciar el launcher +# ./dev-scripts/server.sh status # resumen general del servidor +# ./dev-scripts/server.sh ps # proceso con detalle +# ./dev-scripts/server.sh logs [lines] # tail -f de logs +# ./dev-scripts/server.sh kill # SIGKILL forzado (emergencia) +# ./dev-scripts/server.sh enable # habilitar un agente +# ./dev-scripts/server.sh disable # deshabilitar un agente +# ./dev-scripts/server.sh dashboard # TUI interactivo source "$(dirname "$0")/_common.sh" CMD="${1:-status}" shift || true -AGENT="${1:-}" +ARG="${1:-}" + +toggle_agent_enabled() { + local id="$1" value="$2" + for cfg in agents/*/config.yaml; do + [[ -f "$cfg" ]] || continue + local cid + cid=$(grep -m1 '^ id:' "$cfg" | awk '{print $2}') + if [[ "$cid" == "$id" ]]; then + sed -i "s/^\\( enabled:\\).*/\\1 $value/" "$cfg" + ok "$id enabled: $value" + info "Reinicia el launcher para aplicar: ./dev-scripts/server.sh restart" + return 0 + fi + done + fail "Agente '$id' no encontrado" +} case "$CMD" in start) - exec "$REPO_ROOT/dev-scripts/start.sh" ${AGENT:+"$AGENT"} + exec "$REPO_ROOT/dev-scripts/start.sh" ;; stop) - exec "$REPO_ROOT/dev-scripts/stop.sh" ${AGENT:+"$AGENT"} + exec "$REPO_ROOT/dev-scripts/stop.sh" ;; restart) - exec "$REPO_ROOT/dev-scripts/restart.sh" ${AGENT:+"$AGENT"} + exec "$REPO_ROOT/dev-scripts/restart.sh" ;; ps) - exec "$REPO_ROOT/dev-scripts/ps.sh" ${AGENT:+"$AGENT"} + exec "$REPO_ROOT/dev-scripts/ps.sh" ;; logs) - exec "$REPO_ROOT/dev-scripts/logs.sh" ${AGENT:+"$AGENT"} + exec "$REPO_ROOT/dev-scripts/logs.sh" ${ARG:+"$ARG"} ;; dashboard|tui) exec "$REPO_ROOT/dev-scripts/dashboard.sh" ;; - kill) - # SIGKILL forzado para emergencias - if [[ -n "$AGENT" ]]; then - agents=("$AGENT") - else - agents=() - while IFS='|' read -r id _v _e _d _c; do - agents+=("$id") - done < <(list_agents_raw) - fi + enable) + [[ -n "$ARG" ]] || fail "Uso: $0 enable " + toggle_agent_enabled "$ARG" "true" + ;; - killed=0 - for id in "${agents[@]}"; do - all_pids="$(find_agent_pids "$id")" - if [[ -n "$all_pids" ]]; then - cnt="$(echo "$all_pids" | wc -l)" - for p in $all_pids; do - kill -9 "$p" 2>/dev/null || true - done - rm -f "$(pid_file "$id")" - ok "$id killed ($cnt instance(s), PIDs: $(echo $all_pids | tr '\n' ' '))" - ((killed++)) || true - else - dim " $id (no estaba corriendo)" - fi - done - [[ "$killed" -eq 0 ]] && dim "Ningún proceso eliminado." + disable) + [[ -n "$ARG" ]] || fail "Uso: $0 disable " + toggle_agent_enabled "$ARG" "false" + ;; + + kill) + if ! is_launcher_running; then + dim " El launcher no está corriendo." + exit 0 + fi + pid="$(read_launcher_pid)" + kill -9 "$pid" 2>/dev/null || true + rm -f "$(launcher_pid_file)" + ok "Launcher killed (PID $pid)" ;; status) - # Resumen general del servidor - total=0 - running=0 - stopped=0 - disabled=0 - - while IFS='|' read -r id _version enabled _desc _cfg; do - ((total++)) || true - st=$(agent_status "$id" "$enabled") - case "$st" in - running) ((running++)) || true ;; - stopped) ((stopped++)) || true ;; - disabled) ((disabled++)) || true ;; - esac - done < <(list_agents_raw) - echo "" echo -e " ${BLU}Bot Server Status${RST}" printf '%s\n' " $(printf '─%.0s' {1..40})" - echo -e " Agentes totales: $total" - echo -e " ${GRN}● Running:${RST} $running" - echo -e " ${DIM}○ Stopped:${RST} $stopped" - echo -e " ${YLW} Disabled:${RST} $disabled" + + if is_launcher_running; then + pid="$(read_launcher_pid)" + echo -e " ${GRN}● Launcher running${RST} PID $pid" + else + echo -e " ${DIM}○ Launcher stopped${RST}" + fi + + echo "" + + enabled=0 + disabled=0 + total=0 + while IFS='|' read -r id _v en _d _c; do + ((total++)) || true + if [[ "$en" == "true" ]]; then + ((enabled++)) || true + else + ((disabled++)) || true + fi + done < <(list_agents_raw) + + echo -e " Agentes totales: $total" + echo -e " ${GRN}● Enabled:${RST} $enabled" + echo -e " ${DIM}○ Disabled:${RST} $disabled" echo "" - # Mostrar tabla de agentes "$REPO_ROOT/dev-scripts/list.sh" - # Si hay agentes corriendo, mostrar uso de recursos - if [[ "$running" -gt 0 ]]; then + if is_launcher_running; then echo "" "$REPO_ROOT/dev-scripts/ps.sh" fi ;; *) - echo "Uso: $0 {start|stop|restart|status|ps|logs|kill|dashboard} [agent-id]" + echo "Uso: $0 {start|stop|restart|status|ps|logs|kill|enable|disable|dashboard}" echo "" echo "Comandos:" - echo " start [id] Iniciar uno o todos los agentes habilitados" - echo " stop [id] Detener uno o todos los agentes" - echo " restart [id] Reiniciar uno o todos los agentes" - echo " status Resumen general del servidor" - echo " ps [id] Procesos corriendo con detalle (PID, mem, CPU)" - echo " logs [id] Tail -f de logs" - echo " kill [id] SIGKILL forzado (solo emergencias)" - echo " dashboard TUI interactivo de gestión" + echo " start Iniciar el launcher unificado" + echo " stop Detener el launcher" + echo " restart Reiniciar el launcher" + echo " status Resumen general del servidor" + echo " ps Proceso del launcher con detalle (PID, mem, CPU)" + echo " logs [lines] Tail -f de logs del launcher" + echo " kill SIGKILL forzado (solo emergencias)" + echo " enable Habilitar un agente (requiere restart)" + echo " disable Deshabilitar un agente (requiere restart)" + echo " dashboard TUI interactivo de gestión" exit 1 ;; esac diff --git a/dev-scripts/start.sh b/dev-scripts/start.sh index a3129f4..c6a2c44 100755 --- a/dev-scripts/start.sh +++ b/dev-scripts/start.sh @@ -1,73 +1,51 @@ #!/usr/bin/env bash -# start.sh — inicia uno o todos los agentes habilitados en background +# start.sh — inicia el launcher unificado (todos los agentes habilitados) # # Uso: -# ./dev-scripts/start.sh # inicia todos los habilitados -# ./dev-scripts/start.sh assistant-bot # inicia uno específico +# ./dev-scripts/start.sh # inicia el launcher unificado source "$(dirname "$0")/_common.sh" load_env -TARGET="${1:-}" +if is_launcher_running; then + pid="$(read_launcher_pid)" + fail "El launcher ya está corriendo (PID $pid). Usa restart.sh para reiniciar." +fi -start_agent() { - local id="$1" cfg="$2" - local log; log="$(log_file "$id")" - local pid_f; pid_f="$(pid_file "$id")" - local bin="$REPO_ROOT/bin/launcher" +BIN="$REPO_ROOT/bin/launcher" +LOG="$(launcher_log_file)" +PID_F="$(launcher_pid_file)" - info "Iniciando $id..." +# Build if needed +if [[ ! -x "$BIN" ]] || [[ "$(find ./cmd/launcher -newer "$BIN" 2>/dev/null | head -1)" ]]; then + info "Ejecutando tests..." + "$GO" test -tags goolm ./... || fail "Tests fallaron — corrige antes de compilar" - # Build the binary first to avoid go run wrapper PID issues - if [[ ! -x "$bin" ]] || [[ "$(find ./cmd/launcher -newer "$bin" 2>/dev/null | head -1)" ]]; then - info "Ejecutando tests..." - "$GO" test -tags goolm ./... || { - fail "$id tests fallaron — corrige antes de compilar" - return 1 - } - info "Compilando launcher..." - mkdir -p "$(dirname "$bin")" - "$GO" build -tags goolm -o "$bin" ./cmd/launcher || { - fail "$id error de compilación — revisa el código" - return 1 - } - fi + info "Compilando launcher..." + mkdir -p "$(dirname "$BIN")" + "$GO" build -tags goolm -o "$BIN" ./cmd/launcher || fail "Error de compilación" +fi - # Launch the compiled binary directly (no go run wrapper) - nohup "$bin" -c "$cfg" --log-level "${LOG_LEVEL:-info}" \ - >> "$log" 2>&1 & +info "Iniciando launcher unificado..." - local pid=$! - echo "$pid" > "$pid_f" +nohup "$BIN" --log-level "${LOG_LEVEL:-info}" \ + >> "$LOG" 2>&1 & - # Espera un momento y verifica que el proceso siga vivo - sleep 1 - if kill -0 "$pid" 2>/dev/null; then - local inst; inst="$(count_instances "$id")" - ok "$id PID $pid (instances: $inst) → logs: $log" - else - rm -f "$pid_f" - fail "$id arrancó pero murió — revisa: tail -f $log" - fi -} +pid=$! +echo "$pid" > "$PID_F" -started=0 +sleep 1 +if kill -0 "$pid" 2>/dev/null; then + # Count enabled agents + enabled=0 + total=0 + while IFS='|' read -r _id _v en _d _c; do + ((total++)) || true + [[ "$en" == "true" ]] && ((enabled++)) || true + done < <(list_agents_raw) -while IFS='|' read -r id version enabled desc cfg; do - # Filtrar por TARGET si se especificó uno - [[ -n "$TARGET" && "$id" != "$TARGET" ]] && continue - - if [[ "$enabled" != "true" ]]; then - warn "$id (disabled en config, saltar)" - continue - fi - - start_agent "$id" "$cfg" - ((started++)) || true - -done < <(list_agents_raw) - -[[ "$started" -eq 0 && -z "$TARGET" ]] && warn "Ningún agente iniciado." -[[ -n "$TARGET" && "$started" -eq 0 ]] && fail "Agente '$TARGET' no encontrado o ya está corriendo." - -true + ok "Launcher PID $pid ($enabled/$total agentes habilitados) → logs: $LOG" +else + rm -f "$PID_F" + fail "Launcher arrancó pero murió — revisa: tail -f $LOG" +fi diff --git a/dev-scripts/stop.sh b/dev-scripts/stop.sh index 36907de..29732c6 100755 --- a/dev-scripts/stop.sh +++ b/dev-scripts/stop.sh @@ -1,59 +1,32 @@ #!/usr/bin/env bash -# stop.sh — detiene uno o todos los agentes en ejecución +# stop.sh — detiene el launcher unificado # # Uso: -# ./dev-scripts/stop.sh # detiene todos los que estén corriendo -# ./dev-scripts/stop.sh assistant-bot # detiene uno específico +# ./dev-scripts/stop.sh source "$(dirname "$0")/_common.sh" -TARGET="${1:-}" -stopped=0 +if ! is_launcher_running; then + dim " El launcher no está corriendo." + exit 0 +fi -while IFS='|' read -r id _version _enabled _desc _cfg; do - [[ -n "$TARGET" && "$id" != "$TARGET" ]] && continue +pid="$(read_launcher_pid)" +info "Deteniendo launcher (PID $pid)..." - if ! is_running "$id"; then - dim " $id (no está corriendo)" - continue - fi +kill -TERM "$pid" 2>/dev/null || true - # Kill ALL instances, not just the one in the PID file - all_pids="$(find_agent_pids "$id")" - instance_count="$(echo "$all_pids" | grep -c . 2>/dev/null || echo 0)" +# Wait up to 5s for graceful shutdown +for _ in {1..10}; do + kill -0 "$pid" 2>/dev/null || break + sleep 0.5 +done - if [[ "$instance_count" -gt 1 ]]; then - warn "$id has $instance_count instances running — stopping all" - fi +# SIGKILL if still alive +if kill -0 "$pid" 2>/dev/null; then + warn "Launcher no respondió a SIGTERM, enviando SIGKILL..." + kill -9 "$pid" 2>/dev/null || true +fi - # Send SIGTERM to all instances - for p in $all_pids; do - kill -TERM "$p" 2>/dev/null || true - done - - # Wait up to 5s for graceful shutdown - for _ in {1..10}; do - remaining="$(find_agent_pids "$id")" - [[ -z "$remaining" ]] && break - sleep 0.5 - done - - # SIGKILL any survivors - survivors="$(find_agent_pids "$id")" - if [[ -n "$survivors" ]]; then - warn "$id no respondió a SIGTERM, enviando SIGKILL..." - for p in $survivors; do - kill -9 "$p" 2>/dev/null || true - done - fi - - rm -f "$(pid_file "$id")" - ok "$id detenido ($instance_count instance(s) stopped)" - ((stopped++)) || true - -done < <(list_agents_raw) - -[[ "$stopped" -eq 0 && -z "$TARGET" ]] && dim "Ningún agente estaba corriendo." -[[ -n "$TARGET" && "$stopped" -eq 0 ]] && fail "Agente '$TARGET' no encontrado o no estaba corriendo." - -true +rm -f "$(launcher_pid_file)" +ok "Launcher detenido"