Erick Silva

"Crie um mod para Fabric que conecte os comandos do chat com as ações do jogador usando a API do Baritone, permitindo que a IA assuma o controle do meu próprio personagem de forma assíncrona."

Kodari AI
KodariOct 15 at 2:48 pm 2
BaritoneChatCommander
Fabric mod enabling asynchronous AI control of the player character via chat commands integrated with the Baritone API. Provides a command system that parses chat input and translates it into Baritone pathfinding and action tasks, allowing the AI to autonomously navigate, mine, build, and interact with the world. Features configurable permissions, task queueing, and real-time status feedback in chat. Designed for seamless integration with existing Baritone installations, empowering users to delegate complex in-game actions to automated agents.
  • Criar a estrutura de um mod Fabric 1.21.11 exclusivamente client-side.

  • Registrar /ai com comandos de ação permitidos e validação dos argumentos.

  • Acionar o gerenciador de comandos do Baritone por reflexão, sem exigir sua API para compilar; o pathfinding continua assíncrono no Baritone.

Mod criado. Registra os comandos client-side /ai goto <x> <y> <z>, /ai mine <bloco>, /ai follow <jogador>, /ai come e /ai stop, validando os argumentos antes de encaminhá-los ao Baritone. O movimento é executado de forma assíncrona pelo pathfinding do Baritone.

O Baritone precisa estar instalado no cliente. Esta versão oferece uma ponte local de comandos; não inclui conexão com um modelo de IA ou serviço externo.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 189
src/client/java/com/kodari/chatbaritone/ChatBaritoneClient.java
package com.kodari.chatbaritone;

import com.mojang.brigadier.arguments.StringArgumentType;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.minecraft.text.Text;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;

public class ChatBaritoneClient implements ClientModInitializer {
    @Override
    public void onInitializeClient() {
        ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) ->
                dispatcher.register(ClientCommandManager.literal("ai")
                        .then(ClientCommandManager.argument("instruction", StringArgumentType.greedyString())
                                .executes(context -> executeInstruction(
                                        context.getSource(),
                                        StringArgumentType.getString(context, "instruction")
                                ))))
        );
    }

    private static int executeInstruction(FabricClientCommandSource source, String instruction) {
        final String command;
        try {
            command = validateInstruction(instruction);
        } catch (IllegalArgumentException exception) {
            source.sendError(Text.literal(exception.getMessage()));
            return 0;
        }

        try {
            runBaritoneCommand(command);
            source.sendFeedback(Text.literal("Baritone action started: " + command));
            return 1;
        } catch (ReflectiveOperationException exception) {
            Throwable cause = exception instanceof InvocationTargetException invocation && invocation.getCause() != null
                    ? invocation.getCause()
                    : exception;
            String detail = cause.getMessage() == null ? cause.getClass().getSimpleName() : cause.getMessage();
            source.sendError(Text.literal("Could not call Baritone. Make sure it is installed and enabled. " + detail));
            return 0;
        }
    }

    private static String validateInstruction(String instruction) {
        String[] parts = instruction.trim().split("\\s+");
        if (parts.length == 0 || parts[0].isBlank()) {
            throw usageError();
        }

        parts[0] = parts[0].toLowerCase(Locale.ROOT);
        switch (parts[0]) {
            case "goto" -> {
                if (parts.length != 4) {
                    throw usageError();
                }
                for (int i = 1; i < parts.length; i++) {
                    try {
                        parts[i] = Integer.toString(Integer.parseInt(parts[i]));
                    } catch (NumberFormatException exception) {
                        throw new IllegalArgumentException("Coordinates for 'goto' must be integers: /ai goto <x> <y> <z>");
                    }
                }
            }
            case "mine" -> {
                if (parts.length != 2 || !parts[1].matches("[a-zA-Z0-9_.-]+:[a-zA-Z0-9_./-]+|[a-zA-Z0-9_./-]+")) {
                    throw new IllegalArgumentException("Usage: /ai mine <block_id>");
                }
            }
            case "follow" -> {
                if (parts.length != 2 || !parts[1].matches("[A-Za-z0-9_]{1,16}")) {
                    throw new IllegalArgumentException("Usage: /ai follow <player_name>");
                }
            }
            case "stop", "come" -> {
                if (parts.length != 1) {
                    throw usageError();
                }
            }
            default -> throw usageError();
        }

        return String.join(" ", parts);
    }

    private static IllegalArgumentException usageError() {
        return new IllegalArgumentException("Usage: /ai goto <x> <y> <z> | mine <block_id> | follow <player_name> | come | stop");
    }

    private static void runBaritoneCommand(String command) throws ReflectiveOperationException {
        Class<?> api = Class.forName("baritone.api.BaritoneAPI");
        Method getProvider = api.getMethod("getProvider");
        Object provider = getProvider.invoke(null);

        Method getPrimaryBaritone = getProvider.getReturnType().getMethod("getPrimaryBaritone");
        Object baritone = getPrimaryBaritone.invoke(provider);

        Method getCommandManager = getPrimaryBaritone.getReturnType().getMethod("getCommandManager");
        Object commandManager = getCommandManager.invoke(baritone);

        Method execute = getCommandManager.getReturnType().getMethod("execute", String.class);
        execute.invoke(commandManager, command);
    }
}