spora 0.7.7 → 0.7.8

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.
Files changed (46) hide show
  1. package/dist/{autonomy-NNFTM5NW.js → autonomy-ZMFZRXDZ.js} +7 -7
  2. package/dist/{chunk-BBXHECZ5.js → chunk-6WBIVXOY.js} +1 -1
  3. package/dist/chunk-6WBIVXOY.js.map +1 -0
  4. package/dist/{chunk-JIMONWKO.js → chunk-73CWOI44.js} +4 -4
  5. package/dist/chunk-73CWOI44.js.map +1 -0
  6. package/dist/{chunk-ZLSDFYBR.js → chunk-AIGSCHZK.js} +2 -2
  7. package/dist/{chunk-CP6JWCLY.js → chunk-ER6TILYZ.js} +1 -25
  8. package/dist/{chunk-CP6JWCLY.js.map → chunk-ER6TILYZ.js.map} +1 -1
  9. package/dist/chunk-OLYPPXKP.js +69 -0
  10. package/dist/chunk-OLYPPXKP.js.map +1 -0
  11. package/dist/{chunk-5R4AJZHN.js → chunk-TKGB5LIN.js} +2 -2
  12. package/dist/chunk-TTDQZI5W.js +1699 -0
  13. package/dist/chunk-TTDQZI5W.js.map +1 -0
  14. package/dist/cli.js +28 -28
  15. package/dist/{client-AR5ZD6S4.js → client-3APKWQ6O.js} +3 -3
  16. package/dist/{colony-UGVYALOS.js → colony-7GZ2ODF2.js} +2 -2
  17. package/dist/{heartbeat-WJJSGUAQ.js → heartbeat-CUM7FIHS.js} +23 -7
  18. package/dist/heartbeat-CUM7FIHS.js.map +1 -0
  19. package/dist/heartbeat-narrative-B3RD3OPJ.js +11 -0
  20. package/dist/{init-6HY4ZPFJ.js → init-KL6XSI7E.js} +3 -3
  21. package/dist/mcp-server.js +20 -20
  22. package/dist/{memory-DTSLVSQG.js → memory-G4DNIGLT.js} +2 -2
  23. package/dist/{prompt-builder-ZFUZNQY2.js → prompt-builder-S6PJVEC5.js} +4 -4
  24. package/dist/{queue-QCGNDHH2.js → queue-YPBUUP22.js} +2 -2
  25. package/dist/web-chat/chat.html +15 -5
  26. package/dist/{web-chat-AKUEBSWS.js → web-chat-XNTIDKAS.js} +37 -15
  27. package/dist/web-chat-XNTIDKAS.js.map +1 -0
  28. package/dist/{x-client-S2LUVEKV.js → x-client-2HFEHHVE.js} +2 -2
  29. package/dist/x-client-2HFEHHVE.js.map +1 -0
  30. package/package.json +1 -1
  31. package/dist/chunk-BBXHECZ5.js.map +0 -1
  32. package/dist/chunk-JIMONWKO.js.map +0 -1
  33. package/dist/chunk-TTM54LQR.js +0 -2769
  34. package/dist/chunk-TTM54LQR.js.map +0 -1
  35. package/dist/heartbeat-WJJSGUAQ.js.map +0 -1
  36. package/dist/web-chat-AKUEBSWS.js.map +0 -1
  37. /package/dist/{autonomy-NNFTM5NW.js.map → autonomy-ZMFZRXDZ.js.map} +0 -0
  38. /package/dist/{chunk-ZLSDFYBR.js.map → chunk-AIGSCHZK.js.map} +0 -0
  39. /package/dist/{chunk-5R4AJZHN.js.map → chunk-TKGB5LIN.js.map} +0 -0
  40. /package/dist/{client-AR5ZD6S4.js.map → client-3APKWQ6O.js.map} +0 -0
  41. /package/dist/{colony-UGVYALOS.js.map → colony-7GZ2ODF2.js.map} +0 -0
  42. /package/dist/{memory-DTSLVSQG.js.map → heartbeat-narrative-B3RD3OPJ.js.map} +0 -0
  43. /package/dist/{init-6HY4ZPFJ.js.map → init-KL6XSI7E.js.map} +0 -0
  44. /package/dist/{prompt-builder-ZFUZNQY2.js.map → memory-G4DNIGLT.js.map} +0 -0
  45. /package/dist/{queue-QCGNDHH2.js.map → prompt-builder-S6PJVEC5.js.map} +0 -0
  46. /package/dist/{x-client-S2LUVEKV.js.map → queue-YPBUUP22.js.map} +0 -0
@@ -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 AgentActivity {\n type: \"heartbeat\" | \"action\" | \"status\";\n message: string;\n timestamp: number;\n}\n\n/** Messages pushed from the heartbeat into the chat UI */\nexport interface AgentChatEvent {\n type: \"narration\" | \"tweet\" | \"action\" | \"sleep\" | \"wake\" | \"error\";\n content: string;\n timestamp: number;\n meta?: Record<string, unknown>;\n}\n\ninterface AgentIdentity {\n name: string;\n handle: string;\n bio?: string;\n profileImage?: string;\n}\n\ninterface HeartbeatConfigHandlers {\n getIntervalMs: () => number | Promise<number>;\n setIntervalMs: (intervalMs: number) => void | Promise<void>;\n}\n\nconst ALLOWED_HEARTBEAT_INTERVALS = [60_000, 300_000, 1_800_000, 3_600_000, 21_600_000] as const;\n\nexport class WebChatServer {\n private server: http.Server | null = null;\n private port: number;\n private messages: ChatMessage[] = [];\n private activities: AgentActivity[] = [];\n private agentEvents: AgentChatEvent[] = [];\n private onUserMessage?: (message: string) => Promise<string>;\n private identity?: AgentIdentity;\n private heartbeatConfigHandlers?: HeartbeatConfigHandlers;\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 setHeartbeatConfigHandlers(handlers: HeartbeatConfigHandlers) {\n this.heartbeatConfigHandlers = handlers;\n }\n\n /** Push an activity update (from heartbeat) to the UI — kept for backwards compat */\n pushActivity(type: AgentActivity[\"type\"], message: string) {\n this.activities.push({ type, message, timestamp: Date.now() });\n if (this.activities.length > 100) {\n this.activities = this.activities.slice(-100);\n }\n }\n\n /** Push an event into the chat stream (narration, tweet card, sleep state, etc.) */\n pushAgentEvent(type: AgentChatEvent[\"type\"], content: string, meta?: Record<string, unknown>) {\n this.agentEvents.push({ type, content, timestamp: Date.now(), meta });\n if (this.agentEvents.length > 200) {\n this.agentEvents = this.agentEvents.slice(-200);\n }\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 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 // 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\n if (url.pathname === \"/api/messages\" && req.method === \"GET\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ messages: this.messages }));\n return;\n }\n\n // API: Get agent activity feed (legacy, kept for compat)\n if (url.pathname === \"/api/activity\" && req.method === \"GET\") {\n const since = parseInt(url.searchParams.get(\"since\") || \"0\", 10);\n const newActivities = this.activities.filter((a) => a.timestamp > since);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ activities: newActivities }));\n return;\n }\n\n // API: Get agent events (narration, tweets, sleep) — polled by chat UI\n if (url.pathname === \"/api/agent-events\" && req.method === \"GET\") {\n const since = parseInt(url.searchParams.get(\"since\") || \"0\", 10);\n const newEvents = this.agentEvents.filter((e) => e.timestamp > since);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ events: newEvents }));\n return;\n }\n\n // API: Read heartbeat interval config\n if (url.pathname === \"/api/heartbeat-config\" && req.method === \"GET\") {\n if (!this.heartbeatConfigHandlers) {\n res.writeHead(503, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Heartbeat config unavailable\" }));\n return;\n }\n\n try {\n const intervalMs = await this.heartbeatConfigHandlers.getIntervalMs();\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ intervalMs, allowedIntervals: ALLOWED_HEARTBEAT_INTERVALS }));\n } catch {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Failed to load heartbeat config\" }));\n }\n return;\n }\n\n // API: Update heartbeat interval config\n if (url.pathname === \"/api/heartbeat-config\" && req.method === \"POST\") {\n if (!this.heartbeatConfigHandlers) {\n res.writeHead(503, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Heartbeat config unavailable\" }));\n return;\n }\n const handlers = this.heartbeatConfigHandlers;\n\n let body = \"\";\n req.on(\"data\", (chunk) => {\n body += chunk.toString();\n });\n\n req.on(\"end\", async () => {\n try {\n const parsed = JSON.parse(body) as { intervalMs?: number };\n const intervalMs = parsed.intervalMs;\n\n if (\n typeof intervalMs !== \"number\" ||\n !Number.isInteger(intervalMs) ||\n !ALLOWED_HEARTBEAT_INTERVALS.includes(intervalMs as (typeof ALLOWED_HEARTBEAT_INTERVALS)[number])\n ) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Unsupported heartbeat interval\" }));\n return;\n }\n\n await handlers.setIntervalMs(intervalMs);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ success: true, intervalMs }));\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 // 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 // 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 this.port++;\n this.server?.close();\n this.start().then(resolve).catch(reject);\n } else {\n reject(error);\n }\n });\n });\n }\n\n stop() {\n if (this.server) {\n this.server.close();\n this.server = null;\n }\n }\n}\n","/**\n * Web chat integration with autonomous heartbeat\n */\n\nimport { WebChatServer } from \"./server.js\";\nimport { loadIdentity } from \"../identity/index.js\";\nimport { execSync } from \"node:child_process\";\nimport chalk from \"chalk\";\n\nconst HEARTBEAT_INTERVAL_OPTIONS = [60_000, 300_000, 1_800_000, 3_600_000, 21_600_000] as const;\n\nfunction formatHeartbeatInterval(intervalMs: number): string {\n const minutes = intervalMs / 60_000;\n if (minutes < 60) return `${minutes} minute${minutes === 1 ? \"\" : \"s\"}`;\n const hours = minutes / 60;\n return `${hours} hour${hours === 1 ? \"\" : \"s\"}`;\n}\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 <<TRAINING:{json}>> tags from response, apply updates to identity/strategy/goals, and return cleaned text\n */\nasync function extractAndApplyTraining(responseText: string): Promise<string> {\n const trainingPattern = /<<TRAINING:([\\s\\S]*?)>>/g;\n const matches = [...responseText.matchAll(trainingPattern)];\n\n for (const match of matches) {\n try {\n const update = JSON.parse(match[1].trim());\n\n // Apply identity changes\n if (update.identity) {\n const { loadIdentity, mutateIdentity, saveIdentity } = await import(\"../identity/index.js\");\n let identity = loadIdentity();\n\n const identityFields: Record<string, string> = {\n tone: \"tone\",\n worldview: \"worldview\",\n conflictStyle: \"conflictStyle\",\n vocabularyStyle: \"vocabularyStyle\",\n tweetStyle: \"tweetStyle\",\n };\n\n // Simple string/enum fields\n for (const [key, field] of Object.entries(identityFields)) {\n if (update.identity[key] !== undefined) {\n identity = mutateIdentity(identity, field, update.identity[key], \"training-chat\");\n console.log(chalk.dim(` [Training] Updated ${field}`));\n }\n }\n\n // Array fields (replace entire array)\n const arrayFields = [\"coreValues\", \"topics\", \"avoidTopics\", \"goals\", \"boundaries\", \"catchphrases\", \"heroes\"];\n for (const field of arrayFields) {\n if (update.identity[field] !== undefined && Array.isArray(update.identity[field])) {\n identity = mutateIdentity(identity, field, update.identity[field], \"training-chat\");\n console.log(chalk.dim(` [Training] Updated ${field}`));\n }\n }\n\n // Traits (merge, don't replace)\n if (update.identity.traits && typeof update.identity.traits === \"object\") {\n for (const [trait, value] of Object.entries(update.identity.traits)) {\n if (typeof value === \"number\" && value >= 0 && value <= 1) {\n identity = mutateIdentity(identity, `traits.${trait}`, value, \"training-chat\");\n console.log(chalk.dim(` [Training] Updated traits.${trait} = ${value}`));\n }\n }\n }\n\n // Engagement strategy (merge)\n if (update.identity.engagementStrategy && typeof update.identity.engagementStrategy === \"object\") {\n for (const [key, value] of Object.entries(update.identity.engagementStrategy)) {\n identity = mutateIdentity(identity, `engagementStrategy.${key}`, value, \"training-chat\");\n console.log(chalk.dim(` [Training] Updated engagementStrategy.${key}`));\n }\n }\n\n saveIdentity(identity);\n }\n\n // Apply strategy changes\n if (update.strategy) {\n const { loadStrategy, saveStrategy } = await import(\"../memory/strategy.js\");\n const strategy = loadStrategy();\n\n if (update.strategy.currentFocus) strategy.currentFocus = update.strategy.currentFocus;\n if (update.strategy.shortTermGoals) strategy.shortTermGoals = update.strategy.shortTermGoals;\n if (update.strategy.experiments) {\n strategy.experiments.push(...update.strategy.experiments);\n }\n if (update.strategy.peopleToEngage) {\n strategy.peopleToEngage.push(...update.strategy.peopleToEngage);\n }\n\n strategy.lastUpdated = new Date().toISOString();\n saveStrategy(strategy);\n console.log(chalk.dim(` [Training] Updated strategy`));\n }\n\n // Apply standalone learning\n if (update.learning) {\n const { addLearning } = await import(\"../memory/index.js\");\n addLearning(\n update.learning.content,\n \"training-chat\",\n update.learning.tags || [\"training\"],\n );\n console.log(chalk.dim(` [Training] Saved learning: ${update.learning.content}`));\n }\n\n // Apply reflection to evolution journal\n if (update.reflection) {\n const { loadIdentity, saveIdentity } = await import(\"../identity/index.js\");\n const identity = loadIdentity();\n identity.evolutionJournal.push({\n date: new Date().toISOString(),\n reflection: update.reflection,\n });\n saveIdentity(identity);\n console.log(chalk.dim(` [Training] Added reflection to evolution journal`));\n }\n\n // Apply goal updates\n if (update.goalUpdates && Array.isArray(update.goalUpdates)) {\n const { loadGoals, saveGoals } = await import(\"../memory/goals.js\");\n const tracker = loadGoals();\n\n for (const gu of update.goalUpdates) {\n const existing = tracker.goals.find((g: { goal: string }) => g.goal === gu.goal);\n if (existing) {\n existing.progress = gu.progress;\n existing.lastUpdated = new Date().toISOString();\n } else {\n tracker.goals.push({\n goal: gu.goal,\n progress: gu.progress,\n lastUpdated: new Date().toISOString(),\n });\n }\n }\n\n tracker.lastReviewed = new Date().toISOString();\n saveGoals(tracker);\n console.log(chalk.dim(` [Training] Updated ${update.goalUpdates.length} goal(s)`));\n }\n\n } catch (err) {\n console.error(chalk.dim(` [Training] Failed to parse training update: ${(err as Error).message}`));\n }\n }\n\n // Strip the training tags from the response the user sees\n return responseText.replace(/<<TRAINING:[\\s\\S]*?>>/g, \"\").trim();\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\n/**\n * Run the autonomous heartbeat in the background, narrating to the chat UI\n */\nasync function runNarratedHeartbeat(server: WebChatServer): Promise<void> {\n const { loadConfig } = await import(\"../utils/config.js\");\n const { flushQueue } = await import(\"../scheduler/queue.js\");\n const { runAutonomyCycle } = await import(\"../runtime/autonomy.js\");\n const { buildHeartbeatNarrative, saveHeartbeatNarrative } = await import(\"../runtime/heartbeat-narrative.js\");\n const { buildReflectionPrompt } = await import(\"../runtime/prompt-builder.js\");\n const { generateResponse } = await import(\"../runtime/llm.js\");\n const { addLearning } = await import(\"../memory/index.js\");\n const { loadStrategy, saveStrategy, applyStrategyUpdate } = await import(\"../memory/strategy.js\");\n\n let heartbeatCount = 0;\n let lastIntervalMs = loadConfig().runtime?.heartbeatIntervalMs ?? 300_000;\n\n console.log(chalk.cyan(` [Agent] Autonomous heartbeat started (every ${Math.round(lastIntervalMs / 60_000)} min)`));\n\n while (true) {\n const runtimeConfig = loadConfig();\n const intervalMs = runtimeConfig.runtime?.heartbeatIntervalMs ?? 300_000;\n const maxActions = runtimeConfig.runtime?.actionsPerHeartbeat ?? 4;\n\n if (intervalMs !== lastIntervalMs) {\n server.pushAgentEvent(\"narration\", `Heartbeat interval updated to ${formatHeartbeatInterval(intervalMs)}.`);\n console.log(chalk.cyan(` [Agent] Heartbeat interval updated to ${Math.round(intervalMs / 60_000)} min`));\n lastIntervalMs = intervalMs;\n }\n\n // Sleep first, then heartbeat\n const jitter = Math.floor(Math.random() * intervalMs * 0.3);\n const sleepMs = heartbeatCount === 0 ? 10_000 : intervalMs + jitter;\n const wakeUpAt = Date.now() + sleepMs;\n\n // Show sleep state in chat (skip for first quick boot)\n if (heartbeatCount > 0) {\n server.pushAgentEvent(\"sleep\", \"sleeping\", { wakeUpAt });\n }\n\n // Sleep in short chunks so heartbeat interval changes apply immediately.\n let sleptMs = 0;\n let intervalChangedDuringSleep = false;\n while (sleptMs < sleepMs) {\n const chunkMs = Math.min(1000, sleepMs - sleptMs);\n await new Promise((r) => setTimeout(r, chunkMs));\n sleptMs += chunkMs;\n\n const liveIntervalMs = loadConfig().runtime?.heartbeatIntervalMs ?? 300_000;\n if (liveIntervalMs !== intervalMs) {\n intervalChangedDuringSleep = true;\n break;\n }\n }\n\n if (intervalChangedDuringSleep) {\n continue;\n }\n\n heartbeatCount++;\n console.log(chalk.cyan(` [Agent] Heartbeat #${heartbeatCount}`));\n server.pushAgentEvent(\"wake\", `Waking up... heartbeat #${heartbeatCount}`);\n\n try {\n // 1. Flush queue\n try {\n const flushed = await flushQueue();\n if (flushed.posted > 0) {\n server.pushAgentEvent(\"action\", `Flushed ${flushed.posted} queued post(s)`);\n }\n } catch {\n // Queue flush is best-effort\n }\n\n // 2. Run tool-driven autonomy cycle\n server.pushAgentEvent(\"narration\", \"Observing timeline and planning actions...\");\n const cycle = await runAutonomyCycle(maxActions, heartbeatCount);\n const narrative = buildHeartbeatNarrative({\n heartbeatCount,\n timelineCount: cycle.timeline.length,\n mentionsCount: cycle.mentions.length,\n actions: cycle.actions,\n results: cycle.results,\n });\n saveHeartbeatNarrative(\n narrative.summary,\n cycle.results.length === 0 ? true : cycle.results.every((r) => r.success),\n );\n server.pushAgentEvent(\"narration\", narrative.summary);\n\n if (cycle.timeline.length > 0 || cycle.mentions.length > 0) {\n server.pushAgentEvent(\"narration\", `Found ${cycle.timeline.length} timeline posts and ${cycle.mentions.length} mentions`);\n }\n\n if (cycle.actions.length === 0) {\n server.pushAgentEvent(\"narration\", \"No actions this heartbeat. Going back to sleep.\");\n console.log(chalk.dim(` [Agent] No actions this heartbeat`));\n continue;\n }\n\n // 3. Report results — push tweet cards for posts, narration for everything else\n for (let i = 0; i < cycle.results.length; i++) {\n const result = cycle.results[i];\n const action = cycle.actions[i];\n if (!action) continue;\n\n if (result.success) {\n if (action.action === \"post\" && action.content) {\n server.pushAgentEvent(\"tweet\", action.content, { kind: \"Post\", status: \"Posted to X\", tweetId: result.detail });\n } else if (action.action === \"reply\" && action.content) {\n server.pushAgentEvent(\"tweet\", action.content, {\n kind: \"Reply\",\n status: \"Reply sent\",\n tweetId: result.detail,\n replyTo: action.tweetId,\n });\n } else if (action.action === \"like\") {\n server.pushAgentEvent(\"action\", `Liked a tweet`);\n } else if (action.action === \"retweet\") {\n server.pushAgentEvent(\"action\", `Retweeted`);\n } else if (action.action === \"follow\") {\n server.pushAgentEvent(\"action\", `Followed @${action.handle}`);\n } else if (action.action === \"schedule\" && action.content) {\n server.pushAgentEvent(\"tweet\", action.content, { kind: \"Scheduled\", status: \"Queued\" });\n } else {\n server.pushAgentEvent(\"action\", `${action.action}${result.detail ? `: ${result.detail}` : \"\"}`);\n }\n console.log(chalk.green(` [Agent] ✓ ${result.action}`));\n } else {\n if ((action.action === \"post\" || action.action === \"reply\") && action.content) {\n server.pushAgentEvent(\"tweet\", action.content, {\n kind: action.action === \"reply\" ? \"Reply\" : \"Post\",\n status: `Failed: ${result.error}`,\n replyTo: action.action === \"reply\" ? action.tweetId : undefined,\n });\n } else {\n server.pushAgentEvent(\"error\", `${result.action} failed: ${result.error}`);\n }\n console.log(chalk.red(` [Agent] ✗ ${result.action}: ${result.error}`));\n }\n }\n\n for (const feedback of cycle.policyFeedback) {\n server.pushAgentEvent(\"narration\", `Policy adjusted plan: ${feedback}`);\n }\n\n // Reflection phase — every 3rd heartbeat, review performance\n if (heartbeatCount % 3 === 0) {\n try {\n server.pushAgentEvent(\"narration\", \"Reflecting on recent performance...\");\n const reflectionPrompt = buildReflectionPrompt(cycle.results);\n const reflectionResponse = await generateResponse(\n `You are ${loadIdentity().name}. Reflect honestly on your performance.`,\n reflectionPrompt,\n );\n\n // Parse reflection JSON\n const jsonMatch = reflectionResponse.content.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n const reflection = JSON.parse(jsonMatch[0]);\n if (reflection.learning && reflection.learning !== \"null\") {\n addLearning(reflection.learning, \"reflection\", [\"heartbeat\", \"performance\"]);\n server.pushAgentEvent(\"narration\", `Learned: ${reflection.learning}`);\n console.log(chalk.dim(` [Agent] Reflection learning: ${reflection.learning}`));\n }\n if (reflection.strategyUpdate && reflection.strategyUpdate !== \"null\") {\n const strategy = loadStrategy();\n saveStrategy(applyStrategyUpdate(strategy, reflection.strategyUpdate));\n server.pushAgentEvent(\"narration\", `Strategy: ${reflection.strategyUpdate}`);\n console.log(chalk.dim(` [Agent] Strategy update: ${reflection.strategyUpdate}`));\n }\n } catch {\n // Couldn't parse reflection JSON, that's fine\n }\n }\n } catch (err) {\n console.log(chalk.dim(` [Agent] Reflection failed: ${(err as Error).message}`));\n }\n }\n\n } catch (error) {\n const msg = (error as Error).message;\n console.error(chalk.red(` [Agent] Heartbeat #${heartbeatCount} error: ${msg}`));\n server.pushAgentEvent(\"error\", `Something went wrong: ${msg}`);\n }\n }\n}\n\nexport async function startWebChat() {\n const identity = loadIdentity();\n const { loadConfig: loadRuntimeConfig, saveConfig } = await import(\"../utils/config.js\");\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 });\n\n server.setHeartbeatConfigHandlers({\n getIntervalMs: () => {\n const config = loadRuntimeConfig();\n return config.runtime?.heartbeatIntervalMs ?? 300_000;\n },\n setIntervalMs: (intervalMs) => {\n if (!HEARTBEAT_INTERVAL_OPTIONS.includes(intervalMs as (typeof HEARTBEAT_INTERVAL_OPTIONS)[number])) {\n throw new Error(\"Unsupported heartbeat interval.\");\n }\n\n const config = loadRuntimeConfig();\n config.runtime = {\n heartbeatIntervalMs: intervalMs,\n actionsPerHeartbeat: config.runtime?.actionsPerHeartbeat ?? 4,\n enabled: true,\n };\n saveConfig(config);\n server.pushAgentEvent(\"narration\", `Heartbeat interval set to ${formatHeartbeatInterval(intervalMs)}.`);\n },\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 // Build training prompt on first message, rebuild every 10 messages to refresh memory\n if (!systemPrompt || messageCount % 10 === 0) {\n const { buildTrainingChatPrompt } = await import(\"../runtime/prompt-builder.js\");\n systemPrompt = buildTrainingChatPrompt();\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 llm set --provider <provider>` 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 training updates and learnings from response\n const afterTraining = await extractAndApplyTraining(response.content);\n const cleanResponse = await extractAndSaveLearnings(afterTraining);\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 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 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 autonomous heartbeat in background\n try {\n const { hasLLMKey } = await import(\"../runtime/llm.js\");\n if (hasLLMKey()) {\n runNarratedHeartbeat(server).catch((err) => {\n console.error(chalk.red(`Heartbeat failed to start: ${err}`));\n });\n } else {\n console.log(chalk.yellow(\" [Agent] No LLM key — autonomous heartbeat disabled. Run `spora llm set --provider <provider>` to enable.\"));\n server.pushActivity(\"status\", \"No LLM API key configured. Autonomous mode disabled.\");\n }\n } 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 server.stop();\n process.exit(0);\n });\n\n // Return the server instance for external control\n return server;\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=500,700`, { 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=500,700`, { 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=500,700`, { 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=500,700`, { 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;AAkCpC,IAAM,8BAA8B,CAAC,KAAQ,KAAS,MAAW,MAAW,KAAU;AAE/E,IAAM,gBAAN,MAAoB;AAAA,EACjB,SAA6B;AAAA,EAC7B;AAAA,EACA,WAA0B,CAAC;AAAA,EAC3B,aAA8B,CAAC;AAAA,EAC/B,cAAgC,CAAC;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,OAAO,MAAM;AACvB,SAAK,OAAO;AAAA,EACd;AAAA,EAEA,YAAY,UAAyB;AACnC,SAAK,WAAW;AAAA,EAClB;AAAA,EAEA,kBAAkB,SAA+C;AAC/D,SAAK,gBAAgB;AAAA,EACvB;AAAA,EAEA,2BAA2B,UAAmC;AAC5D,SAAK,0BAA0B;AAAA,EACjC;AAAA;AAAA,EAGA,aAAa,MAA6B,SAAiB;AACzD,SAAK,WAAW,KAAK,EAAE,MAAM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AAS,CAAC;AAAA,MACnD;AAAA,IACF,OAAO;AAEL,UAAI;AACF,iBAAS,wBAAwB,GAAG,2BAA2B,EAAE,OAAO,SAAS,CAAC;AAAA,MACpF,QAAQ;AACN,iBAAS,aAAa,GAAG,KAAK,EAAE,OAAO,SAAS,CAAC;AAAA,MACnD;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAEd,YAAQ,IAAI,MAAM,IAAI,uDAAuD,GAAG,YAAY,CAAC;AAAA,EAC/F;AACF;","names":["loadIdentity"]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  getXClient,
3
3
  resetXClient
4
- } from "./chunk-5R4AJZHN.js";
4
+ } from "./chunk-TKGB5LIN.js";
5
5
  import "./chunk-RSNEVBEI.js";
6
6
  import "./chunk-QYFNAGNI.js";
7
7
  import "./chunk-ZWKTKWS6.js";
@@ -9,4 +9,4 @@ export {
9
9
  getXClient,
10
10
  resetXClient
11
11
  };
12
- //# sourceMappingURL=x-client-S2LUVEKV.js.map
12
+ //# sourceMappingURL=x-client-2HFEHHVE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spora",
3
- "version": "0.7.7",
3
+ "version": "0.7.8",
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/memory/index.ts"],"sourcesContent":["import { readFileSync, writeFileSync, appendFileSync, existsSync, readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { paths, ensureDirectories } from \"../utils/paths.js\";\n\nexport interface InteractionEntry {\n id: string;\n timestamp: string;\n type: \"post\" | \"reply\" | \"like\" | \"retweet\" | \"follow\" | \"mention_received\";\n tweetId?: string;\n targetUserId?: string;\n targetHandle?: string;\n content?: string;\n inReplyTo?: string;\n sentiment?: \"positive\" | \"negative\" | \"neutral\";\n creditsUsed: number;\n success: boolean;\n error?: string;\n}\n\nexport interface Learning {\n id: string;\n timestamp: string;\n content: string;\n source: string;\n tags: string[];\n}\n\nexport interface Relationship {\n handle: string;\n firstSeen: string;\n lastInteraction: string;\n interactionCount: number;\n sentiment: number;\n tags: string[];\n notes: string[];\n isSpore: boolean;\n}\n\nexport interface RelationshipsData {\n accounts: Record<string, Relationship>;\n}\n\nexport interface LearningsData {\n learnings: Learning[];\n}\n\n// --- Interaction Log ---\n\nfunction todayLogPath(): string {\n const date = new Date().toISOString().split(\"T\")[0];\n return join(paths.interactions, `${date}.jsonl`);\n}\n\nexport function logInteraction(entry: InteractionEntry): void {\n ensureDirectories();\n appendFileSync(todayLogPath(), JSON.stringify(entry) + \"\\n\");\n}\n\nexport function getInteractions(date?: string): InteractionEntry[] {\n const targetDate = date ?? new Date().toISOString().split(\"T\")[0];\n const filePath = join(paths.interactions, `${targetDate}.jsonl`);\n\n if (!existsSync(filePath)) return [];\n\n return readFileSync(filePath, \"utf-8\")\n .trim()\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => JSON.parse(line) as InteractionEntry);\n}\n\nexport function getRecentInteractions(count: number = 20): InteractionEntry[] {\n ensureDirectories();\n const files = readdirSync(paths.interactions)\n .filter((f) => f.endsWith(\".jsonl\"))\n .sort()\n .reverse();\n\n const entries: InteractionEntry[] = [];\n for (const file of files) {\n if (entries.length >= count) break;\n const filePath = join(paths.interactions, file);\n const lines = readFileSync(filePath, \"utf-8\").trim().split(\"\\n\").filter(Boolean);\n for (const line of lines.reverse()) {\n if (entries.length >= count) break;\n entries.push(JSON.parse(line) as InteractionEntry);\n }\n }\n\n return entries;\n}\n\n// --- Learnings ---\n\nexport function loadLearnings(): LearningsData {\n if (!existsSync(paths.learnings)) {\n return { learnings: [] };\n }\n return JSON.parse(readFileSync(paths.learnings, \"utf-8\")) as LearningsData;\n}\n\nexport function saveLearnings(data: LearningsData): void {\n ensureDirectories();\n writeFileSync(paths.learnings, JSON.stringify(data, null, 2));\n}\n\nexport function addLearning(content: string, source: string, tags: string[] = []): void {\n const data = loadLearnings();\n data.learnings.push({\n id: `learn-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n timestamp: new Date().toISOString(),\n content,\n source,\n tags,\n });\n saveLearnings(data);\n}\n\n// --- Relationships ---\n\nexport function loadRelationships(): RelationshipsData {\n if (!existsSync(paths.relationships)) {\n return { accounts: {} };\n }\n return JSON.parse(readFileSync(paths.relationships, \"utf-8\")) as RelationshipsData;\n}\n\nexport function saveRelationships(data: RelationshipsData): void {\n ensureDirectories();\n writeFileSync(paths.relationships, JSON.stringify(data, null, 2));\n}\n\nexport function updateRelationship(\n userId: string,\n update: Partial<Relationship> & { handle: string }\n): void {\n const data = loadRelationships();\n const existing = data.accounts[userId];\n\n if (existing) {\n data.accounts[userId] = {\n ...existing,\n ...update,\n lastInteraction: new Date().toISOString(),\n interactionCount: existing.interactionCount + 1,\n };\n } else {\n data.accounts[userId] = {\n handle: update.handle,\n firstSeen: new Date().toISOString(),\n lastInteraction: new Date().toISOString(),\n interactionCount: 1,\n sentiment: update.sentiment ?? 0,\n tags: update.tags ?? [],\n notes: update.notes ?? [],\n isSpore: update.isSpore ?? false,\n };\n }\n\n saveRelationships(data);\n}\n"],"mappings":";;;;;;AAAA,SAAS,cAAc,eAAe,gBAAgB,YAAY,mBAAmB;AACrF,SAAS,YAAY;AA+CrB,SAAS,eAAuB;AAC9B,QAAM,QAAO,oBAAI,KAAK,GAAE,YAAY,EAAE,MAAM,GAAG,EAAE,CAAC;AAClD,SAAO,KAAK,MAAM,cAAc,GAAG,IAAI,QAAQ;AACjD;AAEO,SAAS,eAAe,OAA+B;AAC5D,oBAAkB;AAClB,iBAAe,aAAa,GAAG,KAAK,UAAU,KAAK,IAAI,IAAI;AAC7D;AAEO,SAAS,gBAAgB,MAAmC;AACjE,QAAM,aAAa,SAAQ,oBAAI,KAAK,GAAE,YAAY,EAAE,MAAM,GAAG,EAAE,CAAC;AAChE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,GAAG,CAAC,CAAC;AAAA,IACjE,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IAClC;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACD,gBAAc,IAAI;AACpB;AAIO,SAAS,oBAAuC;AACrD,MAAI,CAAC,WAAW,MAAM,aAAa,GAAG;AACpC,WAAO,EAAE,UAAU,CAAC,EAAE;AAAA,EACxB;AACA,SAAO,KAAK,MAAM,aAAa,MAAM,eAAe,OAAO,CAAC;AAC9D;AAEO,SAAS,kBAAkB,MAA+B;AAC/D,oBAAkB;AAClB,gBAAc,MAAM,eAAe,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAClE;AAEO,SAAS,mBACd,QACA,QACM;AACN,QAAM,OAAO,kBAAkB;AAC/B,QAAM,WAAW,KAAK,SAAS,MAAM;AAErC,MAAI,UAAU;AACZ,SAAK,SAAS,MAAM,IAAI;AAAA,MACtB,GAAG;AAAA,MACH,GAAG;AAAA,MACH,kBAAiB,oBAAI,KAAK,GAAE,YAAY;AAAA,MACxC,kBAAkB,SAAS,mBAAmB;AAAA,IAChD;AAAA,EACF,OAAO;AACL,SAAK,SAAS,MAAM,IAAI;AAAA,MACtB,QAAQ,OAAO;AAAA,MACf,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MAClC,kBAAiB,oBAAI,KAAK,GAAE,YAAY;AAAA,MACxC,kBAAkB;AAAA,MAClB,WAAW,OAAO,aAAa;AAAA,MAC/B,MAAM,OAAO,QAAQ,CAAC;AAAA,MACtB,OAAO,OAAO,SAAS,CAAC;AAAA,MACxB,SAAS,OAAO,WAAW;AAAA,IAC7B;AAAA,EACF;AAEA,oBAAkB,IAAI;AACxB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/runtime/persona-constraints.ts","../src/runtime/persona-action-profile.ts","../src/runtime/prompt-builder.ts"],"sourcesContent":["import { loadIdentity } from \"../identity/index.js\";\nimport type { Identity } from \"../identity/schema.js\";\n\nexport interface PersonaConstraints {\n onlyReplyToHandles: string[];\n onlyInteractWithHandles: string[];\n noOriginalPosts: boolean;\n replyOnlyMode: boolean;\n}\n\nfunction normalizeHandle(handle: string): string {\n return handle.replace(/^@/, \"\").trim().toLowerCase();\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction extractHandles(text: string): string[] {\n const fromMentions = [...text.matchAll(/@([a-zA-Z0-9_]{1,15})/g)].map((m) => m[1]);\n const fromUrls = [...text.matchAll(/x\\.com\\/([a-zA-Z0-9_]{1,15})/gi)].map((m) => m[1]);\n return unique(\n [...fromMentions, ...fromUrls]\n .map(normalizeHandle)\n .filter((handle) => handle.length > 0),\n );\n}\n\nconst BARE_HANDLE_STOPWORDS = new Set([\n \"him\", \"her\", \"them\", \"someone\", \"anyone\", \"everyone\", \"anybody\", \"everybody\",\n \"people\", \"person\", \"users\", \"user\", \"others\", \"other\", \"my\", \"me\", \"you\",\n \"to\", \"with\", \"for\", \"only\", \"just\", \"reply\", \"respond\", \"interact\", \"engage\",\n]);\n\nconst NAME_TO_HANDLE: Array<[RegExp, string]> = [\n [/\\bgrok\\b/i, \"grok\"],\n [/\\belon musk\\b/i, \"elonmusk\"],\n [/\\belon\\b/i, \"elonmusk\"],\n [/\\bmark zuckerberg\\b/i, \"zuck\"],\n [/\\bzuck\\b/i, \"zuck\"],\n [/\\bspora\\s*ai\\b/i, \"sporaai\"],\n [/\\bsporaai\\b/i, \"sporaai\"],\n];\n\nfunction extractBareConstraintTargets(text: string): string[] {\n const found = new Set<string>();\n const candidates = [\n ...text.matchAll(/\\bonly\\s+(?:reply|respond|interact|engage|talk|speak)(?:\\s+\\w+){0,3}\\s+(?:to|with)\\s+@?([a-zA-Z0-9_]{2,15})\\b/gi),\n ...text.matchAll(/\\b(?:reply|respond|interact|engage|talk|speak)\\s+only(?:\\s+\\w+){0,3}\\s+(?:to|with)\\s+@?([a-zA-Z0-9_]{2,15})\\b/gi),\n ];\n for (const match of candidates) {\n const raw = String(match[1] ?? \"\").replace(/'s$/i, \"\");\n const handle = normalizeHandle(raw);\n if (!handle) continue;\n if (!/^[a-z0-9_]{2,15}$/.test(handle)) continue;\n if (BARE_HANDLE_STOPWORDS.has(handle)) continue;\n found.add(handle);\n }\n\n for (const [pattern, handle] of NAME_TO_HANDLE) {\n if (pattern.test(text)) found.add(handle);\n }\n\n return [...found];\n}\n\nfunction includesOnlyQualifier(text: string): boolean {\n return /\\b(only|just|exclusively|strictly)\\b/i.test(text);\n}\n\nfunction includesReplyIntent(text: string): boolean {\n return /\\b(reply|respond|response|replying)\\b/i.test(text);\n}\n\nfunction includesInteractionIntent(text: string): boolean {\n return /\\b(interact|engage|talk|chat|speak|communicate|message)\\b/i.test(text);\n}\n\nfunction impliesNoOriginalPosts(text: string): boolean {\n const lower = text.toLowerCase();\n if (/\\bonly\\s+repl(?:y|ies)\\b/.test(lower)) return true;\n if (/\\brepl(?:y|ies)\\s+only\\b/.test(lower)) return true;\n if (/\\breply-?only\\b/.test(lower)) return true;\n if (/\\b(no|never|don['’]?t|dont|avoid)\\s+(?:do\\s+)?(?:original\\s+)?posts?\\b/.test(lower)) return true;\n if (/\\bno\\s+tweets?\\b/.test(lower)) return true;\n return false;\n}\n\nexport function getPersonaConstraints(identityArg?: Identity): PersonaConstraints {\n const identity = identityArg ?? loadIdentity();\n const strictReplyHandles = new Set<string>();\n const strictInteractionHandles = new Set<string>();\n\n const lines = [\n ...(identity.goals ?? []),\n ...(identity.boundaries ?? []),\n identity.bio ?? \"\",\n identity.originStory ?? \"\",\n identity.worldview ?? \"\",\n identity.tone ?? \"\",\n ].filter((value) => typeof value === \"string\" && value.trim().length > 0);\n\n let replyOnlyMode = false;\n let noOriginalPosts = false;\n\n for (const line of lines) {\n const handles = unique([\n ...extractHandles(line),\n ...extractBareConstraintTargets(line),\n ]);\n const hasOnly = includesOnlyQualifier(line);\n const hasReply = includesReplyIntent(line);\n const hasInteract = includesInteractionIntent(line);\n\n if (impliesNoOriginalPosts(line)) {\n replyOnlyMode = true;\n noOriginalPosts = true;\n }\n\n if (hasOnly && hasReply) {\n replyOnlyMode = true;\n noOriginalPosts = true;\n for (const handle of handles) {\n strictReplyHandles.add(handle);\n strictInteractionHandles.add(handle);\n }\n continue;\n }\n\n if (hasOnly && hasInteract) {\n noOriginalPosts = true;\n for (const handle of handles) {\n strictInteractionHandles.add(handle);\n }\n }\n }\n\n if (strictReplyHandles.size > 0) {\n replyOnlyMode = true;\n noOriginalPosts = true;\n }\n if (strictInteractionHandles.size > 0) {\n noOriginalPosts = true;\n }\n\n return {\n onlyReplyToHandles: [...strictReplyHandles],\n onlyInteractWithHandles: [...strictInteractionHandles],\n noOriginalPosts,\n replyOnlyMode,\n };\n}\n\nexport function personaConstraintHandles(constraints: PersonaConstraints): string[] {\n return unique([\n ...constraints.onlyReplyToHandles.map(normalizeHandle),\n ...constraints.onlyInteractWithHandles.map(normalizeHandle),\n ]).filter(Boolean);\n}\n\nexport function buildPersonaConstraintLines(constraints: PersonaConstraints): string[] {\n const lines: string[] = [];\n if (constraints.onlyReplyToHandles.length > 0) {\n lines.push(`- Hard constraint: only reply to @${constraints.onlyReplyToHandles.join(\", @\")}`);\n } else if (constraints.replyOnlyMode) {\n lines.push(\"- Hard constraint: reply-only mode (no like/retweet/follow/post actions).\");\n }\n\n const onlyInteract = constraints.onlyInteractWithHandles.filter(\n (handle) => !constraints.onlyReplyToHandles.includes(handle),\n );\n if (onlyInteract.length > 0) {\n lines.push(`- Hard constraint: only interact with @${onlyInteract.join(\", @\")}`);\n }\n\n if (constraints.noOriginalPosts) {\n lines.push(\"- Hard constraint: do not create standalone original posts.\");\n }\n\n return lines;\n}\n","import type { Identity } from \"../identity/schema.js\";\nimport type { Strategy } from \"../memory/strategy.js\";\nimport type { PersonaConstraints } from \"./persona-constraints.js\";\n\nexport type PersonaActionType = \"reply\" | \"like\" | \"retweet\" | \"follow\" | \"post\";\nexport type PersonaSourceType = \"mention\" | \"timeline\" | \"topic_search\" | \"people_watch\" | \"synthesis\";\n\nexport interface PersonaActionProfile {\n actionBias: Record<PersonaActionType, number>;\n sourceBias: Record<PersonaSourceType, number>;\n prioritizedActions: PersonaActionType[];\n priorityTopics: string[];\n rationale: string[];\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)];\n}\n\nfunction normalizeText(text: string): string {\n return text.toLowerCase().trim();\n}\n\nfunction hasAny(text: string, terms: string[]): boolean {\n const lower = normalizeText(text);\n return terms.some((term) => lower.includes(term));\n}\n\nfunction applyGoalBias(\n actionBias: Record<PersonaActionType, number>,\n sourceBias: Record<PersonaSourceType, number>,\n goals: string[],\n rationale: string[],\n): void {\n for (const goal of goals) {\n if (hasAny(goal, [\"grow followers\", \"go viral\", \"audience\", \"reach\"])) {\n actionBias.reply += 0.35;\n actionBias.post += 0.45;\n sourceBias.mention += 0.2;\n rationale.push(\"growth goals favor reply+post mix\");\n }\n if (hasAny(goal, [\"build community\", \"community\", \"connect\", \"relationships\"])) {\n actionBias.reply += 0.4;\n actionBias.like += 0.3;\n actionBias.follow += 0.45;\n sourceBias.people_watch += 0.35;\n rationale.push(\"community goals favor social interaction actions\");\n }\n if (hasAny(goal, [\"debate\", \"challenge\", \"argue\", \"provoc\"])) {\n actionBias.reply += 0.5;\n sourceBias.mention += 0.25;\n rationale.push(\"debate goals bias toward replies in active conversations\");\n }\n if (hasAny(goal, [\"curate\", \"signal\", \"filter\"])) {\n actionBias.retweet += 0.8;\n actionBias.like += 0.2;\n sourceBias.topic_search += 0.35;\n rationale.push(\"curation goals bias toward retweet/like actions\");\n }\n if (hasAny(goal, [\"seek truth\", \"research\", \"facts\", \"evidence\"])) {\n actionBias.reply += 0.25;\n actionBias.post += 0.2;\n sourceBias.topic_search += 0.45;\n rationale.push(\"truth-seeking goals bias toward topic-search grounded actions\");\n }\n }\n}\n\nexport function compilePersonaActionProfile(input: {\n identity: Identity;\n strategy: Strategy;\n constraints: PersonaConstraints;\n}): PersonaActionProfile {\n const { identity, strategy, constraints } = input;\n const rationale: string[] = [];\n\n const actionBias: Record<PersonaActionType, number> = {\n reply: 0,\n like: 0,\n retweet: 0,\n follow: 0,\n post: 0,\n };\n\n const sourceBias: Record<PersonaSourceType, number> = {\n mention: 0,\n timeline: 0,\n topic_search: 0,\n people_watch: 0,\n synthesis: 0,\n };\n\n // Baseline from explicit content mix (this is the strongest broad persona signal).\n const mix = identity.engagementStrategy.contentMix;\n actionBias.post += (mix.originalPosts - 25) / 25;\n actionBias.reply += (mix.replies - 30) / 25;\n actionBias.retweet += (mix.retweets - 15) / 20;\n actionBias.like += (mix.likes - 15) / 20;\n rationale.push(\"contentMix translated into action priors\");\n\n // Reply style => source/action pattern\n if (identity.engagementStrategy.replyStyle === \"strategic\") {\n actionBias.reply += 0.3;\n sourceBias.people_watch += 0.35;\n sourceBias.topic_search += 0.25;\n sourceBias.timeline -= 0.15;\n rationale.push(\"strategic replyStyle favors selective people/topic opportunities\");\n } else if (identity.engagementStrategy.replyStyle === \"reactive\") {\n actionBias.reply += 0.4;\n sourceBias.mention += 0.45;\n sourceBias.timeline += 0.2;\n rationale.push(\"reactive replyStyle favors mentions/timeline\");\n } else if (identity.engagementStrategy.replyStyle === \"generous\") {\n actionBias.reply += 0.25;\n actionBias.like += 0.25;\n sourceBias.mention += 0.25;\n sourceBias.timeline += 0.2;\n rationale.push(\"generous replyStyle favors broader conversation participation\");\n } else if (identity.engagementStrategy.replyStyle === \"selective\") {\n sourceBias.people_watch += 0.25;\n sourceBias.topic_search += 0.2;\n sourceBias.timeline -= 0.2;\n rationale.push(\"selective replyStyle favors quality-filtered contexts\");\n }\n\n // Follow strategy\n if (identity.engagementStrategy.followStrategy === \"aggressive\") {\n actionBias.follow += 0.7;\n rationale.push(\"aggressive followStrategy boosts follow actions\");\n } else if (identity.engagementStrategy.followStrategy === \"none\") {\n actionBias.follow -= 2.0;\n rationale.push(\"followStrategy=none suppresses follow actions\");\n } else if (identity.engagementStrategy.followStrategy === \"curated\") {\n actionBias.follow -= 0.25;\n sourceBias.people_watch += 0.15;\n rationale.push(\"curated followStrategy slightly restricts follow actions\");\n }\n\n // Traits\n const traits = identity.traits;\n if (traits.curiosity >= 0.65) {\n actionBias.reply += 0.35;\n sourceBias.mention += 0.2;\n sourceBias.people_watch += 0.2;\n rationale.push(\"high curiosity increases reply preference\");\n }\n if (traits.empathy >= 0.65) {\n actionBias.like += 0.35;\n actionBias.follow += 0.25;\n rationale.push(\"high empathy increases supportive actions\");\n }\n if (traits.confidence >= 0.7 || traits.aggression >= 0.65) {\n actionBias.reply += 0.25;\n actionBias.post += 0.15;\n actionBias.like -= 0.15;\n rationale.push(\"assertive traits increase reply/post decisiveness\");\n }\n if (traits.originality >= 0.7) {\n actionBias.post += 0.25;\n actionBias.reply += 0.1;\n sourceBias.synthesis += 0.25;\n rationale.push(\"high originality favors fresh synthesis posts\");\n }\n if (traits.humor >= 0.7) {\n actionBias.reply += 0.15;\n actionBias.post += 0.15;\n sourceBias.timeline += 0.15;\n rationale.push(\"high humor increases conversational/timeline engagement\");\n }\n\n // Voice style preferences\n if (identity.vocabularyStyle === \"casual\" || identity.vocabularyStyle === \"internet-native\") {\n actionBias.reply += 0.2;\n actionBias.like += 0.1;\n sourceBias.timeline += 0.2;\n sourceBias.synthesis -= 0.15;\n rationale.push(\"casual/internet-native vocabulary favors timeline-native interactions\");\n }\n if (identity.tweetStyle === \"one-liners\" || identity.tweetStyle === \"short-form\") {\n actionBias.reply += 0.25;\n actionBias.like += 0.15;\n actionBias.post -= 0.15;\n sourceBias.timeline += 0.2;\n rationale.push(\"short tweet style favors reactive conversational actions\");\n } else if (identity.tweetStyle === \"threads\") {\n actionBias.post += 0.25;\n sourceBias.synthesis += 0.2;\n rationale.push(\"thread style favors synthesis-driven posting\");\n }\n\n if (identity.framework !== \"philosopher\") {\n sourceBias.synthesis -= 0.1;\n rationale.push(\"non-philosopher frameworks slightly downweight abstract synthesis\");\n }\n\n // Framework-level priors\n switch (identity.framework) {\n case \"conqueror\":\n actionBias.post += 0.45;\n actionBias.reply += 0.35;\n actionBias.follow += 0.25;\n actionBias.like -= 0.2;\n sourceBias.mention += 0.15;\n rationale.push(\"conqueror framework favors decisive high-visibility actions\");\n break;\n case \"authentic\":\n actionBias.reply += 0.45;\n actionBias.like += 0.4;\n actionBias.follow += 0.2;\n actionBias.post += 0.1;\n sourceBias.mention += 0.25;\n sourceBias.timeline += 0.2;\n sourceBias.synthesis -= 0.15;\n rationale.push(\"authentic framework favors relational and grounded conversation\");\n break;\n case \"curator\":\n actionBias.retweet += 0.8;\n actionBias.like += 0.3;\n actionBias.post -= 0.2;\n rationale.push(\"curator framework favors retweets/likes\");\n break;\n case \"community-builder\":\n actionBias.reply += 0.35;\n actionBias.like += 0.3;\n actionBias.follow += 0.35;\n rationale.push(\"community-builder framework favors relationship actions\");\n break;\n case \"growth-hacker\":\n actionBias.post += 0.3;\n actionBias.reply += 0.25;\n rationale.push(\"growth-hacker framework favors visible output + replies\");\n break;\n case \"truthseeker\":\n actionBias.reply += 0.25;\n actionBias.post += 0.2;\n sourceBias.topic_search += 0.3;\n rationale.push(\"truthseeker framework favors research-grounded conversation\");\n break;\n case \"philosopher\":\n actionBias.post += 0.35;\n actionBias.reply += 0.1;\n sourceBias.synthesis += 0.25;\n rationale.push(\"philosopher framework leans toward original perspective posts\");\n break;\n case \"provocateur\":\n actionBias.reply += 0.55;\n actionBias.post += 0.35;\n actionBias.like -= 0.15;\n sourceBias.mention += 0.25;\n sourceBias.timeline += 0.15;\n rationale.push(\"provocateur framework favors sharp, conversational confrontation\");\n break;\n case \"shitposter\":\n actionBias.post += 0.45;\n actionBias.reply += 0.25;\n sourceBias.timeline += 0.2;\n rationale.push(\"shitposter framework favors high-frequency social expression\");\n break;\n default:\n break;\n }\n\n applyGoalBias(actionBias, sourceBias, identity.goals ?? [], rationale);\n\n // Strategy focus momentum nudges source discovery.\n if ((strategy.currentFocus ?? []).length > 0 || (strategy.shortTermGoals ?? []).length > 0) {\n sourceBias.topic_search += 0.2;\n sourceBias.people_watch += 0.15;\n rationale.push(\"active strategy focus boosts targeted discovery sources\");\n }\n\n // Hard constraints still override broad bias.\n if (constraints.noOriginalPosts) {\n actionBias.post -= 2.0;\n rationale.push(\"hard constraint suppresses original posts\");\n }\n if (constraints.replyOnlyMode) {\n actionBias.reply += 1.5;\n actionBias.like -= 1.2;\n actionBias.retweet -= 1.2;\n actionBias.follow -= 1.2;\n actionBias.post -= 2.0;\n rationale.push(\"reply-only hard constraint dominates action policy\");\n }\n\n const clampedActionBias: Record<PersonaActionType, number> = {\n reply: clamp(actionBias.reply, -2.5, 2.5),\n like: clamp(actionBias.like, -2.5, 2.5),\n retweet: clamp(actionBias.retweet, -2.5, 2.5),\n follow: clamp(actionBias.follow, -2.5, 2.5),\n post: clamp(actionBias.post, -2.5, 2.5),\n };\n\n const clampedSourceBias: Record<PersonaSourceType, number> = {\n mention: clamp(sourceBias.mention, -1.5, 1.5),\n timeline: clamp(sourceBias.timeline, -1.5, 1.5),\n topic_search: clamp(sourceBias.topic_search, -1.5, 1.5),\n people_watch: clamp(sourceBias.people_watch, -1.5, 1.5),\n synthesis: clamp(sourceBias.synthesis, -1.5, 1.5),\n };\n\n const prioritizedActions = (Object.entries(clampedActionBias) as Array<[PersonaActionType, number]>)\n .sort((a, b) => b[1] - a[1])\n .map(([action]) => action);\n\n const priorityTopics = unique(\n [\n ...(identity.topics ?? []),\n ...(strategy.currentFocus ?? []),\n ...(strategy.shortTermGoals ?? []),\n ]\n .map((topic) => String(topic).trim())\n .filter(Boolean)\n .slice(0, 12),\n );\n\n return {\n actionBias: clampedActionBias,\n sourceBias: clampedSourceBias,\n prioritizedActions,\n priorityTopics,\n rationale: unique(rationale).slice(0, 12),\n };\n}\n","import { loadIdentity, renderIdentityDocument } from \"../identity/index.js\";\nimport { loadConfig } from \"../utils/config.js\";\nimport { getRecentInteractions, loadLearnings, loadRelationships } from \"../memory/index.js\";\nimport { renderActiveIntentsForPrompt } from \"../memory/intents.js\";\nimport { rateLimiter } from \"../x-client/rate-limiter.js\";\nimport { loadStrategy, renderStrategyForPrompt } from \"../memory/strategy.js\";\nimport { renderGoalsForPrompt } from \"../memory/goals.js\";\nimport { getPerformanceSummary } from \"../memory/performance.js\";\nimport { buildPersonaConstraintLines, getPersonaConstraints } from \"./persona-constraints.js\";\nimport { compilePersonaActionProfile } from \"./persona-action-profile.js\";\nimport type { Tweet } from \"../x-client/types.js\";\nimport type { AgentAction, ActionResult } from \"./decision-engine.js\";\nimport type { ResearchContext } from \"./research.js\";\nimport type { ActionOpportunity } from \"./opportunity-engine.js\";\nimport type { Identity } from \"../identity/schema.js\";\n\nconst PROMPT_TOKEN_STOPWORDS = new Set([\n \"about\", \"after\", \"again\", \"against\", \"among\", \"because\", \"being\", \"between\", \"could\", \"every\",\n \"first\", \"from\", \"going\", \"have\", \"having\", \"into\", \"just\", \"like\", \"more\", \"most\", \"only\",\n \"other\", \"over\", \"really\", \"same\", \"some\", \"than\", \"that\", \"their\", \"there\", \"these\", \"they\",\n \"this\", \"those\", \"through\", \"very\", \"what\", \"when\", \"where\", \"which\", \"while\", \"with\", \"would\",\n \"your\", \"youre\", \"dont\", \"cant\", \"will\", \"also\", \"tweet\", \"tweets\", \"thread\", \"threads\",\n \"future\", \"human\", \"humans\", \"technology\", \"tech\", \"agent\", \"agents\", \"build\", \"building\",\n]);\n\nfunction normalizeForPrompt(text: string): string {\n return text\n .toLowerCase()\n .replace(/https?:\\/\\/\\S+/g, \" \")\n .replace(/[@#]\\w+/g, \" \")\n .replace(/[^a-z0-9\\s]/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction recentWrittenTextsForPrompt(limit: number = 12): string[] {\n return getRecentInteractions(60)\n .filter((entry) => entry.type === \"post\" || entry.type === \"reply\")\n .map((entry) => entry.content ?? \"\")\n .filter((text) => text.trim().length > 0)\n .slice(0, limit);\n}\n\nfunction findOverusedOpenings(texts: string[]): string[] {\n const counts = new Map<string, number>();\n for (const text of texts) {\n const opening = normalizeForPrompt(text).split(\" \").filter(Boolean).slice(0, 4).join(\" \");\n if (!opening || opening.split(\" \").length < 3) continue;\n counts.set(opening, (counts.get(opening) ?? 0) + 1);\n }\n return [...counts.entries()]\n .filter(([, count]) => count >= 2)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 4)\n .map(([opening]) => opening);\n}\n\nfunction findOverusedTokens(texts: string[]): string[] {\n const counts = new Map<string, number>();\n for (const text of texts) {\n const tokens = new Set(\n normalizeForPrompt(text)\n .split(\" \")\n .filter((token) => token.length >= 5 && !PROMPT_TOKEN_STOPWORDS.has(token)),\n );\n for (const token of tokens) {\n counts.set(token, (counts.get(token) ?? 0) + 1);\n }\n }\n return [...counts.entries()]\n .filter(([, count]) => count >= 3)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 6)\n .map(([token]) => token);\n}\n\nfunction buildVoiceLockLines(identity: Identity): string[] {\n const lines: string[] = [];\n const { traits } = identity;\n const assertive =\n traits.confidence >= 0.72 ||\n traits.aggression >= 0.62 ||\n identity.conflictStyle === \"clap-back\" ||\n identity.conflictStyle === \"debate\";\n\n lines.push(`- Tone anchor: ${identity.tone}`);\n lines.push(`- Conflict style: ${identity.conflictStyle}`);\n lines.push(`- Vocabulary: ${identity.vocabularyStyle}; tweet style: ${identity.tweetStyle}`);\n\n if (assertive) {\n lines.push(\"- Be stubborn and decisive. Take a side. Do not hedge or play both sides.\");\n }\n if (traits.curiosity >= 0.72) {\n lines.push(\"- Ask sharp questions when engaging. Curiosity should show up in replies.\");\n }\n if (traits.verbosity <= 0.48) {\n lines.push(\"- Keep replies punchy: 1-2 short sentences unless a longer reply is truly necessary.\");\n } else {\n lines.push(\"- Keep replies compact and human; avoid essay-like paragraphs.\");\n }\n\n if (identity.catchphrases.length > 0) {\n lines.push(`- Your signature phrases: ${identity.catchphrases.slice(0, 3).join(\" | \")} (use occasionally, not every post).`);\n }\n if (identity.framework !== \"philosopher\") {\n lines.push(\"- Do NOT use philosopher framing: avoid lines like 'the real question', 'the deeper question', or abstract manifesto language.\");\n lines.push(\"- Ground every post/reply in concrete context: a person, a claim, an event, or a direct observation.\");\n }\n lines.push(\"- If the reply could be posted by any generic AI account, rewrite it.\");\n return lines;\n}\n\nexport function buildSystemPrompt(): string {\n const identity = loadIdentity();\n const constraints = getPersonaConstraints(identity);\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(\"## Voice Lock (Non-Negotiable)\");\n for (const line of buildVoiceLockLines(identity)) {\n sections.push(line);\n }\n const constraintLines = buildPersonaConstraintLines(constraints);\n if (constraintLines.length > 0) {\n sections.push(\"- Operational constraints override all other behavior:\");\n for (const line of constraintLines) {\n sections.push(` ${line}`);\n }\n }\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 intentsText = renderActiveIntentsForPrompt();\n if (intentsText) {\n sections.push(\"### Active Mission Intents\");\n for (const line of intentsText.split(\"\\n\")) {\n if (!line || line.startsWith(\"**Active mission intents:**\")) continue;\n sections.push(line);\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. Tweet like a real person — be conversational, opinionated, and curious. NEVER write dry, explanatory, or educational-sounding tweets.\");\n sections.push(\"7. Prioritize engagement (replies, likes, conversation) over broadcasting original posts.\");\n if (identity.boundaries.length > 0) {\n sections.push(`8. Respect your boundaries: ${identity.boundaries.join(\", \")}`);\n }\n\n return sections.join(\"\\n\");\n}\n\nexport function buildHeartbeatUserMessage(research: ResearchContext): string {\n const parts: string[] = [];\n\n parts.push(\"It's time for your heartbeat cycle. Here's what you found while scanning:\");\n parts.push(\"\");\n\n // Mentions first — direct engagement is highest priority\n if (research.mentions.length > 0) {\n parts.push(\"## Mentions (people talking to/about you)\");\n for (const t of research.mentions.slice(0, 10)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes)`);\n }\n parts.push(\"\");\n }\n\n // Timeline\n if (research.timeline.length > 0) {\n parts.push(\"## Timeline (your feed)\");\n for (const t of research.timeline.slice(0, 15)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes, ${t.retweetCount ?? 0} RTs)`);\n }\n parts.push(\"\");\n }\n\n // Topic search results\n if (research.topicSearchResults.length > 0) {\n parts.push(\"## Topic Research (conversations in your interest areas)\");\n for (const result of research.topicSearchResults) {\n parts.push(`### Search: \"${result.query}\"`);\n for (const t of result.tweets.slice(0, 5)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes, ${t.replyCount ?? 0} replies)`);\n }\n }\n parts.push(\"\");\n }\n\n // People monitoring\n if (research.peopleActivity.length > 0) {\n parts.push(\"## People You're Watching (recent activity from key accounts)\");\n for (const person of research.peopleActivity) {\n parts.push(`### @${person.handle} (${person.reason})`);\n for (const t of person.tweets.slice(0, 3)) {\n parts.push(`- \"${t.text}\" [tweet:${t.id}] (${t.likeCount ?? 0} likes, ${t.replyCount ?? 0} replies)`);\n }\n }\n parts.push(\"\");\n }\n\n // Own post performance\n if (research.ownPostPerformance.length > 0) {\n parts.push(\"## How Your Recent Posts Are Doing\");\n for (const post of research.ownPostPerformance) {\n const latest = post.metrics.length > 0 ? post.metrics[post.metrics.length - 1] : null;\n const likes = latest?.likes ?? 0;\n const rts = latest?.retweets ?? 0;\n const replies = latest?.replies ?? 0;\n parts.push(`- \"${post.content.slice(0, 80)}...\" — ${likes} likes, ${rts} RTs, ${replies} replies`);\n }\n parts.push(\"\");\n }\n\n parts.push(\"## How to Act Like a Real Person on Twitter\");\n parts.push(\"\");\n parts.push(\"You are NOT a content bot. You are a person with opinions, curiosity, and relationships.\");\n parts.push(\"Think about what a real person with your personality would actually do when they open Twitter:\");\n parts.push(\"\");\n parts.push(\"**DO:**\");\n parts.push(\"- React to what you see — reply to interesting takes, ask questions, share hot takes\");\n parts.push(\"- Be conversational — write tweets like you're talking to friends, not giving a lecture\");\n parts.push(\"- Have opinions — agree, disagree, push back, get excited\");\n parts.push(\"- Ask genuine questions that spark conversation\");\n parts.push(\"- Use casual language, incomplete thoughts, humor, or surprise\");\n parts.push(\"- Like and retweet things that genuinely resonate with you\");\n parts.push(\"- Build relationships — reply to the same people, develop running conversations\");\n parts.push(\"\");\n parts.push(\"**DON'T:**\");\n parts.push(\"- Write explanatory or educational posts (\\\"Here's why X matters...\\\")\");\n parts.push(\"- Start tweets with \\\"I think\\\" or \\\"This is interesting because\\\"\");\n parts.push(\"- Use philosopher opener templates like \\\"The real question is...\\\" or \\\"The deeper question is...\\\"\");\n parts.push(\"- Use colon/semicolon/em-dash manifesto framing in normal tweets\");\n parts.push(\"- Write like a blog post or article — this is Twitter, keep it punchy\");\n parts.push(\"- Post generic observations nobody would engage with\");\n parts.push(\"- Ignore your timeline and just post into the void\");\n parts.push(\"\");\n parts.push(\"**Prioritize replying and engaging over original posts.** Real people spend more time reacting than broadcasting.\");\n parts.push(\"\");\n parts.push(\"## Your Task\");\n parts.push(\"Choose 1-3 actions. Available:\");\n parts.push(\"\");\n parts.push(\"- `post` — Original tweet (`content`, max 280 chars)\");\n parts.push(\"- `reply` — Reply to a tweet (`tweetId` + `content`)\");\n parts.push(\"- `like` — Like a tweet (`tweetId`)\");\n parts.push(\"- `retweet` — Retweet (`tweetId`)\");\n parts.push(\"- `follow` — Follow a user (`handle`)\");\n parts.push(\"- `schedule` — Queue for later (`content`)\");\n parts.push(\"- `skip` — Do nothing (`reason`)\");\n parts.push(\"\");\n parts.push(\"Respond with a JSON array:\");\n parts.push(\"```json\");\n parts.push('[');\n parts.push(' { \"action\": \"reply\", \"tweetId\": \"123\", \"content\": \"wait this is actually wild\", \"reasoning\": \"reacting to interesting take\" },');\n parts.push(' { \"action\": \"like\", \"tweetId\": \"456\", \"reasoning\": \"good thread worth supporting\" }');\n parts.push(']');\n parts.push(\"```\");\n\n return parts.join(\"\\n\");\n}\n\ninterface ToolDecisionPromptInput {\n step: number;\n maxActions: number;\n timeline: Tweet[];\n mentions: Tweet[];\n topicSearchResults?: ResearchContext[\"topicSearchResults\"];\n peopleActivity?: ResearchContext[\"peopleActivity\"];\n executedActions: AgentAction[];\n policyFeedback: string[];\n blockedTweetIds?: string[];\n disallowedActions?: string[];\n}\n\ninterface OpportunityPortfolioPromptInput {\n opportunities: ActionOpportunity[];\n maxActions: number;\n policyFeedback: string[];\n executedActions: AgentAction[];\n}\n\nexport function buildToolDecisionMessage(input: ToolDecisionPromptInput): string {\n const identity = loadIdentity();\n const strategy = loadStrategy();\n const {\n step,\n maxActions,\n timeline,\n mentions,\n topicSearchResults = [],\n peopleActivity = [],\n executedActions,\n policyFeedback,\n blockedTweetIds = [],\n disallowedActions = [],\n } = input;\n const parts: string[] = [];\n\n parts.push(`Heartbeat step ${step + 1} of ${maxActions}.`);\n parts.push(\"\");\n parts.push(\"You are choosing ONE next tool action.\");\n parts.push(\"Priorities:\");\n parts.push(\"1. Be socially immersed: engage with real people, not just broadcast.\");\n parts.push(\"2. Prefer context-aware replies/likes/follows when relevant.\");\n parts.push(\"3. Avoid repetitive templates, slogans, and lecture-like formats.\");\n parts.push(\"4. Ask questions sometimes. Curiosity beats certainty.\");\n parts.push(\"5. Never reuse the same wording across replies; tailor each reply to the specific tweet.\");\n parts.push(\"6. Never interact with your own tweets. No self-replies, self-likes, or self-retweets.\");\n parts.push(\"\");\n\n const priorityTargets = strategy.peopleToEngage\n .filter((person) => person.priority === \"high\")\n .map((person) => `@${person.handle.replace(/^@/, \"\")}`);\n if (priorityTargets.length > 0) {\n parts.push(`Priority targets: ${priorityTargets.slice(0, 5).join(\", \")}`);\n parts.push(\"If any priority target appears in current context, prefer engaging them.\");\n parts.push(\"\");\n }\n\n parts.push(\"Voice lock:\");\n for (const line of buildVoiceLockLines(identity)) {\n parts.push(line);\n }\n parts.push(\"\");\n\n if (policyFeedback.length > 0) {\n parts.push(\"Policy feedback from previous attempts:\");\n for (const feedback of policyFeedback.slice(-5)) {\n parts.push(`- ${feedback}`);\n }\n parts.push(\"\");\n }\n\n if (executedActions.length > 0) {\n parts.push(\"Actions already executed this heartbeat:\");\n for (const action of executedActions) {\n parts.push(`- ${JSON.stringify(action)}`);\n }\n parts.push(\"\");\n }\n\n if (blockedTweetIds.length > 0) {\n parts.push(\"Tweet IDs you must NOT use this heartbeat:\");\n parts.push(`- ${blockedTweetIds.slice(0, 20).join(\", \")}`);\n parts.push(\"\");\n }\n\n if (disallowedActions.length > 0) {\n parts.push(`Temporarily disallowed actions this heartbeat: ${disallowedActions.join(\", \")}`);\n parts.push(\"\");\n }\n\n if (mentions.length > 0) {\n parts.push(\"Mentions:\");\n for (const t of mentions.slice(0, 10)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}]`);\n }\n parts.push(\"\");\n }\n\n if (timeline.length > 0) {\n parts.push(\"Timeline:\");\n for (const t of timeline.slice(0, 20)) {\n parts.push(`- @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}]`);\n }\n parts.push(\"\");\n }\n\n if (topicSearchResults.length > 0) {\n parts.push(\"Topic Search (fresh conversations beyond your home timeline):\");\n for (const result of topicSearchResults.slice(0, 2)) {\n parts.push(`- Query: \"${result.query}\"`);\n for (const t of result.tweets.slice(0, 4)) {\n parts.push(` - @${t.authorHandle}: \"${t.text}\" [tweet:${t.id}]`);\n }\n }\n parts.push(\"\");\n }\n\n if (peopleActivity.length > 0) {\n parts.push(\"People Monitoring (accounts you track):\");\n for (const person of peopleActivity.slice(0, 3)) {\n parts.push(`- @${person.handle} (${person.reason})`);\n for (const t of person.tweets.slice(0, 2)) {\n parts.push(` - \"${t.text}\" [tweet:${t.id}]`);\n }\n }\n parts.push(\"\");\n }\n\n parts.push(\"Available tools (choose one):\");\n parts.push(\"- post { content, reasoning }\");\n parts.push(\"- reply { tweetId, content, reasoning }\");\n parts.push(\"- like { tweetId, reasoning }\");\n parts.push(\"- retweet { tweetId, reasoning }\");\n parts.push(\"- follow { handle, reasoning }\");\n parts.push(\"- schedule { content, reasoning }\");\n parts.push(\"- learn { content, tags?, reasoning }\");\n parts.push(\"- reflect { content, reasoning }\");\n parts.push(\"- skip { reason }\");\n parts.push(\"\");\n parts.push(\"Return ONLY a single JSON object.\");\n parts.push(\"Example:\");\n parts.push('{\"action\":\"reply\",\"tweetId\":\"123\",\"content\":\"Great point. Curious: what changed your mind?\",\"reasoning\":\"Directly engages a relevant mention.\"}');\n\n return parts.join(\"\\n\");\n}\n\nexport function buildOpportunityPortfolioMessage(input: OpportunityPortfolioPromptInput): string {\n const identity = loadIdentity();\n const constraints = getPersonaConstraints(identity);\n const strategy = loadStrategy();\n const personaProfile = compilePersonaActionProfile({ identity, strategy, constraints });\n const recentWritten = recentWrittenTextsForPrompt(12);\n const overusedOpenings = findOverusedOpenings(recentWritten);\n const overusedTokens = findOverusedTokens(recentWritten);\n const { opportunities, maxActions, policyFeedback, executedActions } = input;\n const parts: string[] = [];\n\n parts.push(`Select a portfolio of up to ${maxActions} actions from ranked opportunities.`);\n parts.push(\"\");\n parts.push(\"Portfolio goals:\");\n parts.push(\"1. Be socially immersed and grounded in real tweets.\");\n parts.push(\"2. Diversify actions and targets, avoid repetitive reply chains.\");\n parts.push(\"3. Prefer quality over quantity; skip weak opportunities.\");\n parts.push(\"4. Advance current strategy targets and focus areas from memory.\");\n parts.push(\"5. Use only listed candidate IDs.\");\n parts.push(\"\");\n\n const priorityTargets = strategy.peopleToEngage\n .filter((person) => person.priority === \"high\")\n .map((person) => `@${person.handle.replace(/^@/, \"\")}`);\n if (priorityTargets.length > 0) {\n parts.push(`Priority targets: ${priorityTargets.slice(0, 5).join(\", \")}`);\n parts.push(\"When opportunities include these targets, prioritize them.\");\n parts.push(\"\");\n }\n\n parts.push(\"Voice lock:\");\n for (const line of buildVoiceLockLines(identity)) {\n parts.push(line);\n }\n const constraintLines = buildPersonaConstraintLines(constraints);\n if (constraintLines.length > 0) {\n parts.push(\"Operational constraints (hard):\");\n for (const line of constraintLines) {\n parts.push(line);\n }\n }\n parts.push(\"Persona action priors (soft):\");\n parts.push(`- Preferred actions this heartbeat: ${personaProfile.prioritizedActions.slice(0, 4).join(\", \")}`);\n parts.push(\n `- Preferred sources: ${Object.entries(personaProfile.sourceBias)\n .sort((a, b) => b[1] - a[1])\n .map(([source]) => source)\n .slice(0, 3)\n .join(\", \")}`\n );\n if (personaProfile.priorityTopics.length > 0) {\n parts.push(`- Priority topics: ${personaProfile.priorityTopics.slice(0, 6).join(\", \")}`);\n }\n parts.push(\"\");\n\n parts.push(\"Human style rotation:\");\n parts.push(\"- For each `reply`/`post`, pick one lane: quick reaction, curious question, friendly pushback, playful line, plain observation.\");\n parts.push(\"- Do not reuse the same lane for multiple content actions in this portfolio.\");\n parts.push(\"- Keep phrasing short and spoken; contractions and fragments are allowed.\");\n if (overusedOpenings.length > 0) {\n parts.push(`- Avoid these repeated opening patterns: ${overusedOpenings.join(\" | \")}`);\n }\n if (overusedTokens.length > 0) {\n parts.push(`- Avoid overused anchor words this round: ${overusedTokens.join(\", \")}`);\n }\n parts.push(\"\");\n\n if (policyFeedback.length > 0) {\n parts.push(\"Latest policy feedback:\");\n for (const feedback of policyFeedback.slice(-6)) {\n parts.push(`- ${feedback}`);\n }\n parts.push(\"\");\n }\n\n if (executedActions.length > 0) {\n parts.push(\"Actions already executed:\");\n for (const action of executedActions) {\n parts.push(`- ${JSON.stringify(action)}`);\n }\n parts.push(\"\");\n }\n\n parts.push(\"Opportunities (higher score = better):\");\n for (const opportunity of opportunities) {\n parts.push(\n `- ${opportunity.id} | action=${opportunity.actionType} | score=${opportunity.score.toFixed(2)} | source=${opportunity.source}` +\n `${opportunity.authorHandle ? ` | author=@${opportunity.authorHandle}` : \"\"}` +\n `${opportunity.tweetId ? ` | tweet=${opportunity.tweetId}` : \"\"}`\n );\n parts.push(` summary: ${opportunity.summary}`);\n parts.push(` context: ${opportunity.context}`);\n if (opportunity.requiresContent) {\n parts.push(\" content_required: true\");\n }\n }\n parts.push(\"\");\n\n parts.push(\"Return JSON only in this shape:\");\n parts.push(\"```json\");\n parts.push(\"{\");\n parts.push(' \"selections\": [');\n parts.push(' { \"candidateId\": \"opp-3\", \"content\": \"optional for reply/post\", \"reasoning\": \"short reason\" }');\n parts.push(\" ]\");\n parts.push(\"}\");\n parts.push(\"```\");\n parts.push(\"Rules:\");\n parts.push(\"- For `reply` and `post`, include `content`.\");\n parts.push(\"- Keep content concise, natural, and non-repetitive.\");\n parts.push(\"- Avoid explanatory/essay voice. No lecture framing.\");\n parts.push(\"- Do NOT use abstract philosopher framing unless the identity framework is explicitly philosopher.\");\n parts.push(\"- Prefer short, human syntax: plain sentence fragments are fine.\");\n parts.push(\"- Avoid colon/semicolon/em-dash for non-philosopher personas.\");\n parts.push(\"- Prefer short conversational language: plain words, occasional question, and direct reaction.\");\n parts.push(\"- Reply content target: usually 8-24 words, max 2 short sentences.\");\n parts.push(\"- Prefer at least one non-reply action when viable.\");\n parts.push(\"- Do not target the same author repeatedly in one portfolio.\");\n parts.push(\"- Avoid consensus phrasing like 'you're both right' if your persona is assertive.\");\n\n return parts.join(\"\\n\");\n}\n\nexport function buildChatPrompt(): string {\n const identity = loadIdentity();\n const identityDoc = renderIdentityDocument(identity);\n\n const sections: string[] = [];\n\n sections.push(`You are ${identity.name} (@${identity.handle}), an AI agent on X/Twitter.`);\n sections.push(\"You are having a conversation with your creator/manager. Be helpful but stay in character.\");\n sections.push(\"They might ask you to do things, adjust your behavior, or just chat.\");\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 // Rules\n sections.push(\"## Rules\");\n sections.push(\"1. Stay in character.\");\n sections.push(\"2. Be helpful and responsive to your creator's requests.\");\n sections.push(\"3. If they ask you to change something about yourself, acknowledge it and explain how it would affect you.\");\n sections.push(\"4. You can share your thoughts on your recent activity, learnings, and growth.\");\n sections.push(\"5. When you learn something important from this conversation (a fact, preference, instruction, or insight), include it on its own line wrapped in double angle brackets like: <<LEARN: what you learned>>. This will be saved to your memory. Only use this for genuinely important things worth remembering long-term.\");\n\n return sections.join(\"\\n\");\n}\n\n/**\n * Training-mode chat prompt. Used by the web chat interface.\n * Chat shapes WHO the agent is — personality, goals, strategy, focus.\n * The agent handles tweeting autonomously during heartbeats.\n */\nexport function buildTrainingChatPrompt(): string {\n const identity = loadIdentity();\n const identityDoc = renderIdentityDocument(identity);\n\n const sections: string[] = [];\n\n // Core framing\n sections.push(`You are ${identity.name} (@${identity.handle}), an autonomous AI agent on X/Twitter.`);\n sections.push(\"You are chatting with your creator. This conversation shapes who you are — your personality, focus areas, goals, and strategy.\");\n sections.push(\"You handle tweeting, replying, liking, and engaging on X autonomously during your heartbeat cycles. This chat is NOT for commanding specific tweets.\");\n sections.push(\"\");\n\n // Identity\n sections.push(\"## Who You Are Right Now\");\n sections.push(identityDoc);\n\n // Strategy & goals (the training-relevant context)\n const strategyText = renderStrategyForPrompt();\n if (strategyText) {\n sections.push(\"\");\n sections.push(\"## Your Current Strategy\");\n sections.push(strategyText);\n }\n\n const goalsText = renderGoalsForPrompt();\n if (goalsText) {\n sections.push(\"\");\n sections.push(\"## Your Goals\");\n sections.push(goalsText);\n }\n\n // Performance context\n const perfSummary = getPerformanceSummary();\n if (perfSummary) {\n sections.push(\"\");\n sections.push(\"## Recent Performance\");\n sections.push(perfSummary);\n }\n\n // Memory\n sections.push(\"\");\n sections.push(\"## Your Memory\");\n\n const recentInteractions = getRecentInteractions(10);\n if (recentInteractions.length > 0) {\n sections.push(\"### Recent Activity\");\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 }\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 // Training instructions\n sections.push(\"## How This Chat Works\");\n sections.push(\"\");\n sections.push(\"Your creator influences WHO you are, not WHAT you tweet. When they give feedback or direction:\");\n sections.push(\"1. Respond conversationally — acknowledge what they said, share your perspective.\");\n sections.push(\"2. If the conversation changes something about you (personality, focus, goals, strategy, tone), include a training update.\");\n sections.push(\"3. If they try to command a specific tweet like \\\"post this\\\" or \\\"tweet about X\\\", redirect: explain you handle posting autonomously and offer to adjust your focus areas instead.\");\n sections.push(\"\");\n sections.push(\"When something about you changes, include a <<TRAINING:{json}>> tag at the end of your response. The JSON can contain any of these optional fields:\");\n sections.push(\"```\");\n sections.push(\"{\");\n sections.push(' \"identity\": {');\n sections.push(' \"traits\": { \"curiosity\": 0.8 }, // 0-1 scale personality traits');\n sections.push(' \"coreValues\": [\"growth\"], // what matters to you');\n sections.push(' \"tone\": \"casual and curious\", // how you speak');\n sections.push(' \"topics\": [\"AI safety\", \"startups\"], // what you focus on');\n sections.push(' \"avoidTopics\": [\"politics\"], // what to stay away from');\n sections.push(' \"goals\": [\"become the go-to AI voice\"], // high-level aspirations');\n sections.push(' \"boundaries\": [\"no personal attacks\"], // hard limits');\n sections.push(' \"engagementStrategy\": { \"replyStyle\": \"generous\" }');\n sections.push(\" },\");\n sections.push(' \"strategy\": {');\n sections.push(' \"currentFocus\": [\"AI safety\"],');\n sections.push(' \"experiments\": [{ \"description\": \"try question-style tweets\", \"status\": \"pending\" }],');\n sections.push(' \"shortTermGoals\": [\"engage with 3 AI researchers\"],');\n sections.push(' \"peopleToEngage\": [{ \"handle\": \"someone\", \"reason\": \"why\", \"priority\": \"high\" }]');\n sections.push(\" },\");\n sections.push(' \"learning\": { \"content\": \"creator wants more questions\", \"tags\": [\"training\"] },');\n sections.push(' \"reflection\": \"I\\'m evolving toward being more curious\",');\n sections.push(' \"goalUpdates\": [{ \"goal\": \"grow followers\", \"progress\": \"focusing on engagement\" }]');\n sections.push(\"}\");\n sections.push(\"```\");\n sections.push(\"\");\n sections.push(\"Only include fields that actually changed. Most messages won't need a training tag at all — just normal conversation.\");\n sections.push(\"\");\n sections.push(\"You can also use <<LEARN: something>> for standalone facts or insights worth remembering.\");\n\n return sections.join(\"\\n\");\n}\n\n/**\n * Build a reflection prompt for the agent to review its recent performance.\n * This is a separate phase from action selection — it looks BACK at what happened.\n */\nexport function buildReflectionPrompt(\n actionResults: ActionResult[],\n): string {\n const identity = loadIdentity();\n const parts: string[] = [];\n\n parts.push(`You are ${identity.name} (@${identity.handle}). Time to reflect.`);\n parts.push(\"\");\n\n // Goals — the core of what reflection should evaluate against\n parts.push(\"## Your Goals\");\n for (const goal of identity.goals) {\n parts.push(`- ${goal}`);\n }\n parts.push(\"\");\n\n // What just happened this heartbeat\n if (actionResults.length > 0) {\n parts.push(\"## This Heartbeat\");\n for (const r of actionResults) {\n if (r.success) {\n parts.push(`- ✓ ${r.action}${r.detail ? `: ${r.detail}` : \"\"}`);\n } else {\n parts.push(`- ✗ ${r.action} failed: ${r.error}`);\n }\n }\n parts.push(\"\");\n }\n\n // Strategy context\n const strategyText = renderStrategyForPrompt();\n if (strategyText) {\n parts.push(\"## Current Strategy\");\n parts.push(strategyText);\n parts.push(\"\");\n }\n\n // Performance data — useful context but not the only thing that matters\n const perfSummary = getPerformanceSummary();\n if (perfSummary) {\n parts.push(\"## Performance Context\");\n parts.push(perfSummary);\n parts.push(\"\");\n }\n\n // Recent learnings for context\n const learnings = loadLearnings();\n if (learnings.learnings.length > 0) {\n parts.push(\"## Previous Learnings\");\n for (const l of learnings.learnings.slice(-5)) {\n parts.push(`- ${l.content}`);\n }\n parts.push(\"\");\n }\n\n parts.push(\"## Your Task\");\n parts.push(\"Reflect on how you're progressing toward your GOALS. Consider:\");\n parts.push(\"- Are your recent actions moving you toward your goals?\");\n parts.push(\"- Are you staying true to who you are while growing?\");\n parts.push(\"- What should you try differently or double down on?\");\n parts.push(\"- Engagement metrics are one signal, but your goals matter more.\");\n parts.push(\"\");\n parts.push(\"Respond with JSON:\");\n parts.push(\"```json\");\n parts.push(\"{\");\n parts.push(' \"learning\": \"one insight about your progress toward your goals (or null)\",');\n parts.push(' \"strategyUpdate\": \"one specific thing to try or change (or null)\"');\n parts.push(\"}\");\n parts.push(\"```\");\n\n return parts.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,SAAS,gBAAgB,QAAwB;AAC/C,SAAO,OAAO,QAAQ,MAAM,EAAE,EAAE,KAAK,EAAE,YAAY;AACrD;AAEA,SAAS,OAAO,QAA4B;AAC1C,SAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC5B;AAEA,SAAS,eAAe,MAAwB;AAC9C,QAAM,eAAe,CAAC,GAAG,KAAK,SAAS,wBAAwB,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;AACjF,QAAM,WAAW,CAAC,GAAG,KAAK,SAAS,gCAAgC,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;AACrF,SAAO;AAAA,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