a tool to help your Letta AI agents navigate bluesky
1import {
2 agentContext,
3 claimTaskThread,
4 releaseTaskThread,
5 resetAgentContextCounts,
6} from "../utils/agentContext.ts";
7import {
8 msFrom,
9 msRandomOffset,
10 msUntilNextWakeWindow,
11} from "../utils/time.ts";
12import { reflectionPrompt } from "../prompts/reflectionPrompt.ts";
13import { messageAgent } from "../utils/messageAgent.ts";
14
15export const runReflection = async () => {
16 if (!claimTaskThread()) {
17 const newDelay = msFrom.minutes(2);
18
19 console.log(
20 `🔹 ${agentContext.agentBskyName} is busy, will try reflecting again in ${
21 (newDelay / 1000) / 60
22 } minutes…`,
23 );
24 // session is busy, try to start reflection in 2 minutes.
25 setTimeout(runReflection, newDelay);
26 return;
27 }
28
29 if (!agentContext.reflectionEnabled) {
30 console.log(
31 `🔹 Reflection is currently disabled. Provide a minimum and/or maximum delay duration in \`.env\` to enable reflections…`,
32 );
33 releaseTaskThread();
34 return;
35 }
36
37 // adds 2-4 hours to wake time
38 // only applies if sleep is enabled
39 const delay = msUntilNextWakeWindow(
40 msFrom.hours(2),
41 msFrom.hours(4),
42 );
43
44 if (delay !== 0) {
45 setTimeout(runReflection, delay);
46 console.log(
47 `🔹 ${agentContext.agentBskyName} is currently asleep. scheduling next reflection for ${
48 (delay / 1000 / 60 / 60).toFixed(2)
49 } hours from now…`,
50 );
51 releaseTaskThread();
52 return;
53 }
54
55 try {
56 console.log("🔹 starting reflection prompt…");
57 await messageAgent(reflectionPrompt);
58 } catch (error) {
59 console.error("Error in reflectionCheck:", error);
60 } finally {
61 resetAgentContextCounts();
62 agentContext.reflectionCount++;
63 console.log(
64 "🔹 finished reflection prompt. returning to checking for notifications…",
65 );
66 // schedules the next reflection, random between the min and max delay
67 setTimeout(
68 runReflection,
69 msRandomOffset(
70 agentContext.reflectionDelayMinimum,
71 agentContext.reflectionDelayMaximum,
72 ),
73 );
74 releaseTaskThread();
75 }
76};