Volver al índice

src/main/java/ar/com/companeros/runtime/AgentRuntime.java

package ar.com.companeros.runtime;

import ar.com.companeros.action.ToolResult;
import ar.com.companeros.body.PlayerSessions;
import ar.com.companeros.decision.*;
import ar.com.companeros.identity.*;
import ar.com.companeros.memory.*;
import ar.com.companeros.social.AgentInbox;
import ar.com.companeros.tools.*;
import ar.com.companeros.world.*;
import com.google.gson.*;
import com.mojang.logging.LogUtils;
import java.util.*;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.*;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.living.LivingDamageEvent;
import net.minecraftforge.event.server.*;
import net.minecraftforge.fml.loading.FMLPaths;

/** Percepción → decisión → plan → herramientas → resultados. No contiene un guion de vida. */
public final class AgentRuntime implements AutoCloseable {
    private static final Map<MinecraftServer, AgentRuntime> SERVERS = new WeakHashMap<>();
    private static final Set<ToolPermission> PERMISSIONS = Set.copyOf(EnumSet.allOf(ToolPermission.class));
    private static boolean installed;
    private final MinecraftServer server;
    private final AgentConfig config;
    private final ToolRegistry tools;
    private final ToolLearningService learning;
    private final DecisionGateway gateway;
    private final ParasiteReasoning parasiteReasoning;
    private final String operatorInstructions;
    private final PersistentMemoryArchive archive;
    private final java.util.concurrent.ThreadPoolExecutor archiveWriter = new java.util.concurrent.ThreadPoolExecutor(
        1, 1, 0, java.util.concurrent.TimeUnit.MILLISECONDS, new java.util.concurrent.ArrayBlockingQueue<>(1), runnable -> {
            Thread thread = new Thread(runnable, "raps-memory"); thread.setDaemon(true); return thread;
        });
    private final Map<UUID, Mind> minds = new HashMap<>();
    private final ContactInterpretation.PeaceSignals peaceSignals = new ContactInterpretation.PeaceSignals();
    private final LinkedHashMap<UUID, AgentIdentity> pendingConnections = new LinkedHashMap<>();
    private final Map<String, Long> operationalNotices = new HashMap<>();
    private boolean waitingForAccountRetry;
    private boolean accountCheckPending;
    private long nextAccountCheckMillis;
    private long nextJoinTick;
    private boolean closed;
    private static final class Mind {
        long epoch = 1, seq, lastDecisionTick = -1200, lastProgressTick;
        long nextDecisionTick, lastHumanOrder = -1;
        int idleDecisions;
        long lastNightCycle = Long.MIN_VALUE;
        UUID conversationPartner;
        long conversationAt = -12000, lastObservedCombatEvent, lastCompanionReactionTick = -1200;
        Set<UUID> nearbyHumans = Set.of();
        Set<UUID> nearbyThreats = Set.of();
        UUID damageSource;
        long damagedAt = -1200, nextDefenseTick;
        long attentionAt = -1200;
        UUID peaceSource, attentionSource;
        long peaceAt = -1200;
        final Map<UUID, Long> humanContacts = new HashMap<>();
        ServerPlayer body;
        String dimension = "";
        ToolExecution execution;
        PlayerOperations.Operation survivalMeal;
        long nextMealTick;
        final ArrayDeque<ToolDecision.Step> plan = new ArrayDeque<>();
        final ArrayDeque<String> recent = new ArrayDeque<>();
        final DecisionProgress decisionProgress = new DecisionProgress();
        final FailedActions failedActions = new FailedActions();
        String actionConditions = "";
        final ar.com.companeros.decision.DecisionRetry decisionRetry = new ar.com.companeros.decision.DecisionRetry();
        String goal, trigger = "INITIAL_OBSERVATION", activity = "Evaluando entorno", failedFingerprint = "";
        String pendingReplanReason = "";
        long lastAdminOrder = -1;
        long lastPrivateOrder = -1;
        String currentFingerprint = "";
        String webQuery = "";
        int repeatedFailure;
        float observedHealth = -1;
        int observedHunger = -1;
        double progress;
        boolean pending;
        java.util.concurrent.CompletableFuture<List<String>> notebookLoad;
        Mind(String goal) { this.goal = goal; }
    }
    private AgentRuntime(MinecraftServer server) throws java.io.IOException {
        this.server = server;
        config = AgentConfig.load(FMLPaths.CONFIGDIR.get());
        Perception.configureVision(server, config.visionRadiusBlocks());
        operatorInstructions = AgentInstructions.load(FMLPaths.CONFIGDIR.get().resolve("raps"));
        archive = new PersistentMemoryArchive(FMLPaths.CONFIGDIR.get().resolve("raps").resolve("memory"));
        tools = new ToolRegistry(FMLPaths.CONFIGDIR.get().resolve("raps").resolve("Tools"));
        new ar.com.companeros.suggestions.SuggestionStore(FMLPaths.CONFIGDIR.get().resolve("raps/Suggestions"));
        BuiltinTools.install(tools); learning = new ToolLearningService(tools);
        BuiltinTools.installRequestedTools(tools, learning);
        var providerConfig = config.decisionConfig();
        java.util.function.Supplier<String> credential = providerConfig.enabled()
            ? new ApiCredential(FMLPaths.CONFIGDIR.get().resolve("raps")) : () -> "";
        gateway = new DecisionGateway(providerConfig, credential, new StrategicGate(providerConfig.solEnabled()),
            BudgetLedger.file(FMLPaths.CONFIGDIR.get().resolve("raps/budget.json")));
        // El operador puede elegir cuota promocional o facturación sin tope local.
        // Una fecha promocional anterior no bloquea el segundo modo.
        if (providerConfig.budgetLimitEnabled())
            gateway.installPromotionQuota(PromotionQuota.load(FMLPaths.CONFIGDIR.get().resolve("raps/promotion.json")));
        String providerBlock = gateway.unavailableReason();
        if (providerBlock.startsWith("PROMOTION_")) LogUtils.getLogger().warn("Raps IA: {}", providerBlock);
        parasiteReasoning = new ParasiteReasoning(server, gateway, providerConfig, archive);
    }

    // Vida del servicio: el banco de GameTests controla sus propios fixtures.
    public static synchronized void install() {
        if (installed) return; installed = true;
        ObservedCombat.install();
        MinecraftForge.EVENT_BUS.addListener(AgentRuntime::started);
        MinecraftForge.EVENT_BUS.addListener(AgentRuntime::tick);
        MinecraftForge.EVENT_BUS.addListener(AgentRuntime::stopping);
        MinecraftForge.EVENT_BUS.addListener(AgentRuntime::death);
        MinecraftForge.EVENT_BUS.addListener(AgentRuntime::damaged);
        MinecraftForge.EVENT_BUS.addListener(AgentRuntime::auditAdmissionCommand);
    }
    // Diagnóstico de expulsiones externas: registrar sólo órdenes de admisión, sin otros argumentos.
    private static void auditAdmissionCommand(net.minecraftforge.event.CommandEvent event) {
        String command = event.getParseResults().getReader().getString().strip();
        String root = command.split("\\s+", 2)[0].toLowerCase(java.util.Locale.ROOT);
        root = root.substring(root.indexOf(':') + 1);
        if (!Set.of("kick", "whitelist").contains(root)) return;
        var source = event.getParseResults().getContext().getSource();
        String origin = StackWalker.getInstance().walk(frames -> frames.limit(10)
            .map(frame -> frame.getClassName() + "." + frame.getMethodName())
            .collect(java.util.stream.Collectors.joining(" <- ")));
        LogUtils.getLogger().warn("Raps admisión orden={} fuente={} entidad={} origen={}",
            command, source.getTextName(), source.getEntity() == null ? "console" : source.getEntity().getUUID(), origin);
    }
    private static void started(ServerStartedEvent event) {
        if (event.getServer() instanceof net.minecraft.gametest.framework.GameTestServer) return;
        AgentRuntime runtime;
        try { runtime = get(event.getServer()); }
        catch (RuntimeException failure) {
            LogUtils.getLogger().error("No se pudo iniciar el controlador de agentes; revisá config/raps", failure);
            return;
        }
        for (AgentIdentity identity : AgentRegistry.get(runtime.server).entries())
            AgentNotebooks.run(identity.id(), identity.name(), "init", "", "", "", 0, "")
                .exceptionally(failure -> { LogUtils.getLogger().warn("No se pudo preparar el cuaderno de {}", identity.name()); return List.of(); });
        if (runtime.config.autoConnect()) for (AgentIdentity identity : AgentRegistry.get(runtime.server).entries()) {
            if (identity.autoLogin()) try { runtime.enqueueConnection(identity); }
            catch (RuntimeException failure) { LogUtils.getLogger().warn("No se pudo conectar al agente {}: {}", identity.name(), failure.getMessage()); }
        }
    }
    public static java.util.concurrent.CompletionStage<DecisionResponse> appraiseUpgrade(MinecraftServer server, DecisionRequest request) {
        if (!server.isSameThread() || request.kind() != DecisionRequest.Kind.UPGRADE_APPRAISAL)
            throw new IllegalArgumentException("La tasación pertenece al servicio del servidor");
        DecisionGateway gateway = get(server).gateway;
        gateway.updateSession(request.actorUUID(), request.sessionEpoch(), request.observationSeq());
        return gateway.decide(request);
    }
    private static AgentRuntime get(MinecraftServer server) {
        if (!server.isSameThread()) throw new IllegalStateException("El runtime exige el hilo del servidor");
        AgentRuntime current = SERVERS.get(server);
        if (current == null) try { current = new AgentRuntime(server); SERVERS.put(server, current); }
        catch (java.io.IOException failure) { throw new IllegalStateException("No se pudo cargar la biblioteca de herramientas", failure); }
        return current;
    }
    private static void stopping(ServerStoppingEvent event) {
        AgentRuntime runtime = SERVERS.remove(event.getServer()); if (runtime != null) runtime.close();
    }
    private static void tick(TickEvent.ServerTickEvent event) {
        if (event.phase != TickEvent.Phase.END) return;
        AgentRuntime runtime = SERVERS.get(event.getServer()); if (runtime == null || runtime.closed) return;
        if (runtime.gateway.disabled() || runtime.gateway.budgetExhausted()) {
            runtime.disconnectAutonomous(runtime.gateway.budgetExhausted() ? "API_BUDGET_EXHAUSTED"
                : "API_UNAVAILABLE:" + runtime.gateway.unavailableReason());
            if (runtime.gateway.accountRetryAtMillis() > 0) runtime.waitingForAccountRetry = true;
        } else if (runtime.waitingForAccountRetry && !runtime.accountCheckPending
                && System.currentTimeMillis() >= runtime.nextAccountCheckMillis) {
            runtime.accountCheckPending = true;
            runtime.nextAccountCheckMillis = System.currentTimeMillis() + 5 * 60_000L;
            runtime.gateway.checkAvailability().whenComplete((available, failure) -> runtime.server.execute(() -> {
                runtime.accountCheckPending = false;
                if (runtime.closed) return;
                if (failure == null && Boolean.TRUE.equals(available)) {
                    runtime.waitingForAccountRetry = false;
                    runtime.notifyAdministrators("api-access-restored", "La API volvió a responder. Los bots ya pueden conectarse.");
                }
            }));
        }
        runtime.advanceConnections();
        for (AgentIdentity identity : AgentRegistry.get(runtime.server).entries()) {
            if (identity.state() != AgentState.ACTIVE) continue;
            ServerPlayer body = PlayerSessions.find(runtime.server, identity.id()); if (body == null) continue;
            try { runtime.advance(identity, body); }
            catch (RuntimeException failure) {
                LogUtils.getLogger().error("Se pausó el controlador de {}", identity.name(), failure);
                Mind mind = runtime.minds.get(identity.id()); if (mind != null) runtime.invalidate(identity.id(), mind, "CONTROLLER_ERROR");
                AgentRegistry.get(runtime.server).markState(identity.id(), AgentState.PAUSED);
                // Un controlador roto no deja al jugador inmóvil y vulnerable en el mundo.
                PlayerSessions.remove(runtime.server, identity.id());
            }
        }
        runtime.advanceParasite();
        if (runtime.server.getTickCount() % 1200 == 0) try { runtime.tools.saveStatistics(); runtime.learning.save(); runtime.queueMemories(); }
        catch (java.io.IOException failure) { LogUtils.getLogger().warn("No se pudo guardar estadísticas de herramientas", failure); }
    }

    // Un tick local sigue el plan. La observación para el modelo sólo se prepara por eventos y cupo.
    private void advanceParasite() {
        if (waitingForAccountRetry) return;
        try { parasiteReasoning.tick(); }
        catch (RuntimeException failure) { LogUtils.getLogger().error("No se pudo evaluar la intención del parásito", failure); }
    }
    private void advance(AgentIdentity identity, ServerPlayer body) {
        Mind mind = minds.computeIfAbsent(identity.id(), id -> new Mind(AgentJournal.get(server).entry(id).goal()));
        if (mind.body != body) { invalidate(identity.id(), mind, "BODY_CHANGED"); mind.body = body; }
        String dimension = body.level().dimension().location().toString();
        if (!mind.dimension.equals(dimension)) { invalidate(identity.id(), mind, "DIMENSION_CHANGED"); mind.dimension = dimension; }
        if (!body.isAlive()) return;
        long tick = server.getTickCount();
        // Un gesto rápido requiere observar posturas cada tick; no genera consultas por cada postura.
        observePeaceGesture(identity.id(), body, mind, tick);
        // Contrarrestar un golpe real al alcance no espera una respuesta remota.
        // Luna conserva la elección de perseguir, combatir a distancia o retirarse.
        if (identity.mode().equals("autonomo") && tick >= mind.nextDefenseTick && tick - mind.damagedAt <= 200
                && mind.damageSource != null && (mind.execution == null || !Set.of("attack", "combat_entity", "hunt_entity").contains(mind.execution.activePrimitiveId()))) {
            var aggressor = body.serverLevel().getEntity(mind.damageSource);
            if (aggressor != null && aggressor.isAlive() && body.distanceToSqr(aggressor) <= 9
                    && Perception.canSee(body, aggressor) && body.getAttackStrengthScale(0) >= .95) {
                ToolResult reaction = PlayerOperations.attack(body, UUID.randomUUID(), aggressor.getUUID()).tick(tick);
                mind.nextDefenseTick = tick + 20;
                if (reaction.finished()) {
                    remember(mind, "self_defense " + reaction.status() + " " + reaction.reason() + " " + String.join(" ", reaction.actualEffects()));
                    LogUtils.getLogger().info("Raps defensa jugador={} objetivo={} estado={} motivo={}", identity.name(),
                        aggressor.getUUID(), reaction.status(), reaction.reason());
                }
            }
        }
        if (tick % 20 == 0) {
            observeCompanionCombat(identity.id(), body, mind, tick);
            long worldTime = body.serverLevel().getDayTime(), phase = Math.floorMod(worldTime, 24000), day = Math.floorDiv(worldTime, 24000);
            if (body.serverLevel().dimensionType().hasSkyLight() && phase >= 12000 && phase < 23000 && mind.lastNightCycle != day) {
                mind.lastNightCycle = day;
                remember(mind, "night_shelter_priority=true choose_known_base_or_temporary_closed_shelter; exposed_waiting_is_not_a_plan; if_already_sheltered_work_or_rest=true");
                if (mind.execution == null || !Set.of("attack", "combat_entity", "hunt_entity", "eat").contains(mind.execution.activePrimitiveId()))
                    invalidate(identity.id(), mind, "NIGHT_SURVIVAL_REPLAN");
                else { mind.nextDecisionTick = 0; mind.idleDecisions = 0; }
            }
            EquipmentMaintenance.equip(body).forEach(effect -> remember(mind, effect));
            Set<UUID> nearby = body.serverLevel().getEntitiesOfClass(ServerPlayer.class,
                body.getBoundingBox().inflate(4), other -> other != body && !AgentRegistry.get(server).isAgent(other.getUUID())
                    && other.isAlive() && body.hasLineOfSight(other)).stream().map(ServerPlayer::getUUID)
                    .collect(java.util.stream.Collectors.toSet());
            if (!mind.nearbyHumans.containsAll(nearby)) { mind.nextDecisionTick = 0; mind.idleDecisions = 0; }
            mind.nearbyHumans = Set.copyOf(nearby);
            observeSurvivalSignals(identity.id(), body, mind, tick);
            // Un pedido dirigido corrige también una decisión pendiente; una charla ajena no despierta al agente.
            reconsiderMessages(identity.id(), mind);
            if (mind.execution != null && !Set.of("attack", "combat_entity", "hunt_entity", "eat").contains(mind.execution.activePrimitiveId())
                    && body.getHealth() <= 8 && !body.serverLevel().getEntitiesOfClass(Monster.class,
                    body.getBoundingBox().inflate(6), monster -> monster.isAlive() && !(monster instanceof ar.com.companeros.horror.ParasiteEntity)
                        && ThreatAssessment.assess(body, monster).immediate()).isEmpty())
                invalidate(identity.id(), mind, "DANGER_LOW_HEALTH");
        }
        // Comer no espera a terminar una herramienta de diez minutos ni necesita otra llamada a IA.
        if (mind.survivalMeal == null && mind.execution != null && tick >= mind.nextMealTick
                && body.getFoodData().getFoodLevel() <= 12
                && !Set.of("attack", "combat_entity", "hunt_entity", "eat").contains(mind.execution.activePrimitiveId())
                && PlayerOperations.find(body, stack -> stack.isEdible()
                    && !stack.is(net.minecraft.world.item.Items.ROTTEN_FLESH)
                    && !stack.is(net.minecraft.world.item.Items.PUFFERFISH)
                    && !stack.is(net.minecraft.world.item.Items.SPIDER_EYE)
                    && !stack.is(net.minecraft.world.item.Items.POISONOUS_POTATO)) >= 0)
            mind.survivalMeal = PlayerOperations.eat(body, UUID.randomUUID());
        if (mind.survivalMeal != null) {
            PlayerSessions.setMovementIntent(server, identity.id(), 0, 0, false);
            body.setSprinting(false);
            ToolResult meal = mind.survivalMeal.tick(tick);
            if (meal.finished()) {
                remember(mind, "local_meal " + meal.status() + " " + meal.reason());
                mind.survivalMeal = null; mind.nextMealTick = tick + 40; mind.lastProgressTick = tick;
            }
            return;
        }
        if (mind.execution != null) {
            ToolExecution.Status status = mind.execution.tick(tick);
            if (status == ToolExecution.Status.RUNNING) {
                if (mind.execution.progress() > mind.progress) { mind.progress = mind.execution.progress(); mind.lastProgressTick = tick; }
                if (tick - mind.lastProgressTick >= 2400) invalidate(identity.id(), mind, "NO_PROGRESS");
                return;
            }
            String outcome = mind.execution.toolId() + ":" + status + ":" + mind.execution.failureReason()
                + " " + mind.execution.summary();
            remember(mind, outcome);
            if (status == ToolExecution.Status.SUCCEEDED) {
                if (physicalAction(mind.execution.toolId())) {
                    mind.failedActions.succeeded(mind.currentFingerprint);
                    mind.repeatedFailure = 0; mind.failedFingerprint = "";
                }
            }
            else {
                if (physicalAction(mind.execution.toolId()))
                    mind.failedActions.failed(mind.currentFingerprint, mind.actionConditions, tick);
                mind.repeatedFailure = mind.failedFingerprint.equals(mind.currentFingerprint) ? mind.repeatedFailure + 1 : 1;
                mind.failedFingerprint = mind.currentFingerprint;
                // Un chat rechazado por cadencia no cancela caminar, minar o defenderse después.
                // No tener comida o no ver un drop no invalida explorar/minar después de ese paso opcional.
                if (!Set.of("message_global", "message_internal", "eat", "collect", "collect_area", "equip_armor").contains(mind.execution.toolId())) mind.plan.clear();
                mind.trigger = "ACTION_FAILED_RECONSIDER";
                if (mind.repeatedFailure >= 2 && mind.plan.isEmpty())
                    mind.nextDecisionTick = tick + Math.min(30, 2L << Math.min(4, mind.repeatedFailure - 2)) * 20;
            }
            mind.execution = null;
            AgentJournal.get(server).checkpoint(identity.id(), mind.goal, outcome, mind.repeatedFailure, false);
        }
        // Reflejos breves no eligen proyectos: comer un alimento que ya se posee.
        if (body.getFoodData().getFoodLevel() <= 12 && PlayerOperations.find(body,
                stack -> stack.isEdible() && !stack.is(net.minecraft.world.item.Items.ROTTEN_FLESH)
                    && !stack.is(net.minecraft.world.item.Items.PUFFERFISH) && !stack.is(net.minecraft.world.item.Items.SPIDER_EYE)
                    && !stack.is(net.minecraft.world.item.Items.POISONOUS_POTATO)) >= 0) {
            start(identity.id(), mind, new ToolDecision.Step("eat", 1, Map.of())); return;
        }
        // Una amenaza visible cercana interrumpe el trabajo antes de replantearlo.
        if (tick % 20 == 0 && body.getHealth() <= 8 && !body.serverLevel().getEntitiesOfClass(Monster.class,
                body.getBoundingBox().inflate(6), monster -> monster.isAlive() && !(monster instanceof ar.com.companeros.horror.ParasiteEntity)
                    && ThreatAssessment.assess(body, monster).immediate()).isEmpty()) {
            mind.plan.clear(); mind.trigger = "DANGER_LOW_HEALTH";
        }
        if (!identity.mode().equals("autonomo")) { mind.activity = "En pausa"; return; }
        if (!mind.plan.isEmpty()) { start(identity.id(), mind, mind.plan.removeFirst()); return; }
        if (gateway.disabled()) { mind.activity = "Esperando decisión"; return; }
        // Leer sólo la cabecera de su cuaderno al conectarse, sin bloquear disco ni enviar todo el archivo.
        if (mind.notebookLoad != null) {
            if (!mind.notebookLoad.isDone()) { mind.activity = "Recuperando contexto"; return; }
            try { mind.notebookLoad.join().forEach(row -> remember(mind, row)); }
            catch (java.util.concurrent.CompletionException | java.util.concurrent.CancellationException ignored) {
                remember(mind, "notebook_unavailable; persistent_world_memory_remains_available=true");
            }
            mind.notebookLoad = null;
        }
        if (mind.pending || !mind.decisionRetry.ready(tick) || tick < mind.nextDecisionTick || tick - mind.lastDecisionTick < config.decisionConfig().minAgentIntervalSeconds() * 20L) return;
        request(identity, body, mind);
    }
    // Los éxitos administrativos no demuestran movimiento, recolección ni construcción.
    private static boolean physicalAction(String tool) {
        return Set.of("move_to", "move_relative", "follow_entity", "explore_area", "mine_tunnel",
            "harvest_block", "mine_block", "place_block", "build_at", "build_plan", "pillar_up",
            "dig_down_step", "craft_chain", "smelt", "accessory", "backpack", "container_take", "quick_cover").contains(tool);
    }
    private String physicalConditions(UUID id, String action) {
        ServerPlayer body = PlayerSessions.find(server, id);
        if (body == null) return "no_body";
        return body.level().dimension().location() + ":" + body.blockPosition().toShortString()
            + ":" + new TreeMap<>(PlayerCrafting.counts(body)) + ":risk=" + AgentKnowledge.get(server).riskRevision(id, action);
    }
    private void start(UUID id, Mind mind, ToolDecision.Step step) {
        String fingerprint = step.toolId() + ":" + step.version() + ":" + new TreeMap<>(step.arguments());
        String conditions = physicalConditions(id, step.toolId());
        if (physicalAction(step.toolId()) && mind.failedActions.blocked(fingerprint, conditions, server.getTickCount())) {
            mind.plan.clear(); mind.trigger = "REPEATED_FAILURE_REQUIRE_NEW_STRATEGY";
            mind.nextDecisionTick = server.getTickCount() + 30 * 20L;
            remember(mind, "Tres fallos de la misma acción: elegir otra estrategia o volver a verificar condiciones."); return;
        }
        JsonObject inputs = inputs(step.arguments()); defaults(step.toolId(), inputs);
        try {
            if (!AgentRoles.get(server).allows(id, step.toolId())) {
                mind.plan.clear(); remember(mind, "El rol actual delega esa tarea a otro compañero."); return;
            }
            mind.execution = startExecution(id, step.toolId(), step.version(), inputs, result -> {
                    LogUtils.getLogger().info("Raps acción jugador={} herramienta={} estado={} motivo={} efectos={}",
                        id, step.toolId(), result.status(), result.reason(), result.actualEffects());
                    rememberToolResult(mind, step.toolId(), result);
                    for (String effect : result.actualEffects()) if (effect.startsWith("web_query:")) {
                        mind.webQuery = effect.substring("web_query:".length()); mind.plan.clear();
                    }
                });
        } catch (IllegalArgumentException rejected) {
            mind.plan.clear(); mind.trigger = "INVALID_TOOL_ARGUMENT_RECONSIDER";
            mind.repeatedFailure = mind.failedFingerprint.equals(fingerprint) ? mind.repeatedFailure + 1 : 1;
            mind.failedFingerprint = fingerprint;
            remember(mind, "Argumentos rechazados " + step.toolId() + ": " + rejected.getMessage());
            LogUtils.getLogger().warn("Raps acción rechazada jugador={} herramienta={} motivo={}", id, step.toolId(), rejected.getMessage());
            return;
        }
        mind.currentFingerprint = fingerprint; mind.actionConditions = conditions;
        mind.activity = step.toolId(); mind.progress = 0; mind.lastProgressTick = server.getTickCount();
        AgentJournal.get(server).checkpoint(id, mind.goal, "RUNNING:" + step.toolId(), mind.repeatedFailure, true);
    }

    // Sólo despierta ante daño PRESENCIADO a alguien seguido, del equipo o del diálogo actual.
    // La confianza y la respuesta (defender, cubrir, retirarse juntos...) siguen siendo decisiones.
    private void observeCompanionCombat(UUID actor, ServerPlayer body, Mind mind, long tick) {
        UUID followed = null;
        if (mind.execution != null && mind.execution.activePrimitiveId().equals("follow_entity")) {
            JsonObject args = mind.execution.activeArguments();
            if (args.has("target")) try { followed = UUID.fromString(args.get("target").getAsString()); }
            catch (IllegalArgumentException ignored) { }
        }
        for (ObservedCombat.Incident incident : ObservedCombat.recent(body)) {
            if (incident.sequence() <= mind.lastObservedCombatEvent) continue;
            mind.lastObservedCombatEvent = incident.sequence();
            var victim = body.serverLevel().getEntity(incident.victimId());
            boolean associated = incident.victimId().equals(followed)
                || incident.victimId().equals(mind.conversationPartner) && tick - mind.conversationAt <= 12000
                || victim != null && body.getTeam() != null && body.isAlliedTo(victim);
            if (!associated) continue;
            remember(mind, "companion_under_attack " + incident.compact(body)
                + " consider_help_cover_or_retreat_together=true; association_does_not_prove_trust=true");
            mind.nextDecisionTick = 0; mind.idleDecisions = 0;
            if (!mind.pending && tick - mind.lastCompanionReactionTick >= 100
                    && (mind.execution == null || !Set.of("attack", "combat_entity", "hunt_entity", "eat").contains(mind.execution.activePrimitiveId()))) {
                mind.lastCompanionReactionTick = tick;
                invalidate(actor, mind, "OBSERVED_COMPANION_ATTACK_REPLAN");
            }
        }
    }
    private void observePeaceGesture(UUID actor, ServerPlayer body, Mind mind, long tick) {
        for (UUID humanId : mind.humanContacts.keySet()) {
            if (!peaceSignals.needsPostureObservation(actor, humanId, tick)) continue;
            var human = server.getPlayerList().getPlayer(humanId);
            if (human == null || human.level() != body.level() || !human.isAlive() || body.distanceToSqr(human) > 64
                    || !Perception.canSee(body, human)) continue;
            peaceSignals.observePosture(actor, humanId, human.isShiftKeyDown(), tick);
            if (!peaceSignals.consumePeaceSignal(actor, humanId, tick)) continue;
            mind.peaceSource = humanId; mind.peaceAt = tick; mind.nextDecisionTick = 0; mind.idleDecisions = 0;
            remember(mind, "observed_peace_gesture human=" + humanId + " after_isolated_light_contact=true attention_likely=true damage_remains_real=true");
            MemoryStore memory = MemoryStore.get(server); long now = System.currentTimeMillis();
            memory.record(new MemoryRecord(UUID.randomUUID(), actor, memory.worldId(), GlobalPos.of(body.level().dimension(), body.blockPosition()),
                now, server.overworld().getGameTime(), MemoryType.EXPERIENCE, .35, 1, now, server.overworld().getGameTime(), MemoryOrigin.OBSERVED,
                "peace_gesture:" + humanId, List.of(), "Tras un toque débil aislado, " + human.getGameProfile().getName() + " se agachó y levantó rápidamente: señal de paz observada.",
                Set.of("peace", "relationship"), Set.of(humanId), null, false));
        }
    }
    private void request(AgentIdentity identity, ServerPlayer body, Mind mind) {
        // La nueva percepción ya incluye estos peligros; no hereda una revisión de la consulta anterior.
        observeSurvivalSignals(identity.id(), body, mind, server.getTickCount());
        mind.pendingReplanReason = "";
        mind.pending = true; mind.lastDecisionTick = server.getTickCount(); mind.seq++;
        gateway.updateSession(identity.id(), mind.epoch, mind.seq);
        List<AgentInbox.Message> messages = AgentInbox.get(server).pending(identity.id(), 8);
        observeMessageOrders(identity.id(), mind, messages);
        UUID observedAdmin = latestAdminId(server, identity.id());
        boolean research = !mind.webQuery.isBlank();
        String query = mind.webQuery; mind.webQuery = "";
        ObservationSnapshot observation = Perception.snapshot(server, body, research ? query : mind.goal, List.copyOf(mind.recent), archive);
        int unchanged = mind.decisionProgress.observe(observation);
        if (!research && unchanged >= 2) {
            mind.trigger = "NO_STATE_PROGRESS_RECONSIDER";
            List<String> facts = new ArrayList<>();
            facts.add("unchanged_state_decisions=" + unchanged
                + " inspect_has_not_changed_position_inventory_or_visible_resources=true; reconsider_goal_or_action");
            facts.addAll(observation.observations().stream().limit(31).toList());
            observation = new ObservationSnapshot(observation.worldId(), observation.dimension(), observation.x(), observation.y(), observation.z(),
                observation.health(), observation.hunger(), observation.inventory(), observation.currentGoal(), facts,
                observation.memories(), observation.untrustedMessages());
        }
        Map<String, ToolCapability> capabilities = new LinkedHashMap<>();
        List<ToolManifest> available = new ArrayList<>();
        // Reservar primero las acciones básicas y luego espacio para herramientas aprendidas.
        // Agregar capacidades nativas no debe ocultar las composiciones que acaba de crear el agente.
        Set<String> core = Set.of("inspect", "move_to", "explore_area", "look_at", "follow_entity", "harvest_block",
            "mine_tunnel", "pillar_up", "dig_down_step", "move_relative", "place_relative", "observe_work", "inspect_structure", "quick_cover", "build_plan", "place_block", "build_at", "craft_chain", "smelt", "eat", "equip_armor", "combat_entity",
            "hunt_entity", "collect_area", "drop_item", "container_put", "container_take", "interact_block", "rest", "accessory", "backpack", "recipe_plan",
            "sneak", "remember_place", "read_map", "teleport_to", "project_note", "notebook", "faction_base", "knowledge", "risk_decision", "research_recipe", "research_web", "propose_tool",
            "message_internal", "message_global", "player_command");
        List<ToolManifest> builtins = tools.certifiedTools().stream().filter(tool -> tool.author().equals(new UUID(0, 1))).toList();
        builtins.stream().filter(tool -> core.contains(tool.id())).forEach(available::add);
        available.addAll(learning.trialTools(identity.id()));
        List<ToolManifest> learned = new ArrayList<>(tools.certifiedTools().stream()
            .filter(tool -> !tool.author().equals(new UUID(0, 1))).toList());
        Collections.reverse(learned); // Las recién creadas deben entrar en el próximo catálogo compacto.
        learned.sort(Comparator.comparingInt(tool -> tool.author().equals(identity.id()) ? 0 : 1));
        available.addAll(learned);
        builtins.stream().filter(tool -> !core.contains(tool.id())).forEach(available::add);
        for (ToolManifest tool : available) {
            if (!AgentRoles.get(server).allows(identity.id(), tool.id()) || tool.id().equals("research_web") && (!config.webEnabled() || research)) continue;
            if (research && !Set.of("inspect", "research_recipe", "message_internal", "message_global").contains(tool.id())) continue;
            if (AgentRoles.get(server).role(identity.id()) == AgentRoles.Role.INVESTIGADOR
                    && tool.permissions().stream().anyMatch(p -> Set.of(ToolPermission.MINE, ToolPermission.PLACE, ToolPermission.CRAFT).contains(p))) continue;
            if (capabilities.size() >= 64 && !capabilities.containsKey(tool.id())) continue;
            ToolCapability previous = capabilities.get(tool.id());
            if (previous != null && previous.version() > tool.version()) continue;
            capabilities.put(tool.id(), new ToolCapability(tool.id(), tool.version(),
            CapabilityDescriptions.compose(tool.description(), tool.id().equals("player_command")
                ? PlayerCommands.describeAvailable(body) : "", tool.sha256()),
            tool.permissions().stream().map(Enum::name).collect(java.util.stream.Collectors.toSet())));
        }
        Set<String> allowed = PERMISSIONS.stream().map(Enum::name).collect(java.util.stream.Collectors.toSet());
        boolean addressedMessage = messages.stream().anyMatch(message -> message.kind() != AgentInbox.Kind.HUMAN_CONTEXT);
        String trigger = unchanged >= 2 && !research ? mind.trigger : !addressedMessage ? mind.trigger : "MESSAGE_RECEIVED_RECONSIDER";
        DecisionRequest request = new DecisionRequest(UUID.randomUUID(), identity.id(), mind.epoch, mind.seq, trigger,
            observation, capabilities, allowed, research ? DecisionRequest.Kind.WEB_RESEARCH : DecisionRequest.Kind.ORDINARY,
            null, operatorInstructions);
        if (research) request = new DecisionRequest(request.requestId(), identity.id(), mind.epoch, mind.seq,
            "Investigar Minecraft 1.20.1: " + query, observation, capabilities, allowed, DecisionRequest.Kind.WEB_RESEARCH, null, operatorInstructions);
        final DecisionRequest sentRequest = request;
        gateway.decide(sentRequest).whenComplete((answer, failure) -> server.execute(() -> {
            // Auditoría del operador: uso real y herramientas propuestas, sin claves ni cuerpos HTTP.
            if (answer != null) LogUtils.getLogger().info(
                "Raps IA agente={} estado={} motivo={} modelo={} entrada={} salida={} cache={} escrituraCache={} usd={} pasos={}",
                identity.name(), answer.status(), answer.reason(), answer.model(), answer.usage().inputTokens(),
                answer.usage().outputTokens(), answer.usage().cachedTokens(), answer.usage().cacheWriteTokens(),
                answer.usage().usd(), answer.decision() == null ? List.of() :
                    answer.decision().steps().stream().map(ToolDecision.Step::toolId).toList());
            if (closed || minds.get(identity.id()) != mind || sentRequest.sessionEpoch() != mind.epoch || sentRequest.observationSeq() != mind.seq) return;
            if (answer != null && (answer.status() == DecisionResponse.Status.HTTP_ERROR
                    || answer.status() == DecisionResponse.Status.NETWORK_ERROR
                    || answer.status() == DecisionResponse.Status.CLOSED
                    || answer.reason().startsWith("PROMOTION_")
                    || answer.status() == DecisionResponse.Status.DISABLED && gateway.disabled()
                    || answer.status() == DecisionResponse.Status.BUDGET_EXHAUSTED
                        && sentRequest.kind() == DecisionRequest.Kind.ORDINARY)) {
                disconnectAutonomous("API_" + answer.status() + ":" + answer.reason()); return;
            }
            // Registrar el error antes de procesar interrupciones: el chat no puede saltarse la espera.
            if (failure != null || answer == null || !answer.validFor(identity.id(), mind.epoch, mind.seq)) {
                mind.pending = false;
                long seconds = mind.decisionRetry.failed(server.getTickCount(),
                    answer != null && answer.status() == DecisionResponse.Status.INVALID_RESPONSE);
                String reason = answer == null ? "ASYNC_FAILURE" : answer.status() + ":" + answer.reason();
                remember(mind, "DECISION:" + reason + " retry_seconds=" + seconds);
                if (answer != null && answer.status() == DecisionResponse.Status.INVALID_RESPONSE
                        && mind.decisionRetry.invalidFailures() >= 5) {
                    invalidate(identity.id(), mind, "REPEATED_DECISION_ERROR");
                    AgentRegistry.get(server).markState(identity.id(), AgentState.PAUSED);
                    PlayerSessions.remove(server, identity.id());
                    notifyAdministrators("decision-error:" + identity.id(), identity.name()
                        + " pausado por errores repetidos de decisión. Inventario guardado; /Raps join bot " + identity.name() + " permite reintentar.");
                }
                return;
            }
            mind.decisionRetry.accepted();
            // Puede llegar un pedido después del último sondeo: descartar el plan viejo antes de aceptarlo.
            if (reconsiderMessages(identity.id(), mind)) return;
            if (PlayerSessions.find(server, identity.id()) == body && body.isAlive())
                observeSurvivalSignals(identity.id(), body, mind, server.getTickCount());
            if (resolvePendingReplan(identity.id(), mind)) return;
            mind.pending = false;
            if (!Objects.equals(observedAdmin, latestAdminId(server, identity.id()))) {
                invalidate(identity.id(), mind, "ADMIN_MESSAGE_CHANGED_REOBSERVE"); return;
            }
            ServerPlayer current = PlayerSessions.find(server, identity.id());
            if (current != body || !current.isAlive() || !current.level().dimension().location().toString().equals(sentRequest.observation().dimension())
                    || AgentRegistry.get(server).find(identity.id()).orElseThrow().state() != AgentState.ACTIVE) return;
            mind.goal = answer.decision().goal(); mind.plan.addAll(answer.decision().steps()); mind.trigger = "PLAN_FINISHED";
            // Un plan vacío significa esperar, no volver a preguntar al modelo en un bucle ocupado.
            if (mind.plan.isEmpty()) {
                mind.idleDecisions = Math.min(5, mind.idleDecisions + 1);
                mind.nextDecisionTick = server.getTickCount() + Math.min(60, 5L << (mind.idleDecisions - 1)) * 20;
            } else {
                mind.idleDecisions = 0;
                // Un éxito nominal sin cambio del mundo tampoco justifica consultar en bucle.
                // El plan se ejecuta completo; sólo se demora la próxima consulta si sigue sin progreso.
                // Mensajes dirigidos, daño y amenazas siguen interrumpiendo esta espera.
                mind.nextDecisionTick = unchanged >= 2
                    ? server.getTickCount() + Math.min(60, unchanged * 5L) * 20 : 0;
            }
            if (research) {
                String report = answer.decision().briefRationale() + "\nFuentes: " + String.join(" ", answer.webSources());
                if (report.length() > 2048) report = report.substring(0, 2048);
                long now = System.currentTimeMillis();
                MemoryStore.get(server).record(new MemoryRecord(sentRequest.requestId(), identity.id(), AgentRegistry.get(server).worldId(),
                    GlobalPos.of(body.level().dimension(), body.blockPosition()), now, body.serverLevel().getGameTime(), MemoryType.STRATEGY,
                    .6, .5, 0, 0, MemoryOrigin.REPORTED, "web:" + sentRequest.requestId(), List.of(), report, Set.of("investigacion", "web"), Set.of(), null, false));
                remember(mind, "Hallazgo web por verificar: " + report.substring(0, Math.min(480, report.length())));
            }
            for (AgentInbox.Message message : messages) {
                if (storeMessage(identity.id(), body, message)) AgentInbox.get(server).acknowledge(identity.id(), message.id());
            }
            AgentJournal.get(server).checkpoint(identity.id(), mind.goal, "PLAN_ACCEPTED", mind.repeatedFailure, !mind.plan.isEmpty());
        }));
    }
    // Supervivencia: observar cambios concretos, también entre el último sondeo y la respuesta remota.
    private void observeSurvivalSignals(UUID id, ServerPlayer body, Mind mind, long tick) {
        Set<UUID> threats = body.serverLevel().getEntitiesOfClass(net.minecraft.world.entity.Mob.class,
            body.getBoundingBox().inflate(12), mob -> (mob instanceof net.minecraft.world.entity.monster.Enemy || mob.getTarget() == body)
                && !(mob instanceof ar.com.companeros.horror.ParasiteEntity) && Perception.canSee(body, mob)
                && ThreatAssessment.assess(body, mob).immediate())
            .stream().map(net.minecraft.world.entity.Entity::getUUID).collect(java.util.stream.Collectors.toSet());
        if (!mind.nearbyThreats.containsAll(threats)) {
            remember(mind, "visible_hostile_threat_approaching: choose combat_entity or a viable retreat now");
            reconsiderSurvival(id, mind, "THREAT_APPROACHING_RECONSIDER");
        }
        mind.nearbyThreats = Set.copyOf(threats);
        boolean hurt = mind.observedHealth >= 0 && body.getHealth() < mind.observedHealth && tick - mind.attentionAt > 25;
        boolean hungry = (mind.observedHunger > 12 && body.getFoodData().getFoodLevel() <= 12
                || mind.observedHunger > 6 && body.getFoodData().getFoodLevel() <= 6)
            && PlayerOperations.find(body, stack -> stack.isEdible()
                && !stack.is(net.minecraft.world.item.Items.ROTTEN_FLESH)
                && !stack.is(net.minecraft.world.item.Items.PUFFERFISH)
                && !stack.is(net.minecraft.world.item.Items.SPIDER_EYE)
                && !stack.is(net.minecraft.world.item.Items.POISONOUS_POTATO)) < 0;
        mind.observedHealth = body.getHealth(); mind.observedHunger = body.getFoodData().getFoodLevel();
        if (hurt || hungry) reconsiderSurvival(id, mind, hurt ? "DAMAGED_RECONSIDER" : "HUNGER_RECONSIDER");
    }
    private void reconsiderSurvival(UUID id, Mind mind, String reason) {
        mind.nextDecisionTick = 0; mind.idleDecisions = 0;
        if (mind.pending) {
            // Muchos golpes durante la misma consulta exigen una revisión, sin abrir una llamada por golpe.
            if (mind.pendingReplanReason.isEmpty()) mind.pendingReplanReason = reason;
        } else if (mind.execution == null || !Set.of("attack", "combat_entity", "hunt_entity", "eat").contains(mind.execution.activePrimitiveId()))
            invalidate(id, mind, reason);
    }
    private boolean resolvePendingReplan(UUID id, Mind mind) {
        if (mind.pendingReplanReason.isEmpty()) return false;
        invalidate(id, mind, mind.pendingReplanReason);
        return true;
    }

    // Atención del buzón: consumir la señal de interrupción no confirma ni borra el mensaje.
    private boolean reconsiderMessages(UUID id, Mind mind) {
        List<AgentInbox.Message> messages = AgentInbox.get(server).pending(id, 64);
        boolean admin = latestMessageOrder(id, messages, AgentInbox.Kind.ADMIN) > mind.lastAdminOrder;
        boolean whisper = latestMessageOrder(id, messages, AgentInbox.Kind.HUMAN_PRIVATE) > mind.lastPrivateOrder;
        boolean directed = latestMessageOrder(id, messages, AgentInbox.Kind.HUMAN) > mind.lastHumanOrder;
        if (!admin && !whisper && !directed) return false;
        observeMessageOrders(id, mind, messages);
        mind.nextDecisionTick = 0; mind.idleDecisions = 0;
        if (!admin && !whisper && !mind.pending && mind.execution == null && mind.plan.isEmpty()) return false;
        String reason = admin ? "ADMIN_MESSAGE_RECEIVED" : whisper ? "PRIVATE_MESSAGE_RECEIVED_RECONSIDER"
            : "DIRECT_MESSAGE_RECEIVED_RECONSIDER";
        invalidate(id, mind, reason);
        return true;
    }
    private void observeMessageOrders(UUID id, Mind mind, List<AgentInbox.Message> messages) {
        mind.lastAdminOrder = Math.max(mind.lastAdminOrder, latestMessageOrder(id, messages, AgentInbox.Kind.ADMIN));
        mind.lastPrivateOrder = Math.max(mind.lastPrivateOrder, latestMessageOrder(id, messages, AgentInbox.Kind.HUMAN_PRIVATE));
        mind.lastHumanOrder = Math.max(mind.lastHumanOrder, latestMessageOrder(id, messages, AgentInbox.Kind.HUMAN));
    }
    private long latestMessageOrder(UUID id, List<AgentInbox.Message> messages, AgentInbox.Kind kind) {
        AgentInbox inbox = AgentInbox.get(server);
        return messages.stream().filter(message -> message.kind() == kind)
            .mapToLong(message -> inbox.deliveryOrder(id, message.id())).max().orElse(-1);
    }

    private void invalidate(UUID id, Mind mind, String reason) {
        if (mind.survivalMeal != null) { mind.survivalMeal.cancel(); mind.survivalMeal = null; }
        if (mind.execution != null) { mind.execution.cancel(); mind.execution = null; }
        mind.plan.clear(); mind.pending = false; mind.epoch++; mind.seq = 0;
        mind.pendingReplanReason = "";
        mind.nextDecisionTick = 0; mind.idleDecisions = 0;
        gateway.updateSession(id, mind.epoch, mind.seq); mind.trigger = reason; remember(mind, reason);
        AgentJournal.get(server).checkpoint(id, mind.goal, reason, mind.repeatedFailure, true);
        if (PlayerSessions.find(server, id) != null) PlayerSessions.setMovementIntent(server, id, 0, 0, false);
    }

    // Una IA ausente no deja jugadores inmóviles en peligro. El inventario usa playerdata normal.
    private void disconnectAutonomous(String reason) {
        int removed = 0;
        for (AgentIdentity identity : AgentRegistry.get(server).entries()) {
            if (identity.state() != AgentState.ACTIVE || !identity.mode().equals("autonomo")) continue;
            Mind mind = minds.get(identity.id());
            if (mind != null) invalidate(identity.id(), mind, reason);
            AgentRegistry.get(server).markState(identity.id(), AgentState.PAUSED);
            PlayerSessions.remove(server, identity.id()); removed++;
        }
        if (removed > 0) {
            server.overworld().getDataStorage().save();
            queueMemories();
            LogUtils.getLogger().warn("Raps desconectó y guardó {} agentes autónomos: {} {}", removed, reason, budgetSummary());
            notifyAdministrators("pause:" + reason, "Se pausaron " + removed + " bot(s). "
                + pauseReason(reason) + " " + budgetSummary());
        }
    }

    // Avisos operativos privados: sólo administradores humanos; el mismo motivo se informa una vez por minuto.
    private void notifyAdministrators(String key, String message) {
        if (!OperationalNotices.get(server).enabled()) return;
        long tick = server.getTickCount();
        Long previous = operationalNotices.get(key);
        if (previous != null && tick >= previous && tick - previous < 1200) return;
        operationalNotices.put(key, tick);
        Component notice = Component.literal("[Bots] " + message);
        AgentRegistry registry = AgentRegistry.get(server);
        for (ServerPlayer player : server.getPlayerList().getPlayers()) {
            if (registry.isHuman(player) && !PlayerSessions.isAgent(server, player.getUUID())
                    && player.createCommandSourceStack().hasPermission(2)) player.sendSystemMessage(notice);
        }
    }
    private String budgetSummary() {
        DecisionGateway.BudgetUsage usage = gateway.budgetUsage();
        String limit = gateway.budgetLimited() ? "tope USD " + config.decisionConfig().maxSessionUsd().stripTrailingZeros().toPlainString()
            : "sin tope";
        PromotionQuota.Usage promotion = gateway.promotionUsage();
        String freeUsage = promotion == null ? "" : "Cupo gratuito: " + promotion.usedTokens() + "/" + promotion.tokenLimit()
            + " tokens; reservados " + promotion.reservedTokens() + ". ";
        return freeUsage + "Coste teórico acumulado USD " + usage.chargedUsd().stripTrailingZeros().toPlainString() + "; " + limit + ".";
    }
    private String pauseReason(String reason) {
        if (Set.of("ACCOUNT_NO_CREDIT", "MODEL_OR_ACCOUNT_ACCESS").contains(gateway.unavailableReason()))
            return autonomousConnectionBlock();
        String promotion = promotionBlock(reason.substring(reason.indexOf(':') + 1));
        if (!promotion.isEmpty()) return promotion;
        if (reason.startsWith("API_BUDGET_EXHAUSTED")) return reason.contains("SESSION_BUDGET")
            ? "El saldo autorizado no alcanza para reservar la próxima consulta." : "Se alcanzó el presupuesto autorizado.";
        if (reason.startsWith("API_NETWORK_ERROR")) return "No hubo respuesta del proveedor de IA.";
        if (reason.startsWith("API_HTTP_ERROR")) return "El proveedor de IA rechazó la consulta (" + reason.substring(reason.indexOf(':') + 1) + ").";
        if (reason.startsWith("API_CLOSED")) return "El servicio de IA se cerró.";
        String blocked = autonomousConnectionBlock();
        return blocked.isEmpty() ? "El proveedor de IA no está disponible." : blocked;
    }
    private String autonomousConnectionBlock() {
        String reason = gateway.unavailableReason();
        String promotion = promotionBlock(reason);
        if (!promotion.isEmpty()) return promotion;
        if (gateway.budgetExhausted()) return "Se alcanzó el presupuesto autorizado.";
        return switch (reason) {
            case "" -> "";
            case "OPERATOR_DISABLED" -> "La IA está desactivada en la configuración.";
            case "FOUNDATION_NOT_VERIFIED" -> "La base de funcionamiento de la IA no está habilitada.";
            case "NO_BUDGET" -> "No hay presupuesto autorizado para la IA.";
            case "NO_CREDENTIAL" -> "No se encontró una credencial válida para el proveedor de IA.";
            case "ACCOUNT_NO_CREDIT" -> "OpenAI rechazó la consulta por falta de cuota o saldo. "
                + "El servidor comprobará la disponibilidad automáticamente.";
            case "MODEL_OR_ACCOUNT_ACCESS" -> "La cuenta no tiene acceso al modelo solicitado.";
            case "BUDGET_STORAGE_ERROR" -> "No se pudo leer o guardar el registro de consumo.";
            default -> "El proveedor de IA no está disponible.";
        };
    }
    private static String promotionBlock(String reason) {
        return switch (reason) {
            case "PROMOTION_UNVERIFIED" -> "Cupo gratuito sin verificar.";
            case "PROMOTION_EXPIRED" -> "El cupo gratuito venció.";
            case "PROMOTION_TOKEN_LIMIT" -> "El cupo gratuito se agotó o no alcanza para la próxima consulta.";
            case "PROMOTION_MODEL_NOT_ELIGIBLE" -> "El modelo solicitado no está incluido en el cupo gratuito.";
            case "PROMOTION_EXTRAS_NOT_COVERED" -> "La consulta pide funciones que el cupo gratuito no cubre.";
            case "PROMOTION_STORAGE_ERROR" -> "No se pudo leer o guardar el contador del cupo gratuito.";
            case "PROMOTION_USAGE_UNCONFIRMED" -> "El proveedor no confirmó el consumo; la IA se pausó para proteger el cupo.";
            default -> "";
        };
    }
    private void requireConnectionAvailable(AgentIdentity identity) {
        if (!identity.mode().equals("autonomo")) return;
        String blocked = autonomousConnectionBlock();
        if (!blocked.isEmpty()) throw new IllegalStateException(blocked + " " + budgetSummary());
    }
    private static UUID latestAdminId(MinecraftServer server, UUID agent) {
        return AgentInbox.get(server).pending(agent, 64).stream().filter(m -> m.kind() == AgentInbox.Kind.ADMIN).map(AgentInbox.Message::id).findFirst().orElse(null);
    }
    private boolean storeMessage(UUID agent, ServerPlayer body, AgentInbox.Message message) {
        Mind mind = minds.get(agent);
        if (mind != null && Set.of(AgentInbox.Kind.HUMAN, AgentInbox.Kind.HUMAN_PRIVATE).contains(message.kind())) {
            mind.conversationPartner = message.senderId(); mind.conversationAt = server.getTickCount();
        }
        AgentKnowledge.get(server).conversation(agent, message);
        MemoryStore memory = MemoryStore.get(server); MemoryRecord existing = memory.find(message.id()).orElse(null);
        if (existing != null) return existing.agentId().equals(agent) && existing.content().equals(message.body())
            && existing.sourceId().equals(message.kind() + ":" + message.senderId());
        return memory.record(new MemoryRecord(message.id(), agent, memory.worldId(), null,
            message.createdAtUtc(), server.overworld().getGameTime(), MemoryType.EXPERIENCE, .5, .5, 0, 0,
            MemoryOrigin.REPORTED, message.kind() + ":" + message.senderId(), List.of(), message.body(), Set.of("message"),
            Set.of(message.senderId()), null, false));
    }
    private static void remember(Mind mind, String text) {
        if (text.length() > 512) text = text.substring(0, 512);
        mind.recent.addLast(text); while (mind.recent.size() > 8) mind.recent.removeFirst();
    }
    // Mapas y geometría conservan varias filas útiles dentro del presupuesto de contexto.
    private static void rememberToolResult(Mind mind, String tool, ToolResult result) {
        if (!Set.of("read_map", "inspect_structure", "notebook", "faction_base", "knowledge").contains(tool)) {
            remember(mind, result.reason().name() + " " + String.join(" ", result.actualEffects())); return;
        }
        List<String> parts = new ArrayList<>(); StringBuilder part = new StringBuilder(tool + " "); int emitted = 0;
        for (String effect : result.actualEffects()) {
            String row = effect.length() > 380 ? effect.substring(0, 360) + " [row_truncated]" : effect;
            if (part.length() + row.length() + 2 > 420) {
                parts.add(part.toString()); if (parts.size() == 3) break;
                part = new StringBuilder(tool + " ");
            }
            part.append(row).append("; "); emitted++;
        }
        if (parts.size() < 3 && part.length() > tool.length() + 1) parts.add(part.toString());
        int omitted = result.actualEffects().size() - emitted;
        if (omitted > 0 && !parts.isEmpty()) parts.set(parts.size() - 1, parts.get(parts.size() - 1) + " context_rows_omitted=" + omitted);
        parts.forEach(text -> remember(mind, text));
    }
    private static void death(LivingDeathEvent event) {
        if (!(event.getEntity() instanceof ServerPlayer body) || body.level().isClientSide) return;
        AgentRuntime runtime = SERVERS.get(body.server); if (runtime == null || !PlayerSessions.isAgent(body.server, body.getUUID())) return;
        AgentKnowledge.get(body.server).death(body);
        Mind mind = runtime.minds.get(body.getUUID()); if (mind != null) runtime.invalidate(body.getUUID(), mind, "DEATH_RECOVERY");
        MemoryStore memory = MemoryStore.get(body.server); long now = System.currentTimeMillis();
        var attacker = event.getSource().getEntity();
        String who = attacker == null ? "" : " · atacante " + attacker.getName().getString() + " " + attacker.getUUID();
        memory.record(new MemoryRecord(UUID.randomUUID(), body.getUUID(), memory.worldId(), GlobalPos.of(body.level().dimension(), body.blockPosition()),
            now, body.server.overworld().getGameTime(), MemoryType.DEATH, .9, 1, now, body.server.overworld().getGameTime(), MemoryOrigin.OBSERVED,
            event.getSource().getMsgId(), List.of(), "Muerte: " + event.getSource().getMsgId() + " en " + body.blockPosition().toShortString() + who,
            Set.of("death", "danger"), attacker == null ? Set.of() : Set.of(attacker.getUUID()), null, true));
    }
    // Daño confirmado: conservar también al tirador de flechas y al atacante de un mod.
    private static void damaged(LivingDamageEvent event) {
        if (event.isCanceled() || event.getAmount() <= 0 || !(event.getEntity() instanceof ServerPlayer body)
                || body.level().isClientSide || !PlayerSessions.isAgent(body.server, body.getUUID())) return;
        AgentRuntime runtime = SERVERS.get(body.server); if (runtime == null) return;
        var attacker = event.getSource().getEntity();
        Mind mind = runtime.minds.get(body.getUUID()); if (mind == null || attacker == null || attacker == body) return;
        long tick = body.server.getTickCount();
        // Cada golpe exige interpretar de nuevo: ningún gesto anterior se hereda por esta copia del contexto.
        if (attacker.getUUID().equals(mind.peaceSource)) mind.peaceSource = null;
        boolean human = attacker instanceof ServerPlayer && !PlayerSessions.isAgent(body.server, attacker.getUUID());
        Long previous = human ? mind.humanContacts.put(attacker.getUUID(), tick) : null;
        if (mind.humanContacts.size() > 64) mind.humanContacts.entrySet().removeIf(entry -> tick - entry.getValue() > 1200);
        boolean armed = event.getSource().getDirectEntity() != attacker
            || attacker instanceof net.minecraft.world.entity.LivingEntity living && living.getMainHandItem()
                .getAttributeModifiers(net.minecraft.world.entity.EquipmentSlot.MAINHAND)
                .get(net.minecraft.world.entity.ai.attributes.Attributes.ATTACK_DAMAGE).stream().anyMatch(modifier -> modifier.getAmount() > 0);
        boolean hostile = human ? runtime.peaceSignals.recordHit(body.getUUID(), attacker.getUUID(), armed, event.getAmount(), body.getHealth(),
            previous == null ? Long.MAX_VALUE : tick - previous, tick, attacker.isShiftKeyDown())
            : ContactInterpretation.hostile(false, armed, event.getAmount(), body.getHealth(), Long.MAX_VALUE);
        boolean changed = !attacker.getUUID().equals(mind.damageSource) || tick - mind.damagedAt > 100;
        if (hostile) {
            mind.damageSource = attacker.getUUID(); mind.damagedAt = tick;
            if (attacker.getUUID().equals(mind.attentionSource)) { mind.attentionSource = null; mind.attentionAt = -1200; }
            if (mind.pending) runtime.reconsiderSurvival(body.getUUID(), mind, "DAMAGED_RECONSIDER");
        }
        else { mind.attentionAt = tick; mind.attentionSource = attacker.getUUID(); }
        mind.nextDecisionTick = 0; mind.idleDecisions = 0;
        if (changed || !hostile) remember(mind, (hostile ? "damage_confirmed" : "isolated_light_human_contact attention_or_accident_possible=true") + " source=" + event.getSource().getMsgId() + " attacker=" + attacker.getUUID()
            + " type=" + net.minecraftforge.registries.ForgeRegistries.ENTITY_TYPES.getKey(attacker.getType())
            + " amount=" + event.getAmount() + " visible_now=" + Perception.canSee(body, attacker));
        if (hostile && changed) {
            MemoryStore memory = MemoryStore.get(body.server); long now = System.currentTimeMillis();
            memory.record(new MemoryRecord(UUID.randomUUID(), body.getUUID(), memory.worldId(), GlobalPos.of(body.level().dimension(), body.blockPosition()),
                now, body.server.overworld().getGameTime(), MemoryType.EXPERIENCE, .7, 1, now, body.server.overworld().getGameTime(), MemoryOrigin.OBSERVED,
                "attacked_by:" + attacker.getUUID(), List.of(), "Ataque real de " + attacker.getName().getString() + " (" + attacker.getUUID() + "), daño " + event.getAmount() + ".",
                Set.of("attack", "danger", "relationship"), Set.of(attacker.getUUID()), null, false));
            runtime.invalidate(body.getUUID(), mind, "ATTACKED_RECONSIDER_DEFENSE_OR_PURSUIT");
        }
    }
    public static String contactMeaning(MinecraftServer server, UUID actor, UUID attacker) {
        AgentRuntime runtime = SERVERS.get(server); Mind mind = runtime == null ? null : runtime.minds.get(actor);
        if (mind != null && attacker.equals(mind.peaceSource) && server.getTickCount() - mind.peaceAt <= 100)
            return "observed_peace_gesture_after_light_contact human=" + mind.peaceSource;
        return mind != null && attacker.equals(mind.attentionSource) && server.getTickCount() - mind.attentionAt <= 100
            ? "isolated_light_contact_intent_unconfirmed" : "damage_source_intent_requires_context";
    }
    private void open(AgentIdentity identity) {
        pendingConnections.remove(identity.id());
        if (ar.com.companeros.horror.HorrorModule.isInfected(server, identity.id()))
            throw new IllegalStateException("Ese jugador es el huésped del parásito.");
        if (PlayerSessions.find(server, identity.id()) != null) {
            AgentRegistry.get(server).markState(identity.id(), AgentState.ACTIVE); return;
        }
        if (PlayerSessions.players(server).size() >= config.populationLimit()) throw new IllegalStateException("Se alcanzó la población habilitada");
        GlobalPos camp = identity.camp(); var level = camp == null ? server.overworld() : server.getLevel(camp.dimension());
        if (level == null) throw new IllegalStateException("La dimensión del campamento no está disponible");
        BlockPos pos = camp == null ? level.getSharedSpawnPos() : camp.pos();
        PlayerSessions.create(server, identity.id(), identity.name(), level, pos);
        nextJoinTick = server.getTickCount() + 100L;
        AgentRegistry.get(server).markState(identity.id(), AgentState.ACTIVE);
        Mind mind = minds.computeIfAbsent(identity.id(), id -> new Mind(AgentJournal.get(server).entry(id).goal()));
        mind.notebookLoad = AgentNotebooks.run(identity.id(), identity.name(), "read", "", "", "", 0, "")
            .orTimeout(5, java.util.concurrent.TimeUnit.SECONDS);
        mind.trigger = AgentJournal.get(server).entry(identity.id()).interrupted() ? "RESTART_REOBSERVE" : "INITIAL_OBSERVATION";
    }
    // Una admisión cada cinco segundos; no se duerme ni bloquea el hilo del servidor.
    private boolean enqueueConnection(AgentIdentity identity) {
        if (PlayerSessions.find(server,identity.id())!=null || ar.com.companeros.horror.HorrorModule.isInfected(server,identity.id())) return false;
        requireConnectionAvailable(identity);
        return pendingConnections.putIfAbsent(identity.id(),identity)==null;
    }
    private void advanceConnections() {
        if(pendingConnections.isEmpty()||server.getTickCount()<nextJoinTick)return;
        AgentIdentity requested=pendingConnections.values().iterator().next(); pendingConnections.remove(requested.id());
        nextJoinTick=server.getTickCount()+100L;
        AgentIdentity current=AgentRegistry.get(server).find(requested.id()).orElse(null);
        if(current==null||current.state()==AgentState.RETIRED||current.state()==AgentState.LEGACY)return;
        try { requireConnectionAvailable(current); open(current); }
        catch(RuntimeException failure){
            LogUtils.getLogger().warn("No se pudo conectar al agente {} en la cola: {}",current.name(),failure.getMessage());
            notifyAdministrators("join:" + failure.getMessage(), "No se pudo conectar a " + current.name() + ": " + failure.getMessage());
        }
    }
    @Override public void close() {
        if (closed) return;
        for (var item : minds.entrySet()) invalidate(item.getKey(), item.getValue(), "SERVER_STOPPED");
        closed = true; gateway.close();
        archiveWriter.shutdown();
        try {
            if (archiveWriter.awaitTermination(30, java.util.concurrent.TimeUnit.SECONDS)) writeMemories(memorySnapshot());
            else LogUtils.getLogger().warn("El archivado sigue ocupado; SavedData conserva el estado del mundo");
            tools.saveStatistics(); learning.save();
        } catch (InterruptedException failure) { Thread.currentThread().interrupt(); }
        catch (java.io.IOException failure) { LogUtils.getLogger().warn("No se guardaron estadísticas o memoria persistente", failure); }
    }
    private Map<UUID, List<MemoryRecord>> memorySnapshot() {
        MemoryStore memory = MemoryStore.get(server);
        Map<UUID, List<MemoryRecord>> snapshot = new HashMap<>();
        for (AgentIdentity identity : AgentRegistry.get(server).entries())
            if (identity.state() != AgentState.LEGACY) snapshot.put(identity.id(), memory.recordsFor(identity.id()));
        return Map.copyOf(snapshot);
    }
    private void writeMemories(Map<UUID, List<MemoryRecord>> snapshot) throws java.io.IOException {
        for (var entry : snapshot.entrySet()) archive.sync(entry.getKey(), entry.getValue());
    }
    private void queueMemories() {
        Map<UUID, List<MemoryRecord>> snapshot = memorySnapshot();
        try { archiveWriter.execute(() -> {
            try { writeMemories(snapshot); }
            catch (java.io.IOException failure) { LogUtils.getLogger().error("No se pudo archivar memoria fuera del mundo", failure); }
        }); } catch (java.util.concurrent.RejectedExecutionException busy) {
            LogUtils.getLogger().warn("Archivador ocupado; se conserva SavedData para la siguiente sincronización");
        }
    }

    // Controles humanos. Un agente nunca hereda los permisos de su administrador.
    public static boolean isRegisteredPlayer(MinecraftServer server, String name) { return find(server, name) != null; }
    private static AgentIdentity find(MinecraftServer server, String name) {
        return AgentRegistry.get(server).entries().stream().filter(a -> a.state() != AgentState.LEGACY && a.state() != AgentState.RETIRED && a.name().equalsIgnoreCase(name)).findFirst().orElse(null);
    }
    private static boolean authorized(CommandSourceStack source, AgentIdentity identity, boolean admin) {
        if (source.getEntity() != null && (!(source.getEntity() instanceof ServerPlayer player)
                || !AgentRegistry.get(source.getServer()).isHuman(player) || PlayerSessions.isAgent(source.getServer(), player.getUUID()))) return false;
        return source.hasPermission(2) || !admin && identity != null && source.getEntity() != null && source.getEntity().getUUID().equals(identity.legacyOwner());
    }
    private static int reject(CommandSourceStack source, String text) { source.sendFailure(Component.literal(text)); return 0; }
    private static int reply(CommandSourceStack source, String text) { source.sendSuccess(() -> Component.literal(text), false); return 1; }
    public static int create(CommandSourceStack source, String name) {
        return create(source,name,false);
    }
    private static int create(CommandSourceStack source, String name, boolean queued) {
        if (!authorized(source, null, true)) return reject(source, "Necesitás permiso de administrador.");
        if (!name.matches("[A-Za-z0-9_]{1,16}") || name.equalsIgnoreCase("all")) return reject(source, "Usá un nombre de hasta 16 letras, números o guiones bajos.");
        AgentRuntime runtime = get(source.getServer()); AgentRegistry registry = AgentRegistry.get(source.getServer());
        AgentIdentity previous = registry.entries().stream().filter(a -> a.name().equalsIgnoreCase(name)).findFirst().orElse(null);
        if (previous != null) return reject(source, previous.state() == AgentState.RETIRED || previous.state() == AgentState.LEGACY
            ? "Ese nombre tiene datos de un bot retirado o del prototipo. Elegí otro nombre."
            : "Ese nombre ya tiene datos guardados. Usá /Raps join bot " + previous.name() + ".");
        if (registry.entries().stream().filter(a -> a.state() != AgentState.LEGACY && a.state() != AgentState.RETIRED).count() >= runtime.config.populationLimit()) return reject(source, "Se alcanzó la población habilitada.");
        UUID id = PlayerProfileIds.offline(name); BlockPos pos;
        if (source.getServer().getPlayerList().getPlayerByName(name) != null
                || java.nio.file.Files.exists(source.getServer().getWorldPath(net.minecraft.world.level.storage.LevelResource.PLAYER_DATA_DIR).resolve(id + ".dat")))
            return reject(source, "Ese nombre ya pertenece a un jugador del mundo. Elegí otro para el bot.");
        if (source.getEntity() == null) {
            BlockPos spawn = source.getLevel().getSharedSpawnPos();
            int x = spawn.getX() + 2, z = spawn.getZ();
            // getHeight devuelve la altura mínima cuando el chunk todavía no está cargado.
            source.getLevel().getChunk(x >> 4, z >> 4);
            pos = new BlockPos(x, source.getLevel().getHeight(net.minecraft.world.level.levelgen.Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, x, z), z);
        } else pos = BlockPos.containing(source.getPosition().add(1.5, 0, 0));
        AgentIdentity identity = registry.register(id, name, source.getEntity() == null ? null : source.getEntity().getUUID(),
            GlobalPos.of(source.getLevel().dimension(), pos), "autonomo");
        try {
            if(queued) { runtime.enqueueConnection(identity); return 1; }
            runtime.open(identity); return reply(source, name + " se sumó a la aventura.");
        }
        catch (RuntimeException failure) { registry.markState(id, AgentState.RETIRED); return reject(source, "No se pudo conectar a " + name + ": " + failure.getMessage()); }
    }
    public static int connect(CommandSourceStack source, String name) {
        if (!authorized(source, null, true)) return reject(source, "Necesitás permiso de administrador.");
        AgentRuntime runtime = get(source.getServer());
        AgentIdentity identity = find(source.getServer(), name);
        if (identity == null || identity.mode().equals("autonomo")) {
            String blocked = runtime.autonomousConnectionBlock();
            if (!blocked.isEmpty()) return reject(source, "No se pudo conectar: " + blocked + " " + runtime.budgetSummary());
        }
        if (identity == null) return create(source, name);
        try { runtime.open(identity); return reply(source, name + " conectado."); }
        catch (RuntimeException failure) { return reject(source, "No se pudo conectar: " + failure.getMessage()); }
    }
    public static List<String> joinableNames(MinecraftServer server) {
        return AgentRegistry.get(server).entries().stream()
            .filter(a -> a.state() != AgentState.LEGACY && a.state() != AgentState.RETIRED)
            .filter(a -> !ar.com.companeros.horror.HorrorModule.isInfected(server, a.id()))
            .map(AgentIdentity::name).toList();
    }
    public static int connectAll(CommandSourceStack source) {
        if (!authorized(source, null, true)) return reject(source, "Necesitás permiso de administrador.");
        AgentRuntime runtime = get(source.getServer());
        String blocked = runtime.autonomousConnectionBlock();
        if (!blocked.isEmpty()) return reject(source, "No se agregaron bots: " + blocked + " " + runtime.budgetSummary());
        int joined = 0;
        // Reutilizar primero identidades guardadas: no borrar memoria ni duplicar jugadores.
        for (String name : joinableNames(source.getServer())) {
            AgentIdentity identity = find(source.getServer(), name);
            if (PlayerSessions.find(source.getServer(), identity.id()) != null) continue;
            try { if(runtime.enqueueConnection(identity)) joined++; }
            catch (RuntimeException failure) { reject(source, name + ": " + failure.getMessage()); }
        }
        // Completar la población sólo al pedir join bots, con recursos e inventario inicial normales.
        List<String> defaults = List.of("Hydrogen", "Helium", "Lithium", "Beryllium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", "Neon");
        AgentRegistry registry = AgentRegistry.get(source.getServer());
        long registered = registry.entries().stream()
            .filter(a -> a.state() != AgentState.LEGACY && a.state() != AgentState.RETIRED).count();
        for (int attempt = 0; attempt < 100 && registered < runtime.config.populationLimit(); attempt++) {
            String base = defaults.get(attempt % defaults.size());
            String candidate = base + (attempt < defaults.size() ? "" : "_" + (attempt / defaults.size() + 1));
            UUID candidateId = PlayerProfileIds.offline(candidate);
            if (registry.entries().stream().anyMatch(a -> a.name().equalsIgnoreCase(candidate))
                    || source.getServer().getPlayerList().getPlayerByName(candidate) != null
                    || java.nio.file.Files.exists(source.getServer().getWorldPath(net.minecraft.world.level.storage.LevelResource.PLAYER_DATA_DIR)
                        .resolve(candidateId + ".dat"))) continue;
            if (create(source, candidate,true) > 0) { registered++; joined++; }
        }
        if (joined == 0) return reject(source, "No se agregaron bots: ya están conectados o pendientes, o no hay lugares disponibles.");
        reply(source, "Se agregaron " + joined + " bot(s) a la cola. Entran de a uno cada 5 segundos. Pendientes: " + runtime.pendingConnections.size() + ".");
        return joined;
    }
    public static int pause(CommandSourceStack source, String name) {
        AgentIdentity identity = find(source.getServer(), name); if (identity == null || !authorized(source, identity, false)) return reject(source, "No encontré un bot que puedas pausar.");
        if (ar.com.companeros.horror.HorrorModule.isInfected(source.getServer(), identity.id())) return reject(source, "El huésped se controla mediante /Raps mimicer.");
        AgentRuntime runtime = get(source.getServer()); Mind mind = runtime.minds.get(identity.id()); if (mind != null) runtime.invalidate(identity.id(), mind, "ADMIN_PAUSED");
        runtime.pendingConnections.remove(identity.id());
        AgentRegistry.get(source.getServer()).markState(identity.id(), AgentState.PAUSED); PlayerSessions.remove(source.getServer(), identity.id());
        return reply(source, name + " pausado. Su inventario está guardado.");
    }
    public static int retire(CommandSourceStack source, String name) {
        AgentIdentity identity = find(source.getServer(), name); if (identity == null || !authorized(source, identity, true)) return reject(source, "No encontré un bot que puedas retirar.");
        if (ar.com.companeros.horror.HorrorModule.isInfected(source.getServer(), identity.id())) return reject(source, "El huésped conserva su identidad durante la infección.");
        pause(source, name); AgentRegistry.get(source.getServer()).markState(identity.id(), AgentState.RETIRED); return reply(source, name + " retirado.");
    }
    public static int setMode(CommandSourceStack source, String name, String mode) {
        AgentIdentity identity = find(source.getServer(), name); if (identity == null || !authorized(source, identity, false)) return reject(source, "No encontré un compañero tuyo con ese nombre.");
        if (mode.equals("seguir")) return reject(source, "Usá /botmalo para coordinar una tarea con " + name + ".");
        AgentRuntime runtime = get(source.getServer()); Mind mind = runtime.minds.get(identity.id()); if (mind != null) runtime.invalidate(identity.id(), mind, "MODE_CHANGED");
        AgentRegistry.get(source.getServer()).updateSettings(identity.id(), identity.camp(), mode);
        return reply(source, name + ": " + mode);
    }
    public static int setRole(CommandSourceStack source, String name, AgentRoles.Role role) {
        AgentIdentity identity = find(source.getServer(), name);
        if (identity == null || !authorized(source, identity, true)) return reject(source, "Necesitás un bot registrado y permiso de administrador.");
        AgentRoles.get(source.getServer()).assign(identity.id(), role);
        AgentRuntime runtime = get(source.getServer()); Mind mind = runtime.minds.get(identity.id());
        if (mind != null) runtime.invalidate(identity.id(), mind, "ROLE_CHANGED");
        return reply(source, name + " · Rol: " + role.name().toLowerCase(Locale.ROOT));
    }
    public static int setCamp(CommandSourceStack source, String name) {
        AgentIdentity identity = find(source.getServer(), name); if (identity == null || !authorized(source, identity, false)) return reject(source, "No encontré un compañero tuyo con ese nombre.");
        GlobalPos camp = GlobalPos.of(source.getLevel().dimension(), BlockPos.containing(source.getPosition()));
        AgentRuntime runtime = get(source.getServer()); Mind mind = runtime.minds.get(identity.id()); if (mind != null) runtime.invalidate(identity.id(), mind, "CAMP_CHANGED");
        AgentRegistry.get(source.getServer()).updateSettings(identity.id(), camp, identity.mode()); return reply(source, "Campamento de " + name + " marcado.");
    }
    public static int inventory(CommandSourceStack source, String name) {
        AgentIdentity identity = find(source.getServer(), name); if (identity == null || !authorized(source, identity, false)) return reject(source, "No encontré un compañero tuyo con ese nombre.");
        ServerPlayer player = PlayerSessions.find(source.getServer(), identity.id()); if (player == null) return reject(source, "Conectá al bot para consultar su inventario.");
        List<String> entries = new ArrayList<>(); for (int i = 0; i < player.getInventory().getContainerSize(); i++) {
            ItemStack stack = player.getInventory().getItem(i); if (!stack.isEmpty()) entries.add(stack.getCount() + " " + stack.getHoverName().getString());
        }
        return reply(source, name + ": " + (entries.isEmpty() ? "Inventario vacío" : String.join(", ", entries)));
    }
    public static int handOver(CommandSourceStack source, String name) {
        AgentIdentity identity = find(source.getServer(), name); if (identity == null || !authorized(source, identity, false)) return reject(source, "No encontré un compañero tuyo con ese nombre.");
        ServerPlayer player = PlayerSessions.find(source.getServer(), identity.id());
        if (player == null || source.getEntity() == null || player.distanceToSqr(source.getEntity()) > 16) return reject(source, "Acercate al compañero para recibir sus objetos.");
        for (int i = 0; i < 36; i++) { ItemStack stack = player.getInventory().removeItemNoUpdate(i); if (!stack.isEmpty()) player.drop(stack, false, true); }
        player.getInventory().setChanged(); return reply(source, "Objetos entregados.");
    }
    // Estado administrativo resumido: nunca devuelve credenciales ni consulta la API.
    public static JsonObject panelStatus(MinecraftServer server) {
        AgentRuntime runtime = get(server);
        JsonObject result = new JsonObject();
        var usage = runtime.gateway.budgetUsage();
        result.addProperty("population", runtime.config.populationLimit());
        result.addProperty("apiReason", runtime.gateway.unavailableReason());
        result.addProperty("calls", usage.dispatchedCalls());
        result.addProperty("inputTokens", usage.inputTokens());
        result.addProperty("outputTokens", usage.outputTokens());
        result.addProperty("recordedUsd", usage.chargedUsd().stripTrailingZeros().toPlainString());
        result.addProperty("inFlight", usage.inFlight());
        result.addProperty("queued", usage.queued());
        var promotion = runtime.gateway.promotionUsage();
        if (promotion != null) {
            result.addProperty("promotionRemaining", promotion.unavailableReason().isEmpty() ? promotion.remainingTokens() : 0);
            result.addProperty("promotionLimit", promotion.tokenLimit());
            result.addProperty("promotionUsed", promotion.usedTokens());
            result.addProperty("promotionReserved", promotion.reservedTokens());
            result.addProperty("promotionExpiresAt", promotion.expiresAt().toString());
        }
        result.addProperty("retrySeconds", Math.max(0, (runtime.gateway.accountRetryAtMillis() - System.currentTimeMillis() + 999) / 1000));
        return result;
    }
    public static List<String> describe(MinecraftServer server) {
        AgentRuntime runtime = get(server); List<String> rows = new ArrayList<>();
        for (AgentIdentity identity : AgentRegistry.get(server).entries()) {
            if (identity.state() == AgentState.LEGACY || identity.state() == AgentState.RETIRED) continue;
            ServerPlayer player = PlayerSessions.find(server, identity.id()); Mind mind = runtime.minds.get(identity.id());
            boolean infected = ar.com.companeros.horror.HorrorModule.isInfected(server, identity.id());
            String activity = infected ? "Huésped · Etapa " + ar.com.companeros.horror.HorrorState.get(server).stage(server.overworld().getGameTime(), ar.com.companeros.horror.HorrorModule.config(server))
                : player == null ? "Desconectado" : mind == null ? "Evaluando entorno" : mind.activity;
            rows.add(identity.name() + " · " + activity
                + (player == null ? "" : " · Salud " + (int)player.getHealth() + "/20 · Comida " + player.getFoodData().getFoodLevel() + "/20 · " + player.blockPosition().toShortString())
                + " · Rol " + AgentRoles.get(server).role(identity.id()).name().toLowerCase(Locale.ROOT)
                + " · UUID " + identity.id() + " · Mensajes " + AgentInbox.get(server).pending(identity.id(), 64).size());
        } return List.copyOf(rows);
    }
    public static List<String> toolNames(MinecraftServer server) { return get(server).tools.certifiedTools().stream().map(t -> t.id() + " v" + t.version() + " · " + t.description()).toList(); }
    public static int proposeTool(CommandSourceStack source, String name, String json) {
        AgentIdentity identity = find(source.getServer(), name);
        if (identity == null || !authorized(source, identity, true)) return reject(source, "Necesitás un bot registrado y permiso de administrador.");
        if (ar.com.companeros.horror.HorrorModule.isInfected(source.getServer(), identity.id())) return reject(source, "El huésped ya no propone herramientas de jugador.");
        try {
            var proposal = get(source.getServer()).learning.propose(identity.id(), json);
            return reply(source, name + " creó " + proposal.manifest().id() + " v" + proposal.manifest().version() + ". Disponible para usar.");
        } catch (java.io.IOException | IllegalArgumentException failure) { return reject(source, "La propuesta no pudo validarse o guardarse."); }
    }
    public static int toolState(CommandSourceStack source, String name) {
        AgentIdentity identity = find(source.getServer(), name);
        if (identity == null || !authorized(source, identity, true)) return reject(source, "Necesitás un bot registrado y permiso de administrador.");
        AgentRuntime runtime = get(source.getServer());
        List<ToolManifest> all = new ArrayList<>(runtime.tools.certifiedTools());
        runtime.tools.pendingProposals().stream().map(ToolRegistry.Proposal::manifest).forEach(all::add);
        List<ToolManifest> own = all.stream().filter(tool -> tool.author().equals(identity.id())).limit(64).toList();
        if (own.isEmpty()) return reply(source, name + " todavía no creó herramientas.");
        for (ToolManifest tool : own) {
            var progress = runtime.learning.statistics(tool.sha256());
            reply(source, tool.id() + " v" + tool.version() + " · " + (progress.certified() ? "Certificada" : "En pruebas")
                + " · Éxitos " + progress.successes() + " · Fallos " + progress.failures() + " · Cancelaciones " + progress.cancellations());
        }
        return own.size();
    }
    public static int runTool(CommandSourceStack source, String name, String tool, String json) {
        AgentIdentity identity = find(source.getServer(), name); if (identity == null || !authorized(source, identity, true)) return reject(source, "Necesitás un bot registrado y permiso de administrador.");
        AgentRuntime runtime = get(source.getServer()); ServerPlayer player = PlayerSessions.find(source.getServer(), identity.id()); if (player == null) return reject(source, "Conectá al bot primero.");
        if (ar.com.companeros.horror.HorrorModule.isInfected(source.getServer(), identity.id())) return reject(source, "El huésped ya no usa herramientas de jugador.");
        try {
            if (json.length() > 4096) throw new IllegalArgumentException(); JsonObject parsed = JsonParser.parseString(json).getAsJsonObject(); defaults(tool, parsed);
            Mind mind = runtime.minds.computeIfAbsent(identity.id(), id -> new Mind(AgentJournal.get(runtime.server).entry(id).goal()));
            runtime.invalidate(identity.id(), mind, "ADMIN_TOOL_TEST"); mind.body = player; mind.dimension = player.level().dimension().location().toString();
            int version = runtime.toolVersion(identity.id(), tool);
            mind.execution = runtime.startExecution(identity.id(), tool, version, parsed, r -> remember(mind, r.status() + ":" + r.reason()));
            mind.activity = tool; mind.lastProgressTick = runtime.server.getTickCount(); mind.progress = 0;
            AgentJournal.get(runtime.server).checkpoint(identity.id(), mind.goal, "ADMIN_TOOL:" + tool, mind.repeatedFailure, true);
            return reply(source, name + " inició " + tool + ".");
        } catch (RuntimeException failure) { return reject(source, "La herramienta o sus argumentos no son válidos."); }
    }
    public static int setPopulationLimit(CommandSourceStack source, int value) {
        if (!authorized(source, null, true)) return reject(source, "Necesitás permiso de administrador.");
        AgentRuntime runtime = get(source.getServer());
        if (PlayerSessions.players(source.getServer()).size() > value) return reject(source, "Pausá bots antes de reducir la población.");
        runtime.config.setPopulationLimit(value); return reply(source, "Población habilitada: " + value + ".");
    }
    private static void defaults(String tool, JsonObject inputs) {
        if (Set.of("notebook", "faction_base", "knowledge").contains(tool)) NotebookInputs.defaults(inputs);
        if (tool.equals("faction_base") && !inputs.has("scope")) inputs.addProperty("scope", "own");
        if (tool.equals("knowledge") && !inputs.has("recipient")) inputs.addProperty("recipient", "self");
        if (Set.of("remember_place", "read_map").contains(tool) && !inputs.has("scope")) inputs.addProperty("scope", "own");
        if (tool.equals("share_waypoint") && !inputs.has("recipient")) inputs.addProperty("recipient", "all");
        if ((tool.equals("craft") || tool.equals("store")) && !inputs.has("count")) inputs.addProperty("count", tool.equals("craft") ? 1 : 64);
        if (tool.equals("collect") && !inputs.has("radius")) inputs.addProperty("radius", 1);
        if (tool.equals("follow_entity") && !inputs.has("durationSeconds")) inputs.addProperty("durationSeconds", 30);
        if (tool.equals("explore_area") && !inputs.has("durationSeconds")) inputs.addProperty("durationSeconds", 60);
        if (tool.equals("explore_area") && !inputs.has("goal")) inputs.addProperty("goal", "madera");
        if (tool.equals("create_banner") && !inputs.has("symbol")) inputs.addProperty("symbol", "none");
        if (tool.equals("create_banner") && !inputs.has("symbolColor")) inputs.addProperty("symbolColor", "black");
    }

    // Una propuesta sólo se prueba por su autor; las certificadas se comparten entre jugadores.
    private ToolExecution startExecution(UUID actor, String tool, int version, JsonObject inputs,
            java.util.function.Consumer<ToolResult> completed) {
        var context = new ToolRegistry.ExecutionContext(actor, server.getTickCount(), PERMISSIONS, inputs);
        var candidate = learning.pending(actor, tool, version);
        ToolManifest manifest = candidate.orElseGet(() -> tools.certifiedTools().stream()
            .filter(value -> value.id().equals(tool) && value.version() == version).findFirst()
            .orElseThrow(() -> new IllegalArgumentException("Herramienta desconocida")));
        if (AgentRoles.get(server).role(actor) == AgentRoles.Role.INVESTIGADOR
                && manifest.permissions().stream().anyMatch(permission -> Set.of(ToolPermission.MINE, ToolPermission.PLACE, ToolPermission.CRAFT).contains(permission)))
            throw new IllegalArgumentException("El investigador delega esa producción");
        return candidate.isPresent() ? learning.startTrial(candidate.get().sha256(), context, server, completed)
            : tools.start(tool, version, context, new WorldPrimitiveExecutor(server, completed, learning));
    }
    private int toolVersion(UUID actor, String tool) {
        return java.util.stream.Stream.concat(tools.certifiedTools().stream(), learning.trialTools(actor).stream())
            .filter(manifest -> manifest.id().equals(tool)).mapToInt(ToolManifest::version).max().orElse(1);
    }
    private static JsonObject inputs(Map<String, String> arguments) {
        JsonObject inputs = new JsonObject();
        for (var entry : arguments.entrySet()) {
            if (Set.of("x", "y", "z", "count", "radius", "durationSeconds", "headingDegrees", "length", "slope", "height", "slot", "offset").contains(entry.getKey())) inputs.addProperty(entry.getKey(), Double.parseDouble(entry.getValue()));
            else if (Set.of("enabled", "sprint", "jump").contains(entry.getKey())) {
                if (!Set.of("true", "false").contains(entry.getValue())) throw new IllegalArgumentException("Booleano inválido");
                inputs.addProperty(entry.getKey(), Boolean.parseBoolean(entry.getValue()));
            }
            else inputs.addProperty(entry.getKey(), entry.getValue());
        } return inputs;
    }
}