Make repo Faces chatty and meme-capable
This commit is contained in:
parent
e366d403d5
commit
7e4dd55981
6 changed files with 282 additions and 26 deletions
|
|
@ -58,6 +58,7 @@ import {
|
|||
validateRenderedArticleMarkdown,
|
||||
} from "./repo-face-article.js";
|
||||
import { resolveRepoIdentityPostArtifactLinks } from "./repo-face-artifact-links.js";
|
||||
import { postDiscordMessage } from "./mcp-server-discord.js";
|
||||
|
||||
const config = loadConfig();
|
||||
const REPO_IDENTITY_POST_SENTINEL = "VOIDBOT_REPO_IDENTITY_POST:";
|
||||
|
|
@ -377,6 +378,7 @@ async function processJob(job: JobRecord): Promise<void> {
|
|||
if (job.command === "repo-face-rumination") {
|
||||
const repoFaceOutput = rawFinalResponse;
|
||||
const repoIdentityPosts = parseRepoIdentityPostIntents(repoFaceOutput);
|
||||
const repoIdentityMemes = parseRepoIdentityMemeIntents(repoFaceOutput);
|
||||
const repoIdentityStateNotes = parseRepoIdentityStateNoteIntents(repoFaceOutput);
|
||||
const repoIdentityBifrostTopics = config.repoFaceBifrostEnabled
|
||||
? parseRepoIdentityBifrostTopicIntents(repoFaceOutput)
|
||||
|
|
@ -414,7 +416,7 @@ async function processJob(job: JobRecord): Promise<void> {
|
|||
!bifrostTopicSubmitted &&
|
||||
repoIdentityUpdateRequests.length > 0;
|
||||
console.log(
|
||||
`Repo-face job ${job.id} parsed actions: say=${repoIdentityPosts.length}, stateNote=${repoIdentityStateNotes.length}, bifrostTopic=${repoIdentityBifrostTopics.length}, updateRequest=${repoIdentityUpdateRequests.length}, article=${repoIdentityArticles.length}, proposalPr=${repoIdentityProposals.length}, prComment=${repoIdentityPrComments.length}.`,
|
||||
`Repo-face job ${job.id} parsed actions: say=${repoIdentityPosts.length}, meme=${repoIdentityMemes.length}, stateNote=${repoIdentityStateNotes.length}, bifrostTopic=${repoIdentityBifrostTopics.length}, updateRequest=${repoIdentityUpdateRequests.length}, article=${repoIdentityArticles.length}, proposalPr=${repoIdentityProposals.length}, prComment=${repoIdentityPrComments.length}.`,
|
||||
);
|
||||
for (const stateNote of repoIdentityStateNotes.slice(0, 4)) {
|
||||
await applyRepoIdentityStateNoteIntent(job, stateNote);
|
||||
|
|
@ -466,6 +468,38 @@ async function processJob(job: JobRecord): Promise<void> {
|
|||
repoIdentityPostDelivered += 1;
|
||||
}
|
||||
}
|
||||
if (repoIdentityPostDelivered === 0) {
|
||||
for (const meme of repoIdentityMemes.slice(0, 1)) {
|
||||
const resolvedMeme = await resolveRepoIdentityMemeIntent(job, meme);
|
||||
if (!resolvedMeme) {
|
||||
continue;
|
||||
}
|
||||
const siblingDuplicate = await detectRepoFaceRecentSiblingSpeechDuplicate(job, resolvedMeme);
|
||||
if (siblingDuplicate) {
|
||||
console.warn(
|
||||
`Rejected repo identity ${resolvedMeme.identity.id} meme for job ${job.id}: ${siblingDuplicate.reason}`,
|
||||
);
|
||||
await auditLog.record({
|
||||
type: "repo_face.speech_rejected_recent_sibling_duplicate",
|
||||
actorId: job.requester.id,
|
||||
jobId: job.id,
|
||||
provider: job.provider,
|
||||
details: {
|
||||
identityId: resolvedMeme.identity.id,
|
||||
channelId: resolvedMeme.channelId,
|
||||
reason: siblingDuplicate.reason,
|
||||
duplicateReceiptKey: siblingDuplicate.receiptKey,
|
||||
duplicatePreview: siblingDuplicate.preview,
|
||||
},
|
||||
});
|
||||
repoIdentityPostRejectedDuplicate += 1;
|
||||
continue;
|
||||
}
|
||||
if (await postRepoIdentityMemeIntent(job, meme)) {
|
||||
repoIdentityPostDelivered += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const cleanedFinalResponse = stripRepoIdentityPostIntents(repoFaceOutput);
|
||||
await jobQueue.completeJobDirect(job.id, cleanedFinalResponse || repoFaceOutput);
|
||||
|
|
@ -1149,6 +1183,17 @@ interface ResolvedRepoIdentityPostIntent {
|
|||
replyToMessageId?: string;
|
||||
}
|
||||
|
||||
interface RepoIdentityMemeIntent {
|
||||
identity?: string;
|
||||
channelId?: string;
|
||||
caption: string;
|
||||
top: string;
|
||||
bottom?: string;
|
||||
alt?: string;
|
||||
style?: string;
|
||||
replyToMessageId?: string;
|
||||
}
|
||||
|
||||
interface RepoIdentityStateNoteIntent {
|
||||
identity?: string;
|
||||
kind: "memory" | "need" | "bond" | "status" | "mood" | "bias" | "agency" | "doctrine";
|
||||
|
|
@ -1356,6 +1401,119 @@ async function resolveRepoIdentityPostIntent(
|
|||
};
|
||||
}
|
||||
|
||||
async function resolveRepoIdentityMemeIntent(
|
||||
job: JobRecord,
|
||||
intent: RepoIdentityMemeIntent,
|
||||
): Promise<ResolvedRepoIdentityPostIntent | undefined> {
|
||||
return resolveRepoIdentityPostIntent(job, {
|
||||
identity: intent.identity,
|
||||
channelId: intent.channelId,
|
||||
replyToMessageId: intent.replyToMessageId,
|
||||
content: intent.caption || [intent.top, intent.bottom].filter(Boolean).join(" / "),
|
||||
});
|
||||
}
|
||||
|
||||
async function postRepoIdentityMemeIntent(job: JobRecord, intent: RepoIdentityMemeIntent): Promise<boolean> {
|
||||
if (!config.botToken) {
|
||||
throw new Error("DISCORD_BOT_TOKEN is required for Bifrost to post repo identity memes.");
|
||||
}
|
||||
|
||||
const resolved = await resolveRepoIdentityMemeIntent(job, intent);
|
||||
if (!resolved) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const { identity, channelId, content, replyToMessageId } = resolved;
|
||||
const imagePath = await renderRepoIdentityMeme(job, identity.id, intent);
|
||||
const posted = await postDiscordMessage(
|
||||
config.botToken,
|
||||
channelId,
|
||||
content.slice(0, 1900),
|
||||
replyToMessageId,
|
||||
{
|
||||
personaName: identity.displayName,
|
||||
personaAvatarUrl: identity.avatarUrl,
|
||||
},
|
||||
[
|
||||
{
|
||||
path: imagePath,
|
||||
name: `${identity.id}-meme.png`,
|
||||
mimeType: "image/png",
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
await recordRepoIdentityDeliveryReceipt({
|
||||
identity,
|
||||
channelId,
|
||||
content: `${content}\n[image: ${intent.alt ?? [intent.top, intent.bottom].filter(Boolean).join(" / ")}]`,
|
||||
replyToMessageId,
|
||||
messageId: posted.id,
|
||||
transport: posted.transport,
|
||||
}).catch((error: unknown) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`Could not record repo identity meme delivery receipt for job ${job.id}: ${message}`);
|
||||
});
|
||||
console.log(
|
||||
`Posted repo identity ${identity.id} meme to Discord channel ${channelId} from job ${job.id} via ${posted.transport} message ${posted.id}.`,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
async function renderRepoIdentityMeme(
|
||||
job: JobRecord,
|
||||
identityId: string,
|
||||
intent: RepoIdentityMemeIntent,
|
||||
): Promise<string> {
|
||||
const directory = resolve(config.storageRoot, "artifacts", job.id, "repo-face-memes");
|
||||
await mkdir(directory, { recursive: true });
|
||||
const textPath = join(directory, `${sanitizePathSegment(identityId)}-meme.txt`);
|
||||
const imagePath = join(directory, `${sanitizePathSegment(identityId)}-meme.png`);
|
||||
const memeText = [intent.top, intent.bottom].filter(Boolean).join("\n\n").toUpperCase();
|
||||
await writeFile(textPath, memeText, "utf8");
|
||||
|
||||
const colors = normalizeMemeStyle(intent.style);
|
||||
const result = spawnSync("magick", [
|
||||
"-background",
|
||||
colors.background,
|
||||
"-fill",
|
||||
colors.foreground,
|
||||
"-font",
|
||||
"Arial",
|
||||
"-gravity",
|
||||
"center",
|
||||
"-pointsize",
|
||||
"52",
|
||||
"-size",
|
||||
"900x520",
|
||||
`caption:@${textPath}`,
|
||||
imagePath,
|
||||
], {
|
||||
encoding: "utf8",
|
||||
windowsHide: true,
|
||||
});
|
||||
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`ImageMagick meme render failed: ${result.stderr || result.stdout}`);
|
||||
}
|
||||
|
||||
return imagePath;
|
||||
}
|
||||
|
||||
function normalizeMemeStyle(style: string | undefined): { background: string; foreground: string } {
|
||||
switch (style?.trim().toLowerCase()) {
|
||||
case "terminal":
|
||||
return { background: "#020617", foreground: "#a7f3d0" };
|
||||
case "warning":
|
||||
return { background: "#18181b", foreground: "#fde047" };
|
||||
case "soft":
|
||||
return { background: "#f8fafc", foreground: "#111827" };
|
||||
case "classic":
|
||||
default:
|
||||
return { background: "#111827", foreground: "#f8fafc" };
|
||||
}
|
||||
}
|
||||
|
||||
async function detectRepoFaceRecentSiblingSpeechDuplicate(
|
||||
job: JobRecord,
|
||||
post: ResolvedRepoIdentityPostIntent,
|
||||
|
|
@ -1567,6 +1725,32 @@ function parseRepoIdentityPostIntents(finalResponse: string): RepoIdentityPostIn
|
|||
return intents;
|
||||
}
|
||||
|
||||
function parseRepoIdentityMemeIntents(finalResponse: string): RepoIdentityMemeIntent[] {
|
||||
return parseRepoFaceActionBlocks(finalResponse)
|
||||
.filter((block) => block.kind === "meme")
|
||||
.flatMap((block): RepoIdentityMemeIntent[] => {
|
||||
const top = requiredDslString(block.fields.top);
|
||||
if (!top) {
|
||||
return [];
|
||||
}
|
||||
const bottom = optionalDslString(block.fields.bottom);
|
||||
const caption =
|
||||
optionalDslString(block.fields.caption) ?? [top, bottom].filter(Boolean).join(" / ");
|
||||
return [
|
||||
{
|
||||
identity: optionalDslString(block.fields.identity),
|
||||
channelId: optionalDslString(block.fields.channel) ?? optionalDslString(block.fields.channelId),
|
||||
replyToMessageId: optionalDslString(block.fields.reply_to) ?? optionalDslString(block.fields.replyToMessageId),
|
||||
caption,
|
||||
top,
|
||||
bottom,
|
||||
alt: optionalDslString(block.fields.alt),
|
||||
style: optionalDslString(block.fields.style),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
function parseRepoIdentityIdFromRequestMessageId(requestMessageId: string | undefined): string | undefined {
|
||||
const match = requestMessageId?.match(/^agent-turn:([^:]+):/i);
|
||||
return match?.[1]?.trim();
|
||||
|
|
@ -2446,7 +2630,7 @@ function countRepoIdentityGithubActionIntents(finalResponse: string): number {
|
|||
}
|
||||
|
||||
interface RepoFaceActionBlock {
|
||||
kind: "say" | "state_note" | "article" | "bifrost_topic" | "update_request";
|
||||
kind: "say" | "meme" | "state_note" | "article" | "bifrost_topic" | "update_request";
|
||||
fields: Record<string, string>;
|
||||
}
|
||||
|
||||
|
|
@ -2486,6 +2670,8 @@ function parseRepoFaceActionKind(line: string): RepoFaceActionBlock["kind"] | un
|
|||
switch (line.trim().toUpperCase()) {
|
||||
case "SAY":
|
||||
return "say";
|
||||
case "MEME":
|
||||
return "meme";
|
||||
case "STATE NOTE":
|
||||
return "state_note";
|
||||
case "ARTICLE":
|
||||
|
|
|
|||
|
|
@ -13,6 +13,12 @@ export interface DiscordPersonaOptions {
|
|||
personaAvatarUrl?: string;
|
||||
}
|
||||
|
||||
export interface DiscordMessageFile {
|
||||
path: string;
|
||||
name: string;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
interface NormalizedDiscordPersonaOptions {
|
||||
personaName: string;
|
||||
personaAvatarUrl?: string;
|
||||
|
|
@ -61,6 +67,7 @@ export async function postDiscordMessage(
|
|||
content: string,
|
||||
replyToMessageId?: string,
|
||||
persona?: DiscordPersonaOptions,
|
||||
files: DiscordMessageFile[] = [],
|
||||
): Promise<{ id: string; transport: "bot" | "webhook" }> {
|
||||
const normalizedPersona = normalizePersonaOptions(persona);
|
||||
|
||||
|
|
@ -71,9 +78,14 @@ export async function postDiscordMessage(
|
|||
content,
|
||||
normalizedPersona,
|
||||
replyToMessageId,
|
||||
files,
|
||||
);
|
||||
}
|
||||
|
||||
if (files.length > 0) {
|
||||
throw new Error("Discord bot message attachments are only implemented for persona webhook messages.");
|
||||
}
|
||||
|
||||
const response = await fetch(`https://discord.com/api/v10/channels/${channelId}/messages`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
|
|
@ -113,6 +125,7 @@ async function postDiscordPersonaMessage(
|
|||
content: string,
|
||||
persona: NormalizedDiscordPersonaOptions,
|
||||
replyToMessageId?: string,
|
||||
files: DiscordMessageFile[] = [],
|
||||
): Promise<{ id: string; transport: "webhook" }> {
|
||||
const target = await resolveWebhookTarget(botToken, channelId);
|
||||
const configuredWebhook = await getConfiguredPersonaWebhook(target.webhookChannelId);
|
||||
|
|
@ -130,6 +143,7 @@ async function postDiscordPersonaMessage(
|
|||
replyToMessageId,
|
||||
username: persona.personaName,
|
||||
avatarUrl: persona.personaAvatarUrl,
|
||||
files,
|
||||
});
|
||||
} catch (error) {
|
||||
if (!isStaleWebhookError(error)) {
|
||||
|
|
@ -153,6 +167,7 @@ async function postDiscordPersonaMessage(
|
|||
replyToMessageId,
|
||||
username: persona.personaName,
|
||||
avatarUrl: persona.personaAvatarUrl,
|
||||
files,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -313,12 +328,14 @@ async function executePersonaWebhook(
|
|||
replyToMessageId,
|
||||
username,
|
||||
avatarUrl,
|
||||
files = [],
|
||||
}: {
|
||||
threadId?: string;
|
||||
content: string;
|
||||
replyToMessageId?: string;
|
||||
username: string;
|
||||
avatarUrl?: string;
|
||||
files?: DiscordMessageFile[];
|
||||
},
|
||||
): Promise<{ id: string; transport: "webhook" }> {
|
||||
const url = new URL(`https://discord.com/api/v10/webhooks/${webhook.id}/${webhook.token}`);
|
||||
|
|
@ -328,38 +345,58 @@ async function executePersonaWebhook(
|
|||
url.searchParams.set("thread_id", threadId);
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
const requestPayload = {
|
||||
content,
|
||||
username,
|
||||
avatar_url: avatarUrl,
|
||||
message_reference: replyToMessageId
|
||||
? {
|
||||
message_id: replyToMessageId,
|
||||
fail_if_not_exists: false,
|
||||
}
|
||||
: undefined,
|
||||
allowed_mentions: {
|
||||
parse: [],
|
||||
},
|
||||
body: JSON.stringify({
|
||||
content,
|
||||
username,
|
||||
avatar_url: avatarUrl,
|
||||
message_reference: replyToMessageId
|
||||
? {
|
||||
message_id: replyToMessageId,
|
||||
fail_if_not_exists: false,
|
||||
}
|
||||
: undefined,
|
||||
allowed_mentions: {
|
||||
parse: [],
|
||||
},
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const response = files.length > 0
|
||||
? await fetch(url, {
|
||||
method: "POST",
|
||||
body: buildWebhookMultipartBody(requestPayload, files),
|
||||
})
|
||||
: await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(requestPayload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to execute Discord webhook: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as { id?: string };
|
||||
const responsePayload = (await response.json()) as { id?: string };
|
||||
|
||||
if (!payload.id) {
|
||||
if (!responsePayload.id) {
|
||||
throw new Error("Discord webhook execution returned no message id.");
|
||||
}
|
||||
|
||||
return { id: payload.id, transport: "webhook" };
|
||||
return { id: responsePayload.id, transport: "webhook" };
|
||||
}
|
||||
|
||||
function buildWebhookMultipartBody(payload: Record<string, unknown>, files: DiscordMessageFile[]): FormData {
|
||||
const form = new FormData();
|
||||
form.append("payload_json", JSON.stringify(payload));
|
||||
|
||||
for (const [index, file] of files.entries()) {
|
||||
const data = readFileSync(file.path);
|
||||
const blob = new Blob([data], { type: file.mimeType ?? "application/octet-stream" });
|
||||
form.append(`files[${index}]`, blob, file.name);
|
||||
}
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
function normalizePersonaOptions(
|
||||
|
|
|
|||
Loading…
Reference in a new issue