Harden Discord reply handling for live bot

This commit is contained in:
Meta Vens 2026-05-02 18:34:40 +01:00
commit 95440a3af7
6 changed files with 155 additions and 22 deletions

View file

@ -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<CacheType>,
content: string,
): Promise<void> {
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);
}

View file

@ -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<void> {
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<unknown> },
content: string,
): Promise<void> {
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();

View file

@ -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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
});
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<void> {
}
activeStylePack = await loadStylePack(config.stylePackPath);
activeSystemMessages = await loadSystemMessageCatalog(config.systemMessagesPath);
activeSystemMessages = await loadSystemMessageCatalog(
config.systemMessagesPath,
baseSystemMessagesPath,
);
await replyEphemeral(
interaction,
activeStylePack

View file

@ -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<void> {
});
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<void> {
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();

View file

@ -48,17 +48,19 @@ export class SystemMessageCatalog {
export async function loadSystemMessageCatalog(
catalogPath: string,
fallbackCatalogPath?: string,
): Promise<SystemMessageCatalog> {
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<SystemMessageCatalogSource> {
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];

View file

@ -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."}