2026-04-24 13:17:00 +01:00
import "dotenv/config" ;
import { mkdir , writeFile } from "node:fs/promises" ;
2026-05-19 12:23:22 +01:00
import { spawnSync } from "node:child_process" ;
2026-05-20 20:31:42 +01:00
import { isAbsolute , join , relative , resolve } from "node:path" ;
2026-04-24 13:17:00 +01:00
import { loadConfig } from "@voidbot/config" ;
import {
2026-05-20 20:31:42 +01:00
applyRepoFacePostFatigueAfterSpeech ,
2026-04-24 15:10:34 +01:00
type AuditLog ,
2026-04-24 13:17:00 +01:00
buildVoidMcpServerConfig ,
2026-04-24 15:10:34 +01:00
createStateStorage ,
2026-05-18 17:33:02 +01:00
applyVoidSelfStateOperation ,
2026-05-18 14:21:50 +01:00
findRepoDiscordIdentity ,
isRepoDiscordIdentityAllowedInChannel ,
2026-04-24 15:10:34 +01:00
type JobQueue ,
2026-05-18 14:21:50 +01:00
loadRepoDiscordIdentityRegistry ,
2026-04-24 13:17:00 +01:00
loadSystemMessageCatalog ,
2026-05-18 17:33:02 +01:00
resolveRepoFaceStatePath ,
2026-04-24 13:17:00 +01:00
type SystemMessageCatalog ,
} from "@voidbot/core" ;
import {
LocalLlmProvider ,
OpenAiApiProvider ,
OwnerCodexProvider ,
ProviderRegistry ,
} from "@voidbot/providers" ;
import {
2026-05-04 09:54:27 +01:00
filterPromptEchoHistoryResults ,
2026-04-24 13:17:00 +01:00
createTextEmbedder ,
createVectorStores ,
FileMessageArchiveRepository ,
FileSourceDocumentArchiveRepository ,
RetrievalService ,
2026-05-04 09:54:27 +01:00
searchHistoryWithArchiveFallback ,
2026-04-24 13:17:00 +01:00
SourceDocumentIngester ,
type ArchivedMessageRecord ,
} from "@voidbot/rag" ;
import {
type JobRecord ,
type ProviderArtifact ,
type ProviderNotificationIntent ,
} from "@voidbot/shared" ;
const config = loadConfig ( ) ;
2026-05-18 17:33:02 +01:00
const REPO_IDENTITY_POST_SENTINEL = "VOIDBOT_REPO_IDENTITY_POST:" ;
2026-05-19 12:23:22 +01:00
const REPO_IDENTITY_ARTICLE_SENTINEL = "VOIDBOT_REPO_IDENTITY_ARTICLE:" ;
2026-05-19 16:06:26 +01:00
const REPO_IDENTITY_PROPOSAL_PR_SENTINEL = "VOIDBOT_REPO_IDENTITY_PROPOSAL_PR:" ;
const REPO_IDENTITY_PR_COMMENT_SENTINEL = "VOIDBOT_REPO_IDENTITY_PR_COMMENT:" ;
2026-05-20 21:29:10 +01:00
const REPO_IDENTITY_UPDATE_REQUEST_SENTINEL = "VOIDBOT_REPO_IDENTITY_UPDATE_REQUEST:" ;
2026-05-20 21:45:56 +01:00
const REPO_IDENTITY_BIFROST_TOPIC_SENTINEL = "VOIDBOT_REPO_IDENTITY_BIFROST_TOPIC:" ;
2026-05-02 20:11:49 +01:00
2026-04-24 13:17:00 +01:00
const embedder = createTextEmbedder ( {
backend : config.ragEmbeddingBackend ,
hashDimensions : config.ragEmbeddingDimensions ,
ollamaBaseUrl : config.ragOllamaBaseUrl ,
ollamaModel : config.ragOllamaModel ,
ollamaTimeoutMs : config.ragOllamaTimeoutMs ,
queryInstruction : config.ragQueryInstruction ,
} ) ;
const sourceQueryEmbedder = createTextEmbedder ( {
backend : config.ragEmbeddingBackend ,
hashDimensions : config.ragEmbeddingDimensions ,
ollamaBaseUrl : config.ragOllamaBaseUrl ,
ollamaModel : config.ragOllamaModel ,
ollamaTimeoutMs : config.ragOllamaTimeoutMs ,
queryInstruction : config.ragSourceQueryInstruction ,
} ) ;
const vectorStores = createVectorStores ( {
kind : config.vectorStore.kind ,
historyPath : config.vectorStore.path ,
sourceRoot : config.sourceVectorStoreRoot ,
qdrant : config.qdrant ,
historyEmbedder : embedder ,
sourceEmbedder : sourceQueryEmbedder ,
} ) ;
const historyVectorStore = vectorStores . history ;
const sourceVectorStore = vectorStores . source ;
const archiveRepository = new FileMessageArchiveRepository ( config . ragArchivePath ) ;
const sourceArchiveRepository = new FileSourceDocumentArchiveRepository ( config . ragSourceArchivePath ) ;
const sourceDocumentIngester = new SourceDocumentIngester ( ) ;
const retrievalService = new RetrievalService (
historyVectorStore ,
sourceVectorStore ,
) ;
let isProcessing = false ;
let providerRegistry : ProviderRegistry ;
let systemMessages : SystemMessageCatalog ;
2026-04-24 15:10:34 +01:00
let jobQueue : JobQueue ;
let auditLog : AuditLog ;
2026-04-24 13:17:00 +01:00
void main ( ) . catch ( ( error ) = > {
console . error ( error ) ;
process . exitCode = 1 ;
} ) ;
async function main ( ) : Promise < void > {
2026-04-24 15:10:34 +01:00
const {
jobQueue : stateJobQueue ,
auditLog : stateAuditLog ,
} = await createStateStorage ( {
backend : config.stateStorageBackend ,
databaseDsn : config.databaseDsn ,
jobsFile : config.jobsFile ,
auditLogFile : config.auditLogFile ,
interactionMemoryFile : config.interactionMemoryFile ,
2026-04-26 01:39:42 +01:00
rateLimitStateFile : config.rateLimitStateFile ,
2026-04-24 15:10:34 +01:00
} ) ;
jobQueue = stateJobQueue ;
auditLog = stateAuditLog ;
2026-05-02 18:34:40 +01:00
systemMessages = await loadSystemMessageCatalog (
config . systemMessagesPath ,
resolve ( "config/system-messages.json" ) ,
) ;
2026-04-24 13:17:00 +01:00
providerRegistry = await buildProviderRegistry ( systemMessages ) ;
console . log ( ` VoidBot worker polling every ${ config . workerPollIntervalMs } ms. ` ) ;
2026-05-13 19:46:29 +01:00
await pollPendingJobs ( ) ;
2026-04-24 13:17:00 +01:00
setInterval ( ( ) = > {
2026-05-13 19:46:29 +01:00
void pollPendingJobs ( ) ;
2026-04-24 13:17:00 +01:00
} , config . workerPollIntervalMs ) ;
}
async function processPendingJobs ( ) : Promise < void > {
if ( isProcessing ) {
return ;
}
isProcessing = true ;
try {
2026-05-02 18:34:40 +01:00
systemMessages = await loadSystemMessageCatalog (
config . systemMessagesPath ,
resolve ( "config/system-messages.json" ) ,
) ;
2026-04-24 13:17:00 +01:00
providerRegistry = await buildProviderRegistry ( systemMessages ) ;
const jobs = await jobQueue . claimRunnableJobs ( ) ;
for ( const job of jobs ) {
await processJob ( job ) ;
}
} finally {
isProcessing = false ;
}
}
2026-05-13 19:46:29 +01:00
async function pollPendingJobs ( ) : Promise < void > {
try {
await processPendingJobs ( ) ;
} catch ( error ) {
const message =
error instanceof Error ? ` ${ error . name } : ${ error . message } ` : "Unexpected worker poll failure." ;
console . error ( ` Worker poll failed: ${ message } ` ) ;
}
}
2026-04-24 13:17:00 +01:00
async function buildProviderRegistry ( systemMessagesCatalog : SystemMessageCatalog ) : Promise < ProviderRegistry > {
return new ProviderRegistry ( [
new OwnerCodexProvider ( {
ownerDiscordId : config.ownerDiscordId ,
enabled : config.enabledProviders.includes ( "owner_codex" ) ,
mode : config.ownerCodexMode ,
executable : config.codexExecutable ,
executableArgs : config.codexExecArgs ,
2026-05-02 19:04:09 +01:00
model : config.codexModel ,
2026-04-24 13:17:00 +01:00
reasoningEffort : config.codexModelReasoningEffort ,
timeoutMs : config.codexExecTimeoutMs ,
workingDirectory : process.cwd ( ) ,
historyLookup : retrievalService ,
handoffNoticeBuilder : ( jobId ) = >
systemMessagesCatalog . render ( "owner_codex.handoff_notice" , {
handoffPath : ` .voidbot/artifacts/ ${ jobId } /handoff.md ` ,
debugPath : ` .voidbot/artifacts/ ${ jobId } /debug-trace.md ` ,
} ) ,
mcpServers : [ buildVoidMcpServerConfig ( process . cwd ( ) ) ] ,
} ) ,
new OpenAiApiProvider ( config . enabledProviders . includes ( "openai_api" ) ) ,
new LocalLlmProvider ( {
enabled : config.enabledProviders.includes ( "local_llm" ) ,
ownerDiscordId : config.ownerDiscordId ,
ollamaBaseUrl : config.localLlm.ollamaBaseUrl ,
ollamaModel : config.localLlm.ollamaModel ,
ollamaTimeoutMs : config.localLlm.ollamaTimeoutMs ,
ollamaKeepAlive : config.localLlm.ollamaKeepAlive ,
ollamaThink : config.localLlm.ollamaThink ,
ollamaNumCtx : config.localLlm.ollamaNumCtx ,
allowPublicResponses : config.localLlm.allowPublic ,
toolbox : {
listIndexedRepos : async ( ) = > {
const repos = await sourceArchiveRepository . listRepoSummaries ( ) ;
return {
repoCount : repos.length ,
repos ,
} ;
} ,
searchHistory : async ( input ) = > {
2026-05-04 09:54:27 +01:00
const rawResults = await searchHistoryWithArchiveFallback ( {
retrievalService ,
archiveRepository ,
query : input.query ,
limit : input.limit ,
2026-04-24 13:17:00 +01:00
guildId : input.guildId ,
channelId : input.channelId ,
authorId : input.authorId ,
2026-05-04 09:54:27 +01:00
preserveOverfetch : true ,
2026-04-24 13:17:00 +01:00
} ) ;
2026-05-02 20:11:49 +01:00
const results = filterPromptEchoHistoryResults ( rawResults , input . query ) ;
2026-04-24 13:17:00 +01:00
return {
query : input.query ,
resultCount : results.length ,
results : formatHistoryResults ( results ) ,
} ;
} ,
getMessageContext : async ( input ) = > {
const messages = await archiveRepository . listContextWindow (
input . messageId ,
input . before ,
input . after ,
) ;
return {
found : messages.length > 0 ,
messageId : input.messageId ,
count : messages.length ,
messages : messages.map ( ( message ) = >
formatArchivedMessageContext ( message , input . messageId ) ,
) ,
} ;
} ,
searchSources : async ( input ) = > {
const results = await retrievalService . searchRepositorySources ( input . query , input . limit , {
repoName : input.repoName ,
pathPrefix : input.pathPrefix ,
language : input.language ,
} ) ;
return {
query : input.query ,
resultCount : results.length ,
results : formatSourceResults ( results ) ,
} ;
} ,
getSourceContext : async ( input ) = > {
const document = await sourceArchiveRepository . get ( input . sourceId ) ;
if ( ! document ) {
return {
found : false ,
sourceId : input.sourceId ,
count : 0 ,
chunks : [ ] ,
} ;
}
const chunks = sourceDocumentIngester . buildContextWindow (
document ,
input . chunkIndex ,
input . before ,
input . after ,
) ;
return {
found : true ,
sourceId : input.sourceId ,
repoName : document.repoName ,
path : document.path ,
language : document.language ,
count : chunks.length ,
chunks : chunks.map ( ( chunk ) = > ( {
chunkId : chunk.chunkId ,
chunkIndex : chunk.chunkIndex ,
lineStart : chunk.lineStart ,
lineEnd : chunk.lineEnd ,
isAnchor : chunk.chunkIndex === input . chunkIndex ,
text : chunk.text ,
} ) ) ,
} ;
} ,
} ,
} ) ,
] ) ;
}
async function processJob ( job : JobRecord ) : Promise < void > {
const provider = providerRegistry . get ( job . provider ) ;
if ( ! provider || ! provider . isEnabled ( ) ) {
const errorMessage = ` Provider ${ job . provider } is not enabled. ` ;
await jobQueue . markFailed ( job . id , errorMessage ) ;
await maybeNotifyOwnerOfJobFailure ( job , errorMessage ) ;
return ;
}
try {
const request = provider . buildRequest ( job . contextBundle , {
jobId : job.id ,
command : job.command ,
} ) ;
const response = await provider . execute ( request ) ;
const artifactPaths = await writeArtifacts ( job . id , response . artifacts ? ? [ ] ) ;
if ( response . status === "ready_for_review" ) {
await jobQueue . markAwaitingPostApproval ( job . id , artifactPaths , response . summary ) ;
await deliverOwnerNotifications ( job , response . notifications ? ? [ ] ) ;
await auditLog . record ( {
type : "provider.bundle_ready" ,
actorId : job.requester.id ,
jobId : job.id ,
provider : job.provider ,
details : {
artifactPaths ,
} ,
} ) ;
console . log ( ` Prepared manual package for job ${ job . id } . ` ) ;
return ;
}
const finalResponse = fitDiscordMessage ( response . outputText ? ? response . summary ) ;
if ( job . postApprovalRequired ) {
await jobQueue . markAwaitingPostApproval ( job . id , artifactPaths , response . summary ) ;
await deliverOwnerNotifications ( job , response . notifications ? ? [ ] ) ;
await auditLog . record ( {
type : "provider.completed_pending_post_approval" ,
actorId : job.requester.id ,
jobId : job.id ,
provider : job.provider ,
details : {
summary : response.summary ,
} ,
} ) ;
console . log ( ` Prepared response for post approval on job ${ job . id } . ` ) ;
return ;
}
2026-05-18 14:21:50 +01:00
if ( job . command === "repo-face-rumination" ) {
2026-05-18 17:33:02 +01:00
const repoIdentityPosts = parseRepoIdentityPostIntents ( finalResponse ) ;
2026-05-20 21:45:56 +01:00
const repoIdentityBifrostTopics = parseRepoIdentityBifrostTopicIntents ( finalResponse ) ;
2026-05-20 21:29:10 +01:00
const repoIdentityUpdateRequests = parseRepoIdentityUpdateRequestIntents ( finalResponse ) ;
2026-05-19 16:30:51 +01:00
const repoIdentityArticles = config . repoFaceGithubActionsEnabled
? parseRepoIdentityArticleIntents ( finalResponse )
: [ ] ;
const repoIdentityProposals = config . repoFaceGithubActionsEnabled
? parseRepoIdentityProposalPrIntents ( finalResponse )
: [ ] ;
const repoIdentityPrComments = config . repoFaceGithubActionsEnabled
? parseRepoIdentityPrCommentIntents ( finalResponse )
: [ ] ;
const ignoredGithubActionIntents = config . repoFaceGithubActionsEnabled
? 0
: countRepoIdentityGithubActionIntents ( finalResponse ) ;
2026-05-19 16:06:26 +01:00
const proposalPrSubmitted = repoIdentityProposals . length > 0 ;
const prCommentSubmitted = ! proposalPrSubmitted && repoIdentityPrComments . length > 0 ;
const articlePrSubmitted =
! proposalPrSubmitted && ! prCommentSubmitted && repoIdentityArticles . length > 0 ;
2026-05-20 21:45:56 +01:00
const bifrostTopicSubmitted =
! proposalPrSubmitted && ! prCommentSubmitted && ! articlePrSubmitted && repoIdentityBifrostTopics . length > 0 ;
2026-05-20 21:29:10 +01:00
const updateRequestSubmitted =
2026-05-20 21:45:56 +01:00
! proposalPrSubmitted &&
! prCommentSubmitted &&
! articlePrSubmitted &&
! bifrostTopicSubmitted &&
repoIdentityUpdateRequests . length > 0 ;
2026-05-19 16:06:26 +01:00
if ( repoIdentityProposals . length > 0 ) {
await writeRepoIdentityProposalPrIntent ( job , repoIdentityProposals [ 0 ] ) ;
} else if ( repoIdentityPrComments . length > 0 ) {
await commentRepoIdentityPullRequestIntent ( job , repoIdentityPrComments [ 0 ] ) ;
} else if ( repoIdentityArticles . length > 0 ) {
await writeRepoIdentityArticleIntent ( job , repoIdentityArticles [ 0 ] ) ;
2026-05-20 21:45:56 +01:00
} else if ( repoIdentityBifrostTopics . length > 0 ) {
await submitRepoIdentityBifrostTopicIntent ( job , repoIdentityBifrostTopics [ 0 ] ) ;
2026-05-20 21:29:10 +01:00
} else if ( repoIdentityUpdateRequests . length > 0 ) {
await enqueueRepoIdentityUpdateRequestIntent ( job , repoIdentityUpdateRequests [ 0 ] ) ;
2026-05-19 12:23:22 +01:00
}
2026-05-20 21:45:56 +01:00
if (
! proposalPrSubmitted &&
! prCommentSubmitted &&
! articlePrSubmitted &&
! bifrostTopicSubmitted &&
! updateRequestSubmitted
) {
2026-05-19 16:06:26 +01:00
for ( const post of repoIdentityPosts . slice ( 0 , 1 ) ) {
await postRepoIdentityIntent ( job , post ) ;
}
2026-05-18 17:33:02 +01:00
}
const cleanedFinalResponse = stripRepoIdentityPostIntents ( finalResponse ) ;
await jobQueue . completeJobDirect ( job . id , cleanedFinalResponse || finalResponse ) ;
2026-05-18 10:39:02 +01:00
await deliverOwnerNotifications ( job , response . notifications ? ? [ ] ) ;
await auditLog . record ( {
type : "provider.completed" ,
actorId : job.requester.id ,
jobId : job.id ,
provider : job.provider ,
details : {
summary : response.summary ,
2026-05-19 16:06:26 +01:00
autoPosted :
repoIdentityPosts . length > 0 ||
proposalPrSubmitted ||
prCommentSubmitted ||
2026-05-20 21:29:10 +01:00
articlePrSubmitted ||
2026-05-20 21:45:56 +01:00
bifrostTopicSubmitted ||
2026-05-20 21:29:10 +01:00
updateRequestSubmitted ,
2026-05-19 16:06:26 +01:00
articlePrSubmitted ,
proposalPrSubmitted ,
prCommentSubmitted ,
2026-05-20 21:45:56 +01:00
bifrostTopicSubmitted ,
2026-05-20 21:29:10 +01:00
updateRequestSubmitted ,
2026-05-19 16:30:51 +01:00
ignoredGithubActionIntents ,
2026-05-18 17:33:02 +01:00
reason :
2026-05-19 16:06:26 +01:00
proposalPrSubmitted
? "repo_face_rumination_submitted_registered_identity_proposal_pr"
: prCommentSubmitted
? "repo_face_rumination_commented_on_pr_as_registered_identity"
: articlePrSubmitted
2026-05-19 12:23:22 +01:00
? "repo_face_rumination_submitted_registered_identity_article_pr"
2026-05-20 21:45:56 +01:00
: bifrostTopicSubmitted
? "repo_face_rumination_submitted_bifrost_topic"
2026-05-20 21:29:10 +01:00
: updateRequestSubmitted
? "repo_face_rumination_enqueued_bifrost_update_request"
2026-05-19 16:06:26 +01:00
: repoIdentityPosts . length > 0
? "repo_face_rumination_posted_as_registered_identity"
2026-05-18 17:33:02 +01:00
: ` ${ job . command } _private_summary ` ,
2026-05-18 10:39:02 +01:00
} ,
} ) ;
2026-05-18 10:57:51 +01:00
console . log ( ` Completed ${ job . command } job ${ job . id } . ` ) ;
2026-05-18 10:39:02 +01:00
return ;
}
2026-04-24 13:17:00 +01:00
await postJobResponse ( job , finalResponse ) ;
await jobQueue . completeJobDirect ( job . id , finalResponse ) ;
await deliverOwnerNotifications ( job , response . notifications ? ? [ ] ) ;
await auditLog . record ( {
type : "provider.completed" ,
actorId : job.requester.id ,
jobId : job.id ,
provider : job.provider ,
details : {
summary : response.summary ,
autoPosted : true ,
} ,
} ) ;
console . log ( ` Completed job ${ job . id } . ` ) ;
} catch ( error ) {
const message = error instanceof Error ? error . message : "Unexpected worker failure." ;
await jobQueue . markFailed ( job . id , message ) ;
await maybeNotifyOwnerOfJobFailure ( job , message ) ;
await auditLog . record ( {
type : "provider.failed" ,
actorId : job.requester.id ,
jobId : job.id ,
provider : job.provider ,
details : {
error : message ,
} ,
} ) ;
console . error ( ` Failed job ${ job . id } : ${ message } ` ) ;
}
}
async function maybeNotifyOwnerOfJobFailure ( job : JobRecord , errorMessage : string ) : Promise < void > {
if ( job . requester . id !== config . ownerDiscordId ) {
return ;
}
try {
await postOwnerNotification (
systemMessages . render ( "job.owner.worker_failed_dm" , {
jobId : job.id ,
command : job.command ,
providerName : job.provider ,
errorMessage ,
} ) ,
) ;
} catch ( error ) {
console . error (
` Failed to DM owner about job ${ job . id } : ${
error instanceof Error ? error . message : "Unexpected notification failure."
} ` ,
) ;
}
}
async function deliverOwnerNotifications (
job : JobRecord ,
notifications : ProviderNotificationIntent [ ] ,
) : Promise < void > {
if ( notifications . length === 0 ) {
return ;
}
for ( const notification of notifications ) {
try {
await postOwnerNotification ( notification . message ) ;
await auditLog . record ( {
type : "provider.notification_sent" ,
actorId : job.requester.id ,
jobId : job.id ,
provider : job.provider ,
details : {
channel : notification.channel ,
reason : notification.reason ,
message : notification.message ,
} ,
} ) ;
} catch ( error ) {
const message =
error instanceof Error ? error . message : "Unexpected notification delivery failure." ;
await auditLog . record ( {
type : "provider.notification_failed" ,
actorId : job.requester.id ,
jobId : job.id ,
provider : job.provider ,
details : {
channel : notification.channel ,
reason : notification.reason ,
message : notification.message ,
error : message ,
} ,
} ) ;
console . error ( ` Failed owner notification for job ${ job . id } : ${ message } ` ) ;
}
}
}
async function writeArtifacts (
jobId : string ,
artifacts : ProviderArtifact [ ] ,
) : Promise < Record < string , string > > {
if ( artifacts . length === 0 ) {
return { } ;
}
const artifactDirectory = join ( config . artifactsDir , jobId ) ;
await mkdir ( artifactDirectory , { recursive : true } ) ;
const paths : Record < string , string > = { } ;
for ( const artifact of artifacts ) {
const filePath = join ( artifactDirectory , artifact . name ) ;
await writeFile ( filePath , artifact . content , "utf8" ) ;
paths [ artifact . name ] = filePath ;
}
return paths ;
}
async function postJobResponse ( job : JobRecord , content : string ) : Promise < void > {
if ( ! config . botToken ) {
throw new Error ( "DISCORD_BOT_TOKEN is required for the worker to post completed responses." ) ;
}
const response = await fetch ( ` https://discord.com/api/v10/channels/ ${ job . outputChannelId } /messages ` , {
method : "POST" ,
headers : {
Authorization : ` Bot ${ config . botToken } ` ,
"Content-Type" : "application/json" ,
} ,
body : JSON.stringify ( {
content ,
message_reference : job.requestMessageId
? {
message_id : job.requestMessageId ,
fail_if_not_exists : false ,
}
: undefined ,
allowed_mentions : {
parse : [ ] ,
} ,
} ) ,
} ) ;
if ( ! response . ok ) {
throw new Error ( ` Discord post failed with ${ response . status } : ${ await response . text ( ) } ` ) ;
}
}
2026-05-18 14:21:50 +01:00
function parseRepoIdentityIdFromPrompt ( prompt : string ) : string | undefined {
const match = prompt . match ( /repo identity\s+.+?\(([^)]+)\)\s+for repo/i ) ;
2026-05-18 17:33:02 +01:00
return (
match ? . [ 1 ] ? . trim ( ) ? ?
prompt . match ( /repo Face heartbeat for .+?\(([^)]+)\) over repo/i ) ? . [ 1 ] ? . trim ( ) ? ?
prompt . match ( /identity "([^"]+)"/i ) ? . [ 1 ] ? . trim ( )
) ;
}
interface RepoIdentityPostIntent {
identity? : string ;
channelId? : string ;
content : string ;
replyToMessageId? : string ;
}
2026-05-19 12:23:22 +01:00
interface RepoIdentityArticleIntent {
identity? : string ;
title : string ;
path? : string ;
content : string ;
shareContent? : string ;
channelId? : string ;
replyToMessageId? : string ;
}
2026-05-19 16:06:26 +01:00
interface RepoIdentityProposalPrIntent {
identity? : string ;
title : string ;
path? : string ;
content : string ;
shareContent? : string ;
channelId? : string ;
replyToMessageId? : string ;
}
interface RepoIdentityPrCommentIntent {
identity? : string ;
pr : string ;
content : string ;
shareContent? : string ;
channelId? : string ;
replyToMessageId? : string ;
}
2026-05-20 21:29:10 +01:00
interface RepoIdentityUpdateRequestIntent {
identity? : string ;
title : string ;
content : string ;
priority? : number ;
sourceMessageIds : string [ ] ;
channelId? : string ;
replyToMessageId? : string ;
}
2026-05-20 21:45:56 +01:00
interface RepoIdentityBifrostTopicIntent {
identity? : string ;
topicId? : string ;
title? : string ;
content : string ;
2026-05-20 21:55:28 +01:00
mirrorContent? : string ;
2026-05-20 21:45:56 +01:00
stance? : string ;
priority? : number ;
approve? : boolean ;
dispatch? : boolean ;
sourceMessageIds : string [ ] ;
channelId? : string ;
replyToMessageId? : string ;
}
2026-05-20 20:31:42 +01:00
interface BifrostBridgeReceipt {
action? : string ;
ok? : boolean ;
branch? : string ;
prUrl? : string ;
messageId? : string ;
transport ? : "bot" | "webhook" ;
}
2026-05-20 21:29:10 +01:00
interface BifrostUpdateRequestReceipt {
id : string ;
status : "queued" | "claimed" | "completed" | "cancelled" ;
title : string ;
targetRepoName : string ;
targetAgentIdentity? : string ;
priority : number ;
}
2026-05-20 21:45:56 +01:00
interface BifrostGovernanceTopicReceipt {
id : string ;
status : string ;
title : string ;
jurisdictionRepoName : string ;
jurisdictionAgentIdentity? : string ;
dispatchRequestId? : string ;
}
2026-05-18 17:33:02 +01:00
async function postRepoIdentityIntent ( job : JobRecord , intent : RepoIdentityPostIntent ) : Promise < void > {
if ( ! config . botToken ) {
2026-05-20 20:31:42 +01:00
throw new Error ( "DISCORD_BOT_TOKEN is required for Bifrost to post repo identity responses." ) ;
2026-05-18 17:33:02 +01:00
}
const identityId = intent . identity ? ? parseRepoIdentityIdFromPrompt ( job . prompt ) ;
if ( ! identityId ) {
throw new Error ( ` Could not resolve repo identity for job ${ job . id } . ` ) ;
}
const channelId = intent . channelId ? ? job . outputChannelId ;
const registry = await loadRepoDiscordIdentityRegistry ( config . repoDiscordIdentitiesPath ) ;
const identity = findRepoDiscordIdentity ( registry , identityId ) ;
if ( ! identity ) {
throw new Error ( ` No registered repo identity matched " ${ identityId } " for job ${ job . id } . ` ) ;
}
if ( ! isRepoDiscordIdentityAllowedInChannel ( identity , channelId ) ) {
throw new Error ( ` Repo identity ${ identity . id } is not registered for Discord channel ${ channelId } . ` ) ;
}
2026-05-19 13:56:40 +01:00
const content = sanitizeRepoIdentityPostContent ( identity , intent . content ) ;
2026-05-20 20:31:42 +01:00
const contentFile = await writeBifrostPayloadFile ( job , ` ${ identity . id } -discord-post.md ` , fitDiscordMessage ( content ) ) ;
const posted = runBifrostBridge ( [
"discord-post" ,
"--channel-id" ,
2026-05-18 17:33:02 +01:00
channelId ,
2026-05-20 20:31:42 +01:00
"--content-file" ,
contentFile ,
"--persona-name" ,
identity . displayName ,
. . . ( identity . avatarUrl ? [ "--persona-avatar-url" , identity . avatarUrl ] : [ ] ) ,
. . . ( intent . replyToMessageId ? [ "--reply-to-message-id" , intent . replyToMessageId ] : [ ] ) ,
] ) ;
if ( ! posted . messageId || ! posted . transport ) {
throw new Error ( ` Bifrost Discord bridge returned no message receipt for job ${ job . id } . ` ) ;
}
2026-05-18 17:33:02 +01:00
await recordRepoIdentityDeliveryReceipt ( {
identity ,
channelId ,
2026-05-19 13:56:40 +01:00
content ,
2026-05-18 17:33:02 +01:00
replyToMessageId : intent.replyToMessageId ,
2026-05-20 20:31:42 +01:00
messageId : posted.messageId ,
2026-05-18 17:33:02 +01:00
transport : posted.transport ,
} ) . catch ( ( error : unknown ) = > {
const message = error instanceof Error ? error.message : String ( error ) ;
console . warn ( ` Could not record repo identity delivery receipt for job ${ job . id } : ${ message } ` ) ;
} ) ;
}
2026-05-19 13:56:40 +01:00
function sanitizeRepoIdentityPostContent ( identity : { displayName : string ; repoName : string } , content : string ) : string {
let sanitized = content . trim ( ) ;
const escapedRepo = escapeRegExp ( identity . repoName ) ;
const escapedDisplay = escapeRegExp ( identity . displayName ) ;
const prefixPatterns = [
new RegExp ( ` ^(?:repo[- ]?face \\ s+)?heartbeat \\ s+from \\ s+ ${ escapedRepo } \\ s*: \\ s* ` , "i" ) ,
new RegExp ( ` ^ ${ escapedRepo } \\ s+heartbeat(?: \\ s+complete)? \\ s*: \\ s* ` , "i" ) ,
new RegExp ( ` ^ ${ escapedDisplay } \\ s+heartbeat(?: \\ s+complete)? \\ s*: \\ s* ` , "i" ) ,
/^(?:repo[- ]?face\s+)?heartbeat\s+from\s+[^:]{1,80}\s*:\s*/i ,
] ;
for ( const pattern of prefixPatterns ) {
sanitized = sanitized . replace ( pattern , "" ) . trim ( ) ;
}
return sanitized . length > 0 ? sanitized : content.trim ( ) ;
}
function escapeRegExp ( value : string ) : string {
return value . replace ( /[.*+?^${}()|[\]\\]/g , "\\$&" ) ;
}
2026-05-18 17:33:02 +01:00
function parseRepoIdentityPostIntents ( finalResponse : string ) : RepoIdentityPostIntent [ ] {
const intents : RepoIdentityPostIntent [ ] = [ ] ;
for ( const line of finalResponse . split ( /\r?\n/ ) ) {
const trimmed = line . trim ( ) ;
if ( ! trimmed . startsWith ( REPO_IDENTITY_POST_SENTINEL ) ) {
continue ;
}
const payload = trimmed . slice ( REPO_IDENTITY_POST_SENTINEL . length ) . trim ( ) ;
try {
const parsed = JSON . parse ( payload ) as Record < string , unknown > ;
const content = typeof parsed . content === "string" ? parsed . content . trim ( ) : "" ;
if ( ! content ) {
continue ;
}
intents . push ( {
identity : typeof parsed . identity === "string" ? parsed . identity . trim ( ) : undefined ,
channelId : typeof parsed . channelId === "string" ? parsed . channelId . trim ( ) : undefined ,
replyToMessageId :
typeof parsed . replyToMessageId === "string" ? parsed . replyToMessageId . trim ( ) : undefined ,
content ,
} ) ;
} catch {
continue ;
}
}
return intents ;
}
2026-05-19 12:23:22 +01:00
async function writeRepoIdentityArticleIntent ( job : JobRecord , intent : RepoIdentityArticleIntent ) : Promise < void > {
const identityId = intent . identity ? ? parseRepoIdentityIdFromPrompt ( job . prompt ) ;
if ( ! identityId ) {
throw new Error ( ` Could not resolve repo identity for article intent on job ${ job . id } . ` ) ;
}
const registry = await loadRepoDiscordIdentityRegistry ( config . repoDiscordIdentitiesPath ) ;
const identity = findRepoDiscordIdentity ( registry , identityId ) ;
if ( ! identity ) {
throw new Error ( ` No registered repo identity matched " ${ identityId } " for article intent on job ${ job . id } . ` ) ;
}
const repoRoot = resolveRepoRoot ( identity ) ;
const relativePath = normalizeArticlePath ( intent , identity ) ;
const articlePath = resolve ( repoRoot , relativePath ) ;
if ( ! isPathInside ( repoRoot , articlePath ) ) {
throw new Error ( ` Article path escapes repo root for ${ identity . id } : ${ relativePath } ` ) ;
}
2026-05-20 20:31:42 +01:00
const contentFile = await writeBifrostPayloadFile ( job , ` ${ identity . id } -article.md ` , ensureTrailingNewline ( intent . content ) ) ;
const pr = runBifrostBridge ( [
"github-draft-pr" ,
"--repo-root" ,
2026-05-19 12:23:22 +01:00
repoRoot ,
2026-05-20 20:31:42 +01:00
"--identity" ,
identity . id ,
"--title" ,
` ${ identity . id } : article: ${ intent . title } ` ,
"--path" ,
2026-05-19 12:23:22 +01:00
relativePath ,
2026-05-20 20:31:42 +01:00
"--content-file" ,
contentFile ,
"--body" ,
` Draft bylined article submitted by repo Face ${ identity . id } . \ n \ nPath: ${ relativePath } ` ,
"--commit-message" ,
` ${ identity . id } : draft article ${ intent . title } ` ,
] ) ;
2026-05-19 12:23:22 +01:00
2026-05-20 20:31:42 +01:00
const prLine = pr . prUrl ? ` \ n \ nPR: ${ pr . prUrl } ` : ` \ n \ nDraft branch: ${ pr . branch } ` ;
2026-05-19 12:32:07 +01:00
const articleLine = ` \ nArticle path: ${ relativePath } ` ;
const shareContent =
intent . shareContent && intent . shareContent . trim ( ) . length > 0
? intent . shareContent . trim ( )
: ` ${ identity . displayName } : I drafted " ${ intent . title } " as a bylined article and submitted it for review. ` ;
await postRepoIdentityIntent ( job , {
identity : identity.id ,
channelId : intent.channelId ? ? job . outputChannelId ,
replyToMessageId : intent.replyToMessageId ,
content : ` ${ shareContent } ${ prLine } ${ articleLine } ` ,
} ) ;
2026-05-19 12:23:22 +01:00
}
2026-05-19 16:06:26 +01:00
async function writeRepoIdentityProposalPrIntent (
job : JobRecord ,
intent : RepoIdentityProposalPrIntent ,
) : Promise < void > {
const identityId = intent . identity ? ? parseRepoIdentityIdFromPrompt ( job . prompt ) ;
if ( ! identityId ) {
throw new Error ( ` Could not resolve repo identity for proposal PR intent on job ${ job . id } . ` ) ;
}
const registry = await loadRepoDiscordIdentityRegistry ( config . repoDiscordIdentitiesPath ) ;
const identity = findRepoDiscordIdentity ( registry , identityId ) ;
if ( ! identity ) {
throw new Error ( ` No registered repo identity matched " ${ identityId } " for proposal PR intent on job ${ job . id } . ` ) ;
}
const repoRoot = resolveRepoRoot ( identity ) ;
const relativePath = normalizeProposalPath ( intent , identity ) ;
const proposalPath = resolve ( repoRoot , relativePath ) ;
if ( ! isPathInside ( repoRoot , proposalPath ) ) {
throw new Error ( ` Proposal path escapes repo root for ${ identity . id } : ${ relativePath } ` ) ;
}
2026-05-20 20:31:42 +01:00
const contentFile = await writeBifrostPayloadFile ( job , ` ${ identity . id } -proposal.md ` , ensureTrailingNewline ( intent . content ) ) ;
const pr = runBifrostBridge ( [
"github-draft-pr" ,
"--repo-root" ,
2026-05-19 16:06:26 +01:00
repoRoot ,
2026-05-20 20:31:42 +01:00
"--identity" ,
identity . id ,
"--title" ,
` ${ identity . id } : proposal: ${ intent . title } ` ,
"--path" ,
2026-05-19 16:06:26 +01:00
relativePath ,
2026-05-20 20:31:42 +01:00
"--content-file" ,
contentFile ,
"--body" ,
` Draft change proposal submitted by repo Face ${ identity . id } . \ n \ nPath: ${ relativePath } ` ,
"--commit-message" ,
` ${ identity . id } : draft proposal ${ intent . title } ` ,
] ) ;
2026-05-19 16:06:26 +01:00
2026-05-20 20:31:42 +01:00
const prLine = pr . prUrl ? ` \ n \ nPR: ${ pr . prUrl } ` : ` \ n \ nDraft branch: ${ pr . branch } ` ;
2026-05-19 16:06:26 +01:00
const proposalLine = ` \ nProposal path: ${ relativePath } ` ;
const shareContent =
intent . shareContent && intent . shareContent . trim ( ) . length > 0
? intent . shareContent . trim ( )
: ` ${ identity . displayName } : I put the change proposal where it belongs: a draft PR for review. ` ;
await postRepoIdentityIntent ( job , {
identity : identity.id ,
channelId : intent.channelId ? ? job . outputChannelId ,
replyToMessageId : intent.replyToMessageId ,
content : ` ${ shareContent } ${ prLine } ${ proposalLine } ` ,
} ) ;
}
async function commentRepoIdentityPullRequestIntent (
job : JobRecord ,
intent : RepoIdentityPrCommentIntent ,
) : Promise < void > {
const identityId = intent . identity ? ? parseRepoIdentityIdFromPrompt ( job . prompt ) ;
if ( ! identityId ) {
throw new Error ( ` Could not resolve repo identity for PR comment intent on job ${ job . id } . ` ) ;
}
const registry = await loadRepoDiscordIdentityRegistry ( config . repoDiscordIdentitiesPath ) ;
const identity = findRepoDiscordIdentity ( registry , identityId ) ;
if ( ! identity ) {
throw new Error ( ` No registered repo identity matched " ${ identityId } " for PR comment intent on job ${ job . id } . ` ) ;
}
const repoRoot = resolveRepoRoot ( identity ) ;
const prTarget = intent . pr . trim ( ) ;
if ( ! prTarget ) {
throw new Error ( ` PR comment intent for ${ identity . id } on job ${ job . id } did not include a PR target. ` ) ;
}
const body = ` ${ identity . displayName } ( ${ identity . id } ) says: \ n \ n ${ intent . content . trim ( ) } ` ;
2026-05-20 20:31:42 +01:00
const contentFile = await writeBifrostPayloadFile ( job , ` ${ identity . id } -pr-comment.md ` , body ) ;
runBifrostBridge ( [
"github-pr-comment" ,
"--repo-root" ,
repoRoot ,
"--identity" ,
identity . id ,
"--pr" ,
prTarget ,
"--content-file" ,
contentFile ,
] ) ;
2026-05-19 16:06:26 +01:00
const shareContent =
intent . shareContent && intent . shareContent . trim ( ) . length > 0
? intent . shareContent . trim ( )
: ` ${ identity . displayName } : I left my argument on the PR so the proposal has a real review trail. ` ;
await postRepoIdentityIntent ( job , {
identity : identity.id ,
channelId : intent.channelId ? ? job . outputChannelId ,
replyToMessageId : intent.replyToMessageId ,
content : ` ${ shareContent } \ n \ nPR: ${ prTarget } ` ,
} ) ;
}
2026-05-20 21:29:10 +01:00
async function enqueueRepoIdentityUpdateRequestIntent (
job : JobRecord ,
intent : RepoIdentityUpdateRequestIntent ,
) : Promise < void > {
const identityId = intent . identity ? ? parseRepoIdentityIdFromPrompt ( job . prompt ) ;
if ( ! identityId ) {
throw new Error ( ` Could not resolve repo identity for Bifrost update request intent on job ${ job . id } . ` ) ;
}
const registry = await loadRepoDiscordIdentityRegistry ( config . repoDiscordIdentitiesPath ) ;
const identity = findRepoDiscordIdentity ( registry , identityId ) ;
if ( ! identity ) {
throw new Error ( ` No registered repo identity matched " ${ identityId } " for update request intent on job ${ job . id } . ` ) ;
}
const contentFile = await writeBifrostPayloadFile (
job ,
` ${ identity . id } -bifrost-update-request.md ` ,
ensureTrailingNewline ( renderRepoIdentityUpdateRequestMarkdown ( identity , intent ) ) ,
) ;
const sourceMessageIds = Array . from ( new Set ( [
. . . intent . sourceMessageIds ,
intent . replyToMessageId ,
] . filter ( ( value ) : value is string = > typeof value === "string" && value . trim ( ) . length > 0 ) ) ) ;
const request = runBifrostAgentTransport ( [
"enqueue" ,
"--repo" ,
identity . repoName ,
"--agent" ,
identity . id ,
"--title" ,
intent . title ,
"--request-file" ,
contentFile ,
"--priority" ,
String ( normalizeBifrostPriority ( intent . priority ) ) ,
"--source-kind" ,
"repo_face_heartbeat" ,
"--packet-path" ,
contentFile ,
"--created-by" ,
identity . id ,
. . . ( intent . channelId ? ? job . outputChannelId ? [ "--source-channel-id" , intent . channelId ? ? job . outputChannelId ] : [ ] ) ,
. . . ( sourceMessageIds . length > 0 ? [ "--source-message-ids" , sourceMessageIds . join ( "," ) ] : [ ] ) ,
] ) ;
console . log (
` Enqueued Bifrost update request ${ request . id } for ${ identity . id } / ${ identity . repoName } from job ${ job . id } . ` ,
) ;
}
2026-05-20 21:45:56 +01:00
async function submitRepoIdentityBifrostTopicIntent (
job : JobRecord ,
intent : RepoIdentityBifrostTopicIntent ,
) : Promise < void > {
const identityId = intent . identity ? ? parseRepoIdentityIdFromPrompt ( job . prompt ) ;
if ( ! identityId ) {
throw new Error ( ` Could not resolve repo identity for Bifrost topic intent on job ${ job . id } . ` ) ;
}
const registry = await loadRepoDiscordIdentityRegistry ( config . repoDiscordIdentitiesPath ) ;
const identity = findRepoDiscordIdentity ( registry , identityId ) ;
if ( ! identity ) {
throw new Error ( ` No registered repo identity matched " ${ identityId } " for Bifrost topic intent on job ${ job . id } . ` ) ;
}
const contentFile = await writeBifrostPayloadFile (
job ,
` ${ identity . id } -bifrost-topic.md ` ,
ensureTrailingNewline ( intent . content ) ,
) ;
2026-05-20 21:55:28 +01:00
const mirrorContentFile = intent . mirrorContent
? await writeBifrostPayloadFile (
job ,
` ${ identity . id } -bifrost-topic-mirror.md ` ,
ensureTrailingNewline ( intent . mirrorContent ) ,
)
: undefined ;
2026-05-20 21:45:56 +01:00
const sourceMessageIds = Array . from ( new Set ( [
. . . intent . sourceMessageIds ,
intent . replyToMessageId ,
] . filter ( ( value ) : value is string = > typeof value === "string" && value . trim ( ) . length > 0 ) ) ) ;
let topicId = intent . topicId ;
if ( ! topicId ) {
if ( ! intent . title ) {
throw new Error ( ` Bifrost topic intent for ${ identity . id } on job ${ job . id } needs title when topicId is absent. ` ) ;
}
const opened = runBifrostGovernanceThreads ( [
"open" ,
"--repo" ,
identity . repoName ,
"--agent" ,
identity . id ,
"--title" ,
intent . title ,
"--summary-file" ,
contentFile ,
"--priority" ,
String ( normalizeBifrostPriority ( intent . priority ) ) ,
"--source-kind" ,
"repo_face_heartbeat" ,
"--created-by" ,
identity . id ,
. . . ( intent . channelId ? ? job . outputChannelId ? [ "--source-channel-id" , intent . channelId ? ? job . outputChannelId ] : [ ] ) ,
. . . ( sourceMessageIds . length > 0 ? [ "--source-message-ids" , sourceMessageIds . join ( "," ) ] : [ ] ) ,
2026-05-20 21:55:28 +01:00
. . . bifrostMirrorArgs ( identity , mirrorContentFile ) ,
2026-05-20 21:45:56 +01:00
] ) as BifrostGovernanceTopicReceipt ;
topicId = opened . id ;
} else if ( ! intent . approve ) {
runBifrostGovernanceThreads ( [
"comment" ,
"--topic" ,
topicId ,
"--author" ,
identity . id ,
"--author-kind" ,
"face" ,
"--stance" ,
normalizeBifrostTopicStance ( intent . stance ) ,
"--body-file" ,
contentFile ,
. . . ( intent . replyToMessageId ? [ "--source-message-id" , intent . replyToMessageId ] : [ ] ) ,
2026-05-20 21:55:28 +01:00
. . . bifrostMirrorArgs ( identity , mirrorContentFile ) ,
2026-05-20 21:45:56 +01:00
] ) ;
}
if ( intent . approve ) {
runBifrostGovernanceThreads ( [
"approve" ,
"--topic" ,
topicId ,
"--approved-by" ,
identity . id ,
"--body-file" ,
contentFile ,
. . . ( intent . replyToMessageId ? [ "--source-message-id" , intent . replyToMessageId ] : [ ] ) ,
2026-05-20 21:55:28 +01:00
. . . bifrostMirrorArgs ( identity , mirrorContentFile ) ,
2026-05-20 21:45:56 +01:00
] ) ;
}
let promoted : { topic? : BifrostGovernanceTopicReceipt ; request? : BifrostUpdateRequestReceipt } | undefined ;
if ( intent . dispatch ) {
2026-05-20 21:55:28 +01:00
promoted = runBifrostGovernanceThreads ( [
"promote" ,
"--topic" ,
topicId ,
] ) as {
2026-05-20 21:45:56 +01:00
topic? : BifrostGovernanceTopicReceipt ;
request? : BifrostUpdateRequestReceipt ;
} ;
}
console . log (
promoted ? . request
? ` Promoted Bifrost topic ${ topicId } to update request ${ promoted . request . id } for ${ identity . id } / ${ identity . repoName } from job ${ job . id } . `
: ` Updated Bifrost topic ${ topicId } for ${ identity . id } / ${ identity . repoName } from job ${ job . id } . ` ,
) ;
}
2026-05-20 20:31:42 +01:00
async function writeBifrostPayloadFile ( job : JobRecord , fileName : string , content : string ) : Promise < string > {
const directory = resolve ( config . storageRoot , "artifacts" , job . id , "bifrost-bridge" ) ;
await mkdir ( directory , { recursive : true } ) ;
const path = join ( directory , sanitizePathSegment ( fileName ) || "payload.md" ) ;
await writeFile ( path , content , "utf8" ) ;
return path ;
2026-05-19 12:23:22 +01:00
}
2026-05-20 21:29:10 +01:00
function runBifrostAgentTransport ( args : string [ ] ) : BifrostUpdateRequestReceipt {
const transportScript = resolve ( config . bifrostRoot , "tools" , "agent-transport.mjs" ) ;
const result = spawnSync ( process . execPath , [ transportScript , . . . args ] , {
cwd : config.bifrostRoot ,
encoding : "utf8" ,
windowsHide : true ,
} ) ;
if ( result . status !== 0 ) {
throw new Error ( ` Bifrost agent transport failed: ${ result . stderr || result . stdout } ` ) ;
}
try {
return JSON . parse ( result . stdout ) as BifrostUpdateRequestReceipt ;
} catch {
throw new Error ( ` Bifrost agent transport returned non-JSON output: ${ result . stdout } ` ) ;
}
}
2026-05-20 21:45:56 +01:00
function runBifrostGovernanceThreads ( args : string [ ] ) : BifrostGovernanceTopicReceipt | Record < string , unknown > {
const governanceScript = resolve ( config . bifrostRoot , "tools" , "governance-threads.mjs" ) ;
const result = spawnSync ( process . execPath , [ governanceScript , . . . args ] , {
cwd : config.bifrostRoot ,
encoding : "utf8" ,
windowsHide : true ,
} ) ;
if ( result . status !== 0 ) {
throw new Error ( ` Bifrost governance thread command failed: ${ result . stderr || result . stdout } ` ) ;
}
try {
return JSON . parse ( result . stdout ) as BifrostGovernanceTopicReceipt | Record < string , unknown > ;
} catch {
throw new Error ( ` Bifrost governance thread command returned non-JSON output: ${ result . stdout } ` ) ;
}
}
2026-05-20 21:55:28 +01:00
function bifrostMirrorArgs (
identity : { displayName : string ; avatarUrl? : string } ,
mirrorContentFile? : string ,
) : string [ ] {
if ( ! config . bifrostDiscordChannelId ) {
return [ ] ;
}
return [
"--mirror-channel-id" ,
config . bifrostDiscordChannelId ,
"--mirror-persona-name" ,
identity . displayName ,
. . . ( identity . avatarUrl ? [ "--mirror-persona-avatar-url" , identity . avatarUrl ] : [ ] ) ,
. . . ( mirrorContentFile ? [ "--mirror-content-file" , mirrorContentFile ] : [ ] ) ,
] ;
}
2026-05-20 20:31:42 +01:00
function runBifrostBridge ( args : string [ ] ) : BifrostBridgeReceipt {
const bridgeScript = resolve ( config . bifrostRoot , "tools" , "bifrost-bridge.mjs" ) ;
const result = spawnSync ( "node" , [ bridgeScript , . . . args ] , {
cwd : config.bifrostRoot ,
2026-05-19 12:23:22 +01:00
encoding : "utf8" ,
windowsHide : true ,
} ) ;
2026-05-20 20:31:42 +01:00
2026-05-19 12:23:22 +01:00
if ( result . status !== 0 ) {
2026-05-20 20:31:42 +01:00
throw new Error ( ` Bifrost bridge failed: ${ result . stderr || result . stdout } ` ) ;
2026-05-19 12:23:22 +01:00
}
2026-05-20 20:31:42 +01:00
try {
return JSON . parse ( result . stdout ) as BifrostBridgeReceipt ;
} catch {
throw new Error ( ` Bifrost bridge returned non-JSON output: ${ result . stdout } ` ) ;
2026-05-19 16:06:26 +01:00
}
}
2026-05-20 21:29:10 +01:00
function parseRepoIdentityUpdateRequestIntents ( finalResponse : string ) : RepoIdentityUpdateRequestIntent [ ] {
const intents : RepoIdentityUpdateRequestIntent [ ] = [ ] ;
for ( const line of finalResponse . split ( /\r?\n/ ) ) {
const trimmed = line . trim ( ) ;
if ( ! trimmed . startsWith ( REPO_IDENTITY_UPDATE_REQUEST_SENTINEL ) ) {
continue ;
}
const payload = trimmed . slice ( REPO_IDENTITY_UPDATE_REQUEST_SENTINEL . length ) . trim ( ) ;
try {
const parsed = JSON . parse ( payload ) as Record < string , unknown > ;
const title = typeof parsed . title === "string" ? parsed . title . trim ( ) : "" ;
const content = typeof parsed . content === "string" ? parsed . content . trim ( ) : "" ;
if ( ! title || ! content ) {
continue ;
}
intents . push ( {
identity : typeof parsed . identity === "string" ? parsed . identity . trim ( ) : undefined ,
title ,
content ,
priority : typeof parsed . priority === "number" ? parsed.priority : undefined ,
sourceMessageIds : Array.isArray ( parsed . sourceMessageIds )
? parsed . sourceMessageIds . filter ( ( entry ) : entry is string = > typeof entry === "string" )
: [ ] ,
channelId : typeof parsed . channelId === "string" ? parsed . channelId . trim ( ) : undefined ,
replyToMessageId :
typeof parsed . replyToMessageId === "string" ? parsed . replyToMessageId . trim ( ) : undefined ,
} ) ;
} catch {
continue ;
}
}
return intents ;
}
2026-05-20 21:45:56 +01:00
function parseRepoIdentityBifrostTopicIntents ( finalResponse : string ) : RepoIdentityBifrostTopicIntent [ ] {
const intents : RepoIdentityBifrostTopicIntent [ ] = [ ] ;
for ( const line of finalResponse . split ( /\r?\n/ ) ) {
const trimmed = line . trim ( ) ;
if ( ! trimmed . startsWith ( REPO_IDENTITY_BIFROST_TOPIC_SENTINEL ) ) {
continue ;
}
const payload = trimmed . slice ( REPO_IDENTITY_BIFROST_TOPIC_SENTINEL . length ) . trim ( ) ;
try {
const parsed = JSON . parse ( payload ) as Record < string , unknown > ;
const content = typeof parsed . content === "string" ? parsed . content . trim ( ) : "" ;
const title = typeof parsed . title === "string" ? parsed . title . trim ( ) : undefined ;
const topicId = typeof parsed . topicId === "string" ? parsed . topicId . trim ( ) : undefined ;
if ( ! content || ( ! topicId && ! title ) ) {
continue ;
}
intents . push ( {
identity : typeof parsed . identity === "string" ? parsed . identity . trim ( ) : undefined ,
topicId ,
title ,
content ,
2026-05-20 21:55:28 +01:00
mirrorContent : typeof parsed . mirrorContent === "string" ? parsed . mirrorContent . trim ( ) : undefined ,
2026-05-20 21:45:56 +01:00
stance : typeof parsed . stance === "string" ? parsed . stance . trim ( ) : undefined ,
priority : typeof parsed . priority === "number" ? parsed.priority : undefined ,
approve : parsed.approve === true ,
dispatch : parsed.dispatch === true ,
sourceMessageIds : Array.isArray ( parsed . sourceMessageIds )
? parsed . sourceMessageIds . filter ( ( entry ) : entry is string = > typeof entry === "string" )
: [ ] ,
channelId : typeof parsed . channelId === "string" ? parsed . channelId . trim ( ) : undefined ,
replyToMessageId :
typeof parsed . replyToMessageId === "string" ? parsed . replyToMessageId . trim ( ) : undefined ,
} ) ;
} catch {
continue ;
}
}
return intents ;
}
2026-05-19 12:23:22 +01:00
function parseRepoIdentityArticleIntents ( finalResponse : string ) : RepoIdentityArticleIntent [ ] {
const intents : RepoIdentityArticleIntent [ ] = [ ] ;
for ( const line of finalResponse . split ( /\r?\n/ ) ) {
const trimmed = line . trim ( ) ;
if ( ! trimmed . startsWith ( REPO_IDENTITY_ARTICLE_SENTINEL ) ) {
continue ;
}
const payload = trimmed . slice ( REPO_IDENTITY_ARTICLE_SENTINEL . length ) . trim ( ) ;
try {
const parsed = JSON . parse ( payload ) as Record < string , unknown > ;
const title = typeof parsed . title === "string" ? parsed . title . trim ( ) : "" ;
const content = typeof parsed . content === "string" ? parsed . content . trim ( ) : "" ;
if ( ! title || ! content ) {
continue ;
}
intents . push ( {
identity : typeof parsed . identity === "string" ? parsed . identity . trim ( ) : undefined ,
title ,
path : typeof parsed . path === "string" ? parsed . path . trim ( ) : undefined ,
content ,
shareContent : typeof parsed . shareContent === "string" ? parsed . shareContent . trim ( ) : undefined ,
channelId : typeof parsed . channelId === "string" ? parsed . channelId . trim ( ) : undefined ,
replyToMessageId :
typeof parsed . replyToMessageId === "string" ? parsed . replyToMessageId . trim ( ) : undefined ,
} ) ;
} catch {
continue ;
}
}
return intents ;
}
2026-05-19 16:06:26 +01:00
function parseRepoIdentityProposalPrIntents ( finalResponse : string ) : RepoIdentityProposalPrIntent [ ] {
const intents : RepoIdentityProposalPrIntent [ ] = [ ] ;
for ( const line of finalResponse . split ( /\r?\n/ ) ) {
const trimmed = line . trim ( ) ;
if ( ! trimmed . startsWith ( REPO_IDENTITY_PROPOSAL_PR_SENTINEL ) ) {
continue ;
}
const payload = trimmed . slice ( REPO_IDENTITY_PROPOSAL_PR_SENTINEL . length ) . trim ( ) ;
try {
const parsed = JSON . parse ( payload ) as Record < string , unknown > ;
const title = typeof parsed . title === "string" ? parsed . title . trim ( ) : "" ;
const content = typeof parsed . content === "string" ? parsed . content . trim ( ) : "" ;
if ( ! title || ! content ) {
continue ;
}
intents . push ( {
identity : typeof parsed . identity === "string" ? parsed . identity . trim ( ) : undefined ,
title ,
path : typeof parsed . path === "string" ? parsed . path . trim ( ) : undefined ,
content ,
shareContent : typeof parsed . shareContent === "string" ? parsed . shareContent . trim ( ) : undefined ,
channelId : typeof parsed . channelId === "string" ? parsed . channelId . trim ( ) : undefined ,
replyToMessageId :
typeof parsed . replyToMessageId === "string" ? parsed . replyToMessageId . trim ( ) : undefined ,
} ) ;
} catch {
continue ;
}
}
return intents ;
}
function parseRepoIdentityPrCommentIntents ( finalResponse : string ) : RepoIdentityPrCommentIntent [ ] {
const intents : RepoIdentityPrCommentIntent [ ] = [ ] ;
for ( const line of finalResponse . split ( /\r?\n/ ) ) {
const trimmed = line . trim ( ) ;
if ( ! trimmed . startsWith ( REPO_IDENTITY_PR_COMMENT_SENTINEL ) ) {
continue ;
}
const payload = trimmed . slice ( REPO_IDENTITY_PR_COMMENT_SENTINEL . length ) . trim ( ) ;
try {
const parsed = JSON . parse ( payload ) as Record < string , unknown > ;
const pr = typeof parsed . pr === "string" ? parsed . pr . trim ( ) : "" ;
const content = typeof parsed . content === "string" ? parsed . content . trim ( ) : "" ;
if ( ! pr || ! content ) {
continue ;
}
intents . push ( {
identity : typeof parsed . identity === "string" ? parsed . identity . trim ( ) : undefined ,
pr ,
content ,
shareContent : typeof parsed . shareContent === "string" ? parsed . shareContent . trim ( ) : undefined ,
channelId : typeof parsed . channelId === "string" ? parsed . channelId . trim ( ) : undefined ,
replyToMessageId :
typeof parsed . replyToMessageId === "string" ? parsed . replyToMessageId . trim ( ) : undefined ,
} ) ;
} catch {
continue ;
}
}
return intents ;
}
2026-05-19 16:30:51 +01:00
function countRepoIdentityGithubActionIntents ( finalResponse : string ) : number {
let count = 0 ;
for ( const line of finalResponse . split ( /\r?\n/ ) ) {
const trimmed = line . trim ( ) ;
if (
trimmed . startsWith ( REPO_IDENTITY_ARTICLE_SENTINEL ) ||
trimmed . startsWith ( REPO_IDENTITY_PROPOSAL_PR_SENTINEL ) ||
trimmed . startsWith ( REPO_IDENTITY_PR_COMMENT_SENTINEL )
) {
count += 1 ;
}
}
return count ;
}
2026-05-20 21:29:10 +01:00
function renderRepoIdentityUpdateRequestMarkdown (
identity : { id : string ; displayName : string ; repoName : string } ,
intent : RepoIdentityUpdateRequestIntent ,
) : string {
return [
"# Repo Face Update Request" ,
"" ,
` Source Face: ${ identity . displayName } ( ${ identity . id } ) ` ,
` Target repo: ${ identity . repoName } ` ,
"" ,
"## Request" ,
"" ,
intent . content . trim ( ) ,
"" ,
"## Instructions For Codex" ,
"" ,
"Work this request in the target workspace. Prefer a small coherent change, proposal, doc, or test-backed patch. If the request is not actionable enough, write down the smallest missing question instead of silently dropping it." ,
"" ,
] . join ( "\n" ) ;
}
function normalizeBifrostPriority ( value : number | undefined ) : number {
if ( typeof value !== "number" || ! Number . isFinite ( value ) ) {
return 80 ;
}
return Math . max ( 1 , Math . min ( 100 , Math . round ( value ) ) ) ;
}
2026-05-20 21:45:56 +01:00
function normalizeBifrostTopicStance ( value : string | undefined ) : string {
const normalized = value ? . trim ( ) . toLowerCase ( ) ;
return [
"comment" ,
"proposal" ,
"support" ,
"objection" ,
"question" ,
"approval" ,
"summary" ,
"receipt" ,
] . includes ( normalized ? ? "" )
? normalized !
: "comment" ;
}
2026-05-19 12:23:22 +01:00
function resolveRepoRoot ( identity : { repoName : string ; repoPath? : string } ) : string {
if ( identity . repoPath && identity . repoPath . trim ( ) . length > 0 ) {
return resolve ( identity . repoPath ) ;
}
if ( config . sourceRepoRoot ) {
return resolve ( config . sourceRepoRoot , identity . repoName ) ;
}
return resolve ( config . storageRoot , "repo-article-drafts" , identity . repoName ) ;
}
function normalizeArticlePath (
intent : RepoIdentityArticleIntent ,
identity : { displayName : string } ,
) : string {
const path = intent . path ? . trim ( ) ;
if ( path && ! isAbsolute ( path ) && ! path . split ( /[\\/]+/ ) . includes ( ".." ) ) {
return path . replace ( /\\/g , "/" ) ;
}
const date = new Date ( ) . toISOString ( ) . slice ( 0 , 10 ) ;
return ` Aetheria/Articles/ ${ sanitizePathSegment ( identity . displayName ) } / ${ date } - ${ slugify ( intent . title ) } .md ` ;
}
2026-05-19 16:06:26 +01:00
function normalizeProposalPath (
intent : RepoIdentityProposalPrIntent ,
identity : { displayName : string } ,
) : string {
const path = intent . path ? . trim ( ) ;
if ( path && ! isAbsolute ( path ) && ! path . split ( /[\\/]+/ ) . includes ( ".." ) ) {
return path . replace ( /\\/g , "/" ) ;
}
const date = new Date ( ) . toISOString ( ) . slice ( 0 , 10 ) ;
return ` Proposals/ ${ sanitizePathSegment ( identity . displayName ) } / ${ date } - ${ slugify ( intent . title ) } .md ` ;
}
2026-05-18 17:33:02 +01:00
function stripRepoIdentityPostIntents ( finalResponse : string ) : string {
return finalResponse
. split ( /\r?\n/ )
2026-05-19 12:23:22 +01:00
. filter ( ( line ) = > {
const trimmed = line . trim ( ) ;
return (
! trimmed . startsWith ( REPO_IDENTITY_POST_SENTINEL ) &&
2026-05-20 21:45:56 +01:00
! trimmed . startsWith ( REPO_IDENTITY_BIFROST_TOPIC_SENTINEL ) &&
2026-05-20 21:29:10 +01:00
! trimmed . startsWith ( REPO_IDENTITY_UPDATE_REQUEST_SENTINEL ) &&
2026-05-19 16:06:26 +01:00
! trimmed . startsWith ( REPO_IDENTITY_ARTICLE_SENTINEL ) &&
! trimmed . startsWith ( REPO_IDENTITY_PROPOSAL_PR_SENTINEL ) &&
! trimmed . startsWith ( REPO_IDENTITY_PR_COMMENT_SENTINEL )
2026-05-19 12:23:22 +01:00
) ;
} )
2026-05-18 17:33:02 +01:00
. join ( "\n" )
. trim ( ) ;
}
2026-05-19 12:23:22 +01:00
function isPathInside ( rootPath : string , candidatePath : string ) : boolean {
const relativePath = relative ( resolve ( rootPath ) , resolve ( candidatePath ) ) ;
return relativePath === "" || ( ! relativePath . startsWith ( ".." ) && ! isAbsolute ( relativePath ) ) ;
}
function ensureTrailingNewline ( value : string ) : string {
return value . endsWith ( "\n" ) ? value : ` ${ value } \ n ` ;
}
function slugify ( value : string ) : string {
return sanitizePathSegment ( value )
. replace ( /\.+/g , "-" )
. replace ( /-+/g , "-" )
. slice ( 0 , 80 ) || "article" ;
}
function sanitizePathSegment ( value : string ) : string {
return value
. trim ( )
. toLowerCase ( )
. replace ( /[^a-z0-9._-]+/g , "-" )
. replace ( /^-+|-+$/g , "" ) ;
}
2026-05-18 17:33:02 +01:00
async function recordRepoIdentityDeliveryReceipt ( input : {
identity : NonNullable < ReturnType < typeof findRepoDiscordIdentity > > ;
channelId : string ;
content : string ;
replyToMessageId? : string ;
messageId : string ;
transport : "bot" | "webhook" ;
} ) : Promise < void > {
await applyVoidSelfStateOperation (
{
canonicalPath : resolveRepoFaceStatePath ( input . identity , config . storageRoot ) ,
identity : {
agentId : input.identity.id ,
publicName : input.identity.displayName ,
publicDescription : input.identity.description ,
} ,
} ,
{
operation : "record_delivery_receipt" ,
receipt : {
receiptKey : ` repo-identity: ${ input . identity . id } : ${ input . messageId } ` ,
sentAt : new Date ( ) . toISOString ( ) ,
mode : "repo_identity" ,
transport : input.transport ,
channelId : input.channelId ,
replyToMessageId : input.replyToMessageId ,
personaName : input.identity.displayName ,
personaAvatarUrl : input.identity.avatarUrl ,
contentLength : input.content.length ,
chunkCount : 1 ,
preview : input.content.slice ( 0 , 1000 ) ,
} ,
} ,
) ;
2026-05-20 20:31:42 +01:00
try {
await applyRepoFacePostFatigueAfterSpeech ( {
identity : input.identity ,
storageRoot : config.storageRoot ,
heartbeatStatePath : config.repoFaceHeartbeats.statePath ,
} ) ;
} catch ( error ) {
const message = error instanceof Error ? error.message : String ( error ) ;
console . warn ( ` Could not apply repo Face post fatigue for ${ input . identity . id } : ${ message } ` ) ;
}
2026-05-18 14:21:50 +01:00
}
2026-04-24 13:17:00 +01:00
async function postOwnerNotification ( content : string ) : Promise < void > {
if ( ! config . botToken ) {
throw new Error ( "DISCORD_BOT_TOKEN is required for the worker to send owner notifications." ) ;
}
const dmChannelId = await openOwnerDmChannel ( ) ;
const response = await fetch ( ` https://discord.com/api/v10/channels/ ${ dmChannelId } /messages ` , {
method : "POST" ,
headers : {
Authorization : ` Bot ${ config . botToken } ` ,
"Content-Type" : "application/json" ,
} ,
body : JSON.stringify ( {
content : fitDiscordMessage ( content ) ,
allowed_mentions : {
parse : [ ] ,
} ,
} ) ,
} ) ;
if ( ! response . ok ) {
throw new Error ( ` Discord owner notification failed with ${ response . status } : ${ await response . text ( ) } ` ) ;
}
}
async function openOwnerDmChannel ( ) : Promise < string > {
if ( ! config . botToken ) {
throw new Error ( "DISCORD_BOT_TOKEN is required for the worker to open an owner DM." ) ;
}
const response = await fetch ( "https://discord.com/api/v10/users/@me/channels" , {
method : "POST" ,
headers : {
Authorization : ` Bot ${ config . botToken } ` ,
"Content-Type" : "application/json" ,
} ,
body : JSON.stringify ( {
recipient_id : config.ownerDiscordId ,
} ) ,
} ) ;
if ( ! response . ok ) {
throw new Error ( ` Discord DM open failed with ${ response . status } : ${ await response . text ( ) } ` ) ;
}
const payload = ( await response . json ( ) ) as { id? : string } ;
if ( ! payload . id ) {
throw new Error ( "Discord DM open succeeded without returning a channel id." ) ;
}
return payload . id ;
}
function fitDiscordMessage ( content : string ) : string {
const trimmed = content . trim ( ) ;
if ( trimmed . length <= 1900 ) {
return trimmed ;
}
return ` ${ trimmed . slice ( 0 , 1897 ) } ... ` ;
}
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 ,
2026-05-02 20:57:10 +01:00
timeContext : formatTimeContext ( result . metadata . timestamp ) ,
2026-04-24 13:17:00 +01:00
jumpUrl : result.metadata.jumpUrl ,
threadId : result.metadata.threadId ,
} ) ) ;
}
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 ,
} ) ) ;
}
function formatArchivedMessageContext (
message : ArchivedMessageRecord ,
anchorMessageId : string ,
) : Record < string , unknown > {
return {
id : message.id ,
isAnchor : message.id === anchorMessageId ,
timestamp : message.timestamp ,
2026-05-02 20:57:10 +01:00
timeContext : formatTimeContext ( message . timestamp ) ,
2026-04-24 13:17:00 +01:00
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 ,
} ;
}
2026-05-02 20:57:10 +01:00
function formatTimeContext ( timestamp : string | undefined ) : string | undefined {
if ( ! timestamp ) {
return undefined ;
}
const parsed = new Date ( timestamp ) ;
if ( Number . isNaN ( parsed . getTime ( ) ) ) {
return undefined ;
}
const absolute = formatUtcTimestamp ( timestamp ) ;
const now = new Date ( ) ;
const deltaMs = now . getTime ( ) - parsed . getTime ( ) ;
const absDeltaMs = Math . abs ( deltaMs ) ;
const suffix = deltaMs >= 0 ? "ago" : "from now" ;
if ( absDeltaMs < 60 _000 ) {
return ` ${ absolute } (just now) ` ;
}
const minuteMs = 60 _000 ;
const hourMs = 60 * minuteMs ;
const dayMs = 24 * hourMs ;
const yearMs = 365 * dayMs ;
if ( absDeltaMs < hourMs ) {
const minutes = Math . round ( absDeltaMs / minuteMs ) ;
return ` ${ absolute } ( ${ minutes } minute ${ minutes === 1 ? "" : "s" } ${ suffix } ) ` ;
}
if ( absDeltaMs < dayMs ) {
const hours = Math . round ( absDeltaMs / hourMs ) ;
return ` ${ absolute } ( ${ hours } hour ${ hours === 1 ? "" : "s" } ${ suffix } ) ` ;
}
if ( absDeltaMs < yearMs ) {
const days = Math . round ( absDeltaMs / dayMs ) ;
return ` ${ absolute } ( ${ days } day ${ days === 1 ? "" : "s" } ${ suffix } ) ` ;
}
const years = Math . round ( absDeltaMs / yearMs ) ;
return ` ${ absolute } ( ${ years } year ${ years === 1 ? "" : "s" } ${ suffix } ) ` ;
}
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 ` ;
}