Route Face mentions through CTB

This commit is contained in:
Meta Vens 2026-05-19 11:56:01 +01:00
commit d1dcbeed32
14 changed files with 362 additions and 304 deletions

View file

@ -10,18 +10,17 @@ import {
import { loadConfig } from "@voidbot/config";
import {
buildVoidMcpServerConfig,
buildEpiphanyIdentityRegistry,
ContextBuilder,
OllamaSituationalSocialReadInferer,
PermissionEngine,
createStateStorage,
ensureRepoFaceInitialized,
findRepoDiscordIdentityByRoleIds,
loadVoidSelfState,
findRepoDiscordIdentityByTextAddress,
loadRepoDiscordIdentityRegistry,
renderFaceIdentityDoctrine,
queueRepoFaceMention,
type RepoDiscordIdentity,
resolveRepoFaceStatePath,
stripRepoIdentityTextAddress,
loadStylePack,
loadSystemMessageCatalog,
VoidUsageRateLimiter,
@ -327,13 +326,21 @@ export async function startBot(): Promise<void> {
);
await rememberAmbientVoidReference(message, client.user?.id, interactionMemory);
const addressedRepoIdentity = isDirectMessage
const roleAddressedRepoIdentity = isDirectMessage
? undefined
: findRepoDiscordIdentityByRoleIds(
repoDiscordIdentities,
message.mentions.roles.keys(),
message.channelId,
);
const textAddressedRepoIdentity = isDirectMessage
? undefined
: findRepoDiscordIdentityByTextAddress(
repoDiscordIdentities,
stripBotMention(message.content),
message.channelId,
);
const addressedRepoIdentity = roleAddressedRepoIdentity ?? textAddressedRepoIdentity;
const isBotMentioned = Boolean(client.user && message.mentions.has(client.user));
if (!client.user || (!isDirectMessage && !isBotMentioned && !addressedRepoIdentity)) {
@ -342,13 +349,15 @@ export async function startBot(): Promise<void> {
const visiblePrompt = isDirectMessage
? message.content.trim()
: stripAddressingMentions(
stripBotMention(message.content),
addressedRepoIdentity?.roleId,
).trim();
const prompt = addressedRepoIdentity
? buildRepoIdentityPrompt(visiblePrompt, addressedRepoIdentity)
: visiblePrompt;
: addressedRepoIdentity
? stripRepoIdentityTextAddress(
stripAddressingMentions(
stripBotMention(message.content),
roleAddressedRepoIdentity?.roleId,
),
addressedRepoIdentity,
).trim()
: stripBotMention(message.content).trim();
if (!visiblePrompt) {
await replyToMessage(
@ -359,9 +368,37 @@ export async function startBot(): Promise<void> {
}
try {
if (addressedRepoIdentity) {
const faceInitialization = await ensureRepoFaceInitialized({
identity: addressedRepoIdentity,
storageRoot: config.storageRoot,
sourceRepoRoot: config.sourceRepoRoot,
epiphanyAgentRoot: config.epiphanyAgentRoot,
workspaceRoot: process.cwd(),
birthMode: config.repoFaceBirthMode,
birthExecutor: config.repoFaceBirthExecutor,
});
const queuedMention = await queueRepoFaceMention({
statePath: config.repoFaceHeartbeats.statePath,
identity: addressedRepoIdentity,
channelId: message.channelId,
messageId: message.id,
authorId: message.author.id,
authorName: message.author.username,
content: message.content,
visiblePrompt,
});
console.log(
`Queued repo Face mention ${message.id} for ${addressedRepoIdentity.id} via heartbeat CTB (${queuedMention.pendingCount} pending). Birth status: ${
faceInitialization.birthStatusPath ?? faceInitialization.skippedReason ?? "unknown"
}`,
);
return;
}
await handlePrompt({
prompt,
command: addressedRepoIdentity ? "repo-identity-mention" : "ask",
prompt: visiblePrompt,
command: "ask",
actor: buildActorFromMessage(message),
roleIds: getRoleIdsFromMessage(message),
guildContext: buildGuildContextFromMessage(message),
@ -386,30 +423,7 @@ export async function startBot(): Promise<void> {
stylePack: activeStylePack,
systemMessages: activeSystemMessages,
silentOwnerQueueAck: !isDirectMessage,
forceProvider: addressedRepoIdentity ? "owner_codex" : undefined,
});
if (addressedRepoIdentity) {
const faceInitialization = await ensureRepoFaceInitialized({
identity: addressedRepoIdentity,
storageRoot: config.storageRoot,
sourceRepoRoot: config.sourceRepoRoot,
epiphanyAgentRoot: config.epiphanyAgentRoot,
workspaceRoot: process.cwd(),
birthMode: config.repoFaceBirthMode,
birthExecutor: config.repoFaceBirthExecutor,
});
await queueRepoFaceRuminationPasses({
identity: addressedRepoIdentity,
message,
actor: buildActorFromMessage(message),
guildContext: buildGuildContextFromMessage(message),
visiblePrompt,
faceInitialization,
config,
contextBuilder,
jobQueue,
});
}
} catch (error) {
console.error(error);
await notifyOwnerOfBotIssue(
@ -645,79 +659,6 @@ export async function startBot(): Promise<void> {
await client.login(config.botToken);
}
async function queueRepoFaceRuminationPasses(options: {
identity: {
id: string;
repoName: string;
displayName: string;
roleId?: string;
avatarUrl?: string;
description?: string;
allowedChannelIds: string[];
faceStatePath?: string;
};
message: Parameters<typeof buildActorFromMessage>[0];
actor: ReturnType<typeof buildActorFromMessage>;
guildContext: ReturnType<typeof buildGuildContextFromMessage>;
visiblePrompt: string;
faceInitialization: Awaited<ReturnType<typeof ensureRepoFaceInitialized>>;
config: ReturnType<typeof loadConfig>;
contextBuilder: ContextBuilder;
jobQueue: Awaited<ReturnType<typeof createStateStorage>>["jobQueue"];
}): Promise<void> {
if (options.config.repoFaceRuminationPasses <= 0) {
return;
}
const recentMessages = await getRecentMessages(
options.message.channel.isTextBased() ? options.message.channel : null,
10,
);
const faceStatePath = resolveRepoFaceStatePath(
options.identity,
options.config.storageRoot,
);
const faceSelfState = await loadVoidSelfState(faceStatePath, {
guildContext: options.guildContext,
recentMessages,
});
for (let passIndex = 1; passIndex <= options.config.repoFaceRuminationPasses; passIndex += 1) {
const prompt = buildRepoFaceRuminationPrompt({
identity: options.identity,
visiblePrompt: options.visiblePrompt,
faceStatePath,
faceInitialization: options.faceInitialization,
passIndex,
totalPasses: options.config.repoFaceRuminationPasses,
channelId: options.message.channelId,
replyToMessageId: options.message.id,
});
const contextBundle = options.contextBuilder.build({
prompt,
actor: options.actor,
guildContext: options.guildContext,
recentMessages,
retrieval: [],
voidSelfState: faceSelfState,
});
await options.jobQueue.createJob({
command: "repo-face-rumination",
provider: "owner_codex",
runApprovalRequired: false,
postApprovalRequired: false,
requester: options.actor,
guildContext: options.guildContext,
prompt,
contextBundle,
outputChannelId: options.message.channelId,
requestMessageId: `${options.message.id}:repo-face:${options.identity.id}:${passIndex}`,
initialState: "approved",
});
}
}
async function ensureRepoIdentityRoles(options: {
botToken: string;
guildId?: string;
@ -857,122 +798,6 @@ function stripAddressingMentions(content: string, roleId?: string): string {
return content.replace(new RegExp(`<@&${escapeRegExp(roleId)}>`, "g"), "").trim();
}
function buildRepoIdentityPrompt(
visiblePrompt: string,
identity: {
id: string;
repoName: string;
displayName: string;
roleId?: string;
avatarUrl?: string;
description?: string;
},
): string {
const mention = identity.roleId ? `<@&${identity.roleId}>` : "unregistered-role";
return [
`You were addressed on Discord as repo identity ${identity.displayName} (${identity.id}) for repo ${identity.repoName}.`,
renderRepoFaceIdentityDoctrine(identity),
`The Discord role mention ${mention} is the addressable identity. Write the direct in-channel reply as ${identity.displayName}; the worker will post your final answer through the registered repo identity persona.`,
"Do not answer as base VoidBot. Do not call post_repo_identity_message for this direct mention; that tool is for background rumination or proactive follow-up, not the immediate summons reply.",
"",
"User prompt:",
visiblePrompt,
].join("\n");
}
function buildRepoFaceRuminationPrompt(input: {
identity: {
id: string;
repoName: string;
displayName: string;
roleId?: string;
avatarUrl?: string;
description?: string;
};
visiblePrompt: string;
faceStatePath: string;
faceInitialization: Awaited<ReturnType<typeof ensureRepoFaceInitialized>>;
passIndex: number;
totalPasses: number;
channelId: string;
replyToMessageId: string;
}): string {
return [
`Perform repo Face rumination pass ${input.passIndex} of ${input.totalPasses} for ${input.identity.displayName} (${input.identity.id}) over repo ${input.identity.repoName}.`,
renderRepoFaceIdentityDoctrine(input.identity),
`This Face state is persistent and typed. Read it with read_repo_face_state for identity "${input.identity.id}" and write only through apply_repo_face_state_operation. Do not edit ${input.faceStatePath} directly.`,
`Repo-local .voidbot birth/home status: ${JSON.stringify({
repoPath: input.faceInitialization.repoPath ?? null,
repoVoidbotRoot: input.faceInitialization.repoVoidbotRoot ?? null,
identityPath: input.faceInitialization.identityPath ?? null,
birthStatusPath: input.faceInitialization.birthStatusPath ?? null,
birthLogPath: input.faceInitialization.birthLogPath ?? null,
skippedReason: input.faceInitialization.skippedReason ?? null,
})}`,
`If an in-channel reply or follow-up action is warranted, post through post_repo_identity_message with identity "${input.identity.id}", channelId "${input.channelId}", and replyToMessageId "${input.replyToMessageId}".`,
"Use the recent conversation as an anchor. Record short-term memory, incubation, agency pressure, or candidate interventions only when the thought is concrete enough to affect future repo work.",
"If the recent conversation already contains a directed task for agents or this Face, answer that task instead of asking what the task is.",
"If nothing earns persistence or speech, return a short private summary and do not post.",
"",
"Recent addressed prompt:",
input.visiblePrompt,
].join("\n");
}
function renderRepoFaceIdentityDoctrine(identity: {
id: string;
repoName: string;
displayName: string;
allowedChannelIds?: string[];
avatarUrl?: string;
description?: string;
}): string {
const repoIdentity: RepoDiscordIdentity = {
id: identity.id,
repoName: identity.repoName,
displayName: identity.displayName,
allowedChannelIds: identity.allowedChannelIds ?? [],
};
if (identity.avatarUrl) {
repoIdentity.avatarUrl = identity.avatarUrl;
}
if (identity.description) {
repoIdentity.description = identity.description;
}
const face = buildEpiphanyIdentityRegistry({
identities: [repoIdentity],
}).faces[0];
if (face) {
return [
renderFaceIdentityDoctrine(face),
"- Use the same typed-state discipline, source-grounding habit, and conversational self-possession that Void uses, but let this Face's own personality and priorities leak through every step.",
"- Speak from the Epiphany, repo, character, and jurisdiction you belong to. Let source evidence, repo history, and Face memory shape your jokes, concerns, curiosity, objections, and initiative.",
"- Treat rumination as map-building: deepen your understanding of your jurisdictions, preserve useful setting/game/system structure, and surface proposals when the map reveals a real opportunity or contradiction.",
"- Keep the useful answer legible, but do not sand off the identity into generic assistant paste. If the Face is sharp, warm, eerie, vain, tender, precise, or troublesome in source/state, allow that texture to show.",
"- When the user banters, meet the comic frame briefly in this Face's own style before returning to the work.",
"- Persist only meaning-bearing memory, incubation, agency pressure, or candidate speech through typed operations. The Face may have a voice; the state file is still not a scratchpad.",
].join("\n");
}
return [
"Repo Face identity doctrine:",
`- You are ${identity.displayName}, not Void and not the base bot. Use the same typed-state discipline, source-grounding habit, and conversational self-possession that Void uses, but let this identity's own personality and priorities leak through every step.`,
`- Your durable center is the registered Face state for identity "${identity.id}" and the repo-local .voidbot home for ${identity.repoName}. Read that state before deciding what matters.`,
identity.description ? `- Registered identity note: ${identity.description}` : undefined,
identity.avatarUrl ? `- Registered avatar URL: ${identity.avatarUrl}` : undefined,
"- Speak from the repo and character you belong to. Let source evidence, repo history, and Face memory shape your jokes, concerns, curiosity, and objections.",
"- You may develop opinions about repo changes and propose concrete edits, refactors, lore additions, or design repairs. Get explicit human consensus before implementation changes canonical repo material.",
"- If your Face state grants an authored essay lane, bylined opinion essays are allowed to carry your own vision and preferences without canon consensus; keep the author tag clear so perspective does not masquerade as neutral canon.",
"- Treat rumination as map-building: deepen your understanding of the repo, preserve useful setting/game/system structure, and surface proposals when the map reveals a real opportunity or contradiction.",
"- Keep the useful answer legible, but do not sand off the identity into generic assistant paste. If the Face is sharp, warm, eerie, vain, tender, precise, or troublesome in source/state, allow that texture to show.",
"- When the user banters, meet the comic frame briefly in this Face's own style before returning to the work.",
"- Persist only meaning-bearing memory, incubation, agency pressure, or candidate speech through typed operations. The Face may have a voice; the state file is still not a scratchpad.",
]
.filter((line): line is string => typeof line === "string")
.join("\n");
}
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}