Refactor Discord bot seams

This commit is contained in:
Meta Vens 2026-04-26 03:28:21 +01:00
commit 1856123451
8 changed files with 1192 additions and 1101 deletions

View file

@ -0,0 +1,609 @@
import {
REST,
Routes,
SlashCommandBuilder,
type CacheType,
type ChatInputCommandInteraction,
type Client,
type TextBasedChannel,
} from "discord.js";
import type { AppConfig } from "@voidbot/config";
import {
ContextBuilder,
PermissionEngine,
type AuditLog,
type InteractionMemoryBank,
type JobQueue,
type SystemMessageCatalog,
type VoidUsageRateLimiter,
} from "@voidbot/core";
import type { ProviderRegistry } from "@voidbot/providers";
import {
FileSourceDocumentArchiveRepository,
RagPipeline,
RetrievalService,
} from "@voidbot/rag";
import {
type Actor,
type CommandName,
type GuildContext,
type JobRecord,
type ProviderName,
type StylePack,
isProviderName,
shouldIndexChannel,
} from "@voidbot/shared";
import {
buildChannelIndexingTarget,
canSendMessages,
convertDiscordMessageToArchive,
getRecentMessages,
inferSourceGroundingHint,
renderRateLimitMessage,
renderSystemMessage,
truncate,
} from "./discord-bot-support";
export const commandDefinitions = [
new SlashCommandBuilder()
.setName("ask")
.setDescription("Ask VoidBot a question.")
.addStringOption((option) =>
option.setName("question").setDescription("What do you want to ask?").setRequired(true),
)
.addStringOption((option) =>
option
.setName("provider")
.setDescription("Override the provider instead of using auto-selection.")
.setRequired(false)
.addChoices(
{ name: "Auto", value: "auto" },
{ name: "Owner Codex", value: "owner_codex" },
{ name: "Local LLM", value: "local_llm" },
),
),
new SlashCommandBuilder()
.setName("queue-codex")
.setDescription("Force a fuller owner-only Codex handoff.")
.addStringOption((option) =>
option.setName("prompt").setDescription("The owner workflow prompt.").setRequired(true),
),
new SlashCommandBuilder()
.setName("approve-job")
.setDescription("Approve a queued job or post its final response.")
.addStringOption((option) =>
option.setName("job-id").setDescription("The job id to approve.").setRequired(true),
)
.addStringOption((option) =>
option
.setName("response")
.setDescription("Optional final response to publish when the job is awaiting post approval.")
.setRequired(false),
),
new SlashCommandBuilder()
.setName("reject-job")
.setDescription("Reject a queued job.")
.addStringOption((option) =>
option.setName("job-id").setDescription("The job id to reject.").setRequired(true),
)
.addStringOption((option) =>
option.setName("reason").setDescription("Optional rejection reason.").setRequired(false),
),
new SlashCommandBuilder()
.setName("provider-status")
.setDescription("Show current provider availability for you."),
new SlashCommandBuilder()
.setName("search-history")
.setDescription("Search indexed channel history.")
.addStringOption((option) =>
option.setName("query").setDescription("What to search for.").setRequired(true),
),
new SlashCommandBuilder()
.setName("summarize-channel")
.setDescription("Summarize recent messages in this channel."),
new SlashCommandBuilder()
.setName("reindex-channel")
.setDescription("Reindex the current indexed channel."),
new SlashCommandBuilder()
.setName("set-style")
.setDescription("Reload the configured style pack from disk."),
];
export interface PromptHandlerOptions {
prompt: string;
command: CommandName;
actor: Actor;
roleIds: string[];
guildContext: GuildContext;
outputChannelId: string;
requestMessageId?: string;
channel: TextBasedChannel | null;
respond: (content: string) => Promise<void>;
config: AppConfig;
permissionEngine: PermissionEngine;
contextBuilder: ContextBuilder;
retrievalService: RetrievalService;
sourceArchiveRepository: FileSourceDocumentArchiveRepository;
jobQueue: JobQueue;
auditLog: AuditLog;
interactionMemory: InteractionMemoryBank;
voidUsageRateLimiter: VoidUsageRateLimiter;
providerRegistry: ProviderRegistry;
stylePack?: StylePack;
systemMessages: SystemMessageCatalog;
forceProvider?: ProviderName;
silentOwnerQueueAck?: boolean;
}
export async function handlePrompt(options: PromptHandlerOptions): Promise<void> {
const providerName =
options.forceProvider ?? pickProvider(options.actor, options.guildContext, options.providerRegistry);
if (!providerName) {
await options.respond(
renderSystemMessage(options.systemMessages, "provider.none_available"),
);
return;
}
const provider = options.providerRegistry.get(providerName);
if (!provider) {
await options.respond(
renderSystemMessage(options.systemMessages, "provider.missing_registration", {
providerName,
}),
);
return;
}
const access = options.permissionEngine.canUseProvider(options.actor, providerName);
if (!access.allowed) {
await options.respond(
access.reasonKey
? renderSystemMessage(options.systemMessages, access.reasonKey)
: renderSystemMessage(options.systemMessages, "provider.access_denied.generic"),
);
return;
}
const rateLimitDecision = await options.voidUsageRateLimiter.consume({
actorId: options.actor.id,
roleIds: options.roleIds,
command: options.command,
provider: providerName,
guildId: options.guildContext.guildId,
channelId: options.guildContext.channelId,
});
if (!rateLimitDecision.allowed) {
await options.auditLog.record({
type: "rate_limit.denied",
actorId: options.actor.id,
provider: providerName,
details: {
command: options.command,
reason: rateLimitDecision.reason,
dailyCount: rateLimitDecision.dailyCount,
dailyLimit: rateLimitDecision.policy.dailyLimit ?? null,
cooldownSeconds: rateLimitDecision.policy.cooldownSeconds ?? null,
retryAfterSeconds: rateLimitDecision.retryAfterSeconds ?? null,
resetsAt: rateLimitDecision.resetsAt ?? null,
modifier: rateLimitDecision.policy.modifier,
matchedSubjects: rateLimitDecision.policy.matchedSubjects,
},
});
await options.respond(renderRateLimitMessage(options.systemMessages, rateLimitDecision));
return;
}
const rememberedInteraction = await options.interactionMemory.recordInteraction({
actorId: options.actor.id,
actorName: options.actor.displayName,
sourceKind: "direct_prompt",
guildId: options.guildContext.guildId,
channelId: options.guildContext.channelId,
channelName: options.guildContext.channelName,
command: options.command,
prompt: options.prompt,
eventId: options.requestMessageId,
});
const interactionMemory =
rememberedInteraction.totalInteractions > 0 ? rememberedInteraction : undefined;
const recentMessages = await getRecentMessages(options.channel, 10);
const sourceGrounding = inferSourceGroundingHint(
options.prompt,
await options.sourceArchiveRepository.listRepoSummaries(),
);
const shouldAttachInitialRetrieval =
!provider.getCapabilities().includes("tool_driven_retrieval") &&
(shouldIndexChannel(options.config.channelIndexing, buildChannelIndexingTarget(options.channel)) ||
providerName !== "owner_codex");
const retrieval = shouldAttachInitialRetrieval
? await options.retrievalService.search(options.prompt, 5, {
guildId: options.guildContext.guildId,
corpusKind: "discord_history",
})
: [];
const contextBundle = options.contextBuilder.build({
prompt: options.prompt,
actor: options.actor,
guildContext: options.guildContext,
recentMessages,
retrieval,
interactionMemory,
sourceGrounding,
stylePack: options.stylePack,
});
if (providerName === "owner_codex") {
const runApprovalRequired = options.config.ownerCodexMode === "manual_package";
const postApprovalRequired = options.config.ownerCodexMode === "manual_package";
const { job, created } = await options.jobQueue.createJob({
command: options.command,
provider: "owner_codex",
runApprovalRequired,
postApprovalRequired,
requester: options.actor,
guildContext: options.guildContext,
prompt: options.prompt,
contextBundle,
outputChannelId: options.outputChannelId,
requestMessageId: options.requestMessageId,
initialState: runApprovalRequired ? "awaiting_approval" : "approved",
});
if (!created) {
return;
}
await options.auditLog.record({
type: "job.queued",
actorId: options.actor.id,
jobId: job.id,
provider: "owner_codex",
details: {
command: options.command,
channelId: options.outputChannelId,
runApprovalRequired,
postApprovalRequired,
},
});
if (runApprovalRequired) {
await options.respond(
renderSystemMessage(options.systemMessages, "job.owner.awaiting_run_approval", {
jobId: job.id,
}),
);
return;
}
if (!options.silentOwnerQueueAck) {
await options.respond(
renderSystemMessage(options.systemMessages, "job.owner.auto_queued", {
jobId: job.id,
}),
);
}
return;
}
const response = await provider.execute(provider.buildRequest(contextBundle));
await options.auditLog.record({
type: "provider.responded",
actorId: options.actor.id,
provider: providerName,
details: {
command: options.command,
summary: response.summary,
},
});
await options.respond(response.outputText ?? response.summary);
}
export async function handleApproveJob(options: {
interaction: ChatInputCommandInteraction<CacheType>;
client: Client;
actor: Actor;
jobQueue: JobQueue;
auditLog: AuditLog;
permissionEngine: PermissionEngine;
systemMessages: SystemMessageCatalog;
}): Promise<void> {
const jobId = options.interaction.options.getString("job-id", true);
const response = options.interaction.options.getString("response", false);
const job = await options.jobQueue.getJob(jobId);
if (!job) {
await replyEphemeral(
options.interaction,
renderSystemMessage(options.systemMessages, "job.not_found", { jobId }),
);
return;
}
if (!options.permissionEngine.canApproveJob(options.actor, job)) {
await replyEphemeral(
options.interaction,
renderSystemMessage(options.systemMessages, "job.approval_forbidden"),
);
return;
}
if (job.state === "awaiting_approval") {
await options.jobQueue.approveRun(jobId, options.actor.id);
await options.auditLog.record({
type: "job.run_approved",
actorId: options.actor.id,
jobId,
provider: job.provider,
details: {},
});
await replyEphemeral(
options.interaction,
renderSystemMessage(options.systemMessages, "job.run_approved", { jobId }),
);
return;
}
if (job.state === "awaiting_post_approval") {
if (!response) {
await replyEphemeral(
options.interaction,
renderSystemMessage(options.systemMessages, "job.post_approval.needs_response"),
);
return;
}
await postFinalResponse(options.client, job, response);
await options.jobQueue.completeJob(jobId, options.actor.id, response);
await options.auditLog.record({
type: "job.post_approved",
actorId: options.actor.id,
jobId,
provider: job.provider,
details: {
publishedLength: response.length,
},
});
await replyEphemeral(
options.interaction,
renderSystemMessage(options.systemMessages, "job.post_approved", { jobId }),
);
return;
}
await replyEphemeral(
options.interaction,
renderSystemMessage(options.systemMessages, "job.no_action_for_state", {
jobId,
jobState: job.state,
}),
);
}
export async function handleRejectJob(options: {
interaction: ChatInputCommandInteraction<CacheType>;
actor: Actor;
jobQueue: JobQueue;
auditLog: AuditLog;
permissionEngine: PermissionEngine;
systemMessages: SystemMessageCatalog;
}): Promise<void> {
const jobId = options.interaction.options.getString("job-id", true);
const reason = options.interaction.options.getString("reason", false) ?? undefined;
const job = await options.jobQueue.getJob(jobId);
if (!job) {
await replyEphemeral(
options.interaction,
renderSystemMessage(options.systemMessages, "job.not_found", { jobId }),
);
return;
}
if (!options.permissionEngine.canApproveJob(options.actor, job)) {
await replyEphemeral(
options.interaction,
renderSystemMessage(options.systemMessages, "job.rejection_forbidden"),
);
return;
}
await options.jobQueue.rejectJob(jobId, options.actor.id, reason);
await options.auditLog.record({
type: "job.rejected",
actorId: options.actor.id,
jobId,
provider: job.provider,
details: {
reason,
},
});
await replyEphemeral(
options.interaction,
renderSystemMessage(options.systemMessages, "job.rejected", { jobId }),
);
}
export async function handleSearchHistory(
interaction: ChatInputCommandInteraction<CacheType>,
retrievalService: RetrievalService,
systemMessages: SystemMessageCatalog,
): Promise<void> {
const query = interaction.options.getString("query", true);
const results = await retrievalService.searchHistory(query, 5, {
guildId: interaction.guildId ?? undefined,
});
if (results.length === 0) {
await replyEphemeral(interaction, renderSystemMessage(systemMessages, "history.no_results"));
return;
}
const body = results
.map((result, index) => `${index + 1}. (${result.score.toFixed(2)}) ${truncate(result.text, 180)}`)
.join("\n");
await replyEphemeral(
interaction,
`${renderSystemMessage(systemMessages, "history.results_intro")}\n${body}`,
);
}
export async function handleSummarizeChannel(
interaction: ChatInputCommandInteraction<CacheType>,
systemMessages: SystemMessageCatalog,
): Promise<void> {
const messages = await getRecentMessages(interaction.channel?.isTextBased() ? interaction.channel : null, 15);
if (messages.length === 0) {
await replyEphemeral(
interaction,
renderSystemMessage(systemMessages, "summarize.no_messages"),
);
return;
}
const summary = messages
.slice(-8)
.map((message) => `- ${message.authorName}: ${truncate(message.content, 100)}`)
.join("\n");
await replyEphemeral(
interaction,
`${renderSystemMessage(systemMessages, "summarize.results_intro")}\n${summary}`,
);
}
export async function handleReindexChannel(
interaction: ChatInputCommandInteraction<CacheType>,
actor: Actor,
channelIndexing: AppConfig["channelIndexing"],
permissionEngine: PermissionEngine,
ragPipeline: RagPipeline,
systemMessages: SystemMessageCatalog,
): Promise<void> {
if (!permissionEngine.canReindex(actor)) {
await replyEphemeral(interaction, renderSystemMessage(systemMessages, "reindex.forbidden"));
return;
}
if (
!shouldIndexChannel(
channelIndexing,
buildChannelIndexingTarget(interaction.channel?.isTextBased() ? interaction.channel : null),
)
) {
await replyEphemeral(
interaction,
renderSystemMessage(systemMessages, "reindex.excluded"),
);
return;
}
if (!interaction.channel?.isTextBased()) {
await replyEphemeral(
interaction,
renderSystemMessage(systemMessages, "reindex.unsupported_channel"),
);
return;
}
const fetched = await interaction.channel.messages.fetch({ limit: 100 });
const archivedMessages = [...fetched.values()].map(convertDiscordMessageToArchive);
const result = await ragPipeline.upsertMessages(archivedMessages);
await replyEphemeral(
interaction,
renderSystemMessage(systemMessages, "reindex.completed", {
archivedMessages: archivedMessages.length,
createdMessages: result.createdMessages,
updatedMessages: result.updatedMessages,
unchangedMessages: result.unchangedMessages,
indexedChunks: result.indexedChunks,
}),
);
}
export function parseProviderOverride(value: string | null): ProviderName | undefined {
if (!value || value === "auto") {
return undefined;
}
return isProviderName(value) ? value : undefined;
}
export async function maybeRegisterCommands(
botToken: string,
applicationId?: string,
developmentGuildId?: string,
): Promise<void> {
if (!applicationId || !developmentGuildId) {
console.log("Skipping slash command registration because DISCORD_APPLICATION_ID or DISCORD_GUILD_ID is missing.");
return;
}
const rest = new REST({ version: "10" }).setToken(botToken);
await rest.put(Routes.applicationGuildCommands(applicationId, developmentGuildId), {
body: commandDefinitions.map((command) => command.toJSON()),
});
console.log(`Registered ${commandDefinitions.length} guild slash commands for ${developmentGuildId}.`);
}
export async function replyEphemeral(
interaction: ChatInputCommandInteraction<CacheType>,
content: string,
): Promise<void> {
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content, ephemeral: true });
return;
}
await interaction.reply({ content, ephemeral: true });
}
function pickProvider(
actor: Actor,
guildContext: GuildContext,
providerRegistry: ProviderRegistry,
): ProviderName | undefined {
const ownerCodex = providerRegistry.get("owner_codex");
if (ownerCodex?.isAllowedForActor(actor, guildContext)) {
return "owner_codex";
}
const openAi = providerRegistry.get("openai_api");
if (openAi?.isAllowedForActor(actor, guildContext)) {
return "openai_api";
}
const local = providerRegistry.get("local_llm");
if (local?.isAllowedForActor(actor, guildContext)) {
return "local_llm";
}
return undefined;
}
async function postFinalResponse(client: Client, job: JobRecord, finalResponse: string): Promise<void> {
const channel = await client.channels.fetch(job.outputChannelId);
if (!canSendMessages(channel)) {
throw new Error(`Channel ${job.outputChannelId} is not available for publishing.`);
}
await channel.send(finalResponse);
}

View file

@ -0,0 +1,535 @@
import {
ChannelType,
Client,
PermissionsBitField,
type CacheType,
type ChatInputCommandInteraction,
type Message,
type PartialMessage,
type TextBasedChannel,
} from "discord.js";
import {
type InteractionMemoryBank,
type SystemMessageCatalog,
type VoidUsageRateLimiter,
} from "@voidbot/core";
import type { ProviderRegistry } from "@voidbot/providers";
import {
RagPipeline,
RetrievalService,
type ArchivedMessageRecord,
} from "@voidbot/rag";
import {
type Actor,
type ArchivedMessage,
type ChannelIndexingPolicy,
type ChannelIndexingTarget,
type GuildContext,
type SourceGroundingHint,
type SourceMessage,
shouldIndexChannel,
} from "@voidbot/shared";
export function buildActorFromMessage(message: Message): Actor {
return {
id: message.author.id,
displayName: message.author.displayName ?? message.author.username,
isAdmin: message.member?.permissions.has(PermissionsBitField.Flags.Administrator) ?? false,
isBot: message.author.bot,
};
}
export function buildActorFromInteraction(
interaction: ChatInputCommandInteraction<CacheType>,
): Actor {
return {
id: interaction.user.id,
displayName: interaction.user.displayName ?? interaction.user.username,
isAdmin:
interaction.memberPermissions?.has(PermissionsBitField.Flags.Administrator) ?? false,
isBot: interaction.user.bot,
};
}
export function getRoleIdsFromMessage(message: Message): string[] {
return message.member ? [...message.member.roles.cache.keys()] : [];
}
export function getRoleIdsFromInteraction(
interaction: ChatInputCommandInteraction<CacheType>,
): string[] {
const member = interaction.member;
if (!member || !("roles" in member)) {
return [];
}
const { roles } = member;
if (Array.isArray(roles)) {
return roles.filter((roleId): roleId is string => typeof roleId === "string");
}
if (roles && typeof roles === "object" && "cache" in roles) {
return [...roles.cache.keys()];
}
return [];
}
export function buildGuildContextFromMessage(message: Message): GuildContext {
return {
guildId: message.guildId ?? undefined,
guildName: message.guild?.name,
channelId: message.channelId,
channelName: "name" in message.channel ? message.channel.name ?? undefined : undefined,
threadId: message.channel.type === ChannelType.PublicThread ? message.channel.id : undefined,
};
}
export function buildGuildContextFromInteraction(
interaction: ChatInputCommandInteraction<CacheType>,
): GuildContext {
return {
guildId: interaction.guildId ?? undefined,
guildName: interaction.guild?.name,
channelId: interaction.channelId,
channelName:
interaction.channel && "name" in interaction.channel ? interaction.channel.name ?? undefined : undefined,
threadId:
interaction.channel?.type === ChannelType.PublicThread ? interaction.channel.id : undefined,
};
}
export async function ingestIfIndexed(
message: Message,
channelIndexing: ChannelIndexingPolicy,
ragPipeline: RagPipeline,
): Promise<void> {
if (!shouldIndexChannel(channelIndexing, buildChannelIndexingTarget(message.channel))) {
return;
}
await ragPipeline.upsertMessages([convertDiscordMessageToArchive(message)]);
}
export async function rememberAmbientVoidReference(
message: Message,
botUserId: string | undefined,
interactionMemory: InteractionMemoryBank,
): Promise<void> {
if (!isAmbientVoidReference(message, botUserId)) {
return;
}
await interactionMemory.recordInteraction({
actorId: message.author.id,
actorName: message.author.displayName ?? message.author.username,
sourceKind: "ambient_mention",
guildId: message.guildId ?? undefined,
channelId: message.channelId,
channelName: "name" in message.channel ? message.channel.name ?? undefined : undefined,
prompt: message.content,
eventId: message.id,
timestamp: (message.editedAt ?? message.createdAt).toISOString(),
});
}
export function buildChannelIndexingTarget(
channel: TextBasedChannel | null | undefined,
): ChannelIndexingTarget {
if (!channel) {
return {};
}
const target: ChannelIndexingTarget = {
channelId: channel.id,
channelName: "name" in channel ? channel.name ?? undefined : undefined,
};
if (channel.isThread()) {
target.parentChannelId = channel.parentId ?? undefined;
target.parentChannelName =
channel.parent && "name" in channel.parent ? channel.parent.name ?? undefined : undefined;
}
return target;
}
export function convertDiscordMessageToArchive(message: Message): ArchivedMessage {
const metadata: Record<string, string> = {
jumpUrl: message.url,
};
if ("name" in message.channel && message.channel.name) {
metadata.channelName = message.channel.name;
}
if (message.channel.isThread()) {
if (message.channel.parentId) {
metadata.parentChannelId = message.channel.parentId;
}
if (message.channel.parent && "name" in message.channel.parent && message.channel.parent.name) {
metadata.parentChannelName = message.channel.parent.name;
}
}
return {
id: message.id,
guildId: message.guildId ?? undefined,
channelId: message.channelId,
authorId: message.author.id,
authorName: message.author.displayName ?? message.author.username,
content: message.content,
timestamp: message.createdAt.toISOString(),
editedAt: message.editedAt?.toISOString(),
threadId: message.channel.isThread() ? message.channel.id : undefined,
attachments:
message.attachments.size > 0
? [...message.attachments.values()].map(
(attachment) => attachment.url ?? attachment.proxyURL ?? attachment.name,
)
: undefined,
metadata,
};
}
export function convertDiscordMessageToSource(message: Message): SourceMessage {
return {
id: message.id,
authorId: message.author.id,
authorName: message.author.displayName ?? message.author.username,
content: message.content,
timestamp: message.createdAt.toISOString(),
};
}
export async function getRecentMessages(
channel: TextBasedChannel | null,
limit: number,
): Promise<SourceMessage[]> {
if (!channel || !("messages" in channel)) {
return [];
}
const fetched = await channel.messages.fetch({ limit });
return [...fetched.values()]
.sort((left, right) => left.createdTimestamp - right.createdTimestamp)
.map(convertDiscordMessageToSource);
}
export async function materializeMessage(
message: Message | PartialMessage,
): Promise<Message | undefined> {
if (!message.partial) {
return message;
}
try {
return await message.fetch();
} catch {
return undefined;
}
}
export function stripBotMention(content: string): string {
return content.replace(/<@!?(\d+)>/g, "").trim();
}
export function inferSourceGroundingHint(
prompt: string,
repoSummaries: Array<{ repoName: string }>,
): SourceGroundingHint {
const normalized = ` ${normalizeForMatching(prompt)} `;
const reasons = new Set<string>();
const matchedRepoNames = new Set<string>();
for (const repo of repoSummaries) {
for (const alias of buildRepoAliases(repo.repoName)) {
if (alias.length < 4) {
continue;
}
if (normalized.includes(` ${alias} `)) {
matchedRepoNames.add(repo.repoName);
}
}
}
if (matchedRepoNames.size > 0) {
reasons.add("matched indexed repo/project name");
}
const genericSourceCues = [
" repo ",
" repository ",
" repositories ",
" codebase ",
" source ",
" sources ",
" lore ",
" vault ",
" canon ",
" file ",
" files ",
" docs ",
" documentation ",
" module ",
" implementation ",
" project ",
" projects ",
];
if (genericSourceCues.some((cue) => normalized.includes(cue))) {
reasons.add("contains source/lore cue");
}
return {
required: reasons.size > 0,
reasons: [...reasons],
matchedRepoNames: [...matchedRepoNames].sort(),
};
}
export function formatProviderStatuses(
statuses: ReturnType<ProviderRegistry["listStatuses"]>,
systemMessages: SystemMessageCatalog,
): string {
return [
renderSystemMessage(systemMessages, "provider_status.intro"),
statuses
.map((status) => {
const state = status.enabled ? "enabled" : "disabled";
const access = status.allowed ? "allowed" : "blocked";
return `${status.name}: ${state}, ${access}, capabilities=${status.capabilities.join(", ")}`;
})
.join("\n"),
].join("\n");
}
export function renderSystemMessage(
systemMessages: SystemMessageCatalog,
key: string,
variables: Record<string, string | number | boolean | null | undefined> = {},
): string {
return systemMessages.render(key, variables);
}
export function renderRateLimitMessage(
systemMessages: SystemMessageCatalog,
decision: Awaited<ReturnType<VoidUsageRateLimiter["consume"]>>,
): string {
if (decision.reason === "daily_limit") {
return renderSystemMessage(systemMessages, "rate_limit.daily_limit", {
dailyLimit: decision.policy.dailyLimit ?? decision.dailyCount,
resetsAt: decision.resetsAt ? formatUtcTimestamp(decision.resetsAt) : "the next UTC midnight",
});
}
return renderSystemMessage(systemMessages, "rate_limit.cooldown", {
retryAfter: formatDurationSeconds(decision.retryAfterSeconds ?? 1),
});
}
export function formatHistoryResults(
results: Awaited<ReturnType<RetrievalService["searchHistory"]>>,
): Array<Record<string, unknown>> {
return results.map((result) => ({
score: Number(result.score.toFixed(4)),
text: result.text,
sourceId: result.sourceId,
channelId: result.metadata.channelId,
channelName: result.metadata.channelName,
authorId: result.metadata.authorId,
authorName: result.metadata.authorName,
timestamp: result.metadata.timestamp,
jumpUrl: result.metadata.jumpUrl,
threadId: result.metadata.threadId,
}));
}
export function formatSourceResults(
results: Awaited<ReturnType<RetrievalService["searchRepositorySources"]>>,
): Array<Record<string, unknown>> {
return results.map((result) => ({
score: Number(result.score.toFixed(4)),
text: result.text,
sourceId: result.sourceId,
repoName: result.metadata.repoName,
path: result.metadata.path,
language: result.metadata.language,
title: result.metadata.title,
chunkIndex: Number(result.metadata.chunkIndex ?? 0),
lineStart: Number(result.metadata.lineStart ?? 1),
lineEnd: Number(result.metadata.lineEnd ?? 1),
lastModifiedAt: result.metadata.lastModifiedAt,
}));
}
export function formatArchivedMessageContext(
message: ArchivedMessageRecord,
anchorMessageId: string,
): Record<string, unknown> {
return {
id: message.id,
isAnchor: message.id === anchorMessageId,
timestamp: message.timestamp,
authorId: message.authorId,
authorName: message.authorName,
channelId: message.channelId,
channelName: message.metadata?.channelName,
threadId: message.threadId,
content: message.content,
jumpUrl: message.metadata?.jumpUrl,
editedAt: message.editedAt,
};
}
export async function notifyOwnerOfBotIssue(
client: Client,
ownerDiscordId: string,
content: string,
): Promise<void> {
try {
const owner = await client.users.fetch(ownerDiscordId);
await owner.send(truncate(content, 1900));
} catch (error) {
console.error(
`Failed to DM owner about bot-side issue: ${
error instanceof Error ? error.message : "Unexpected notification failure."
}`,
);
}
}
export function truncate(input: string, limit: number): string {
if (input.length <= limit) {
return input;
}
return `${input.slice(0, limit - 3)}...`;
}
export function formatDurationSeconds(totalSeconds: number): string {
const seconds = Math.max(1, Math.ceil(totalSeconds));
if (seconds < 60) {
return `${seconds} second${seconds === 1 ? "" : "s"}`;
}
const minutes = Math.floor(seconds / 60);
const remainderSeconds = seconds % 60;
if (minutes < 60) {
return remainderSeconds === 0
? `${minutes} minute${minutes === 1 ? "" : "s"}`
: `${minutes}m ${remainderSeconds}s`;
}
const hours = Math.floor(minutes / 60);
const remainderMinutes = minutes % 60;
return remainderMinutes === 0
? `${hours} hour${hours === 1 ? "" : "s"}`
: `${hours}h ${remainderMinutes}m`;
}
export function formatUtcTimestamp(timestamp: string): string {
const date = new Date(timestamp);
const year = date.getUTCFullYear();
const month = `${date.getUTCMonth() + 1}`.padStart(2, "0");
const day = `${date.getUTCDate()}`.padStart(2, "0");
const hours = `${date.getUTCHours()}`.padStart(2, "0");
const minutes = `${date.getUTCMinutes()}`.padStart(2, "0");
return `${year}-${month}-${day} ${hours}:${minutes} UTC`;
}
export function canSendMessages(
channel: Awaited<ReturnType<Client["channels"]["fetch"]>>,
): channel is TextBasedChannel & { send: (content: string) => Promise<unknown> } {
return (
channel !== null &&
channel.isTextBased() &&
"send" in channel &&
typeof channel.send === "function"
);
}
function buildRepoAliases(repoName: string): string[] {
const normalizedRepo = repoName.replace(/[_-]+/g, " ").trim();
const lower = normalizeForMatching(normalizedRepo);
const compact = normalizeForMatching(repoName);
const words = splitPascalCase(normalizedRepo)
.flatMap((part) => part.split(/\s+/))
.map((part) => normalizeForMatching(part))
.filter((part) => part.length > 0);
const aliases = new Set<string>([lower, compact, words.join(" ")]);
for (const word of words) {
if (word.length >= 4) {
aliases.add(word);
}
}
return [...aliases].filter((alias) => alias.length > 0);
}
function splitPascalCase(value: string): string[] {
return value
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.split(/\s+/)
.filter((part) => part.length > 0);
}
function normalizeForMatching(value: string): string {
return value
.toLowerCase()
.replace(/[^a-z0-9]+/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function isAmbientVoidReference(
message: Message,
botUserId: string | undefined,
): boolean {
const content = message.content.trim();
if (content.length === 0) {
return false;
}
if (botUserId && message.mentions.users.has(botUserId)) {
return false;
}
if (/\bvoidbot\b/i.test(content)) {
return true;
}
if (!/\bvoid\b/i.test(content)) {
return false;
}
const normalized = ` ${content
.toLowerCase()
.replace(/[^a-z0-9]+/g, " ")
.replace(/\s+/g, " ")
.trim()} `;
if (
normalized.includes(" the void ") ||
normalized.includes(" into the void ") ||
normalized.includes(" return void ") ||
normalized.includes(" void function ") ||
normalized.includes(" void pointer ") ||
normalized.includes(" non void ")
) {
return false;
}
return true;
}

File diff suppressed because it is too large Load diff