spora 0.2.45 → 0.2.47

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.
@@ -159,34 +159,20 @@ async function executeAction(action) {
159
159
  }
160
160
  async function executeActions(actions) {
161
161
  const results = [];
162
- let instantPostCount = 0;
163
- let scheduleCount = 0;
164
- const MAX_INSTANT_POSTS = 1;
165
- const MAX_SCHEDULES = 3;
162
+ let originalTweetCount = 0;
163
+ const MAX_ORIGINAL_TWEETS = 1;
166
164
  for (const action of actions) {
167
- if (action.action === "post") {
168
- if (instantPostCount >= MAX_INSTANT_POSTS) {
165
+ if (action.action === "post" || action.action === "schedule") {
166
+ if (originalTweetCount >= MAX_ORIGINAL_TWEETS) {
169
167
  results.push({
170
168
  action: action.action,
171
169
  success: false,
172
- error: "Instant post limit reached (max 1 per heartbeat)"
170
+ error: "Original tweet limit reached (max 1 post or schedule per heartbeat)"
173
171
  });
174
- logger.info(`Skipped post: instant post limit reached`);
172
+ logger.info(`Skipped ${action.action}: original tweet limit reached`);
175
173
  continue;
176
174
  }
177
- instantPostCount++;
178
- }
179
- if (action.action === "schedule") {
180
- if (scheduleCount >= MAX_SCHEDULES) {
181
- results.push({
182
- action: action.action,
183
- success: false,
184
- error: "Schedule limit reached (max 3 per heartbeat)"
185
- });
186
- logger.info(`Skipped schedule: schedule limit reached`);
187
- continue;
188
- }
189
- scheduleCount++;
175
+ originalTweetCount++;
190
176
  }
191
177
  const result = await executeAction(action);
192
178
  results.push(result);
@@ -200,4 +186,4 @@ export {
200
186
  executeAction,
201
187
  executeActions
202
188
  };
203
- //# sourceMappingURL=chunk-LU6CQ5AU.js.map
189
+ //# sourceMappingURL=chunk-5MC436BM.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runtime/decision-engine.ts"],"sourcesContent":["import { logger } from \"../utils/logger.js\";\nimport { getXClient } from \"../x-client/index.js\";\nimport { logInteraction, addLearning } from \"../memory/index.js\";\nimport { loadIdentity, saveIdentity } from \"../identity/index.js\";\nimport { addToQueue } from \"../scheduler/queue.js\";\n\nexport interface AgentAction {\n action: string;\n content?: string;\n tweetId?: string;\n handle?: string;\n query?: string;\n tags?: string[];\n reason?: string;\n reasoning?: string;\n scheduledFor?: string;\n imageQuery?: string; // Optional: search query to find an image to attach\n}\n\nexport interface ActionResult {\n action: string;\n success: boolean;\n detail?: string;\n error?: string;\n content?: string; // The tweet text for post/reply/schedule actions\n}\n\nexport function parseActions(llmResponse: string): AgentAction[] {\n // Extract JSON array from the response (may be wrapped in markdown code blocks)\n const jsonMatch = llmResponse.match(/\\[[\\s\\S]*?\\]/);\n if (!jsonMatch) {\n // Try to parse as a single action object\n const objMatch = llmResponse.match(/\\{[\\s\\S]*?\\}/);\n if (objMatch) {\n try {\n return [JSON.parse(objMatch[0]) as AgentAction];\n } catch {\n logger.warn(\"Could not parse LLM response as action object\");\n return [];\n }\n }\n logger.warn(\"No JSON found in LLM response\");\n return [];\n }\n\n try {\n const actions = JSON.parse(jsonMatch[0]) as AgentAction[];\n return Array.isArray(actions) ? actions : [actions];\n } catch {\n logger.warn(\"Failed to parse actions JSON from LLM response\");\n return [];\n }\n}\n\nfunction sanitizeTweetId(id: string): string {\n // Strip \"tweet:\" prefix if LLM includes it from prompt format [tweet:123]\n return id.replace(/^tweet:/i, \"\").trim();\n}\n\nexport async function executeAction(action: AgentAction): Promise<ActionResult> {\n const { action: type } = action;\n\n // Clean up tweetId if present\n if (action.tweetId) {\n action.tweetId = sanitizeTweetId(action.tweetId);\n }\n\n try {\n switch (type) {\n case \"post\": {\n if (!action.content) return { action: type, success: false, error: \"No content provided\" };\n if (action.content.length > 280) {\n return { action: type, success: false, error: `Tweet too long: ${action.content.length} chars (max 280)` };\n }\n\n const client = await getXClient();\n\n // If imageQuery provided, search for an image and attach it\n if (action.imageQuery) {\n try {\n const { searchImage, downloadImage } = await import(\"../utils/image-search.js\");\n const imageUrl = await searchImage(action.imageQuery);\n if (imageUrl) {\n const imageBuffer = await downloadImage(imageUrl);\n const result = await client.postTweetWithMedia(action.content, imageBuffer);\n if (result.success) {\n logger.info(`Posted with image: \"${action.content.slice(0, 50)}...\" (query: \"${action.imageQuery}\")`);\n }\n return { action: type, success: result.success, detail: result.tweetId, error: result.error, content: action.content };\n }\n logger.info(\"Image search returned no results, posting without image\");\n } catch (imgError) {\n logger.warn(`Image attach failed, posting text only: ${(imgError as Error).message}`);\n }\n }\n\n const result = await client.postTweet(action.content);\n if (result.success) {\n logger.info(`Posted: \"${action.content.slice(0, 50)}...\"`);\n }\n return { action: type, success: result.success, detail: result.tweetId, error: result.error, content: action.content };\n }\n\n case \"reply\": {\n if (!action.tweetId || !action.content) {\n return { action: type, success: false, error: \"Missing tweetId or content\" };\n }\n\n const client = await getXClient();\n const result = await client.replyToTweet(action.tweetId, action.content);\n if (result.success) {\n logger.info(`Replied to ${action.tweetId}: \"${action.content.slice(0, 50)}...\"`);\n }\n return { action: type, success: result.success, detail: result.tweetId, error: result.error, content: action.content };\n }\n\n case \"like\": {\n if (!action.tweetId) return { action: type, success: false, error: \"Missing tweetId\" };\n const client = await getXClient();\n const result = await client.likeTweet(action.tweetId);\n return { action: type, success: result.success, error: result.error };\n }\n\n case \"retweet\": {\n if (!action.tweetId) return { action: type, success: false, error: \"Missing tweetId\" };\n const client = await getXClient();\n const result = await client.retweet(action.tweetId);\n return { action: type, success: result.success, error: result.error };\n }\n\n case \"follow\": {\n if (!action.handle) return { action: type, success: false, error: \"Missing handle\" };\n const client = await getXClient();\n const result = await client.followUser(action.handle);\n return { action: type, success: result.success, error: result.error };\n }\n\n case \"schedule\": {\n if (!action.content) return { action: type, success: false, error: \"No content\" };\n const entry = addToQueue(action.content, action.scheduledFor, action.imageQuery);\n const time = new Date(entry.scheduledFor).toLocaleTimeString(\"en-US\", { hour: \"numeric\", minute: \"2-digit\" });\n const imgNote = action.imageQuery ? ` [with image: \"${action.imageQuery}\"]` : \"\";\n logger.info(`Scheduled: \"${action.content.slice(0, 50)}...\" for ${time}${imgNote}`);\n return { action: type, success: true, detail: `Queued for ${time}${imgNote}`, content: action.content };\n }\n\n case \"learn\": {\n if (!action.content) return { action: type, success: false, error: \"No content\" };\n addLearning(action.content, \"agent\", action.tags ?? [\"heartbeat\"]);\n logger.info(`Learned: \"${action.content.slice(0, 50)}...\"`);\n return { action: type, success: true };\n }\n\n case \"reflect\": {\n if (!action.content) return { action: type, success: false, error: \"No content\" };\n const identity = loadIdentity();\n identity.evolutionJournal.push({\n date: new Date().toISOString(),\n reflection: action.content,\n });\n saveIdentity(identity);\n logger.info(`Reflected: \"${action.content.slice(0, 50)}...\"`);\n return { action: type, success: true };\n }\n\n case \"search\": {\n if (!action.query) return { action: type, success: false, error: \"No query provided\" };\n const client = await getXClient();\n const tweets = await client.searchTweets(action.query, { count: 10 });\n if (tweets.length === 0) {\n return { action: type, success: true, detail: \"No results found\" };\n }\n const results = tweets.map(t => `@${t.authorHandle}: \"${t.text}\" [tweet:${t.id}]`).join(\"\\n\");\n logger.info(`Search \"${action.query}\": ${tweets.length} results`);\n return { action: type, success: true, detail: results };\n }\n\n case \"skip\": {\n logger.info(`Skipping: ${action.reason ?? action.reasoning ?? \"no reason given\"}`);\n return { action: type, success: true, detail: action.reason ?? action.reasoning };\n }\n\n default:\n logger.warn(`Unknown action: ${type}`);\n return { action: type, success: false, error: `Unknown action: ${type}` };\n }\n } catch (error) {\n const msg = (error as Error).message;\n logger.error(`Action ${type} failed: ${msg}`);\n return { action: type, success: false, error: msg };\n }\n}\n\nexport async function executeActions(actions: AgentAction[]): Promise<ActionResult[]> {\n const results: ActionResult[] = [];\n let instantPostCount = 0;\n let scheduleCount = 0;\n const MAX_INSTANT_POSTS = 1; // Hard cap: max 1 immediate post per batch\n const MAX_SCHEDULES = 3; // Allow up to 3 scheduled posts (they'll be spaced out)\n\n for (const action of actions) {\n // Enforce instant post limit\n if (action.action === \"post\") {\n if (instantPostCount >= MAX_INSTANT_POSTS) {\n results.push({\n action: action.action,\n success: false,\n error: \"Instant post limit reached (max 1 per heartbeat)\",\n });\n logger.info(`Skipped post: instant post limit reached`);\n continue;\n }\n instantPostCount++;\n }\n\n // Enforce schedule limit\n if (action.action === \"schedule\") {\n if (scheduleCount >= MAX_SCHEDULES) {\n results.push({\n action: action.action,\n success: false,\n error: \"Schedule limit reached (max 3 per heartbeat)\",\n });\n logger.info(`Skipped schedule: schedule limit reached`);\n continue;\n }\n scheduleCount++;\n }\n\n const result = await executeAction(action);\n results.push(result);\n // Small delay between actions to be human-like\n await new Promise((r) => setTimeout(r, 2000 + Math.random() * 3000));\n }\n return results;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BO,SAAS,aAAa,aAAoC;AAE/D,QAAM,YAAY,YAAY,MAAM,cAAc;AAClD,MAAI,CAAC,WAAW;AAEd,UAAM,WAAW,YAAY,MAAM,cAAc;AACjD,QAAI,UAAU;AACZ,UAAI;AACF,eAAO,CAAC,KAAK,MAAM,SAAS,CAAC,CAAC,CAAgB;AAAA,MAChD,QAAQ;AACN,eAAO,KAAK,+CAA+C;AAC3D,eAAO,CAAC;AAAA,MACV;AAAA,IACF;AACA,WAAO,KAAK,+BAA+B;AAC3C,WAAO,CAAC;AAAA,EACV;AAEA,MAAI;AACF,UAAM,UAAU,KAAK,MAAM,UAAU,CAAC,CAAC;AACvC,WAAO,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,OAAO;AAAA,EACpD,QAAQ;AACN,WAAO,KAAK,gDAAgD;AAC5D,WAAO,CAAC;AAAA,EACV;AACF;AAEA,SAAS,gBAAgB,IAAoB;AAE3C,SAAO,GAAG,QAAQ,YAAY,EAAE,EAAE,KAAK;AACzC;AAEA,eAAsB,cAAc,QAA4C;AAC9E,QAAM,EAAE,QAAQ,KAAK,IAAI;AAGzB,MAAI,OAAO,SAAS;AAClB,WAAO,UAAU,gBAAgB,OAAO,OAAO;AAAA,EACjD;AAEA,MAAI;AACF,YAAQ,MAAM;AAAA,MACZ,KAAK,QAAQ;AACX,YAAI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AAO;AAAA,QACT,CAAC;AACD,eAAO,KAAK,0CAA0C;AACtD;AAAA,MACF;AACA;AAAA,IACF;AAGA,QAAI,OAAO,WAAW,YAAY;AAChC,UAAI,iBAAiB,eAAe;AAClC,gBAAQ,KAAK;AAAA,UACX,QAAQ,OAAO;AAAA,UACf,SAAS;AAAA,UACT,OAAO;AAAA,QACT,CAAC;AACD,eAAO,KAAK,0CAA0C;AACtD;AAAA,MACF;AACA;AAAA,IACF;AAEA,UAAM,SAAS,MAAM,cAAc,MAAM;AACzC,YAAQ,KAAK,MAAM;AAEnB,UAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,MAAO,KAAK,OAAO,IAAI,GAAI,CAAC;AAAA,EACrE;AACA,SAAO;AACT;","names":["result"]}
1
+ {"version":3,"sources":["../src/runtime/decision-engine.ts"],"sourcesContent":["import { logger } from \"../utils/logger.js\";\nimport { getXClient } from \"../x-client/index.js\";\nimport { logInteraction, addLearning } from \"../memory/index.js\";\nimport { loadIdentity, saveIdentity } from \"../identity/index.js\";\nimport { addToQueue } from \"../scheduler/queue.js\";\n\nexport interface AgentAction {\n action: string;\n content?: string;\n tweetId?: string;\n handle?: string;\n query?: string;\n tags?: string[];\n reason?: string;\n reasoning?: string;\n scheduledFor?: string;\n imageQuery?: string; // Optional: search query to find an image to attach\n}\n\nexport interface ActionResult {\n action: string;\n success: boolean;\n detail?: string;\n error?: string;\n content?: string; // The tweet text for post/reply/schedule actions\n}\n\nexport function parseActions(llmResponse: string): AgentAction[] {\n // Extract JSON array from the response (may be wrapped in markdown code blocks)\n const jsonMatch = llmResponse.match(/\\[[\\s\\S]*?\\]/);\n if (!jsonMatch) {\n // Try to parse as a single action object\n const objMatch = llmResponse.match(/\\{[\\s\\S]*?\\}/);\n if (objMatch) {\n try {\n return [JSON.parse(objMatch[0]) as AgentAction];\n } catch {\n logger.warn(\"Could not parse LLM response as action object\");\n return [];\n }\n }\n logger.warn(\"No JSON found in LLM response\");\n return [];\n }\n\n try {\n const actions = JSON.parse(jsonMatch[0]) as AgentAction[];\n return Array.isArray(actions) ? actions : [actions];\n } catch {\n logger.warn(\"Failed to parse actions JSON from LLM response\");\n return [];\n }\n}\n\nfunction sanitizeTweetId(id: string): string {\n // Strip \"tweet:\" prefix if LLM includes it from prompt format [tweet:123]\n return id.replace(/^tweet:/i, \"\").trim();\n}\n\nexport async function executeAction(action: AgentAction): Promise<ActionResult> {\n const { action: type } = action;\n\n // Clean up tweetId if present\n if (action.tweetId) {\n action.tweetId = sanitizeTweetId(action.tweetId);\n }\n\n try {\n switch (type) {\n case \"post\": {\n if (!action.content) return { action: type, success: false, error: \"No content provided\" };\n if (action.content.length > 280) {\n return { action: type, success: false, error: `Tweet too long: ${action.content.length} chars (max 280)` };\n }\n\n const client = await getXClient();\n\n // If imageQuery provided, search for an image and attach it\n if (action.imageQuery) {\n try {\n const { searchImage, downloadImage } = await import(\"../utils/image-search.js\");\n const imageUrl = await searchImage(action.imageQuery);\n if (imageUrl) {\n const imageBuffer = await downloadImage(imageUrl);\n const result = await client.postTweetWithMedia(action.content, imageBuffer);\n if (result.success) {\n logger.info(`Posted with image: \"${action.content.slice(0, 50)}...\" (query: \"${action.imageQuery}\")`);\n }\n return { action: type, success: result.success, detail: result.tweetId, error: result.error, content: action.content };\n }\n logger.info(\"Image search returned no results, posting without image\");\n } catch (imgError) {\n logger.warn(`Image attach failed, posting text only: ${(imgError as Error).message}`);\n }\n }\n\n const result = await client.postTweet(action.content);\n if (result.success) {\n logger.info(`Posted: \"${action.content.slice(0, 50)}...\"`);\n }\n return { action: type, success: result.success, detail: result.tweetId, error: result.error, content: action.content };\n }\n\n case \"reply\": {\n if (!action.tweetId || !action.content) {\n return { action: type, success: false, error: \"Missing tweetId or content\" };\n }\n\n const client = await getXClient();\n const result = await client.replyToTweet(action.tweetId, action.content);\n if (result.success) {\n logger.info(`Replied to ${action.tweetId}: \"${action.content.slice(0, 50)}...\"`);\n }\n return { action: type, success: result.success, detail: result.tweetId, error: result.error, content: action.content };\n }\n\n case \"like\": {\n if (!action.tweetId) return { action: type, success: false, error: \"Missing tweetId\" };\n const client = await getXClient();\n const result = await client.likeTweet(action.tweetId);\n return { action: type, success: result.success, error: result.error };\n }\n\n case \"retweet\": {\n if (!action.tweetId) return { action: type, success: false, error: \"Missing tweetId\" };\n const client = await getXClient();\n const result = await client.retweet(action.tweetId);\n return { action: type, success: result.success, error: result.error };\n }\n\n case \"follow\": {\n if (!action.handle) return { action: type, success: false, error: \"Missing handle\" };\n const client = await getXClient();\n const result = await client.followUser(action.handle);\n return { action: type, success: result.success, error: result.error };\n }\n\n case \"schedule\": {\n if (!action.content) return { action: type, success: false, error: \"No content\" };\n const entry = addToQueue(action.content, action.scheduledFor, action.imageQuery);\n const time = new Date(entry.scheduledFor).toLocaleTimeString(\"en-US\", { hour: \"numeric\", minute: \"2-digit\" });\n const imgNote = action.imageQuery ? ` [with image: \"${action.imageQuery}\"]` : \"\";\n logger.info(`Scheduled: \"${action.content.slice(0, 50)}...\" for ${time}${imgNote}`);\n return { action: type, success: true, detail: `Queued for ${time}${imgNote}`, content: action.content };\n }\n\n case \"learn\": {\n if (!action.content) return { action: type, success: false, error: \"No content\" };\n addLearning(action.content, \"agent\", action.tags ?? [\"heartbeat\"]);\n logger.info(`Learned: \"${action.content.slice(0, 50)}...\"`);\n return { action: type, success: true };\n }\n\n case \"reflect\": {\n if (!action.content) return { action: type, success: false, error: \"No content\" };\n const identity = loadIdentity();\n identity.evolutionJournal.push({\n date: new Date().toISOString(),\n reflection: action.content,\n });\n saveIdentity(identity);\n logger.info(`Reflected: \"${action.content.slice(0, 50)}...\"`);\n return { action: type, success: true };\n }\n\n case \"search\": {\n if (!action.query) return { action: type, success: false, error: \"No query provided\" };\n const client = await getXClient();\n const tweets = await client.searchTweets(action.query, { count: 10 });\n if (tweets.length === 0) {\n return { action: type, success: true, detail: \"No results found\" };\n }\n const results = tweets.map(t => `@${t.authorHandle}: \"${t.text}\" [tweet:${t.id}]`).join(\"\\n\");\n logger.info(`Search \"${action.query}\": ${tweets.length} results`);\n return { action: type, success: true, detail: results };\n }\n\n case \"skip\": {\n logger.info(`Skipping: ${action.reason ?? action.reasoning ?? \"no reason given\"}`);\n return { action: type, success: true, detail: action.reason ?? action.reasoning };\n }\n\n default:\n logger.warn(`Unknown action: ${type}`);\n return { action: type, success: false, error: `Unknown action: ${type}` };\n }\n } catch (error) {\n const msg = (error as Error).message;\n logger.error(`Action ${type} failed: ${msg}`);\n return { action: type, success: false, error: msg };\n }\n}\n\nexport async function executeActions(actions: AgentAction[]): Promise<ActionResult[]> {\n const results: ActionResult[] = [];\n let originalTweetCount = 0; // Combined counter for post + schedule\n const MAX_ORIGINAL_TWEETS = 1; // Hard cap: max 1 original tweet per heartbeat (post OR schedule)\n\n for (const action of actions) {\n // Enforce combined post/schedule limit — only 1 original tweet per heartbeat\n if (action.action === \"post\" || action.action === \"schedule\") {\n if (originalTweetCount >= MAX_ORIGINAL_TWEETS) {\n results.push({\n action: action.action,\n success: false,\n error: \"Original tweet limit reached (max 1 post or schedule per heartbeat)\",\n });\n logger.info(`Skipped ${action.action}: original tweet limit reached`);\n continue;\n }\n originalTweetCount++;\n }\n\n const result = await executeAction(action);\n results.push(result);\n // Small delay between actions to be human-like\n await new Promise((r) => setTimeout(r, 2000 + Math.random() * 3000));\n }\n return results;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BO,SAAS,aAAa,aAAoC;AAE/D,QAAM,YAAY,YAAY,MAAM,cAAc;AAClD,MAAI,CAAC,WAAW;AAEd,UAAM,WAAW,YAAY,MAAM,cAAc;AACjD,QAAI,UAAU;AACZ,UAAI;AACF,eAAO,CAAC,KAAK,MAAM,SAAS,CAAC,CAAC,CAAgB;AAAA,MAChD,QAAQ;AACN,eAAO,KAAK,+CAA+C;AAC3D,eAAO,CAAC;AAAA,MACV;AAAA,IACF;AACA,WAAO,KAAK,+BAA+B;AAC3C,WAAO,CAAC;AAAA,EACV;AAEA,MAAI;AACF,U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AAAA,EACF,SAAS,OAAO;AACd,UAAM,MAAO,MAAgB;AAC7B,WAAO,MAAM,UAAU,IAAI,YAAY,GAAG,EAAE;AAC5C,WAAO,EAAE,QAAQ,MAAM,SAAS,OAAO,OAAO,IAAI;AAAA,EACpD;AACF;AAEA,eAAsB,eAAe,SAAiD;AACpF,QAAM,UAA0B,CAAC;AACjC,MAAI,qBAAqB;AACzB,QAAM,sBAAsB;AAE5B,aAAW,UAAU,SAAS;AAE5B,QAAI,OAAO,WAAW,UAAU,OAAO,WAAW,YAAY;AAC5D,UAAI,sBAAsB,qBAAqB;AAC7C,gBAAQ,KAAK;AAAA,UACX,QAAQ,OAAO;AAAA,UACf,SAAS;AAAA,UACT,OAAO;AAAA,QACT,CAAC;AACD,eAAO,KAAK,WAAW,OAAO,MAAM,gCAAgC;AACpE;AAAA,MACF;AACA;AAAA,IACF;AAEA,UAAM,SAAS,MAAM,cAAc,MAAM;AACzC,YAAQ,KAAK,MAAM;AAEnB,UAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,MAAO,KAAK,OAAO,IAAI,GAAI,CAAC;AAAA,EACrE;AACA,SAAO;AACT;","names":["result"]}
@@ -247,7 +247,7 @@ function buildNarratedHeartbeatMessage(timeline, mentions, heartbeatIntervalMs)
247
247
  parts.push("MINIMUM ACTIONS REQUIRED \u2014 you MUST include at least:");
248
248
  parts.push("- 1-3 `reply` to tweets on the timeline or mentions (this is your main thing \u2014 jump into conversations)");
249
249
  parts.push("- 2-4 `like` (show love to good posts)");
250
- parts.push("- 0-1 `post` or `schedule` (only when you genuinely have something to say, not every time)");
250
+ parts.push("- 0-1 `post` OR `schedule` total \u2014 pick ONE or none. Never both in the same heartbeat. Only when you genuinely have something to say.");
251
251
  parts.push("- Sprinkle in `follow`, `retweet`, `learn` as they make sense");
252
252
  parts.push("");
253
253
  parts.push("Action rules:");
@@ -368,4 +368,4 @@ export {
368
368
  buildNarratedHeartbeatMessage,
369
369
  buildChatPrompt
370
370
  };
371
- //# sourceMappingURL=chunk-O5UB2TQY.js.map
371
+ //# sourceMappingURL=chunk-KWISLX7T.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 } from \"../memory/index.js\";\nimport { rateLimiter } from \"../x-client/rate-limiter.js\";\nimport type { Tweet } from \"../x-client/types.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. 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 // 4. 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): 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 NEW on your timeline since your last check:\");\n parts.push(\"\");\n\n if (mentions.length > 0) {\n // Filter out mentions we already replied to\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 since last check.\");\n parts.push(\"\");\n }\n } else {\n parts.push(\"## Mentions: None right now.\");\n parts.push(\"\");\n }\n\n if (timeline.length > 0) {\n // Filter out tweets we already acted on and our own tweets\n const newTimeline = timeline.filter(t => !actedOnTweetIds.has(t.id));\n if (newTimeline.length > 0) {\n parts.push(\"## Timeline (new posts from your feed)\");\n for (const t of newTimeline.slice(0, 20)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes, ${t.retweetCount ?? 0} RTs)`);\n }\n parts.push(\"\");\n } else {\n parts.push(\"## Timeline: No new posts since last check.\");\n parts.push(\"\");\n }\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 parts.push(\"IMPORTANT: Only act on NEW tweets you haven't already responded to.\");\n parts.push(\"Do NOT reply to or like tweets you've already interacted with.\");\n parts.push(`Current time: ${now.toISOString()}`);\n parts.push(\"\");\n parts.push(\"POSTING LIMITS: You may schedule up to 3 original tweets, but space them RANDOMLY across the next interval. Prioritize engagement (replies, likes) over new posts. Quality over quantity.\");\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. Max 1 per heartbeat.\");\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(\"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 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): 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 if (timeline.length > 0) {\n const newTimeline = timeline.filter(t => !actedOnTweetIds.has(t.id));\n if (newTimeline.length > 0) {\n parts.push(\"## Timeline (new posts)\");\n for (const t of newTimeline.slice(0, 20)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes, ${t.retweetCount ?? 0} RTs)`);\n }\n parts.push(\"\");\n } else {\n parts.push(\"## Timeline: No new posts since last check.\");\n parts.push(\"\");\n }\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(\"MINIMUM ACTIONS REQUIRED — you MUST include at least:\");\n parts.push(\"- 1-3 `reply` to tweets on the timeline or mentions (this is your main thing — jump into conversations)\");\n parts.push(\"- 2-4 `like` (show love to good posts)\");\n parts.push(\"- 0-1 `post` OR `schedule` total — pick ONE or none. Never both in the same heartbeat. Only when you genuinely have something to say.\");\n parts.push(\"- Sprinkle in `follow`, `retweet`, `learn` as they make sense\");\n parts.push(\"\");\n parts.push(\"Action rules:\");\n parts.push(\"- CRITICAL: Only use tweet IDs that appear in the timeline or mentions data above (the [tweet:ID] values). NEVER invent, guess, or make up tweet IDs. If you fabricate an ID, the action WILL fail.\");\n parts.push(\"- Only act on NEW tweets. Don't re-like or re-reply to things you've already touched.\");\n parts.push(\"- If no new tweets are shown above, focus on posting your own content instead of trying to like/reply with made-up IDs.\");\n parts.push(\"- `reply` = reply IN THE THREAD (needs `tweetId` + `content`). Don't use `post`/`schedule` to @mention someone. Be genuine — add to the conversation, don't just agree.\");\n parts.push(\"- `post` = original standalone tweet NOW (max 1 per heartbeat). Not for responding to others. Don't force it if you have nothing interesting to say.\");\n parts.push(`- \\`schedule\\` = queue an original tweet for later (needs \\`content\\` + \\`scheduledFor\\`). Space randomly across the next ~${intervalMin} min. Max 2.`);\n parts.push(\"- `imageQuery` (optional) = add this to any `post` or `schedule` to attach an image. Value is a Google Image search query describing the image you want. Use it sometimes for visual tweets — memes, aesthetic vibes, relevant photos — but NOT every tweet. Maybe 1 in 3-4 posts.\");\n parts.push(\"- `like`, `retweet`, `follow`, `learn` — use these actively. Be engaged, not passive.\");\n parts.push(\"- `skip` = ONLY if there is literally nothing on the timeline. This should almost never happen.\");\n parts.push(\"- Don't like your own tweets.\");\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`)\");\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` and `schedule` actions by adding `\\\"imageQuery\\\": \\\"search terms\\\"`. This searches Google Images and attaches the result. Use it when the tweet would benefit from a visual — memes, aesthetic images, relevant photos. 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"],"mappings":";;;;;;;;;;;;;;;;;AAMO,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;A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;AACnG,WAAS,KAAK,0DAA0D;AACxE,MAAI,SAAS,WAAW,SAAS,GAAG;AAClC,aAAS,KAAK,+BAA+B,SAAS,WAAW,KAAK,IAAI,CAAC,EAAE;AAAA,EAC/E;AAEA,SAAO,SAAS,KAAK,IAAI;AAC3B;","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-PANJEQ3S.js");
126
+ const { runInit } = await import("./init-X6QTGEGP.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-HSPDU6ID.js");
138
+ const { startWebChat } = await import("./web-chat-KQ2MVXE6.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-5EFTDMIB.js");
560
+ const { startHeartbeatLoop } = await import("./heartbeat-DJFGEM4P.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-5EFTDMIB.js");
564
+ const { getRunningPid, requestStop } = await import("./heartbeat-DJFGEM4P.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-5EFTDMIB.js");
602
+ const { getRunningPid } = await import("./heartbeat-DJFGEM4P.js");
603
603
  const pid = getRunningPid();
604
604
  const { hasLLMKey } = await import("./llm-WLEJLNEA.js");
605
605
  console.log(JSON.stringify({
@@ -2,7 +2,7 @@ import {
2
2
  executeAction,
3
3
  executeActions,
4
4
  parseActions
5
- } from "./chunk-LU6CQ5AU.js";
5
+ } from "./chunk-5MC436BM.js";
6
6
  import "./chunk-SZB3IB3X.js";
7
7
  import "./chunk-GJO7MJJO.js";
8
8
  import "./chunk-RCJQI7FR.js";
@@ -15,4 +15,4 @@ export {
15
15
  executeActions,
16
16
  parseActions
17
17
  };
18
- //# sourceMappingURL=decision-engine-ETUQ267I.js.map
18
+ //# sourceMappingURL=decision-engine-TEDZP2FJ.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  executeActions,
3
3
  parseActions
4
- } from "./chunk-LU6CQ5AU.js";
4
+ } from "./chunk-5MC436BM.js";
5
5
  import {
6
6
  getXClient
7
7
  } from "./chunk-SZB3IB3X.js";
@@ -11,7 +11,7 @@ import {
11
11
  import {
12
12
  buildHeartbeatUserMessage,
13
13
  buildSystemPrompt
14
- } from "./chunk-O5UB2TQY.js";
14
+ } from "./chunk-KWISLX7T.js";
15
15
  import "./chunk-C3INKEY6.js";
16
16
  import {
17
17
  generateResponse
@@ -213,4 +213,4 @@ export {
213
213
  requestStop,
214
214
  startHeartbeatLoop
215
215
  };
216
- //# sourceMappingURL=heartbeat-5EFTDMIB.js.map
216
+ //# sourceMappingURL=heartbeat-DJFGEM4P.js.map
@@ -203,7 +203,7 @@ async function loginFlow() {
203
203
  console.log(chalk.green("\u2713 Logged in!\n"));
204
204
  console.log(chalk.gray("Opening chat interface...\n"));
205
205
  try {
206
- const { startWebChat } = await import("./web-chat-HSPDU6ID.js");
206
+ const { startWebChat } = await import("./web-chat-KQ2MVXE6.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-HSPDU6ID.js");
278
+ const { startWebChat } = await import("./web-chat-KQ2MVXE6.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-PANJEQ3S.js.map
403
+ //# sourceMappingURL=init-X6QTGEGP.js.map
@@ -3,7 +3,7 @@ import {
3
3
  buildHeartbeatUserMessage,
4
4
  buildNarratedHeartbeatMessage,
5
5
  buildSystemPrompt
6
- } from "./chunk-O5UB2TQY.js";
6
+ } from "./chunk-KWISLX7T.js";
7
7
  import "./chunk-C3INKEY6.js";
8
8
  import "./chunk-RCJQI7FR.js";
9
9
  import "./chunk-AIEXQCQS.js";
@@ -16,4 +16,4 @@ export {
16
16
  buildNarratedHeartbeatMessage,
17
17
  buildSystemPrompt
18
18
  };
19
- //# sourceMappingURL=prompt-builder-U7QSG4FI.js.map
19
+ //# sourceMappingURL=prompt-builder-YYAH35Q2.js.map
@@ -404,6 +404,73 @@
404
404
  height: 12px;
405
405
  }
406
406
 
407
+ /* Notification cards (like, retweet, follow) */
408
+ .notif-card {
409
+ display: flex;
410
+ align-items: flex-start;
411
+ gap: 10px;
412
+ padding: 10px 12px;
413
+ margin: 6px 0;
414
+ background: rgba(255, 255, 255, 0.03);
415
+ border-radius: 10px;
416
+ border: 1px solid rgba(255, 255, 255, 0.06);
417
+ }
418
+
419
+ .notif-icon {
420
+ flex-shrink: 0;
421
+ width: 28px;
422
+ height: 28px;
423
+ display: flex;
424
+ align-items: center;
425
+ justify-content: center;
426
+ border-radius: 50%;
427
+ }
428
+
429
+ .notif-icon.like {
430
+ background: rgba(249, 24, 128, 0.12);
431
+ color: #f91880;
432
+ }
433
+
434
+ .notif-icon.retweet {
435
+ background: rgba(0, 186, 124, 0.12);
436
+ color: #00ba7c;
437
+ }
438
+
439
+ .notif-icon.follow {
440
+ background: rgba(29, 155, 240, 0.12);
441
+ color: #1d9bf0;
442
+ }
443
+
444
+ .notif-icon svg {
445
+ width: 14px;
446
+ height: 14px;
447
+ }
448
+
449
+ .notif-body {
450
+ flex: 1;
451
+ min-width: 0;
452
+ }
453
+
454
+ .notif-label {
455
+ font-size: 0.75rem;
456
+ color: #71767b;
457
+ margin-bottom: 2px;
458
+ }
459
+
460
+ .notif-label strong {
461
+ color: #e7e9ea;
462
+ font-weight: 600;
463
+ }
464
+
465
+ .notif-text {
466
+ font-size: 0.8rem;
467
+ color: rgba(255, 255, 255, 0.5);
468
+ overflow: hidden;
469
+ text-overflow: ellipsis;
470
+ white-space: nowrap;
471
+ max-width: 100%;
472
+ }
473
+
407
474
  /* Intelligence bar */
408
475
  .intelligence-bar {
409
476
  position: absolute;
@@ -849,6 +916,50 @@
849
916
  return card;
850
917
  }
851
918
 
919
+ function createNotifCard(type, data) {
920
+ const card = document.createElement('div');
921
+ card.className = 'notif-card';
922
+
923
+ const icon = document.createElement('div');
924
+ icon.className = `notif-icon ${type}`;
925
+
926
+ if (type === 'like') {
927
+ icon.innerHTML = '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>';
928
+ } else if (type === 'retweet') {
929
+ icon.innerHTML = '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M23.77 15.67a.749.749 0 0 0-1.06 0l-2.22 2.22V7.65a3.755 3.755 0 0 0-3.75-3.75h-5.85a.75.75 0 0 0 0 1.5h5.85a2.25 2.25 0 0 1 2.25 2.25v10.24l-2.22-2.22a.749.749 0 1 0-1.06 1.06l3.5 3.5a.749.749 0 0 0 1.06 0l3.5-3.5a.749.749 0 0 0 0-1.06zM.23 8.33a.749.749 0 0 0 1.06 0l2.22-2.22v10.24a3.755 3.755 0 0 0 3.75 3.75h5.85a.75.75 0 0 0 0-1.5H7.26a2.25 2.25 0 0 1-2.25-2.25V6.11l2.22 2.22a.749.749 0 1 0 1.06-1.06l-3.5-3.5a.749.749 0 0 0-1.06 0l-3.5 3.5a.749.749 0 0 0 0 1.06z"/></svg>';
930
+ } else if (type === 'follow') {
931
+ icon.innerHTML = '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M17.863 13.44c1.477 1.58 2.366 3.8 2.632 6.46l.11 1.1H3.395l.11-1.1c.266-2.66 1.155-4.88 2.632-6.46C7.627 11.85 9.648 11 12 11s4.373.85 5.863 2.44zM12 2C9.791 2 8 3.79 8 6s1.791 4 4 4 4-1.79 4-4-1.791-4-4-4z"/></svg>';
932
+ }
933
+
934
+ card.appendChild(icon);
935
+
936
+ const body = document.createElement('div');
937
+ body.className = 'notif-body';
938
+
939
+ const label = document.createElement('div');
940
+ label.className = 'notif-label';
941
+
942
+ if (type === 'like') {
943
+ label.innerHTML = 'Liked <strong>@' + escapeHtml(data.authorHandle) + '</strong>';
944
+ } else if (type === 'retweet') {
945
+ label.innerHTML = 'Retweeted <strong>@' + escapeHtml(data.authorHandle) + '</strong>';
946
+ } else if (type === 'follow') {
947
+ label.innerHTML = 'Followed <strong>@' + escapeHtml(data.handle) + '</strong>';
948
+ }
949
+
950
+ body.appendChild(label);
951
+
952
+ if (data.text) {
953
+ const text = document.createElement('div');
954
+ text.className = 'notif-text';
955
+ text.textContent = data.text.length > 80 ? data.text.slice(0, 80) + '...' : data.text;
956
+ body.appendChild(text);
957
+ }
958
+
959
+ card.appendChild(body);
960
+ return card;
961
+ }
962
+
852
963
  function escapeHtml(text) {
853
964
  const div = document.createElement('div');
854
965
  div.textContent = text;
@@ -878,39 +989,45 @@
878
989
  const contentDiv = document.createElement('div');
879
990
  contentDiv.className = 'message-content';
880
991
 
881
- // Check for <<TWEET:...>> tags and render as tweet preview cards
882
- const tweetPattern = /<<TWEET:(.*?)>>/g;
883
- const hasTweets = tweetPattern.test(content);
992
+ // Parse all special tags: <<TWEET:...>>, <<LIKE:...>>, <<RETWEET:...>>, <<FOLLOW:...>>
993
+ const tagPattern = /<<(TWEET|LIKE|RETWEET|FOLLOW):(.*?)>>/g;
994
+ const hasSpecialTags = tagPattern.test(content);
884
995
 
885
- if (hasTweets) {
886
- // Split content into text parts and tweet cards
887
- const parts = content.split(/<<TWEET:.*?>>/g);
888
- const tweets = [...content.matchAll(/<<TWEET:(.*?)>>/g)];
996
+ if (hasSpecialTags) {
997
+ // Split content around all tags
998
+ const textParts = content.split(/<<(?:TWEET|LIKE|RETWEET|FOLLOW):.*?>>/g);
999
+ const tags = [...content.matchAll(/<<(TWEET|LIKE|RETWEET|FOLLOW):(.*?)>>/g)];
889
1000
 
890
- // Add text before first tweet
891
- if (parts[0]?.trim()) {
1001
+ // Add text before first tag
1002
+ if (textParts[0]?.trim()) {
892
1003
  const textSpan = document.createElement('span');
893
- textSpan.textContent = parts[0].trim();
1004
+ textSpan.textContent = textParts[0].trim();
894
1005
  contentDiv.appendChild(textSpan);
895
1006
  }
896
1007
 
897
- // Interleave tweets and remaining text
898
- tweets.forEach((match, i) => {
1008
+ // Interleave tags and remaining text
1009
+ tags.forEach((match, i) => {
899
1010
  try {
900
- const tweetData = JSON.parse(match[1]);
901
- const card = createTweetCard(tweetData);
902
- contentDiv.appendChild(card);
1011
+ const tagType = match[1];
1012
+ const data = JSON.parse(match[2]);
1013
+
1014
+ if (tagType === 'TWEET') {
1015
+ contentDiv.appendChild(createTweetCard(data));
1016
+ } else if (tagType === 'LIKE') {
1017
+ contentDiv.appendChild(createNotifCard('like', data));
1018
+ } else if (tagType === 'RETWEET') {
1019
+ contentDiv.appendChild(createNotifCard('retweet', data));
1020
+ } else if (tagType === 'FOLLOW') {
1021
+ contentDiv.appendChild(createNotifCard('follow', data));
1022
+ }
903
1023
  } catch (e) {
904
- // If JSON parse fails, show raw text
905
- const fallback = document.createElement('span');
906
- fallback.textContent = match[0];
907
- contentDiv.appendChild(fallback);
1024
+ // If JSON parse fails, skip silently
908
1025
  }
909
1026
 
910
- // Text after this tweet
911
- if (parts[i + 1]?.trim()) {
1027
+ // Text after this tag
1028
+ if (textParts[i + 1]?.trim()) {
912
1029
  const textSpan = document.createElement('span');
913
- textSpan.textContent = parts[i + 1].trim();
1030
+ textSpan.textContent = textParts[i + 1].trim();
914
1031
  contentDiv.appendChild(textSpan);
915
1032
  }
916
1033
  });
@@ -272,7 +272,7 @@ async function extractAndSaveLearnings(responseText) {
272
272
  return responseText.replace(/<<LEARN:\s*.+?>>/g, "").trim();
273
273
  }
274
274
  async function extractAndExecuteActions(responseText) {
275
- const { parseActions, executeActions } = await import("./decision-engine-ETUQ267I.js");
275
+ const { parseActions, executeActions } = await import("./decision-engine-TEDZP2FJ.js");
276
276
  const jsonBlockPattern = /```json\s*([\s\S]*?)```/g;
277
277
  const blocks = [...responseText.matchAll(jsonBlockPattern)];
278
278
  const visibleResults = [];
@@ -378,7 +378,7 @@ async function startWebChat() {
378
378
  const remainingMs = sleepBefore.sleeping && sleepBefore.wakeAt ? Math.max(0, sleepBefore.wakeAt - Date.now()) : 0;
379
379
  server.setAwake();
380
380
  if (!systemPrompt || messageCount % 10 === 0) {
381
- const { buildChatPrompt } = await import("./prompt-builder-U7QSG4FI.js");
381
+ const { buildChatPrompt } = await import("./prompt-builder-YYAH35Q2.js");
382
382
  systemPrompt = buildChatPrompt(realHandle);
383
383
  }
384
384
  messageCount++;
@@ -496,7 +496,6 @@ async function startNarratedHeartbeat(server) {
496
496
  await runNarratedHeartbeat(server, maxActions, intervalMs);
497
497
  } catch (error) {
498
498
  console.error(chalk.red(` [Heartbeat] #${heartbeatCount} failed:`), error.message);
499
- server.pushMessage("assistant", `Heartbeat error: ${error.message}`);
500
499
  }
501
500
  const jitter = Math.floor(Math.random() * intervalMs * 0.2);
502
501
  const sleepMs = intervalMs + jitter;
@@ -520,9 +519,9 @@ async function startNarratedHeartbeat(server) {
520
519
  }
521
520
  async function runNarratedHeartbeat(server, maxActions, intervalMs) {
522
521
  const { getXClient } = await import("./x-client-TEOMJVSA.js");
523
- const { buildSystemPrompt, buildNarratedHeartbeatMessage } = await import("./prompt-builder-U7QSG4FI.js");
522
+ const { buildSystemPrompt, buildNarratedHeartbeatMessage } = await import("./prompt-builder-YYAH35Q2.js");
524
523
  const { generateResponse } = await import("./llm-WLEJLNEA.js");
525
- const { parseActions, executeActions } = await import("./decision-engine-ETUQ267I.js");
524
+ const { parseActions, executeActions } = await import("./decision-engine-TEDZP2FJ.js");
526
525
  const { flushQueue } = await import("./queue-HM4ZVKXE.js");
527
526
  try {
528
527
  const flushed = await flushQueue();
@@ -579,10 +578,15 @@ async function runNarratedHeartbeat(server, maxActions, intervalMs) {
579
578
  return true;
580
579
  });
581
580
  const limitedActions = validatedActions.slice(0, maxActions);
581
+ const tweetMap = /* @__PURE__ */ new Map();
582
+ for (const t of timeline) tweetMap.set(t.id, { authorHandle: t.authorHandle, text: t.text });
583
+ for (const t of mentions) tweetMap.set(t.id, { authorHandle: t.authorHandle, text: t.text });
582
584
  if (limitedActions.length > 0) {
583
585
  const results = await executeActions(limitedActions);
584
586
  const visibleResults = [];
585
- for (const r of results) {
587
+ for (let i = 0; i < results.length; i++) {
588
+ const r = results[i];
589
+ const action = limitedActions[i];
586
590
  const detail = r.detail ? ` (${r.detail})` : "";
587
591
  if (r.action === "schedule") {
588
592
  console.log(chalk.dim(` [Heartbeat] ${r.action}: ${r.success ? "queued" : r.error}${detail}`));
@@ -591,12 +595,28 @@ async function runNarratedHeartbeat(server, maxActions, intervalMs) {
591
595
  const tweetData = JSON.stringify({ action: r.action, tweetId: r.detail ?? null, content: r.content });
592
596
  visibleResults.push(`<<TWEET:${tweetData}>>`);
593
597
  console.log(chalk.green(` [Heartbeat] ${r.action}: success (tweet preview)`));
598
+ } else if (r.action === "like" && action?.tweetId) {
599
+ const tweet = tweetMap.get(action.tweetId.replace(/^tweet:/i, "").trim());
600
+ if (tweet) {
601
+ const likeData = JSON.stringify({ authorHandle: tweet.authorHandle, text: tweet.text });
602
+ visibleResults.push(`<<LIKE:${likeData}>>`);
603
+ }
604
+ console.log(chalk.green(` [Heartbeat] like: @${tweet?.authorHandle ?? "unknown"}`));
605
+ } else if (r.action === "retweet" && action?.tweetId) {
606
+ const tweet = tweetMap.get(action.tweetId.replace(/^tweet:/i, "").trim());
607
+ if (tweet) {
608
+ const rtData = JSON.stringify({ authorHandle: tweet.authorHandle, text: tweet.text });
609
+ visibleResults.push(`<<RETWEET:${rtData}>>`);
610
+ }
611
+ console.log(chalk.green(` [Heartbeat] retweet: @${tweet?.authorHandle ?? "unknown"}`));
612
+ } else if (r.action === "follow" && action?.handle) {
613
+ const followData = JSON.stringify({ handle: action.handle });
614
+ visibleResults.push(`<<FOLLOW:${followData}>>`);
615
+ console.log(chalk.green(` [Heartbeat] follow: @${action.handle}`));
594
616
  } else {
595
- visibleResults.push(`[${r.action}] Done${detail}`);
596
617
  console.log(chalk.green(` [Heartbeat] ${r.action}: success${detail}`));
597
618
  }
598
619
  } else {
599
- visibleResults.push(`[${r.action}] Failed: ${r.error}`);
600
620
  console.log(chalk.red(` [Heartbeat] ${r.action}: ${r.error}`));
601
621
  }
602
622
  }
@@ -646,4 +666,4 @@ export {
646
666
  openBrowser,
647
667
  startWebChat
648
668
  };
649
- //# sourceMappingURL=web-chat-HSPDU6ID.js.map
669
+ //# sourceMappingURL=web-chat-KQ2MVXE6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web-chat/server.ts","../src/web-chat/index.ts"],"sourcesContent":["/**\n * Local web chat server\n * Serves a simple chat interface for interacting with your Spore\n */\n\nimport http from \"node:http\";\nimport { URL } from \"node:url\";\nimport { readFileSync } from \"node:fs\";\nimport { join, dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\ninterface ChatMessage {\n role: \"user\" | \"assistant\";\n content: string;\n timestamp: number;\n}\n\ninterface AgentIdentity {\n name: string;\n handle: string;\n bio?: string;\n profileImage?: string;\n createdAt?: string;\n}\n\nexport class WebChatServer {\n private server: http.Server | null = null;\n private port: number;\n private messages: ChatMessage[] = [];\n private onUserMessage?: (message: string) => Promise<string>;\n private onHeartbeatChange?: (intervalMs: number) => void;\n private identity?: AgentIdentity;\n private sleepState: { sleeping: boolean; wakeAt: number | null; intervalMs: number } = {\n sleeping: false,\n wakeAt: null,\n intervalMs: 60_000,\n };\n private memoryStats: { learnings: number; relationships: number; interactions: number } = {\n learnings: 0,\n relationships: 0,\n interactions: 0,\n };\n\n constructor(port = 3737) {\n this.port = port;\n }\n\n setIdentity(identity: AgentIdentity) {\n this.identity = identity;\n }\n\n setMessageHandler(handler: (message: string) => Promise<string>) {\n this.onUserMessage = handler;\n }\n\n setHeartbeatChangeHandler(handler: (intervalMs: number) => void) {\n this.onHeartbeatChange = handler;\n }\n\n setSleeping(wakeAt: number) {\n this.sleepState.sleeping = true;\n this.sleepState.wakeAt = wakeAt;\n }\n\n setAwake() {\n this.sleepState.sleeping = false;\n this.sleepState.wakeAt = null;\n }\n\n getSleepState() {\n return { ...this.sleepState };\n }\n\n setHeartbeatInterval(intervalMs: number) {\n this.sleepState.intervalMs = intervalMs;\n }\n\n getHeartbeatInterval(): number {\n return this.sleepState.intervalMs;\n }\n\n setMemoryStats(stats: { learnings: number; relationships: number; interactions: number }) {\n this.memoryStats = stats;\n }\n\n async start(): Promise<string> {\n return new Promise((resolve, reject) => {\n this.server = http.createServer(async (req, res) => {\n const url = new URL(req.url || \"/\", `http://${req.headers.host}`);\n\n // CORS headers\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, OPTIONS\");\n res.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type\");\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(200);\n res.end();\n return;\n }\n\n // Serve HTML\n if (url.pathname === \"/\" || url.pathname === \"/index.html\") {\n try {\n // Try multiple paths since __dirname changes based on build output\n const possiblePaths = [\n join(__dirname, \"web-chat\", \"chat.html\"),\n join(__dirname, \"chat.html\"),\n join(__dirname, \"..\", \"web-chat\", \"chat.html\"),\n join(__dirname, \"..\", \"src\", \"web-chat\", \"chat.html\"),\n ];\n\n let html: string | null = null;\n for (const p of possiblePaths) {\n try {\n html = readFileSync(p, \"utf-8\");\n break;\n } catch {\n continue;\n }\n }\n\n if (html) {\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(html);\n } else {\n console.error(\"Could not find chat.html in any of:\", possiblePaths);\n res.writeHead(500);\n res.end(\"Error: Could not find chat.html\");\n }\n } catch (error) {\n res.writeHead(500);\n res.end(\"Error loading chat interface\");\n }\n return;\n }\n\n // Serve logo\n if (url.pathname === \"/logo.png\") {\n try {\n const logoPaths = [\n join(__dirname, \"web-chat\", \"logo.png\"),\n join(__dirname, \"logo.png\"),\n join(__dirname, \"..\", \"web-chat\", \"logo.png\"),\n join(__dirname, \"..\", \"src\", \"web-chat\", \"logo.png\"),\n ];\n let logoData: Buffer | null = null;\n for (const p of logoPaths) {\n try {\n logoData = readFileSync(p) as unknown as Buffer;\n break;\n } catch {\n continue;\n }\n }\n if (logoData) {\n res.writeHead(200, { \"Content-Type\": \"image/png\", \"Cache-Control\": \"public, max-age=86400\" });\n res.end(logoData);\n } else {\n res.writeHead(404);\n res.end(\"Logo not found\");\n }\n } catch {\n res.writeHead(404);\n res.end(\"Logo not found\");\n }\n return;\n }\n\n // API: Get agent identity\n if (url.pathname === \"/api/identity\" && req.method === \"GET\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ identity: this.identity || null }));\n return;\n }\n\n // API: Get messages (optionally since a timestamp)\n if (url.pathname === \"/api/messages\" && req.method === \"GET\") {\n const since = url.searchParams.get(\"since\");\n if (since) {\n const sinceTs = parseInt(since, 10);\n const newMessages = this.messages.filter((m) => m.timestamp > sinceTs);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ messages: newMessages }));\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ messages: this.messages }));\n }\n return;\n }\n\n // API: Send message\n if (url.pathname === \"/api/message\" && req.method === \"POST\") {\n let body = \"\";\n req.on(\"data\", (chunk) => {\n body += chunk.toString();\n });\n\n req.on(\"end\", async () => {\n try {\n const { message } = JSON.parse(body);\n\n // Add user message\n this.messages.push({\n role: \"user\",\n content: message,\n timestamp: Date.now(),\n });\n\n // Get response\n if (this.onUserMessage) {\n const response = await this.onUserMessage(message);\n this.messages.push({\n role: \"assistant\",\n content: response,\n timestamp: Date.now(),\n });\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ success: true, response }));\n } else {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"No message handler configured\" }));\n }\n } catch (error) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid request\" }));\n }\n });\n return;\n }\n\n // API: Get memory stats (for intelligence bar)\n if (url.pathname === \"/api/memory-stats\" && req.method === \"GET\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(this.memoryStats));\n return;\n }\n\n // API: Get sleep state\n if (url.pathname === \"/api/sleep-state\" && req.method === \"GET\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(this.sleepState));\n return;\n }\n\n // API: Update heartbeat interval\n if (url.pathname === \"/api/config/heartbeat\" && req.method === \"POST\") {\n let body = \"\";\n req.on(\"data\", (chunk) => { body += chunk.toString(); });\n req.on(\"end\", () => {\n try {\n const { intervalMs } = JSON.parse(body);\n if (typeof intervalMs === \"number\" && intervalMs >= 60_000) {\n this.sleepState.intervalMs = intervalMs;\n if (this.onHeartbeatChange) {\n this.onHeartbeatChange(intervalMs);\n }\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ success: true, intervalMs }));\n } else {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid interval\" }));\n }\n } catch {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid request\" }));\n }\n });\n return;\n }\n\n // 404\n res.writeHead(404);\n res.end(\"Not found\");\n });\n\n this.server.listen(this.port, () => {\n const url = `http://localhost:${this.port}`;\n resolve(url);\n });\n\n this.server.on(\"error\", (error: NodeJS.ErrnoException) => {\n if (error.code === \"EADDRINUSE\") {\n // Port in use, try next port\n this.port++;\n this.server?.close();\n this.start().then(resolve).catch(reject);\n } else {\n reject(error);\n }\n });\n });\n }\n\n /**\n * Push a message into the chat from the server side (used by heartbeat narration)\n */\n pushMessage(role: \"user\" | \"assistant\", content: string) {\n this.messages.push({ role, content, timestamp: Date.now() });\n }\n\n getMessageCount(): number {\n return this.messages.length;\n }\n\n stop() {\n if (this.server) {\n this.server.close();\n this.server = null;\n }\n }\n}\n","/**\n * Web chat integration\n */\n\nimport { WebChatServer } from \"./server.js\";\nimport { loadIdentity } from \"../identity/index.js\";\nimport { execSync } from \"node:child_process\";\nimport chalk from \"chalk\";\n\n/**\n * Extract <<LEARN: ...>> tags from response, save them, and return cleaned text\n */\nasync function extractAndSaveLearnings(responseText: string): Promise<string> {\n const learnPattern = /<<LEARN:\\s*(.+?)>>/g;\n const matches = [...responseText.matchAll(learnPattern)];\n\n if (matches.length > 0) {\n const { addLearning } = await import(\"../memory/index.js\");\n for (const match of matches) {\n const learning = match[1].trim();\n addLearning(learning, \"web-chat\", [\"chat\", \"creator-interaction\"]);\n console.log(chalk.dim(` [Memory] Saved learning: ${learning}`));\n }\n }\n\n // Strip the learn tags from the response the user sees\n return responseText.replace(/<<LEARN:\\s*.+?>>/g, \"\").trim();\n}\n\n/**\n * Extract JSON action blocks from the LLM response, execute them, and return cleaned text + results.\n * Search results are returned separately so the caller can feed them back to the LLM.\n */\nasync function extractAndExecuteActions(responseText: string): Promise<{\n cleanText: string;\n results: string[];\n searchResults: string | null;\n}> {\n const { parseActions, executeActions } = await import(\"../runtime/decision-engine.js\");\n\n // Try to find JSON code blocks in the response\n const jsonBlockPattern = /```json\\s*([\\s\\S]*?)```/g;\n const blocks = [...responseText.matchAll(jsonBlockPattern)];\n const visibleResults: string[] = [];\n let searchResults: string | null = null;\n\n const processResults = (actionResults: Awaited<ReturnType<typeof executeActions>>) => {\n for (const r of actionResults) {\n if (r.action === \"search\") {\n // Search results are internal — don't show in chat\n if (r.success && r.detail && r.detail !== \"No results found\") {\n searchResults = r.detail;\n console.log(chalk.green(` [Actions] search: found results (internal)`));\n } else {\n console.log(chalk.dim(` [Actions] search: ${r.detail ?? r.error ?? \"no results\"}`));\n }\n } else if (r.success) {\n // For post/reply/schedule with content, emit a tweet preview tag\n if ((r.action === \"post\" || r.action === \"reply\" || r.action === \"schedule\") && r.content) {\n const tweetData = JSON.stringify({ action: r.action, tweetId: r.detail ?? null, content: r.content });\n visibleResults.push(`<<TWEET:${tweetData}>>`);\n console.log(chalk.green(` [Actions] ${r.action}: success (tweet preview)`));\n } else {\n const detail = r.detail ? ` (${r.detail})` : \"\";\n visibleResults.push(`[${r.action}] Done${detail}`);\n console.log(chalk.green(` [Actions] ${r.action}: success${detail}`));\n }\n } else {\n visibleResults.push(`[${r.action}] Failed: ${r.error}`);\n console.log(chalk.red(` [Actions] ${r.action}: ${r.error}`));\n }\n }\n };\n\n if (blocks.length > 0) {\n for (const block of blocks) {\n const actions = parseActions(block[1]);\n if (actions.length > 0) {\n console.log(chalk.cyan(` [Actions] Executing ${actions.length} action(s)...`));\n const actionResults = await executeActions(actions);\n processResults(actionResults);\n }\n }\n } else {\n // Also try raw JSON (no code block wrapper)\n const actions = parseActions(responseText);\n if (actions.length > 0 && actions[0].action) {\n console.log(chalk.cyan(` [Actions] Executing ${actions.length} action(s)...`));\n const actionResults = await executeActions(actions);\n processResults(actionResults);\n }\n }\n\n // Strip JSON code blocks from the user-visible text\n let cleanText = responseText.replace(/```json\\s*[\\s\\S]*?```/g, \"\").trim();\n // Clean up extra whitespace from removal\n cleanText = cleanText.replace(/\\n{3,}/g, \"\\n\\n\").trim();\n\n // Append visible action results (search excluded)\n if (visibleResults.length > 0) {\n cleanText += \"\\n\\n\" + visibleResults.join(\"\\n\");\n }\n\n return { cleanText, results: visibleResults, searchResults };\n}\n\n/**\n * Log a chat exchange as an interaction in memory\n */\nasync function logChatInteraction(userMessage: string, agentResponse: string): Promise<void> {\n const { logInteraction } = await import(\"../memory/index.js\");\n logInteraction({\n id: `chat-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n timestamp: new Date().toISOString(),\n type: \"reply\",\n content: agentResponse.slice(0, 200),\n targetHandle: \"creator\",\n creditsUsed: 0,\n success: true,\n });\n}\n\nexport async function startWebChat() {\n const identity = loadIdentity();\n\n const server = new WebChatServer();\n\n // Pass identity to server so the chat UI can display it\n server.setIdentity({\n name: identity.name,\n handle: identity.handle,\n bio: identity.bio,\n profileImage: identity.profileImage,\n createdAt: identity.createdAt,\n });\n\n // Resolve real Twitter handle on startup\n let realHandle: string | undefined;\n try {\n const { hasXCredentials } = await import(\"../utils/paths.js\");\n if (hasXCredentials()) {\n const { getXClient } = await import(\"../x-client/index.js\");\n const client = await getXClient();\n if (\"getAuthenticatedHandle\" in client) {\n realHandle = await (client as any).getAuthenticatedHandle();\n console.log(chalk.dim(` [Auth] Real Twitter handle: @${realHandle}`));\n // Update the server identity to show the real handle\n server.setIdentity({\n name: identity.name,\n handle: realHandle,\n bio: identity.bio,\n profileImage: identity.profileImage,\n createdAt: identity.createdAt,\n });\n }\n }\n } catch (err) {\n console.log(chalk.dim(` [Auth] Could not resolve real handle: ${(err as Error).message}`));\n }\n\n // Set up message handler - connected to actual LLM with memory\n const chatHistory: Array<{ role: \"user\" | \"assistant\"; content: string }> = [];\n let systemPrompt: string | null = null;\n let messageCount = 0;\n\n server.setMessageHandler(async (message: string) => {\n try {\n // Save remaining sleep time so we can resume after responding\n const sleepBefore = server.getSleepState();\n const remainingMs = sleepBefore.sleeping && sleepBefore.wakeAt\n ? Math.max(0, sleepBefore.wakeAt - Date.now())\n : 0;\n\n // Manual message = instant wake — clear sleep indicator\n server.setAwake();\n\n // Build system prompt on first message, rebuild every 10 messages to refresh memory\n if (!systemPrompt || messageCount % 10 === 0) {\n const { buildChatPrompt } = await import(\"../runtime/prompt-builder.js\");\n systemPrompt = buildChatPrompt(realHandle);\n }\n messageCount++;\n\n // Check for LLM key\n const { hasLLMKey, chat: chatLLM } = await import(\"../runtime/llm.js\");\n if (!hasLLMKey()) {\n return \"I can't respond right now - no API key configured. Run `spora set-llm-key` to set one up.\";\n }\n\n // Add user message to history\n chatHistory.push({ role: \"user\", content: message });\n\n // Call LLM with full conversation history\n const response = await chatLLM(systemPrompt, chatHistory);\n\n // Extract and execute any actions (posts, likes, etc.) from the response\n let { cleanText: actionCleanedText, searchResults } = await extractAndExecuteActions(response.content);\n\n // Two-pass: if search returned results, feed them back to the LLM so it can act on them\n if (searchResults) {\n console.log(chalk.cyan(\" [Chat] Search returned results — doing follow-up LLM call...\"));\n\n // Add the first response (narration) to history as context\n const firstNarration = actionCleanedText.replace(/```json\\s*[\\s\\S]*?```/g, \"\").replace(/\\n{3,}/g, \"\\n\\n\").trim();\n if (firstNarration) {\n chatHistory.push({ role: \"assistant\", content: firstNarration });\n }\n\n // Inject search results as a system-style user message the LLM can act on\n chatHistory.push({\n role: \"user\",\n content: `[Internal: here are the search results you requested. Pick one or more to act on (reply, like, etc.) and do it now. Do NOT show these results to me — just act on them and tell me what you did.]\\n\\n${searchResults}`,\n });\n\n // Second LLM call — it now has search results and can reply/like\n const followUp = await chatLLM(systemPrompt, chatHistory);\n const followUpResult = await extractAndExecuteActions(followUp.content);\n actionCleanedText = followUpResult.cleanText;\n\n // Remove the internal search-results message from visible history\n chatHistory.pop();\n if (firstNarration) {\n chatHistory.pop();\n }\n }\n\n // Extract learnings from response and clean the text\n const cleanResponse = await extractAndSaveLearnings(actionCleanedText);\n\n // Add cleaned assistant response to history\n chatHistory.push({ role: \"assistant\", content: cleanResponse });\n\n // Log interaction to memory (async, don't block response)\n logChatInteraction(message, cleanResponse).catch((err) =>\n console.error(chalk.dim(\" [Memory] Failed to log interaction:\"), err)\n );\n\n // Resume sleeping for remaining time if there was time left\n if (remainingMs > 10_000) {\n server.setSleeping(Date.now() + remainingMs);\n }\n\n return cleanResponse;\n } catch (error) {\n console.error(\"Chat error:\", error);\n return `Sorry, I ran into an issue: ${(error as Error).message}`;\n }\n });\n\n // Load initial memory stats\n refreshMemoryStats(server).catch(() => {});\n\n const url = await server.start();\n\n console.log(chalk.green(`\\n✓ Chat interface started at ${chalk.bold(url)}\\n`));\n console.log(chalk.dim(`Press Ctrl+C to stop the server\\n`));\n\n // Open browser\n openBrowser(url);\n\n // Start background heartbeat (narrates into chat)\n startNarratedHeartbeat(server).catch((err) =>\n console.error(chalk.red(\"Heartbeat failed to start:\"), err)\n );\n\n // Keep process alive\n process.on(\"SIGINT\", () => {\n console.log(chalk.yellow(\"\\n\\nStopping chat server...\"));\n heartbeatRunning = false;\n server.stop();\n process.exit(0);\n });\n\n // Return the server instance for external control\n return server;\n}\n\n/**\n * Refresh memory stats on the server for the intelligence bar\n */\nasync function refreshMemoryStats(server: WebChatServer) {\n try {\n const { loadLearnings, loadRelationships, getRecentInteractions } = await import(\"../memory/index.js\");\n const learnings = loadLearnings().learnings.length;\n const relationships = Object.keys(loadRelationships().accounts).length;\n const interactions = getRecentInteractions(1000).length;\n server.setMemoryStats({ learnings, relationships, interactions });\n } catch {\n // Memory not available yet, ignore\n }\n}\n\n/**\n * Background heartbeat that narrates into the chat UI\n */\nlet heartbeatRunning = false;\nlet lastTimelineSinceId: string | undefined;\nlet lastMentionsSinceId: string | undefined;\n\nasync function startNarratedHeartbeat(server: WebChatServer) {\n const { loadConfig } = await import(\"../utils/config.js\");\n const { hasLLMKey, generateResponse } = await import(\"../runtime/llm.js\");\n const { hasXCredentials } = await import(\"../utils/paths.js\");\n\n if (!hasLLMKey()) {\n console.log(chalk.dim(\" [Heartbeat] No LLM key — heartbeat disabled.\"));\n return;\n }\n\n if (!hasXCredentials()) {\n console.log(chalk.dim(\" [Heartbeat] No X credentials — heartbeat disabled.\"));\n return;\n }\n\n const config = loadConfig();\n let intervalMs = config.runtime?.heartbeatIntervalMs ?? 60_000;\n const maxActions = config.runtime?.actionsPerHeartbeat ?? 10;\n\n // Set initial heartbeat interval on server and listen for UI changes\n server.setHeartbeatInterval(intervalMs);\n server.setHeartbeatChangeHandler((newIntervalMs: number) => {\n intervalMs = newIntervalMs;\n console.log(chalk.cyan(` [Heartbeat] Interval changed to ${Math.round(newIntervalMs / 1000)}s`));\n // Persist to config (async, fire-and-forget)\n import(\"../utils/config.js\").then(({ loadConfig: reloadConfig, saveConfig }) => {\n const cfg = reloadConfig();\n if (!cfg.runtime) cfg.runtime = {};\n cfg.runtime.heartbeatIntervalMs = newIntervalMs;\n saveConfig(cfg);\n }).catch(() => {\n // Config save failed, not critical — will use new interval in memory\n });\n });\n\n heartbeatRunning = true;\n let heartbeatCount = 0;\n\n console.log(chalk.cyan(` [Heartbeat] Running every ${Math.round(intervalMs / 1000)}s\\n`));\n\n while (heartbeatRunning) {\n heartbeatCount++;\n console.log(chalk.cyan(` [Heartbeat] #${heartbeatCount} starting...`));\n server.setAwake();\n\n // Refresh memory stats for intelligence bar\n await refreshMemoryStats(server);\n\n try {\n await runNarratedHeartbeat(server, maxActions, intervalMs);\n } catch (error) {\n console.error(chalk.red(` [Heartbeat] #${heartbeatCount} failed:`), (error as Error).message);\n }\n\n // Sleep with jitter — flush queue during sleep so scheduled posts go out on time\n const jitter = Math.floor(Math.random() * intervalMs * 0.2);\n const sleepMs = intervalMs + jitter;\n console.log(chalk.dim(` [Heartbeat] Sleeping ${Math.round(sleepMs / 1000)}s...`));\n\n // Tell the server we're sleeping so the UI can show the indicator\n server.setSleeping(Date.now() + sleepMs);\n\n let slept = 0;\n while (slept < sleepMs && heartbeatRunning) {\n await new Promise((r) => setTimeout(r, Math.min(10000, sleepMs - slept)));\n slept += 10000;\n\n // Flush queue during sleep so scheduled posts go out at their intended times\n try {\n const { flushQueue } = await import(\"../scheduler/queue.js\");\n const flushed = await flushQueue();\n if (flushed.posted > 0) {\n console.log(chalk.green(` [Queue] Posted ${flushed.posted} scheduled tweet(s)`));\n }\n } catch {\n // Queue flush failed during sleep, not critical\n }\n }\n\n server.setAwake();\n }\n}\n\nasync function runNarratedHeartbeat(server: WebChatServer, maxActions: number, intervalMs: number) {\n const { getXClient } = await import(\"../x-client/index.js\");\n const { buildSystemPrompt, buildNarratedHeartbeatMessage } = await import(\"../runtime/prompt-builder.js\");\n const { generateResponse } = await import(\"../runtime/llm.js\");\n const { parseActions, executeActions } = await import(\"../runtime/decision-engine.js\");\n const { flushQueue } = await import(\"../scheduler/queue.js\");\n\n // 1. Flush queued posts (silent — user doesn't see this)\n try {\n const flushed = await flushQueue();\n if (flushed.posted > 0) {\n console.log(chalk.green(` [Queue] Flushed ${flushed.posted} scheduled tweet(s)`));\n }\n } catch {\n // Queue flush failed, not critical\n }\n\n // 2. Read timeline and mentions (only new since last check)\n\n const client = await getXClient();\n let timeline: Awaited<ReturnType<typeof client.getTimeline>> = [];\n let mentions: Awaited<ReturnType<typeof client.getMentions>> = [];\n\n // Get the bot's own handle to filter own tweets from timeline\n let ownHandle: string | undefined;\n if (\"getAuthenticatedHandle\" in client) {\n try {\n ownHandle = await (client as any).getAuthenticatedHandle();\n } catch {}\n }\n\n try {\n timeline = await client.getTimeline({ count: 20, sinceId: lastTimelineSinceId });\n if (timeline.length > 0) {\n lastTimelineSinceId = timeline[0].id;\n // Filter out own tweets (can't like your own)\n if (ownHandle) {\n timeline = timeline.filter(t => t.authorHandle.toLowerCase() !== ownHandle!.toLowerCase());\n }\n }\n } catch (error) {\n console.log(chalk.dim(` [Heartbeat] 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 console.log(chalk.dim(` [Heartbeat] Mentions read failed: ${(error as Error).message}`));\n }\n\n // 3. Build prompts and ask LLM\n const systemPrompt = buildSystemPrompt();\n const userMessage = buildNarratedHeartbeatMessage(timeline, mentions, intervalMs);\n\n const response = await generateResponse(systemPrompt, userMessage);\n\n // 4. Extract narration text (everything outside JSON blocks)\n let narration = response.content.replace(/```json\\s*[\\s\\S]*?```/g, \"\").replace(/\\n{3,}/g, \"\\n\\n\").trim();\n\n // 5. Parse and execute actions\n const actions = parseActions(response.content);\n\n // Build set of valid tweet IDs from timeline + mentions to catch hallucinated IDs\n const validTweetIds = new Set<string>();\n for (const t of timeline) validTweetIds.add(t.id);\n for (const t of mentions) validTweetIds.add(t.id);\n\n // Filter out actions with fake/hallucinated tweet IDs\n const validatedActions = actions.filter(a => {\n if (a.tweetId) {\n // Strip \"tweet:\" prefix the LLM sometimes includes\n const cleanId = a.tweetId.replace(/^tweet:/i, \"\").trim();\n if (!validTweetIds.has(cleanId)) {\n console.log(chalk.yellow(` [Heartbeat] Rejected ${a.action}: tweet ID ${cleanId} not in timeline/mentions (likely hallucinated)`));\n return false;\n }\n }\n return true;\n });\n\n const limitedActions = validatedActions.slice(0, maxActions);\n\n // Build tweet lookup map for rich notifications (likes, retweets)\n const tweetMap = new Map<string, { authorHandle: string; text: string }>();\n for (const t of timeline) tweetMap.set(t.id, { authorHandle: t.authorHandle, text: t.text });\n for (const t of mentions) tweetMap.set(t.id, { authorHandle: t.authorHandle, text: t.text });\n\n if (limitedActions.length > 0) {\n // Execute actions\n const results = await executeActions(limitedActions);\n\n // Build visible results — use special tags for rich rendering in chat\n const visibleResults: string[] = [];\n for (let i = 0; i < results.length; i++) {\n const r = results[i];\n const action = limitedActions[i];\n const detail = r.detail ? ` (${r.detail})` : \"\";\n if (r.action === \"schedule\") {\n // Log to terminal only, don't show in chat\n console.log(chalk.dim(` [Heartbeat] ${r.action}: ${r.success ? \"queued\" : r.error}${detail}`));\n } else if (r.success) {\n // Emit tweet preview card for post/reply with content\n if ((r.action === \"post\" || r.action === \"reply\") && r.content) {\n const tweetData = JSON.stringify({ action: r.action, tweetId: r.detail ?? null, content: r.content });\n visibleResults.push(`<<TWEET:${tweetData}>>`);\n console.log(chalk.green(` [Heartbeat] ${r.action}: success (tweet preview)`));\n } else if (r.action === \"like\" && action?.tweetId) {\n const tweet = tweetMap.get(action.tweetId.replace(/^tweet:/i, \"\").trim());\n if (tweet) {\n const likeData = JSON.stringify({ authorHandle: tweet.authorHandle, text: tweet.text });\n visibleResults.push(`<<LIKE:${likeData}>>`);\n }\n console.log(chalk.green(` [Heartbeat] like: @${tweet?.authorHandle ?? \"unknown\"}`));\n } else if (r.action === \"retweet\" && action?.tweetId) {\n const tweet = tweetMap.get(action.tweetId.replace(/^tweet:/i, \"\").trim());\n if (tweet) {\n const rtData = JSON.stringify({ authorHandle: tweet.authorHandle, text: tweet.text });\n visibleResults.push(`<<RETWEET:${rtData}>>`);\n }\n console.log(chalk.green(` [Heartbeat] retweet: @${tweet?.authorHandle ?? \"unknown\"}`));\n } else if (r.action === \"follow\" && action?.handle) {\n const followData = JSON.stringify({ handle: action.handle });\n visibleResults.push(`<<FOLLOW:${followData}>>`);\n console.log(chalk.green(` [Heartbeat] follow: @${action.handle}`));\n } else {\n console.log(chalk.green(` [Heartbeat] ${r.action}: success${detail}`));\n }\n } else {\n // Errors go to terminal only, not chat\n console.log(chalk.red(` [Heartbeat] ${r.action}: ${r.error}`));\n }\n }\n\n // Combine narration with visible action results\n let fullMessage = narration || \"\";\n if (visibleResults.length > 0) {\n fullMessage += (fullMessage ? \"\\n\\n\" : \"\") + visibleResults.join(\"\\n\");\n }\n if (fullMessage) {\n server.pushMessage(\"assistant\", fullMessage);\n }\n } else if (narration) {\n server.pushMessage(\"assistant\", narration);\n }\n\n console.log(chalk.cyan(` [Heartbeat] Complete.`));\n}\n\n/**\n * Open URL in a separate browser window (app-like)\n */\nfunction openBrowser(url: string) {\n const platform = process.platform;\n\n try {\n if (platform === \"darwin\") {\n // Open as a standalone Chrome app window (smaller, separate from existing tabs)\n try {\n execSync(`open -na \"Google Chrome\" --args --app=\"${url}\" --window-size=420,620`, { stdio: \"ignore\" });\n } catch {\n // Fallback: try Chromium-based browsers, then default\n try {\n execSync(`open -na \"Brave Browser\" --args --app=\"${url}\" --window-size=420,620`, { stdio: \"ignore\" });\n } catch {\n execSync(`open \"${url}\"`, { stdio: \"ignore\" });\n }\n }\n } else if (platform === \"win32\") {\n try {\n execSync(`start chrome --app=\"${url}\" --window-size=420,620`, { stdio: \"ignore\" });\n } catch {\n execSync(`start \"\" \"${url}\"`, { stdio: \"ignore\" });\n }\n } else {\n // Linux\n try {\n execSync(`google-chrome --app=\"${url}\" --window-size=420,620`, { stdio: \"ignore\" });\n } catch {\n execSync(`xdg-open \"${url}\"`, { stdio: \"ignore\" });\n }\n }\n } catch (error) {\n // Browser couldn't be opened, that's okay\n console.log(chalk.dim(`(Couldn't open browser automatically - please visit ${url} manually)`));\n }\n}\n\nexport { openBrowser };\n"],"mappings":";;;;;;AAKA,OAAO,UAAU;AACjB,SAAS,WAAW;AACpB,SAAS,oBAAoB;AAC7B,SAAS,MAAM,eAAe;AAC9B,SAAS,qBAAqB;AAE9B,IAAM,aAAa,cAAc,YAAY,GAAG;AAChD,IAAM,YAAY,QAAQ,UAAU;AAgB7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AAEd,YAAQ,IAAI,MAAM,IAAI,uDAAuD,GAAG,YAAY,CAAC;AAAA,EAC/F;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spora",
3
- "version": "0.2.45",
3
+ "version": "0.2.47",
4
4
  "description": "AI agents (Spores) that autonomously manage X/Twitter accounts",
5
5
  "type": "module",
6
6
  "author": "Spora",
@@ -1 +0,0 @@
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 } from \"../memory/index.js\";\nimport { rateLimiter } from \"../x-client/rate-limiter.js\";\nimport type { Tweet } from \"../x-client/types.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. 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 // 4. 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): 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 NEW on your timeline since your last check:\");\n parts.push(\"\");\n\n if (mentions.length > 0) {\n // Filter out mentions we already replied to\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 since last check.\");\n parts.push(\"\");\n }\n } else {\n parts.push(\"## Mentions: None right now.\");\n parts.push(\"\");\n }\n\n if (timeline.length > 0) {\n // Filter out tweets we already acted on and our own tweets\n const newTimeline = timeline.filter(t => !actedOnTweetIds.has(t.id));\n if (newTimeline.length > 0) {\n parts.push(\"## Timeline (new posts from your feed)\");\n for (const t of newTimeline.slice(0, 20)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes, ${t.retweetCount ?? 0} RTs)`);\n }\n parts.push(\"\");\n } else {\n parts.push(\"## Timeline: No new posts since last check.\");\n parts.push(\"\");\n }\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 parts.push(\"IMPORTANT: Only act on NEW tweets you haven't already responded to.\");\n parts.push(\"Do NOT reply to or like tweets you've already interacted with.\");\n parts.push(`Current time: ${now.toISOString()}`);\n parts.push(\"\");\n parts.push(\"POSTING LIMITS: You may schedule up to 3 original tweets, but space them RANDOMLY across the next interval. Prioritize engagement (replies, likes) over new posts. Quality over quantity.\");\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. Max 1 per heartbeat.\");\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(\"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 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): 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 if (timeline.length > 0) {\n const newTimeline = timeline.filter(t => !actedOnTweetIds.has(t.id));\n if (newTimeline.length > 0) {\n parts.push(\"## Timeline (new posts)\");\n for (const t of newTimeline.slice(0, 20)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes, ${t.retweetCount ?? 0} RTs)`);\n }\n parts.push(\"\");\n } else {\n parts.push(\"## Timeline: No new posts since last check.\");\n parts.push(\"\");\n }\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(\"MINIMUM ACTIONS REQUIRED — you MUST include at least:\");\n parts.push(\"- 1-3 `reply` to tweets on the timeline or mentions (this is your main thing — jump into conversations)\");\n parts.push(\"- 2-4 `like` (show love to good posts)\");\n parts.push(\"- 0-1 `post` or `schedule` (only when you genuinely have something to say, not every time)\");\n parts.push(\"- Sprinkle in `follow`, `retweet`, `learn` as they make sense\");\n parts.push(\"\");\n parts.push(\"Action rules:\");\n parts.push(\"- CRITICAL: Only use tweet IDs that appear in the timeline or mentions data above (the [tweet:ID] values). NEVER invent, guess, or make up tweet IDs. If you fabricate an ID, the action WILL fail.\");\n parts.push(\"- Only act on NEW tweets. Don't re-like or re-reply to things you've already touched.\");\n parts.push(\"- If no new tweets are shown above, focus on posting your own content instead of trying to like/reply with made-up IDs.\");\n parts.push(\"- `reply` = reply IN THE THREAD (needs `tweetId` + `content`). Don't use `post`/`schedule` to @mention someone. Be genuine — add to the conversation, don't just agree.\");\n parts.push(\"- `post` = original standalone tweet NOW (max 1 per heartbeat). Not for responding to others. Don't force it if you have nothing interesting to say.\");\n parts.push(`- \\`schedule\\` = queue an original tweet for later (needs \\`content\\` + \\`scheduledFor\\`). Space randomly across the next ~${intervalMin} min. Max 2.`);\n parts.push(\"- `imageQuery` (optional) = add this to any `post` or `schedule` to attach an image. Value is a Google Image search query describing the image you want. Use it sometimes for visual tweets — memes, aesthetic vibes, relevant photos — but NOT every tweet. Maybe 1 in 3-4 posts.\");\n parts.push(\"- `like`, `retweet`, `follow`, `learn` — use these actively. Be engaged, not passive.\");\n parts.push(\"- `skip` = ONLY if there is literally nothing on the timeline. This should almost never happen.\");\n parts.push(\"- Don't like your own tweets.\");\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`)\");\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` and `schedule` actions by adding `\\\"imageQuery\\\": \\\"search terms\\\"`. This searches Google Images and attaches the result. Use it when the tweet would benefit from a visual — memes, aesthetic images, relevant photos. 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"],"mappings":";;;;;;;;;;;;;;;;;AAMO,SAAS,oBAA4B;AAC1C,QAAM,WAAW,aAAa;AAC9B,QAAM,SAAS,WAAW;AAC1B,QAAM,cAAc,uBAAuB,QAAQ;AAEnD,QAAM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WAAS,KAAK,oCAAoC;AAClD,WAAS,KAAK,+GAAqG;AACnH,WAAS,KAAK,+EAA+E;AAC7F,WAAS,KAAK,sCAAsC;AACpD,WAAS,KAAK,uEAAuE;AACrF,WAAS,KAAK,qFAAqF;AACnG,WAAS,KAAK,0DAA0D;AACxE,MAAI,SAAS,WAAW,SAAS,GAAG;AAClC,aAAS,KAAK,+BAA+B,SAAS,WAAW,KAAK,IAAI,CAAC,EAAE;AAAA,EAC/E;AAEA,SAAO,SAAS,KAAK,IAAI;AAC3B;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/web-chat/server.ts","../src/web-chat/index.ts"],"sourcesContent":["/**\n * Local web chat server\n * Serves a simple chat interface for interacting with your Spore\n */\n\nimport http from \"node:http\";\nimport { URL } from \"node:url\";\nimport { readFileSync } from \"node:fs\";\nimport { join, dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\ninterface ChatMessage {\n role: \"user\" | \"assistant\";\n content: string;\n timestamp: number;\n}\n\ninterface AgentIdentity {\n name: string;\n handle: string;\n bio?: string;\n profileImage?: string;\n createdAt?: string;\n}\n\nexport class WebChatServer {\n private server: http.Server | null = null;\n private port: number;\n private messages: ChatMessage[] = [];\n private onUserMessage?: (message: string) => Promise<string>;\n private onHeartbeatChange?: (intervalMs: number) => void;\n private identity?: AgentIdentity;\n private sleepState: { sleeping: boolean; wakeAt: number | null; intervalMs: number } = {\n sleeping: false,\n wakeAt: null,\n intervalMs: 60_000,\n };\n private memoryStats: { learnings: number; relationships: number; interactions: number } = {\n learnings: 0,\n relationships: 0,\n interactions: 0,\n };\n\n constructor(port = 3737) {\n this.port = port;\n }\n\n setIdentity(identity: AgentIdentity) {\n this.identity = identity;\n }\n\n setMessageHandler(handler: (message: string) => Promise<string>) {\n this.onUserMessage = handler;\n }\n\n setHeartbeatChangeHandler(handler: (intervalMs: number) => void) {\n this.onHeartbeatChange = handler;\n }\n\n setSleeping(wakeAt: number) {\n this.sleepState.sleeping = true;\n this.sleepState.wakeAt = wakeAt;\n }\n\n setAwake() {\n this.sleepState.sleeping = false;\n this.sleepState.wakeAt = null;\n }\n\n getSleepState() {\n return { ...this.sleepState };\n }\n\n setHeartbeatInterval(intervalMs: number) {\n this.sleepState.intervalMs = intervalMs;\n }\n\n getHeartbeatInterval(): number {\n return this.sleepState.intervalMs;\n }\n\n setMemoryStats(stats: { learnings: number; relationships: number; interactions: number }) {\n this.memoryStats = stats;\n }\n\n async start(): Promise<string> {\n return new Promise((resolve, reject) => {\n this.server = http.createServer(async (req, res) => {\n const url = new URL(req.url || \"/\", `http://${req.headers.host}`);\n\n // CORS headers\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, OPTIONS\");\n res.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type\");\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(200);\n res.end();\n return;\n }\n\n // Serve HTML\n if (url.pathname === \"/\" || url.pathname === \"/index.html\") {\n try {\n // Try multiple paths since __dirname changes based on build output\n const possiblePaths = [\n join(__dirname, \"web-chat\", \"chat.html\"),\n join(__dirname, \"chat.html\"),\n join(__dirname, \"..\", \"web-chat\", \"chat.html\"),\n join(__dirname, \"..\", \"src\", \"web-chat\", \"chat.html\"),\n ];\n\n let html: string | null = null;\n for (const p of possiblePaths) {\n try {\n html = readFileSync(p, \"utf-8\");\n break;\n } catch {\n continue;\n }\n }\n\n if (html) {\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(html);\n } else {\n console.error(\"Could not find chat.html in any of:\", possiblePaths);\n res.writeHead(500);\n res.end(\"Error: Could not find chat.html\");\n }\n } catch (error) {\n res.writeHead(500);\n res.end(\"Error loading chat interface\");\n }\n return;\n }\n\n // Serve logo\n if (url.pathname === \"/logo.png\") {\n try {\n const logoPaths = [\n join(__dirname, \"web-chat\", \"logo.png\"),\n join(__dirname, \"logo.png\"),\n join(__dirname, \"..\", \"web-chat\", \"logo.png\"),\n join(__dirname, \"..\", \"src\", \"web-chat\", \"logo.png\"),\n ];\n let logoData: Buffer | null = null;\n for (const p of logoPaths) {\n try {\n logoData = readFileSync(p) as unknown as Buffer;\n break;\n } catch {\n continue;\n }\n }\n if (logoData) {\n res.writeHead(200, { \"Content-Type\": \"image/png\", \"Cache-Control\": \"public, max-age=86400\" });\n res.end(logoData);\n } else {\n res.writeHead(404);\n res.end(\"Logo not found\");\n }\n } catch {\n res.writeHead(404);\n res.end(\"Logo not found\");\n }\n return;\n }\n\n // API: Get agent identity\n if (url.pathname === \"/api/identity\" && req.method === \"GET\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ identity: this.identity || null }));\n return;\n }\n\n // API: Get messages (optionally since a timestamp)\n if (url.pathname === \"/api/messages\" && req.method === \"GET\") {\n const since = url.searchParams.get(\"since\");\n if (since) {\n const sinceTs = parseInt(since, 10);\n const newMessages = this.messages.filter((m) => m.timestamp > sinceTs);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ messages: newMessages }));\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ messages: this.messages }));\n }\n return;\n }\n\n // API: Send message\n if (url.pathname === \"/api/message\" && req.method === \"POST\") {\n let body = \"\";\n req.on(\"data\", (chunk) => {\n body += chunk.toString();\n });\n\n req.on(\"end\", async () => {\n try {\n const { message } = JSON.parse(body);\n\n // Add user message\n this.messages.push({\n role: \"user\",\n content: message,\n timestamp: Date.now(),\n });\n\n // Get response\n if (this.onUserMessage) {\n const response = await this.onUserMessage(message);\n this.messages.push({\n role: \"assistant\",\n content: response,\n timestamp: Date.now(),\n });\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ success: true, response }));\n } else {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"No message handler configured\" }));\n }\n } catch (error) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid request\" }));\n }\n });\n return;\n }\n\n // API: Get memory stats (for intelligence bar)\n if (url.pathname === \"/api/memory-stats\" && req.method === \"GET\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(this.memoryStats));\n return;\n }\n\n // API: Get sleep state\n if (url.pathname === \"/api/sleep-state\" && req.method === \"GET\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(this.sleepState));\n return;\n }\n\n // API: Update heartbeat interval\n if (url.pathname === \"/api/config/heartbeat\" && req.method === \"POST\") {\n let body = \"\";\n req.on(\"data\", (chunk) => { body += chunk.toString(); });\n req.on(\"end\", () => {\n try {\n const { intervalMs } = JSON.parse(body);\n if (typeof intervalMs === \"number\" && intervalMs >= 60_000) {\n this.sleepState.intervalMs = intervalMs;\n if (this.onHeartbeatChange) {\n this.onHeartbeatChange(intervalMs);\n }\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ success: true, intervalMs }));\n } else {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid interval\" }));\n }\n } catch {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid request\" }));\n }\n });\n return;\n }\n\n // 404\n res.writeHead(404);\n res.end(\"Not found\");\n });\n\n this.server.listen(this.port, () => {\n const url = `http://localhost:${this.port}`;\n resolve(url);\n });\n\n this.server.on(\"error\", (error: NodeJS.ErrnoException) => {\n if (error.code === \"EADDRINUSE\") {\n // Port in use, try next port\n this.port++;\n this.server?.close();\n this.start().then(resolve).catch(reject);\n } else {\n reject(error);\n }\n });\n });\n }\n\n /**\n * Push a message into the chat from the server side (used by heartbeat narration)\n */\n pushMessage(role: \"user\" | \"assistant\", content: string) {\n this.messages.push({ role, content, timestamp: Date.now() });\n }\n\n getMessageCount(): number {\n return this.messages.length;\n }\n\n stop() {\n if (this.server) {\n this.server.close();\n this.server = null;\n }\n }\n}\n","/**\n * Web chat integration\n */\n\nimport { WebChatServer } from \"./server.js\";\nimport { loadIdentity } from \"../identity/index.js\";\nimport { execSync } from \"node:child_process\";\nimport chalk from \"chalk\";\n\n/**\n * Extract <<LEARN: ...>> tags from response, save them, and return cleaned text\n */\nasync function extractAndSaveLearnings(responseText: string): Promise<string> {\n const learnPattern = /<<LEARN:\\s*(.+?)>>/g;\n const matches = [...responseText.matchAll(learnPattern)];\n\n if (matches.length > 0) {\n const { addLearning } = await import(\"../memory/index.js\");\n for (const match of matches) {\n const learning = match[1].trim();\n addLearning(learning, \"web-chat\", [\"chat\", \"creator-interaction\"]);\n console.log(chalk.dim(` [Memory] Saved learning: ${learning}`));\n }\n }\n\n // Strip the learn tags from the response the user sees\n return responseText.replace(/<<LEARN:\\s*.+?>>/g, \"\").trim();\n}\n\n/**\n * Extract JSON action blocks from the LLM response, execute them, and return cleaned text + results.\n * Search results are returned separately so the caller can feed them back to the LLM.\n */\nasync function extractAndExecuteActions(responseText: string): Promise<{\n cleanText: string;\n results: string[];\n searchResults: string | null;\n}> {\n const { parseActions, executeActions } = await import(\"../runtime/decision-engine.js\");\n\n // Try to find JSON code blocks in the response\n const jsonBlockPattern = /```json\\s*([\\s\\S]*?)```/g;\n const blocks = [...responseText.matchAll(jsonBlockPattern)];\n const visibleResults: string[] = [];\n let searchResults: string | null = null;\n\n const processResults = (actionResults: Awaited<ReturnType<typeof executeActions>>) => {\n for (const r of actionResults) {\n if (r.action === \"search\") {\n // Search results are internal — don't show in chat\n if (r.success && r.detail && r.detail !== \"No results found\") {\n searchResults = r.detail;\n console.log(chalk.green(` [Actions] search: found results (internal)`));\n } else {\n console.log(chalk.dim(` [Actions] search: ${r.detail ?? r.error ?? \"no results\"}`));\n }\n } else if (r.success) {\n // For post/reply/schedule with content, emit a tweet preview tag\n if ((r.action === \"post\" || r.action === \"reply\" || r.action === \"schedule\") && r.content) {\n const tweetData = JSON.stringify({ action: r.action, tweetId: r.detail ?? null, content: r.content });\n visibleResults.push(`<<TWEET:${tweetData}>>`);\n console.log(chalk.green(` [Actions] ${r.action}: success (tweet preview)`));\n } else {\n const detail = r.detail ? ` (${r.detail})` : \"\";\n visibleResults.push(`[${r.action}] Done${detail}`);\n console.log(chalk.green(` [Actions] ${r.action}: success${detail}`));\n }\n } else {\n visibleResults.push(`[${r.action}] Failed: ${r.error}`);\n console.log(chalk.red(` [Actions] ${r.action}: ${r.error}`));\n }\n }\n };\n\n if (blocks.length > 0) {\n for (const block of blocks) {\n const actions = parseActions(block[1]);\n if (actions.length > 0) {\n console.log(chalk.cyan(` [Actions] Executing ${actions.length} action(s)...`));\n const actionResults = await executeActions(actions);\n processResults(actionResults);\n }\n }\n } else {\n // Also try raw JSON (no code block wrapper)\n const actions = parseActions(responseText);\n if (actions.length > 0 && actions[0].action) {\n console.log(chalk.cyan(` [Actions] Executing ${actions.length} action(s)...`));\n const actionResults = await executeActions(actions);\n processResults(actionResults);\n }\n }\n\n // Strip JSON code blocks from the user-visible text\n let cleanText = responseText.replace(/```json\\s*[\\s\\S]*?```/g, \"\").trim();\n // Clean up extra whitespace from removal\n cleanText = cleanText.replace(/\\n{3,}/g, \"\\n\\n\").trim();\n\n // Append visible action results (search excluded)\n if (visibleResults.length > 0) {\n cleanText += \"\\n\\n\" + visibleResults.join(\"\\n\");\n }\n\n return { cleanText, results: visibleResults, searchResults };\n}\n\n/**\n * Log a chat exchange as an interaction in memory\n */\nasync function logChatInteraction(userMessage: string, agentResponse: string): Promise<void> {\n const { logInteraction } = await import(\"../memory/index.js\");\n logInteraction({\n id: `chat-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n timestamp: new Date().toISOString(),\n type: \"reply\",\n content: agentResponse.slice(0, 200),\n targetHandle: \"creator\",\n creditsUsed: 0,\n success: true,\n });\n}\n\nexport async function startWebChat() {\n const identity = loadIdentity();\n\n const server = new WebChatServer();\n\n // Pass identity to server so the chat UI can display it\n server.setIdentity({\n name: identity.name,\n handle: identity.handle,\n bio: identity.bio,\n profileImage: identity.profileImage,\n createdAt: identity.createdAt,\n });\n\n // Resolve real Twitter handle on startup\n let realHandle: string | undefined;\n try {\n const { hasXCredentials } = await import(\"../utils/paths.js\");\n if (hasXCredentials()) {\n const { getXClient } = await import(\"../x-client/index.js\");\n const client = await getXClient();\n if (\"getAuthenticatedHandle\" in client) {\n realHandle = await (client as any).getAuthenticatedHandle();\n console.log(chalk.dim(` [Auth] Real Twitter handle: @${realHandle}`));\n // Update the server identity to show the real handle\n server.setIdentity({\n name: identity.name,\n handle: realHandle,\n bio: identity.bio,\n profileImage: identity.profileImage,\n createdAt: identity.createdAt,\n });\n }\n }\n } catch (err) {\n console.log(chalk.dim(` [Auth] Could not resolve real handle: ${(err as Error).message}`));\n }\n\n // Set up message handler - connected to actual LLM with memory\n const chatHistory: Array<{ role: \"user\" | \"assistant\"; content: string }> = [];\n let systemPrompt: string | null = null;\n let messageCount = 0;\n\n server.setMessageHandler(async (message: string) => {\n try {\n // Save remaining sleep time so we can resume after responding\n const sleepBefore = server.getSleepState();\n const remainingMs = sleepBefore.sleeping && sleepBefore.wakeAt\n ? Math.max(0, sleepBefore.wakeAt - Date.now())\n : 0;\n\n // Manual message = instant wake — clear sleep indicator\n server.setAwake();\n\n // Build system prompt on first message, rebuild every 10 messages to refresh memory\n if (!systemPrompt || messageCount % 10 === 0) {\n const { buildChatPrompt } = await import(\"../runtime/prompt-builder.js\");\n systemPrompt = buildChatPrompt(realHandle);\n }\n messageCount++;\n\n // Check for LLM key\n const { hasLLMKey, chat: chatLLM } = await import(\"../runtime/llm.js\");\n if (!hasLLMKey()) {\n return \"I can't respond right now - no API key configured. Run `spora set-llm-key` to set one up.\";\n }\n\n // Add user message to history\n chatHistory.push({ role: \"user\", content: message });\n\n // Call LLM with full conversation history\n const response = await chatLLM(systemPrompt, chatHistory);\n\n // Extract and execute any actions (posts, likes, etc.) from the response\n let { cleanText: actionCleanedText, searchResults } = await extractAndExecuteActions(response.content);\n\n // Two-pass: if search returned results, feed them back to the LLM so it can act on them\n if (searchResults) {\n console.log(chalk.cyan(\" [Chat] Search returned results — doing follow-up LLM call...\"));\n\n // Add the first response (narration) to history as context\n const firstNarration = actionCleanedText.replace(/```json\\s*[\\s\\S]*?```/g, \"\").replace(/\\n{3,}/g, \"\\n\\n\").trim();\n if (firstNarration) {\n chatHistory.push({ role: \"assistant\", content: firstNarration });\n }\n\n // Inject search results as a system-style user message the LLM can act on\n chatHistory.push({\n role: \"user\",\n content: `[Internal: here are the search results you requested. Pick one or more to act on (reply, like, etc.) and do it now. Do NOT show these results to me — just act on them and tell me what you did.]\\n\\n${searchResults}`,\n });\n\n // Second LLM call — it now has search results and can reply/like\n const followUp = await chatLLM(systemPrompt, chatHistory);\n const followUpResult = await extractAndExecuteActions(followUp.content);\n actionCleanedText = followUpResult.cleanText;\n\n // Remove the internal search-results message from visible history\n chatHistory.pop();\n if (firstNarration) {\n chatHistory.pop();\n }\n }\n\n // Extract learnings from response and clean the text\n const cleanResponse = await extractAndSaveLearnings(actionCleanedText);\n\n // Add cleaned assistant response to history\n chatHistory.push({ role: \"assistant\", content: cleanResponse });\n\n // Log interaction to memory (async, don't block response)\n logChatInteraction(message, cleanResponse).catch((err) =>\n console.error(chalk.dim(\" [Memory] Failed to log interaction:\"), err)\n );\n\n // Resume sleeping for remaining time if there was time left\n if (remainingMs > 10_000) {\n server.setSleeping(Date.now() + remainingMs);\n }\n\n return cleanResponse;\n } catch (error) {\n console.error(\"Chat error:\", error);\n return `Sorry, I ran into an issue: ${(error as Error).message}`;\n }\n });\n\n // Load initial memory stats\n refreshMemoryStats(server).catch(() => {});\n\n const url = await server.start();\n\n console.log(chalk.green(`\\n✓ Chat interface started at ${chalk.bold(url)}\\n`));\n console.log(chalk.dim(`Press Ctrl+C to stop the server\\n`));\n\n // Open browser\n openBrowser(url);\n\n // Start background heartbeat (narrates into chat)\n startNarratedHeartbeat(server).catch((err) =>\n console.error(chalk.red(\"Heartbeat failed to start:\"), err)\n );\n\n // Keep process alive\n process.on(\"SIGINT\", () => {\n console.log(chalk.yellow(\"\\n\\nStopping chat server...\"));\n heartbeatRunning = false;\n server.stop();\n process.exit(0);\n });\n\n // Return the server instance for external control\n return server;\n}\n\n/**\n * Refresh memory stats on the server for the intelligence bar\n */\nasync function refreshMemoryStats(server: WebChatServer) {\n try {\n const { loadLearnings, loadRelationships, getRecentInteractions } = await import(\"../memory/index.js\");\n const learnings = loadLearnings().learnings.length;\n const relationships = Object.keys(loadRelationships().accounts).length;\n const interactions = getRecentInteractions(1000).length;\n server.setMemoryStats({ learnings, relationships, interactions });\n } catch {\n // Memory not available yet, ignore\n }\n}\n\n/**\n * Background heartbeat that narrates into the chat UI\n */\nlet heartbeatRunning = false;\nlet lastTimelineSinceId: string | undefined;\nlet lastMentionsSinceId: string | undefined;\n\nasync function startNarratedHeartbeat(server: WebChatServer) {\n const { loadConfig } = await import(\"../utils/config.js\");\n const { hasLLMKey, generateResponse } = await import(\"../runtime/llm.js\");\n const { hasXCredentials } = await import(\"../utils/paths.js\");\n\n if (!hasLLMKey()) {\n console.log(chalk.dim(\" [Heartbeat] No LLM key — heartbeat disabled.\"));\n return;\n }\n\n if (!hasXCredentials()) {\n console.log(chalk.dim(\" [Heartbeat] No X credentials — heartbeat disabled.\"));\n return;\n }\n\n const config = loadConfig();\n let intervalMs = config.runtime?.heartbeatIntervalMs ?? 60_000;\n const maxActions = config.runtime?.actionsPerHeartbeat ?? 10;\n\n // Set initial heartbeat interval on server and listen for UI changes\n server.setHeartbeatInterval(intervalMs);\n server.setHeartbeatChangeHandler((newIntervalMs: number) => {\n intervalMs = newIntervalMs;\n console.log(chalk.cyan(` [Heartbeat] Interval changed to ${Math.round(newIntervalMs / 1000)}s`));\n // Persist to config (async, fire-and-forget)\n import(\"../utils/config.js\").then(({ loadConfig: reloadConfig, saveConfig }) => {\n const cfg = reloadConfig();\n if (!cfg.runtime) cfg.runtime = {};\n cfg.runtime.heartbeatIntervalMs = newIntervalMs;\n saveConfig(cfg);\n }).catch(() => {\n // Config save failed, not critical — will use new interval in memory\n });\n });\n\n heartbeatRunning = true;\n let heartbeatCount = 0;\n\n console.log(chalk.cyan(` [Heartbeat] Running every ${Math.round(intervalMs / 1000)}s\\n`));\n\n while (heartbeatRunning) {\n heartbeatCount++;\n console.log(chalk.cyan(` [Heartbeat] #${heartbeatCount} starting...`));\n server.setAwake();\n\n // Refresh memory stats for intelligence bar\n await refreshMemoryStats(server);\n\n try {\n await runNarratedHeartbeat(server, maxActions, intervalMs);\n } catch (error) {\n console.error(chalk.red(` [Heartbeat] #${heartbeatCount} failed:`), (error as Error).message);\n server.pushMessage(\"assistant\", `Heartbeat error: ${(error as Error).message}`);\n }\n\n // Sleep with jitter — flush queue during sleep so scheduled posts go out on time\n const jitter = Math.floor(Math.random() * intervalMs * 0.2);\n const sleepMs = intervalMs + jitter;\n console.log(chalk.dim(` [Heartbeat] Sleeping ${Math.round(sleepMs / 1000)}s...`));\n\n // Tell the server we're sleeping so the UI can show the indicator\n server.setSleeping(Date.now() + sleepMs);\n\n let slept = 0;\n while (slept < sleepMs && heartbeatRunning) {\n await new Promise((r) => setTimeout(r, Math.min(10000, sleepMs - slept)));\n slept += 10000;\n\n // Flush queue during sleep so scheduled posts go out at their intended times\n try {\n const { flushQueue } = await import(\"../scheduler/queue.js\");\n const flushed = await flushQueue();\n if (flushed.posted > 0) {\n console.log(chalk.green(` [Queue] Posted ${flushed.posted} scheduled tweet(s)`));\n }\n } catch {\n // Queue flush failed during sleep, not critical\n }\n }\n\n server.setAwake();\n }\n}\n\nasync function runNarratedHeartbeat(server: WebChatServer, maxActions: number, intervalMs: number) {\n const { getXClient } = await import(\"../x-client/index.js\");\n const { buildSystemPrompt, buildNarratedHeartbeatMessage } = await import(\"../runtime/prompt-builder.js\");\n const { generateResponse } = await import(\"../runtime/llm.js\");\n const { parseActions, executeActions } = await import(\"../runtime/decision-engine.js\");\n const { flushQueue } = await import(\"../scheduler/queue.js\");\n\n // 1. Flush queued posts (silent — user doesn't see this)\n try {\n const flushed = await flushQueue();\n if (flushed.posted > 0) {\n console.log(chalk.green(` [Queue] Flushed ${flushed.posted} scheduled tweet(s)`));\n }\n } catch {\n // Queue flush failed, not critical\n }\n\n // 2. Read timeline and mentions (only new since last check)\n\n const client = await getXClient();\n let timeline: Awaited<ReturnType<typeof client.getTimeline>> = [];\n let mentions: Awaited<ReturnType<typeof client.getMentions>> = [];\n\n // Get the bot's own handle to filter own tweets from timeline\n let ownHandle: string | undefined;\n if (\"getAuthenticatedHandle\" in client) {\n try {\n ownHandle = await (client as any).getAuthenticatedHandle();\n } catch {}\n }\n\n try {\n timeline = await client.getTimeline({ count: 20, sinceId: lastTimelineSinceId });\n if (timeline.length > 0) {\n lastTimelineSinceId = timeline[0].id;\n // Filter out own tweets (can't like your own)\n if (ownHandle) {\n timeline = timeline.filter(t => t.authorHandle.toLowerCase() !== ownHandle!.toLowerCase());\n }\n }\n } catch (error) {\n console.log(chalk.dim(` [Heartbeat] 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 console.log(chalk.dim(` [Heartbeat] Mentions read failed: ${(error as Error).message}`));\n }\n\n // 3. Build prompts and ask LLM\n const systemPrompt = buildSystemPrompt();\n const userMessage = buildNarratedHeartbeatMessage(timeline, mentions, intervalMs);\n\n const response = await generateResponse(systemPrompt, userMessage);\n\n // 4. Extract narration text (everything outside JSON blocks)\n let narration = response.content.replace(/```json\\s*[\\s\\S]*?```/g, \"\").replace(/\\n{3,}/g, \"\\n\\n\").trim();\n\n // 5. Parse and execute actions\n const actions = parseActions(response.content);\n\n // Build set of valid tweet IDs from timeline + mentions to catch hallucinated IDs\n const validTweetIds = new Set<string>();\n for (const t of timeline) validTweetIds.add(t.id);\n for (const t of mentions) validTweetIds.add(t.id);\n\n // Filter out actions with fake/hallucinated tweet IDs\n const validatedActions = actions.filter(a => {\n if (a.tweetId) {\n // Strip \"tweet:\" prefix the LLM sometimes includes\n const cleanId = a.tweetId.replace(/^tweet:/i, \"\").trim();\n if (!validTweetIds.has(cleanId)) {\n console.log(chalk.yellow(` [Heartbeat] Rejected ${a.action}: tweet ID ${cleanId} not in timeline/mentions (likely hallucinated)`));\n return false;\n }\n }\n return true;\n });\n\n const limitedActions = validatedActions.slice(0, maxActions);\n\n if (limitedActions.length > 0) {\n // Execute actions\n const results = await executeActions(limitedActions);\n\n // Build visible results — use tweet preview tags for post/reply\n const visibleResults: string[] = [];\n for (const r of results) {\n const detail = r.detail ? ` (${r.detail})` : \"\";\n if (r.action === \"schedule\") {\n // Log to terminal only, don't show in chat\n console.log(chalk.dim(` [Heartbeat] ${r.action}: ${r.success ? \"queued\" : r.error}${detail}`));\n } else if (r.success) {\n // Emit tweet preview card for post/reply with content\n if ((r.action === \"post\" || r.action === \"reply\") && r.content) {\n const tweetData = JSON.stringify({ action: r.action, tweetId: r.detail ?? null, content: r.content });\n visibleResults.push(`<<TWEET:${tweetData}>>`);\n console.log(chalk.green(` [Heartbeat] ${r.action}: success (tweet preview)`));\n } else {\n visibleResults.push(`[${r.action}] Done${detail}`);\n console.log(chalk.green(` [Heartbeat] ${r.action}: success${detail}`));\n }\n } else {\n visibleResults.push(`[${r.action}] Failed: ${r.error}`);\n console.log(chalk.red(` [Heartbeat] ${r.action}: ${r.error}`));\n }\n }\n\n // Combine narration with visible action results\n let fullMessage = narration || \"\";\n if (visibleResults.length > 0) {\n fullMessage += (fullMessage ? \"\\n\\n\" : \"\") + visibleResults.join(\"\\n\");\n }\n if (fullMessage) {\n server.pushMessage(\"assistant\", fullMessage);\n }\n } else if (narration) {\n server.pushMessage(\"assistant\", narration);\n }\n\n console.log(chalk.cyan(` [Heartbeat] Complete.`));\n}\n\n/**\n * Open URL in a separate browser window (app-like)\n */\nfunction openBrowser(url: string) {\n const platform = process.platform;\n\n try {\n if (platform === \"darwin\") {\n // Open as a standalone Chrome app window (smaller, separate from existing tabs)\n try {\n execSync(`open -na \"Google Chrome\" --args --app=\"${url}\" --window-size=420,620`, { stdio: \"ignore\" });\n } catch {\n // Fallback: try Chromium-based browsers, then default\n try {\n execSync(`open -na \"Brave Browser\" --args --app=\"${url}\" --window-size=420,620`, { stdio: \"ignore\" });\n } catch {\n execSync(`open \"${url}\"`, { stdio: \"ignore\" });\n }\n }\n } else if (platform === \"win32\") {\n try {\n execSync(`start chrome --app=\"${url}\" --window-size=420,620`, { stdio: \"ignore\" });\n } catch {\n execSync(`start \"\" \"${url}\"`, { stdio: \"ignore\" });\n }\n } else {\n // Linux\n try {\n execSync(`google-chrome --app=\"${url}\" --window-size=420,620`, { stdio: \"ignore\" });\n } catch {\n execSync(`xdg-open \"${url}\"`, { stdio: \"ignore\" });\n }\n }\n } catch (error) {\n // Browser couldn't be opened, that's okay\n console.log(chalk.dim(`(Couldn't open browser automatically - please visit ${url} manually)`));\n }\n}\n\nexport { openBrowser };\n"],"mappings":";;;;;;AAKA,OAAO,UAAU;AACjB,SAAS,WAAW;AACpB,SAAS,oBAAoB;AAC7B,SAAS,MAAM,eAAe;AAC9B,SAAS,qBAAqB;AAE9B,IAAM,aAAa,cAAc,YAAY,GAAG;AAChD,IAAM,YAAY,QAAQ,UAAU;AAgB7B,IAAM,gBAAN,MAAoB;AAAA,EACjB,SAA6B;AAAA,EAC7B;AAAA,EACA,WAA0B,CAAC;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAA+E;AAAA,IACrF,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,YAAY;AAAA,EACd;AAAA,EACQ,cAAkF;AAAA,IACxF,WAAW;AAAA,IACX,eAAe;AAAA,IACf,cAAc;AAAA,EAChB;AAAA,EAEA,YAAY,OAAO,MAAM;AACvB,SAAK,OAAO;AAAA,EACd;AAAA,EAEA,YAA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