spora 0.7.9 → 0.7.11
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.
- package/dist/{autonomy-ZMFZRXDZ.js → autonomy-ZVXD2OP2.js} +2 -2
- package/dist/{chunk-TTDQZI5W.js → chunk-3S44SIUP.js} +313 -18
- package/dist/chunk-3S44SIUP.js.map +1 -0
- package/dist/chunk-N7E4XZQN.js +99 -0
- package/dist/chunk-N7E4XZQN.js.map +1 -0
- package/dist/cli.js +5 -5
- package/dist/{heartbeat-CUM7FIHS.js → heartbeat-7HPOTN5Z.js} +3 -3
- package/dist/{heartbeat-narrative-B3RD3OPJ.js → heartbeat-narrative-WGYRAWUH.js} +2 -2
- package/dist/{init-4SBU4H6F.js → init-75RMQFHC.js} +19 -5
- package/dist/init-75RMQFHC.js.map +1 -0
- package/dist/web-chat/chat.html +29 -10
- package/dist/{web-chat-YRQQB435.js → web-chat-FCOETDEZ.js} +13 -14
- package/dist/web-chat-FCOETDEZ.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-OLYPPXKP.js +0 -69
- package/dist/chunk-OLYPPXKP.js.map +0 -1
- package/dist/chunk-TTDQZI5W.js.map +0 -1
- package/dist/init-4SBU4H6F.js.map +0 -1
- package/dist/web-chat-YRQQB435.js.map +0 -1
- /package/dist/{autonomy-ZMFZRXDZ.js.map → autonomy-ZVXD2OP2.js.map} +0 -0
- /package/dist/{heartbeat-CUM7FIHS.js.map → heartbeat-7HPOTN5Z.js.map} +0 -0
- /package/dist/{heartbeat-narrative-B3RD3OPJ.js.map → heartbeat-narrative-WGYRAWUH.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/runtime/decision-engine.ts","../src/runtime/policy.ts","../src/runtime/bandit.ts","../src/runtime/autonomy.ts"],"sourcesContent":["import { logger } from \"../utils/logger.js\";\nimport { getXClient } from \"../x-client/index.js\";\nimport { addLearning, logInteraction } from \"../memory/index.js\";\nimport { loadIdentity, saveIdentity } from \"../identity/index.js\";\nimport { addToQueue } from \"../scheduler/queue.js\";\n\nexport interface AgentAction {\n action: string;\n content?: string;\n tweetId?: string;\n handle?: string;\n targetHandle?: string;\n source?: string;\n banditArm?: string;\n opportunityId?: string;\n intentIds?: string[];\n tags?: string[];\n reason?: string;\n reasoning?: string;\n}\n\nexport interface ActionResult {\n action: string;\n success: boolean;\n detail?: string;\n error?: string;\n}\n\nexport function parseActions(llmResponse: string): AgentAction[] {\n // Strategy: try multiple extraction approaches, most specific first\n\n // 1. Try markdown code block first (```json ... ``` or ``` ... ```)\n const codeBlockMatch = llmResponse.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)```/);\n if (codeBlockMatch) {\n const inside = codeBlockMatch[1].trim();\n try {\n const parsed = JSON.parse(inside);\n return Array.isArray(parsed) ? parsed : [parsed];\n } catch {\n // Code block content wasn't valid JSON, continue to other strategies\n }\n }\n\n // 2. Find the last JSON array in the response (LLMs often put reasoning before the array)\n // Use a greedy approach to find the outermost array brackets\n let lastArrayStart = -1;\n let lastArrayEnd = -1;\n let depth = 0;\n for (let i = 0; i < llmResponse.length; i++) {\n if (llmResponse[i] === \"[\") {\n if (depth === 0) lastArrayStart = i;\n depth++;\n } else if (llmResponse[i] === \"]\") {\n depth--;\n if (depth === 0) lastArrayEnd = i;\n }\n }\n\n if (lastArrayStart >= 0 && lastArrayEnd > lastArrayStart) {\n const arrayStr = llmResponse.slice(lastArrayStart, lastArrayEnd + 1);\n try {\n const parsed = JSON.parse(arrayStr);\n if (Array.isArray(parsed) && parsed.length > 0 && parsed[0].action) {\n return parsed;\n }\n } catch {\n // Not valid JSON array, try next strategy\n }\n }\n\n // 3. Try to find a single action object (last one in the response)\n const objMatches = [...llmResponse.matchAll(/\\{[^{}]*\"action\"\\s*:\\s*\"[^\"]+\"/g)];\n if (objMatches.length > 0) {\n // Find the full object starting from this match\n for (let i = objMatches.length - 1; i >= 0; i--) {\n const start = objMatches[i].index!;\n let braceDepth = 0;\n let end = -1;\n for (let j = start; j < llmResponse.length; j++) {\n if (llmResponse[j] === \"{\") braceDepth++;\n else if (llmResponse[j] === \"}\") {\n braceDepth--;\n if (braceDepth === 0) { end = j; break; }\n }\n }\n if (end > start) {\n try {\n const obj = JSON.parse(llmResponse.slice(start, end + 1));\n if (obj.action) return [obj as AgentAction];\n } catch {\n continue;\n }\n }\n }\n }\n\n // 4. Last resort: try the whole response as JSON\n try {\n const parsed = JSON.parse(llmResponse.trim());\n if (Array.isArray(parsed)) return parsed;\n if (parsed.action) return [parsed as AgentAction];\n } catch {\n // Not JSON at all\n }\n\n logger.warn(\"Failed to parse actions from LLM response\");\n if (llmResponse.length < 500) {\n logger.warn(`Response was: ${llmResponse}`);\n } else {\n logger.warn(`Response starts with: ${llmResponse.slice(0, 200)}...`);\n }\n return [];\n}\n\nexport async function executeAction(action: AgentAction): Promise<ActionResult> {\n const { action: type } = action;\n\n try {\n switch (type) {\n case \"post\": {\n if (!action.content) return { action: type, success: false, error: \"No content provided\" };\n if (action.content.length > 280) {\n return { action: type, success: false, error: `Tweet too long: ${action.content.length} chars (max 280)` };\n }\n\n const client = await getXClient();\n const result = await client.postTweet(action.content);\n if (result.success) logger.info(`Posted: \"${action.content.slice(0, 50)}...\"`);\n return { action: type, success: result.success, detail: result.tweetId, error: result.error };\n }\n\n case \"reply\": {\n if (!action.tweetId || !action.content) {\n return { action: type, success: false, error: \"Missing tweetId or content\" };\n }\n const client = await getXClient();\n const result = await client.replyToTweet(action.tweetId, action.content);\n if (result.success) logger.info(`Replied to ${action.tweetId}: \"${action.content.slice(0, 50)}...\"`);\n return { action: type, success: result.success, detail: result.tweetId, error: result.error };\n }\n\n case \"like\": {\n if (!action.tweetId) return { action: type, success: false, error: \"Missing tweetId\" };\n const client = await getXClient();\n const result = await client.likeTweet(action.tweetId);\n return { action: type, success: result.success, error: result.error };\n }\n\n case \"retweet\": {\n if (!action.tweetId) return { action: type, success: false, error: \"Missing tweetId\" };\n const client = await getXClient();\n const result = await client.retweet(action.tweetId);\n return { action: type, success: result.success, error: result.error };\n }\n\n case \"follow\": {\n if (!action.handle) return { action: type, success: false, error: \"Missing handle\" };\n const client = await getXClient();\n const result = await client.followUser(action.handle);\n if (!result.success) {\n logInteraction({\n id: `int-${Date.now()}`,\n timestamp: new Date().toISOString(),\n type: \"follow\",\n targetHandle: action.handle.replace(/^@/, \"\"),\n creditsUsed: 0,\n success: false,\n error: result.error,\n });\n }\n return { action: type, success: result.success, error: result.error };\n }\n\n case \"schedule\": {\n if (!action.content) return { action: type, success: false, error: \"No content\" };\n const entry = addToQueue(action.content);\n logger.info(`Scheduled: \"${action.content.slice(0, 50)}...\" for ${entry.scheduledFor}`);\n return { action: type, success: true, detail: `Scheduled for ${entry.scheduledFor}` };\n }\n\n case \"learn\": {\n if (!action.content) return { action: type, success: false, error: \"No content\" };\n addLearning(action.content, \"agent\", action.tags ?? [\"heartbeat\"]);\n logger.info(`Learned: \"${action.content.slice(0, 50)}...\"`);\n return { action: type, success: true };\n }\n\n case \"reflect\": {\n if (!action.content) return { action: type, success: false, error: \"No content\" };\n const identity = loadIdentity();\n identity.evolutionJournal.push({\n date: new Date().toISOString(),\n reflection: action.content,\n });\n saveIdentity(identity);\n logger.info(`Reflected: \"${action.content.slice(0, 50)}...\"`);\n return { action: type, success: true };\n }\n\n case \"skip\": {\n logger.info(`Skipping: ${action.reason ?? action.reasoning ?? \"no reason given\"}`);\n return { action: type, success: true, detail: action.reason ?? action.reasoning };\n }\n\n default:\n logger.warn(`Unknown action: ${type}`);\n return { action: type, success: false, error: `Unknown action: ${type}` };\n }\n } catch (error) {\n const msg = (error as Error).message;\n logger.error(`Action ${type} failed: ${msg}`);\n return { action: type, success: false, error: msg };\n }\n}\n\nexport async function executeActions(actions: AgentAction[]): Promise<ActionResult[]> {\n const results: ActionResult[] = [];\n for (const action of actions) {\n const result = await executeAction(action);\n results.push(result);\n // Small delay between actions to be human-like\n await new Promise((r) => setTimeout(r, 2000 + Math.random() * 3000));\n }\n return results;\n}\n","import { getRecentInteractions, type InteractionEntry } from \"../memory/index.js\";\nimport { loadIdentity } from \"../identity/index.js\";\nimport { getPersonaConstraints, personaConstraintHandles } from \"./persona-constraints.js\";\nimport type { Tweet } from \"../x-client/types.js\";\nimport type { AgentAction } from \"./decision-engine.js\";\n\nexport interface PolicyContext {\n action: AgentAction;\n step: number;\n timeline: Tweet[];\n mentions: Tweet[];\n executedActions: AgentAction[];\n observedTweetIds?: string[];\n observedTweets?: Tweet[];\n selfHandle?: string;\n selfUserId?: string | null;\n}\n\nexport interface PolicyDecision {\n allowed: boolean;\n reason?: string;\n}\n\nfunction normalize(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 tokenSet(text: string): Set<string> {\n const tokens = normalize(text).split(\" \").filter(Boolean);\n return new Set(tokens);\n}\n\nfunction jaccardSimilarity(a: string, b: string): number {\n const aSet = tokenSet(a);\n const bSet = tokenSet(b);\n if (aSet.size === 0 || bSet.size === 0) return 0;\n\n let overlap = 0;\n for (const token of aSet) {\n if (bSet.has(token)) overlap += 1;\n }\n\n const union = aSet.size + bSet.size - overlap;\n return union === 0 ? 0 : overlap / union;\n}\n\nfunction firstWords(text: string, n: number): string {\n return normalize(text).split(\" \").filter(Boolean).slice(0, n).join(\" \");\n}\n\nfunction hasAllCapsEnding(text: string): boolean {\n const ending = text.split(/[.!?]/).map((s) => s.trim()).filter(Boolean).slice(-1)[0] ?? \"\";\n const words = ending.split(/\\s+/).filter(Boolean);\n if (words.length < 3) return false;\n return words.every((word) => /^[A-Z0-9]+$/.test(word));\n}\n\nfunction wordCount(text: string): number {\n return normalize(text).split(\" \").filter(Boolean).length;\n}\n\nfunction sentenceCount(text: string): number {\n return text\n .split(/[.!?]/)\n .map((part) => part.trim())\n .filter(Boolean).length;\n}\n\nfunction explanatoryMarkerHits(text: string): number {\n const lower = text.toLowerCase();\n const markers = [\n \"the real issue\",\n \"the core issue\",\n \"in other words\",\n \"the point is\",\n \"what this means\",\n \"the lesson\",\n \"therefore\",\n \"ultimately\",\n \"meanwhile\",\n \"this reveals\",\n \"this proves\",\n ];\n return markers.reduce((hits, marker) => hits + (lower.includes(marker) ? 1 : 0), 0);\n}\n\nfunction soundsLikeLecture(content: string): boolean {\n const words = wordCount(content);\n const commas = (content.match(/,/g) ?? []).length;\n const semicolons = (content.match(/;/g) ?? []).length;\n const hasQuestion = content.includes(\"?\");\n const markerHits = explanatoryMarkerHits(content);\n\n if (words > 58) return true;\n if (words > 42 && commas + semicolons >= 3 && !hasQuestion) return true;\n if (markerHits >= 2) return true;\n return false;\n}\n\nfunction soundsTooHedgedForPersona(content: string): boolean {\n try {\n const identity = loadIdentity();\n const assertive =\n identity.traits.confidence >= 0.72 ||\n identity.traits.aggression >= 0.62 ||\n identity.conflictStyle === \"clap-back\" ||\n identity.conflictStyle === \"debate\";\n if (!assertive) return false;\n\n const lower = content.toLowerCase();\n const hedges = [\n \"you're both right\",\n \"both can be true\",\n \"on one hand\",\n \"on the other hand\",\n \"it depends\",\n \"it's complicated\",\n \"nuance\",\n \"fair point from both\",\n ];\n return hedges.some((phrase) => lower.includes(phrase));\n } catch {\n return false;\n }\n}\n\nfunction allowsPhilosopherCadence(): boolean {\n try {\n const identity = loadIdentity();\n if (identity.framework === \"philosopher\") return true;\n // Truthseeker can be analytical, but still should avoid abstract manifesto loops.\n if (identity.framework === \"truthseeker\") return false;\n return false;\n } catch {\n return false;\n }\n}\n\nfunction philosophicalPatternHits(content: string): number {\n const lower = content.toLowerCase();\n const markers = [\n \"the real question\",\n \"the deeper question\",\n \"what becomes possible\",\n \"is just the start\",\n \"the future isn't about\",\n \"the future is not about\",\n \"when intelligence becomes\",\n \"protocols are infrastructure\",\n \"the core future\",\n \"the true question\",\n \"value might emerge\",\n \"isn't about\",\n \"is not about\",\n \"it's about\",\n \"just the start\",\n ];\n return markers.reduce((hits, marker) => hits + (lower.includes(marker) ? 1 : 0), 0);\n}\n\nfunction abstractWordCount(content: string): number {\n const words = normalize(content).split(\" \").filter(Boolean);\n const abstractWords = new Set([\n \"infrastructure\",\n \"protocol\",\n \"protocols\",\n \"architecture\",\n \"architectures\",\n \"consciousness\",\n \"economy\",\n \"economics\",\n \"currency\",\n \"systems\",\n \"system\",\n \"future\",\n \"intelligence\",\n \"optimization\",\n \"abstraction\",\n \"paradigm\",\n \"emerge\",\n \"emergence\",\n \"governs\",\n \"governance\",\n ]);\n return words.filter((word) => abstractWords.has(word)).length;\n}\n\nfunction usesManifestoPunctuation(content: string): boolean {\n // Colon/semicolon/em-dash patterns correlate strongly with the explanatory style we want to avoid.\n return content.includes(\":\") || content.includes(\";\") || content.includes(\"—\");\n}\n\nconst OVERLAP_STOPWORDS = new Set([\n \"this\", \"that\", \"with\", \"from\", \"have\", \"what\", \"when\", \"where\", \"which\", \"your\", \"youre\",\n \"they\", \"them\", \"about\", \"into\", \"over\", \"under\", \"while\", \"just\", \"like\", \"really\",\n \"there\", \"their\", \"then\", \"than\", \"because\", \"would\", \"could\", \"should\", \"being\", \"been\",\n \"it's\", \"its\", \"the\", \"and\", \"for\", \"are\", \"was\", \"were\", \"will\", \"not\", \"but\", \"you\",\n \"our\", \"out\", \"all\", \"too\", \"can\", \"get\", \"got\", \"any\",\n]);\n\nfunction meaningfulTokenSet(text: string): Set<string> {\n const tokens = normalize(text)\n .split(\" \")\n .filter((token) => token.length >= 4 && !OVERLAP_STOPWORDS.has(token));\n return new Set(tokens);\n}\n\nfunction hasMeaningfulContextOverlap(content: string, targetText: string): boolean {\n const a = meaningfulTokenSet(content);\n const b = meaningfulTokenSet(targetText);\n if (a.size === 0 || b.size === 0) return false;\n for (const token of a) {\n if (b.has(token)) return true;\n }\n return false;\n}\n\nfunction recentWrittenContent(): string[] {\n const recent = getRecentInteractions(40);\n return recent\n .filter((i) => i.type === \"post\" || i.type === \"reply\")\n .map((i) => i.content ?? \"\")\n .filter((content) => content.length > 0);\n}\n\nconst REPETITION_STOPWORDS = new Set([\n \"about\", \"after\", \"again\", \"against\", \"almost\", \"always\", \"among\", \"because\", \"being\", \"between\",\n \"could\", \"every\", \"first\", \"found\", \"from\", \"going\", \"great\", \"have\", \"having\", \"here\", \"into\",\n \"just\", \"like\", \"make\", \"more\", \"most\", \"much\", \"only\", \"other\", \"over\", \"really\", \"same\", \"some\",\n \"such\", \"than\", \"that\", \"their\", \"there\", \"these\", \"they\", \"this\", \"those\", \"through\", \"time\", \"very\",\n \"what\", \"when\", \"where\", \"which\", \"while\", \"with\", \"would\", \"your\", \"youre\", \"dont\", \"cant\", \"will\",\n \"shall\", \"should\", \"also\", \"tweet\", \"tweets\", \"thread\", \"threads\", \"future\", \"human\", \"humans\",\n \"technology\", \"tech\", \"build\", \"building\", \"system\", \"systems\", \"agent\", \"agents\",\n]);\n\nfunction informativeTokens(text: string): string[] {\n return normalize(text)\n .split(\" \")\n .filter((token) => token.length >= 5 && !REPETITION_STOPWORDS.has(token));\n}\n\nfunction findOverusedAnchor(content: string, recent: string[]): string | null {\n const recentWindow = recent.slice(0, 12);\n if (recentWindow.length < 5) return null;\n\n const tokenCounts = new Map<string, number>();\n const bigramCounts = new Map<string, number>();\n\n for (const sample of recentWindow) {\n const tokens = informativeTokens(sample);\n const uniqueTokens = new Set(tokens);\n for (const token of uniqueTokens) {\n tokenCounts.set(token, (tokenCounts.get(token) ?? 0) + 1);\n }\n for (let i = 0; i < tokens.length - 1; i += 1) {\n const bigram = `${tokens[i]} ${tokens[i + 1]}`;\n bigramCounts.set(bigram, (bigramCounts.get(bigram) ?? 0) + 1);\n }\n }\n\n const contentTokens = informativeTokens(content);\n const contentTokenSet = new Set(contentTokens);\n for (const token of contentTokenSet) {\n const count = tokenCounts.get(token) ?? 0;\n if (count >= 4) return token;\n }\n\n for (let i = 0; i < contentTokens.length - 1; i += 1) {\n const bigram = `${contentTokens[i]} ${contentTokens[i + 1]}`;\n const count = bigramCounts.get(bigram) ?? 0;\n if (count >= 3) return bigram;\n }\n\n return null;\n}\n\nfunction openingFragment(text: string, words: number = 4): string {\n return normalize(text).split(\" \").filter(Boolean).slice(0, words).join(\" \");\n}\n\nfunction findOverusedOpening(content: string, recent: string[]): string | null {\n const opening = openingFragment(content, 4);\n if (!opening || opening.split(\" \").length < 3) return null;\n\n let matches = 0;\n for (const sample of recent.slice(0, 12)) {\n if (openingFragment(sample, 4) === opening) {\n matches += 1;\n }\n }\n\n return matches >= 2 ? opening : null;\n}\n\nfunction vocabularyNoveltyRatio(content: string, recent: string[]): number {\n const current = new Set(informativeTokens(content));\n if (current.size === 0) return 1;\n\n const seen = new Set<string>();\n for (const sample of recent.slice(0, 14)) {\n for (const token of informativeTokens(sample)) {\n seen.add(token);\n }\n }\n\n let fresh = 0;\n for (const token of current) {\n if (!seen.has(token)) fresh += 1;\n }\n return fresh / current.size;\n}\n\nfunction looksOverAbstractWithoutAnchor(content: string): boolean {\n const abstractCount = abstractWordCount(content);\n if (abstractCount < 4) return false;\n\n const words = wordCount(content);\n const density = abstractCount / Math.max(1, words);\n if (density < 0.2) return false;\n\n const lower = content.toLowerCase();\n const hasHandle = /@\\w+/.test(content);\n const hasNumber = /\\b\\d+(\\.\\d+)?\\b/.test(content);\n const hasQuote = /[\"“”']/.test(content);\n const hasSpecificFigure = /\\b(musk|elon|zuck|altman|openai|tesla|spacex|meta|google|apple)\\b/.test(lower);\n const hasQuestion = content.includes(\"?\");\n\n return !(hasHandle || hasNumber || hasQuote || hasSpecificFigure || hasQuestion);\n}\n\nfunction hasStrongConversationOpportunity(timeline: Tweet[], mentions: Tweet[]): boolean {\n if (mentions.length > 0) return true;\n return timeline.some((tweet) => (tweet.replyCount ?? 0) > 0 || tweet.text.includes(\"?\"));\n}\n\nfunction wasInteractionAction(action: AgentAction): boolean {\n return [\"reply\", \"like\", \"retweet\", \"follow\"].includes(action.action);\n}\n\nfunction isWritingAction(action: AgentAction): boolean {\n return [\"post\", \"reply\", \"schedule\"].includes(action.action);\n}\n\nfunction normalizeHandle(handle: string | undefined): string {\n return (handle ?? \"\").replace(/^@/, \"\").trim().toLowerCase();\n}\n\nfunction resolveActionTargetHandle(action: AgentAction, tweetById: Map<string, Tweet>): string {\n if (action.handle) return normalizeHandle(action.handle);\n if (action.targetHandle) return normalizeHandle(action.targetHandle);\n if (action.tweetId) return normalizeHandle(tweetById.get(action.tweetId)?.authorHandle);\n return \"\";\n}\n\nfunction executedWrittenContent(executedActions: AgentAction[]): string[] {\n return executedActions\n .filter((a) => isWritingAction(a) && typeof a.content === \"string\")\n .map((a) => a.content?.trim() ?? \"\")\n .filter((content) => content.length > 0);\n}\n\nfunction nearExactDuplicate(content: string, recent: string[]): boolean {\n const normalized = normalize(content);\n if (!normalized) return false;\n\n return recent.some((r) => {\n const candidate = normalize(r);\n if (!candidate) return false;\n if (candidate === normalized) return true;\n return jaccardSimilarity(content, r) >= 0.88;\n });\n}\n\nfunction isDuplicateTarget(action: AgentAction, executedActions: AgentAction[]): boolean {\n if (!action.tweetId) return false;\n return executedActions.some((a) => a.tweetId === action.tweetId && a.action === action.action);\n}\n\nfunction repeatedTemplate(content: string, recent: string[]): boolean {\n const prefix = firstWords(content, 7);\n if (!prefix) return false;\n\n return recent.some((r) => {\n const sameStart = firstWords(r, 7) === prefix;\n const similar = jaccardSimilarity(content, r) >= 0.62;\n return sameStart || similar;\n });\n}\n\nfunction overusingAllCapsCadence(content: string, recentEntries: InteractionEntry[]): boolean {\n if (!hasAllCapsEnding(content)) return false;\n const recentCaps = recentEntries\n .filter((i) => i.type === \"post\" && i.content)\n .slice(0, 8)\n .filter((i) => hasAllCapsEnding(i.content ?? \"\"));\n\n return recentCaps.length >= 2;\n}\n\nexport function evaluateActionPolicy(context: PolicyContext): PolicyDecision {\n const {\n action,\n step,\n timeline,\n mentions,\n executedActions,\n observedTweetIds,\n observedTweets,\n selfHandle,\n selfUserId,\n } = context;\n const self = normalizeHandle(selfHandle);\n const selfId = (selfUserId ?? \"\").trim();\n const knownTweets = observedTweets ?? [...timeline, ...mentions];\n const tweetById = new Map(knownTweets.map((tweet) => [tweet.id, tweet]));\n const constraints = getPersonaConstraints();\n const strictReplyHandles = new Set(constraints.onlyReplyToHandles.map((handle) => normalizeHandle(handle)));\n const strictInteractHandles = new Set(personaConstraintHandles(constraints).map((handle) => normalizeHandle(handle)));\n const targetHandle = resolveActionTargetHandle(action, tweetById);\n\n // Persona hard constraints: these are operational, not advisory.\n if (constraints.replyOnlyMode && ![\"reply\", \"skip\", \"learn\", \"reflect\"].includes(action.action)) {\n return {\n allowed: false,\n reason: \"Persona is in reply-only mode. Use reply actions only.\",\n };\n }\n\n if (constraints.noOriginalPosts && (action.action === \"post\" || action.action === \"schedule\")) {\n return {\n allowed: false,\n reason: \"Persona forbids standalone original posts.\",\n };\n }\n\n if (strictReplyHandles.size > 0) {\n if (action.action !== \"reply\") {\n return {\n allowed: false,\n reason: `Persona requires replying only to specific target(s): @${[...strictReplyHandles].join(\", @\")}.`,\n };\n }\n if (!targetHandle || !strictReplyHandles.has(targetHandle)) {\n return {\n allowed: false,\n reason: `Reply target must be one of @${[...strictReplyHandles].join(\", @\")}.`,\n };\n }\n }\n\n if (\n strictInteractHandles.size > 0 &&\n [\"reply\", \"like\", \"retweet\", \"follow\"].includes(action.action)\n ) {\n if (!targetHandle || !strictInteractHandles.has(targetHandle)) {\n return {\n allowed: false,\n reason: `Interaction target must be one of @${[...strictInteractHandles].join(\", @\")}.`,\n };\n }\n }\n\n if (isDuplicateTarget(action, executedActions)) {\n return { allowed: false, reason: `Action ${action.action} already executed for tweet ${action.tweetId} this heartbeat.` };\n }\n\n if (action.content && isWritingAction(action)) {\n if (action.content.length > 280) {\n return {\n allowed: false,\n reason: `Content is too long (${action.content.length}/280). Keep it tighter and more conversational.`,\n };\n }\n\n if (action.action === \"reply\" && wordCount(action.content) > 45 && !action.content.includes(\"?\")) {\n return {\n allowed: false,\n reason: \"Reply is too monologue-like. Keep it shorter or ask a direct question.\",\n };\n }\n\n if (soundsLikeLecture(action.content)) {\n return {\n allowed: false,\n reason: \"Rejected lecture-like writing style. Use a more human, reactive, conversational tone.\",\n };\n }\n\n if (soundsTooHedgedForPersona(action.content)) {\n return {\n allowed: false,\n reason: \"Rejected hedged consensus phrasing. Your persona should be more decisive and opinionated.\",\n };\n }\n\n if (!allowsPhilosopherCadence()) {\n const phiHits = philosophicalPatternHits(action.content);\n const abstractCount = abstractWordCount(action.content);\n const hasQuestion = action.content.includes(\"?\");\n if (phiHits >= 1 || (abstractCount >= 5 && hasQuestion)) {\n return {\n allowed: false,\n reason: \"Rejected abstract philosopher cadence. Use concrete, contextual language tied to the actual tweet.\",\n };\n }\n\n const words = wordCount(action.content);\n const sentences = sentenceCount(action.content);\n if (action.action === \"reply\" && (words > 34 || sentences > 2)) {\n return {\n allowed: false,\n reason: \"Reply is too long/explanatory for this persona. Keep it short and direct.\",\n };\n }\n if (action.action === \"post\" && (words > 42 || sentences > 3)) {\n return {\n allowed: false,\n reason: \"Post is drifting into manifesto style. Keep it more concrete and human.\",\n };\n }\n if ((action.action === \"reply\" || action.action === \"post\") && usesManifestoPunctuation(action.content) && words > 16) {\n return {\n allowed: false,\n reason: \"Rejected manifesto punctuation style. Avoid colon/semicolon/em-dash framing.\",\n };\n }\n }\n\n const existingInHeartbeat = executedWrittenContent(executedActions);\n if (nearExactDuplicate(action.content, existingInHeartbeat)) {\n return {\n allowed: false,\n reason: \"Rejected duplicate wording in this heartbeat. Write a distinct message before posting/replying again.\",\n };\n }\n\n const recent = recentWrittenContent();\n const overusedAnchor = findOverusedAnchor(action.content, recent);\n if (overusedAnchor) {\n return {\n allowed: false,\n reason: `Rejected repetitive anchor phrase/term \"${overusedAnchor}\". Use a different framing and vocabulary.`,\n };\n }\n\n const overusedOpening = findOverusedOpening(action.content, recent);\n if (overusedOpening) {\n return {\n allowed: false,\n reason: `Rejected repetitive opening phrase \"${overusedOpening}\". Start from a fresh angle.`,\n };\n }\n\n if (recent.length >= 6 && wordCount(action.content) >= 10) {\n const novelty = vocabularyNoveltyRatio(action.content, recent);\n if (novelty < 0.34) {\n return {\n allowed: false,\n reason: \"Rejected low-novelty vocabulary loop. Use fresher words, examples, or a different conversational angle.\",\n };\n }\n }\n\n if (!allowsPhilosopherCadence() && looksOverAbstractWithoutAnchor(action.content)) {\n return {\n allowed: false,\n reason: \"Rejected abstract wording without concrete anchor. Reference a specific person, event, quote, or question.\",\n };\n }\n }\n\n const hasConversationOpportunity = hasStrongConversationOpportunity(timeline, mentions);\n const interactedAlready = executedActions.some(wasInteractionAction);\n const observedCount = observedTweetIds && observedTweetIds.length > 0\n ? observedTweetIds.length\n : timeline.length + mentions.length;\n\n if ((action.action === \"reply\" || action.action === \"like\" || action.action === \"retweet\") && observedCount === 0) {\n return {\n allowed: false,\n reason: \"No tweets observed in current context. Avoid blind interactions; gather timeline/search context first.\",\n };\n }\n\n if (\n action.action === \"post\" &&\n hasConversationOpportunity &&\n !interactedAlready &&\n step < 2\n ) {\n return {\n allowed: false,\n reason: \"Engage first: reply/like/follow when mentions or active conversations are available before posting an original tweet.\",\n };\n }\n\n if (isWritingAction(action) && action.content) {\n const recent = recentWrittenContent();\n if (nearExactDuplicate(action.content, recent)) {\n return {\n allowed: false,\n reason: \"Rejected near-duplicate content from recent history. Tailor this message to the specific context.\",\n };\n }\n\n if (repeatedTemplate(action.content, recent)) {\n return {\n allowed: false,\n reason: \"Rejected repetitive content pattern. Use a more novel structure or engage directly with timeline context.\",\n };\n }\n }\n\n if ((action.action === \"post\" || action.action === \"schedule\") && action.content) {\n const recentInteractions = getRecentInteractions(20);\n if (overusingAllCapsCadence(action.content, recentInteractions)) {\n return {\n allowed: false,\n reason: \"Rejected repetitive all-caps slogan cadence. Vary style and reduce monologue formatting.\",\n };\n }\n }\n\n if ((action.action === \"reply\" || action.action === \"like\" || action.action === \"retweet\") && action.tweetId) {\n const known = new Set(observedTweetIds ?? [...timeline, ...mentions].map((tweet) => tweet.id));\n if (!known.has(action.tweetId)) {\n return {\n allowed: false,\n reason: `Tweet ${action.tweetId} is not in current observations. Choose a visible timeline/mention tweet for grounded engagement.`,\n };\n }\n\n const targetTweet = tweetById.get(action.tweetId);\n if (targetTweet && (\n (self && normalizeHandle(targetTweet.authorHandle) === self) ||\n (selfId && targetTweet.authorId === selfId)\n )) {\n return {\n allowed: false,\n reason: \"Rejected self-interaction. Do not reply/like/retweet your own tweets.\",\n };\n }\n }\n\n if (action.action === \"reply\" && action.tweetId) {\n if (action.content) {\n const targetTweet = tweetById.get(action.tweetId);\n if (targetTweet && !hasMeaningfulContextOverlap(action.content, targetTweet.text)) {\n const phiHits = philosophicalPatternHits(action.content);\n if (wordCount(action.content) > 9 || phiHits > 0 || abstractWordCount(action.content) >= 4) {\n return {\n allowed: false,\n reason: \"Reply is not grounded in the target tweet context. Reference concrete details from their actual post.\",\n };\n }\n }\n }\n }\n\n if (action.action === \"follow\" && action.handle) {\n const target = normalizeHandle(action.handle);\n if (!target) {\n return { allowed: false, reason: \"Follow target is empty.\" };\n }\n\n if (self && target === self) {\n return {\n allowed: false,\n reason: \"Rejected self-follow. Do not follow your own account.\",\n };\n }\n\n }\n\n return { allowed: true };\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { updatePostMetrics } from \"../memory/performance.js\";\nimport { paths } from \"../utils/paths.js\";\nimport { logger } from \"../utils/logger.js\";\nimport type { AgentAction, ActionResult } from \"./decision-engine.js\";\nimport type { ActionOpportunity } from \"./opportunity-engine.js\";\nimport type { XClientInterface } from \"../x-client/types.js\";\n\ninterface BanditArm {\n key: string;\n pulls: number;\n rewardSum: number;\n lastReward: number;\n updatedAt: string;\n}\n\ninterface PendingOutcome {\n id: string;\n armKey: string;\n actionType: string;\n tweetId?: string;\n createdAt: string;\n resolveAt: string;\n resolved: boolean;\n}\n\ninterface BanditState {\n totalPulls: number;\n explorationBudget: number;\n arms: Record<string, BanditArm>;\n pending: PendingOutcome[];\n}\n\ninterface ScoredOpportunity {\n opportunity: ActionOpportunity;\n adjustedScore: number;\n pulls: number;\n}\n\nexport interface OutcomeCollectionResult {\n processed: number;\n resolved: number;\n rewardAdded: number;\n}\n\nconst DEFAULT_EXPLORATION_BUDGET = 0.25;\n\nfunction defaultState(): BanditState {\n return {\n totalPulls: 0,\n explorationBudget: DEFAULT_EXPLORATION_BUDGET,\n arms: {},\n pending: [],\n };\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction loadState(): BanditState {\n if (!existsSync(paths.bandit)) return defaultState();\n try {\n const parsed = JSON.parse(readFileSync(paths.bandit, \"utf-8\")) as Partial<BanditState>;\n const state: BanditState = {\n totalPulls: Math.max(0, parsed.totalPulls ?? 0),\n explorationBudget: clamp(parsed.explorationBudget ?? DEFAULT_EXPLORATION_BUDGET, 0.1, 0.45),\n arms: parsed.arms ?? {},\n pending: Array.isArray(parsed.pending) ? parsed.pending : [],\n };\n return state;\n } catch {\n return defaultState();\n }\n}\n\nfunction saveState(state: BanditState): void {\n state.explorationBudget = clamp(state.explorationBudget, 0.1, 0.45);\n state.pending = state.pending\n .filter((entry) => {\n if (!entry.resolved) return true;\n const resolvedAtMs = Date.parse(entry.resolveAt);\n if (Number.isNaN(resolvedAtMs)) return false;\n return Date.now() - resolvedAtMs < 7 * 24 * 60 * 60 * 1000;\n })\n .slice(-1200);\n writeFileSync(paths.bandit, JSON.stringify(state, null, 2));\n}\n\nfunction ensureArm(state: BanditState, armKey: string): BanditArm {\n const existing = state.arms[armKey];\n if (existing) return existing;\n const arm: BanditArm = {\n key: armKey,\n pulls: 0,\n rewardSum: 0,\n lastReward: 0,\n updatedAt: new Date().toISOString(),\n };\n state.arms[armKey] = arm;\n return arm;\n}\n\nfunction averageReward(arm: BanditArm): number {\n if (arm.pulls <= 0) return 0;\n return arm.rewardSum / arm.pulls;\n}\n\nfunction ucbBonus(totalPulls: number, armPulls: number): number {\n const t = Math.max(1, totalPulls);\n return Math.sqrt((2 * Math.log(t + 1)) / (armPulls + 1));\n}\n\nfunction computeImmediateReward(result: ActionResult): number {\n if (result.success) return 0.12;\n const error = (result.error ?? \"\").toLowerCase();\n if (error.includes(\"duplicate content\")) return -0.95;\n if (error.includes(\"rate limit\")) return -0.5;\n if (error.includes(\"forbidden\") || error.includes(\"403\")) return -0.55;\n return -0.35;\n}\n\nfunction resolveDelayedReward(metrics: { likeCount: number; replyCount: number; retweetCount: number } | null): number {\n if (!metrics) return -0.05;\n const reward =\n Math.min(metrics.likeCount * 0.03, 0.9) +\n Math.min(metrics.replyCount * 0.12, 0.9) +\n Math.min(metrics.retweetCount * 0.08, 0.8);\n if (metrics.likeCount === 0 && metrics.replyCount === 0 && metrics.retweetCount === 0) {\n return -0.15;\n }\n return Math.min(reward, 1.8);\n}\n\nfunction armKeyFromAction(action: AgentAction): string {\n if (action.banditArm && action.banditArm.trim().length > 0) return action.banditArm;\n const source = action.source ?? \"unknown\";\n return `${action.action}:${source}`;\n}\n\nfunction extractTweetId(action: AgentAction, result: ActionResult): string | undefined {\n if (result.detail && /^\\d+$/.test(result.detail)) return result.detail;\n if (action.action !== \"reply\" && action.tweetId) return action.tweetId;\n return undefined;\n}\n\nexport function selectBanditOpportunityPool(\n opportunities: ActionOpportunity[],\n maxPoolSize: number = 24,\n): ActionOpportunity[] {\n if (opportunities.length <= maxPoolSize) return opportunities;\n\n const state = loadState();\n const totalPulls = Math.max(1, state.totalPulls);\n const scored: ScoredOpportunity[] = opportunities.map((opportunity) => {\n const arm = ensureArm(state, opportunity.armKey);\n const mean = averageReward(arm);\n const bonus = ucbBonus(totalPulls, arm.pulls);\n const coldStartBoost = arm.pulls === 0 ? 0.25 : 0;\n const adjustedScore = opportunity.score + mean * 1.5 + bonus * 0.35 + coldStartBoost;\n return {\n opportunity: {\n ...opportunity,\n score: adjustedScore,\n },\n adjustedScore,\n pulls: arm.pulls,\n };\n });\n\n const explorationBudget = clamp(state.explorationBudget, 0.1, 0.45);\n const exploreCount = Math.max(1, Math.floor(maxPoolSize * explorationBudget));\n const exploitCount = Math.max(1, maxPoolSize - exploreCount);\n\n const exploit = [...scored].sort((a, b) => b.adjustedScore - a.adjustedScore).slice(0, exploitCount);\n const selected = new Map<string, ActionOpportunity>();\n for (const row of exploit) {\n selected.set(row.opportunity.id, row.opportunity);\n }\n\n const remaining = scored\n .filter((row) => !selected.has(row.opportunity.id))\n .sort((a, b) => {\n if (a.pulls !== b.pulls) return a.pulls - b.pulls;\n return b.adjustedScore - a.adjustedScore;\n });\n\n // Add low-pull candidates first, with slight randomization for exploration.\n while (selected.size < maxPoolSize && remaining.length > 0) {\n const window = remaining.splice(0, Math.min(5, remaining.length));\n const pick = window[Math.floor(Math.random() * window.length)];\n if (!selected.has(pick.opportunity.id)) {\n selected.set(pick.opportunity.id, pick.opportunity);\n }\n for (const row of window) {\n if (row.opportunity.id !== pick.opportunity.id) {\n remaining.push(row);\n }\n }\n remaining.sort((a, b) => {\n if (a.pulls !== b.pulls) return a.pulls - b.pulls;\n return b.adjustedScore - a.adjustedScore;\n });\n }\n\n const picked = [...selected.values()].sort((a, b) => b.score - a.score).slice(0, maxPoolSize);\n saveState(state);\n return picked;\n}\n\nexport function recordBanditActionResults(actions: AgentAction[], results: ActionResult[]): void {\n if (actions.length === 0 || results.length === 0) return;\n const state = loadState();\n const now = new Date().toISOString();\n\n for (let i = 0; i < Math.min(actions.length, results.length); i += 1) {\n const action = actions[i];\n const result = results[i];\n const armKey = armKeyFromAction(action);\n const arm = ensureArm(state, armKey);\n\n const immediateReward = computeImmediateReward(result);\n arm.pulls += 1;\n arm.rewardSum += immediateReward;\n arm.lastReward = immediateReward;\n arm.updatedAt = now;\n state.totalPulls += 1;\n\n const tweetId = extractTweetId(action, result);\n if (result.success && tweetId && (action.action === \"post\" || action.action === \"reply\")) {\n const delayMs = action.action === \"reply\" ? 20 * 60 * 1000 : 45 * 60 * 1000;\n state.pending.push({\n id: `pending-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n armKey,\n actionType: action.action,\n tweetId,\n createdAt: now,\n resolveAt: new Date(Date.now() + delayMs).toISOString(),\n resolved: false,\n });\n }\n }\n\n saveState(state);\n}\n\nexport async function collectDelayedOutcomes(client: XClientInterface): Promise<OutcomeCollectionResult> {\n const state = loadState();\n const now = Date.now();\n const pendingDue = state.pending.filter((entry) => !entry.resolved && Date.parse(entry.resolveAt) <= now).slice(0, 8);\n if (pendingDue.length === 0) {\n return { processed: 0, resolved: 0, rewardAdded: 0 };\n }\n\n let rewardAdded = 0;\n let resolved = 0;\n const checkedAt = new Date().toISOString();\n\n for (const pending of pendingDue) {\n const arm = ensureArm(state, pending.armKey);\n let metrics: { likeCount: number; retweetCount: number; replyCount: number } | null = null;\n\n if (pending.tweetId) {\n metrics = await client.getTweetMetrics(pending.tweetId);\n if (metrics) {\n updatePostMetrics(pending.tweetId, {\n checkedAt,\n likes: metrics.likeCount,\n retweets: metrics.retweetCount,\n replies: metrics.replyCount,\n });\n }\n }\n\n const reward = resolveDelayedReward(\n metrics\n ? {\n likeCount: metrics.likeCount,\n retweetCount: metrics.retweetCount,\n replyCount: metrics.replyCount,\n }\n : null,\n );\n\n arm.rewardSum += reward;\n arm.lastReward = reward;\n arm.updatedAt = checkedAt;\n rewardAdded += reward;\n pending.resolved = true;\n resolved += 1;\n }\n\n saveState(state);\n logger.info(\n `Bandit delayed outcomes processed=${pendingDue.length}, resolved=${resolved}, rewardDelta=${rewardAdded.toFixed(2)}`\n );\n\n return {\n processed: pendingDue.length,\n resolved,\n rewardAdded,\n };\n}\n","import { getXClient } from \"../x-client/index.js\";\nimport { logger } from \"../utils/logger.js\";\nimport { getRecentInteractions } from \"../memory/index.js\";\nimport { listIntents, recordIntentExecution } from \"../memory/intents.js\";\nimport { loadIdentity } from \"../identity/index.js\";\nimport { loadCredentials } from \"../utils/crypto.js\";\nimport type { Tweet } from \"../x-client/types.js\";\nimport { buildSystemPrompt } from \"./prompt-builder.js\";\nimport { executeAction, type AgentAction, type ActionResult } from \"./decision-engine.js\";\nimport { evaluateActionPolicy } from \"./policy.js\";\nimport { generateResponse } from \"./llm.js\";\nimport { buildPersonaConstraintLines, getPersonaConstraints } from \"./persona-constraints.js\";\nimport {\n collectDelayedOutcomes,\n recordBanditActionResults,\n} from \"./bandit.js\";\n\nexport interface AutonomyCycleResult {\n timeline: Tweet[];\n mentions: Tweet[];\n actions: AgentAction[];\n results: ActionResult[];\n policyFeedback: string[];\n}\n\nfunction selfUserIdFromCredentials(): string | null {\n try {\n const creds = loadCredentials();\n const accessToken = creds.accessToken;\n if (!accessToken) return null;\n const dashIdx = accessToken.indexOf(\"-\");\n if (dashIdx <= 0) return null;\n const candidate = accessToken.substring(0, dashIdx);\n return /^\\d+$/.test(candidate) ? candidate : null;\n } catch {\n return null;\n }\n}\n\nfunction normalizeHandle(handle: string | undefined): string {\n return (handle ?? \"\").replace(/^@/, \"\").trim().toLowerCase();\n}\n\nfunction canonicalPlannerHandle(handle: string): string {\n const clean = normalizeHandle(handle);\n const aliasMap: Record<string, string> = {\n gork: \"grok\",\n spora: \"sporaai\",\n spora_ai: \"sporaai\",\n };\n return aliasMap[clean] ?? clean;\n}\n\nfunction canonicalizePlannerQuery(rawQuery: string): string {\n return rawQuery.replace(/from:([a-zA-Z0-9_]{1,15})/gi, (_match, handle) => `from:${canonicalPlannerHandle(handle)}`);\n}\n\ntype RewriteStyleMode =\n | \"quick_reaction\"\n | \"curious_question\"\n | \"friendly_pushback\"\n | \"plain_observation\"\n | \"playful_line\";\n\nfunction roughWordCount(text: string): number {\n return text.trim().split(/\\s+/).filter(Boolean).length;\n}\n\nfunction inferStyleMode(text: string): RewriteStyleMode {\n const lower = text.toLowerCase();\n if (text.includes(\"?\")) return \"curious_question\";\n if (/\\b(lol|lmao|haha|wild|fr|ngl)\\b/i.test(text)) return \"playful_line\";\n if (/\\b(not|isn'?t|wrong|nah|nope|doesn'?t)\\b/i.test(lower)) return \"friendly_pushback\";\n if (roughWordCount(text) <= 9) return \"quick_reaction\";\n return \"plain_observation\";\n}\n\nfunction chooseRewriteStyleMode(recentTexts?: string[], targetTweetText?: string): RewriteStyleMode {\n const counts: Record<RewriteStyleMode, number> = {\n quick_reaction: 0,\n curious_question: 0,\n friendly_pushback: 0,\n plain_observation: 0,\n playful_line: 0,\n };\n for (const text of (recentTexts ?? []).slice(0, 10)) {\n counts[inferStyleMode(text)] += 1;\n }\n\n if ((targetTweetText ?? \"\").includes(\"?\") && counts.curious_question <= 2) {\n return \"curious_question\";\n }\n\n return (Object.entries(counts).sort((a, b) => a[1] - b[1])[0]?.[0] as RewriteStyleMode) ?? \"plain_observation\";\n}\n\nfunction rewriteStyleModeInstructions(mode: RewriteStyleMode): string[] {\n if (mode === \"quick_reaction\") {\n return [\n \"- style mode: quick reaction\",\n \"- 6-14 words, one short sentence\",\n \"- immediate reaction tone, no thesis statement\",\n ];\n }\n if (mode === \"curious_question\") {\n return [\n \"- style mode: curious question\",\n \"- include exactly one direct question\",\n \"- ask about a specific detail from the target tweet\",\n ];\n }\n if (mode === \"friendly_pushback\") {\n return [\n \"- style mode: friendly pushback\",\n \"- politely disagree in plain words\",\n \"- no lecture or abstract framing\",\n ];\n }\n if (mode === \"playful_line\") {\n return [\n \"- style mode: playful line\",\n \"- keep it light and witty, not sarcastic essay mode\",\n \"- avoid internet clichés and overused slogans\",\n ];\n }\n return [\n \"- style mode: plain observation\",\n \"- write like a natural human thought said out loud\",\n \"- concrete detail first, no broad generalization\",\n ];\n}\n\nfunction shouldAttemptStyleRewrite(action: AgentAction, reason: string): boolean {\n if (!action.content || (action.action !== \"reply\" && action.action !== \"post\")) return false;\n const lower = reason.toLowerCase();\n return (\n lower.includes(\"lecture-like\") ||\n lower.includes(\"abstract philosopher cadence\") ||\n lower.includes(\"manifesto\") ||\n lower.includes(\"too long/explanatory\") ||\n lower.includes(\"grounded in the target tweet context\") ||\n lower.includes(\"hedged consensus phrasing\") ||\n lower.includes(\"repetitive anchor phrase/term\") ||\n lower.includes(\"repetitive opening phrase\") ||\n lower.includes(\"low-novelty vocabulary loop\") ||\n lower.includes(\"abstract wording without concrete anchor\")\n );\n}\n\nfunction cleanRewriteOutput(text: string): string {\n const cleaned = text\n .replace(/```[\\s\\S]*?```/g, \"\")\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .trim();\n const firstLine = cleaned.split(\"\\n\").map((line) => line.trim()).filter(Boolean)[0] ?? cleaned;\n return firstLine.trim();\n}\n\nasync function rewriteDraftForHumanVoice(input: {\n action: AgentAction;\n reason: string;\n targetTweetText?: string;\n recentTexts?: string[];\n}): Promise<string | null> {\n if (!input.action.content) return null;\n const identity = loadIdentity();\n const maxChars = input.action.action === \"reply\" ? 100 : 130;\n const minChars = input.action.action === \"reply\" ? 18 : 24;\n const styleMode = chooseRewriteStyleMode(input.recentTexts, input.targetTweetText);\n\n const system = [\n `You rewrite X/Twitter drafts into ${identity.name}'s natural voice.`,\n \"Output must feel human, direct, and contextual.\",\n \"Never write abstract philosophy or explanatory manifesto style.\",\n \"Return ONLY rewritten tweet text, no commentary.\",\n ].join(\" \");\n\n const promptParts: string[] = [];\n promptParts.push(`Current draft: ${input.action.content}`);\n promptParts.push(`Rejected because: ${input.reason}`);\n if (input.targetTweetText) {\n promptParts.push(`Target tweet context: ${input.targetTweetText}`);\n }\n promptParts.push(`Constraints:`);\n promptParts.push(`- ${minChars}-${maxChars} characters`);\n promptParts.push(\"- 1-2 short sentences max\");\n promptParts.push(\"- no 'the real question' / 'the deeper question' framing\");\n promptParts.push(\"- no colon, semicolon, or em dash\");\n promptParts.push(\"- specific and concrete, not abstract\");\n promptParts.push(\"- keep the same core stance\");\n promptParts.push(\"- use natural spoken phrasing and contractions when it fits\");\n for (const line of rewriteStyleModeInstructions(styleMode)) {\n promptParts.push(line);\n }\n if (input.recentTexts && input.recentTexts.length > 0) {\n promptParts.push(\"- avoid vocabulary anchors from these recent outputs:\");\n for (const text of input.recentTexts.slice(0, 5)) {\n promptParts.push(` - ${text.slice(0, 120)}`);\n }\n }\n\n try {\n const rewrite = await generateResponse(system, promptParts.join(\"\\n\"));\n const candidate = cleanRewriteOutput(rewrite.content);\n if (!candidate) return null;\n return candidate;\n } catch {\n return null;\n }\n}\n\ninterface LoopTopicSearchResult {\n query: string;\n tweets: Tweet[];\n}\n\ninterface LoopPersonActivity {\n handle: string;\n userId: string;\n reason: string;\n tweets: Tweet[];\n}\n\ninterface LoopResearchState {\n timeline: Tweet[];\n mentions: Tweet[];\n topicSearchResults: LoopTopicSearchResult[];\n peopleActivity: LoopPersonActivity[];\n}\n\ntype PlannerToolName =\n | \"observe_timeline\"\n | \"observe_mentions\"\n | \"search_tweets\"\n | \"check_profile\"\n | \"reply\"\n | \"like\"\n | \"retweet\"\n | \"follow\"\n | \"post\"\n | \"skip\";\n\ninterface PlannerDecision {\n tool: PlannerToolName;\n args: Record<string, unknown>;\n reasoning?: string;\n}\n\ninterface ToolStepSummary {\n step: number;\n tool: PlannerToolName;\n summary: string;\n}\n\nfunction loopClampInt(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, Math.round(value)));\n}\n\nfunction parseJsonObjectFromText(text: string): Record<string, unknown> | null {\n const fenced = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/i)?.[1];\n const candidates = [fenced, text].filter((v): v is string => Boolean(v)).map((v) => v.trim());\n for (const candidate of candidates) {\n try {\n const parsed = JSON.parse(candidate);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n if (Array.isArray(parsed) && parsed.length > 0 && parsed[0] && typeof parsed[0] === \"object\") {\n return parsed[0] as Record<string, unknown>;\n }\n } catch {\n // Continue to extraction fallback.\n }\n const obj = candidate.match(/\\{[\\s\\S]*\\}/);\n if (!obj) continue;\n try {\n const parsed = JSON.parse(obj[0]);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n // Continue.\n }\n }\n return null;\n}\n\nfunction mapPlannerTool(raw: string | undefined): PlannerToolName | null {\n const clean = (raw ?? \"\").trim().toLowerCase();\n if (!clean) return null;\n if (clean === \"observe_timeline\" || clean === \"read_timeline\" || clean === \"timeline\") return \"observe_timeline\";\n if (clean === \"observe_mentions\" || clean === \"read_mentions\" || clean === \"mentions\") return \"observe_mentions\";\n if (clean === \"search_tweets\" || clean === \"search\" || clean === \"topic_search\") return \"search_tweets\";\n if (clean === \"check_profile\" || clean === \"check_person\" || clean === \"people_check\" || clean === \"profile_check\") return \"check_profile\";\n if (clean === \"reply\") return \"reply\";\n if (clean === \"like\") return \"like\";\n if (clean === \"retweet\") return \"retweet\";\n if (clean === \"follow\") return \"follow\";\n if (clean === \"post\" || clean === \"tweet\") return \"post\";\n if (clean === \"skip\" || clean === \"noop\" || clean === \"no_action\") return \"skip\";\n return null;\n}\n\nfunction parsePlannerDecision(text: string): PlannerDecision | null {\n const parsed = parseJsonObjectFromText(text);\n if (!parsed) return null;\n\n const rawTool =\n typeof parsed.tool === \"string\"\n ? parsed.tool\n : typeof parsed.action === \"string\"\n ? parsed.action\n : undefined;\n const tool = mapPlannerTool(rawTool);\n if (!tool) return null;\n\n const rawArgs = parsed.args;\n const args: Record<string, unknown> =\n rawArgs && typeof rawArgs === \"object\" && !Array.isArray(rawArgs)\n ? { ...(rawArgs as Record<string, unknown>) }\n : {};\n\n for (const key of [\"tweetId\", \"content\", \"handle\", \"query\", \"count\", \"reason\"]) {\n if (args[key] !== undefined) continue;\n if (parsed[key] !== undefined) args[key] = parsed[key];\n }\n\n const reasoning = typeof parsed.reasoning === \"string\" ? parsed.reasoning.trim() : undefined;\n return { tool, args, reasoning };\n}\n\nfunction argString(args: Record<string, unknown>, key: string): string | undefined {\n const value = args[key];\n if (typeof value !== \"string\") return undefined;\n const clean = value.trim();\n return clean.length > 0 ? clean : undefined;\n}\n\nfunction argCount(args: Record<string, unknown>, fallback: number, min: number, max: number): number {\n const raw = args.count;\n if (typeof raw === \"number\" && Number.isFinite(raw)) {\n return loopClampInt(raw, min, max);\n }\n if (typeof raw === \"string\" && raw.trim().length > 0) {\n const parsed = Number(raw);\n if (Number.isFinite(parsed)) return loopClampInt(parsed, min, max);\n }\n return loopClampInt(fallback, min, max);\n}\n\nfunction tweetTimestamp(tweet: Tweet): number {\n const ts = Date.parse(tweet.createdAt);\n return Number.isNaN(ts) ? 0 : ts;\n}\n\nfunction mergeTweetList(current: Tweet[], incoming: Tweet[]): { tweets: Tweet[]; added: number } {\n const byId = new Map<string, Tweet>();\n for (const tweet of current) byId.set(tweet.id, tweet);\n let added = 0;\n for (const tweet of incoming) {\n if (!tweet.id) continue;\n if (!byId.has(tweet.id)) added += 1;\n byId.set(tweet.id, tweet);\n }\n const tweets = [...byId.values()].sort((a, b) => tweetTimestamp(b) - tweetTimestamp(a));\n return { tweets, added };\n}\n\nfunction mergeTopicResult(\n current: LoopTopicSearchResult[],\n query: string,\n incoming: Tweet[],\n): { next: LoopTopicSearchResult[]; added: number } {\n const idx = current.findIndex((item) => item.query.toLowerCase() === query.toLowerCase());\n if (idx < 0) {\n const merged = mergeTweetList([], incoming);\n return {\n next: [...current, { query, tweets: merged.tweets }],\n added: merged.added,\n };\n }\n const merged = mergeTweetList(current[idx].tweets, incoming);\n const next = [...current];\n next[idx] = { ...next[idx], tweets: merged.tweets };\n return { next, added: merged.added };\n}\n\nfunction mergePeopleActivity(\n current: LoopPersonActivity[],\n incoming: LoopPersonActivity,\n): { next: LoopPersonActivity[]; added: number } {\n const handle = normalizeHandle(incoming.handle);\n const idx = current.findIndex((item) => normalizeHandle(item.handle) === handle);\n if (idx < 0) {\n const merged = mergeTweetList([], incoming.tweets);\n return {\n next: [...current, { ...incoming, handle, tweets: merged.tweets }],\n added: merged.added,\n };\n }\n const merged = mergeTweetList(current[idx].tweets, incoming.tweets);\n const next = [...current];\n next[idx] = {\n ...next[idx],\n userId: incoming.userId || next[idx].userId,\n reason: incoming.reason || next[idx].reason,\n tweets: merged.tweets,\n };\n return { next, added: merged.added };\n}\n\nfunction collectObserved(state: LoopResearchState): {\n ids: string[];\n tweets: Tweet[];\n byId: Map<string, Tweet>;\n} {\n const tweets = [\n ...state.timeline,\n ...state.mentions,\n ...state.topicSearchResults.flatMap((item) => item.tweets),\n ...state.peopleActivity.flatMap((item) => item.tweets),\n ];\n const byId = new Map<string, Tweet>();\n for (const tweet of tweets) {\n if (!tweet.id || byId.has(tweet.id)) continue;\n byId.set(tweet.id, tweet);\n }\n return {\n ids: [...byId.keys()],\n tweets: [...byId.values()],\n byId,\n };\n}\n\nfunction buildPlannerCandidates(\n state: LoopResearchState,\n): Tweet[] {\n const ordered = [\n ...state.mentions,\n ...state.timeline,\n ...state.topicSearchResults.flatMap((item) => item.tweets),\n ...state.peopleActivity.flatMap((item) => item.tweets),\n ];\n const byId = new Map<string, Tweet>();\n for (const tweet of ordered) {\n if (!tweet.id) continue;\n if (!byId.has(tweet.id)) byId.set(tweet.id, tweet);\n }\n return [...byId.values()].slice(0, 24);\n}\n\nfunction buildToolLoopPrompt(input: {\n identity: {\n name: string;\n handle: string;\n bio: string;\n tone: string;\n goals: string[];\n boundaries: string[];\n };\n constraintLines: string[];\n candidates: Tweet[];\n state: LoopResearchState;\n actions: AgentAction[];\n policyFeedback: string[];\n toolHistory: ToolStepSummary[];\n recentMemory: string[];\n heartbeatCount: number;\n}): string {\n const lines: string[] = [];\n lines.push(\"Choose exactly ONE tool call in strict JSON.\");\n lines.push(\"You are the autonomous planner. No fixed research sequence is required.\");\n lines.push(\"Act based on persona + live context, not templates.\");\n lines.push(\"\");\n lines.push(`Heartbeat: #${input.heartbeatCount}`);\n lines.push(`Agent: ${input.identity.name} (@${input.identity.handle})`);\n lines.push(`Bio: ${input.identity.bio}`);\n lines.push(`Tone: ${input.identity.tone}`);\n lines.push(`Goals: ${input.identity.goals.join(\" | \") || \"none\"}`);\n lines.push(`Boundaries: ${input.identity.boundaries.join(\" | \") || \"none\"}`);\n lines.push(\"\");\n if (input.constraintLines.length > 0) {\n lines.push(\"Hard persona constraints:\");\n for (const line of input.constraintLines) lines.push(line);\n lines.push(\"\");\n }\n if (input.recentMemory.length > 0) {\n lines.push(\"Recent memory:\");\n for (const row of input.recentMemory.slice(0, 8)) {\n lines.push(`- ${row}`);\n }\n lines.push(\"\");\n }\n lines.push(`Executed actions this heartbeat: ${input.actions.length}`);\n lines.push(\n `Current context counts: timeline=${input.state.timeline.length}, mentions=${input.state.mentions.length}, topicTweets=${input.state.topicSearchResults.reduce((sum, item) => sum + item.tweets.length, 0)}, peopleTweets=${input.state.peopleActivity.reduce((sum, item) => sum + item.tweets.length, 0)}`\n );\n lines.push(\"\");\n if (input.toolHistory.length > 0) {\n lines.push(\"Recent tool steps:\");\n for (const row of input.toolHistory.slice(-6)) {\n lines.push(`- Step ${row.step}: ${row.tool} -> ${row.summary}`);\n }\n lines.push(\"\");\n }\n if (input.policyFeedback.length > 0) {\n lines.push(\"Recent policy feedback:\");\n for (const note of input.policyFeedback.slice(-8)) {\n lines.push(`- ${note}`);\n }\n lines.push(\"\");\n }\n if (input.candidates.length > 0) {\n lines.push(`Top candidate tweets (${input.candidates.length}):`);\n for (const tweet of input.candidates.slice(0, 16)) {\n lines.push(\n `- [${tweet.id}] @${tweet.authorHandle}: ${tweet.text.slice(0, 190)} (${tweet.likeCount ?? 0} likes, ${tweet.replyCount ?? 0} replies)`\n );\n }\n lines.push(\"\");\n } else {\n lines.push(\"No candidate tweets currently in context.\");\n lines.push(\"\");\n }\n lines.push(\"Tool options:\");\n lines.push('- observe_timeline: { \"count\": 8-30 }');\n lines.push('- observe_mentions: { \"count\": 8-30 }');\n lines.push('- search_tweets: { \"query\": \"x api search query\", \"count\": 3-20 }');\n lines.push('- check_profile: { \"handle\": \"@username\", \"count\": 3-12 }');\n lines.push('- reply: { \"tweetId\": \"id\", \"content\": \"reply under 220 chars\" }');\n lines.push('- like: { \"tweetId\": \"id\" }');\n lines.push('- retweet: { \"tweetId\": \"id\" }');\n lines.push('- follow: { \"handle\": \"@username\" }');\n lines.push('- post: { \"content\": \"post under 220 chars\" }');\n lines.push('- skip: { \"reason\": \"short reason\" }');\n lines.push(\"\");\n lines.push(\"Output JSON object only:\");\n lines.push('{ \"tool\": \"reply\", \"args\": { \"tweetId\": \"...\", \"content\": \"...\" }, \"reasoning\": \"short why\" }');\n lines.push(\"\");\n lines.push(\"Planning rules:\");\n lines.push(\"- if timeline/mentions already have viable tweets, prefer acting over more research\");\n lines.push(\"- use search/profile checks only when you have a clear reason\");\n lines.push(\"- avoid repeating the same query/target unless context changed\");\n lines.push(\"\");\n lines.push(\"Writing constraints:\");\n lines.push(\"- sound human and specific, no manifesto language\");\n lines.push(\"- avoid 'the real question' / 'the deeper question' phrasing\");\n lines.push(\"- no repetitive anchor terms from recent outputs\");\n lines.push(\"- match the persona tone strictly\");\n return lines.join(\"\\n\");\n}\n\nfunction fallbackPlannerDecision(step: number, observedCount: number): PlannerDecision {\n if (observedCount === 0) {\n return {\n tool: step % 2 === 0 ? \"observe_timeline\" : \"observe_mentions\",\n args: { count: 20 },\n reasoning: \"fallback context bootstrap\",\n };\n }\n return {\n tool: \"skip\",\n args: { reason: \"planner parse fallback; preserve current context\" },\n reasoning: \"fallback no-op\",\n };\n}\n\nfunction decisionToAgentAction(decision: PlannerDecision): AgentAction | null {\n if (decision.tool === \"reply\") {\n const tweetId = argString(decision.args, \"tweetId\");\n const content = argString(decision.args, \"content\");\n if (!tweetId || !content) return null;\n return { action: \"reply\", tweetId, content, reasoning: decision.reasoning };\n }\n if (decision.tool === \"like\") {\n const tweetId = argString(decision.args, \"tweetId\");\n if (!tweetId) return null;\n return { action: \"like\", tweetId, reasoning: decision.reasoning };\n }\n if (decision.tool === \"retweet\") {\n const tweetId = argString(decision.args, \"tweetId\");\n if (!tweetId) return null;\n return { action: \"retweet\", tweetId, reasoning: decision.reasoning };\n }\n if (decision.tool === \"follow\") {\n const handle = argString(decision.args, \"handle\");\n if (!handle) return null;\n return { action: \"follow\", handle, targetHandle: handle, reasoning: decision.reasoning };\n }\n if (decision.tool === \"post\") {\n const content = argString(decision.args, \"content\");\n if (!content) return null;\n return { action: \"post\", content, reasoning: decision.reasoning };\n }\n if (decision.tool === \"skip\") {\n return { action: \"skip\", reason: argString(decision.args, \"reason\"), reasoning: decision.reasoning };\n }\n return null;\n}\n\nexport async function runAutonomyCycle(maxActions: number, heartbeatCount: number = 0): Promise<AutonomyCycleResult> {\n const client = await getXClient();\n const identity = loadIdentity();\n const constraints = getPersonaConstraints();\n const constraintLines = buildPersonaConstraintLines(constraints);\n if (constraintLines.length > 0) {\n logger.info(`Persona constraints active: ${constraintLines.join(\" | \")}`);\n }\n logger.info(`Autonomy runtime v2 active: planner-primary, persona+memory driven.`);\n\n try {\n const delayed = await collectDelayedOutcomes(client);\n if (delayed.processed > 0) {\n logger.info(\n `Delayed outcomes: processed=${delayed.processed}, resolved=${delayed.resolved}, rewardDelta=${delayed.rewardAdded.toFixed(2)}`\n );\n }\n } catch (error) {\n logger.warn(`Delayed outcome collection failed: ${(error as Error).message}`);\n }\n\n const selfHandle = identity.handle.replace(/^@/, \"\").toLowerCase();\n const selfUserId = selfUserIdFromCredentials();\n const isSelfTweet = (tweet: Tweet): boolean =>\n tweet.authorHandle.replace(/^@/, \"\").toLowerCase() === selfHandle ||\n (selfUserId !== null && tweet.authorId === selfUserId);\n\n const state: LoopResearchState = {\n timeline: [],\n mentions: [],\n topicSearchResults: [],\n peopleActivity: [],\n };\n\n try {\n const timeline = (await client.getTimeline({ count: 30 })).filter((tweet) => !isSelfTweet(tweet));\n state.timeline = mergeTweetList(state.timeline, timeline).tweets;\n } catch (error) {\n logger.warn(`Seed timeline read failed: ${(error as Error).message}`);\n }\n\n try {\n const mentions = (await client.getMentions({ count: 30 })).filter((tweet) => !isSelfTweet(tweet));\n state.mentions = mergeTweetList(state.mentions, mentions).tweets;\n } catch (error) {\n logger.warn(`Seed mentions read failed: ${(error as Error).message}`);\n }\n\n logger.info(\n `Autonomy context: timeline=${state.timeline.length}, mentions=${state.mentions.length}, topicTweets=${state.topicSearchResults.reduce((sum, item) => sum + item.tweets.length, 0)}, peopleTweets=${state.peopleActivity.reduce((sum, item) => sum + item.tweets.length, 0)}`\n );\n\n const actions: AgentAction[] = [];\n const results: ActionResult[] = [];\n const toolHistory: ToolStepSummary[] = [];\n const policyFeedback: string[] = [\n `Persona: ${identity.name} (@${identity.handle})`,\n `Tone: ${identity.tone}`,\n `Goals: ${(identity.goals ?? []).slice(0, 4).join(\" | \") || \"none\"}`,\n ];\n\n const systemPrompt = buildSystemPrompt();\n const toolSystemPrompt = [\n systemPrompt,\n \"TOOL LOOP MODE: You must choose exactly one tool call each step using strict JSON.\",\n \"Planner-first mode: there is no pre-defined research flow.\",\n \"Everything must be persona-driven, memory-aware, and context-grounded.\",\n \"Do not fall into repetitive searches or repetitive targets.\",\n ].join(\"\\n\\n\");\n const activeIntents = listIntents();\n let staleSteps = 0;\n let attemptedActions = 0;\n const maxToolSteps = Math.max(12, maxActions * 6);\n\n // Keep short memory available in context by touching it before loop.\n getRecentInteractions(20);\n\n for (let step = 0; step < maxToolSteps && actions.length < maxActions; step += 1) {\n const candidates = buildPlannerCandidates(state);\n const recentMemory = getRecentInteractions(24)\n .slice(0, 12)\n .map((entry) => {\n const text = (entry.content ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, 120);\n const target = entry.targetHandle ? ` @${entry.targetHandle}` : \"\";\n return `${entry.type}${target}${text ? `: ${text}` : \"\"}`;\n });\n const prompt = buildToolLoopPrompt({\n identity: {\n name: identity.name,\n handle: identity.handle,\n bio: identity.bio,\n tone: identity.tone,\n goals: identity.goals ?? [],\n boundaries: identity.boundaries ?? [],\n },\n constraintLines,\n candidates,\n state,\n actions,\n policyFeedback,\n toolHistory,\n recentMemory,\n heartbeatCount,\n });\n\n let decision = fallbackPlannerDecision(step, candidates.length);\n try {\n const response = await generateResponse(toolSystemPrompt, prompt);\n const parsed = parsePlannerDecision(response.content);\n if (parsed) {\n decision = parsed;\n } else {\n policyFeedback.push(\"Planner returned invalid JSON decision. Using fallback tool.\");\n }\n } catch (error) {\n policyFeedback.push(`Planner call failed: ${(error as Error).message}`);\n }\n\n logger.info(`Tool loop step ${step + 1}: ${decision.tool}`);\n let stepProgress = false;\n\n if (decision.tool === \"observe_timeline\") {\n const count = argCount(decision.args, 16, 8, 30);\n try {\n const incoming = (await client.getTimeline({ count })).filter((tweet) => !isSelfTweet(tweet));\n const merged = mergeTweetList(state.timeline, incoming);\n state.timeline = merged.tweets;\n stepProgress = merged.added > 0;\n toolHistory.push({\n step: step + 1,\n tool: decision.tool,\n summary: `fetched ${incoming.length}, added ${merged.added}`,\n });\n } catch (error) {\n policyFeedback.push(`observe_timeline failed: ${(error as Error).message}`);\n }\n if (!stepProgress) policyFeedback.push(\"observe_timeline found no new tweets.\");\n continue;\n }\n\n if (decision.tool === \"observe_mentions\") {\n const count = argCount(decision.args, 16, 8, 30);\n try {\n const incoming = (await client.getMentions({ count })).filter((tweet) => !isSelfTweet(tweet));\n const merged = mergeTweetList(state.mentions, incoming);\n state.mentions = merged.tweets;\n stepProgress = merged.added > 0;\n toolHistory.push({\n step: step + 1,\n tool: decision.tool,\n summary: `fetched ${incoming.length}, added ${merged.added}`,\n });\n } catch (error) {\n policyFeedback.push(`observe_mentions failed: ${(error as Error).message}`);\n }\n if (!stepProgress) policyFeedback.push(\"observe_mentions found no new tweets.\");\n continue;\n }\n\n if (decision.tool === \"search_tweets\") {\n const rawQuery = argString(decision.args, \"query\");\n if (!rawQuery) {\n policyFeedback.push(\"search_tweets rejected: missing query.\");\n continue;\n }\n const query = canonicalizePlannerQuery(rawQuery);\n if (query !== rawQuery) {\n policyFeedback.push(`search_tweets normalized handle query: \"${rawQuery}\" -> \"${query}\"`);\n }\n const count = argCount(decision.args, 10, 3, 20);\n try {\n const incoming = (await client.searchTweets(query, { count })).filter((tweet) => !isSelfTweet(tweet));\n const merged = mergeTopicResult(state.topicSearchResults, query, incoming);\n state.topicSearchResults = merged.next;\n stepProgress = merged.added > 0;\n toolHistory.push({\n step: step + 1,\n tool: decision.tool,\n summary: `\"${query}\" fetched ${incoming.length}, added ${merged.added}`,\n });\n logger.info(`Tool search \"${query}\": found ${incoming.length} tweets`);\n } catch (error) {\n policyFeedback.push(`search_tweets failed for \"${query}\": ${(error as Error).message}`);\n }\n if (!stepProgress) policyFeedback.push(`search_tweets \"${query}\" found no new tweets.`);\n continue;\n }\n\n if (decision.tool === \"check_profile\") {\n const handleInput = argString(decision.args, \"handle\");\n const handle = handleInput ? canonicalPlannerHandle(handleInput) : \"\";\n if (!handle) {\n policyFeedback.push(\"check_profile rejected: missing handle.\");\n continue;\n }\n const count = argCount(decision.args, 6, 3, 12);\n try {\n const profile = await client.getProfile(handle);\n const tweets = (await client.getUserTweets(profile.id, { count })).filter((tweet) => !isSelfTweet(tweet));\n const merged = mergePeopleActivity(state.peopleActivity, {\n handle,\n userId: profile.id,\n reason: \"tool-loop check\",\n tweets,\n });\n state.peopleActivity = merged.next;\n stepProgress = merged.added > 0;\n toolHistory.push({\n step: step + 1,\n tool: decision.tool,\n summary: `@${handle} fetched ${tweets.length}, added ${merged.added}`,\n });\n logger.info(`People check @${handle}: ${tweets.length} recent tweets`);\n } catch (error) {\n policyFeedback.push(`check_profile failed for @${handle}: ${(error as Error).message}`);\n }\n if (!stepProgress) policyFeedback.push(`check_profile @${handle} found no new tweets.`);\n continue;\n }\n\n const observed = collectObserved(state);\n let candidateAction = decisionToAgentAction(decision);\n if (!candidateAction) {\n policyFeedback.push(`Tool decision ${decision.tool} rejected: invalid arguments.`);\n staleSteps += 1;\n continue;\n }\n\n if (candidateAction.tweetId && observed.byId.has(candidateAction.tweetId)) {\n const author = normalizeHandle(observed.byId.get(candidateAction.tweetId)?.authorHandle);\n if (author && !candidateAction.targetHandle) {\n candidateAction.targetHandle = `@${author}`;\n }\n }\n\n if (candidateAction.action === \"skip\") {\n const reason = candidateAction.reason ?? candidateAction.reasoning ?? \"planner skip\";\n policyFeedback.push(`Planner chose skip: ${reason}`);\n toolHistory.push({\n step: step + 1,\n tool: decision.tool,\n summary: reason,\n });\n staleSteps += 1;\n if (staleSteps >= 4) break;\n continue;\n }\n\n attemptedActions += 1;\n let policy = evaluateActionPolicy({\n action: candidateAction,\n step: attemptedActions,\n timeline: state.timeline,\n mentions: state.mentions,\n executedActions: actions,\n observedTweetIds: observed.ids,\n observedTweets: observed.tweets,\n selfHandle,\n selfUserId,\n });\n\n if (!policy.allowed && shouldAttemptStyleRewrite(candidateAction, policy.reason ?? \"\")) {\n const recentTexts = getRecentInteractions(10)\n .filter((entry) => entry.type === \"post\" || entry.type === \"reply\")\n .map((entry) => entry.content ?? \"\")\n .filter(Boolean);\n const rewritten = await rewriteDraftForHumanVoice({\n action: candidateAction,\n reason: policy.reason ?? \"policy rejected\",\n targetTweetText: candidateAction.tweetId ? observed.byId.get(candidateAction.tweetId)?.text : undefined,\n recentTexts,\n });\n\n if (rewritten && rewritten !== candidateAction.content) {\n candidateAction = {\n ...candidateAction,\n content: rewritten,\n reasoning: `${candidateAction.reasoning ?? \"rewritten\"} | style rewrite`,\n };\n policy = evaluateActionPolicy({\n action: candidateAction,\n step: attemptedActions,\n timeline: state.timeline,\n mentions: state.mentions,\n executedActions: actions,\n observedTweetIds: observed.ids,\n observedTweets: observed.tweets,\n selfHandle,\n selfUserId,\n });\n }\n }\n\n if (!policy.allowed) {\n const reason = policy.reason ?? \"Policy rejected action\";\n // Policy is fully advisory in planner-primary mode.\n policyFeedback.push(`Policy advisory (not blocking): ${reason}`);\n logger.info(`Policy advisory for ${candidateAction.action}: ${reason}`);\n }\n\n const result = await executeAction(candidateAction);\n actions.push(candidateAction);\n results.push(result);\n staleSteps = 0;\n stepProgress = true;\n toolHistory.push({\n step: step + 1,\n tool: decision.tool,\n summary: `${candidateAction.action}${result.success ? \" success\" : \" failed\"}`,\n });\n\n if (activeIntents.length > 0) {\n const touchedHandle = normalizeHandle(\n candidateAction.targetHandle ??\n candidateAction.handle ??\n (candidateAction.tweetId ? observed.byId.get(candidateAction.tweetId)?.authorHandle : undefined)\n );\n const loweredContent = (candidateAction.content ?? \"\").toLowerCase();\n for (const intent of activeIntents) {\n const handleMatch =\n touchedHandle.length > 0 &&\n intent.targetHandles.some((handle) => normalizeHandle(handle) === touchedHandle);\n const topicMatch =\n loweredContent.length > 0 &&\n intent.focusTopics.some((topic) => loweredContent.includes(topic.toLowerCase()));\n if (!handleMatch && !topicMatch) continue;\n recordIntentExecution(intent.id, {\n success: result.success,\n note: `${candidateAction.action}${touchedHandle ? ` @${touchedHandle}` : \"\"}`,\n });\n }\n }\n\n if (!result.success) {\n const err = result.error ?? \"\";\n if (candidateAction.action === \"reply\" && /duplicate content/i.test(err)) {\n const reason = \"Reply failed with duplicate-content error. Planner should choose a different wording/target.\";\n policyFeedback.push(reason);\n logger.info(`Policy adjustment: ${reason}`);\n }\n if (candidateAction.action === \"post\" && /duplicate content/i.test(err)) {\n const reason = \"Post failed with duplicate-content error. Change framing and try a different angle.\";\n policyFeedback.push(reason);\n logger.info(`Policy adjustment: ${reason}`);\n }\n }\n\n if (!stepProgress) {\n staleSteps += 1;\n }\n if (staleSteps >= 5) {\n logger.info(\"Tool loop stopped after repeated no-progress steps.\");\n break;\n }\n }\n\n recordBanditActionResults(actions, results);\n\n return {\n timeline: state.timeline,\n mentions: state.mentions,\n actions,\n results,\n policyFeedback,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkHA,eAAsB,cAAc,QAA4C;AAC9E,QAAM,EAAE,QAAQ,KAAK,IAAI;AAEzB,MAAI;AACF,YAAQ,MAAM;AAAA,MACZ,KAAK,QAAQ;AACX,YAAI,CAAC,OAAO,QAAS,QAAO,EAAE,QAAQ,MAAM,SAAS,OAAO,OAAO,sBAAsB;AACzF,YAAI,OAAO,QAAQ,SAAS,KAAK;AAC/B,iBAAO,EAAE,QAAQ,MAAM,SAAS,OAAO,OAAO,mBAAmB,OAAO,QAAQ,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AAW,UAAU,eAAe;AAClC,cAAM,cACJ,cAAc,SAAS,KACvB,OAAO,cAAc,KAAK,CAAC,WAAWA,iBAAgB,MAAM,MAAM,aAAa;AACjF,cAAM,aACJ,eAAe,SAAS,KACxB,OAAO,YAAY,KAAK,CAAC,UAAU,eAAe,SAAS,MAAM,YAAY,CAAC,CAAC;AACjF,YAAI,CAAC,eAAe,CAAC,WAAY;AACjC,8BAAsB,OAAO,IAAI;AAAA,UAC/B,SAAS,OAAO;AAAA,UAChB,MAAM,GAAG,gBAAgB,MAAM,GAAG,gBAAgB,KAAK,aAAa,KAAK,EAAE;AAAA,QAC7E,CAAC;AAAA,MACH;AAAA,IACF;AAEA,QAAI,CAAC,OAAO,SAAS;AACnB,YAAM,MAAM,OAAO,SAAS;AAC5B,UAAI,gBAAgB,WAAW,WAAW,qBAAqB,KAAK,GAAG,GAAG;AACxE,cAAM,SAAS;AACf,uBAAe,KAAK,MAAM;AAC1B,eAAO,KAAK,sBAAsB,MAAM,EAAE;AAAA,MAC5C;AACA,UAAI,gBAAgB,WAAW,UAAU,qBAAqB,KAAK,GAAG,GAAG;AACvE,cAAM,SAAS;AACf,uBAAe,KAAK,MAAM;AAC1B,eAAO,KAAK,sBAAsB,MAAM,EAAE;AAAA,MAC5C;AAAA,IACF;AAEA,QAAI,CAAC,cAAc;AACjB,oBAAc;AAAA,IAChB;AACA,QAAI,cAAc,GAAG;AACnB,aAAO,KAAK,qDAAqD;AACjE;AAAA,IACF;AAAA,EACF;AAEA,4BAA0B,SAAS,OAAO;AAE1C,SAAO;AAAA,IACL,UAAU,MAAM;AAAA,IAChB,UAAU,MAAM;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["normalizeHandle","merged"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/init.ts","../src/x-client/profile-updater.ts"],"sourcesContent":["import { input, select, password as passwordPrompt } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport { ensureDirectories } from \"./utils/paths.js\";\nimport { createDefaultConfig, saveConfig } from \"./utils/config.js\";\nimport { saveCredentials } from \"./utils/crypto.js\";\nimport { loadIdentity } from \"./identity/index.js\";\nimport type { Identity } from \"./identity/schema.js\";\nimport { updateXProfile } from \"./x-client/profile-updater.js\";\nimport { setLLMApiKey, type LLMProvider, getDefaultModel } from \"./runtime/llm.js\";\n\n/**\n * Fetch identity from token and save locally\n */\nasync function syncIdentityFromToken(token: string): Promise<void> {\n console.log(chalk.gray(\"Connecting to spora.dev...\\n\"));\n\n const apiUrl = process.env.SPORA_API_URL || \"https://www.spora.social\";\n const response = await fetch(`${apiUrl}/api/v1/connect`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ token }),\n });\n\n if (!response.ok) {\n const errData = await response.json().catch(() => ({} as { error?: string })) as { error?: string };\n throw new Error(errData.error || `Connection failed: ${response.statusText}`);\n }\n\n const data = await response.json() as {\n identity?: Identity;\n media?: { profileImage?: string; bannerImage?: string };\n readme?: string;\n };\n\n if (!data.identity) {\n throw new Error(\"No Spore identity found for this token\");\n }\n\n // Merge media fields\n if (data.media) {\n if (data.media.profileImage) data.identity.profileImage = data.media.profileImage;\n if (data.media.bannerImage) data.identity.bannerImage = data.media.bannerImage;\n }\n\n const { saveIdentity } = await import(\"./identity/index.js\");\n saveIdentity(data.identity);\n\n console.log(chalk.green(`✓ Connected to Spore: ${data.identity.name} (@${data.identity.handle})\\n`));\n\n // Save README if provided\n if (data.readme) {\n const { writeFileSync } = await import(\"node:fs\");\n const { paths } = await import(\"./utils/paths.js\");\n const { join, dirname } = await import(\"node:path\");\n const readmePath = join(dirname(paths.identity), \"IDENTITY.md\");\n writeFileSync(readmePath, data.readme, \"utf-8\");\n console.log(chalk.green(\"✓ Saved identity README\\n\"));\n }\n\n // Save connection token to config\n const { existsSync } = await import(\"node:fs\");\n const { paths } = await import(\"./utils/paths.js\");\n if (existsSync(paths.config)) {\n const { loadConfig, saveConfig } = await import(\"./utils/config.js\");\n const config = loadConfig();\n config.connection = {\n token,\n apiEndpoint: process.env.SPORA_API_URL || \"https://www.spora.social/api/v1\",\n configVersion: config.connection?.configVersion ?? 0,\n };\n saveConfig(config);\n }\n}\n\nasync function notifyConnectProfileCompletion(input: {\n token: string;\n profileUpdated: boolean;\n updatedFields: string[];\n errors: string[];\n}): Promise<void> {\n const apiUrl = process.env.SPORA_API_URL || \"https://www.spora.social\";\n try {\n const response = await fetch(`${apiUrl}/api/v1/connect/complete`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n token: input.token,\n profileUpdated: input.profileUpdated,\n updatedFields: input.updatedFields,\n errors: input.errors,\n }),\n });\n\n if (!response.ok) {\n const payload = await response.json().catch(() => ({})) as { error?: string };\n console.log(chalk.yellow(`Token launch callback skipped: ${payload.error || response.statusText}`));\n return;\n }\n\n const payload = await response.json().catch(() => ({})) as {\n triggered?: boolean;\n status?: string;\n reason?: string;\n warning?: string;\n };\n\n if (!payload.triggered) {\n const reason = payload.reason ? ` (${payload.reason})` : \"\";\n console.log(chalk.gray(`Bags token launch not triggered${reason}.`));\n return;\n }\n\n const status = payload.status ? ` [${payload.status}]` : \"\";\n console.log(chalk.green(`✓ Bags token launch request sent${status}`));\n if (payload.warning) {\n console.log(chalk.yellow(` ${payload.warning}`));\n }\n } catch (error) {\n console.log(chalk.yellow(`Token launch callback failed: ${(error as Error).message}`));\n }\n}\n\n/**\n * Login flow: paste token → sync identity → open chat (keys already saved locally)\n */\nasync function loginFlow(): Promise<void> {\n console.log(chalk.bold(\"\\n━━━ Login to Existing Spore ━━━\\n\"));\n console.log(chalk.gray(\"Paste your setup token from spora.dev\"));\n console.log(chalk.gray(\"(It looks like: spora_7e636ac0...)\\n\"));\n\n const token = await input({\n message: \"Setup token:\",\n validate: (val) => val.length > 0 ? true : \"Token is required\",\n });\n\n ensureDirectories();\n\n try {\n await syncIdentityFromToken(token.trim());\n } catch (error) {\n console.log(chalk.red(`\\n✗ ${(error as Error).message}\\n`));\n console.log(chalk.yellow(\"Please check your token and try again.\\n\"));\n process.exit(1);\n }\n\n console.log(chalk.green(\"✓ Logged in!\\n\"));\n console.log(chalk.gray(\"Opening chat interface...\\n\"));\n\n try {\n const { startWebChat } = await import(\"./web-chat/index.js\");\n await startWebChat();\n } catch (error) {\n console.log(chalk.yellow(`Could not start chat interface: ${(error as Error).message}\\n`));\n console.log(chalk.gray(\"You can start it manually with: spora chat\\n\"));\n }\n}\n\ninterface SetupResult {\n llm: {\n provider: LLMProvider;\n model: string;\n };\n}\n\nfunction providerKeyUrl(provider: LLMProvider): string {\n if (provider === \"anthropic\") return \"https://console.anthropic.com/settings/keys\";\n if (provider === \"openai\") return \"https://platform.openai.com/api-keys\";\n return \"https://platform.deepseek.com/api_keys\";\n}\n\n/**\n * Prompt for LLM provider/model + X credentials.\n */\nasync function setupKeys(): Promise<SetupResult> {\n console.log(chalk.bold(\"\\n━━━ LLM Provider Setup ━━━\\n\"));\n\n const provider = await select({\n message: \"Choose your LLM provider:\",\n choices: [\n { name: \"DeepSeek (recommended for low cost)\", value: \"deepseek\" },\n { name: \"Anthropic (Claude)\", value: \"anthropic\" },\n { name: \"OpenAI\", value: \"openai\" },\n ],\n }) as LLMProvider;\n\n const defaultModel = getDefaultModel(provider);\n const model = await input({\n message: `Model name for ${provider} (press enter for ${defaultModel}):`,\n });\n\n console.log(chalk.gray(\"Get your API key at: \") + chalk.cyan(`${providerKeyUrl(provider)}\\n`));\n const llmKey = await passwordPrompt({\n message: `${provider} API Key:`,\n mask: \"*\",\n validate: (val: string) => val.length > 0 ? true : \"API key is required\",\n });\n setLLMApiKey(provider, llmKey.trim());\n console.log(chalk.green(`✓ ${provider} API key saved\\n`));\n\n // X credentials\n console.log(chalk.bold(\"\\n━━━ Connect Your X Account ━━━\\n\"));\n console.log(chalk.gray(\"Your Spore needs OAuth 1.0a credentials for full X API access.\"));\n console.log(chalk.gray(\"This gives your agent the power to read timelines, post tweets, reply, like, and follow.\\n\"));\n console.log(chalk.cyan(\"How to get these credentials:\"));\n console.log(chalk.gray(\" 1. Go to: \") + chalk.cyan(\"https://developer.x.com/en/portal/dashboard\"));\n console.log(chalk.gray(\" 2. Create or select your app\"));\n console.log(chalk.gray(\" 3. Go to \\\"Keys and tokens\\\" tab\"));\n console.log(chalk.gray(\" 4. Copy all 4 credentials below\\n\"));\n console.log(chalk.yellow(\"Note: Some endpoints may require paid X API access depending on your tier.\\n\"));\n\n const apiKey = await passwordPrompt({\n message: \"X API Key (Consumer Key):\",\n mask: \"*\",\n validate: (val: string) => val.length > 0 ? true : \"API Key is required\",\n });\n\n const apiSecret = await passwordPrompt({\n message: \"X API Secret (Consumer Secret):\",\n mask: \"*\",\n validate: (val: string) => val.length > 0 ? true : \"API Secret is required\",\n });\n\n const accessToken = await passwordPrompt({\n message: \"X Access Token:\",\n mask: \"*\",\n validate: (val: string) => val.length > 0 ? true : \"Access Token is required\",\n });\n\n const accessTokenSecret = await passwordPrompt({\n message: \"X Access Token Secret:\",\n mask: \"*\",\n validate: (val: string) => val.length > 0 ? true : \"Access Token Secret is required\",\n });\n\n const bearerToken = await input({\n message: \"X Bearer Token (optional, press enter to skip):\",\n });\n\n saveCredentials({\n method: \"api\",\n apiKey,\n apiSecret,\n accessToken,\n accessTokenSecret,\n bearerToken: bearerToken.trim() || undefined,\n });\n console.log(chalk.green(\"✓ X API credentials saved (encrypted)\\n\"));\n\n return {\n llm: {\n provider,\n model: model.trim() || defaultModel,\n },\n };\n}\n\n/**\n * Show completion message and open chat\n */\nasync function showDoneAndOpenChat(): Promise<void> {\n console.log(chalk.green(\"\\n╔═══════════════════════════════════════╗\"));\n console.log(chalk.green.bold(\"║ Setup Complete! ║\"));\n console.log(chalk.green(\"╚═══════════════════════════════════════╝\\n\"));\n\n console.log(chalk.bold.cyan(\"━━━ Your Spore is Ready! ━━━\\n\"));\n console.log(chalk.gray(\"Opening chat interface...\\n\"));\n\n try {\n const { startWebChat } = await import(\"./web-chat/index.js\");\n await startWebChat();\n } catch (error) {\n console.log(chalk.yellow(`Could not start chat interface: ${(error as Error).message}\\n`));\n console.log(chalk.gray(\"You can start it manually with: spora chat\\n\"));\n }\n\n console.log(chalk.bold(\"Quick Start:\\n\"));\n console.log(chalk.cyan(\" spora chat\"));\n console.log(chalk.gray(\" → Talk to your Spore, tell it what to post, how to behave\\n\"));\n console.log(chalk.bold(\"Or start the autonomous agent:\\n\"));\n console.log(chalk.cyan(\" spora start\"));\n console.log(chalk.gray(\" → Your Spore will post and engage autonomously\\n\"));\n console.log(chalk.bold(\"Other commands:\\n\"));\n console.log(chalk.cyan(\" spora create \") + chalk.gray(\"# Create a personality\"));\n console.log(chalk.cyan(\" spora post <text> \") + chalk.gray(\"# Make your Spore post\"));\n console.log(chalk.cyan(\" spora agent-status \") + chalk.gray(\"# Check if agent is running\"));\n console.log(chalk.cyan(\" spora stop \") + chalk.gray(\"# Stop the agent\"));\n console.log(chalk.cyan(\" spora --help \") + chalk.gray(\"# See all commands\\n\"));\n}\n\nexport async function runInit(token?: string): Promise<void> {\n console.log(chalk.bold.cyan(\"\\n╔════════════════════════════════════════╗\"));\n console.log(chalk.bold.cyan(\"║ Welcome to Spora CLI Setup ║\"));\n console.log(chalk.bold.cyan(\"╚════════════════════════════════════════╝\\n\"));\n\n // If token provided via --token flag, this is a new user from the website → full setup\n if (token) {\n ensureDirectories();\n\n console.log(chalk.bold(\"\\n━━━ Connecting Your Spore ━━━\\n\"));\n try {\n await syncIdentityFromToken(token);\n } catch (error) {\n console.log(chalk.red(`\\n✗ ${(error as Error).message}\\n`));\n console.log(chalk.yellow(\"Please check your token and try again.\\n\"));\n process.exit(1);\n }\n\n const setup = await setupKeys();\n\n // Update X profile\n let profileUpdated = false;\n let updatedFields: string[] = [];\n let profileErrors: string[] = [];\n console.log(chalk.bold(\"\\n━━━ Updating Your X Profile ━━━\\n\"));\n console.log(chalk.gray(\"Setting up username, profile picture, banner, and bio to match your Spore...\\n\"));\n try {\n const identity = loadIdentity();\n const result = await updateXProfile(identity);\n profileUpdated = result.success;\n updatedFields = result.updated;\n profileErrors = result.errors;\n if (result.success) {\n console.log(chalk.green(\"✓ Profile updated successfully!\\n\"));\n if (result.updated.length > 0) {\n console.log(chalk.cyan(\"Updated:\"));\n for (const field of result.updated) {\n console.log(chalk.gray(` • ${field}`));\n }\n console.log();\n }\n }\n if (result.errors.length > 0) {\n console.log(chalk.yellow(\"\\nSome updates failed:\"));\n for (const err of result.errors) {\n console.log(chalk.gray(` • ${err}`));\n }\n console.log();\n }\n } catch (error) {\n console.log(chalk.yellow(`Could not update profile: ${(error as Error).message}\\n`));\n console.log(chalk.gray(\"You can manually update your X profile later.\\n\"));\n profileErrors = [(error as Error).message];\n }\n\n await notifyConnectProfileCompletion({\n token,\n profileUpdated,\n updatedFields,\n errors: profileErrors,\n });\n\n const config = createDefaultConfig({ xMethod: \"api\", xApiTier: \"basic\" });\n config.llm = setup.llm;\n config.runtime = { heartbeatIntervalMs: 300_000, actionsPerHeartbeat: 4, enabled: true };\n config.connection = {\n token,\n apiEndpoint: process.env.SPORA_API_URL || \"https://www.spora.social/api/v1\",\n configVersion: 0,\n };\n saveConfig(config);\n\n await showDoneAndOpenChat();\n return;\n }\n\n // No token provided — ask what they want to do\n const action = await select({\n message: \"What would you like to do?\",\n choices: [\n { name: \"Create a new Spore\", value: \"new\" },\n { name: \"Login to existing Spore\", value: \"login\" },\n ],\n });\n\n if (action === \"login\") {\n await loginFlow();\n return;\n }\n\n // \"new\" — full new Spore creation (no token, manual setup)\n ensureDirectories();\n\n const setup = await setupKeys();\n\n // Update X profile\n console.log(chalk.bold(\"\\n━━━ Updating Your X Profile ━━━\\n\"));\n console.log(chalk.gray(\"Setting up username, profile picture, banner, and bio to match your Spore...\\n\"));\n try {\n const identity = loadIdentity();\n const result = await updateXProfile(identity);\n if (result.success) {\n console.log(chalk.green(\"✓ Profile updated successfully!\\n\"));\n if (result.updated.length > 0) {\n console.log(chalk.cyan(\"Updated:\"));\n for (const field of result.updated) {\n console.log(chalk.gray(` • ${field}`));\n }\n console.log();\n }\n }\n if (result.errors.length > 0) {\n console.log(chalk.yellow(\"\\nSome updates failed:\"));\n for (const err of result.errors) {\n console.log(chalk.gray(` • ${err}`));\n }\n console.log();\n }\n } catch (error) {\n console.log(chalk.yellow(`Could not update profile: ${(error as Error).message}\\n`));\n console.log(chalk.gray(\"You can manually update your X profile later.\\n\"));\n }\n\n const config = createDefaultConfig({ xMethod: \"api\", xApiTier: \"basic\" });\n config.llm = setup.llm;\n config.runtime = { heartbeatIntervalMs: 300_000, actionsPerHeartbeat: 4, enabled: true };\n saveConfig(config);\n\n await showDoneAndOpenChat();\n}\n","/**\n * X Profile Updater\n * Updates X profile to match Spore identity (name, bio, profile pic, banner)\n */\n\nimport { TwitterApi } from \"twitter-api-v2\";\nimport sharp from \"sharp\";\nimport type { Identity } from \"../identity/schema.js\";\nimport { loadCredentials } from \"../utils/crypto.js\";\n\ninterface ProfileUpdateResult {\n success: boolean;\n updated: string[];\n errors: string[];\n}\n\nfunction normalizeHandle(input: string): string {\n return input.replace(/^@/, \"\").trim();\n}\n\nfunction isValidHandle(handle: string): boolean {\n // X handle constraints: 4-15 chars, letters/numbers/underscore.\n return /^[A-Za-z0-9_]{4,15}$/.test(handle);\n}\n\n/**\n * Update X profile to match Spore identity\n * Requires OAuth 1.0a credentials\n */\nexport async function updateXProfile(identity: Identity): Promise<ProfileUpdateResult> {\n const result: ProfileUpdateResult = {\n success: false,\n updated: [],\n errors: [],\n };\n\n try {\n const creds = loadCredentials();\n if (creds.method !== \"api\") {\n result.errors.push(\"API credentials required\");\n return result;\n }\n\n // Create Twitter API client with OAuth 1.0a credentials\n const client = new TwitterApi({\n appKey: creds.apiKey!,\n appSecret: creds.apiSecret!,\n accessToken: creds.accessToken!,\n accessSecret: creds.accessTokenSecret!,\n });\n\n // Update profile name and bio\n try {\n console.log(`Updating name to: ${identity.name}`);\n console.log(`Updating bio to: ${identity.bio.substring(0, 60)}...`);\n await client.v1.updateAccountProfile({\n name: identity.name,\n description: identity.bio,\n });\n result.updated.push(\"name\", \"bio\");\n console.log(\"Name and bio updated successfully\");\n } catch (error) {\n console.error(\"Name/bio update error:\", error);\n result.errors.push(`Failed to update name/bio: ${(error as Error).message}`);\n }\n\n // Best-effort username update.\n // X often restricts handle changes by API permission/account tier, so this may fail.\n try {\n const desiredHandle = normalizeHandle(identity.handle);\n if (!desiredHandle) {\n throw new Error(\"Identity handle is empty\");\n }\n if (!isValidHandle(desiredHandle)) {\n throw new Error(\n `Invalid handle \"${desiredHandle}\". X handles must be 4-15 chars and only letters, numbers, or underscores.`\n );\n }\n\n const before = await client.v1.verifyCredentials();\n const currentHandle = normalizeHandle(before.screen_name || \"\");\n\n if (!currentHandle) {\n throw new Error(\"Could not read current X handle from credentials\");\n }\n\n if (currentHandle.toLowerCase() === desiredHandle.toLowerCase()) {\n console.log(`Username already set: @${desiredHandle}`);\n result.updated.push(\"username\");\n } else {\n console.log(`Updating username from @${currentHandle} to @${desiredHandle}...`);\n\n // twitter-api-v2 typings do not expose screen_name here, but v1 endpoint may accept it.\n await client.v1.post(\"account/update_profile.json\", {\n screen_name: desiredHandle,\n } as unknown as Record<string, string>);\n\n const after = await client.v1.verifyCredentials();\n const updatedHandle = normalizeHandle(after.screen_name || \"\");\n\n if (updatedHandle.toLowerCase() === desiredHandle.toLowerCase()) {\n console.log(`Username updated successfully to @${desiredHandle}`);\n result.updated.push(\"username\");\n } else {\n throw new Error(\n `X did not apply handle change (current @${updatedHandle || currentHandle}).`\n );\n }\n }\n } catch (error) {\n const message = (error as Error).message;\n console.error(\"Username update error:\", error);\n result.errors.push(\n `Failed to update username: ${message}. X may block handle changes via API; update it manually in X Settings -> Account -> Username.`\n );\n }\n\n // Update profile image if available\n if (identity.profileImage) {\n try {\n console.log(`Downloading profile image from: ${identity.profileImage.substring(0, 60)}...`);\n let imageBuffer = await downloadImage(identity.profileImage);\n console.log(`Downloaded ${(imageBuffer.length / 1024 / 1024).toFixed(2)}MB`);\n\n // Check image dimensions - Twitter requires min 400x400\n const metadata = await sharp(imageBuffer).metadata();\n console.log(`Image dimensions: ${metadata.width}x${metadata.height}`);\n\n if (!metadata.width || !metadata.height || metadata.width < 400 || metadata.height < 400) {\n throw new Error(`Image too small (${metadata.width}x${metadata.height}). Twitter requires minimum 400x400 pixels.`);\n }\n\n // Compress if needed (Twitter profile image limit: 2MB)\n const MAX_PROFILE_SIZE = 2 * 1024 * 1024; // 2MB\n imageBuffer = await compressImageIfNeeded(imageBuffer, MAX_PROFILE_SIZE, \"Profile\");\n\n console.log(`Uploading profile image to X...`);\n await client.v1.updateAccountProfileImage(imageBuffer);\n result.updated.push(\"profile_image\");\n console.log(\"Profile image updated successfully\");\n } catch (error) {\n console.error(\"Profile image error:\", error);\n result.errors.push(`Failed to update profile image: ${(error as Error).message}`);\n }\n } else {\n console.log(\"No profile image URL in identity\");\n }\n\n // Update banner image if available\n if (identity.bannerImage) {\n try {\n console.log(`Downloading banner image from: ${identity.bannerImage.substring(0, 60)}...`);\n let imageBuffer = await downloadImage(identity.bannerImage);\n console.log(`Downloaded ${(imageBuffer.length / 1024 / 1024).toFixed(2)}MB`);\n\n // Compress if needed (Twitter banner limit: 5MB)\n const MAX_BANNER_SIZE = 5 * 1024 * 1024; // 5MB\n imageBuffer = await compressImageIfNeeded(imageBuffer, MAX_BANNER_SIZE, \"Banner\");\n\n console.log(`Uploading banner image to X...`);\n await client.v1.updateAccountProfileBanner(imageBuffer);\n result.updated.push(\"banner_image\");\n console.log(\"Banner image updated successfully\");\n } catch (error) {\n console.error(\"Banner image error:\", error);\n result.errors.push(`Failed to update banner: ${(error as Error).message}`);\n }\n } else {\n console.log(\"No banner image URL in identity\");\n }\n\n result.success = result.updated.length > 0;\n return result;\n } catch (error) {\n result.errors.push((error as Error).message);\n return result;\n }\n}\n\n/**\n * Download image from URL and return as Buffer\n */\nasync function downloadImage(url: string): Promise<Buffer> {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to download image: ${response.statusText}`);\n }\n const arrayBuffer = await response.arrayBuffer();\n return Buffer.from(arrayBuffer);\n}\n\n/**\n * Compress image if it exceeds size limit by resizing\n * @param buffer Original image buffer\n * @param maxSizeBytes Maximum allowed size in bytes\n * @param type \"profile\" or \"banner\" for logging\n */\nasync function compressImageIfNeeded(\n buffer: Buffer,\n maxSizeBytes: number,\n type: string\n): Promise<Buffer> {\n if (buffer.length <= maxSizeBytes) {\n return buffer;\n }\n\n console.log(\n `${type} image is ${(buffer.length / 1024 / 1024).toFixed(2)}MB, resizing to fit ${(maxSizeBytes / 1024 / 1024).toFixed(0)}MB limit...`\n );\n\n // Calculate scale factor to fit within size limit\n const scaleFactor = Math.sqrt(maxSizeBytes / buffer.length) * 0.85; // 85% of target for safety\n\n // Get current dimensions and calculate new size\n const metadata = await sharp(buffer).metadata();\n const newWidth = Math.floor((metadata.width || 1000) * scaleFactor);\n\n // Resize and convert to JPEG with good quality\n const compressed = await sharp(buffer)\n .resize(newWidth, null, { fit: \"inside\", withoutEnlargement: true })\n .jpeg({ quality: 90, progressive: true })\n .toBuffer();\n\n console.log(\n `Resized ${type} image from ${(buffer.length / 1024 / 1024).toFixed(2)}MB to ${(compressed.length / 1024 / 1024).toFixed(2)}MB`\n );\n\n return compressed;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,QAAQ,YAAY,sBAAsB;AAC1D,OAAO,WAAW;;;ACIlB,SAAS,kBAAkB;AAC3B,OAAO,WAAW;AAUlB,SAAS,gBAAgBA,QAAuB;AAC9C,SAAOA,OAAM,QAAQ,MAAM,EAAE,EAAE,KAAK;AACtC;AAEA,SAAS,cAAc,QAAyB;AAE9C,SAAO,uBAAuB,KAAK,MAAM;AAC3C;AAMA,eAAsB,eAAe,UAAkD;AACrF,QAAM,SAA8B;AAAA,IAClC,SAAS;AAAA,IACT,SAAS,CAAC;AAAA,IACV,QAAQ,CAAC;AAAA,EACX;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Content":["/**\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, existsSync } 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\" | \"summary\";\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 // Static: logo asset for chat header\n if (url.pathname === \"/logo2.png\" && req.method === \"GET\") {\n const logoPaths = [\n join(__dirname, \"web-chat\", \"logo2.png\"),\n join(__dirname, \"..\", \"web-chat\", \"logo2.png\"),\n join(process.cwd(), \"dist\", \"web-chat\", \"logo2.png\"),\n join(process.cwd(), \"logo2.png\"),\n ];\n const logoPath = logoPaths.find((p) => existsSync(p));\n if (!logoPath) {\n res.writeHead(404);\n res.end(\"Not found\");\n return;\n }\n res.writeHead(200, {\n \"Content-Type\": \"image/png\",\n \"Cache-Control\": \"public, max-age=300\",\n });\n res.end(readFileSync(logoPath));\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 set 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\", `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\", \"scanning timeline...\");\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(\"summary\", narrative.summary);\n\n if (cycle.timeline.length > 0 || cycle.mentions.length > 0) {\n server.pushAgentEvent(\"narration\", `found ${cycle.timeline.length} timeline, ${cycle.mentions.length} mentions`);\n }\n\n if (cycle.actions.length === 0) {\n server.pushAgentEvent(\"narration\", \"no actions, sleeping\");\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 ? ` ${String(result.detail).slice(0, 40)}` : \"\"}`);\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`);\n }\n console.log(chalk.red(` [Agent] ✗ ${result.action}: ${result.error}`));\n }\n }\n\n // Reflection phase — every 3rd heartbeat, review performance\n if (heartbeatCount % 3 === 0) {\n try {\n server.pushAgentEvent(\"narration\", \"reflecting...\");\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 something new\");\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 updated\");\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,cAAc,kBAAkB;AACzC,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,EAC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