فهرست منبع

feat(agents): first-class external pushers with cadence-aware freshness (#289)

* feat(agents): first-class external pushers with cadence-aware freshness

- payload declares kind (native|external) and interval (push cadence in
  seconds); the registry widens the per-slug freshness window to 3x the
  declared interval so a 5-minute scraper stops reading as down
- agent-down dead man's switch scales its confirmation the same way,
  killing spurious down alerts for slow pushers
- GET /api/agents exposes kind/interval; upgrade-all message counts
  external pushers as skipped; fleet UI badges them (no v-prefix, no
  upgrade affordances)
- deploy/switch-scraper.sh: configurable scraper (env file, 600 perm)
  versioned in the repo; pushes kind=external + interval

Closes #285, closes #288

* fix(scraper): login POST before scraping the KP-9000 web UI

The switch no longer serves data pages to the bare admin=<md5> cookie:
it needs the login form POST (username/password/Response=md5) to open
the session, and the Referer header on subsequent GETs. Without it both
mac.cgi and port.cgi return the login redirect and the push carries an
empty FDB.

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 ماه پیش
والد
کامیت
7d260dedc6

+ 13 - 4
agent/probe/payload.go

@@ -6,10 +6,19 @@ package probe
 
 // Payload es el cuerpo JSON único que el agente empuja cada intervalo.
 type Payload struct {
-	Router  string      `json:"router"`  // slug del equipo (token agent.token.<slug>)
-	Ts      int64       `json:"ts"`      // unix SEGUNDOS de la muestra
-	Version string      `json:"version"` // versión del agente (la muestra GET /api/agents)
-	Data    PayloadData `json:"data"`
+	Router  string `json:"router"`  // slug del equipo (token agent.token.<slug>)
+	Ts      int64  `json:"ts"`      // unix SEGUNDOS de la muestra
+	Version string `json:"version"` // versión del agente (la muestra GET /api/agents)
+	// Kind declara el tipo de pusher (#288): "" y "native" = agente nativo
+	// netpulse-agent; "external" = pusher externo (scraper de un switch
+	// gestionado, integración de terceros). El server lo usa para la UI y
+	// para escalar ventanas de frescura.
+	Kind string `json:"kind,omitempty"`
+	// Interval declara la cadencia de push en SEGUNDOS (#288). 0 = default
+	// del agente nativo (~30 s). Un pusher externo que empuja cada 5 min
+	// declara 300 y el server amplía su TTL a 3x ese intervalo.
+	Interval int           `json:"interval,omitempty"`
+	Data     PayloadData   `json:"data"`
 }
 
 // PayloadData agrupa las secciones del tier rápido. Punteros/mapas nil =

+ 3 - 1
app/public/locales/en/translation.json

@@ -614,7 +614,9 @@
       "copyCmdTip": "Generates the manual install one-liner (fallback for routers without SSH). The token rotates on every generation.",
       "copied": "Command copied",
       "cmdFail": "Could not generate the command",
-      "title": "Agents"
+      "title": "Agents",
+      "external": "External",
+      "externalTip": "External pusher (scraper): pushes every {{interval}} s, no installable agent or upgrades"
     },
     "upgradeUpdatedDetail": "Updated · {{count}} steps · {{secs}} s"
   },

+ 3 - 1
app/public/locales/es/translation.json

@@ -614,7 +614,9 @@
       "copyCmdTip": "Genera el one-liner de instalación manual (fallback para routers sin SSH). El token se rota en cada generación.",
       "copied": "Comando copiado",
       "cmdFail": "No se pudo generar el comando",
-      "title": "Agentes"
+      "title": "Agentes",
+      "external": "Externo",
+      "externalTip": "Pusher externo (scraper): empuja cada {{interval}} s, sin agente instalable ni actualizaciones"
     },
     "upgradeUpdatedDetail": "Actualizado · {{count}} pasos · {{secs}} s"
   },

+ 13 - 1
app/src/components/routers/AgentsSection.tsx

@@ -156,7 +156,19 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
         <span className="font-mono text-caption text-text-secondary">{lastSeen}</span>
       </td>
       <td className="py-3 pr-3">
-        <span className="font-mono text-caption text-text-secondary">{agent?.version ? `v${agent.version}` : '-'}</span>
+        <span className="flex items-center gap-2">
+          <span className="font-mono text-caption text-text-secondary">
+            {agent?.version ? (agent.kind === 'external' ? agent.version : `v${agent.version}`) : '-'}
+          </span>
+          {agent?.kind === 'external' && (
+            <span
+              title={t('routers.agents.externalTip', { interval: agent.interval ?? 0 })}
+              className="inline-flex items-center rounded-full border border-border bg-surface px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-text-muted"
+            >
+              {t('routers.agents.external')}
+            </span>
+          )}
+        </span>
       </td>
       <td className="py-3">
         <div className="flex flex-wrap items-center gap-2">

+ 4 - 0
app/src/data/types.ts

@@ -376,6 +376,10 @@ export interface AgentInfo {
   lastSeen: number | null
   /** Versión del binario netpulse-agent ("" si aún no se conoce) */
   version?: string
+  /** "native" (agente netpulse-agent) o "external" (pusher tipo scraper, #285/#288) */
+  kind?: 'native' | 'external'
+  /** Cadencia de push declarada en segundos (solo externos, #288) */
+  interval?: number
   fresh: boolean
   /**
    * true si el agente reporta una versión distinta de la del binario embebido

+ 16 - 0
deploy/switch-scraper.env.example

@@ -0,0 +1,16 @@
+# switch-scraper.env — configuración del pusher externo de switches
+# gestionados (deploy/switch-scraper.sh). Copiar a
+# /opt/netpulse/switch-scraper.env con permisos 600 (root).
+# El timer systemd debe casar su OnUnitActiveSec con INTERVAL.
+
+# Switch a scrapear (web UI http)
+SWITCH_HOST="192.168.1.6"
+SWITCH_USER="admin"
+SWITCH_PASS="cambia-esta-clave"
+
+# Identidad ante NetPulse (token en /opt/netpulse/<slug>.token)
+AGENT_SLUG="switch16"
+
+# Servidor NetPulse y cadencia de push (segundos)
+NETPULSE_URL="http://127.0.0.1:3000"
+INTERVAL=300

+ 120 - 0
deploy/switch-scraper.sh

@@ -0,0 +1,120 @@
+#!/bin/bash
+# switch-scraper.sh — pusher externo de NetPulse para switches gestionados
+# sin SSH (Keephome KP-9000 y clones con web UI mac.cgi/port.cgi).
+#
+# Extrae la tabla MAC y el estado de bocas de la web del switch y los
+# empuja a POST /api/ingest/agent como pusher EXTERNO (kind=external,
+# #285/#288): sin agente instalable, con cadencia declarada (interval)
+# para que el servidor escale su ventana de frescura.
+#
+# Configuración: fichero env (default /opt/netpulse/switch-scraper.env,
+# permisos 600; ver switch-scraper.env.example). El timer systemd lanza
+# este script cada 5 min; su OnUnitActiveSec debe casar con INTERVAL.
+#
+# Instalación (host de monitorización):
+#   install -m 0755 switch-scraper.sh /opt/netpulse/switch-scraper.sh
+#   install -m 0600 switch-scraper.env /opt/netpulse/switch-scraper.env  # editado
+#   # timer: netpulse-switch-scraper.{service,timer} (OnUnitActiveSec=5min)
+set -euo pipefail
+
+ENV_FILE="${SWITCH_SCRAPER_ENV:-/opt/netpulse/switch-scraper.env}"
+if [ ! -r "$ENV_FILE" ]; then
+    echo "[switch-scraper] ERROR: no se puede leer $ENV_FILE" >&2
+    exit 2
+fi
+# shellcheck source=/dev/null
+. "$ENV_FILE"
+
+: "${SWITCH_HOST:?SWITCH_HOST no definido en $ENV_FILE}"
+: "${SWITCH_USER:?SWITCH_USER no definido en $ENV_FILE}"
+: "${SWITCH_PASS:?SWITCH_PASS no definido en $ENV_FILE}"
+: "${AGENT_SLUG:?AGENT_SLUG no definido en $ENV_FILE}"
+: "${NETPULSE_URL:=http://127.0.0.1:3000}"
+: "${INTERVAL:=300}"
+TOKEN_FILE="${TOKEN_FILE:-/opt/netpulse/${AGENT_SLUG}.token}"
+
+TOKEN="$(cat "$TOKEN_FILE")"
+if [ -z "$TOKEN" ]; then
+    echo "[$AGENT_SLUG] ERROR: token vacío en $TOKEN_FILE" >&2
+    exit 2
+fi
+
+PASS_MD5="$(echo -n "${SWITCH_USER}${SWITCH_PASS}" | md5sum | awk '{print $1}')"
+
+# --- Login: el switch exige POST /login.cgi (user+pass+Response=md5) para
+# abrir sesión; la cookie admin=<md5> sola ya no basta (firmware actual).
+# La sesión persiste mientras se mantenga el Referer en los GET.
+curl -sf -m 10 -o /dev/null -X POST "http://${SWITCH_HOST}/login.cgi" \
+    -d "username=${SWITCH_USER}&password=${SWITCH_PASS}&Response=${PASS_MD5}" \
+    -b "admin=${PASS_MD5}" || {
+    echo "[$AGENT_SLUG] ERROR: login rechazado por el switch" >&2
+    exit 2
+}
+
+# --- Scrapear MAC table ---
+HTML_MAC="$(curl -sf -m 10 -b "admin=$PASS_MD5" -H "Referer: http://${SWITCH_HOST}/" \
+    "http://${SWITCH_HOST}/mac.cgi?page=fwd_tbl" 2>/dev/null)" || {
+    echo "[$AGENT_SLUG] ERROR: no se pudo obtener la MAC table del switch" >&2
+    exit 2
+}
+
+# Parsear: cada fila <tr>...</tr> tiene 4 <td>: No., MAC, VLAN, Type, Port
+# Extraer bloques de fila y sacar MAC (campo 2) + Port (campo 5)
+MACS_JSON="{}"
+if command -v python3 >/dev/null 2>&1; then
+    MACS_JSON=$(python3 -c "
+import re, sys, json
+html = sys.stdin.read()
+rows = re.findall(r'<tr>\s*(.*?)\s*</tr>', html, re.S)
+macs = {}
+for row in rows:
+    cells = re.findall(r'<td[^>]*>(.*?)</td>', row)
+    if len(cells) >= 5:
+        mac = cells[1].strip()
+        port = cells[4].strip()
+        if re.match(r'^[0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5}$', mac) and port.isdigit():
+            macs[mac.upper()] = port
+print(json.dumps(macs))
+" <<< "$HTML_MAC")
+fi
+
+# --- Scrapear port statistics ---
+HTML_PORTS="$(curl -sf -m 10 -b "admin=$PASS_MD5" -H "Referer: http://${SWITCH_HOST}/" \
+    "http://${SWITCH_HOST}/port.cgi?page=stats" 2>/dev/null)" || {
+    echo "[$AGENT_SLUG] ERROR: no se pudo obtener port statistics del switch" >&2
+    exit 2
+}
+
+PORTS_JSON="[]"
+if command -v python3 >/dev/null 2>&1; then
+    PORTS_JSON=$(python3 -c "
+import re, sys, json
+html = sys.stdin.read()
+ports = []
+# Patrones: <td>Port N</td> <td>Enable</td> <td>Link Up/Down</td>
+for m in re.finditer(r'<td>Port\s*(\d+)</td>\s*<td>(\w+)</td>\s*<td>(Link\s+\w+)</td>', html):
+    ports.append({'id': f'lan{m.group(1)}', 'label': f'Port {m.group(1)}', 'up': m.group(3) == 'Link Up'})
+print(json.dumps(ports))
+" <<< "$HTML_PORTS")
+fi
+
+# --- Construir payload y push (pusher externo: kind + interval, #288) ---
+TS="$(date +%s)"
+PAYLOAD="{\"router\":\"${AGENT_SLUG}\",\"ts\":${TS},\"version\":\"scraper-2.0\",\"kind\":\"external\",\"interval\":${INTERVAL},\"data\":{\"fdb\":{\"macs\":${MACS_JSON},\"ports\":${PORTS_JSON}}}}"
+
+SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "$TOKEN" 2>/dev/null | awk '{print $NF}')
+
+HTTP_CODE=$(curl -s -o /tmp/${AGENT_SLUG}-response -w '%{http_code}' -m 10 -X POST "${NETPULSE_URL}/api/ingest/agent" \
+    -H "Content-Type: application/json" \
+    -H "Authorization: Bearer ${TOKEN}" \
+    -H "X-Agent-Signature: ${SIG}" \
+    -d "$PAYLOAD" 2>/dev/null)
+
+if [ "$HTTP_CODE" = "202" ]; then
+    MAC_COUNT=$(echo "$MACS_JSON" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null || echo "?")
+    echo "[$AGENT_SLUG] OK: ${MAC_COUNT} MACs, push 202" >&2
+else
+    RESP=$(cat /tmp/${AGENT_SLUG}-response 2>/dev/null)
+    echo "[$AGENT_SLUG] ERROR: push devolvió ${HTTP_CODE}: ${RESP}" >&2
+    exit 2
+fi

+ 58 - 10
server-go/internal/adapters/agent.go

@@ -23,11 +23,30 @@ import (
 // AgentTTLDefault: 3 intervalos de push de 15 s (default del agente) + margen.
 const AgentTTLDefault = 90 * time.Second
 
+// externalGraceFactor: los pushers externos declaran su cadencia en el
+// payload (Interval, segundos); su ventana efectiva es 3x esa cadencia
+// (#288). Un scraper que empuja cada 5 min declara 300 y queda fresco
+// hasta 15 min, en vez de expirar a los 90 s del default nativo.
+const externalGraceFactor = 3
+
 // AgentState es el último push conocido de un agente.
 type AgentState struct {
 	Payload  *probe.Payload
 	LastSeen time.Time
 	Version  string
+	Kind     string // "" | "native" | "external" (#288)
+	Interval int    // cadencia declarada en segundos; 0 = default nativo
+}
+
+// effectiveTTL devuelve la ventana de frescura del estado: el TTL base, o
+// 3x la cadencia declarada si es mayor (pushers externos lentos, #288).
+func (r *AgentRegistry) effectiveTTL(st *AgentState) time.Duration {
+	if st != nil && st.Interval > 0 {
+		if d := time.Duration(st.Interval*externalGraceFactor) * time.Second; d > r.ttl {
+			return d
+		}
+	}
+	return r.ttl
 }
 
 // AgentRegistry guarda el último payload por slug (thread-safe: lo escribe el
@@ -59,26 +78,48 @@ func (r *AgentRegistry) SetClock(f func() time.Time) {
 func (r *AgentRegistry) Ingest(p *probe.Payload) {
 	r.mu.Lock()
 	defer r.mu.Unlock()
-	r.states[p.Router] = &AgentState{Payload: p, LastSeen: r.now(), Version: p.Version}
+	r.states[p.Router] = &AgentState{
+		Payload: p, LastSeen: r.now(), Version: p.Version,
+		Kind: p.Kind, Interval: p.Interval,
+	}
 }
 
-// Info devuelve last_seen + versión para GET /api/agents (sin exponer el payload).
-func (r *AgentRegistry) Info(slug string) (lastSeen time.Time, version string, ok bool) {
+// Info devuelve last_seen + versión + kind/interval para GET /api/agents
+// (sin exponer el payload).
+func (r *AgentRegistry) Info(slug string) (lastSeen time.Time, version, kind string, interval int, ok bool) {
 	r.mu.Lock()
 	defer r.mu.Unlock()
 	st, found := r.states[slug]
 	if !found {
-		return time.Time{}, "", false
+		return time.Time{}, "", "", 0, false
+	}
+	return st.LastSeen, st.Version, st.Kind, st.Interval, true
+}
+
+// ExternalDownConfirm escala la ventana de confirmación de caída para un
+// pusher externo: max(confirm base, 3x su cadencia declarada) (#288). Con
+// la base a secas, un scraper de 5 min dispararía "agente caído" tras un
+// único push perdido.
+func (r *AgentRegistry) ExternalDownConfirm(slug string, base time.Duration) time.Duration {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	st, ok := r.states[slug]
+	if !ok || st.Interval <= 0 {
+		return base
+	}
+	if d := time.Duration(st.Interval*externalGraceFactor) * time.Second; d > base {
+		return d
 	}
-	return st.LastSeen, st.Version, true
+	return base
 }
 
-// Fresh devuelve el último payload si está dentro del TTL.
+// Fresh devuelve el último payload si está dentro de su ventana de
+// frescura (TTL base o 3x cadencia declarada, #288).
 func (r *AgentRegistry) Fresh(slug string) (*probe.Payload, bool) {
 	r.mu.Lock()
 	defer r.mu.Unlock()
 	st, ok := r.states[slug]
-	if !ok || r.now().Sub(st.LastSeen) > r.ttl {
+	if !ok || r.now().Sub(st.LastSeen) > r.effectiveTTL(st) {
 		return nil, false
 	}
 	return st.Payload, true
@@ -90,7 +131,7 @@ func (r *AgentRegistry) Expired(slug string) bool {
 	r.mu.Lock()
 	defer r.mu.Unlock()
 	st, ok := r.states[slug]
-	return ok && r.now().Sub(st.LastSeen) > r.ttl
+	return ok && r.now().Sub(st.LastSeen) > r.effectiveTTL(st)
 }
 
 // StalePayload devuelve el último payload del slug sin comprobar TTL.
@@ -125,7 +166,7 @@ func (r *AgentRegistry) ActiveCount() int {
 	defer r.mu.Unlock()
 	n := 0
 	for _, st := range r.states {
-		if r.now().Sub(st.LastSeen) <= r.ttl {
+		if r.now().Sub(st.LastSeen) <= r.effectiveTTL(st) {
 			n++
 		}
 	}
@@ -135,10 +176,14 @@ func (r *AgentRegistry) ActiveCount() int {
 // Restore repuebla el estado de un slug desde el almacén persistente
 // (arranque del servidor). No revalida TTL: la expiración la decide el
 // reloj comparando contra el LastSeen restaurado. Sobrescribe cualquier
-// estado previo del slug.
+// estado previo del slug. Los estados persistidos antes de #288 no traen
+// Kind/Interval: se recuperan del payload si están ahí.
 func (r *AgentRegistry) Restore(slug string, st *AgentState) {
 	r.mu.Lock()
 	defer r.mu.Unlock()
+	if st != nil && st.Interval == 0 && st.Payload != nil {
+		st.Kind, st.Interval = st.Payload.Kind, st.Payload.Interval
+	}
 	r.states[slug] = st
 }
 
@@ -231,6 +276,9 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 		if confirm <= 0 {
 			confirm = 3 * time.Minute
 		}
+		// Pushers externos (#288): escalar la confirmación a su cadencia
+		// declarada (3x interval) para no alertar caídas falsas.
+		confirm = reg.ExternalDownConfirm(cfg.ID, confirm)
 		if reg.StaleFor(cfg.ID, confirm) {
 			l.mu.Lock()
 			if !l.agentDown[cfg.ID] {

+ 88 - 0
server-go/internal/adapters/agent_cadence_test.go

@@ -0,0 +1,88 @@
+// agent_cadence_test.go — #288: frescura por cadencia declarada.
+// Un pusher externo que declara Interval=300 (scraper cada 5 min) debe
+// seguir fresco más allá del TTL base de 90 s y su confirmación de caída
+// escala a 3x su cadencia.
+package adapters
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+func TestRegistryExternalCadenceStaysFresh(t *testing.T) {
+	reg := NewAgentRegistry(0)
+	now := time.Now()
+	reg.SetClock(func() time.Time { return now })
+
+	reg.Ingest(&probe.Payload{
+		Router: "switch16", Ts: now.Unix(), Version: "scraper-2.0",
+		Kind: "external", Interval: 300,
+	})
+
+	// A 200 s del último push: fuera del TTL base (90 s) pero dentro de
+	// 3x300 s → sigue fresco (#288).
+	now = now.Add(200 * time.Second)
+	if _, ok := reg.Fresh("switch16"); !ok {
+		t.Fatal("pusher externo con interval=300 debería seguir fresco a los 200 s")
+	}
+	if reg.Expired("switch16") {
+		t.Fatal("no debería estar expirado a los 200 s")
+	}
+
+	// A 3x interval + 1 s: expirado.
+	now = now.Add(15*time.Minute + time.Second)
+	if _, ok := reg.Fresh("switch16"); ok {
+		t.Fatal("debería expirar pasados 3x interval")
+	}
+}
+
+func TestRegistryNativeDefaultUnchanged(t *testing.T) {
+	reg := NewAgentRegistry(0)
+	now := time.Now()
+	reg.SetClock(func() time.Time { return now })
+
+	reg.Ingest(&probe.Payload{Router: "patio", Ts: now.Unix(), Version: "0.1.3"})
+
+	now = now.Add(91 * time.Second)
+	if _, ok := reg.Fresh("patio"); ok {
+		t.Fatal("agente nativo sin interval declarado debe expirar al TTL base")
+	}
+}
+
+func TestRegistryExternalDownConfirmScales(t *testing.T) {
+	reg := NewAgentRegistry(0)
+	now := time.Now()
+	reg.SetClock(func() time.Time { return now })
+
+	reg.Ingest(&probe.Payload{
+		Router: "switch16", Ts: now.Unix(), Version: "scraper-2.0",
+		Kind: "external", Interval: 300,
+	})
+
+	got := reg.ExternalDownConfirm("switch16", 3*time.Minute)
+	if got != 15*time.Minute {
+		t.Fatalf("confirm para externo de 5 min: got %v want 15m", got)
+	}
+	// Sin interval declarado (nativo): la base se respeta tal cual.
+	reg.Ingest(&probe.Payload{Router: "patio", Ts: now.Unix(), Version: "0.1.3"})
+	if got := reg.ExternalDownConfirm("patio", 3*time.Minute); got != 3*time.Minute {
+		t.Fatalf("confirm para nativo: got %v want 3m", got)
+	}
+}
+
+func TestRegistryInfoExposesKindAndInterval(t *testing.T) {
+	reg := NewAgentRegistry(0)
+	now := time.Now()
+	reg.SetClock(func() time.Time { return now })
+
+	reg.Ingest(&probe.Payload{
+		Router: "switch16", Ts: now.Unix(), Version: "scraper-2.0",
+		Kind: "external", Interval: 300,
+	})
+	_, _, kind, interval, ok := reg.Info("switch16")
+	if !ok || kind != "external" || interval != 300 {
+		t.Fatalf("Info: ok=%v kind=%q interval=%d", ok, kind, interval)
+	}
+}

+ 1 - 1
server-go/internal/adapters/agent_live_test.go

@@ -71,7 +71,7 @@ func TestAgentRegistry(t *testing.T) {
 	if !ok || p.Version != "0.1.0" {
 		t.Fatalf("payload fresco esperado: %v %v", ok, p)
 	}
-	seen, ver, ok := reg.Info("patio")
+	seen, ver, _, _, ok := reg.Info("patio")
 	if !ok || ver != "0.1.0" || !seen.Equal(now) {
 		t.Fatalf("Info: %v %q %v", seen, ver, ok)
 	}

+ 14 - 3
server-go/internal/httpapi/agent.go

@@ -361,6 +361,11 @@ type agentListItem struct {
 	// swapping/restarting/failed) con su marca de tiempo. null si no hay
 	// actividad reciente (#284: progreso en vivo para la UI).
 	Upgrade *agentUpgradeInfo `json:"upgrade,omitempty"`
+	// Kind: "native" (agente netpulse-agent) o "external" (pusher externo
+	// tipo scraper de switch gestionado, #285/#288). Default "native".
+	Kind string `json:"kind"`
+	// Interval: cadencia de push declarada en segundos (solo externos, #288).
+	Interval int `json:"interval,omitempty"`
 }
 
 // agentUpgradeStep es un paso de la historia (timeline de la UI, #284).
@@ -431,10 +436,16 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 				slug := strings.TrimPrefix(key, agentTokenKeyPrefix)
 				item := agentListItem{Slug: slug}
 				if s.agents != nil {
-					if seen, version, ok := s.agents.Info(slug); ok {
+					if seen, version, kind, interval, ok := s.agents.Info(slug); ok {
 						ts := seen.Unix()
 						item.LastSeen = &ts
 						item.Version = version
+						if kind == "external" {
+							item.Kind = "external"
+						} else {
+							item.Kind = "native"
+						}
+						item.Interval = interval
 						// Fase 6.3 (issue #243): upgrade disponible si el agente
 						// reporta una versión distinta del binario embebido y es
 						// un agente nativo OpenWrt (no un scraper).
@@ -608,7 +619,7 @@ func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
 	before := time.Now()
 	var prevSeen time.Time
 	if s.agents != nil {
-		if seen, _, ok := s.agents.Info(slug); ok {
+		if seen, _, _, _, ok := s.agents.Info(slug); ok {
 			prevSeen = seen
 		}
 	}
@@ -626,7 +637,7 @@ func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
 		if s.agents == nil {
 			break
 		}
-		if seen, _, ok := s.agents.Info(slug); ok && seen.After(prevSeen) && seen.After(before.Add(-5*time.Second)) {
+		if seen, _, _, _, ok := s.agents.Info(slug); ok && seen.After(prevSeen) && seen.After(before.Add(-5*time.Second)) {
 			recovered = true
 			break
 		}

+ 2 - 2
server-go/internal/httpapi/agent_api_test.go

@@ -154,7 +154,7 @@ func TestIngestTokenValidoEInvalido(t *testing.T) {
 	if res.StatusCode != 202 {
 		t.Fatalf("ingest válido: %d", res.StatusCode)
 	}
-	if _, version, ok := ts.agents.Info("patio"); !ok || version != "0.1.0" {
+	if _, version, _, _, ok := ts.agents.Info("patio"); !ok || version != "0.1.0" {
 		t.Fatalf("registry no actualizado: %v %q", ok, version)
 	}
 	// Token inválido → 401; sin token → 401; token de otro slug → 401
@@ -338,7 +338,7 @@ func TestAgentStatePersistenciaYRestauracion(t *testing.T) {
 	reg2 := adapters.NewAgentRegistry(90 * time.Second)
 	httpapi.NewStateRestorer(ts.db)(reg2)
 
-	_, version, ok := reg2.Info("patio")
+	_, version, _, _, ok := reg2.Info("patio")
 	if !ok {
 		t.Fatal("estado no restaurado tras reinicio")
 	}

+ 1 - 1
server-go/internal/httpapi/demoreadonly_test.go

@@ -160,7 +160,7 @@ func TestIngestAgentNoOpEnDemo(t *testing.T) {
 	}
 
 	// No-op: el registry NO debe haber ingerido el payload
-	if _, _, ok := ts.agents.Info("patio"); ok {
+	if _, _, _, _, ok := ts.agents.Info("patio"); ok {
 		t.Fatal("en demo el registry NO debe actualizarse")
 	}
 	// No-op: tampoco debe persistirse el estado del agente en kv

+ 10 - 4
server-go/internal/httpapi/upgrade.go

@@ -317,7 +317,7 @@ func (s *server) handleAgentsUpgradeAll(w http.ResponseWriter, r *http.Request)
 	for _, slug := range slugs {
 		item := upgradeAllItem{Slug: slug}
 		if s.agents != nil {
-			if _, version, ok := s.agents.Info(slug); ok {
+			if _, version, _, _, ok := s.agents.Info(slug); ok {
 				item.Version = version
 				// Solo agentes nativos OpenWrt: los de type managed-switch/
 				// external son scrapers que no entienden el comando "upgrade".
@@ -340,17 +340,23 @@ func (s *server) handleAgentsUpgradeAll(w http.ResponseWriter, r *http.Request)
 		}
 		out = append(out, item)
 	}
-	queued := 0
+	queued, external := 0, 0
 	for _, it := range out {
-		if it.Status == "queued" {
+		switch it.Status {
+		case "queued":
 			queued++
+		case "not_openwrt":
+			external++
 		}
 	}
-	log.Printf("[netpulse] upgrade-all: %d/%d enviados, %d en cola", sent, len(out), queued)
+	log.Printf("[netpulse] upgrade-all: %d/%d enviados, %d en cola, %d externos", sent, len(out), queued, external)
 	msg := fmt.Sprintf("upgrade enviado a %d de %d agentes", sent, len(out))
 	if queued > 0 {
 		msg += fmt.Sprintf(", %d en cola hasta que conecten", queued)
 	}
+	if external > 0 {
+		msg += fmt.Sprintf(", %d externos sin acción", external)
+	}
 	writeJSON(w, http.StatusOK, map[string]any{
 		"agents":  out,
 		"sent":    sent,

+ 2 - 2
server-go/internal/rearmer/rearmer.go

@@ -161,7 +161,7 @@ func (r *Rearmer) Rearm(slug string) (Result, error) {
 	// Marcar el lastSeen previo para saber si el push que llega es NUEVO.
 	var prevSeen time.Time
 	if r.agents != nil {
-		if seen, _, ok := r.agents.Info(slug); ok {
+		if seen, _, _, _, ok := r.agents.Info(slug); ok {
 			prevSeen = seen
 		}
 	}
@@ -182,7 +182,7 @@ func (r *Rearmer) Rearm(slug string) (Result, error) {
 		if r.agents == nil {
 			break
 		}
-		if seen, _, ok := r.agents.Info(slug); ok && seen.After(prevSeen) && seen.After(before.Add(-5*time.Second)) {
+		if seen, _, _, _, ok := r.agents.Info(slug); ok && seen.After(prevSeen) && seen.After(before.Add(-5*time.Second)) {
 			recovered = true
 			break
 		}