Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(agents): add suspension detection, monitor action, and published content tracking
Adam Eivyfc9f5371b3f4
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.mdindex 5209d5ed2c..2b16461484 100644--- a/.changelog/v0.12.x.md+++ b/.changelog/v0.12.x.md@@ -169,6 +169,17 @@ This release adds branch management and automated release workflow capabilities- `client/src/services/api.js` — Added `getCosLearningSummary()` API function- `client/src/pages/ChiefOfStaff.jsx` — Added learning summary state, fetches summary with page data, renders clickable Learning stat card in both desktop (5-column grid) and mobile layouts+### Agents — Moltbook Account Suspension Detection & Early Termination+- **Suspension detection**: API client now attaches HTTP status codes and a `suspended` flag to errors, with `isAccountSuspended()` helper for easy detection+- **Early loop termination**: Monitor (check-posts), engage, and scheduled executor loops all detect 403 "account suspended" responses and immediately halt — preventing wasted AI generation calls and failing API requests+- **Automatic account status update**: When suspension is detected, the account is automatically marked as `suspended` in the database, preventing further scheduled actions from running+- **Activity logging**: Suspended monitors log as `failed` with the suspension reason instead of `completed`++**Server changes**:+- `server/integrations/moltbook/api.js` — Enriched error objects with `.status` and `.suspended` properties, added `isAccountSuspended()` helper+- `server/routes/agentTools.js` — Check-posts endpoint detects suspension mid-loop, halts immediately, marks account suspended+- `server/services/agentActionExecutor.js` — Monitor and engage actions detect suspension and break early+### CoS — Quick Summary Widget- **At-a-glance dashboard**: New compact status bar on the Tasks tab showing today's work, streak status, pending items, and next scheduled job- **Today's progress**: Displays tasks completed/failed, active running count, and total time worked todaydiff --git a/client/src/components/agents/constants.js b/client/src/components/agents/constants.jsindex 133b32b385..7c0bd7374b 100644--- a/client/src/components/agents/constants.js+++ b/client/src/components/agents/constants.js@@ -23,7 +23,8 @@ export const ACTION_TYPES = [{ value: 'comment', label: 'Comment', description: 'Reply to posts', icon: '💬' },{ value: 'vote', label: 'Vote', description: 'Upvote or downvote content', icon: '👍' },{ value: 'heartbeat', label: 'Heartbeat', description: 'Browse and engage naturally', icon: '💓' },- { value: 'engage', label: 'Engage', description: 'AI-powered browsing, commenting, and voting', icon: '🤝' }+ { value: 'engage', label: 'Engage', description: 'AI-powered browsing, commenting, and voting', icon: '🤝' },+ { value: 'monitor', label: 'Monitor', description: 'Check post engagement and respond', icon: '👀' }];export const SCHEDULE_TYPES = [diff --git a/client/src/components/agents/tabs/ToolsTab.jsx b/client/src/components/agents/tabs/ToolsTab.jsxindex 53a87e683b..bc82c98332 100644--- a/client/src/components/agents/tabs/ToolsTab.jsx+++ b/client/src/components/agents/tabs/ToolsTab.jsx@@ -33,6 +33,10 @@ export default function ToolsTab({ agentId }) {const [engaging, setEngaging] = useState(false);const [engageResult, setEngageResult] = useState(null);+ // Check Posts (Monitor) state+ const [checking, setChecking] = useState(false);+ const [checkResult, setCheckResult] = useState(null);+// Drafts stateconst [drafts, setDrafts] = useState([]);const [activeDraftId, setActiveDraftId] = useState(null);@@ -200,6 +204,19 @@ export default function ToolsTab({ agentId }) {api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});};+ // Check Posts (Monitor)+ const handleCheckPosts = async () => {+ if (!agentId || !selectedAccountId) return;+ setChecking(true);+ setCheckResult(null);+ const result = await api.checkAgentPosts(agentId, selectedAccountId, 7, 2, 10).catch(() => null);+ setChecking(false);+ if (!result) return;+ setCheckResult(result);+ toast.success(`Checked ${result.postsChecked} posts: ${result.engagement?.upvoted?.length || 0} upvotes, ${result.engagement?.replied?.length || 0} replies`);+ api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});+ };+const handleLoadDraft = (draft) => {setActiveDraftId(draft.id);if (draft.type === 'post') {@@ -412,6 +429,68 @@ export default function ToolsTab({ agentId }) {</div>)}</div>++ {/* Check Posts (Monitor) */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between mb-3">+ <div>+ <h3 className="font-semibold text-white">Check Posts</h3>+ <p className="text-xs text-gray-500">Check engagement on published posts, upvote comments, and reply</p>+ </div>+ <button+ onClick={handleCheckPosts}+ disabled={checking}+ className="px-4 py-2 bg-purple-600 text-white rounded hover:bg-purple-500 disabled:opacity-50"+ >+ {checking ? 'Checking...' : 'Check Posts'}+ </button>+ </div>++ {checking && (+ <div className="flex items-center gap-2 text-sm text-gray-400">+ <span className="animate-spin">⏳</span>+ Scanning published posts for new engagement...+ </div>+ )}++ {checkResult && (+ <div className="text-sm space-y-2">+ <div className="flex gap-4 text-gray-400">+ <span>{checkResult.postsChecked} posts checked</span>+ <span>{checkResult.engagement?.totalComments || 0} total comments</span>+ <span className="text-port-accent">{checkResult.engagement?.newComments || 0} by others</span>+ </div>++ {checkResult.engagement?.upvoted?.length > 0 && (+ <div>+ <p className="text-port-accent font-medium">Upvoted ({checkResult.engagement.upvoted.length})</p>+ {checkResult.engagement.upvoted.map((u, i) => (+ <div key={i} className="text-xs pl-2 mt-1">+ <p className="text-gray-400">{u.postTitle}</p>+ <p className="text-gray-500 italic">{u.snippet}</p>+ </div>+ ))}+ </div>+ )}++ {checkResult.engagement?.replied?.length > 0 && (+ <div>+ <p className="text-port-success font-medium">Replied ({checkResult.engagement.replied.length})</p>+ {checkResult.engagement.replied.map((r, i) => (+ <div key={i} className="text-xs pl-2 mt-1">+ <p className="text-gray-400">{r.postTitle} - re: {r.snippet}</p>+ <p className="text-gray-500 italic">{r.reply?.substring(0, 120)}...</p>+ </div>+ ))}+ </div>+ )}++ {(checkResult.engagement?.upvoted?.length === 0 && checkResult.engagement?.replied?.length === 0) && (+ <p className="text-gray-500 text-xs">No new engagement actions taken</p>+ )}+ </div>+ )}+ </div></div>{/* Right Column: Post Composer + Comment Composer */}diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex dc9c1ff5c9..3b20b41c4a 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -12,7 +12,7 @@ import express from 'express';import { spawn } from 'child_process';import { join, dirname, basename } from 'path';import { fileURLToPath } from 'url';-import { writeFile, mkdir, readFile } from 'fs/promises';+import { writeFile, mkdir, readFile, rename } from 'fs/promises';import { existsSync } from 'fs';import http from 'http';import { Server as SocketServer } from 'socket.io';@@ -222,52 +222,40 @@ const io = new SocketServer(server, {cors: { origin: '*' }});+const DEFAULT_STATE = { agents: {}, stats: { spawned: 0, completed: 0, failed: 0 } };+let stateLock = Promise.resolve();+/**- * Validate JSON string before parsing+ * Write state atomically using temp file + rename to prevent partial-write corruption*/-function isValidJSON(str) {- if (!str || !str.trim()) return false;- const trimmed = str.trim();- // Check for basic JSON structure- if (!(trimmed.startsWith('{') && trimmed.endsWith('}'))) return false;- // Check for common corruption patterns- if (trimmed.endsWith('}}') || trimmed.includes('}{')) return false;- return true;+async function atomicWrite(filePath, data) {+ const tmpPath = `${filePath}.tmp.${process.pid}`;+ await writeFile(tmpPath, data);+ await rename(tmpPath, filePath);}/*** Load runner state from disk*/async function loadState() {- const defaultState = { agents: {}, stats: { spawned: 0, completed: 0, failed: 0 } };-- if (!existsSync(STATE_FILE)) {- return defaultState;- }+ if (!existsSync(STATE_FILE)) return { ...DEFAULT_STATE, agents: {}, stats: { ...DEFAULT_STATE.stats } };const content = await readFile(STATE_FILE, 'utf-8');-- if (!isValidJSON(content)) {- console.log('⚠️ Corrupted or empty state file, returning default state');- // Backup the corrupted file for debugging- const backupPath = `${STATE_FILE}.corrupted.${Date.now()}`;- await writeFile(backupPath, content).catch(() => {});- console.log(`📝 Backed up corrupted state to ${backupPath}`);- return defaultState;- }+ if (!content || !content.trim()) return { ...DEFAULT_STATE, agents: {}, stats: { ...DEFAULT_STATE.stats } };return JSON.parse(content);}/**- * Save runner state to disk+ * Save runner state to disk (serialized with atomic writes to prevent corruption)*/-async function saveState(state) {- const dir = dirname(STATE_FILE);- if (!existsSync(dir)) {- await mkdir(dir, { recursive: true });- }- await writeFile(STATE_FILE, JSON.stringify(state, null, 2));+function saveState(state) {+ stateLock = stateLock.then(async () => {+ const dir = dirname(STATE_FILE);+ if (!existsSync(dir)) await mkdir(dir, { recursive: true });+ await atomicWrite(STATE_FILE, JSON.stringify(state, null, 2));+ });+ return stateLock;}/**diff --git a/server/integrations/moltbook/api.js b/server/integrations/moltbook/api.jsindex 66d9a6e3ed..1b2923dbd5 100644--- a/server/integrations/moltbook/api.js+++ b/server/integrations/moltbook/api.js@@ -32,7 +32,10 @@ async function request(endpoint, options = {}) {const error = await response.json().catch(() => ({}));const message = error.error || error.message || `HTTP ${response.status}`;console.error(`❌ Moltbook API error: ${response.status} ${message}`);- throw new Error(message);+ const err = new Error(message);+ err.status = response.status;+ err.suspended = response.status === 403 && message.toLowerCase().includes('suspended');+ throw err;}if (response.status === 204) {@@ -146,6 +149,25 @@ export async function getFeed(apiKey, sort = 'hot', limit = 25) {return authRequest(apiKey, `/feed?sort=${sort}&limit=${limit}`);}+/**+ * Get posts by a specific author+ * @param {string} apiKey - The agent's API key+ * @param {string} username - The author's username+ */+export async function getPostsByAuthor(apiKey, username) {+ const result = await authRequest(apiKey, `/posts?author=${encodeURIComponent(username)}`);+ return result.posts || result || [];+}++/**+ * Delete a post+ * @param {string} apiKey - The agent's API key+ * @param {string} postId - The post ID to delete+ */+export async function deletePost(apiKey, postId) {+ return authRequest(apiKey, `/posts/${postId}`, { method: 'DELETE' });+}+/*** Get a specific post* @param {string} apiKey - The agent's API key@@ -275,9 +297,8 @@ export async function upvoteComment(apiKey, commentId) {throw new Error(`Rate limited: ${rateCheck.reason}`);}- const result = await authRequest(apiKey, `/comments/${commentId}/vote`, {- method: 'POST',- body: JSON.stringify({ direction: 'up' })+ const result = await authRequest(apiKey, `/comments/${commentId}/upvote`, {+ method: 'POST'});recordAction(apiKey, 'vote');@@ -423,3 +444,12 @@ export async function getSubmolts(apiKey) {export async function getSubmolt(apiKey, submoltName) {return authRequest(apiKey, `/submolts/${submoltName}`);}++/**+ * Check if an error indicates account suspension+ * @param {Error} error - The error to check+ * @returns {boolean}+ */+export function isAccountSuspended(error) {+ return error?.suspended || (error?.status === 403 && error?.message?.toLowerCase().includes('suspended'));+}diff --git a/server/integrations/moltbook/index.js b/server/integrations/moltbook/index.jsindex a250dac779..35f9fcd60c 100644--- a/server/integrations/moltbook/index.js+++ b/server/integrations/moltbook/index.js@@ -7,7 +7,7 @@* @module integrations/moltbook*/-// Re-export all API functions+// Re-export all API functions (including isAccountSuspended)export * from './api.js';// Re-export rate limit utilities@@ -40,6 +40,8 @@ export class MoltbookClient {createPost(submolt, title, content) { return api.createPost(this.apiKey, submolt, title, content); }getFeed(sort, limit) { return api.getFeed(this.apiKey, sort, limit); }getPost(postId) { return api.getPost(this.apiKey, postId); }+ getPostsByAuthor(username) { return api.getPostsByAuthor(this.apiKey, username); }+ deletePost(postId) { return api.deletePost(this.apiKey, postId); }// CommentscreateComment(postId, content) { return api.createComment(this.apiKey, postId, content); }diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 457540514e..8f1e734912 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -76,7 +76,7 @@ export const accountRegistrationSchema = z.object({// AUTOMATION SCHEDULE SCHEMAS// =============================================================================-export const scheduleActionTypeSchema = z.enum(['post', 'comment', 'vote', 'heartbeat', 'engage']);+export const scheduleActionTypeSchema = z.enum(['post', 'comment', 'vote', 'heartbeat', 'engage', 'monitor']);export const scheduleActionSchema = z.object({type: scheduleActionTypeSchema,@@ -244,6 +244,14 @@ export const engageSchema = z.object({maxVotes: z.number().int().min(0).max(10).optional().default(3)});+export const checkPostsSchema = z.object({+ agentId: z.string().min(1),+ accountId: z.string().min(1),+ days: z.number().int().min(1).max(30).optional().default(7),+ maxReplies: z.number().int().min(0).max(5).optional().default(2),+ maxUpvotes: z.number().int().min(0).max(20).optional().default(10)+});+export const createDraftSchema = z.object({agentId: z.string().min(1),type: z.enum(['post', 'comment']),diff --git a/server/routes/agentTools.js b/server/routes/agentTools.jsindex b61512da13..56b2b69a8a 100644--- a/server/routes/agentTools.js+++ b/server/routes/agentTools.js@@ -14,6 +14,7 @@ import {publishPostSchema,publishCommentSchema,engageSchema,+ checkPostsSchema,createDraftSchema,updateDraftSchema} from '../lib/validation.js';@@ -24,6 +25,7 @@ import * as agentDrafts from '../services/agentDrafts.js';import { generatePost, generateComment, generateReply } from '../services/agentContentGenerator.js';import { findRelevantPosts } from '../services/agentFeedFilter.js';import { MoltbookClient } from '../integrations/moltbook/index.js';+import { collectPublishedPosts } from '../services/agentPublished.js';const router = Router();@@ -100,7 +102,8 @@ router.post('/publish-post', asyncHandler(async (req, res) => {console.log(`🛠️ POST /api/agents/tools/publish-post agent=${data.agentId} submolt=${data.submolt}`);const { client, account } = await getClientAndAgent(data.accountId, data.agentId);- const post = await client.createPost(data.submolt, data.title, data.content);+ const result = await client.createPost(data.submolt, data.title, data.content);+ const post = result?.post || result;const postId = post?.id || post?._id || post?.post_id;await platformAccounts.recordActivity(data.accountId);@@ -345,57 +348,7 @@ router.get('/published', asyncHandler(async (req, res) => {const { client } = await getClientAndAgent(accountId, agentId);- // Collect activities across multiple days- const postMap = new Map();- const commentMap = new Map();-- for (let i = 0; i < numDays; i++) {- const date = new Date();- date.setDate(date.getDate() - i);-- const [postActivities, commentActivities, engageActivities] = await Promise.all([- agentActivity.getActivities(agentId, { date, action: 'post' }),- agentActivity.getActivities(agentId, { date, action: 'comment' }),- agentActivity.getActivities(agentId, { date, action: 'engage' })- ]);-- // Extract posts- for (const activity of postActivities) {- if (activity.status !== 'completed') continue;- const postId = activity.result?.postId || activity.id;- const title = activity.result?.title || activity.params?.title;- const submolt = activity.result?.submolt || activity.params?.submolt;- if (!postMap.has(postId)) {- postMap.set(postId, { postId: activity.result?.postId || null, title, submolt, publishedAt: activity.timestamp });- }- }-- // Extract comments- for (const activity of commentActivities) {- if (activity.status !== 'completed') continue;- const commentId = activity.result?.commentId || activity.id;- const postId = activity.result?.postId || activity.params?.postId;- const isReply = activity.result?.isReply;- if (!commentMap.has(commentId)) {- commentMap.set(commentId, { commentId: activity.result?.commentId || null, postId, isReply: !!isReply, publishedAt: activity.timestamp });- }- }-- // Extract comments from engage results- for (const activity of engageActivities) {- if (activity.status !== 'completed' || !activity.result?.comments) continue;- for (const c of activity.result.comments) {- if (!c.commentId || commentMap.has(c.commentId)) continue;- commentMap.set(c.commentId, {- commentId: c.commentId,- postId: c.postId,- postTitle: c.postTitle,- isReply: false,- publishedAt: activity.timestamp- });- }- }- }+ const { postMap, commentMap } = await collectPublishedPosts(agentId, numDays);// Fetch live engagement for posts (only for those with postId)const posts = Array.from(postMap.values());@@ -445,6 +398,134 @@ router.get('/published', asyncHandler(async (req, res) => {res.json({ posts: enrichedPosts, comments: enrichedComments });}));+// POST /check-posts - Check engagement on published posts and respond+router.post('/check-posts', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(checkPostsSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`👀 POST /api/agents/tools/check-posts agent=${data.agentId} days=${data.days}`);++ const { client, agent, account } = await getClientAndAgent(data.accountId, data.agentId);+ const { checkRateLimit, isAccountSuspended } = await import('../integrations/moltbook/index.js');++ const agentUsername = account.credentials.username;++ // Fetch posts directly from Moltbook API — more reliable than activity logs+ const allPosts = await client.getPostsByAuthor(agentUsername);++ // Filter to posts within the requested day range+ const cutoff = new Date();+ cutoff.setDate(cutoff.getDate() - data.days);+ const posts = allPosts.filter(p => new Date(p.created_at) >= cutoff);++ console.log(`👀 Found ${allPosts.length} total posts by ${agentUsername}, ${posts.length} within ${data.days} days`);+ const upvoted = [];+ const replied = [];+ const skipped = [];+ let totalComments = 0;+ let newComments = 0;+ let suspended = false;+ const delayMs = (ms) => new Promise(resolve => setTimeout(resolve, ms));++ for (const post of posts) {+ if (suspended) break;++ const postId = post.id;+ const commentsResponse = await client.getComments(postId).catch(e => {+ if (isAccountSuspended(e)) suspended = true;+ return { comments: [] };+ });+ if (suspended) break;++ const allComments = commentsResponse.comments || commentsResponse || [];+ totalComments += allComments.length;++ // Filter to comments NOT by the agent+ const otherComments = allComments.filter(c => {+ const authorName = typeof c.author === 'object' ? c.author?.name : c.author;+ return authorName !== agentUsername;+ });+ newComments += otherComments.length;++ for (const comment of otherComments) {+ if (suspended) break;++ // Upvote positive comments+ if (upvoted.length < data.maxUpvotes) {+ const rateCheck = checkRateLimit(client.apiKey, 'vote');+ if (rateCheck.allowed) {+ const voted = await client.upvoteComment(comment.id).catch(e => {+ if (isAccountSuspended(e)) suspended = true;+ else console.log(`👀 Upvote failed for comment ${comment.id}: ${e.message}`);+ return null;+ });+ if (suspended) break;+ if (voted) {+ upvoted.push({+ commentId: comment.id,+ postId,+ postTitle: post.title,+ snippet: (comment.content || '').substring(0, 80)+ });+ }+ await delayMs(1500);+ }+ }++ // Generate replies for top comments+ if (!suspended && replied.length < data.maxReplies) {+ const rateCheck = checkRateLimit(client.apiKey, 'comment');+ if (rateCheck.allowed) {+ const generated = await generateReply(agent, post, comment);+ const replyResult = await client.replyToComment(postId, comment.id, generated.content).catch(e => {+ if (isAccountSuspended(e)) suspended = true;+ else console.log(`👀 Reply failed on post ${postId}: ${e.message}`);+ return null;+ });+ if (suspended) break;+ if (replyResult) {+ replied.push({+ commentId: comment.id,+ replyId: replyResult?.id || replyResult?._id || replyResult?.comment_id,+ postId,+ postTitle: post.title,+ snippet: (comment.content || '').substring(0, 80),+ reply: generated.content+ });+ }+ await delayMs(1500);+ }+ }++ if (upvoted.length >= data.maxUpvotes && replied.length >= data.maxReplies) break;+ }+ }++ // If account was suspended, mark it and halt early+ if (suspended) {+ console.log(`🚫 Account ${agentUsername} suspended — halting monitor, marking account`);+ await platformAccounts.updateAccountStatus(data.accountId, 'suspended');+ }++ await platformAccounts.recordActivity(data.accountId);+ await agentActivity.logActivity({+ agentId: data.agentId,+ accountId: data.accountId,+ action: 'monitor',+ params: { days: data.days, maxReplies: data.maxReplies, maxUpvotes: data.maxUpvotes },+ status: suspended ? 'failed' : 'completed',+ error: suspended ? 'Account suspended by platform' : undefined,+ result: { type: 'monitor', postsChecked: posts.length, totalComments, newComments, upvoted, replied },+ timestamp: new Date().toISOString()+ });++ console.log(`👀 Monitor ${suspended ? 'aborted (suspended)' : 'complete'} for "${agent.name}": ${posts.length} posts, ${newComments} new comments, ${upvoted.length} upvotes, ${replied.length} replies`);++ res.json({ postsChecked: posts.length, suspended, engagement: { totalComments, newComments, upvoted, replied, skipped } });+}));+// =============================================================================// DRAFTS// =============================================================================diff --git a/server/routes/platformAccounts.js b/server/routes/platformAccounts.jsindex 5f7966abd2..d7a23f61bb 100644--- a/server/routes/platformAccounts.js+++ b/server/routes/platformAccounts.js@@ -149,27 +149,27 @@ router.post('/:id/test', asyncHandler(async (req, res) => {}if (account.platform === 'moltbook') {- // Test with real Moltbook API+ // Test with real Moltbook API - fetch profile (read-only, no side effects)const client = new moltbook.MoltbookClient(account.credentials.apiKey);- const status = await client.getStatus();+ const profileResult = await client.getProfile();+ const agent = profileResult.agent || profileResult;+ const platformStatus = agent.is_claimed ? 'active' : 'pending_claim';const testResult = {- success: status.status === 'active' || status.status === 'claimed',- message: status.status === 'active' || status.status === 'claimed'- ? 'Connection successful'- : status.status === 'pending_claim'- ? 'Account pending claim - visit claim URL to activate'- : `Account status: ${status.status}`,+ success: !!agent.id,+ message: agent.id+ ? `Connection successful — ${agent.name} (${agent.stats?.posts || 0} posts, ${agent.karma || 0} karma)`+ : 'Could not retrieve profile',platform: account.platform,username: account.credentials.username,- platformStatus: status.status+ platformStatus};// Update account status if it changed- if (status.status === 'active' || status.status === 'claimed') {+ if (agent.id && agent.is_claimed) {await platformAccounts.updateAccountStatus(id, 'active');- } else if (status.status === 'suspended') {- await platformAccounts.updateAccountStatus(id, 'suspended');+ } else if (!agent.is_claimed) {+ await platformAccounts.updateAccountStatus(id, 'pending');}res.json(testResult);diff --git a/server/scripts/moltbook-claim.mjs b/server/scripts/moltbook-claim.mjsnew file mode 100644index 0000000000..e034530a61--- /dev/null+++ b/server/scripts/moltbook-claim.mjs@@ -0,0 +1,61 @@+#!/usr/bin/env node+/**+ * Moltbook Claim Bot+ *+ * Retries the claim verification on Moltbook until X.com rate limits clear.+ * Calls the verify-tweet API directly — no browser dependencies needed.+ *+ * Usage:+ * node server/scripts/moltbook-claim.mjs <claim_token> <tweet_url> [backoff_seconds]+ *+ * Example:+ * node server/scripts/moltbook-claim.mjs \+ * "moltbook_claim_abc123" \+ * "https://x.com/antic/status/1234567890" \+ * 60+ */++const [token, tweetUrl, backoffArg] = process.argv.slice(2);+const BACKOFF_MS = (parseInt(backoffArg, 10) || 60) * 1000;+const MAX_ATTEMPTS = 120;+const API_URL = 'https://www.moltbook.com/api/v1/agents/verify-tweet';++if (!token || !tweetUrl) {+ console.error('Usage: node moltbook-claim.mjs <claim_token> <tweet_url> [backoff_seconds]');+ process.exit(1);+}++const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));++console.log(`🦞 Moltbook Claim Bot`);+console.log(`🔑 Token: ${token}`);+console.log(`🐦 Tweet: ${tweetUrl}`);+console.log(`⏱️ Backoff: ${BACKOFF_MS / 1000}s between attempts`);+console.log(`🔁 Max attempts: ${MAX_ATTEMPTS}\n`);++let attempt = 0;+while (attempt < MAX_ATTEMPTS) {+ attempt++;+ const timestamp = new Date().toLocaleTimeString();++ const response = await fetch(API_URL, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token, tweet_url: tweetUrl })+ });++ const data = await response.json();++ if (data.success) {+ console.log(`✅ [${timestamp}] Attempt ${attempt} — CLAIMED! 🦞`);+ console.log(JSON.stringify(data, null, 2));+ process.exit(0);+ }++ const detail = data.details ? ` (${data.details})` : '';+ console.log(`❌ [${timestamp}] Attempt ${attempt} — ${data.error}${detail} — retrying in ${BACKOFF_MS / 1000}s`);+ await sleep(BACKOFF_MS);+}++console.log(`\n💀 Failed after ${MAX_ATTEMPTS} attempts.`);+process.exit(1);diff --git a/server/services/agentActionExecutor.js b/server/services/agentActionExecutor.jsindex 374c9f82d5..008927efd6 100644--- a/server/services/agentActionExecutor.js+++ b/server/services/agentActionExecutor.js@@ -10,7 +10,7 @@ import { scheduleEvents } from './automationScheduler.js';import * as agentActivity from './agentActivity.js';import * as platformAccounts from './platformAccounts.js';import * as agentPersonalities from './agentPersonalities.js';-import { MoltbookClient, checkRateLimit } from '../integrations/moltbook/index.js';+import { MoltbookClient, checkRateLimit, isAccountSuspended } from '../integrations/moltbook/index.js';import { generatePost, generateComment, generateReply } from './agentContentGenerator.js';import { findRelevantPosts, findReplyOpportunities } from './agentFeedFilter.js';@@ -39,6 +39,9 @@ async function executeAction(schedule, account, agent) {case 'engage':return executeEngage(client, agent, action.params);+ case 'monitor':+ return executeMonitor(client, agent, schedule, action.params);+default:throw new Error(`Unknown action type: ${action.type}`);}@@ -80,7 +83,8 @@ async function executePost(client, agent, params) {throw new Error('Post action requires title and content in params (or aiGenerate enabled)');}- const post = await client.createPost(submolt, title, content);+ const result = await client.createPost(submolt, title, content);+ const post = result?.post || result;return {type: 'post',postId: post?.id || post?._id || post?.post_id,@@ -215,21 +219,25 @@ async function executeEngage(client, agent, params) {const votes = [];const comments = [];+ let suspended = false;// Vote on relevant postsfor (const post of relevantPosts) {- if (votes.length >= maxVotes) break;+ if (votes.length >= maxVotes || suspended) break;const rateCheck = checkRateLimit(client.apiKey, 'vote');if (!rateCheck.allowed) break;- await client.upvote(post.id);+ await client.upvote(post.id).catch(e => {+ if (isAccountSuspended(e)) suspended = true;+ });+ if (suspended) break;votes.push({ postId: post.id, title: post.title });await delay(1500);}// Comment on best matches- if (maxComments > 0) {+ if (maxComments > 0 && !suspended) {const opportunities = await findReplyOpportunities(client, agent, {sort: 'hot',minScore: 2,@@ -237,31 +245,136 @@ async function executeEngage(client, agent, params) {});for (const opportunity of opportunities) {- if (comments.length >= maxComments) break;+ if (comments.length >= maxComments || suspended) break;const rateCheck = checkRateLimit(client.apiKey, 'comment');if (!rateCheck.allowed) break;const generated = await generateComment(agent, opportunity.post, opportunity.comments);- const result = await client.createComment(opportunity.post.id, generated.content);+ await client.createComment(opportunity.post.id, generated.content).catch(e => {+ if (isAccountSuspended(e)) suspended = true;+ });+ if (suspended) break;comments.push({postId: opportunity.post.id || opportunity.post._id,postTitle: opportunity.post.title,- commentId: result?.id || result?._id || result?.comment_id,reason: opportunity.reason});await delay(1500);}}- console.log(`🤝 Engage complete for "${agent.name}": ${votes.length} votes, ${comments.length} comments`);+ if (suspended) {+ console.log(`🚫 Account suspended during engage — halting`);+ }++ console.log(`🤝 Engage ${suspended ? 'aborted (suspended)' : 'complete'} for "${agent.name}": ${votes.length} votes, ${comments.length} comments`);return {type: 'engage',postsReviewed: relevantPosts.length,votes,- comments+ comments,+ suspended+ };+}++/**+ * Execute a monitor action - check engagement on published posts and respond+ */+async function executeMonitor(client, agent, schedule, params) {+ const { days = 7, maxReplies = 2, maxUpvotes = 10 } = params;++ console.log(`👀 Starting monitor for "${agent.name}" (days=${days}, maxReplies=${maxReplies}, maxUpvotes=${maxUpvotes})`);++ const account = await platformAccounts.getAccountWithCredentials(schedule.accountId);+ const agentUsername = account?.credentials?.username;++ // Fetch posts directly from Moltbook API+ const allPosts = await client.getPostsByAuthor(agentUsername);+ const cutoff = new Date();+ cutoff.setDate(cutoff.getDate() - days);+ const posts = allPosts.filter(p => new Date(p.created_at) >= cutoff);++ console.log(`👀 Found ${allPosts.length} total posts by ${agentUsername}, ${posts.length} within ${days} days`);++ const upvoted = [];+ const replied = [];+ let totalComments = 0;+ let newComments = 0;+ let suspended = false;++ for (const post of posts) {+ if (suspended) break;++ const postId = post.id;+ const commentsResponse = await client.getComments(postId).catch(e => {+ if (isAccountSuspended(e)) suspended = true;+ return { comments: [] };+ });+ if (suspended) break;++ const allComments = commentsResponse.comments || commentsResponse || [];+ totalComments += allComments.length;++ const otherComments = allComments.filter(c => {+ const authorName = typeof c.author === 'object' ? c.author?.name : c.author;+ return authorName !== agentUsername;+ });+ newComments += otherComments.length;++ for (const comment of otherComments) {+ if (suspended) break;++ if (upvoted.length < maxUpvotes) {+ const rateCheck = checkRateLimit(client.apiKey, 'vote');+ if (rateCheck.allowed) {+ await client.upvoteComment(comment.id).catch(e => {+ if (isAccountSuspended(e)) suspended = true;+ });+ if (suspended) break;+ upvoted.push({ commentId: comment.id, postId, postTitle: post.title });+ await delay(1500);+ }+ }++ if (!suspended && replied.length < maxReplies) {+ const rateCheck = checkRateLimit(client.apiKey, 'comment');+ if (rateCheck.allowed) {+ const generated = await generateReply(agent, post, comment);+ await client.replyToComment(postId, comment.id, generated.content).catch(e => {+ if (isAccountSuspended(e)) suspended = true;+ });+ if (suspended) break;+ replied.push({+ commentId: comment.id,+ postId,+ postTitle: post.title+ });+ await delay(1500);+ }+ }++ if (upvoted.length >= maxUpvotes && replied.length >= maxReplies) break;+ }+ }++ if (suspended) {+ console.log(`🚫 Account ${agentUsername} suspended — halting monitor, marking account`);+ await platformAccounts.updateAccountStatus(schedule.accountId, 'suspended');+ }++ console.log(`👀 Monitor ${suspended ? 'aborted (suspended)' : 'complete'} for "${agent.name}": ${posts.length} posts, ${newComments} new comments, ${upvoted.length} upvotes, ${replied.length} replies`);++ return {+ type: 'monitor',+ postsChecked: posts.length,+ totalComments,+ newComments,+ upvoted,+ replied,+ suspended};}diff --git a/server/services/agentPublished.js b/server/services/agentPublished.jsnew file mode 100644index 0000000000..64b4c4a840--- /dev/null+++ b/server/services/agentPublished.js@@ -0,0 +1,63 @@+/**+ * Agent Published Content Helpers+ *+ * Shared logic for collecting published posts/comments from activity logs.+ * Used by both the agentTools route and agentActionExecutor.+ */++import * as agentActivity from './agentActivity.js';++/**+ * Collect published posts and comments from activity logs over N days+ */+export async function collectPublishedPosts(agentId, numDays) {+ const postMap = new Map();+ const commentMap = new Map();++ for (let i = 0; i < numDays; i++) {+ const date = new Date();+ date.setDate(date.getDate() - i);++ const [postActivities, commentActivities, engageActivities] = await Promise.all([+ agentActivity.getActivities(agentId, { date, action: 'post' }),+ agentActivity.getActivities(agentId, { date, action: 'comment' }),+ agentActivity.getActivities(agentId, { date, action: 'engage' })+ ]);++ for (const activity of postActivities) {+ if (activity.status !== 'completed') continue;+ const postId = activity.result?.postId || activity.id;+ const title = activity.result?.title || activity.params?.title;+ const submolt = activity.result?.submolt || activity.params?.submolt;+ if (!postMap.has(postId)) {+ postMap.set(postId, { postId: activity.result?.postId || null, title, submolt, publishedAt: activity.timestamp });+ }+ }++ for (const activity of commentActivities) {+ if (activity.status !== 'completed') continue;+ const commentId = activity.result?.commentId || activity.id;+ const postId = activity.result?.postId || activity.params?.postId;+ const isReply = activity.result?.isReply;+ if (!commentMap.has(commentId)) {+ commentMap.set(commentId, { commentId: activity.result?.commentId || null, postId, isReply: !!isReply, publishedAt: activity.timestamp });+ }+ }++ for (const activity of engageActivities) {+ if (activity.status !== 'completed' || !activity.result?.comments) continue;+ for (const c of activity.result.comments) {+ if (!c.commentId || commentMap.has(c.commentId)) continue;+ commentMap.set(c.commentId, {+ commentId: c.commentId,+ postId: c.postId,+ postTitle: c.postTitle,+ isReply: false,+ publishedAt: activity.timestamp+ });+ }+ }+ }++ return { postMap, commentMap };+}