From 95440a3af7ad6263163cb44e54c696e36c6c2950 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 2 May 2026 18:34:40 +0100 Subject: [PATCH] Harden Discord reply handling for live bot --- apps/bot/src/discord-bot-handlers.ts | 29 ++++++-- apps/bot/src/discord-bot-support.ts | 73 +++++++++++++++++++++ apps/bot/src/discord-bot.ts | 23 +++++-- apps/worker/src/index.ts | 12 +++- packages/core/src/system-message-catalog.ts | 37 ++++++++--- state/evidence.jsonl | 1 + 6 files changed, 154 insertions(+), 21 deletions(-) diff --git a/apps/bot/src/discord-bot-handlers.ts b/apps/bot/src/discord-bot-handlers.ts index ec18049..67f0b21 100644 --- a/apps/bot/src/discord-bot-handlers.ts +++ b/apps/bot/src/discord-bot-handlers.ts @@ -43,6 +43,8 @@ import { inferSourceGroundingHint, renderRateLimitMessage, renderSystemMessage, + sendChunkedChannelMessage, + splitDiscordContent, truncate, } from "./discord-bot-support"; @@ -564,12 +566,31 @@ export async function replyEphemeral( interaction: ChatInputCommandInteraction, content: string, ): Promise { - if (interaction.replied || interaction.deferred) { - await interaction.followUp({ content, ephemeral: true }); + const chunks = splitDiscordContent(content); + + if (interaction.replied) { + for (const chunk of chunks) { + await interaction.followUp({ content: chunk, ephemeral: true }); + } + return; } - await interaction.reply({ content, ephemeral: true }); + if (interaction.deferred) { + await interaction.editReply({ content: chunks[0] }); + + for (const chunk of chunks.slice(1)) { + await interaction.followUp({ content: chunk, ephemeral: true }); + } + + return; + } + + await interaction.reply({ content: chunks[0], ephemeral: true }); + + for (const chunk of chunks.slice(1)) { + await interaction.followUp({ content: chunk, ephemeral: true }); + } } function pickProvider( @@ -605,5 +626,5 @@ async function postFinalResponse(client: Client, job: JobRecord, finalResponse: throw new Error(`Channel ${job.outputChannelId} is not available for publishing.`); } - await channel.send(finalResponse); + await sendChunkedChannelMessage(channel, finalResponse); } diff --git a/apps/bot/src/discord-bot-support.ts b/apps/bot/src/discord-bot-support.ts index 6d45bf4..91dcc1e 100644 --- a/apps/bot/src/discord-bot-support.ts +++ b/apps/bot/src/discord-bot-support.ts @@ -413,6 +413,57 @@ export function truncate(input: string, limit: number): string { return `${input.slice(0, limit - 3)}...`; } +export function splitDiscordContent(input: string, limit = 1900): string[] { + const normalized = input.replace(/\r\n/g, "\n").trim(); + + if (normalized.length === 0) { + return ["(empty response)"]; + } + + if (normalized.length <= limit) { + return [normalized]; + } + + const chunks: string[] = []; + let remaining = normalized; + + while (remaining.length > limit) { + const splitIndex = findSplitIndex(remaining, limit); + const nextChunk = remaining.slice(0, splitIndex).trim(); + chunks.push(nextChunk.length > 0 ? nextChunk : remaining.slice(0, limit)); + remaining = remaining.slice(splitIndex).trimStart(); + } + + if (remaining.length > 0) { + chunks.push(remaining); + } + + return chunks; +} + +export async function replyToMessage(message: Message, content: string): Promise { + const chunks = splitDiscordContent(content); + + await message.reply(chunks[0]); + + if (!canSendMessages(message.channel)) { + return; + } + + for (const chunk of chunks.slice(1)) { + await message.channel.send(chunk); + } +} + +export async function sendChunkedChannelMessage( + channel: TextBasedChannel & { send: (content: string) => Promise }, + content: string, +): Promise { + for (const chunk of splitDiscordContent(content)) { + await channel.send(chunk); + } +} + export function formatDurationSeconds(totalSeconds: number): string { const seconds = Math.max(1, Math.ceil(totalSeconds)); @@ -437,6 +488,28 @@ export function formatDurationSeconds(totalSeconds: number): string { : `${hours}h ${remainderMinutes}m`; } +function findSplitIndex(input: string, limit: number): number { + const doubleNewline = input.lastIndexOf("\n\n", limit); + + if (doubleNewline >= Math.floor(limit * 0.6)) { + return doubleNewline + 2; + } + + const newline = input.lastIndexOf("\n", limit); + + if (newline >= Math.floor(limit * 0.6)) { + return newline + 1; + } + + const space = input.lastIndexOf(" ", limit); + + if (space >= Math.floor(limit * 0.6)) { + return space + 1; + } + + return limit; +} + export function formatUtcTimestamp(timestamp: string): string { const date = new Date(timestamp); const year = date.getUTCFullYear(); diff --git a/apps/bot/src/discord-bot.ts b/apps/bot/src/discord-bot.ts index 74faa91..f209bc1 100644 --- a/apps/bot/src/discord-bot.ts +++ b/apps/bot/src/discord-bot.ts @@ -1,3 +1,5 @@ +import { resolve } from "node:path"; + import { Client, Events, @@ -58,6 +60,7 @@ import { ingestIfIndexed, materializeMessage, notifyOwnerOfBotIssue, + replyToMessage, rememberAmbientVoidReference, renderSystemMessage, stripBotMention, @@ -99,8 +102,12 @@ export async function startBot(): Promise { config.rateLimits, ); const contextBuilder = new ContextBuilder(); + const baseSystemMessagesPath = resolve("config/system-messages.json"); let activeStylePack = await loadStylePack(config.stylePackPath); - let activeSystemMessages = await loadSystemMessageCatalog(config.systemMessagesPath); + let activeSystemMessages = await loadSystemMessageCatalog( + config.systemMessagesPath, + baseSystemMessagesPath, + ); const archiveRepository = new FileMessageArchiveRepository(config.ragArchivePath); const sourceArchiveRepository = new FileSourceDocumentArchiveRepository( config.ragSourceArchivePath, @@ -274,7 +281,10 @@ export async function startBot(): Promise { const prompt = stripBotMention(message.content).trim(); if (!prompt) { - await message.reply(renderSystemMessage(activeSystemMessages, "mention.missing_prompt")); + await replyToMessage( + message, + renderSystemMessage(activeSystemMessages, "mention.missing_prompt"), + ); return; } @@ -289,7 +299,7 @@ export async function startBot(): Promise { requestMessageId: message.id, channel: message.channel.isTextBased() ? message.channel : null, respond: async (content) => { - await message.reply(content); + await replyToMessage(message, content); }, config, permissionEngine, @@ -360,6 +370,7 @@ export async function startBot(): Promise { const requestedProvider = parseProviderOverride( interaction.options.getString("provider", false), ); + await interaction.deferReply({ ephemeral: true }); await handlePrompt({ prompt: interaction.options.getString("question", true), command: "ask", @@ -388,6 +399,7 @@ export async function startBot(): Promise { }); break; case "queue-codex": + await interaction.deferReply({ ephemeral: true }); await handlePrompt({ prompt: interaction.options.getString("prompt", true), command: "queue-codex", @@ -471,7 +483,10 @@ export async function startBot(): Promise { } activeStylePack = await loadStylePack(config.stylePackPath); - activeSystemMessages = await loadSystemMessageCatalog(config.systemMessagesPath); + activeSystemMessages = await loadSystemMessageCatalog( + config.systemMessagesPath, + baseSystemMessagesPath, + ); await replyEphemeral( interaction, activeStylePack diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index fc2e4f1..fcd5769 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -1,7 +1,7 @@ import "dotenv/config"; import { mkdir, writeFile } from "node:fs/promises"; -import { join } from "node:path"; +import { join, resolve } from "node:path"; import { loadConfig } from "@voidbot/config"; import { @@ -93,7 +93,10 @@ async function main(): Promise { }); jobQueue = stateJobQueue; auditLog = stateAuditLog; - systemMessages = await loadSystemMessageCatalog(config.systemMessagesPath); + systemMessages = await loadSystemMessageCatalog( + config.systemMessagesPath, + resolve("config/system-messages.json"), + ); providerRegistry = await buildProviderRegistry(systemMessages); console.log(`VoidBot worker polling every ${config.workerPollIntervalMs}ms.`); await processPendingJobs(); @@ -110,7 +113,10 @@ async function processPendingJobs(): Promise { isProcessing = true; try { - systemMessages = await loadSystemMessageCatalog(config.systemMessagesPath); + systemMessages = await loadSystemMessageCatalog( + config.systemMessagesPath, + resolve("config/system-messages.json"), + ); providerRegistry = await buildProviderRegistry(systemMessages); const jobs = await jobQueue.claimRunnableJobs(); diff --git a/packages/core/src/system-message-catalog.ts b/packages/core/src/system-message-catalog.ts index bd231aa..3e89b08 100644 --- a/packages/core/src/system-message-catalog.ts +++ b/packages/core/src/system-message-catalog.ts @@ -48,17 +48,19 @@ export class SystemMessageCatalog { export async function loadSystemMessageCatalog( catalogPath: string, + fallbackCatalogPath?: string, ): Promise { - const source = await readFile(catalogPath, "utf8"); - const parsed = JSON.parse(source) as unknown; + const fallbackMessages = + fallbackCatalogPath && fallbackCatalogPath !== catalogPath + ? await readSystemMessageCatalogSource(fallbackCatalogPath) + : {}; + const primaryMessages = await readSystemMessageCatalogSource(catalogPath); + const mergedMessages = { + ...fallbackMessages, + ...primaryMessages, + }; - if (!isSystemMessageCatalogSource(parsed)) { - throw new Error( - `System message catalog at ${catalogPath} must be a JSON object whose values are strings or arrays of strings.`, - ); - } - - const invalidKeys = Object.entries(parsed) + const invalidKeys = Object.entries(mergedMessages) .filter(([, value]) => normalizeVariants(value).length === 0) .map(([key]) => key); @@ -68,7 +70,7 @@ export async function loadSystemMessageCatalog( ); } - return new SystemMessageCatalog(parsed); + return new SystemMessageCatalog(mergedMessages); } function isSystemMessageCatalogSource( @@ -99,6 +101,21 @@ function normalizeVariants(value: string | string[] | undefined): string[] { .filter((entry) => entry.length > 0); } +async function readSystemMessageCatalogSource( + catalogPath: string, +): Promise { + const source = await readFile(catalogPath, "utf8"); + const parsed = JSON.parse(source) as unknown; + + if (!isSystemMessageCatalogSource(parsed)) { + throw new Error( + `System message catalog at ${catalogPath} must be a JSON object whose values are strings or arrays of strings.`, + ); + } + + return parsed; +} + function shuffleVariants(variants: string[], lastUsed?: string): string[] { const shuffled = [...variants]; diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 13a33a7..ebd2543 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -17,3 +17,4 @@ {"ts":"2026-05-01T17:24:56Z","type":"architecture","status":"ok","note":"Moved deeper personality, culture, prompt-projection, and Aetheria persistent-world design notes into the sibling Ghostlight repo so VoidBot remains a consumer instead of the long-term home for that research."} {"ts":"2026-05-02T11:48:55Z","type":"implementation","status":"ok","note":"Source repo indexing now auto-reconciles during startup and watchdog runs, and the source archive is sharded by repo behind a manifest because the old monolithic source-documents.json hit real size limits and broke incremental writes."} {"ts":"2026-05-02T14:05:54Z","type":"implementation","status":"ok","note":"Scheduled-task helpers must anchor repo-relative scripts, dotenv loading, and path resolution to the VoidBot root; relying on cwd keeps sending System32 in to eat them."} +{"ts":"2026-05-02T17:34:02Z","type":"implementation","status":"ok","note":"Layered private system message catalogs over the tracked base, deferred slow slash replies before provider execution, and chunked Discord output so missing keys and overlong local_llm replies stop failing live interactions."}