Queue repo Face rumination jobs
This commit is contained in:
parent
ed36561c8d
commit
32b96ce575
14 changed files with 465 additions and 5 deletions
|
|
@ -1,4 +1,5 @@
|
|||
import { resolve } from "node:path";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Client,
|
||||
|
|
@ -15,6 +16,8 @@ import {
|
|||
createStateStorage,
|
||||
findRepoDiscordIdentityByRoleIds,
|
||||
loadRepoDiscordIdentityRegistry,
|
||||
type RepoDiscordIdentity,
|
||||
resolveRepoFaceStatePath,
|
||||
loadStylePack,
|
||||
loadSystemMessageCatalog,
|
||||
VoidUsageRateLimiter,
|
||||
|
|
@ -60,6 +63,7 @@ import {
|
|||
formatHistoryResults,
|
||||
formatProviderStatuses,
|
||||
formatSourceResults,
|
||||
getRecentMessages,
|
||||
getRoleIdsFromInteraction,
|
||||
getRoleIdsFromMessage,
|
||||
ingestIfIndexed,
|
||||
|
|
@ -86,9 +90,15 @@ export async function startBot(): Promise<void> {
|
|||
GatewayIntentBits.MessageContent,
|
||||
],
|
||||
});
|
||||
const repoDiscordIdentities = await loadRepoDiscordIdentityRegistry(
|
||||
let repoDiscordIdentities = await loadRepoDiscordIdentityRegistry(
|
||||
config.repoDiscordIdentitiesPath,
|
||||
);
|
||||
repoDiscordIdentities = await ensureRepoIdentityRoles({
|
||||
botToken: config.botToken,
|
||||
guildId: config.developmentGuildId,
|
||||
registryPath: config.repoDiscordIdentitiesPath,
|
||||
identities: repoDiscordIdentities.identities,
|
||||
});
|
||||
const botDirectedRoleIds = [
|
||||
...new Set([
|
||||
...config.botTriggerRoleIds,
|
||||
|
|
@ -374,6 +384,18 @@ export async function startBot(): Promise<void> {
|
|||
silentOwnerQueueAck: !isDirectMessage,
|
||||
forceProvider: addressedRepoIdentity ? "owner_codex" : undefined,
|
||||
});
|
||||
if (addressedRepoIdentity) {
|
||||
await queueRepoFaceRuminationPasses({
|
||||
identity: addressedRepoIdentity,
|
||||
message,
|
||||
actor: buildActorFromMessage(message),
|
||||
guildContext: buildGuildContextFromMessage(message),
|
||||
visiblePrompt,
|
||||
config,
|
||||
contextBuilder,
|
||||
jobQueue,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
await notifyOwnerOfBotIssue(
|
||||
|
|
@ -609,6 +631,202 @@ 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;
|
||||
allowedChannelIds: string[];
|
||||
faceStatePath?: string;
|
||||
};
|
||||
message: Parameters<typeof buildActorFromMessage>[0];
|
||||
actor: ReturnType<typeof buildActorFromMessage>;
|
||||
guildContext: ReturnType<typeof buildGuildContextFromMessage>;
|
||||
visiblePrompt: string;
|
||||
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,
|
||||
);
|
||||
|
||||
for (let passIndex = 1; passIndex <= options.config.repoFaceRuminationPasses; passIndex += 1) {
|
||||
const prompt = buildRepoFaceRuminationPrompt({
|
||||
identity: options.identity,
|
||||
visiblePrompt: options.visiblePrompt,
|
||||
faceStatePath,
|
||||
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: [],
|
||||
});
|
||||
|
||||
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;
|
||||
registryPath: string;
|
||||
identities: RepoDiscordIdentity[];
|
||||
}): Promise<{ identities: RepoDiscordIdentity[] }> {
|
||||
const identitiesMissingRoles = options.identities.filter((identity) => !identity.roleId);
|
||||
|
||||
if (identitiesMissingRoles.length === 0) {
|
||||
return { identities: options.identities };
|
||||
}
|
||||
|
||||
if (!options.guildId) {
|
||||
console.warn(
|
||||
`Repo Discord identities missing roles, but DISCORD_GUILD_ID is not configured: ${
|
||||
identitiesMissingRoles.map((identity) => identity.id).join(", ")
|
||||
}`,
|
||||
);
|
||||
return { identities: options.identities };
|
||||
}
|
||||
|
||||
try {
|
||||
const existingRoles = await fetchGuildRoles(options.botToken, options.guildId);
|
||||
const nextIdentities = [...options.identities];
|
||||
let changed = false;
|
||||
|
||||
for (const identity of identitiesMissingRoles) {
|
||||
const existingRole = existingRoles.find((role) => role.name === identity.displayName);
|
||||
const roleId = existingRole?.id ?? await createRepoIdentityRole(
|
||||
options.botToken,
|
||||
options.guildId,
|
||||
identity.displayName,
|
||||
);
|
||||
const index = nextIdentities.findIndex((entry) => entry.id === identity.id);
|
||||
|
||||
if (index !== -1) {
|
||||
nextIdentities[index] = {
|
||||
...nextIdentities[index],
|
||||
roleId,
|
||||
};
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
await writeRepoIdentityRegistry(options.registryPath, nextIdentities);
|
||||
}
|
||||
|
||||
return { identities: nextIdentities };
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`Failed to ensure repo identity Discord roles: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
return { identities: options.identities };
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchGuildRoles(
|
||||
botToken: string,
|
||||
guildId: string,
|
||||
): Promise<Array<{ id: string; name: string }>> {
|
||||
const response = await fetch(`https://discord.com/api/v10/guilds/${guildId}/roles`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bot ${botToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Discord role lookup failed: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
|
||||
const payload = await response.json() as Array<{ id?: string; name?: string }>;
|
||||
return payload
|
||||
.filter((role): role is { id: string; name: string } => Boolean(role.id && role.name));
|
||||
}
|
||||
|
||||
async function createRepoIdentityRole(
|
||||
botToken: string,
|
||||
guildId: string,
|
||||
name: string,
|
||||
): Promise<string> {
|
||||
const response = await fetch(`https://discord.com/api/v10/guilds/${guildId}/roles`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bot ${botToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
mentionable: true,
|
||||
hoist: false,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Discord role creation failed for ${name}: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
|
||||
const payload = await response.json() as { id?: string };
|
||||
if (!payload.id) {
|
||||
throw new Error(`Discord role creation for ${name} returned no role id.`);
|
||||
}
|
||||
|
||||
return payload.id;
|
||||
}
|
||||
|
||||
async function writeRepoIdentityRegistry(
|
||||
registryPath: string,
|
||||
identities: RepoDiscordIdentity[],
|
||||
): Promise<void> {
|
||||
let existing: unknown;
|
||||
|
||||
try {
|
||||
existing = JSON.parse(stripLeadingBom(await readFile(registryPath, "utf8"))) as unknown;
|
||||
} catch {
|
||||
existing = {};
|
||||
}
|
||||
|
||||
const payload = Array.isArray(existing)
|
||||
? identities
|
||||
: {
|
||||
...(isRecord(existing) ? existing : {}),
|
||||
identities,
|
||||
};
|
||||
await writeFile(registryPath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
||||
function stripAddressingMentions(content: string, roleId?: string): string {
|
||||
if (!roleId) {
|
||||
return content;
|
||||
|
|
@ -638,6 +856,41 @@ function buildRepoIdentityPrompt(
|
|||
].join("\n");
|
||||
}
|
||||
|
||||
function buildRepoFaceRuminationPrompt(input: {
|
||||
identity: {
|
||||
id: string;
|
||||
repoName: string;
|
||||
displayName: string;
|
||||
roleId?: string;
|
||||
avatarUrl?: string;
|
||||
};
|
||||
visiblePrompt: string;
|
||||
faceStatePath: string;
|
||||
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}.`,
|
||||
`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.`,
|
||||
`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 nothing earns persistence or speech, return a short private summary and do not post.",
|
||||
"",
|
||||
"Recent addressed prompt:",
|
||||
input.visiblePrompt,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
function stripLeadingBom(input: string): string {
|
||||
return input.charCodeAt(0) === 0xfeff ? input.slice(1) : input;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -322,7 +322,7 @@ async function processJob(job: JobRecord): Promise<void> {
|
|||
return;
|
||||
}
|
||||
|
||||
if (job.command === "repo-identity-mention") {
|
||||
if (job.command === "repo-identity-mention" || job.command === "repo-face-rumination") {
|
||||
await jobQueue.completeJobDirect(job.id, finalResponse);
|
||||
await deliverOwnerNotifications(job, response.notifications ?? []);
|
||||
await auditLog.record({
|
||||
|
|
@ -333,10 +333,10 @@ async function processJob(job: JobRecord): Promise<void> {
|
|||
details: {
|
||||
summary: response.summary,
|
||||
autoPosted: false,
|
||||
reason: "repo_identity_must_post_through_mcp",
|
||||
reason: `${job.command}_must_post_through_mcp`,
|
||||
},
|
||||
});
|
||||
console.log(`Completed repo identity mention job ${job.id}.`);
|
||||
console.log(`Completed ${job.command} job ${job.id}.`);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -39,6 +39,15 @@ export const postRepoIdentityMessageInputSchema = {
|
|||
replyToMessageId: z.string().min(1).optional(),
|
||||
};
|
||||
|
||||
export const repoFaceStateInputSchema = {
|
||||
identity: z.string().min(1),
|
||||
};
|
||||
|
||||
export const applyRepoFaceStateOperationInputSchema = {
|
||||
identity: z.string().min(1),
|
||||
operation: z.record(z.unknown()),
|
||||
};
|
||||
|
||||
export const searchSourcesInputSchema = {
|
||||
query: z.string().min(1).max(240),
|
||||
limit: z.number().int().min(1).max(MAX_RETRIEVAL_RESULT_LIMIT).optional(),
|
||||
|
|
@ -87,6 +96,15 @@ export interface PostRepoIdentityMessageArgs {
|
|||
replyToMessageId?: string;
|
||||
}
|
||||
|
||||
export interface RepoFaceStateArgs {
|
||||
identity: string;
|
||||
}
|
||||
|
||||
export interface ApplyRepoFaceStateOperationArgs {
|
||||
identity: string;
|
||||
operation: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ListIndexedReposArgs {
|
||||
[key: string]: never;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,9 +4,13 @@ import { type CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
|||
import { DEFAULT_RETRIEVAL_RESULT_LIMIT } from "@voidbot/shared";
|
||||
import { searchHistoryWithArchiveFallback } from "@voidbot/rag";
|
||||
import {
|
||||
applyVoidSelfStateOperation,
|
||||
buildVoidSelfStateContext,
|
||||
findRepoDiscordIdentity,
|
||||
isRepoDiscordIdentityAllowedInChannel,
|
||||
loadRepoDiscordIdentityRegistry,
|
||||
loadVoidSelfStateTypedDocuments,
|
||||
resolveRepoFaceStatePath,
|
||||
} from "@voidbot/core";
|
||||
|
||||
import { type VoidbotMcpContext } from "./mcp-server-context";
|
||||
|
|
@ -15,18 +19,22 @@ import {
|
|||
type ListIndexedReposArgs,
|
||||
type MessageContextArgs,
|
||||
type NotifyOwnerArgs,
|
||||
type ApplyRepoFaceStateOperationArgs,
|
||||
type PostDiscordMessageArgs,
|
||||
type PostRepoIdentityMessageArgs,
|
||||
type RepoFaceStateArgs,
|
||||
type SearchHistoryArgs,
|
||||
type SearchSourcesArgs,
|
||||
type SourceContextArgs,
|
||||
formatArchivedMessage,
|
||||
formatHistoryResults,
|
||||
formatSourceResults,
|
||||
applyRepoFaceStateOperationInputSchema,
|
||||
messageContextInputSchema,
|
||||
notifyOwnerInputSchema,
|
||||
postDiscordMessageInputSchema,
|
||||
postRepoIdentityMessageInputSchema,
|
||||
repoFaceStateInputSchema,
|
||||
renderJsonBlock,
|
||||
searchHistoryInputSchema,
|
||||
searchSourcesInputSchema,
|
||||
|
|
@ -527,6 +535,99 @@ export function registerVoidbotTools(
|
|||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"read_repo_face_state",
|
||||
{
|
||||
title: "Read Repo Face State",
|
||||
description:
|
||||
"Read the typed persistent Face state for a registered repo identity. Face state uses the same typed operation machinery as Void, but the state file belongs to the repo identity.",
|
||||
inputSchema: repoFaceStateInputSchema,
|
||||
annotations: READ_ONLY_ANNOTATIONS,
|
||||
},
|
||||
async (input: RepoFaceStateArgs): Promise<CallToolResult> => {
|
||||
const resolved = await resolveRepoIdentityForTool(context, input.identity);
|
||||
|
||||
if (!resolved.identity) {
|
||||
return resolved.error;
|
||||
}
|
||||
|
||||
const typedState = await loadVoidSelfStateTypedDocuments({
|
||||
canonicalPath: resolved.faceStatePath,
|
||||
});
|
||||
const rendered = buildVoidSelfStateContext(typedState, {
|
||||
sourcePath: resolved.faceStatePath,
|
||||
});
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: renderJsonBlock({
|
||||
identity: identityForToolResult(resolved.identity),
|
||||
faceStatePath: resolved.faceStatePath,
|
||||
summary: rendered.summary,
|
||||
typedState,
|
||||
}),
|
||||
},
|
||||
],
|
||||
structuredContent: {
|
||||
identity: identityForToolResult(resolved.identity),
|
||||
faceStatePath: resolved.faceStatePath,
|
||||
summary: rendered.summary,
|
||||
typedState,
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"apply_repo_face_state_operation",
|
||||
{
|
||||
title: "Apply Repo Face State Operation",
|
||||
description:
|
||||
"Apply one typed state operation to a registered repo identity's Face state. Use this for Face memory, incubation, agency pressure, candidate interventions, and receipts; do not edit the Face state file directly.",
|
||||
inputSchema: applyRepoFaceStateOperationInputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: false,
|
||||
openWorldHint: false,
|
||||
},
|
||||
},
|
||||
async (input: ApplyRepoFaceStateOperationArgs): Promise<CallToolResult> => {
|
||||
const resolved = await resolveRepoIdentityForTool(context, input.identity);
|
||||
|
||||
if (!resolved.identity) {
|
||||
return resolved.error;
|
||||
}
|
||||
|
||||
const result = await applyVoidSelfStateOperation(
|
||||
{ canonicalPath: resolved.faceStatePath },
|
||||
input.operation,
|
||||
);
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: renderJsonBlock({
|
||||
applied: true,
|
||||
identity: identityForToolResult(resolved.identity),
|
||||
faceStatePath: resolved.faceStatePath,
|
||||
result,
|
||||
}),
|
||||
},
|
||||
],
|
||||
structuredContent: {
|
||||
applied: true,
|
||||
identity: identityForToolResult(resolved.identity),
|
||||
faceStatePath: resolved.faceStatePath,
|
||||
result,
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"notify_owner",
|
||||
{
|
||||
|
|
@ -578,3 +679,56 @@ export function registerVoidbotTools(
|
|||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveRepoIdentityForTool(
|
||||
context: VoidbotMcpContext,
|
||||
identitySelector: string,
|
||||
): Promise<
|
||||
| {
|
||||
identity: NonNullable<ReturnType<typeof findRepoDiscordIdentity>>;
|
||||
faceStatePath: string;
|
||||
}
|
||||
| {
|
||||
identity?: undefined;
|
||||
error: CallToolResult;
|
||||
}
|
||||
> {
|
||||
const registry = await loadRepoDiscordIdentityRegistry(
|
||||
context.config.repoDiscordIdentitiesPath,
|
||||
);
|
||||
const identity = findRepoDiscordIdentity(registry, identitySelector);
|
||||
|
||||
if (!identity) {
|
||||
return {
|
||||
error: {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `No registered repo Discord identity matched "${identitySelector}".`,
|
||||
},
|
||||
],
|
||||
structuredContent: {
|
||||
found: false,
|
||||
reason: "unknown_identity",
|
||||
identity: identitySelector,
|
||||
},
|
||||
isError: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
identity,
|
||||
faceStatePath: resolveRepoFaceStatePath(identity, context.config.storageRoot),
|
||||
};
|
||||
}
|
||||
|
||||
function identityForToolResult(identity: NonNullable<ReturnType<typeof findRepoDiscordIdentity>>) {
|
||||
return {
|
||||
id: identity.id,
|
||||
repoName: identity.repoName,
|
||||
displayName: identity.displayName,
|
||||
roleId: identity.roleId ?? null,
|
||||
mention: identity.roleId ? `<@&${identity.roleId}>` : null,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue