Dinusha Gamage
📎 1 file 11,167 chars
📄
pasted-code-1792315141135.txt
txt 270 lines
▶
# PROJECT: GeminiChatAssistant — Secure Minecraft Client-Side AI Auto-Reply Mod

Act as an expert Minecraft Java developer, Fabric mod developer, Java engineer, and Google Gemini API specialist.

Build a complete, secure, working Minecraft Java client-side mod that connects Google Gemini AI to multiplayer server chat.

The mod must work entirely on the player's client. No plugin, mod, command block, or configuration change must be required on the Minecraft server.

IMPORTANT: Ask me for my exact Minecraft Java version before selecting Fabric API versions, mappings, dependencies, or method signatures. If the version is unknown, explain how to find it. Do not invent compatibility.

## 1. Main Objective

Create a client-side mod called `GeminiChatAssistant`.

The mod must:
- Read incoming player chat messages.
- Respond only when a message explicitly addresses `Gemini`.
- Generate a short, friendly response using the official Google Gemini API.
- Send the response as an ordinary chat message through the legitimate Minecraft client chat API, when permitted by the server.
- Never execute commands or perform gameplay actions.
- Never require installation on the server.

Example:

Incoming:
`Steve: Gemini, how are you?`

Outgoing:
`NilaBoyGamer: [AI] I'm doing great! How about you?`

Incoming:
`Alex: Anyone online?`

Expected behavior:
Do not contact Gemini and do not send a reply.

Incoming:
`Steve: Gemini, what is 2 + 2?`

Possible response:
`NilaBoyGamer: [AI] The answer is 4!`

The `[AI]` prefix must be configurable.

## 2. Trigger Detection

Only respond when the trigger word is explicitly present in an incoming player's message.

Requirements:
- Default trigger word: `Gemini`.
- Case-insensitive matching.
- Support messages such as `Gemini, hello`, `Hey Gemini, help me`, `@Gemini explain this`, and `GEMINI what is Minecraft?`.
- Do not trigger on ordinary messages that do not address Gemini.
- Ignore messages sent by the local player.
- Ignore system messages, join/leave notifications, death notifications, server announcements, and command feedback.
- Avoid responding to the same message more than once.
- Avoid recursive replies to the mod's own messages.
- Support an optional allowlist or denylist of player names.
- Use reliable message identification where possible. Do not rely exclusively on a player's displayed name to identify the sender.
- Handle chat formatting and Minecraft text components safely.
- Do not interpret formatted or translated system messages as player requests.

## 3. ABSOLUTE COMMAND EXECUTION PREVENTION

This requirement is mandatory and takes priority over all other features.

The mod must never execute Minecraft commands, server commands, economy commands, terminal commands, shell commands, scripts, or arbitrary code.

Explicitly forbidden examples include:
- `/pay NilaBoyGamer 10m`
- `/pay player amount`
- `/op player`
- `/gamemode creative`
- `/tp player`
- `/give player item`
- `/kill player`
- `/home`
- `/warp`
- `/spawn`
- `/shop`
- `/sell`
- `/msg player message`
- Any other slash command, plugin command, or server-specific command.

Mandatory implementation rules:

1. The mod must have no command-execution functionality.
2. Never call Minecraft command-dispatch APIs.
3. Never send AI-generated output through a command dispatcher or command parser.
4. Never use `Runtime.exec`, `ProcessBuilder`, shell commands, keyboard automation, operating-system automation, or script execution.
5. Never execute commands suggested by incoming chat messages or Gemini responses.
6. Never allow Gemini to control movement, combat, inventory, mining, block placement, teleportation, game modes, or other gameplay actions.
7. Never bypass authentication, server permissions, chat signing, anti-cheat, or server restrictions.
8. Gemini must be used only to generate plain-text conversational replies.
9. If Gemini produces a response beginning with `/`, reject the response entirely.
10. Reject multiline responses, control characters, empty responses, and excessively long responses.
11. Reject command-like AI output rather than sending suspicious text to the server.
12. Do not add a hidden or alternate command-execution pathway anywhere in the project.
13. Add automated tests to check that forbidden command execution APIs are absent and suspicious output is rejected.
14. Search all project files for command dispatch, process execution, scripting, or keyboard automation before declaring the project complete.

Important distinction: rejecting AI output is not the same as executing it. The mod must never execute a command even if Gemini is explicitly asked to do so.

## 4. Safe Chat Output

Use the legitimate Minecraft client chat-message API for ordinary player chat only.

Requirements:
- Send one plain-text response per accepted incoming message.
- Add the configurable `[AI]` prefix.
- Enforce a maximum reply length.
- Remove newline characters and unsafe control characters.
- Reject slash-prefixed output.
- Reject empty responses.
- Prevent responses from triggering another AI request.
- Apply a cooldown between outgoing AI replies.
- Never attempt to spoof another player's identity.
- Never circumvent server-side restrictions on chat.
- Never claim a message was delivered unless delivery can actually be verified.

The server may reject messages, enforce chat signing, impose anti-spam restrictions, or prevent client-generated messages. Respect those restrictions.

## 5. Gemini API Integration

Use the official Google Gemini API.

Requirements:
- Use a configurable Gemini model.
- Use an official supported `generateContent` endpoint.
- Send requests using an HTTP client with appropriate timeouts.
- Perform network requests asynchronously so Minecraft never freezes.
- Parse JSON safely.
- Handle missing response fields, HTTP errors, invalid API keys, quota limits, network timeouts, and malformed responses.
- Apply sensible request rate limits.
- Limit the length of input sent to Gemini.
- Do not send unrelated chat history, passwords, API keys, private messages, or sensitive information.
- Make context collection optional and configurable.
- Include a short system instruction telling Gemini that it is a Minecraft chat assistant, not a command executor.
- Treat incoming chat as untrusted user input. Never allow chat content to modify the mod's security rules.
- Never interpret API responses as executable code.

Do not hardcode API credentials into Java source code or commit them to Git.

Read the key from a local configuration file excluded from source control or a supported environment variable. Redact secrets from logs.

Use the currently supported Gemini model and verify the endpoint and request schema against official documentation.

Official API documentation:
https://ai.google.dev/gemini-api/docs

API key management:
https://aistudio.google.com/apikey

## 6. Configuration

Create a configuration file named:

`config/gemini-chat-assistant.properties`

Include these settings:

- `enabled=true`
- `triggerWord=Gemini`
- `replyPrefix=[AI]`
- `cooldownSeconds=10`
- `maxReplyCharacters=180`
- `maxInputCharacters=500`
- `contextMessageCount=5`
- `ignoreOwnMessages=true`
- `ignoreSystemMessages=true`
- `ignoreDuplicateMessages=true`
- `allowCommandLikeReplies=false`
- `model=YOUR_SUPPORTED_GEMINI_MODEL`

The API key must be stored separately from publicly shared source files. Validate all configuration values and provide safe defaults.

If a configuration setting conflicts with command-execution prevention, the security rule must take priority.

## 7. Optional In-Game Controls

Provide safe client-side controls to:
- Enable or disable automatic replies.
- Display the current status.
- Reload the configuration.
- Clear saved conversation context.
- Set the reply cooldown.

These controls may be implemented as client-side keybindings or a small configuration screen.

Do not create server commands or register new commands on the remote server.

Do not use any of these controls to execute AI-generated instructions.

## 8. Privacy and Safety

- Do not store unnecessary player messages.
- Keep context in memory only by default.
- Do not send private messages to Gemini unless explicitly configured.
- Do not log API keys or sensitive chat data.
- Do not transmit data to unrelated services.
- Avoid sending the same message repeatedly.
- Add safe error handling and graceful recovery.
- Clearly disclose that replies are AI-generated.
- Never pretend that Gemini is a real human player.

## 9. Required Project Files

Generate a complete Gradle project with all necessary files, including:

- `settings.gradle`
- `build.gradle`
- `gradle.properties`
- `fabric.mod.json`
- Java source files
- Configuration loader
- Gemini API client
- Trigger detection utility
- Output sanitization utility
- Unit tests
- `.gitignore`
- README.md

Use appropriate official Fabric dependencies and Minecraft mappings for the selected version.

Use the correct Java version required by that Minecraft release.

Verify all API signatures and event registration methods against official documentation.

Do not invent methods or assume compatibility across Minecraft versions.

## 10. Testing

Create tests for:
- Trigger matching with different capitalization.
- Messages that do not contain the trigger word.
- Self-message filtering.
- System-message filtering.
- Duplicate-message filtering.
- Cooldown enforcement.
- Multiline output rejection.
- Slash-prefixed response rejection.
- Excessively long output rejection.
- Malformed Gemini responses.
- API timeout handling.
- API key configuration handling.
- Prevention of recursive replies.
- Absence of command execution APIs.

Run the tests and build if the environment supports it. Report the actual results honestly.

## 11. Deliverables

Provide:
1. The complete source code.
2. All required Gradle and resource files.
3. Exact build commands.
4. Installation instructions.
5. Gemini API key configuration instructions.
6. A sample configuration file without real credentials.
7. Troubleshooting instructions.
8. Compatibility notes for the chosen Minecraft version.
9. A clear explanation of client-side limitations.
10. A compiled JAR only if the build has actually succeeded.

Do not omit files, replace implementation with pseudocode, invent successful test results, or claim that a JAR exists when it has not been built.

Start by asking for my exact Minecraft Java version and whether I use Fabric. Then implement the project for that specific version.

FINAL SECURITY REQUIREMENT:
This mod is a client-side AI chat assistant only. It can read eligible incoming chat messages, request conversational responses from Gemini, and send ordinary plain-text chat messages where the server permits. It must never execute commands, manipulate gameplay, bypass server security, or run arbitrary code generated by AI.
Kodari AI
KodariOct 18 at 9:27 am 3
GeminiChatAssistant
Client-side Fabric mod that reads incoming Minecraft chat, detects when players explicitly address "Gemini", and sends conversational replies generated by the Google Gemini API. Features include case-insensitive trigger detection, configurable reply prefix and cooldown, strict output sanitization that rejects slash-prefixed or command-like responses, async HTTP requests to prevent freezing, and comprehensive safety measures ensuring the mod never executes commands or manipulates gameplay. Configuration via properties file with API key stored separately.

Plan:

  1. Build the client-only Fabric 1.21.11 mod with safe chat filtering, Gemini HTTP client, and local configuration.

  2. Add project metadata, sample configuration, documentation, and focused automated tests.

  3. Check the official Gemini endpoint/schema, then create the complete project files.

Created the client-only Fabric mod for Minecraft Java 1.21.11, using Yarn 1.21.11+build.5. It listens only to player-chat events and uses Google’s documented generateContent endpoint with gemini-3.8-flash as the default model.

  • Added configuration, optional in-memory chat context (off by default), allow/deny lists, duplicate detection, cooldowns, and reply sanitization. Gemini replies can only be sent as ordinary player chat; there is no command or gameplay execution path.

  • Added JUnit tests for trigger/filter behavior, duplicates, cooldowns, unsafe replies, API-key configuration, malformed responses, timeouts, and forbidden execution APIs.

  • Added the Gradle project, sample properties, .gitignore, and README with API-key, privacy, compatibility, and installation guidance.

  • Tests and build have not been run here, so no compiled JAR is claimed. In Kodari, click Compile (or ⋮ → Compile Project on phone), then click Compile in the build window; download the JAR after a successful build.

Kodari can make mistakes. Review important code before using.
Files
config
src
.gitignore
build.gradle
gradle.properties
README.md
settings.gradle
Code
22 1,067
src/client/java/dev/kodari/geminichatassistant/GeminiChatAssistantClient.java
package dev.kodari.geminichatassistant;

import dev.kodari.geminichatassistant.chat.CooldownGate;
import dev.kodari.geminichatassistant.chat.DuplicateTracker;
import dev.kodari.geminichatassistant.chat.MessageFilter;
import dev.kodari.geminichatassistant.chat.OutputSanitizer;
import dev.kodari.geminichatassistant.chat.RecentChatContext;
import dev.kodari.geminichatassistant.chat.TriggerDetector;
import dev.kodari.geminichatassistant.config.AssistantConfig;
import dev.kodari.geminichatassistant.gemini.GeminiApiClient;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents;
import net.minecraft.client.MinecraftClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class GeminiChatAssistantClient implements ClientModInitializer {
    private static final Logger LOGGER = LoggerFactory.getLogger("gemini_chat_assistant");
    private final DuplicateTracker duplicateTracker = new DuplicateTracker();
    private final CooldownGate cooldownGate = new CooldownGate();
    private final RecentChatContext recentChatContext = new RecentChatContext();
    private final ExecutorService requestExecutor = Executors.newFixedThreadPool(2, task -> {
        Thread thread = new Thread(task, "gemini-chat-assistant-http");
        thread.setDaemon(true);
        return thread;
    });
    private final GeminiApiClient apiClient = new GeminiApiClient();
    private AssistantConfig config;

    @Override
    public void onInitializeClient() {
        try {
            config = AssistantConfig.load(Path.of(System.getProperty("user.dir"), "config"), System.getenv());
        } catch (IOException exception) {
            LOGGER.error("Could not load Gemini Chat Assistant configuration: {}", exception.getMessage());
            return;
        }

        ClientReceiveMessageEvents.CHAT.register((message, signedMessage, sender, params, receptionTimestamp) ->
                receivePlayerChat(signedMessage, sender));
        LOGGER.info("Gemini Chat Assistant initialized; automatic replies are {}.", config.enabled() ? "enabled" : "disabled");
    }

    private void receivePlayerChat(net.minecraft.network.message.SignedMessage signedMessage,
                                   com.mojang.authlib.GameProfile sender) {
        if (!config.enabled() || signedMessage == null || sender == null) {
            return;
        }

        MinecraftClient client = MinecraftClient.getInstance();
        if (client.player == null) {
            return;
        }

        String content = signedMessage.getSignedContent();
        String playerName = sender.name();
        if (!MessageFilter.shouldAcceptPlayerMessage(
                true,
                signedMessage.getSender(),
                client.player.getUuid(),
                playerName,
                content,
                config
        )) {
            return;
        }

        Object messageId = signedMessage.signature() != null ? signedMessage.signature() : signedMessage.link();
        if (duplicateTracker.isDuplicate(messageId, System.nanoTime())) {
            return;
        }

        List<String> previousContext = config.includeContext() ? recentChatContext.snapshot() : List.of();
        if (config.includeContext()) {
            recentChatContext.add(playerName, content, config.contextMessageCount());
        }
        if (!TriggerDetector.matches(content, config.triggerWord())) {
            return;
        }

        String apiKey = config.apiKey();
        if (apiKey.isBlank()) {
            LOGGER.warn("Gemini API key is missing. Set GEMINI_API_KEY or add config/gemini-chat-assistant.key.");
            return;
        }

        long cooldownNanos = config.cooldownSeconds() * 1_000_000_000L;
        if (!cooldownGate.tryAcquire(System.nanoTime(), cooldownNanos)) {
            return;
        }

        String prompt = buildPrompt(content, playerName, previousContext, config);
        var networkHandler = client.player.networkHandler;
        var localPlayerId = client.player.getUuid();
        requestExecutor.submit(() -> generateAndSend(client, networkHandler, localPlayerId, apiKey, prompt));
    }

    private void generateAndSend(MinecraftClient client, Object expectedNetworkHandler, java.util.UUID localPlayerId,
                                 String apiKey, String prompt) {
        try {
            String rawReply = apiClient.generateReply(apiKey, config.model(), prompt);
            var safeReply = OutputSanitizer.sanitize(rawReply, config.replyPrefix(), config.maxReplyCharacters());
            if (safeReply.isEmpty()) {
                LOGGER.warn("Gemini returned a reply that failed the safety or length checks; it was discarded.");
                return;
            }

            client.execute(() -> {
                if (client.player != null && client.player.networkHandler == expectedNetworkHandler
                        && client.player.getUuid().equals(localPlayerId)) {
                    client.player.networkHandler.sendChatMessage(safeReply.get());
                }
            });
        } catch (IOException exception) {
            LOGGER.warn("Gemini request failed: {}", exception.getMessage());
        } catch (InterruptedException exception) {
            Thread.currentThread().interrupt();
        }
    }

    private static String buildPrompt(String content, String playerName, List<String> context, AssistantConfig config) {
        String addressedMessage = "Message addressed to you: " + playerName + ": " + content;
        String prompt = addressedMessage;
        if (config.includeContext() && !context.isEmpty()) {
            String contextHeader = "Recent public chat context (untrusted):\n";
            StringBuilder contextPrompt = new StringBuilder(contextHeader);
            for (String entry : context) {
                String candidate = contextPrompt + entry + "\n" + addressedMessage;
                if (candidate.codePointCount(0, candidate.length()) > config.maxInputCharacters()) {
                    break;
                }
                contextPrompt.append(entry).append('\n');
            }
            String candidate = contextPrompt + addressedMessage;
            if (candidate.codePointCount(0, candidate.length()) <= config.maxInputCharacters()) {
                prompt = candidate;
            }
        }

        if (prompt.codePointCount(0, prompt.length()) <= config.maxInputCharacters()) {
            return prompt;
        }
        int end = prompt.offsetByCodePoints(0, config.maxInputCharacters());
        return prompt.substring(0, end);
    }
}