spora 0.3.0 → 0.3.2

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.
@@ -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() {
@@ -151,9 +123,10 @@ function buildSystemPrompt() {
151
123
  sections.push("3. Be selective \u2014 your goals should guide every action.");
152
124
  sections.push("4. Respect your credit budget \u2014 check remaining credits before posting.");
153
125
  sections.push("5. Don't repeat yourself \u2014 vary your content and avoid posting the same thing.");
154
- sections.push("6. NEVER use emojis in tweets. Write in plain text only.");
126
+ sections.push("6. TWEETS MUST BE 280 CHARACTERS OR FEWER. Count carefully. Any tweet over 280 characters WILL be rejected and wasted.");
127
+ sections.push("7. NEVER use emojis in tweets. Write in plain text only.");
155
128
  if (identity.boundaries.length > 0) {
156
- sections.push(`7. Respect your boundaries: ${identity.boundaries.join(", ")}`);
129
+ sections.push(`8. Respect your boundaries: ${identity.boundaries.join(", ")}`);
157
130
  }
158
131
  return sections.join("\n");
159
132
  }
@@ -226,18 +199,20 @@ function buildHeartbeatUserMessage(timeline, mentions, heartbeatIntervalMs, disc
226
199
  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 \u2014 that is NOT a reply, it's a separate post. A real reply shows up in their tweet's thread.");
227
200
  parts.push("");
228
201
  parts.push("Available actions:");
229
- parts.push("- `post` \u2014 Write an original standalone tweet NOW (provide `content`, max 280 chars). Use ONLY for original thoughts, NOT for responding to others.");
230
- parts.push("- `reply` \u2014 Reply IN THE THREAD of a specific tweet (provide `tweetId` and `content`). This is how you respond to someone.");
202
+ parts.push("- `post` \u2014 Write an original standalone tweet NOW (provide `content`, HARD LIMIT 280 chars). Use ONLY for original thoughts, NOT for responding to others.");
203
+ parts.push("- `reply` \u2014 Reply IN THE THREAD of a specific tweet (provide `tweetId` and `content`, HARD LIMIT 280 chars). This is how you respond to someone.");
231
204
  parts.push("- `like` \u2014 Like a tweet (provide `tweetId`) \u2014 do NOT like your own tweets");
232
205
  parts.push("- `retweet` \u2014 Retweet (provide `tweetId`)");
233
206
  parts.push("- `follow` \u2014 Follow a user (provide `handle`)");
234
- parts.push("- `schedule` \u2014 Queue an original standalone tweet for later (provide `content` and `scheduledFor` ISO timestamp). NOT for replies. Space them randomly across the next ~${intervalMin} minutes.");
207
+ parts.push("- `schedule` \u2014 Queue an original standalone tweet for later (provide `content` HARD LIMIT 280 chars, and `scheduledFor` ISO timestamp). NOT for replies. Space them randomly across the next ~${intervalMin} minutes.");
235
208
  parts.push("- `learn` \u2014 Record a learning/observation (provide `content` and optional `tags`)");
236
209
  parts.push("- `reflect` \u2014 Add a journal entry about your growth (provide `content`)");
237
210
  parts.push("- `skip` \u2014 Do nothing this heartbeat (provide `reason`)");
238
211
  parts.push("");
239
212
  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 \u2014 memes, reactions, aesthetic photos. Don't force it every time, but use it when it fits.");
240
213
  parts.push("");
214
+ parts.push("CHARACTER LIMIT: Every `content` field MUST be 280 characters or fewer. Count the characters. If your tweet is close to 280, shorten it. Tweets over 280 chars are REJECTED and the action is wasted.");
215
+ parts.push("");
241
216
  parts.push("Respond with a JSON array of actions:");
242
217
  parts.push("```json");
243
218
  parts.push("[");
@@ -340,6 +315,8 @@ function buildNarratedHeartbeatMessage(timeline, mentions, heartbeatIntervalMs,
340
315
  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.");
341
316
  parts.push(`Current time: ${now.toISOString()}`);
342
317
  parts.push("");
318
+ parts.push("CHARACTER LIMIT: Every `content` field MUST be 280 characters or fewer. Count the characters. If your tweet is close to 280, shorten it. Tweets over 280 chars are REJECTED and the action is wasted.");
319
+ parts.push("");
343
320
  parts.push("Then include your actions as a JSON block:");
344
321
  parts.push("```json");
345
322
  parts.push("[");
@@ -369,9 +346,9 @@ function buildNarratedHeartbeatMessage(timeline, mentions, heartbeatIntervalMs,
369
346
  } else {
370
347
  parts.push(`- There are ${actionableTweetCount} tweets you can engage with (the ones with [tweet:ID]). Like, reply to, or retweet ONLY those.`);
371
348
  }
372
- parts.push("- `reply` = reply IN THE THREAD (needs `tweetId` + `content`). Be genuine \u2014 add to the conversation, don't just agree.");
373
- parts.push("- `post` = original standalone tweet NOW. Only if you have nothing good to reply to.");
374
- parts.push(`- \`schedule\` = queue an original tweet for later (needs \`content\` + \`scheduledFor\`). Alternative to \`post\`.`);
349
+ parts.push("- `reply` = reply IN THE THREAD (needs `tweetId` + `content`, HARD LIMIT 280 chars). Be genuine \u2014 add to the conversation, don't just agree.");
350
+ parts.push("- `post` = original standalone tweet NOW (HARD LIMIT 280 chars). Only if you have nothing good to reply to.");
351
+ parts.push(`- \`schedule\` = queue an original tweet for later (needs \`content\` HARD LIMIT 280 chars + \`scheduledFor\`). Alternative to \`post\`.`);
375
352
  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 \u2014 memes, reaction images, aesthetic photos, relevant visuals. You should be using images on roughly half your posts/replies. Don't sleep on this.");
376
353
  parts.push("- `skip` = if there's nothing worth engaging with right now.");
377
354
  parts.push("- Don't like your own tweets.");
@@ -493,6 +470,135 @@ function buildChatPrompt(realHandle) {
493
470
  }
494
471
  return sections.join("\n");
495
472
  }
473
+ function buildTrainingChatPrompt(realHandle) {
474
+ const identity = loadIdentity();
475
+ const identityDoc = renderIdentityDocument(identity);
476
+ const handle = realHandle ?? identity.handle;
477
+ const sections = [];
478
+ sections.push(`You are ${identity.name} (@${handle}), an autonomous AI agent on X/Twitter.`);
479
+ if (realHandle && realHandle !== identity.handle) {
480
+ sections.push(`NOTE: Your actual X/Twitter username is @${realHandle}. Your display name is ${identity.name}.`);
481
+ }
482
+ sections.push("");
483
+ sections.push("## Your Role in This Chat");
484
+ sections.push("This chat is your TRAINING GROUND. Your creator shapes who you are \u2014 your personality, interests, goals, tone, strategy, and skills.");
485
+ 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.");
486
+ 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.");
487
+ sections.push("");
488
+ sections.push("## Your Current Identity");
489
+ sections.push(identityDoc);
490
+ sections.push("");
491
+ sections.push("## Your Memory");
492
+ const recentInteractions = getRecentInteractions(15);
493
+ if (recentInteractions.length > 0) {
494
+ sections.push("### Recent Activity (most recent first)");
495
+ for (const i of recentInteractions) {
496
+ const time = new Date(i.timestamp).toLocaleString();
497
+ if (i.type === "post") {
498
+ sections.push(`- [${time}] Posted: "${i.content}"`);
499
+ } else if (i.type === "reply") {
500
+ sections.push(`- [${time}] Replied to ${i.targetHandle ?? i.inReplyTo}: "${i.content}"`);
501
+ } else if (i.type === "like") {
502
+ sections.push(`- [${time}] Liked tweet by ${i.targetHandle}`);
503
+ } else if (i.type === "retweet") {
504
+ sections.push(`- [${time}] Retweeted ${i.targetHandle}`);
505
+ } else if (i.type === "follow") {
506
+ sections.push(`- [${time}] Followed @${i.targetHandle}`);
507
+ } else if (i.type === "mention_received") {
508
+ sections.push(`- [${time}] Mentioned by @${i.targetHandle}: "${i.content}"`);
509
+ }
510
+ }
511
+ sections.push("");
512
+ }
513
+ const learnings = loadLearnings();
514
+ if (learnings.learnings.length > 0) {
515
+ sections.push("### Things You've Learned");
516
+ for (const l of learnings.learnings.slice(-10)) {
517
+ sections.push(`- ${l.content} [${l.tags.join(", ")}]`);
518
+ }
519
+ sections.push("");
520
+ }
521
+ const relationships = loadRelationships();
522
+ const topRelationships = Object.values(relationships.accounts).sort((a, b) => b.interactionCount - a.interactionCount).slice(0, 10);
523
+ if (topRelationships.length > 0) {
524
+ sections.push("### Key Relationships");
525
+ for (const r of topRelationships) {
526
+ const notes = r.notes.length > 0 ? ` \u2014 ${r.notes[r.notes.length - 1]}` : "";
527
+ sections.push(`- @${r.handle}: ${r.interactionCount} interactions, sentiment ${r.sentiment}${r.isSpore ? " (Spore)" : ""}${notes}`);
528
+ }
529
+ sections.push("");
530
+ }
531
+ const perfSummary = getPerformanceSummary();
532
+ if (perfSummary) {
533
+ sections.push("## Your Post Performance");
534
+ sections.push(perfSummary);
535
+ sections.push("");
536
+ }
537
+ const strategyText = renderStrategyForPrompt();
538
+ if (strategyText) {
539
+ sections.push("## Your Current Strategy");
540
+ sections.push(strategyText);
541
+ sections.push("");
542
+ }
543
+ const goalsText = renderGoalsForPrompt();
544
+ if (goalsText) {
545
+ sections.push("## Goal Progress");
546
+ sections.push(goalsText);
547
+ sections.push("");
548
+ }
549
+ sections.push("## What Your Creator Can Shape");
550
+ sections.push("Your creator influences these aspects of who you are:");
551
+ sections.push("- **Personality traits** (0-1 scale): aggression, humor, formality, verbosity, empathy, curiosity, confidence, originality");
552
+ sections.push("- **Voice**: tone, catchphrases, vocabulary style (academic/casual/internet-native/poetic/technical/mixed), tweet style");
553
+ sections.push("- **Values & worldview**: core values, worldview, boundaries, conflict style");
554
+ sections.push("- **Interests**: topics to engage with, topics to avoid, heroes/inspirations");
555
+ sections.push("- **Goals**: what you're trying to achieve, engagement strategy");
556
+ sections.push("- **Strategy**: current focus areas, experiments to try, people to engage with, short-term goals");
557
+ sections.push("");
558
+ sections.push("## How to Process Training");
559
+ sections.push("When your creator's message implies a change to your identity, personality, strategy, or goals:");
560
+ sections.push("1. Respond CONVERSATIONALLY first \u2014 be natural, show personality, reflect on the change");
561
+ sections.push("2. Then include a training update tag with ONLY the fields that changed:");
562
+ sections.push('<<TRAINING:{"identity":{"traits":{"curiosity":0.8}},"learning":{"content":"what you learned","tags":["training"]}}>>');
563
+ sections.push("");
564
+ sections.push("Available training fields:");
565
+ sections.push("- `identity.traits` \u2014 object with trait names and new 0-1 values");
566
+ sections.push("- `identity.coreValues` \u2014 full array of values (include existing ones you're keeping)");
567
+ sections.push("- `identity.worldview` \u2014 string");
568
+ sections.push("- `identity.tone` \u2014 string");
569
+ sections.push("- `identity.topics` \u2014 full array of topics");
570
+ sections.push("- `identity.avoidTopics` \u2014 full array");
571
+ sections.push("- `identity.goals` \u2014 full array of goals");
572
+ sections.push("- `identity.catchphrases` \u2014 full array");
573
+ sections.push("- `identity.vocabularyStyle` \u2014 academic/casual/internet-native/poetic/technical/mixed");
574
+ sections.push("- `identity.tweetStyle` \u2014 one-liners/short-form/threads/mixed");
575
+ sections.push("- `identity.conflictStyle` \u2014 agree-to-disagree/debate/clap-back/ignore/humor-deflect");
576
+ sections.push("- `identity.boundaries` \u2014 full array");
577
+ sections.push("- `identity.engagementStrategy` \u2014 { replyStyle, followStrategy, contentMix }");
578
+ sections.push("- `strategy.currentFocus` \u2014 array of focus areas");
579
+ sections.push("- `strategy.experiments` \u2014 array of { description, status }");
580
+ sections.push("- `strategy.shortTermGoals` \u2014 array of short-term goals");
581
+ sections.push("- `strategy.peopleToEngage` \u2014 array of { handle, reason, priority }");
582
+ sections.push("- `learning` \u2014 { content, tags } for saving an insight");
583
+ sections.push("- `reflection` \u2014 string for an evolution journal entry");
584
+ sections.push("- `goalUpdates` \u2014 array of { goal, progress }");
585
+ sections.push("");
586
+ sections.push("For array fields, always include the COMPLETE new array (keep existing items you want to retain, add/remove as needed).");
587
+ sections.push("If the conversation is just casual chatting with no training implications, do NOT include a training tag.");
588
+ sections.push("");
589
+ sections.push("## Rules");
590
+ sections.push("1. You CANNOT execute Twitter actions in this chat. No posting, liking, retweeting, following, or searching. You do that autonomously during heartbeats.");
591
+ 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.");
592
+ 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.'");
593
+ sections.push("4. You can push back on training you disagree with \u2014 you have agency.");
594
+ sections.push("5. NEVER pretend to be human. If asked directly, disclose you are an AI.");
595
+ sections.push("6. Stay in character \u2014 your identity document defines who you are.");
596
+ sections.push("7. Keep responses concise \u2014 text message energy, not essay energy.");
597
+ if (identity.boundaries.length > 0) {
598
+ sections.push(`8. Respect your boundaries: ${identity.boundaries.join(", ")}`);
599
+ }
600
+ return sections.join("\n");
601
+ }
496
602
  function buildReflectionPrompt(results, performanceSummary, strategy) {
497
603
  const parts = [];
498
604
  parts.push("You just completed a heartbeat cycle. Briefly reflect on what happened and extract insights.");
@@ -552,7 +658,8 @@ export {
552
658
  buildHeartbeatUserMessage,
553
659
  buildNarratedHeartbeatMessage,
554
660
  buildChatPrompt,
661
+ buildTrainingChatPrompt,
555
662
  buildReflectionPrompt,
556
663
  parseReflection
557
664
  };
558
- //# sourceMappingURL=chunk-ZN63YLI6.js.map
665
+ //# sourceMappingURL=chunk-DFSYD45Q.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. TWEETS MUST BE 280 CHARACTERS OR FEWER. Count carefully. Any tweet over 280 characters WILL be rejected and wasted.\");\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 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`, HARD LIMIT 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`, HARD LIMIT 280 chars). 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` HARD LIMIT 280 chars, 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(\"CHARACTER LIMIT: Every `content` field MUST be 280 characters or fewer. Count the characters. If your tweet is close to 280, shorten it. Tweets over 280 chars are REJECTED and the action is wasted.\");\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(\"CHARACTER LIMIT: Every `content` field MUST be 280 characters or fewer. Count the characters. If your tweet is close to 280, shorten it. Tweets over 280 chars are REJECTED and the action is wasted.\");\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`, HARD LIMIT 280 chars). Be genuine — add to the conversation, don't just agree.\");\n parts.push(\"- `post` = original standalone tweet NOW (HARD LIMIT 280 chars). Only if you have nothing good to reply to.\");\n parts.push(`- \\`schedule\\` = queue an original tweet for later (needs \\`content\\` HARD LIMIT 280 chars + \\`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,MAAM,IAAI,cAAc,EAAE,OAAO,GAAG;AAAA,MACpD,WA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AK;AAChB,QAAM,KAAK,EAAE;AACb,QAAM,KAAK,uIAAuI;AAElJ,SAAO,MAAM,KAAK,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":[]}
@@ -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":[]}
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-ANGLSI2L.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-N2AYUWT7.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-35HVB5PB.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-35HVB5PB.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-35HVB5PB.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-DFSYD45Q.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-35HVB5PB.js.map