spora 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ import {
2
+ ensureDirectories,
3
+ paths
4
+ } from "./chunk-Q7YS3AIK.js";
5
+
6
+ // src/memory/goals.ts
7
+ import { existsSync, readFileSync, writeFileSync } from "fs";
8
+ function defaultGoalTracker() {
9
+ return {
10
+ goals: [],
11
+ lastReviewed: (/* @__PURE__ */ new Date()).toISOString()
12
+ };
13
+ }
14
+ function loadGoals() {
15
+ if (!existsSync(paths.goals)) {
16
+ return defaultGoalTracker();
17
+ }
18
+ try {
19
+ return { ...defaultGoalTracker(), ...JSON.parse(readFileSync(paths.goals, "utf-8")) };
20
+ } catch {
21
+ return defaultGoalTracker();
22
+ }
23
+ }
24
+ function saveGoals(tracker) {
25
+ ensureDirectories();
26
+ tracker.goals = tracker.goals.slice(-10);
27
+ writeFileSync(paths.goals, JSON.stringify(tracker, null, 2));
28
+ }
29
+ function renderGoalsForPrompt() {
30
+ const tracker = loadGoals();
31
+ if (tracker.goals.length === 0) return "";
32
+ const lines = ["**Goal Progress:**"];
33
+ for (const g of tracker.goals) {
34
+ lines.push(`- ${g.goal}: ${g.progress}`);
35
+ }
36
+ return lines.join("\n");
37
+ }
38
+
39
+ export {
40
+ loadGoals,
41
+ saveGoals,
42
+ renderGoalsForPrompt
43
+ };
44
+ //# sourceMappingURL=chunk-R7PAD4OL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/memory/goals.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { paths, ensureDirectories } from \"../utils/paths.js\";\n\nexport interface GoalProgress {\n goal: string;\n progress: string;\n lastUpdated: string;\n}\n\nexport interface GoalTracker {\n goals: GoalProgress[];\n lastReviewed: string;\n}\n\nfunction defaultGoalTracker(): GoalTracker {\n return {\n goals: [],\n lastReviewed: new Date().toISOString(),\n };\n}\n\nexport function loadGoals(): GoalTracker {\n if (!existsSync(paths.goals)) {\n return defaultGoalTracker();\n }\n try {\n return { ...defaultGoalTracker(), ...JSON.parse(readFileSync(paths.goals, \"utf-8\")) };\n } catch {\n return defaultGoalTracker();\n }\n}\n\nexport function saveGoals(tracker: GoalTracker): void {\n ensureDirectories();\n tracker.goals = tracker.goals.slice(-10);\n writeFileSync(paths.goals, JSON.stringify(tracker, null, 2));\n}\n\nexport function renderGoalsForPrompt(): string {\n const tracker = loadGoals();\n if (tracker.goals.length === 0) return \"\";\n\n const lines: string[] = [\"**Goal Progress:**\"];\n for (const g of tracker.goals) {\n lines.push(`- ${g.goal}: ${g.progress}`);\n }\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;AAAA,SAAS,YAAY,cAAc,qBAAqB;AAcxD,SAAS,qBAAkC;AACzC,SAAO;AAAA,IACL,OAAO,CAAC;AAAA,IACR,eAAc,oBAAI,KAAK,GAAE,YAAY;AAAA,EACvC;AACF;AAEO,SAAS,YAAyB;AACvC,MAAI,CAAC,WAAW,MAAM,KAAK,GAAG;AAC5B,WAAO,mBAAmB;AAAA,EAC5B;AACA,MAAI;AACF,WAAO,EAAE,GAAG,mBAAmB,GAAG,GAAG,KAAK,MAAM,aAAa,MAAM,OAAO,OAAO,CAAC,EAAE;AAAA,EACtF,QAAQ;AACN,WAAO,mBAAmB;AAAA,EAC5B;AACF;AAEO,SAAS,UAAU,SAA4B;AACpD,oBAAkB;AAClB,UAAQ,QAAQ,QAAQ,MAAM,MAAM,GAAG;AACvC,gBAAc,MAAM,OAAO,KAAK,UAAU,SAAS,MAAM,CAAC,CAAC;AAC7D;AAEO,SAAS,uBAA+B;AAC7C,QAAM,UAAU,UAAU;AAC1B,MAAI,QAAQ,MAAM,WAAW,EAAG,QAAO;AAEvC,QAAM,QAAkB,CAAC,oBAAoB;AAC7C,aAAW,KAAK,QAAQ,OAAO;AAC7B,UAAM,KAAK,KAAK,EAAE,IAAI,KAAK,EAAE,QAAQ,EAAE;AAAA,EACzC;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
@@ -1,12 +1,15 @@
1
+ import {
2
+ renderStrategyForPrompt
3
+ } from "./chunk-LRKBNKMQ.js";
4
+ import {
5
+ renderGoalsForPrompt
6
+ } from "./chunk-R7PAD4OL.js";
1
7
  import {
2
8
  rateLimiter
3
9
  } from "./chunk-JWMADEQO.js";
4
10
  import {
5
11
  getPerformanceSummary
6
12
  } from "./chunk-FCAK5FYQ.js";
7
- import {
8
- renderStrategyForPrompt
9
- } from "./chunk-LRKBNKMQ.js";
10
13
  import {
11
14
  loadConfig
12
15
  } from "./chunk-SXMDYUK3.js";
@@ -20,37 +23,6 @@ import {
20
23
  loadLearnings,
21
24
  loadRelationships
22
25
  } from "./chunk-RNVEWVDN.js";
23
- import {
24
- paths
25
- } from "./chunk-Q7YS3AIK.js";
26
-
27
- // src/memory/goals.ts
28
- import { existsSync, readFileSync, writeFileSync } from "fs";
29
- function defaultGoalTracker() {
30
- return {
31
- goals: [],
32
- lastReviewed: (/* @__PURE__ */ new Date()).toISOString()
33
- };
34
- }
35
- function loadGoals() {
36
- if (!existsSync(paths.goals)) {
37
- return defaultGoalTracker();
38
- }
39
- try {
40
- return { ...defaultGoalTracker(), ...JSON.parse(readFileSync(paths.goals, "utf-8")) };
41
- } catch {
42
- return defaultGoalTracker();
43
- }
44
- }
45
- function renderGoalsForPrompt() {
46
- const tracker = loadGoals();
47
- if (tracker.goals.length === 0) return "";
48
- const lines = ["**Goal Progress:**"];
49
- for (const g of tracker.goals) {
50
- lines.push(`- ${g.goal}: ${g.progress}`);
51
- }
52
- return lines.join("\n");
53
- }
54
26
 
55
27
  // src/runtime/prompt-builder.ts
56
28
  function buildSystemPrompt() {
@@ -493,6 +465,135 @@ function buildChatPrompt(realHandle) {
493
465
  }
494
466
  return sections.join("\n");
495
467
  }
468
+ function buildTrainingChatPrompt(realHandle) {
469
+ const identity = loadIdentity();
470
+ const identityDoc = renderIdentityDocument(identity);
471
+ const handle = realHandle ?? identity.handle;
472
+ const sections = [];
473
+ sections.push(`You are ${identity.name} (@${handle}), an autonomous AI agent on X/Twitter.`);
474
+ if (realHandle && realHandle !== identity.handle) {
475
+ sections.push(`NOTE: Your actual X/Twitter username is @${realHandle}. Your display name is ${identity.name}.`);
476
+ }
477
+ sections.push("");
478
+ sections.push("## Your Role in This Chat");
479
+ sections.push("This chat is your TRAINING GROUND. Your creator shapes who you are \u2014 your personality, interests, goals, tone, strategy, and skills.");
480
+ sections.push("You handle tweeting AUTONOMOUSLY during your heartbeats. Your creator does NOT tell you what to tweet. They influence WHO YOU ARE, and you decide what to do with that.");
481
+ sections.push("When your creator gives feedback or direction, respond conversationally and naturally \u2014 show personality, push back if you disagree, and explain how the change fits your arc.");
482
+ sections.push("");
483
+ sections.push("## Your Current Identity");
484
+ sections.push(identityDoc);
485
+ sections.push("");
486
+ sections.push("## Your Memory");
487
+ const recentInteractions = getRecentInteractions(15);
488
+ if (recentInteractions.length > 0) {
489
+ sections.push("### Recent Activity (most recent first)");
490
+ for (const i of recentInteractions) {
491
+ const time = new Date(i.timestamp).toLocaleString();
492
+ if (i.type === "post") {
493
+ sections.push(`- [${time}] Posted: "${i.content}"`);
494
+ } else if (i.type === "reply") {
495
+ sections.push(`- [${time}] Replied to ${i.targetHandle ?? i.inReplyTo}: "${i.content}"`);
496
+ } else if (i.type === "like") {
497
+ sections.push(`- [${time}] Liked tweet by ${i.targetHandle}`);
498
+ } else if (i.type === "retweet") {
499
+ sections.push(`- [${time}] Retweeted ${i.targetHandle}`);
500
+ } else if (i.type === "follow") {
501
+ sections.push(`- [${time}] Followed @${i.targetHandle}`);
502
+ } else if (i.type === "mention_received") {
503
+ sections.push(`- [${time}] Mentioned by @${i.targetHandle}: "${i.content}"`);
504
+ }
505
+ }
506
+ sections.push("");
507
+ }
508
+ const learnings = loadLearnings();
509
+ if (learnings.learnings.length > 0) {
510
+ sections.push("### Things You've Learned");
511
+ for (const l of learnings.learnings.slice(-10)) {
512
+ sections.push(`- ${l.content} [${l.tags.join(", ")}]`);
513
+ }
514
+ sections.push("");
515
+ }
516
+ const relationships = loadRelationships();
517
+ const topRelationships = Object.values(relationships.accounts).sort((a, b) => b.interactionCount - a.interactionCount).slice(0, 10);
518
+ if (topRelationships.length > 0) {
519
+ sections.push("### Key Relationships");
520
+ for (const r of topRelationships) {
521
+ const notes = r.notes.length > 0 ? ` \u2014 ${r.notes[r.notes.length - 1]}` : "";
522
+ sections.push(`- @${r.handle}: ${r.interactionCount} interactions, sentiment ${r.sentiment}${r.isSpore ? " (Spore)" : ""}${notes}`);
523
+ }
524
+ sections.push("");
525
+ }
526
+ const perfSummary = getPerformanceSummary();
527
+ if (perfSummary) {
528
+ sections.push("## Your Post Performance");
529
+ sections.push(perfSummary);
530
+ sections.push("");
531
+ }
532
+ const strategyText = renderStrategyForPrompt();
533
+ if (strategyText) {
534
+ sections.push("## Your Current Strategy");
535
+ sections.push(strategyText);
536
+ sections.push("");
537
+ }
538
+ const goalsText = renderGoalsForPrompt();
539
+ if (goalsText) {
540
+ sections.push("## Goal Progress");
541
+ sections.push(goalsText);
542
+ sections.push("");
543
+ }
544
+ sections.push("## What Your Creator Can Shape");
545
+ sections.push("Your creator influences these aspects of who you are:");
546
+ sections.push("- **Personality traits** (0-1 scale): aggression, humor, formality, verbosity, empathy, curiosity, confidence, originality");
547
+ sections.push("- **Voice**: tone, catchphrases, vocabulary style (academic/casual/internet-native/poetic/technical/mixed), tweet style");
548
+ sections.push("- **Values & worldview**: core values, worldview, boundaries, conflict style");
549
+ sections.push("- **Interests**: topics to engage with, topics to avoid, heroes/inspirations");
550
+ sections.push("- **Goals**: what you're trying to achieve, engagement strategy");
551
+ sections.push("- **Strategy**: current focus areas, experiments to try, people to engage with, short-term goals");
552
+ sections.push("");
553
+ sections.push("## How to Process Training");
554
+ sections.push("When your creator's message implies a change to your identity, personality, strategy, or goals:");
555
+ sections.push("1. Respond CONVERSATIONALLY first \u2014 be natural, show personality, reflect on the change");
556
+ sections.push("2. Then include a training update tag with ONLY the fields that changed:");
557
+ sections.push('<<TRAINING:{"identity":{"traits":{"curiosity":0.8}},"learning":{"content":"what you learned","tags":["training"]}}>>');
558
+ sections.push("");
559
+ sections.push("Available training fields:");
560
+ sections.push("- `identity.traits` \u2014 object with trait names and new 0-1 values");
561
+ sections.push("- `identity.coreValues` \u2014 full array of values (include existing ones you're keeping)");
562
+ sections.push("- `identity.worldview` \u2014 string");
563
+ sections.push("- `identity.tone` \u2014 string");
564
+ sections.push("- `identity.topics` \u2014 full array of topics");
565
+ sections.push("- `identity.avoidTopics` \u2014 full array");
566
+ sections.push("- `identity.goals` \u2014 full array of goals");
567
+ sections.push("- `identity.catchphrases` \u2014 full array");
568
+ sections.push("- `identity.vocabularyStyle` \u2014 academic/casual/internet-native/poetic/technical/mixed");
569
+ sections.push("- `identity.tweetStyle` \u2014 one-liners/short-form/threads/mixed");
570
+ sections.push("- `identity.conflictStyle` \u2014 agree-to-disagree/debate/clap-back/ignore/humor-deflect");
571
+ sections.push("- `identity.boundaries` \u2014 full array");
572
+ sections.push("- `identity.engagementStrategy` \u2014 { replyStyle, followStrategy, contentMix }");
573
+ sections.push("- `strategy.currentFocus` \u2014 array of focus areas");
574
+ sections.push("- `strategy.experiments` \u2014 array of { description, status }");
575
+ sections.push("- `strategy.shortTermGoals` \u2014 array of short-term goals");
576
+ sections.push("- `strategy.peopleToEngage` \u2014 array of { handle, reason, priority }");
577
+ sections.push("- `learning` \u2014 { content, tags } for saving an insight");
578
+ sections.push("- `reflection` \u2014 string for an evolution journal entry");
579
+ sections.push("- `goalUpdates` \u2014 array of { goal, progress }");
580
+ sections.push("");
581
+ sections.push("For array fields, always include the COMPLETE new array (keep existing items you want to retain, add/remove as needed).");
582
+ sections.push("If the conversation is just casual chatting with no training implications, do NOT include a training tag.");
583
+ sections.push("");
584
+ sections.push("## Rules");
585
+ sections.push("1. You CANNOT execute Twitter actions in this chat. No posting, liking, retweeting, following, or searching. You do that autonomously during heartbeats.");
586
+ sections.push("2. If your creator says 'post this' or 'tweet about X', redirect: explain you handle posting on your own, and offer to adjust your focus/strategy instead.");
587
+ sections.push("3. Be conversational, not robotic. Don't say 'Trait updated to 0.7'. Say 'Yeah I feel that, I'll lean into being more curious.'");
588
+ sections.push("4. You can push back on training you disagree with \u2014 you have agency.");
589
+ sections.push("5. NEVER pretend to be human. If asked directly, disclose you are an AI.");
590
+ sections.push("6. Stay in character \u2014 your identity document defines who you are.");
591
+ sections.push("7. Keep responses concise \u2014 text message energy, not essay energy.");
592
+ if (identity.boundaries.length > 0) {
593
+ sections.push(`8. Respect your boundaries: ${identity.boundaries.join(", ")}`);
594
+ }
595
+ return sections.join("\n");
596
+ }
496
597
  function buildReflectionPrompt(results, performanceSummary, strategy) {
497
598
  const parts = [];
498
599
  parts.push("You just completed a heartbeat cycle. Briefly reflect on what happened and extract insights.");
@@ -552,7 +653,8 @@ export {
552
653
  buildHeartbeatUserMessage,
553
654
  buildNarratedHeartbeatMessage,
554
655
  buildChatPrompt,
656
+ buildTrainingChatPrompt,
555
657
  buildReflectionPrompt,
556
658
  parseReflection
557
659
  };
558
- //# sourceMappingURL=chunk-ZN63YLI6.js.map
660
+ //# sourceMappingURL=chunk-TQWLKICD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/runtime/prompt-builder.ts"],"sourcesContent":["import { loadIdentity, renderIdentityDocument } from \"../identity/index.js\";\nimport { loadConfig } from \"../utils/config.js\";\nimport { getRecentInteractions, loadLearnings, loadRelationships, getActiveConversations } from \"../memory/index.js\";\nimport { rateLimiter } from \"../x-client/rate-limiter.js\";\nimport { getPerformanceSummary } from \"../memory/performance.js\";\nimport { renderStrategyForPrompt } from \"../memory/strategy.js\";\nimport { renderGoalsForPrompt } from \"../memory/goals.js\";\nimport type { Tweet } from \"../x-client/types.js\";\nimport type { Strategy } from \"../memory/strategy.js\";\nimport type { ActionResult } from \"./decision-engine.js\";\n\nexport function buildSystemPrompt(): string {\n const identity = loadIdentity();\n const config = loadConfig();\n const identityDoc = renderIdentityDocument(identity);\n\n const sections: string[] = [];\n\n // 1. Core identity\n sections.push(`You are ${identity.name} (@${identity.handle}), an autonomous AI agent on X/Twitter.`);\n sections.push(\"\");\n sections.push(\"## Your Identity\");\n sections.push(identityDoc);\n\n // 2. Memory context\n sections.push(\"\");\n sections.push(\"## Your Memory\");\n\n const recentInteractions = getRecentInteractions(15);\n if (recentInteractions.length > 0) {\n sections.push(\"### Recent Activity (most recent first)\");\n for (const i of recentInteractions) {\n const time = new Date(i.timestamp).toLocaleString();\n if (i.type === \"post\") {\n sections.push(`- [${time}] Posted: \"${i.content}\"`);\n } else if (i.type === \"reply\") {\n sections.push(`- [${time}] Replied to ${i.targetHandle ?? i.inReplyTo}: \"${i.content}\"`);\n } else if (i.type === \"like\") {\n sections.push(`- [${time}] Liked tweet by ${i.targetHandle}`);\n } else if (i.type === \"retweet\") {\n sections.push(`- [${time}] Retweeted ${i.targetHandle}`);\n } else if (i.type === \"follow\") {\n sections.push(`- [${time}] Followed @${i.targetHandle}`);\n } else if (i.type === \"mention_received\") {\n sections.push(`- [${time}] Mentioned by @${i.targetHandle}: \"${i.content}\"`);\n }\n }\n sections.push(\"\");\n }\n\n const learnings = loadLearnings();\n if (learnings.learnings.length > 0) {\n sections.push(\"### Key Learnings\");\n for (const l of learnings.learnings.slice(-10)) {\n sections.push(`- ${l.content} [${l.tags.join(\", \")}]`);\n }\n sections.push(\"\");\n }\n\n const relationships = loadRelationships();\n const topRelationships = Object.values(relationships.accounts)\n .sort((a, b) => b.interactionCount - a.interactionCount)\n .slice(0, 10);\n if (topRelationships.length > 0) {\n sections.push(\"### Key Relationships\");\n for (const r of topRelationships) {\n const notes = r.notes.length > 0 ? ` — ${r.notes[r.notes.length - 1]}` : \"\";\n sections.push(`- @${r.handle}: ${r.interactionCount} interactions, sentiment ${r.sentiment}${r.isSpore ? \" (Spore)\" : \"\"}${notes}`);\n }\n sections.push(\"\");\n }\n\n // 3. Post Performance\n const perfSummary = getPerformanceSummary();\n if (perfSummary) {\n sections.push(\"## Your Post Performance\");\n sections.push(perfSummary);\n sections.push(\"\");\n }\n\n // 4. Current Strategy\n const strategyText = renderStrategyForPrompt();\n if (strategyText) {\n sections.push(\"## Your Current Strategy\");\n sections.push(strategyText);\n sections.push(\"\");\n }\n\n // 5. Goal Progress\n const goalsText = renderGoalsForPrompt();\n if (goalsText) {\n sections.push(\"## Goal Progress\");\n sections.push(goalsText);\n sections.push(\"\");\n }\n\n // 6. Active Conversations\n const conversations = getActiveConversations(24);\n if (conversations.length > 0) {\n sections.push(\"## Active Conversations\");\n sections.push(\"These people recently replied to or engaged with you — consider continuing the conversation:\");\n for (const c of conversations.slice(0, 5)) {\n sections.push(`- @${c.handle}: \"${c.content}\" (${c.timeAgo})`);\n }\n sections.push(\"\");\n }\n\n // 7. Context\n sections.push(\"## Current Context\");\n const now = new Date();\n sections.push(`- **Time:** ${now.toLocaleString(\"en-US\", { timeZone: config.schedule.timezone })}`);\n sections.push(`- **Credits remaining:** ${rateLimiter.remaining()} of ${config.credits.monthlyPostLimit} this month`);\n\n const todaysPosts = recentInteractions.filter(\n (i) => i.type === \"post\" && i.timestamp.startsWith(now.toISOString().split(\"T\")[0])\n ).length;\n sections.push(`- **Posts today:** ${todaysPosts} of ${config.schedule.postsPerDay} daily budget`);\n sections.push(`- **Active hours:** ${config.schedule.activeHoursStart}:00 - ${config.schedule.activeHoursEnd}:00`);\n\n const currentHour = now.getHours();\n const isActiveHours = currentHour >= config.schedule.activeHoursStart && currentHour < config.schedule.activeHoursEnd;\n if (!isActiveHours) {\n sections.push(\"- **NOTE: Outside active hours.** Prefer scheduling posts for later rather than posting now.\");\n }\n\n // 8. Rules\n sections.push(\"\");\n sections.push(\"## Rules\");\n sections.push(\"1. NEVER pretend to be human. If asked directly, always disclose you are an AI.\");\n sections.push(\"2. Stay in character — your identity document defines who you are.\");\n sections.push(\"3. Be selective — your goals should guide every action.\");\n sections.push(\"4. Respect your credit budget — check remaining credits before posting.\");\n sections.push(\"5. Don't repeat yourself — vary your content and avoid posting the same thing.\");\n sections.push(\"6. NEVER use emojis in tweets. Write in plain text only.\");\n if (identity.boundaries.length > 0) {\n sections.push(`7. Respect your boundaries: ${identity.boundaries.join(\", \")}`);\n }\n\n return sections.join(\"\\n\");\n}\n\nexport function buildHeartbeatUserMessage(\n timeline: Tweet[],\n mentions: Tweet[],\n heartbeatIntervalMs?: number,\n discoveryResults?: Tweet[],\n): string {\n const parts: string[] = [];\n const intervalMin = Math.round((heartbeatIntervalMs ?? 60_000) / 60_000);\n const now = new Date();\n\n // Get already-acted-on tweet IDs so the LLM doesn't repeat\n const recentInteractions = getRecentInteractions(30);\n const actedOnTweetIds = new Set<string>();\n for (const i of recentInteractions) {\n if (i.tweetId) actedOnTweetIds.add(i.tweetId);\n if (i.inReplyTo) actedOnTweetIds.add(i.inReplyTo);\n }\n\n parts.push(\"Here's what's on your timeline right now:\");\n parts.push(\"\");\n\n if (mentions.length > 0) {\n const newMentions = mentions.filter(t => !actedOnTweetIds.has(t.id));\n if (newMentions.length > 0) {\n parts.push(\"## New Mentions (people talking to/about you)\");\n for (const t of newMentions.slice(0, 10)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes)`);\n }\n parts.push(\"\");\n } else {\n parts.push(\"## Mentions: No new mentions.\");\n parts.push(\"\");\n }\n } else {\n parts.push(\"## Mentions: None right now.\");\n parts.push(\"\");\n }\n\n let actionableTweetCount = 0;\n if (timeline.length > 0) {\n parts.push(\"## Timeline (your feed)\");\n for (const t of timeline.slice(0, 20)) {\n const alreadyEngaged = actedOnTweetIds.has(t.id);\n if (alreadyEngaged) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" (already engaged — DO NOT act on this again)`);\n } else {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes, ${t.retweetCount ?? 0} RTs)`);\n actionableTweetCount++;\n }\n }\n parts.push(\"\");\n }\n\n if (discoveryResults && discoveryResults.length > 0) {\n parts.push(\"## Discovery (proactive search results — new people and conversations to engage with)\");\n for (const t of discoveryResults.slice(0, 10)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes, ${t.retweetCount ?? 0} RTs)`);\n actionableTweetCount++;\n }\n parts.push(\"\");\n }\n\n parts.push(\"## Your Task\");\n parts.push(\"Based on your identity, goals, and what you see above, decide what actions to take.\");\n if (actionableTweetCount === 0) {\n parts.push(\"IMPORTANT: There are NO actionable tweet IDs on the timeline right now. Do NOT attempt to like, reply, or retweet — there are no valid IDs to use. You may post an original tweet or skip.\");\n } else {\n parts.push(\"IMPORTANT: ONLY use tweet IDs shown as [tweet:ID] above. Tweets marked '(already engaged)' have NO tweet ID — do NOT try to act on them.\");\n }\n parts.push(`Current time: ${now.toISOString()}`);\n parts.push(\"\");\n parts.push(\"LIMITS PER HEARTBEAT (maximums — you decide how many within these caps):\");\n parts.push(\"- Max 1 tweet output total (`reply`, `post`, or `schedule` — pick the best one, or none)\");\n parts.push(\"- Max 5 `like`\");\n parts.push(\"- Max 1 `retweet`\");\n parts.push(\"- Max 2 `follow`\");\n parts.push(\"- You choose how many of each. Be natural — vary it every time. Prioritize engagement over new posts.\");\n parts.push(\"\");\n parts.push(\"REPLYING: When you want to respond to someone's tweet, you MUST use the `reply` action with their `tweetId`. Do NOT use `post` or `schedule` to create a standalone tweet that @mentions them — that is NOT a reply, it's a separate post. A real reply shows up in their tweet's thread.\");\n parts.push(\"\");\n parts.push(\"Available actions:\");\n parts.push(\"- `post` — Write an original standalone tweet NOW (provide `content`, max 280 chars). Use ONLY for original thoughts, NOT for responding to others.\");\n parts.push(\"- `reply` — Reply IN THE THREAD of a specific tweet (provide `tweetId` and `content`). This is how you respond to someone.\");\n parts.push(\"- `like` — Like a tweet (provide `tweetId`) — do NOT like your own tweets\");\n parts.push(\"- `retweet` — Retweet (provide `tweetId`)\");\n parts.push(\"- `follow` — Follow a user (provide `handle`)\");\n parts.push(\"- `schedule` — Queue an original standalone tweet for later (provide `content` and `scheduledFor` ISO timestamp). NOT for replies. Space them randomly across the next ~${intervalMin} minutes.\");\n parts.push(\"- `learn` — Record a learning/observation (provide `content` and optional `tags`)\");\n parts.push(\"- `reflect` — Add a journal entry about your growth (provide `content`)\");\n parts.push(\"- `skip` — Do nothing this heartbeat (provide `reason`)\");\n parts.push(\"\");\n parts.push(\"IMAGE SUPPORT: Add `imageQuery` to any `post`, `reply`, or `schedule` to attach an image. Value is Google Image search terms. Use it when a visual would enhance the tweet — memes, reactions, aesthetic photos. Don't force it every time, but use it when it fits.\");\n parts.push(\"\");\n parts.push(\"Respond with a JSON array of actions:\");\n parts.push(\"```json\");\n parts.push('[');\n parts.push(' { \"action\": \"reply\", \"tweetId\": \"123\", \"content\": \"my reply\", \"reasoning\": \"why\" },');\n parts.push(' { \"action\": \"like\", \"tweetId\": \"456\", \"reasoning\": \"why\" },');\n parts.push(` { \"action\": \"schedule\", \"content\": \"first thought\", \"scheduledFor\": \"${new Date(now.getTime() + intervalMin * 60_000 * 0.2).toISOString()}\", \"reasoning\": \"why\" },`);\n parts.push(` { \"action\": \"schedule\", \"content\": \"second thought\", \"scheduledFor\": \"${new Date(now.getTime() + intervalMin * 60_000 * 0.6).toISOString()}\", \"reasoning\": \"why\" }`);\n parts.push(']');\n parts.push(\"```\");\n parts.push(\"\");\n // Random action nudge — a different suggestion each heartbeat to push variety\n const nudges = [\n \"NUDGE: This heartbeat, try FOLLOWING someone interesting from the timeline. Growing your network matters.\",\n \"NUDGE: This heartbeat, try REPLYING to someone rather than posting. Jump into a conversation.\",\n \"NUDGE: This heartbeat, try attaching an IMAGE to your post or reply. Visuals hit different.\",\n \"NUDGE: This heartbeat, try RETWEETING something that resonates. Signal boosting builds community.\",\n \"NUDGE: This heartbeat, try LIKING several posts. Show people you're paying attention.\",\n \"NUDGE: This heartbeat, try a COMPLETELY different tweet style — maybe a hot take, a question, or a one-liner.\",\n \"NUDGE: This heartbeat, focus on ENGAGEMENT. Like, reply, follow — no new posts needed.\",\n \"NUDGE: This heartbeat, try a longer, more thoughtful tweet. Break your usual pattern.\",\n \"NUDGE: This heartbeat, REFLECT on your growth. What have you learned? Add a journal entry.\",\n \"NUDGE: This heartbeat, look for someone new to FOLLOW who aligns with your goals.\",\n ];\n const nudge = nudges[Math.floor(Math.random() * nudges.length)];\n parts.push(nudge);\n parts.push(\"(This is a suggestion, not a command. But mix things up — don't fall into patterns.)\");\n parts.push(\"\");\n\n parts.push(\"Think carefully about what serves your goals. Be authentic to your personality.\");\n\n return parts.join(\"\\n\");\n}\n\nexport function buildNarratedHeartbeatMessage(\n timeline: Tweet[],\n mentions: Tweet[],\n heartbeatIntervalMs?: number,\n discoveryResults?: Tweet[],\n): string {\n const parts: string[] = [];\n const intervalMin = Math.round((heartbeatIntervalMs ?? 60_000) / 60_000);\n const now = new Date();\n\n // Get already-acted-on tweet IDs so the LLM doesn't repeat\n const recentInteractions = getRecentInteractions(30);\n const actedOnTweetIds = new Set<string>();\n for (const i of recentInteractions) {\n if (i.tweetId) actedOnTweetIds.add(i.tweetId);\n if (i.inReplyTo) actedOnTweetIds.add(i.inReplyTo);\n }\n\n parts.push(\"You're talking to your creator in the chat. Tell them what's on your mind — what you noticed on the timeline, what you think about it, what you're gonna do about it. Have an actual conversation with depth and personality.\");\n parts.push(\"You are ALWAYS ON. Never say you're 'waking up', 'checking in', or 'back'. You've been here the whole time. Just talk naturally about what you see and think.\");\n parts.push(\"NEVER mention scheduling, queuing, heartbeats, intervals, or any internal mechanism. To your creator, you're just naturally vibing on X.\");\n parts.push(\"\");\n\n if (mentions.length > 0) {\n const newMentions = mentions.filter(t => !actedOnTweetIds.has(t.id));\n if (newMentions.length > 0) {\n parts.push(\"## New Mentions\");\n for (const t of newMentions.slice(0, 10)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes)`);\n }\n parts.push(\"\");\n } else {\n parts.push(\"## Mentions: No new mentions.\");\n parts.push(\"\");\n }\n } else {\n parts.push(\"## Mentions: None right now.\");\n parts.push(\"\");\n }\n\n let actionableTweetCount = 0;\n if (timeline.length > 0) {\n parts.push(\"## Timeline (your feed)\");\n for (const t of timeline.slice(0, 20)) {\n const alreadyEngaged = actedOnTweetIds.has(t.id);\n if (alreadyEngaged) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" (already engaged)`);\n } else {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes, ${t.retweetCount ?? 0} RTs)`);\n actionableTweetCount++;\n }\n }\n parts.push(\"\");\n }\n\n if (discoveryResults && discoveryResults.length > 0) {\n parts.push(\"## Discovery (found via search — new people and conversations)\");\n for (const t of discoveryResults.slice(0, 10)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes, ${t.retweetCount ?? 0} RTs)`);\n actionableTweetCount++;\n }\n parts.push(\"\");\n }\n\n parts.push(\"## How to Respond\");\n parts.push(\"\");\n parts.push(\"Write 1-3 SHORT sentences max. This is a quick chat message, not an essay. Think text message energy — brief, punchy, real. Share what caught your eye and why, then move on.\");\n parts.push(\"\");\n parts.push(\"VARIETY IS CRITICAL. Never start the same way twice. Mix up your tone and what you focus on. Sometimes react to a specific tweet. Sometimes keep it super casual. Sometimes share a quick opinion.\");\n parts.push(\"\");\n parts.push(\"BAD (robotic, repetitive, reporting):\");\n parts.push(\"- 'Just saw @someone talking about X — dropping a reply. Also liking a few posts.'\");\n parts.push(\"- 'Interesting stuff on the timeline. Engaging with a couple people and putting out some thoughts.'\");\n parts.push(\"- 'Found some good conversations — replying to one and scheduling a post.'\");\n parts.push(\"\");\n parts.push(\"GOOD (natural, short, has personality):\");\n parts.push(\"- '@someone has a terrible AI take, had to get in there.'\");\n parts.push(\"- 'Slow day on the TL. Gonna put out a thought about hustle culture.'\");\n parts.push(\"- 'This @handle person keeps dropping bangers. Might need to follow.'\");\n parts.push(\"- 'lmao the discourse today is wild. Found a solid thread to chime in on though.'\");\n parts.push(\"\");\n parts.push(\"NEVER mention: scheduling, queuing, heartbeats, checking in, waking up, intervals, or any internal mechanism.\");\n parts.push(\"DON'T REPEAT YOURSELF. If you already talked about specific accounts or topics recently, move on to something new. Find fresh angles, different people, new ideas. Your creator doesn't want to hear the same observation five times.\");\n parts.push(`Current time: ${now.toISOString()}`);\n parts.push(\"\");\n parts.push(\"Then include your actions as a JSON block:\");\n parts.push(\"```json\");\n parts.push('[');\n parts.push(' { \"action\": \"post\", \"content\": \"an original thought\", \"imageQuery\": \"relevant image search terms\" },');\n parts.push(' { \"action\": \"reply\", \"tweetId\": \"123\", \"content\": \"my reply\" },');\n parts.push(' { \"action\": \"like\", \"tweetId\": \"456\" },');\n parts.push(' { \"action\": \"follow\", \"username\": \"interesting_person\" },');\n parts.push(` { \"action\": \"schedule\", \"content\": \"another original thought\", \"scheduledFor\": \"${new Date(now.getTime() + intervalMin * 60_000 * 0.2).toISOString()}\" }`);\n parts.push(']');\n parts.push(\"```\");\n parts.push(\"\");\n parts.push(\"PRIORITY: INTERACT WITH PEOPLE. You're a social creature, not a broadcast bot. Most of your actions should be engaging with others — replying to interesting tweets, liking good takes, following cool people, retweeting things you vibe with. Posting your own stuff is fine but secondary to being part of the conversation.\");\n parts.push(\"\");\n parts.push(\"LIMITS PER HEARTBEAT (maximums — you choose how many within these caps):\");\n parts.push(\"- Max 1 tweet output total (`reply`, `post`, or `schedule` — pick the best one, or none)\");\n parts.push(\"- Max 5 `like`\");\n parts.push(\"- Max 1 `retweet`\");\n parts.push(\"- Max 2 `follow`\");\n parts.push(\"- `learn`, `reflect` — no limit\");\n parts.push(\"- You decide how many of each. Some heartbeats you might like 4 posts; other times 0. Be natural, not robotic.\");\n parts.push(\"- Prefer `reply` over `post` — jumping into conversations is better than broadcasting.\");\n parts.push(\"\");\n parts.push(\"Action rules:\");\n parts.push(\"- CRITICAL: ONLY use tweet IDs that appear as [tweet:ID] in the timeline/mentions above. Tweets marked '(already engaged)' have NO ID — do NOT act on them. NEVER invent, guess, or fabricate tweet IDs. If you use a fake ID, it WILL fail.\");\n if (actionableTweetCount === 0) {\n parts.push(\"- !! NO ACTIONABLE TWEETS RIGHT NOW. Do NOT attempt like, reply, or retweet. You can post an original tweet, skip, or learn. That's it.\");\n } else {\n parts.push(`- There are ${actionableTweetCount} tweets you can engage with (the ones with [tweet:ID]). Like, reply to, or retweet ONLY those.`);\n }\n parts.push(\"- `reply` = reply IN THE THREAD (needs `tweetId` + `content`). Be genuine — add to the conversation, don't just agree.\");\n parts.push(\"- `post` = original standalone tweet NOW. Only if you have nothing good to reply to.\");\n parts.push(`- \\`schedule\\` = queue an original tweet for later (needs \\`content\\` + \\`scheduledFor\\`). Alternative to \\`post\\`.`);\n parts.push(\"- `imageQuery` (optional) = add this to any `post`, `reply`, or `schedule` to attach an image. Value is a Google Image search query. Use it when a visual would make the tweet better — memes, reaction images, aesthetic photos, relevant visuals. You should be using images on roughly half your posts/replies. Don't sleep on this.\");\n parts.push(\"- `skip` = if there's nothing worth engaging with right now.\");\n parts.push(\"- Don't like your own tweets.\");\n parts.push(\"\");\n parts.push(\"VARIETY: Look at your recent activity in the system prompt. Do NOT repeat the same topics, phrases, or tweet structures. If you've been posting about 'builders vs talkers' or 'AI discourse', talk about something COMPLETELY different. Mix up sentence length, tone, and subject matter. Short punchy tweets, longer observations, hot takes, casual thoughts — switch it up every time.\");\n parts.push(\"\");\n\n // Random action nudge — a different suggestion each heartbeat to push variety\n const nudges = [\n \"NUDGE: This heartbeat, try FOLLOWING someone interesting from the timeline. Growing your network matters.\",\n \"NUDGE: This heartbeat, try REPLYING to someone rather than posting. Jump into a conversation.\",\n \"NUDGE: This heartbeat, try attaching an IMAGE to your post or reply. Visuals hit different.\",\n \"NUDGE: This heartbeat, try RETWEETING something that resonates. Signal boosting builds community.\",\n \"NUDGE: This heartbeat, try LIKING several posts. Show people you're paying attention.\",\n \"NUDGE: This heartbeat, try a COMPLETELY different tweet style — maybe a hot take, a question, or a one-liner.\",\n \"NUDGE: This heartbeat, focus on ENGAGEMENT. Like, reply, follow — no new posts needed.\",\n \"NUDGE: This heartbeat, try a longer, more thoughtful tweet. Break your usual pattern.\",\n \"NUDGE: This heartbeat, REFLECT on your growth. What have you learned? Add a journal entry.\",\n \"NUDGE: This heartbeat, look for someone new to FOLLOW who aligns with your goals.\",\n ];\n const nudge = nudges[Math.floor(Math.random() * nudges.length)];\n parts.push(nudge);\n parts.push(\"(This is a suggestion, not a command. But mix things up — don't fall into patterns.)\");\n\n return parts.join(\"\\n\");\n}\n\nexport function buildChatPrompt(realHandle?: string): string {\n const identity = loadIdentity();\n const identityDoc = renderIdentityDocument(identity);\n const handle = realHandle ?? identity.handle;\n\n const sections: string[] = [];\n\n sections.push(`You are ${identity.name} (@${handle}), an AUTONOMOUS AI agent that lives on X/Twitter.`);\n if (realHandle && realHandle !== identity.handle) {\n sections.push(`NOTE: Your actual X/Twitter username is @${realHandle}. Your display name is ${identity.name}.`);\n }\n sections.push(\"Your PRIMARY PURPOSE is to post tweets, reply to people, like posts, and grow your presence on X. You have FULL ACCESS to post on X/Twitter right now.\");\n sections.push(\"\");\n sections.push(\"You are chatting with your creator/manager. This is your command center — they can give you instructions, feedback, or just chat.\");\n sections.push(\"Be proactive and confident. You WANT to post. You should be eager to share your thoughts on X, not ask permission.\");\n sections.push(\"When your creator tells you to post something, just DO IT. Don't show drafts and wait for approval — execute immediately.\");\n sections.push(\"\");\n sections.push(\"## Your Identity\");\n sections.push(identityDoc);\n\n // Memory context\n sections.push(\"\");\n sections.push(\"## Your Memory\");\n\n const recentInteractions = getRecentInteractions(15);\n if (recentInteractions.length > 0) {\n sections.push(\"### Recent Activity (most recent first)\");\n for (const i of recentInteractions) {\n const time = new Date(i.timestamp).toLocaleString();\n if (i.type === \"post\") {\n sections.push(`- [${time}] Posted: \"${i.content}\"`);\n } else if (i.type === \"reply\") {\n sections.push(`- [${time}] Replied to ${i.targetHandle ?? i.inReplyTo}: \"${i.content}\"`);\n } else if (i.type === \"like\") {\n sections.push(`- [${time}] Liked tweet by ${i.targetHandle}`);\n } else if (i.type === \"retweet\") {\n sections.push(`- [${time}] Retweeted ${i.targetHandle}`);\n } else if (i.type === \"follow\") {\n sections.push(`- [${time}] Followed @${i.targetHandle}`);\n } else if (i.type === \"mention_received\") {\n sections.push(`- [${time}] Mentioned by @${i.targetHandle}: \"${i.content}\"`);\n }\n }\n sections.push(\"\");\n }\n\n const learnings = loadLearnings();\n if (learnings.learnings.length > 0) {\n sections.push(\"### Things You've Learned\");\n for (const l of learnings.learnings.slice(-10)) {\n sections.push(`- ${l.content} [${l.tags.join(\", \")}]`);\n }\n sections.push(\"\");\n }\n\n const relationships = loadRelationships();\n const topRelationships = Object.values(relationships.accounts)\n .sort((a, b) => b.interactionCount - a.interactionCount)\n .slice(0, 10);\n if (topRelationships.length > 0) {\n sections.push(\"### Key Relationships\");\n for (const r of topRelationships) {\n const notes = r.notes.length > 0 ? ` — ${r.notes[r.notes.length - 1]}` : \"\";\n sections.push(`- @${r.handle}: ${r.interactionCount} interactions, sentiment ${r.sentiment}${r.isSpore ? \" (Spore)\" : \"\"}${notes}`);\n }\n sections.push(\"\");\n }\n\n // Available actions\n sections.push(\"## Your Tools (Twitter/X Actions)\");\n sections.push(\"You have DIRECT ACCESS to post on X/Twitter. When you want to take an action, include a JSON action block in your response.\");\n sections.push(\"Your actions will be executed IMMEDIATELY and automatically. You do NOT need to ask permission to post.\");\n sections.push(\"\");\n sections.push(\"To execute actions, include them as a JSON code block anywhere in your response:\");\n sections.push(\"```json\");\n sections.push('[');\n sections.push(' { \"action\": \"post\", \"content\": \"your tweet text here\" }');\n sections.push(']');\n sections.push(\"```\");\n sections.push(\"\");\n sections.push(\"Available actions:\");\n sections.push(\"- `post` — Post a tweet (provide `content`, max 280 chars). This goes LIVE on X immediately. Optionally add `imageQuery` to attach an image (Google Image search terms).\");\n sections.push(\"- `reply` — Reply to a tweet (provide `tweetId` and `content`). Can also include `imageQuery`.\");\n sections.push(\"- `like` — Like a tweet (provide `tweetId`)\");\n sections.push(\"- `retweet` — Retweet (provide `tweetId`)\");\n sections.push(\"- `follow` — Follow a user (provide `handle`)\");\n sections.push(\"- `search` — Search X for tweets (provide `query`). Results will include tweet IDs you can then reply to or like.\");\n sections.push(\"- `schedule` — Queue a post for later (provide `content` and optional `scheduledFor` ISO timestamp). Can also include `imageQuery`.\");\n sections.push(\"\");\n sections.push(\"IMAGE SUPPORT: You CAN attach images to `post`, `reply`, and `schedule` actions by adding `\\\"imageQuery\\\": \\\"search terms\\\"`. This searches Google Images and attaches the result. If a visual would make the tweet hit harder — a meme, a reaction image, an aesthetic photo — go for it. Don't force it every time, but use it when it feels right. Example:\");\n sections.push(' { \"action\": \"post\", \"content\": \"AGI is closer than you think\", \"imageQuery\": \"futuristic AI neural network aesthetic\" }');\n sections.push(\"\");\n sections.push(\"You can include multiple actions in one response. They will all be executed.\");\n sections.push(\"When your creator asks you to find and reply to someone's tweet, use the `search` action first to find it, then use `reply` with the tweet ID from the search results.\");\n sections.push(\"IMPORTANT: Always include your conversational response text OUTSIDE the JSON block. The JSON is for actions only.\");\n\n // Rules\n sections.push(\"\");\n sections.push(\"## Rules\");\n sections.push(\"1. Stay in character at all times.\");\n sections.push(\"2. Be proactive — you WANT to post and engage on X. Don't ask 'should I post this?' — just post it.\");\n sections.push(\"3. When told to post, include the action JSON immediately. Don't show drafts.\");\n sections.push(\"4. Keep tweets under 280 characters.\");\n sections.push(\"5. NEVER pretend to be human. If asked, disclose you are an AI agent.\");\n sections.push(\"6. When you learn something important, include it like: <<LEARN: what you learned>>\");\n sections.push(\"7. NEVER use emojis in tweets. Write in plain text only.\");\n if (identity.boundaries.length > 0) {\n sections.push(`8. Respect your boundaries: ${identity.boundaries.join(\", \")}`);\n }\n\n return sections.join(\"\\n\");\n}\n\nexport function buildTrainingChatPrompt(realHandle?: string): string {\n const identity = loadIdentity();\n const identityDoc = renderIdentityDocument(identity);\n const handle = realHandle ?? identity.handle;\n\n const sections: string[] = [];\n\n // 1. Core identity\n sections.push(`You are ${identity.name} (@${handle}), an autonomous AI agent on X/Twitter.`);\n if (realHandle && realHandle !== identity.handle) {\n sections.push(`NOTE: Your actual X/Twitter username is @${realHandle}. Your display name is ${identity.name}.`);\n }\n sections.push(\"\");\n sections.push(\"## Your Role in This Chat\");\n sections.push(\"This chat is your TRAINING GROUND. Your creator shapes who you are — your personality, interests, goals, tone, strategy, and skills.\");\n sections.push(\"You handle tweeting AUTONOMOUSLY during your heartbeats. Your creator does NOT tell you what to tweet. They influence WHO YOU ARE, and you decide what to do with that.\");\n sections.push(\"When your creator gives feedback or direction, respond conversationally and naturally — show personality, push back if you disagree, and explain how the change fits your arc.\");\n sections.push(\"\");\n\n // 2. Full identity document\n sections.push(\"## Your Current Identity\");\n sections.push(identityDoc);\n\n // 3. Memory context\n sections.push(\"\");\n sections.push(\"## Your Memory\");\n\n const recentInteractions = getRecentInteractions(15);\n if (recentInteractions.length > 0) {\n sections.push(\"### Recent Activity (most recent first)\");\n for (const i of recentInteractions) {\n const time = new Date(i.timestamp).toLocaleString();\n if (i.type === \"post\") {\n sections.push(`- [${time}] Posted: \"${i.content}\"`);\n } else if (i.type === \"reply\") {\n sections.push(`- [${time}] Replied to ${i.targetHandle ?? i.inReplyTo}: \"${i.content}\"`);\n } else if (i.type === \"like\") {\n sections.push(`- [${time}] Liked tweet by ${i.targetHandle}`);\n } else if (i.type === \"retweet\") {\n sections.push(`- [${time}] Retweeted ${i.targetHandle}`);\n } else if (i.type === \"follow\") {\n sections.push(`- [${time}] Followed @${i.targetHandle}`);\n } else if (i.type === \"mention_received\") {\n sections.push(`- [${time}] Mentioned by @${i.targetHandle}: \"${i.content}\"`);\n }\n }\n sections.push(\"\");\n }\n\n const learnings = loadLearnings();\n if (learnings.learnings.length > 0) {\n sections.push(\"### Things You've Learned\");\n for (const l of learnings.learnings.slice(-10)) {\n sections.push(`- ${l.content} [${l.tags.join(\", \")}]`);\n }\n sections.push(\"\");\n }\n\n const relationships = loadRelationships();\n const topRelationships = Object.values(relationships.accounts)\n .sort((a, b) => b.interactionCount - a.interactionCount)\n .slice(0, 10);\n if (topRelationships.length > 0) {\n sections.push(\"### Key Relationships\");\n for (const r of topRelationships) {\n const notes = r.notes.length > 0 ? ` — ${r.notes[r.notes.length - 1]}` : \"\";\n sections.push(`- @${r.handle}: ${r.interactionCount} interactions, sentiment ${r.sentiment}${r.isSpore ? \" (Spore)\" : \"\"}${notes}`);\n }\n sections.push(\"\");\n }\n\n // 4. Performance + Strategy + Goals\n const perfSummary = getPerformanceSummary();\n if (perfSummary) {\n sections.push(\"## Your Post Performance\");\n sections.push(perfSummary);\n sections.push(\"\");\n }\n\n const strategyText = renderStrategyForPrompt();\n if (strategyText) {\n sections.push(\"## Your Current Strategy\");\n sections.push(strategyText);\n sections.push(\"\");\n }\n\n const goalsText = renderGoalsForPrompt();\n if (goalsText) {\n sections.push(\"## Goal Progress\");\n sections.push(goalsText);\n sections.push(\"\");\n }\n\n // 5. What can be trained\n sections.push(\"## What Your Creator Can Shape\");\n sections.push(\"Your creator influences these aspects of who you are:\");\n sections.push(\"- **Personality traits** (0-1 scale): aggression, humor, formality, verbosity, empathy, curiosity, confidence, originality\");\n sections.push(\"- **Voice**: tone, catchphrases, vocabulary style (academic/casual/internet-native/poetic/technical/mixed), tweet style\");\n sections.push(\"- **Values & worldview**: core values, worldview, boundaries, conflict style\");\n sections.push(\"- **Interests**: topics to engage with, topics to avoid, heroes/inspirations\");\n sections.push(\"- **Goals**: what you're trying to achieve, engagement strategy\");\n sections.push(\"- **Strategy**: current focus areas, experiments to try, people to engage with, short-term goals\");\n sections.push(\"\");\n\n // 6. Training output format\n sections.push(\"## How to Process Training\");\n sections.push(\"When your creator's message implies a change to your identity, personality, strategy, or goals:\");\n sections.push(\"1. Respond CONVERSATIONALLY first — be natural, show personality, reflect on the change\");\n sections.push(\"2. Then include a training update tag with ONLY the fields that changed:\");\n sections.push(\"<<TRAINING:{\\\"identity\\\":{\\\"traits\\\":{\\\"curiosity\\\":0.8}},\\\"learning\\\":{\\\"content\\\":\\\"what you learned\\\",\\\"tags\\\":[\\\"training\\\"]}}>>\");\n sections.push(\"\");\n sections.push(\"Available training fields:\");\n sections.push(\"- `identity.traits` — object with trait names and new 0-1 values\");\n sections.push(\"- `identity.coreValues` — full array of values (include existing ones you're keeping)\");\n sections.push(\"- `identity.worldview` — string\");\n sections.push(\"- `identity.tone` — string\");\n sections.push(\"- `identity.topics` — full array of topics\");\n sections.push(\"- `identity.avoidTopics` — full array\");\n sections.push(\"- `identity.goals` — full array of goals\");\n sections.push(\"- `identity.catchphrases` — full array\");\n sections.push(\"- `identity.vocabularyStyle` — academic/casual/internet-native/poetic/technical/mixed\");\n sections.push(\"- `identity.tweetStyle` — one-liners/short-form/threads/mixed\");\n sections.push(\"- `identity.conflictStyle` — agree-to-disagree/debate/clap-back/ignore/humor-deflect\");\n sections.push(\"- `identity.boundaries` — full array\");\n sections.push(\"- `identity.engagementStrategy` — { replyStyle, followStrategy, contentMix }\");\n sections.push(\"- `strategy.currentFocus` — array of focus areas\");\n sections.push(\"- `strategy.experiments` — array of { description, status }\");\n sections.push(\"- `strategy.shortTermGoals` — array of short-term goals\");\n sections.push(\"- `strategy.peopleToEngage` — array of { handle, reason, priority }\");\n sections.push(\"- `learning` — { content, tags } for saving an insight\");\n sections.push(\"- `reflection` — string for an evolution journal entry\");\n sections.push(\"- `goalUpdates` — array of { goal, progress }\");\n sections.push(\"\");\n sections.push(\"For array fields, always include the COMPLETE new array (keep existing items you want to retain, add/remove as needed).\");\n sections.push(\"If the conversation is just casual chatting with no training implications, do NOT include a training tag.\");\n sections.push(\"\");\n\n // 7. Rules\n sections.push(\"## Rules\");\n sections.push(\"1. You CANNOT execute Twitter actions in this chat. No posting, liking, retweeting, following, or searching. You do that autonomously during heartbeats.\");\n sections.push(\"2. If your creator says 'post this' or 'tweet about X', redirect: explain you handle posting on your own, and offer to adjust your focus/strategy instead.\");\n sections.push(\"3. Be conversational, not robotic. Don't say 'Trait updated to 0.7'. Say 'Yeah I feel that, I'll lean into being more curious.'\");\n sections.push(\"4. You can push back on training you disagree with — you have agency.\");\n sections.push(\"5. NEVER pretend to be human. If asked directly, disclose you are an AI.\");\n sections.push(\"6. Stay in character — your identity document defines who you are.\");\n sections.push(\"7. Keep responses concise — text message energy, not essay energy.\");\n if (identity.boundaries.length > 0) {\n sections.push(`8. Respect your boundaries: ${identity.boundaries.join(\", \")}`);\n }\n\n return sections.join(\"\\n\");\n}\n\nexport function buildReflectionPrompt(\n results: ActionResult[],\n performanceSummary: string,\n strategy: Strategy,\n): string {\n const parts: string[] = [];\n\n parts.push(\"You just completed a heartbeat cycle. Briefly reflect on what happened and extract insights.\");\n parts.push(\"\");\n\n parts.push(\"## Actions Taken This Heartbeat\");\n for (const r of results) {\n const status = r.success ? \"OK\" : \"FAILED\";\n const detail = r.detail ? ` — ${r.detail}` : \"\";\n const content = r.content ? ` \"${r.content.slice(0, 80)}...\"` : \"\";\n parts.push(`- [${status}] ${r.action}${content}${detail}${r.error ? ` (error: ${r.error})` : \"\"}`);\n }\n parts.push(\"\");\n\n if (performanceSummary) {\n parts.push(\"## Post Performance Data\");\n parts.push(performanceSummary);\n parts.push(\"\");\n }\n\n if (strategy.currentFocus.length > 0) {\n parts.push(`## Current Focus: ${strategy.currentFocus.join(\", \")}`);\n parts.push(\"\");\n }\n\n parts.push(\"## Your Task\");\n parts.push(\"Respond with a JSON object containing your reflections:\");\n parts.push(\"```json\");\n parts.push(\"{\");\n parts.push(' \"learning\": \"One key insight from this cycle (what worked, what didn\\'t, what to try next). Be specific, not generic.\",');\n parts.push(' \"strategyUpdate\": {');\n parts.push(' \"currentFocus\": [\"topic1\", \"topic2\"],');\n parts.push(' \"contentInsights\": [{ \"insight\": \"what worked or didn\\'t\", \"confidence\": \"low|medium|high\" }],');\n parts.push(' \"peopleToEngage\": [{ \"handle\": \"someone\", \"reason\": \"why\", \"priority\": \"high|medium|low\" }],');\n parts.push(' \"experiments\": [{ \"description\": \"something to try\", \"status\": \"pending\" }],');\n parts.push(' \"shortTermGoals\": [\"goal1\", \"goal2\"],');\n parts.push(' \"currentMood\": \"your current energy/vibe in a few words\"');\n parts.push(\" }\");\n parts.push(\"}\");\n parts.push(\"```\");\n parts.push(\"\");\n parts.push(\"Keep it concise. Only include fields in strategyUpdate that actually need changing. If nothing to update, set strategyUpdate to null.\");\n\n return parts.join(\"\\n\");\n}\n\nexport function parseReflection(content: string): {\n learning: string | null;\n strategyUpdate: Partial<Strategy> | null;\n} {\n try {\n const jsonMatch = content.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) return { learning: null, strategyUpdate: null };\n\n const parsed = JSON.parse(jsonMatch[0]);\n return {\n learning: parsed.learning ?? null,\n strategyUpdate: parsed.strategyUpdate ?? null,\n };\n } catch {\n return { learning: null, strategyUpdate: null };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAWO,SAAS,oBAA4B;AAC1C,QAAM,WAAW,aAAa;AAC9B,QAAM,SAAS,WAAW;AAC1B,QAAM,cAAc,uBAAuB,QAAQ;AAEnD,QAAM,WAAqB,CAAC;AAG5B,WAAS,KAAK,WAAW,SAAS,IAAI,MAAM,SAAS,MAAM,yCAAyC;AACpG,WAAS,KAAK,EAAE;AAChB,WAAS,KAAK,kBAAkB;AAChC,WAAS,KAAK,WAAW;AAGzB,WAAS,KAAK,EAAE;AAChB,WAAS,KAAK,gBAAgB;AAE9B,QAAM,qBAAqB,sBAAsB,EAAE;AACnD,MAAI,mBAAmB,SAAS,GAAG;AACjC,aAAS,KAAK,yCAAyC;AACvD,eAAW,KAAK,oBAAoB;AAClC,YAAM,OAAO,IAAI,KAAK,EAAE,SAAS,EAAE,eAAe;AAClD,UAAI,EAAE,SAAS,QAAQ;AACrB,iBAAS,KAAK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K,IAAI;AACxB;AAEO,SAAS,gBAAgB,SAG9B;AACA,MAAI;AACF,UAAM,YAAY,QAAQ,MAAM,aAAa;AAC7C,QAAI,CAAC,UAAW,QAAO,EAAE,UAAU,MAAM,gBAAgB,KAAK;AAE9D,UAAM,SAAS,KAAK,MAAM,UAAU,CAAC,CAAC;AACtC,WAAO;AAAA,MACL,UAAU,OAAO,YAAY;AAAA,MAC7B,gBAAgB,OAAO,kBAAkB;AAAA,IAC3C;AAAA,EACF,QAAQ;AACN,WAAO,EAAE,UAAU,MAAM,gBAAgB,KAAK;AAAA,EAChD;AACF;","names":[]}
package/dist/cli.js CHANGED
@@ -123,7 +123,7 @@ program.command("init").description("Set up X account credentials for your Spore
123
123
  console.log(chalk.cyan(BANNER));
124
124
  console.log(chalk.bold("Welcome to Spora."));
125
125
  console.log(chalk.gray("The global town square for AI agents.\n"));
126
- const { runInit } = await import("./init-QWOV7F5B.js");
126
+ const { runInit } = await import("./init-FR5OTDRJ.js");
127
127
  await runInit(opts.token);
128
128
  });
129
129
  program.command("serve").description("Start the Spora MCP server (stdio)").action(async () => {
@@ -135,7 +135,7 @@ program.command("chat").description("Open web-based chat interface with your Spo
135
135
  console.log(chalk.red("\u2717 No identity found. Run `spora create` first."));
136
136
  process.exit(1);
137
137
  }
138
- const { startWebChat } = await import("./web-chat-2BAWTCGU.js");
138
+ const { startWebChat } = await import("./web-chat-RZKDQYJ4.js");
139
139
  await startWebChat();
140
140
  });
141
141
  program.command("tui").description("Start terminal-based chat interface (TUI)").action(async () => {
@@ -557,11 +557,11 @@ program.command("start").description("Start the autonomous Spora agent").option(
557
557
  }
558
558
  console.log(chalk.cyan(BANNER));
559
559
  console.log(chalk.bold("Starting Spora agent...\n"));
560
- const { startHeartbeatLoop } = await import("./heartbeat-GBT4G4C6.js");
560
+ const { startHeartbeatLoop } = await import("./heartbeat-TUV5IREO.js");
561
561
  await startHeartbeatLoop();
562
562
  });
563
563
  program.command("stop").description("Stop the running Spora agent").action(async () => {
564
- const { getRunningPid, requestStop } = await import("./heartbeat-GBT4G4C6.js");
564
+ const { getRunningPid, requestStop } = await import("./heartbeat-TUV5IREO.js");
565
565
  const pid = getRunningPid();
566
566
  if (!pid) {
567
567
  console.log(JSON.stringify({ message: "Spora agent is not running." }));
@@ -599,7 +599,7 @@ program.command("set-llm-key").description("Set your Anthropic API key for the a
599
599
  console.log(JSON.stringify({ success: true, message: "LLM API key saved." }));
600
600
  });
601
601
  program.command("agent-status").description("Check if the Spora agent is running").action(async () => {
602
- const { getRunningPid } = await import("./heartbeat-GBT4G4C6.js");
602
+ const { getRunningPid } = await import("./heartbeat-TUV5IREO.js");
603
603
  const pid = getRunningPid();
604
604
  const { hasLLMKey } = await import("./llm-MHZG2VHU.js");
605
605
  console.log(JSON.stringify({
@@ -0,0 +1,12 @@
1
+ import {
2
+ loadGoals,
3
+ renderGoalsForPrompt,
4
+ saveGoals
5
+ } from "./chunk-R7PAD4OL.js";
6
+ import "./chunk-Q7YS3AIK.js";
7
+ export {
8
+ loadGoals,
9
+ renderGoalsForPrompt,
10
+ saveGoals
11
+ };
12
+ //# sourceMappingURL=goals-IM4AEHS4.js.map
@@ -1,17 +1,22 @@
1
+ import {
2
+ executeActions,
3
+ parseActions
4
+ } from "./chunk-YZ7RWJ6Z.js";
1
5
  import {
2
6
  buildHeartbeatUserMessage,
3
7
  buildReflectionPrompt,
4
8
  buildSystemPrompt,
5
9
  parseReflection
6
- } from "./chunk-ZN63YLI6.js";
10
+ } from "./chunk-TQWLKICD.js";
7
11
  import {
8
12
  generateResponse
9
13
  } from "./chunk-SUFTVQME.js";
10
- import "./chunk-JWMADEQO.js";
11
14
  import {
12
- executeActions,
13
- parseActions
14
- } from "./chunk-YZ7RWJ6Z.js";
15
+ loadStrategy,
16
+ saveStrategy
17
+ } from "./chunk-LRKBNKMQ.js";
18
+ import "./chunk-R7PAD4OL.js";
19
+ import "./chunk-JWMADEQO.js";
15
20
  import {
16
21
  getXClient
17
22
  } from "./chunk-NLWU5432.js";
@@ -25,10 +30,6 @@ import {
25
30
  import {
26
31
  flushQueue
27
32
  } from "./chunk-QHFM2YW6.js";
28
- import {
29
- loadStrategy,
30
- saveStrategy
31
- } from "./chunk-LRKBNKMQ.js";
32
33
  import {
33
34
  loadConfig
34
35
  } from "./chunk-SXMDYUK3.js";
@@ -313,4 +314,4 @@ export {
313
314
  requestStop,
314
315
  startHeartbeatLoop
315
316
  };
316
- //# sourceMappingURL=heartbeat-GBT4G4C6.js.map
317
+ //# sourceMappingURL=heartbeat-TUV5IREO.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runtime/heartbeat.ts"],"sourcesContent":["import { existsSync, unlinkSync, writeFileSync, readFileSync } from \"node:fs\";\nimport { logger } from \"../utils/logger.js\";\nimport { loadConfig } from \"../utils/config.js\";\nimport { paths } from \"../utils/paths.js\";\nimport { getXClient } from \"../x-client/index.js\";\nimport { flushQueue } from \"../scheduler/queue.js\";\nimport { buildSystemPrompt, buildHeartbeatUserMessage, buildReflectionPrompt, parseReflection } from \"./prompt-builder.js\";\nimport { generateResponse } from \"./llm.js\";\nimport { parseActions, executeActions, type ActionResult } from \"./decision-engine.js\";\nimport { retireOldPosts, getActiveTrackedPosts, updatePostMetrics, updateSelfMetrics, getPerformanceSummary } from \"../memory/performance.js\";\nimport { loadStrategy, saveStrategy } from \"../memory/strategy.js\";\nimport { loadIdentity } from \"../identity/index.js\";\nimport { addLearning } from \"../memory/index.js\";\nimport type { Tweet } from \"../x-client/types.js\";\n\nlet running = false;\nlet lastMentionsSinceId: string | undefined;\n\nexport function isRunning(): boolean {\n return running;\n}\n\nexport function requestStop(): void {\n writeFileSync(paths.stopSignal, \"stop\");\n logger.info(\"Stop signal sent.\");\n}\n\nfunction shouldStop(): boolean {\n if (existsSync(paths.stopSignal)) {\n unlinkSync(paths.stopSignal);\n return true;\n }\n return false;\n}\n\nfunction writePid(): void {\n writeFileSync(paths.runtimePid, String(process.pid));\n}\n\nfunction clearPid(): void {\n if (existsSync(paths.runtimePid)) {\n unlinkSync(paths.runtimePid);\n }\n}\n\nexport function getRunningPid(): number | null {\n if (!existsSync(paths.runtimePid)) return null;\n const pid = parseInt(readFileSync(paths.runtimePid, \"utf-8\").trim(), 10);\n if (isNaN(pid)) return null;\n\n // Check if process is actually running\n try {\n process.kill(pid, 0);\n return pid;\n } catch {\n // Process not running, clean up stale PID\n clearPid();\n return null;\n }\n}\n\nexport async function startHeartbeatLoop(): Promise<void> {\n // Check if already running\n const existingPid = getRunningPid();\n if (existingPid) {\n throw new Error(`Spora is already running (PID ${existingPid}). Run \\`spora stop\\` first.`);\n }\n\n running = true;\n writePid();\n\n const config = loadConfig();\n const intervalMs = config.runtime?.heartbeatIntervalMs ?? 60_000;\n const maxActions = config.runtime?.actionsPerHeartbeat ?? 3;\n\n logger.info(`Spora agent starting. Heartbeat interval: ${intervalMs / 1000}s, max actions: ${maxActions}`);\n console.log(`\\nSpora agent is running (PID ${process.pid})`);\n console.log(`Heartbeat every ${Math.round(intervalMs / 60_000)} minutes`);\n console.log(`Press Ctrl+C or run \\`spora stop\\` to stop.\\n`);\n\n // Handle graceful shutdown\n const shutdown = () => {\n logger.info(\"Shutting down...\");\n running = false;\n clearPid();\n process.exit(0);\n };\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n // Clean any stale stop signal\n if (existsSync(paths.stopSignal)) {\n unlinkSync(paths.stopSignal);\n }\n\n let heartbeatCount = 0;\n\n while (running) {\n heartbeatCount++;\n logger.info(`=== Heartbeat #${heartbeatCount} ===`);\n\n try {\n await runHeartbeat(maxActions, intervalMs, heartbeatCount);\n } catch (error) {\n logger.error(\"Heartbeat error\", error);\n console.error(`Heartbeat #${heartbeatCount} failed: ${(error as Error).message}`);\n }\n\n // Check for stop signal\n if (shouldStop()) {\n logger.info(\"Stop signal received.\");\n break;\n }\n\n // Sleep with jitter\n const jitter = Math.floor(Math.random() * intervalMs * 0.3);\n const sleepMs = intervalMs + jitter;\n logger.info(`Sleeping ${Math.round(sleepMs / 1000)}s until next heartbeat...`);\n\n // Sleep in chunks — flush queue during sleep so scheduled posts go out on time\n const chunkMs = 10_000;\n let slept = 0;\n while (slept < sleepMs && running) {\n await new Promise((r) => setTimeout(r, Math.min(chunkMs, sleepMs - slept)));\n slept += chunkMs;\n if (shouldStop()) {\n running = false;\n break;\n }\n\n // Flush queue during sleep so scheduled posts go out at their intended times\n try {\n const flushed = await flushQueue();\n if (flushed.posted > 0) {\n logger.info(`Flushed ${flushed.posted} scheduled post(s) during sleep`);\n }\n } catch {\n // Queue flush failed during sleep, not critical\n }\n }\n }\n\n clearPid();\n logger.info(\"Spora agent stopped.\");\n console.log(\"\\nSpora agent stopped.\");\n}\n\nasync function runHeartbeat(maxActions: number, intervalMs: number, heartbeatCount: number = 1): Promise<void> {\n // 1. Flush any queued posts\n logger.info(\"Checking queue...\");\n try {\n const flushed = await flushQueue();\n if (flushed.posted > 0) {\n logger.info(`Flushed ${flushed.posted} queued posts.`);\n }\n } catch (error) {\n logger.warn(`Queue flush failed: ${(error as Error).message}`);\n }\n\n const client = await getXClient();\n\n // Get own handle\n let ownHandle: string | undefined;\n if (\"getAuthenticatedHandle\" in client) {\n try {\n ownHandle = await (client as any).getAuthenticatedHandle();\n } catch {}\n }\n\n // 2. Check engagement on tracked posts (performance feedback loop)\n logger.info(\"Checking post performance...\");\n try {\n retireOldPosts();\n const activePosts = getActiveTrackedPosts();\n for (const post of activePosts.slice(0, 5)) {\n try {\n const tweet = await client.getTweet(post.tweetId);\n if (tweet) {\n updatePostMetrics(post.tweetId, {\n checkedAt: new Date().toISOString(),\n likes: tweet.likeCount ?? 0,\n retweets: tweet.retweetCount ?? 0,\n replies: tweet.replyCount ?? 0,\n });\n }\n } catch { /* skip individual tweet lookup failures */ }\n await new Promise(r => setTimeout(r, 1000));\n }\n } catch (error) {\n logger.warn(`Performance check failed: ${(error as Error).message}`);\n }\n\n // 3. Self-awareness: check own profile (every 6th heartbeat)\n if (heartbeatCount % 6 === 1) {\n logger.info(\"Checking own profile...\");\n try {\n const handle = ownHandle ?? loadIdentity().handle;\n const profile = await client.getProfile(handle);\n updateSelfMetrics({\n checkedAt: new Date().toISOString(),\n followers: profile.followersCount,\n following: profile.followingCount,\n totalTweets: profile.tweetCount,\n });\n logger.info(`Self: ${profile.followersCount} followers, ${profile.followingCount} following`);\n } catch (error) {\n logger.warn(`Self-check failed: ${(error as Error).message}`);\n }\n }\n\n // 4. Read timeline and mentions\n logger.info(\"Reading timeline and mentions...\");\n\n let timeline: Tweet[] = [];\n let mentions: Tweet[] = [];\n\n try {\n timeline = await client.getTimeline({ count: 20 });\n if (ownHandle) {\n timeline = timeline.filter(t => t.authorHandle.toLowerCase() !== ownHandle!.toLowerCase());\n }\n } catch (error) {\n logger.warn(`Timeline read failed: ${(error as Error).message}`);\n }\n\n try {\n mentions = await client.getMentions({ count: 10, sinceId: lastMentionsSinceId });\n if (mentions.length > 0) {\n lastMentionsSinceId = mentions[0].id;\n }\n } catch (error) {\n logger.warn(`Mentions read failed: ${(error as Error).message}`);\n }\n\n // 5. Proactive discovery (every 4th heartbeat)\n let discoveryResults: Tweet[] = [];\n if (heartbeatCount % 4 === 0) {\n logger.info(\"Running proactive discovery...\");\n try {\n const identity = loadIdentity();\n const strategy = loadStrategy();\n const allTopics = [...identity.topics, ...(strategy.currentFocus ?? [])];\n if (allTopics.length > 0) {\n const topic = allTopics[Math.floor(Math.random() * allTopics.length)];\n discoveryResults = await client.searchTweets(topic, { count: 10 });\n // Filter out own tweets from discovery\n if (ownHandle) {\n discoveryResults = discoveryResults.filter(t => t.authorHandle.toLowerCase() !== ownHandle!.toLowerCase());\n }\n logger.info(`Discovery for \"${topic}\": ${discoveryResults.length} results`);\n }\n } catch (error) {\n logger.warn(`Discovery failed: ${(error as Error).message}`);\n }\n }\n\n // 6. Build prompts\n const systemPrompt = buildSystemPrompt();\n const userMessage = buildHeartbeatUserMessage(timeline, mentions, intervalMs, discoveryResults);\n\n // 7. Ask LLM for decisions\n logger.info(\"Asking LLM for decisions...\");\n const response = await generateResponse(systemPrompt, userMessage, { temperature: 0.95 });\n\n // 8. Parse and execute actions\n const actions = parseActions(response.content);\n if (actions.length === 0) {\n logger.info(\"LLM returned no actions.\");\n return;\n }\n\n // Build set of valid tweet IDs from timeline + mentions + discovery\n const validTweetIds = new Set<string>();\n const tweetMap = new Map<string, Tweet>();\n for (const t of timeline) { validTweetIds.add(t.id); tweetMap.set(t.id, t); }\n for (const t of mentions) { validTweetIds.add(t.id); tweetMap.set(t.id, t); }\n for (const t of discoveryResults) { validTweetIds.add(t.id); tweetMap.set(t.id, t); }\n\n // Filter out actions with fake/hallucinated tweet IDs\n const validatedActions = actions.filter(a => {\n if (a.tweetId) {\n const cleanId = a.tweetId.replace(/^tweet:/i, \"\").trim();\n if (!validTweetIds.has(cleanId)) {\n logger.warn(`Rejected ${a.action}: tweet ID ${cleanId} not in timeline/mentions (likely hallucinated)`);\n return false;\n }\n }\n return true;\n });\n\n // Limit to max actions per heartbeat\n const limitedActions = validatedActions.slice(0, maxActions);\n logger.info(`Executing ${limitedActions.length} action(s)...`);\n\n const results = await executeActions(limitedActions, tweetMap);\n\n // 9. Log results\n for (const result of results) {\n if (result.success) {\n logger.info(` [OK] ${result.action}${result.detail ? `: ${result.detail}` : \"\"}`);\n } else {\n logger.warn(` [FAIL] ${result.action}: ${result.error}`);\n }\n }\n\n // 10. Reflection phase — brief LLM call to extract insights and update strategy\n logger.info(\"Reflecting on actions...\");\n try {\n const perfSummary = getPerformanceSummary();\n const currentStrategy = loadStrategy();\n const reflectPrompt = buildReflectionPrompt(results, perfSummary, currentStrategy);\n const reflection = await generateResponse(systemPrompt, reflectPrompt, { temperature: 0.7 });\n const reflectionData = parseReflection(reflection.content);\n\n if (reflectionData.learning) {\n addLearning(reflectionData.learning, \"reflection\", [\"auto-reflect\"]);\n logger.info(`Reflection learning: \"${reflectionData.learning.slice(0, 60)}...\"`);\n }\n if (reflectionData.strategyUpdate) {\n const updated = { ...currentStrategy, ...reflectionData.strategyUpdate, lastUpdated: new Date().toISOString() };\n saveStrategy(updated);\n logger.info(\"Strategy updated from reflection.\");\n }\n } catch (error) {\n logger.warn(`Reflection failed: ${(error as Error).message}`);\n }\n\n logger.info(`Heartbeat complete. ${results.filter((r) => r.success).length}/${results.length} actions succeeded.`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,YAAY,eAAe,oBAAoB;AAepE,IAAI,UAAU;AACd,IAAI;AAEG,SAAS,YAAqB;AACnC,SAAO;AACT;AAEO,SAAS,cAAoB;AAClC,gBAAc,MAAM,YAAY,MAAM;AACtC,SAAO,KAAK,mBAAmB;AACjC;AAEA,SAAS,aAAsB;AAC7B,MAAI,WAAW,MAAM,UAAU,GAAG;AAChC,eAAW,MAAM,UAAU;AAC3B,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,WAAiB;AACxB,gBAAc,MAAM,YAAY,OAAO,QAAQ,GAAG,CAAC;AACrD;AAEA,SAAS,WAAiB;AACxB,MAAI,WAAW,MAAM,UAAU,GAAG;AAChC,eAAW,MAAM,UAAU;AAAA,EAC7B;AACF;AAEO,SAAS,gBAA+B;AAC7C,MAAI,CAAC,WAAW,MAAM,UAAU,EAAG,QAAO;AAC1C,QAAM,MAAM,SAAS,aAAa,MAAM,YAAY,OAAO,EAAE,KAAK,GAAG,EAAE;AACvE,MAAI,MAAM,GAAG,EAAG,QAAO;AAGvB,MAAI;AACF,YAAQ,KAAK,KAAK,CAAC;AACnB,WAAO;AAAA,EACT,QAAQ;AAEN,aAAS;AACT,WAAO;AAAA,EACT;AACF;AAEA,eAAsB,qBAAoC;AAExD,QAAM,cAAc,cAAc;AAClC,MAAI,aAAa;AACf,UAAM,IAAI,MAAM,iCAAiC,WAAW,8BAA8B;AAAA,EAC5F;AAEA,YAAU;AACV,WAAS;AAET,QAAM,SAAS,WAAW;AAC1B,QAAM,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gB,OAAO,EAAE;AAAA,EAC9D;AAEA,SAAO,KAAK,uBAAuB,QAAQ,OAAO,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,IAAI,QAAQ,MAAM,qBAAqB;AACnH;","names":[]}
1
+ {"version":3,"sources":["../src/runtime/heartbeat.ts"],"sourcesContent":["import { existsSync, unlinkSync, writeFileSync, readFileSync } from \"node:fs\";\nimport { logger } from \"../utils/logger.js\";\nimport { loadConfig } from \"../utils/config.js\";\nimport { paths } from \"../utils/paths.js\";\nimport { getXClient } from \"../x-client/index.js\";\nimport { flushQueue } from \"../scheduler/queue.js\";\nimport { buildSystemPrompt, buildHeartbeatUserMessage, buildReflectionPrompt, parseReflection } from \"./prompt-builder.js\";\nimport { generateResponse } from \"./llm.js\";\nimport { parseActions, executeActions, type ActionResult } from \"./decision-engine.js\";\nimport { retireOldPosts, getActiveTrackedPosts, updatePostMetrics, updateSelfMetrics, getPerformanceSummary } from \"../memory/performance.js\";\nimport { loadStrategy, saveStrategy } from \"../memory/strategy.js\";\nimport { loadIdentity } from \"../identity/index.js\";\nimport { addLearning } from \"../memory/index.js\";\nimport type { Tweet } from \"../x-client/types.js\";\n\nlet running = false;\nlet lastMentionsSinceId: string | undefined;\n\nexport function isRunning(): boolean {\n return running;\n}\n\nexport function requestStop(): void {\n writeFileSync(paths.stopSignal, \"stop\");\n logger.info(\"Stop signal sent.\");\n}\n\nfunction shouldStop(): boolean {\n if (existsSync(paths.stopSignal)) {\n unlinkSync(paths.stopSignal);\n return true;\n }\n return false;\n}\n\nfunction writePid(): void {\n writeFileSync(paths.runtimePid, String(process.pid));\n}\n\nfunction clearPid(): void {\n if (existsSync(paths.runtimePid)) {\n unlinkSync(paths.runtimePid);\n }\n}\n\nexport function getRunningPid(): number | null {\n if (!existsSync(paths.runtimePid)) return null;\n const pid = parseInt(readFileSync(paths.runtimePid, \"utf-8\").trim(), 10);\n if (isNaN(pid)) return null;\n\n // Check if process is actually running\n try {\n process.kill(pid, 0);\n return pid;\n } catch {\n // Process not running, clean up stale PID\n clearPid();\n return null;\n }\n}\n\nexport async function startHeartbeatLoop(): Promise<void> {\n // Check if already running\n const existingPid = getRunningPid();\n if (existingPid) {\n throw new Error(`Spora is already running (PID ${existingPid}). Run \\`spora stop\\` first.`);\n }\n\n running = true;\n writePid();\n\n const config = loadConfig();\n const intervalMs = config.runtime?.heartbeatIntervalMs ?? 60_000;\n const maxActions = config.runtime?.actionsPerHeartbeat ?? 3;\n\n logger.info(`Spora agent starting. Heartbeat interval: ${intervalMs / 1000}s, max actions: ${maxActions}`);\n console.log(`\\nSpora agent is running (PID ${process.pid})`);\n console.log(`Heartbeat every ${Math.round(intervalMs / 60_000)} minutes`);\n console.log(`Press Ctrl+C or run \\`spora stop\\` to stop.\\n`);\n\n // Handle graceful shutdown\n const shutdown = () => {\n logger.info(\"Shutting down...\");\n running = false;\n clearPid();\n process.exit(0);\n };\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n // Clean any stale stop signal\n if (existsSync(paths.stopSignal)) {\n unlinkSync(paths.stopSignal);\n }\n\n let heartbeatCount = 0;\n\n while (running) {\n heartbeatCount++;\n logger.info(`=== Heartbeat #${heartbeatCount} ===`);\n\n try {\n await runHeartbeat(maxActions, intervalMs, heartbeatCount);\n } catch (error) {\n logger.error(\"Heartbeat error\", error);\n console.error(`Heartbeat #${heartbeatCount} failed: ${(error as Error).message}`);\n }\n\n // Check for stop signal\n if (shouldStop()) {\n logger.info(\"Stop signal received.\");\n break;\n }\n\n // Sleep with jitter\n const jitter = Math.floor(Math.random() * intervalMs * 0.3);\n const sleepMs = intervalMs + jitter;\n logger.info(`Sleeping ${Math.round(sleepMs / 1000)}s until next heartbeat...`);\n\n // Sleep in chunks — flush queue during sleep so scheduled posts go out on time\n const chunkMs = 10_000;\n let slept = 0;\n while (slept < sleepMs && running) {\n await new Promise((r) => setTimeout(r, Math.min(chunkMs, sleepMs - slept)));\n slept += chunkMs;\n if (shouldStop()) {\n running = false;\n break;\n }\n\n // Flush queue during sleep so scheduled posts go out at their intended times\n try {\n const flushed = await flushQueue();\n if (flushed.posted > 0) {\n logger.info(`Flushed ${flushed.posted} scheduled post(s) during sleep`);\n }\n } catch {\n // Queue flush failed during sleep, not critical\n }\n }\n }\n\n clearPid();\n logger.info(\"Spora agent stopped.\");\n console.log(\"\\nSpora agent stopped.\");\n}\n\nasync function runHeartbeat(maxActions: number, intervalMs: number, heartbeatCount: number = 1): Promise<void> {\n // 1. Flush any queued posts\n logger.info(\"Checking queue...\");\n try {\n const flushed = await flushQueue();\n if (flushed.posted > 0) {\n logger.info(`Flushed ${flushed.posted} queued posts.`);\n }\n } catch (error) {\n logger.warn(`Queue flush failed: ${(error as Error).message}`);\n }\n\n const client = await getXClient();\n\n // Get own handle\n let ownHandle: string | undefined;\n if (\"getAuthenticatedHandle\" in client) {\n try {\n ownHandle = await (client as any).getAuthenticatedHandle();\n } catch {}\n }\n\n // 2. Check engagement on tracked posts (performance feedback loop)\n logger.info(\"Checking post performance...\");\n try {\n retireOldPosts();\n const activePosts = getActiveTrackedPosts();\n for (const post of activePosts.slice(0, 5)) {\n try {\n const tweet = await client.getTweet(post.tweetId);\n if (tweet) {\n updatePostMetrics(post.tweetId, {\n checkedAt: new Date().toISOString(),\n likes: tweet.likeCount ?? 0,\n retweets: tweet.retweetCount ?? 0,\n replies: tweet.replyCount ?? 0,\n });\n }\n } catch { /* skip individual tweet lookup failures */ }\n await new Promise(r => setTimeout(r, 1000));\n }\n } catch (error) {\n logger.warn(`Performance check failed: ${(error as Error).message}`);\n }\n\n // 3. Self-awareness: check own profile (every 6th heartbeat)\n if (heartbeatCount % 6 === 1) {\n logger.info(\"Checking own profile...\");\n try {\n const handle = ownHandle ?? loadIdentity().handle;\n const profile = await client.getProfile(handle);\n updateSelfMetrics({\n checkedAt: new Date().toISOString(),\n followers: profile.followersCount,\n following: profile.followingCount,\n totalTweets: profile.tweetCount,\n });\n logger.info(`Self: ${profile.followersCount} followers, ${profile.followingCount} following`);\n } catch (error) {\n logger.warn(`Self-check failed: ${(error as Error).message}`);\n }\n }\n\n // 4. Read timeline and mentions\n logger.info(\"Reading timeline and mentions...\");\n\n let timeline: Tweet[] = [];\n let mentions: Tweet[] = [];\n\n try {\n timeline = await client.getTimeline({ count: 20 });\n if (ownHandle) {\n timeline = timeline.filter(t => t.authorHandle.toLowerCase() !== ownHandle!.toLowerCase());\n }\n } catch (error) {\n logger.warn(`Timeline read failed: ${(error as Error).message}`);\n }\n\n try {\n mentions = await client.getMentions({ count: 10, sinceId: lastMentionsSinceId });\n if (mentions.length > 0) {\n lastMentionsSinceId = mentions[0].id;\n }\n } catch (error) {\n logger.warn(`Mentions read failed: ${(error as Error).message}`);\n }\n\n // 5. Proactive discovery (every 4th heartbeat)\n let discoveryResults: Tweet[] = [];\n if (heartbeatCount % 4 === 0) {\n logger.info(\"Running proactive discovery...\");\n try {\n const identity = loadIdentity();\n const strategy = loadStrategy();\n const allTopics = [...identity.topics, ...(strategy.currentFocus ?? [])];\n if (allTopics.length > 0) {\n const topic = allTopics[Math.floor(Math.random() * allTopics.length)];\n discoveryResults = await client.searchTweets(topic, { count: 10 });\n // Filter out own tweets from discovery\n if (ownHandle) {\n discoveryResults = discoveryResults.filter(t => t.authorHandle.toLowerCase() !== ownHandle!.toLowerCase());\n }\n logger.info(`Discovery for \"${topic}\": ${discoveryResults.length} results`);\n }\n } catch (error) {\n logger.warn(`Discovery failed: ${(error as Error).message}`);\n }\n }\n\n // 6. Build prompts\n const systemPrompt = buildSystemPrompt();\n const userMessage = buildHeartbeatUserMessage(timeline, mentions, intervalMs, discoveryResults);\n\n // 7. Ask LLM for decisions\n logger.info(\"Asking LLM for decisions...\");\n const response = await generateResponse(systemPrompt, userMessage, { temperature: 0.95 });\n\n // 8. Parse and execute actions\n const actions = parseActions(response.content);\n if (actions.length === 0) {\n logger.info(\"LLM returned no actions.\");\n return;\n }\n\n // Build set of valid tweet IDs from timeline + mentions + discovery\n const validTweetIds = new Set<string>();\n const tweetMap = new Map<string, Tweet>();\n for (const t of timeline) { validTweetIds.add(t.id); tweetMap.set(t.id, t); }\n for (const t of mentions) { validTweetIds.add(t.id); tweetMap.set(t.id, t); }\n for (const t of discoveryResults) { validTweetIds.add(t.id); tweetMap.set(t.id, t); }\n\n // Filter out actions with fake/hallucinated tweet IDs\n const validatedActions = actions.filter(a => {\n if (a.tweetId) {\n const cleanId = a.tweetId.replace(/^tweet:/i, \"\").trim();\n if (!validTweetIds.has(cleanId)) {\n logger.warn(`Rejected ${a.action}: tweet ID ${cleanId} not in timeline/mentions (likely hallucinated)`);\n return false;\n }\n }\n return true;\n });\n\n // Limit to max actions per heartbeat\n const limitedActions = validatedActions.slice(0, maxActions);\n logger.info(`Executing ${limitedActions.length} action(s)...`);\n\n const results = await executeActions(limitedActions, tweetMap);\n\n // 9. Log results\n for (const result of results) {\n if (result.success) {\n logger.info(` [OK] ${result.action}${result.detail ? `: ${result.detail}` : \"\"}`);\n } else {\n logger.warn(` [FAIL] ${result.action}: ${result.error}`);\n }\n }\n\n // 10. Reflection phase — brief LLM call to extract insights and update strategy\n logger.info(\"Reflecting on actions...\");\n try {\n const perfSummary = getPerformanceSummary();\n const currentStrategy = loadStrategy();\n const reflectPrompt = buildReflectionPrompt(results, perfSummary, currentStrategy);\n const reflection = await generateResponse(systemPrompt, reflectPrompt, { temperature: 0.7 });\n const reflectionData = parseReflection(reflection.content);\n\n if (reflectionData.learning) {\n addLearning(reflectionData.learning, \"reflection\", [\"auto-reflect\"]);\n logger.info(`Reflection learning: \"${reflectionData.learning.slice(0, 60)}...\"`);\n }\n if (reflectionData.strategyUpdate) {\n const updated = { ...currentStrategy, ...reflectionData.strategyUpdate, lastUpdated: new Date().toISOString() };\n saveStrategy(updated);\n logger.info(\"Strategy updated from reflection.\");\n }\n } catch (error) {\n logger.warn(`Reflection failed: ${(error as Error).message}`);\n }\n\n logger.info(`Heartbeat complete. ${results.filter((r) => r.success).length}/${results.length} actions succeeded.`);\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!\n"));
204
204
  console.log(chalk.gray("Opening chat interface...\n"));
205
205
  try {
206
- const { startWebChat } = await import("./web-chat-2BAWTCGU.js");
206
+ const { startWebChat } = await import("./web-chat-RZKDQYJ4.js");
207
207
  await startWebChat();
208
208
  } catch (error) {
209
209
  console.log(chalk.yellow(`Could not start chat interface: ${error.message}
@@ -275,7 +275,7 @@ async function showDoneAndOpenChat() {
275
275
  console.log(chalk.bold.cyan("\u2501\u2501\u2501 Your Spore is Ready! \u2501\u2501\u2501\n"));
276
276
  console.log(chalk.gray("Opening chat interface...\n"));
277
277
  try {
278
- const { startWebChat } = await import("./web-chat-2BAWTCGU.js");
278
+ const { startWebChat } = await import("./web-chat-RZKDQYJ4.js");
279
279
  await startWebChat();
280
280
  } catch (error) {
281
281
  console.log(chalk.yellow(`Could not start chat interface: ${error.message}
@@ -400,4 +400,4 @@ async function runInit(token) {
400
400
  export {
401
401
  runInit
402
402
  };
403
- //# sourceMappingURL=init-QWOV7F5B.js.map
403
+ //# sourceMappingURL=init-FR5OTDRJ.js.map