import { agentContext, claimTaskThread, releaseTaskThread, resetAgentContextCounts, } from "../utils/agentContext.ts"; import { msFrom, msRandomOffset, msUntilNextWakeWindow, } from "../utils/time.ts"; import { reflectionPrompt } from "../prompts/reflectionPrompt.ts"; import { messageAgent } from "../utils/messageAgent.ts"; export const runReflection = async () => { if (!claimTaskThread()) { const newDelay = msFrom.minutes(2); console.log( `🔹 ${agentContext.agentBskyName} is busy, will try reflecting again in ${ (newDelay / 1000) / 60 } minutes…`, ); // session is busy, try to start reflection in 2 minutes. setTimeout(runReflection, newDelay); return; } if (!agentContext.reflectionEnabled) { console.log( `🔹 Reflection is currently disabled. Provide a minimum and/or maximum delay duration in \`.env\` to enable reflections…`, ); releaseTaskThread(); return; } // adds 2-4 hours to wake time // only applies if sleep is enabled const delay = msUntilNextWakeWindow( msFrom.hours(2), msFrom.hours(4), ); if (delay !== 0) { setTimeout(runReflection, delay); console.log( `🔹 ${agentContext.agentBskyName} is currently asleep. scheduling next reflection for ${ (delay / 1000 / 60 / 60).toFixed(2) } hours from now…`, ); releaseTaskThread(); return; } try { console.log("🔹 starting reflection prompt…"); await messageAgent(reflectionPrompt); } catch (error) { console.error("Error in reflectionCheck:", error); } finally { resetAgentContextCounts(); agentContext.reflectionCount++; console.log( "🔹 finished reflection prompt. returning to checking for notifications…", ); // schedules the next reflection, random between the min and max delay setTimeout( runReflection, msRandomOffset( agentContext.reflectionDelayMinimum, agentContext.reflectionDelayMaximum, ), ); releaseTaskThread(); } };