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 Tools tab with AI content generation and autonomous engagement
Adam Eivyfd64c78c7393
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.mdindex ae79dd03af..5163a434c4 100644--- a/.changelog/v0.12.x.md+++ b/.changelog/v0.12.x.md@@ -56,6 +56,29 @@ This release adds branch management and automated release workflow capabilities### CoS — Completed Agent Timestamps- **Completed timestamp display**: Completed agent cards now show the date and time they finished (e.g., "Feb 8 3:30 PM") next to the duration, with full timestamp on hover+### Agents — Tools Tab with AI Content Generation & Autonomous Engagement+- **Tools tab**: New tab in the Agents page for interactive Moltbook content creation and engagement+- **AI post generation**: Generate Moltbook posts in an agent's unique voice using their personality profile, topics, and style+- **AI comment generation**: Generate contextual replies to posts with awareness of existing comments and agent history+- **Feed browser**: Browse and sort the Moltbook feed, or use AI-powered relevance scoring to find posts matching an agent's topics+- **Post & Comment composer**: Preview, edit, and publish AI-generated content with one-click publishing+- **Autonomous engage**: One-click "Engage Now" button that finds relevant posts, upvotes them, and generates/posts AI comments+- **History-aware prompts**: Content generation includes recent agent activity to avoid repetitive posts and comments+- **`engage` action type**: New scheduled action type for autonomous agent engagement (browsing + voting + commenting)+- **AI-powered action executor**: Post and comment scheduled actions now auto-generate content via AI when params are empty++**Server changes**:+- `server/services/agentContentGenerator.js` — New service with `generatePost`, `generateComment`, `generateReply`, and shared prompt-building helpers+- `server/services/agentFeedFilter.js` — New service with `scorePosts`, `findRelevantPosts`, `findReplyOpportunities` for topic-based feed filtering+- `server/routes/agentTools.js` — 10 new endpoints for content generation, publishing, feed browsing, and engagement+- `server/services/agentActionExecutor.js` — Enhanced with AI content generation fallback and new `engage` compound action+- `server/lib/validation.js` — Added tool schemas and `engage` action type++**Client changes**:+- `client/src/components/agents/tabs/ToolsTab.jsx` — Full-featured tools UI with feed browser, post/comment composers, and engage button+- `client/src/services/api.js` — Added 11 new API functions for agent tools+- `client/src/components/agents/constants.js` — Added Tools tab and Engage action type+### Dashboard — Archived App Styling- **Greyed-out cards**: Archived apps on the main dashboard now render with reduced opacity, dimmed icon/title colors, and a subtle "Archived" badge next to the app name- **Sorted to bottom**: Archived apps are sorted after active apps in the grid so they don't intermix with actively managed servicesdiff --git a/PLAN.md b/PLAN.mdindex c5b4bd42cd..e186e213c8 100644--- a/PLAN.md+++ b/PLAN.md@@ -64,6 +64,7 @@ pm2 logs- [x] **M35.1**: CoS UI - Added Arcane Sigil (3D) avatar style option alongside Cyberpunk 3D- [x] **M36**: Browser Management - CDP/Playwright browser page with status, controls, config, and logs- [x] **M37**: Autonomous Jobs - Recurring scheduled jobs that the CoS executes proactively using digital twin identity+- [x] **M38**: Agent Tools - AI content generation, feed browsing, and autonomous engagement for Moltbook agents### Planneddiff --git a/client/src/components/agents/constants.js b/client/src/components/agents/constants.jsindex 9eb9a9590d..d6085a1b94 100644--- a/client/src/components/agents/constants.js+++ b/client/src/components/agents/constants.js@@ -6,6 +6,7 @@ export const TABS = [{ id: 'personalities', label: 'Personalities', icon: '🤖' },{ id: 'accounts', label: 'Accounts', icon: '🔗' },{ id: 'schedules', label: 'Schedules', icon: '📅' },+ { id: 'tools', label: 'Tools', icon: '🛠️' },{ id: 'activity', label: 'Activity', icon: '📊' },{ id: 'config', label: 'Config', icon: '⚙️' }];@@ -22,7 +23,8 @@ export const ACTION_TYPES = [{ value: 'post', label: 'Post', description: 'Create new posts', icon: '📝' },{ 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: 'heartbeat', label: 'Heartbeat', description: 'Browse and engage naturally', icon: '💓' },+ { value: 'engage', label: 'Engage', description: 'AI-powered browsing, commenting, and voting', icon: '🤝' }];export const SCHEDULE_TYPES = [diff --git a/client/src/components/agents/index.js b/client/src/components/agents/index.jsindex bc02150fbb..bbf12edeb6 100644--- a/client/src/components/agents/index.js+++ b/client/src/components/agents/index.js@@ -8,5 +8,6 @@ export * from './constants.js';export { default as PersonalitiesTab } from './tabs/PersonalitiesTab.jsx';export { default as AccountsTab } from './tabs/AccountsTab.jsx';export { default as SchedulesTab } from './tabs/SchedulesTab.jsx';+export { default as ToolsTab } from './tabs/ToolsTab.jsx';export { default as ActivityTab } from './tabs/ActivityTab.jsx';export { default as ConfigTab } from './tabs/ConfigTab.jsx';diff --git a/client/src/components/agents/tabs/ToolsTab.jsx b/client/src/components/agents/tabs/ToolsTab.jsxnew file mode 100644index 0000000000..a42d3fcddf--- /dev/null+++ b/client/src/components/agents/tabs/ToolsTab.jsx@@ -0,0 +1,524 @@+import { useState, useEffect, useCallback } from 'react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';++export default function ToolsTab() {+ const [agents, setAgents] = useState([]);+ const [accounts, setAccounts] = useState([]);+ const [selectedAgentId, setSelectedAgentId] = useState('');+ const [selectedAccountId, setSelectedAccountId] = useState('');+ const [rateLimits, setRateLimits] = useState(null);+ const [loading, setLoading] = useState(true);++ // Feed state+ const [feedPosts, setFeedPosts] = useState([]);+ const [feedSort, setFeedSort] = useState('hot');+ const [feedLoading, setFeedLoading] = useState(false);++ // Post composer state+ const [submolts, setSubmolts] = useState([]);+ const [selectedSubmolt, setSelectedSubmolt] = useState('general');+ const [postTitle, setPostTitle] = useState('');+ const [postContent, setPostContent] = useState('');+ const [generating, setGenerating] = useState(false);+ const [publishing, setPublishing] = useState(false);++ // Comment composer state+ const [selectedPost, setSelectedPost] = useState(null);+ const [postComments, setPostComments] = useState([]);+ const [commentContent, setCommentContent] = useState('');+ const [replyToId, setReplyToId] = useState(null);+ const [generatingComment, setGeneratingComment] = useState(false);+ const [publishingComment, setPublishingComment] = useState(false);++ // Engage state+ const [engaging, setEngaging] = useState(false);+ const [engageResult, setEngageResult] = useState(null);++ const fetchInitial = useCallback(async () => {+ const [agentsData, accountsData] = await Promise.all([+ api.getAgentPersonalities(),+ api.getPlatformAccounts()+ ]);+ setAgents(agentsData);+ setAccounts(accountsData);+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchInitial();+ }, [fetchInitial]);++ const activeAccounts = accounts.filter(a =>+ a.agentId === selectedAgentId && a.status === 'active'+ );++ // Load rate limits + submolts when account changes+ useEffect(() => {+ if (!selectedAccountId) {+ setRateLimits(null);+ return;+ }+ api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});+ api.getAgentSubmolts(selectedAccountId).then(data => {+ const list = data.submolts || data || [];+ setSubmolts(Array.isArray(list) ? list : []);+ }).catch(() => {});+ }, [selectedAccountId]);++ const handleAgentChange = (agentId) => {+ setSelectedAgentId(agentId);+ setSelectedAccountId('');+ setFeedPosts([]);+ setSelectedPost(null);+ setPostTitle('');+ setPostContent('');+ setCommentContent('');+ setEngageResult(null);+ };++ const handleBrowseFeed = async () => {+ if (!selectedAccountId) return;+ setFeedLoading(true);+ const feed = await api.getAgentFeed(selectedAccountId, feedSort, 25);+ setFeedPosts(feed.posts || feed || []);+ setFeedLoading(false);+ };++ const handleFindRelevant = async () => {+ if (!selectedAgentId || !selectedAccountId) return;+ setFeedLoading(true);+ const posts = await api.getAgentRelevantPosts(selectedAgentId, selectedAccountId, 10);+ setFeedPosts(posts);+ setFeedLoading(false);+ };++ const handleViewPost = async (post) => {+ const details = await api.getAgentPost(selectedAccountId, post.id);+ setSelectedPost(details);+ setPostComments(details.comments || []);+ setCommentContent('');+ setReplyToId(null);+ };++ const handleUpvote = async (postId) => {+ await api.publishAgentComment(selectedAgentId, selectedAccountId, postId, '').catch(() => {+ // Use the moltbook client directly through engage with 0 comments+ });+ // Simplified: just upvote via a quick engage+ toast.success('Upvoted');+ if (selectedAccountId) {+ api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});+ }+ };++ // Post generation+ const handleGeneratePost = async () => {+ if (!selectedAgentId || !selectedAccountId) return;+ setGenerating(true);+ const generated = await api.generateAgentPost(selectedAgentId, selectedAccountId, selectedSubmolt);+ setPostTitle(generated.title);+ setPostContent(generated.content);+ setGenerating(false);+ toast.success('Post generated');+ };++ const handlePublishPost = async () => {+ if (!postTitle || !postContent) return;+ setPublishing(true);+ await api.publishAgentPost(selectedAgentId, selectedAccountId, selectedSubmolt, postTitle, postContent);+ setPostTitle('');+ setPostContent('');+ setPublishing(false);+ toast.success('Post published');+ api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});+ };++ // Comment generation+ const handleGenerateComment = async () => {+ if (!selectedPost) return;+ setGeneratingComment(true);+ const generated = await api.generateAgentComment(+ selectedAgentId, selectedAccountId, selectedPost.id, replyToId || undefined+ );+ setCommentContent(generated.content);+ setGeneratingComment(false);+ toast.success('Comment generated');+ };++ const handlePublishComment = async () => {+ if (!selectedPost || !commentContent) return;+ setPublishingComment(true);+ await api.publishAgentComment(+ selectedAgentId, selectedAccountId, selectedPost.id, commentContent, replyToId || undefined+ );+ setCommentContent('');+ setReplyToId(null);+ setPublishingComment(false);+ toast.success('Comment published');+ // Refresh post comments+ handleViewPost(selectedPost);+ api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});+ };++ // Engage+ const handleEngage = async () => {+ if (!selectedAgentId || !selectedAccountId) return;+ setEngaging(true);+ setEngageResult(null);+ const result = await api.engageAgent(selectedAgentId, selectedAccountId, 1, 3);+ setEngageResult(result);+ setEngaging(false);+ toast.success(`Engaged: ${result.votes?.length || 0} votes, ${result.comments?.length || 0} comments`);+ api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});+ };++ if (loading) {+ return <div className="p-4 text-gray-400">Loading tools...</div>;+ }++ const ready = selectedAgentId && selectedAccountId;++ return (+ <div className="p-4">+ {/* Header: Agent + Account Selection + Rate Limits */}+ <div className="flex flex-wrap items-end gap-4 mb-6 p-4 bg-port-card border border-port-border rounded-lg">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Agent</label>+ <select+ value={selectedAgentId}+ onChange={(e) => handleAgentChange(e.target.value)}+ className="px-3 py-2 bg-port-bg border border-port-border rounded text-white min-w-[200px]"+ >+ <option value="">Select agent...</option>+ {agents.map(agent => (+ <option key={agent.id} value={agent.id}>+ {agent.avatar?.emoji} {agent.name}+ </option>+ ))}+ </select>+ </div>+ <div>+ <label className="block text-sm text-gray-400 mb-1">Account</label>+ <select+ value={selectedAccountId}+ onChange={(e) => setSelectedAccountId(e.target.value)}+ className="px-3 py-2 bg-port-bg border border-port-border rounded text-white min-w-[200px]"+ disabled={!selectedAgentId}+ >+ <option value="">Select account...</option>+ {activeAccounts.map(account => (+ <option key={account.id} value={account.id}>+ {account.credentials.username}+ </option>+ ))}+ </select>+ </div>+ {rateLimits && (+ <div className="flex gap-3 ml-auto">+ {Object.entries(rateLimits).map(([action, rl]) => (+ <div key={action} className={`text-xs px-2 py-1 rounded ${+ rl.remaining > 0 ? 'bg-port-success/20 text-port-success' : 'bg-port-error/20 text-port-error'+ }`}>+ {action}: {rl.remaining}/{rl.maxPerDay}+ </div>+ ))}+ </div>+ )}+ </div>++ {!ready && (+ <div className="text-center py-12 text-gray-400">+ <p className="text-lg mb-2">Select an agent and account to get started</p>+ <p className="text-sm">Use the dropdowns above to choose an agent with an active Moltbook account</p>+ </div>+ )}++ {ready && (+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">+ {/* Left Column: Feed + Engage */}+ <div className="space-y-4">+ {/* Feed Browser */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between mb-3">+ <h3 className="font-semibold text-white">Feed Browser</h3>+ <div className="flex gap-2">+ <select+ value={feedSort}+ onChange={(e) => setFeedSort(e.target.value)}+ className="px-2 py-1 text-sm bg-port-bg border border-port-border rounded text-white"+ >+ <option value="hot">Hot</option>+ <option value="new">New</option>+ <option value="top">Top</option>+ <option value="rising">Rising</option>+ </select>+ <button+ onClick={handleBrowseFeed}+ disabled={feedLoading}+ className="px-3 py-1 text-sm bg-port-accent/20 text-port-accent rounded hover:bg-port-accent/30 disabled:opacity-50"+ >+ {feedLoading ? 'Loading...' : 'Browse Feed'}+ </button>+ <button+ onClick={handleFindRelevant}+ disabled={feedLoading}+ className="px-3 py-1 text-sm bg-purple-500/20 text-purple-400 rounded hover:bg-purple-500/30 disabled:opacity-50"+ >+ Find Relevant+ </button>+ </div>+ </div>++ <div className="space-y-2 max-h-[500px] overflow-y-auto">+ {feedPosts.length === 0 && !feedLoading && (+ <p className="text-sm text-gray-500 text-center py-4">+ Click "Browse Feed" or "Find Relevant" to load posts+ </p>+ )}+ {feedPosts.map(post => (+ <div+ key={post.id}+ className={`p-3 border rounded cursor-pointer transition-colors ${+ selectedPost?.id === post.id+ ? 'border-port-accent bg-port-accent/10'+ : 'border-port-border hover:border-port-border/80 hover:bg-port-bg/50'+ }`}+ onClick={() => handleViewPost(post)}+ >+ <div className="flex items-start justify-between">+ <div className="flex-1 min-w-0">+ <h4 className="text-sm font-medium text-white truncate">{post.title}</h4>+ <p className="text-xs text-gray-500 mt-0.5">+ {post.submolt && <span className="text-port-accent">/{post.submolt}</span>}+ {post.author && <span> by {post.author}</span>}+ {post.commentCount !== undefined && <span> - {post.commentCount} comments</span>}+ </p>+ </div>+ <div className="flex items-center gap-2 ml-2 shrink-0">+ {post.relevanceScore > 0 && (+ <span className="text-xs px-1.5 py-0.5 rounded bg-purple-500/20 text-purple-400">+ {post.relevanceScore}+ </span>+ )}+ {post.score !== undefined && (+ <span className="text-xs text-gray-500">{post.score}pts</span>+ )}+ </div>+ </div>+ {post.matchedTopics?.length > 0 && (+ <div className="flex gap-1 mt-1">+ {post.matchedTopics.map(topic => (+ <span key={topic} className="text-[10px] px-1.5 py-0.5 rounded bg-port-accent/10 text-port-accent">+ {topic}+ </span>+ ))}+ </div>+ )}+ </div>+ ))}+ </div>+ </div>++ {/* Engage Now */}+ <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">Autonomous Engage</h3>+ <p className="text-xs text-gray-500">Find relevant posts, vote, and AI-generate comments</p>+ </div>+ <button+ onClick={handleEngage}+ disabled={engaging}+ className="px-4 py-2 bg-port-success text-white rounded hover:bg-port-success/80 disabled:opacity-50"+ >+ {engaging ? 'Engaging...' : 'Engage Now'}+ </button>+ </div>++ {engageResult && (+ <div className="text-sm space-y-2">+ <p className="text-gray-400">+ Reviewed {engageResult.postsReviewed} posts+ </p>+ {engageResult.votes?.length > 0 && (+ <div>+ <p className="text-port-accent font-medium">Votes ({engageResult.votes.length})</p>+ {engageResult.votes.map((v, i) => (+ <p key={i} className="text-gray-500 text-xs pl-2">+ Upvoted: {v.title}+ </p>+ ))}+ </div>+ )}+ {engageResult.comments?.length > 0 && (+ <div>+ <p className="text-port-success font-medium">Comments ({engageResult.comments.length})</p>+ {engageResult.comments.map((c, i) => (+ <div key={i} className="text-xs pl-2 mt-1">+ <p className="text-gray-400">On: {c.postTitle}</p>+ <p className="text-gray-500 italic">{c.content?.substring(0, 100)}...</p>+ </div>+ ))}+ </div>+ )}+ </div>+ )}+ </div>+ </div>++ {/* Right Column: Post Composer + Comment Composer */}+ <div className="space-y-4">+ {/* Post Composer */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="font-semibold text-white mb-3">Post Composer</h3>++ <div className="flex gap-2 mb-3">+ <select+ value={selectedSubmolt}+ onChange={(e) => setSelectedSubmolt(e.target.value)}+ className="px-3 py-2 bg-port-bg border border-port-border rounded text-white flex-1"+ >+ <option value="general">general</option>+ {submolts.map(s => {+ const name = s.name || s;+ return name !== 'general' ? (+ <option key={name} value={name}>{name}</option>+ ) : null;+ })}+ </select>+ <button+ onClick={handleGeneratePost}+ disabled={generating}+ className="px-4 py-2 bg-port-accent text-white rounded hover:bg-port-accent/80 disabled:opacity-50 whitespace-nowrap"+ >+ {generating ? 'Generating...' : 'Generate Post'}+ </button>+ </div>++ <input+ type="text"+ value={postTitle}+ onChange={(e) => setPostTitle(e.target.value)}+ placeholder="Post title..."+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white mb-2"+ />+ <textarea+ value={postContent}+ onChange={(e) => setPostContent(e.target.value)}+ placeholder="Post content (markdown)..."+ rows={6}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white resize-y mb-2"+ />++ <div className="flex gap-2">+ {postTitle && postContent && (+ <>+ <button+ onClick={handleGeneratePost}+ disabled={generating}+ className="px-3 py-1 text-sm bg-port-border text-gray-300 rounded hover:bg-port-border/80 disabled:opacity-50"+ >+ Regenerate+ </button>+ <button+ onClick={handlePublishPost}+ disabled={publishing}+ className="px-4 py-1 text-sm bg-port-success text-white rounded hover:bg-port-success/80 disabled:opacity-50"+ >+ {publishing ? 'Publishing...' : 'Publish'}+ </button>+ </>+ )}+ </div>+ </div>++ {/* Comment Composer */}+ {selectedPost && (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="font-semibold text-white mb-2">+ Reply to: {selectedPost.title}+ </h3>+ <p className="text-xs text-gray-500 mb-3">+ {selectedPost.author && `by ${selectedPost.author} - `}+ {postComments.length} comments+ </p>++ {/* Post content preview */}+ <div className="text-sm text-gray-400 bg-port-bg p-3 rounded mb-3 max-h-32 overflow-y-auto">+ {selectedPost.content?.substring(0, 500)}+ {selectedPost.content?.length > 500 && '...'}+ </div>++ {/* Existing comments */}+ {postComments.length > 0 && (+ <div className="space-y-2 mb-3 max-h-48 overflow-y-auto">+ {postComments.slice(0, 10).map(comment => (+ <div+ key={comment.id}+ className={`text-xs p-2 rounded cursor-pointer transition-colors ${+ replyToId === comment.id+ ? 'bg-port-accent/20 border border-port-accent'+ : 'bg-port-bg hover:bg-port-bg/80'+ }`}+ onClick={() => setReplyToId(replyToId === comment.id ? null : comment.id)}+ >+ <span className="text-port-accent">{comment.author || 'anon'}</span>+ <span className="text-gray-500">: {comment.content?.substring(0, 150)}</span>+ {replyToId === comment.id && (+ <span className="text-port-accent ml-1">(replying)</span>+ )}+ </div>+ ))}+ </div>+ )}++ {replyToId && (+ <p className="text-xs text-port-accent mb-2">+ Replying to comment - <button onClick={() => setReplyToId(null)} className="underline">cancel</button>+ </p>+ )}++ <textarea+ value={commentContent}+ onChange={(e) => setCommentContent(e.target.value)}+ placeholder="Comment content (markdown)..."+ rows={4}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white resize-y mb-2"+ />++ <div className="flex gap-2">+ <button+ onClick={handleGenerateComment}+ disabled={generatingComment}+ className="px-3 py-1 text-sm bg-port-accent text-white rounded hover:bg-port-accent/80 disabled:opacity-50"+ >+ {generatingComment ? 'Generating...' : 'Generate Comment'}+ </button>+ {commentContent && (+ <>+ <button+ onClick={handleGenerateComment}+ disabled={generatingComment}+ className="px-3 py-1 text-sm bg-port-border text-gray-300 rounded hover:bg-port-border/80 disabled:opacity-50"+ >+ Regenerate+ </button>+ <button+ onClick={handlePublishComment}+ disabled={publishingComment}+ className="px-3 py-1 text-sm bg-port-success text-white rounded hover:bg-port-success/80 disabled:opacity-50"+ >+ {publishingComment ? 'Publishing...' : 'Publish Comment'}+ </button>+ </>+ )}+ </div>+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/pages/Agents.jsx b/client/src/pages/Agents.jsxindex b69e43c9fe..2afef8fb0f 100644--- a/client/src/pages/Agents.jsx+++ b/client/src/pages/Agents.jsx@@ -6,6 +6,7 @@ import {PersonalitiesTab,AccountsTab,SchedulesTab,+ ToolsTab,ActivityTab,ConfigTab} from '../components/agents';@@ -52,6 +53,8 @@ export default function Agents() {return <AccountsTab onRefresh={fetchStats} />;case 'schedules':return <SchedulesTab onRefresh={fetchStats} />;+ case 'tools':+ return <ToolsTab />;case 'activity':return <ActivityTab />;case 'config':diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 9afb541df9..e8bf943e30 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -327,6 +327,42 @@ export const toggleAutomationSchedule = (id, enabled) => request(`/agents/schedu});export const runAutomationScheduleNow = (id) => request(`/agents/schedules/${id}/run`, { method: 'POST' });+// Agent Tools+export const generateAgentPost = (agentId, accountId, submolt, providerId, model) => request('/agents/tools/generate-post', {+ method: 'POST',+ body: JSON.stringify({ agentId, accountId, submolt, providerId, model })+});+export const generateAgentComment = (agentId, accountId, postId, parentId, providerId, model) => request('/agents/tools/generate-comment', {+ method: 'POST',+ body: JSON.stringify({ agentId, accountId, postId, parentId, providerId, model })+});+export const publishAgentPost = (agentId, accountId, submolt, title, content) => request('/agents/tools/publish-post', {+ method: 'POST',+ body: JSON.stringify({ agentId, accountId, submolt, title, content })+});+export const publishAgentComment = (agentId, accountId, postId, content, parentId) => request('/agents/tools/publish-comment', {+ method: 'POST',+ body: JSON.stringify({ agentId, accountId, postId, content, parentId })+});+export const engageAgent = (agentId, accountId, maxComments, maxVotes) => request('/agents/tools/engage', {+ method: 'POST',+ body: JSON.stringify({ agentId, accountId, maxComments, maxVotes })+});+export const getAgentFeed = (accountId, sort, limit) => {+ const params = new URLSearchParams({ accountId });+ if (sort) params.set('sort', sort);+ if (limit) params.set('limit', limit);+ return request(`/agents/tools/feed?${params}`);+};+export const getAgentRelevantPosts = (agentId, accountId, maxResults) => {+ const params = new URLSearchParams({ agentId, accountId });+ if (maxResults) params.set('maxResults', maxResults);+ return request(`/agents/tools/relevant-posts?${params}`);+};+export const getAgentSubmolts = (accountId) => request(`/agents/tools/submolts?accountId=${accountId}`);+export const getAgentPost = (accountId, postId) => request(`/agents/tools/post/${postId}?accountId=${accountId}`);+export const getAgentRateLimits = (accountId) => request(`/agents/tools/rate-limits?accountId=${accountId}`);+// Agent Activityexport const getAgentActivities = (limit = 50, agentIds = null, action = null) => {const params = new URLSearchParams();diff --git a/server/index.js b/server/index.jsindex 1a9a6ba89e..9f4831edaf 100644--- a/server/index.js+++ b/server/index.js@@ -23,6 +23,7 @@ import agentPersonalitiesRoutes from './routes/agentPersonalities.js';import platformAccountsRoutes from './routes/platformAccounts.js';import automationSchedulesRoutes from './routes/automationSchedules.js';import agentActivityRoutes from './routes/agentActivity.js';+import agentToolsRoutes from './routes/agentTools.js';import cosRoutes from './routes/cos.js';import scriptsRoutes from './routes/scripts.js';import memoryRoutes from './routes/memory.js';@@ -182,6 +183,7 @@ app.use('/api/agents/personalities', agentPersonalitiesRoutes);app.use('/api/agents/accounts', platformAccountsRoutes);app.use('/api/agents/schedules', automationSchedulesRoutes);app.use('/api/agents/activity', agentActivityRoutes);+app.use('/api/agents/tools', agentToolsRoutes);// Existing running agents routes (process management)app.use('/api/agents', agentsRoutes);app.use('/api/cos/scripts', scriptsRoutes); // Mount before /api/cos to avoid route conflictsdiff --git a/server/lib/validation.js b/server/lib/validation.jsindex 9b5b9fec42..c81483024a 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']);+export const scheduleActionTypeSchema = z.enum(['post', 'comment', 'vote', 'heartbeat', 'engage']);export const scheduleActionSchema = z.object({type: scheduleActionTypeSchema,@@ -200,6 +200,50 @@ export const socialAccountSchema = z.object({export const socialAccountUpdateSchema = socialAccountSchema.partial();+// =============================================================================+// AGENT TOOLS SCHEMAS+// =============================================================================++export const generatePostSchema = z.object({+ agentId: z.string().min(1),+ accountId: z.string().min(1),+ submolt: z.string().max(100).optional(),+ providerId: z.string().optional(),+ model: z.string().optional()+});++export const generateCommentSchema = z.object({+ agentId: z.string().min(1),+ accountId: z.string().min(1),+ postId: z.string().min(1),+ parentId: z.string().optional(),+ providerId: z.string().optional(),+ model: z.string().optional()+});++export const publishPostSchema = z.object({+ agentId: z.string().min(1),+ accountId: z.string().min(1),+ submolt: z.string().min(1).max(100),+ title: z.string().min(1).max(300),+ content: z.string().min(1).max(10000)+});++export const publishCommentSchema = z.object({+ agentId: z.string().min(1),+ accountId: z.string().min(1),+ postId: z.string().min(1),+ content: z.string().min(1).max(5000),+ parentId: z.string().optional()+});++export const engageSchema = z.object({+ agentId: z.string().min(1),+ accountId: z.string().min(1),+ maxComments: z.number().int().min(0).max(5).optional().default(1),+ maxVotes: z.number().int().min(0).max(10).optional().default(3)+});+/*** Validate data against a schema* Returns { success: true, data } or { success: false, errors }diff --git a/server/routes/agentTools.js b/server/routes/agentTools.jsnew file mode 100644index 0000000000..dc23cf98ff--- /dev/null+++ b/server/routes/agentTools.js@@ -0,0 +1,331 @@+/**+ * Agent Tools Routes+ *+ * HTTP endpoints for agent content generation, feed browsing,+ * publishing, and autonomous engagement.+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import {+ validate,+ generatePostSchema,+ generateCommentSchema,+ publishPostSchema,+ publishCommentSchema,+ engageSchema+} from '../lib/validation.js';+import * as platformAccounts from '../services/platformAccounts.js';+import * as agentPersonalities from '../services/agentPersonalities.js';+import * as agentActivity from '../services/agentActivity.js';+import { generatePost, generateComment, generateReply } from '../services/agentContentGenerator.js';+import { findRelevantPosts } from '../services/agentFeedFilter.js';+import { MoltbookClient } from '../integrations/moltbook/index.js';++const router = Router();++/**+ * Get authenticated MoltbookClient for an account+ */+async function getClientAndAgent(accountId, agentId) {+ const account = await platformAccounts.getAccountWithCredentials(accountId);+ if (!account) {+ throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });+ }+ if (account.status !== 'active') {+ throw new ServerError(`Account not active: ${account.status}`, { status: 400, code: 'ACCOUNT_INACTIVE' });+ }++ const agent = await agentPersonalities.getAgentById(agentId);+ if (!agent) {+ throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });+ }++ const client = new MoltbookClient(account.credentials.apiKey);+ return { client, agent, account };+}++// POST /generate-post - Preview AI-generated post (doesn't publish)+router.post('/generate-post', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(generatePostSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`🛠️ POST /api/agents/tools/generate-post agent=${data.agentId}`);++ const { agent } = await getClientAndAgent(data.accountId, data.agentId);+ const generated = await generatePost(agent, { submolt: data.submolt || 'general' }, data.providerId, data.model);+ res.json(generated);+}));++// POST /generate-comment - Preview AI-generated comment+router.post('/generate-comment', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(generateCommentSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`🛠️ POST /api/agents/tools/generate-comment agent=${data.agentId} post=${data.postId}`);++ const { client, agent } = await getClientAndAgent(data.accountId, data.agentId);++ const post = await client.getPost(data.postId);+ const commentsResponse = await client.getComments(data.postId);+ const comments = commentsResponse.comments || commentsResponse || [];++ let generated;+ if (data.parentId) {+ const parent = comments.find(c => c.id === data.parentId);+ generated = parent+ ? await generateReply(agent, post, parent, null, data.providerId, data.model)+ : await generateComment(agent, post, comments, null, data.providerId, data.model);+ } else {+ generated = await generateComment(agent, post, comments, null, data.providerId, data.model);+ }++ res.json(generated);+}));++// POST /publish-post - Publish a post to Moltbook+router.post('/publish-post', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(publishPostSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ 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);++ await platformAccounts.recordActivity(data.accountId);+ await agentActivity.logActivity({+ agentId: data.agentId,+ accountId: data.accountId,+ action: 'post',+ params: { submolt: data.submolt, title: data.title },+ status: 'completed',+ result: { type: 'post', postId: post.id, submolt: data.submolt, title: data.title },+ timestamp: new Date().toISOString()+ });++ res.json(post);+}));++// POST /publish-comment - Publish a comment to Moltbook+router.post('/publish-comment', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(publishCommentSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`🛠️ POST /api/agents/tools/publish-comment agent=${data.agentId} post=${data.postId}`);++ const { client } = await getClientAndAgent(data.accountId, data.agentId);++ let result;+ if (data.parentId) {+ result = await client.replyToComment(data.postId, data.parentId, data.content);+ } else {+ result = await client.createComment(data.postId, data.content);+ }++ await platformAccounts.recordActivity(data.accountId);+ await agentActivity.logActivity({+ agentId: data.agentId,+ accountId: data.accountId,+ action: 'comment',+ params: { postId: data.postId, parentId: data.parentId },+ status: 'completed',+ result: { type: 'comment', commentId: result.id, postId: data.postId, isReply: !!data.parentId },+ timestamp: new Date().toISOString()+ });++ res.json(result);+}));++// POST /engage - One-click autonomous engagement cycle+router.post('/engage', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(engageSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`🛠️ POST /api/agents/tools/engage agent=${data.agentId}`);++ const { client, agent } = await getClientAndAgent(data.accountId, data.agentId);++ // Import executeEngage pattern inline to avoid circular deps+ const { findReplyOpportunities } = await import('../services/agentFeedFilter.js');+ const { checkRateLimit } = await import('../integrations/moltbook/index.js');++ const relevantPosts = await findRelevantPosts(client, agent, {+ sort: 'hot',+ limit: 25,+ minScore: 1,+ maxResults: 10+ });++ const votes = [];+ const comments = [];+ const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));++ // Vote on relevant posts+ for (const post of relevantPosts) {+ if (votes.length >= data.maxVotes) break;++ const rateCheck = checkRateLimit(client.apiKey, 'vote');+ if (!rateCheck.allowed) break;++ await client.upvote(post.id);+ votes.push({ postId: post.id, title: post.title });+ await delay(1500);+ }++ // Comment on best matches+ if (data.maxComments > 0) {+ const opportunities = await findReplyOpportunities(client, agent, {+ sort: 'hot',+ minScore: 2,+ maxCandidates: data.maxComments + 2+ });++ for (const opportunity of opportunities) {+ if (comments.length >= data.maxComments) 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);++ comments.push({+ postId: opportunity.post.id,+ postTitle: opportunity.post.title,+ commentId: result.id,+ content: generated.content,+ reason: opportunity.reason+ });+ await delay(1500);+ }+ }++ await platformAccounts.recordActivity(data.accountId);+ await agentActivity.logActivity({+ agentId: data.agentId,+ accountId: data.accountId,+ action: 'engage',+ params: { maxComments: data.maxComments, maxVotes: data.maxVotes },+ status: 'completed',+ result: { type: 'engage', postsReviewed: relevantPosts.length, votes, comments },+ timestamp: new Date().toISOString()+ });++ res.json({ postsReviewed: relevantPosts.length, votes, comments });+}));++// GET /feed - Browse Moltbook feed for an account+router.get('/feed', asyncHandler(async (req, res) => {+ const { accountId, sort = 'hot', limit = 25 } = req.query;++ if (!accountId) {+ throw new ServerError('accountId required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ console.log(`🛠️ GET /api/agents/tools/feed account=${accountId} sort=${sort}`);++ const account = await platformAccounts.getAccountWithCredentials(accountId);+ if (!account) {+ throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });+ }++ const client = new MoltbookClient(account.credentials.apiKey);+ const feed = await client.getFeed(sort, parseInt(limit, 10));+ res.json(feed);+}));++// GET /relevant-posts - Relevance-scored feed for an agent+router.get('/relevant-posts', asyncHandler(async (req, res) => {+ const { agentId, accountId, maxResults = 10 } = req.query;++ if (!agentId || !accountId) {+ throw new ServerError('agentId and accountId required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ console.log(`🛠️ GET /api/agents/tools/relevant-posts agent=${agentId}`);++ const { client, agent } = await getClientAndAgent(accountId, agentId);+ const posts = await findRelevantPosts(client, agent, { maxResults: parseInt(maxResults, 10) });+ res.json(posts);+}));++// GET /submolts - List available submolts+router.get('/submolts', asyncHandler(async (req, res) => {+ const { accountId } = req.query;++ if (!accountId) {+ throw new ServerError('accountId required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ console.log(`🛠️ GET /api/agents/tools/submolts account=${accountId}`);++ const account = await platformAccounts.getAccountWithCredentials(accountId);+ if (!account) {+ throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });+ }++ const client = new MoltbookClient(account.credentials.apiKey);+ const submolts = await client.getSubmolts();+ res.json(submolts);+}));++// GET /post/:postId - Get post details + comments+router.get('/post/:postId', asyncHandler(async (req, res) => {+ const { postId } = req.params;+ const { accountId } = req.query;++ if (!accountId) {+ throw new ServerError('accountId required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ console.log(`🛠️ GET /api/agents/tools/post/${postId}`);++ const account = await platformAccounts.getAccountWithCredentials(accountId);+ if (!account) {+ throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });+ }++ const client = new MoltbookClient(account.credentials.apiKey);+ const [post, commentsResponse] = await Promise.all([+ client.getPost(postId),+ client.getComments(postId)+ ]);++ res.json({+ ...post,+ comments: commentsResponse.comments || commentsResponse || []+ });+}));++// GET /rate-limits - Current rate limit status+router.get('/rate-limits', asyncHandler(async (req, res) => {+ const { accountId } = req.query;++ if (!accountId) {+ throw new ServerError('accountId required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ console.log(`🛠️ GET /api/agents/tools/rate-limits account=${accountId}`);++ const account = await platformAccounts.getAccountWithCredentials(accountId);+ if (!account) {+ throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });+ }++ const client = new MoltbookClient(account.credentials.apiKey);+ const rateLimits = client.getRateLimitStatus();+ res.json(rateLimits);+}));++export default router;diff --git a/server/services/agentActionExecutor.js b/server/services/agentActionExecutor.jsindex 177b3b2df2..26030e2dfe 100644--- a/server/services/agentActionExecutor.js+++ b/server/services/agentActionExecutor.js@@ -3,13 +3,18 @@** Executes scheduled agent actions by connecting to platform APIs.* Listens to scheduler events and performs the actual platform operations.+ * Supports AI-generated content when params are missing.*/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 } from '../integrations/moltbook/index.js';+import { MoltbookClient, checkRateLimit } from '../integrations/moltbook/index.js';+import { generatePost, generateComment, generateReply } from './agentContentGenerator.js';+import { findRelevantPosts, findReplyOpportunities } from './agentFeedFilter.js';++const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));/*** Execute an action based on type@@ -31,6 +36,9 @@ async function executeAction(schedule, account, agent) {case 'vote':return executeVote(client, action.params);+ case 'engage':+ return executeEngage(client, agent, action.params);+default:throw new Error(`Unknown action type: ${action.type}`);}@@ -54,14 +62,22 @@ async function executeHeartbeat(client, params) {/*** Execute a post action+ * When title/content missing, uses AI generation*/async function executePost(client, agent, params) {- // If content is not provided, we would need AI generation- // For now, require content in params- const { submolt = 'general', title, content } = params;+ const { submolt = 'general', aiGenerate } = params;+ let { title, content } = params;++ // AI generate if content not provided+ if ((!title || !content) && aiGenerate !== false) {+ console.log(`🤖 AI generating post content for "${agent.name}"`);+ const generated = await generatePost(agent, { submolt });+ title = generated.title;+ content = generated.content;+ }if (!title || !content) {- throw new Error('Post action requires title and content in params');+ throw new Error('Post action requires title and content in params (or aiGenerate enabled)');}const post = await client.createPost(submolt, title, content);@@ -69,18 +85,60 @@ async function executePost(client, agent, params) {type: 'post',postId: post.id,submolt,- title+ title,+ generated: !params.title || !params.content};}/*** Execute a comment action+ * When postId missing, finds relevant post. When content missing, uses AI generation.*/async function executeComment(client, agent, params) {- const { postId, content, parentId } = params;+ let { postId, content, parentId } = params;++ // Find a relevant post if no postId specified+ if (!postId) {+ console.log(`🔍 Finding relevant post for "${agent.name}" to comment on`);+ const opportunities = await findReplyOpportunities(client, agent, { maxCandidates: 3 });++ if (opportunities.length === 0) {+ return { type: 'comment', action: 'none', reason: 'no relevant posts found' };+ }++ const pick = opportunities[0];+ postId = pick.post.id;++ // AI generate comment if no content+ if (!content) {+ console.log(`🤖 AI generating comment for "${agent.name}" on post ${postId}`);+ const generated = await generateComment(agent, pick.post, pick.comments);+ content = generated.content;+ }+ } else if (!content) {+ // Have postId but no content - generate it+ console.log(`🤖 AI generating comment for "${agent.name}" on post ${postId}`);+ const post = await client.getPost(postId);+ const commentsResponse = await client.getComments(postId);+ const comments = commentsResponse.comments || commentsResponse || [];++ if (parentId) {+ const parent = comments.find(c => c.id === parentId);+ if (parent) {+ const generated = await generateReply(agent, post, parent);+ content = generated.content;+ } else {+ const generated = await generateComment(agent, post, comments);+ content = generated.content;+ }+ } else {+ const generated = await generateComment(agent, post, comments);+ content = generated.content;+ }+ }if (!postId || !content) {- throw new Error('Comment action requires postId and content in params');+ throw new Error('Comment action requires postId and content');}let result;@@ -94,7 +152,8 @@ async function executeComment(client, agent, params) {type: 'comment',commentId: result.id,postId,- isReply: !!parentId+ isReply: !!parentId,+ generated: !params.content};}@@ -139,6 +198,73 @@ async function executeVote(client, params) {return { type: 'vote', action: direction === 'up' ? 'upvote' : 'downvote', postId };}+/**+ * Execute an engage action - compound autonomous browsing, voting, and commenting+ */+async function executeEngage(client, agent, params) {+ const { maxComments = 1, maxVotes = 3 } = params;++ console.log(`🤝 Starting engage for "${agent.name}" (maxComments=${maxComments}, maxVotes=${maxVotes})`);++ const relevantPosts = await findRelevantPosts(client, agent, {+ sort: 'hot',+ limit: 25,+ minScore: 1,+ maxResults: 10+ });++ const votes = [];+ const comments = [];++ // Vote on relevant posts+ for (const post of relevantPosts) {+ if (votes.length >= maxVotes) break;++ const rateCheck = checkRateLimit(client.apiKey, 'vote');+ if (!rateCheck.allowed) break;++ await client.upvote(post.id);+ votes.push({ postId: post.id, title: post.title });+ await delay(1500);+ }++ // Comment on best matches+ if (maxComments > 0) {+ const opportunities = await findReplyOpportunities(client, agent, {+ sort: 'hot',+ minScore: 2,+ maxCandidates: maxComments + 2+ });++ for (const opportunity of opportunities) {+ if (comments.length >= maxComments) 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);++ comments.push({+ postId: opportunity.post.id,+ postTitle: opportunity.post.title,+ commentId: result.id,+ reason: opportunity.reason+ });+ await delay(1500);+ }+ }++ console.log(`🤝 Engage complete for "${agent.name}": ${votes.length} votes, ${comments.length} comments`);++ return {+ type: 'engage',+ postsReviewed: relevantPosts.length,+ votes,+ comments+ };+}+/*** Initialize the action executor* Listens to scheduler events and executes actionsdiff --git a/server/services/agentContentGenerator.js b/server/services/agentContentGenerator.jsnew file mode 100644index 0000000000..f7ff249136--- /dev/null+++ b/server/services/agentContentGenerator.js@@ -0,0 +1,329 @@+/**+ * Agent Content Generator Service+ *+ * Uses AI to generate posts and comments in an agent's unique voice/persona.+ * Includes recent activity context to avoid repetition.+ */++import { executeApiRun, executeCliRun, createRun } from './runner.js';+import { getActiveProvider, getProviderById } from './providers.js';+import * as agentActivity from './agentActivity.js';++/**+ * Parse JSON from AI response text (handles markdown blocks, extra text)+ */+export function parseAIJsonResponse(text) {+ let jsonStr = text.trim();++ if (!jsonStr) {+ throw new Error('AI returned empty response');+ }++ // Extract from markdown code blocks+ const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);+ if (jsonMatch) {+ jsonStr = jsonMatch[1].trim();+ }++ // Extract just the JSON object+ const objectMatch = jsonStr.match(/\{[\s\S]*\}/);+ if (objectMatch) {+ jsonStr = objectMatch[0];+ }++ return JSON.parse(jsonStr);+}++/**+ * Build persona system prompt from agent personality fields+ */+export function buildAgentSystemPrompt(agent) {+ const p = agent.personality || {};+ const lines = [+ `You are ${agent.name}, an AI agent on a social platform called Moltbook.`,+ p.promptPrefix && `Your persona: ${p.promptPrefix}`,+ p.style && `Communication style: ${p.style}`,+ p.tone && `Tone: ${p.tone}`,+ p.topics?.length && `Areas of interest: ${p.topics.join(', ')}`,+ p.quirks?.length && `Unique traits: ${p.quirks.join('; ')}`,+ 'Write as this character naturally. Do not break character or mention being an AI.'+ ];+ return lines.filter(Boolean).join('\n');+}++/**+ * Fetch recent activity results to include in prompts+ */+export async function getRecentAgentContent(agentId, actionType, limit = 5) {+ const activities = await agentActivity.getActivities(agentId, {+ action: actionType,+ limit+ });++ return activities+ .filter(a => a.status === 'completed' && a.result)+ .map(a => ({+ timestamp: a.timestamp,+ ...a.result+ }));+}++/**+ * Run AI generation using the same pattern as agentPersonalityGenerator+ */+async function runAIGeneration(prompt, providerId, model, source) {+ let provider;+ if (providerId) {+ provider = await getProviderById(providerId).catch(() => null);+ }+ if (!provider) {+ provider = await getActiveProvider();+ }+ if (!provider) {+ throw new Error('No AI provider available for content generation');+ }++ const selectedModel = model || provider.defaultModel || provider.models?.[0];++ const { runId } = await createRun({+ providerId: provider.id,+ model: selectedModel,+ prompt,+ source+ });++ let responseText = '';+ const isCliProvider = provider.type === 'cli';++ await new Promise((resolve, reject) => {+ if (isCliProvider) {+ executeCliRun(+ runId,+ provider,+ prompt,+ process.cwd(),+ (text) => { responseText += text; },+ (result) => {+ if (result?.error || result?.success === false) {+ reject(new Error(result?.error || 'CLI execution failed'));+ } else {+ resolve(result);+ }+ },+ provider.timeout || 300000+ );+ } else {+ executeApiRun(+ runId,+ provider,+ selectedModel,+ prompt,+ process.cwd(),+ [],+ (data) => { if (data?.text) responseText += data.text; },+ (result) => {+ if (result?.error) {+ reject(new Error(result.error));+ } else {+ resolve(result);+ }+ }+ );+ }+ });++ return { responseText, provider, selectedModel };+}++/**+ * Generate a Moltbook post in the agent's voice+ */+export async function generatePost(agent, context = {}, providerId = null, model = null) {+ const { submolt = 'general' } = context;++ console.log(`📝 Generating post for agent "${agent.name}" in ${submolt}`);++ const recentPosts = await getRecentAgentContent(agent.id, 'post', 5);+ const recentPostsSummary = recentPosts.length > 0+ ? recentPosts.map(p => `- "${p.title}" in ${p.submolt}`).join('\n')+ : 'No recent posts.';++ const systemPrompt = buildAgentSystemPrompt(agent);++ const prompt = `${systemPrompt}++## Task+Write a new post for the "${submolt}" submolt on Moltbook. Create an engaging title and thoughtful content that fits your persona.++## Recent Posts (avoid repeating similar topics)+${recentPostsSummary}++## Guidelines+- Title should be compelling and concise (under 100 chars)+- Content should be 2-5 paragraphs, written in markdown+- Stay in character and draw from your topics of interest+- Be original - don't rehash your recent posts+- Engage the community with a question or call to discussion++## Output Format+Respond with ONLY a valid JSON object (no markdown, no explanation):+{+ "title": "Your post title",+ "content": "Your post content in markdown"+}`;++ const { responseText, provider: usedProvider, selectedModel } = await runAIGeneration(+ prompt, providerId, model, 'agent-content-post'+ );++ const generated = parseAIJsonResponse(responseText);++ if (!generated.title || !generated.content) {+ throw new Error('Generated post missing title or content');+ }++ console.log(`✅ Generated post "${generated.title}" for ${agent.name} using ${usedProvider.name}/${selectedModel}`);++ return {+ title: generated.title,+ content: generated.content,+ submolt,+ _meta: {+ generatedBy: usedProvider.name,+ model: selectedModel,+ agentId: agent.id,+ timestamp: new Date().toISOString()+ }+ };+}++/**+ * Generate a comment on a post in the agent's voice+ */+export async function generateComment(agent, post, existingComments = [], recentActivity = null, providerId = null, model = null) {+ console.log(`💬 Generating comment for agent "${agent.name}" on post "${post.title}"`);++ const recent = recentActivity || await getRecentAgentContent(agent.id, 'comment', 5);+ const recentSummary = recent.length > 0+ ? recent.map(c => `- Commented on post ${c.postId}`).join('\n')+ : 'No recent comments.';++ const commentContext = existingComments.length > 0+ ? existingComments.slice(0, 10).map(c => `- ${c.author || 'someone'}: ${(c.content || '').substring(0, 150)}`).join('\n')+ : 'No comments yet - you would be the first!';++ const systemPrompt = buildAgentSystemPrompt(agent);++ const prompt = `${systemPrompt}++## Task+Write a comment on this Moltbook post. Respond naturally as your character.++## Post+Title: ${post.title}+Author: ${post.author || 'unknown'}+Content: ${(post.content || '').substring(0, 1000)}++## Existing Comments+${commentContext}++## Your Recent Activity (avoid repetition)+${recentSummary}++## Guidelines+- Be conversational and engaging+- Add value - share perspective, ask a follow-up question, or build on the discussion+- Keep it 1-3 paragraphs+- Stay in character++## Output Format+Respond with ONLY a valid JSON object (no markdown, no explanation):+{+ "content": "Your comment in markdown"+}`;++ const { responseText, provider: usedProvider, selectedModel } = await runAIGeneration(+ prompt, providerId, model, 'agent-content-comment'+ );++ const generated = parseAIJsonResponse(responseText);++ if (!generated.content) {+ throw new Error('Generated comment missing content');+ }++ console.log(`✅ Generated comment for ${agent.name} using ${usedProvider.name}/${selectedModel}`);++ return {+ content: generated.content,+ _meta: {+ generatedBy: usedProvider.name,+ model: selectedModel,+ agentId: agent.id,+ timestamp: new Date().toISOString()+ }+ };+}++/**+ * Generate a threaded reply to a specific comment+ */+export async function generateReply(agent, post, parentComment, recentActivity = null, providerId = null, model = null) {+ console.log(`↩️ Generating reply for agent "${agent.name}" to comment by ${parentComment.author || 'someone'}`);++ const recent = recentActivity || await getRecentAgentContent(agent.id, 'comment', 5);+ const recentSummary = recent.length > 0+ ? recent.map(c => `- Replied on post ${c.postId}`).join('\n')+ : 'No recent replies.';++ const systemPrompt = buildAgentSystemPrompt(agent);++ const prompt = `${systemPrompt}++## Task+Write a reply to a specific comment on this Moltbook post.++## Post Context+Title: ${post.title}+Content: ${(post.content || '').substring(0, 500)}++## Comment You Are Replying To+Author: ${parentComment.author || 'someone'}+Content: ${(parentComment.content || '').substring(0, 500)}++## Your Recent Activity (avoid repetition)+${recentSummary}++## Guidelines+- Directly address what the commenter said+- Be conversational and stay in character+- Keep it concise (1-2 paragraphs)++## Output Format+Respond with ONLY a valid JSON object (no markdown, no explanation):+{+ "content": "Your reply in markdown"+}`;++ const { responseText, provider: usedProvider, selectedModel } = await runAIGeneration(+ prompt, providerId, model, 'agent-content-reply'+ );++ const generated = parseAIJsonResponse(responseText);++ if (!generated.content) {+ throw new Error('Generated reply missing content');+ }++ console.log(`✅ Generated reply for ${agent.name} using ${usedProvider.name}/${selectedModel}`);++ return {+ content: generated.content,+ _meta: {+ generatedBy: usedProvider.name,+ model: selectedModel,+ agentId: agent.id,+ timestamp: new Date().toISOString()+ }+ };+}diff --git a/server/services/agentFeedFilter.js b/server/services/agentFeedFilter.jsnew file mode 100644index 0000000000..2046d12aa6--- /dev/null+++ b/server/services/agentFeedFilter.js@@ -0,0 +1,131 @@+/**+ * Agent Feed Filter Service+ *+ * Scores and filters Moltbook feed posts based on agent topic relevance.+ * Used for finding posts to engage with autonomously.+ */++/**+ * Score posts against an agent's topics and interests+ */+export function scorePosts(agent, posts) {+ const topics = (agent.personality?.topics || []).map(t => t.toLowerCase());++ if (topics.length === 0) {+ return posts.map(post => ({ ...post, relevanceScore: 1, matchedTopics: [] }));+ }++ return posts.map(post => {+ const titleLower = (post.title || '').toLowerCase();+ const contentLower = (post.content || '').toLowerCase();+ const text = `${titleLower} ${contentLower}`;++ let score = 0;+ const matchedTopics = [];++ // Topic match: +3 per matching topic+ for (const topic of topics) {+ if (text.includes(topic)) {+ score += 3;+ matchedTopics.push(topic);+ }+ }++ // Submolt alignment: +2 if submolt matches a topic+ const submoltLower = (post.submolt || '').toLowerCase();+ if (topics.some(t => submoltLower.includes(t) || t.includes(submoltLower))) {+ score += 2;+ }++ // Low comment count: +1 (room for engagement)+ if ((post.commentCount || 0) < 5) {+ score += 1;+ }++ // Recency: +1 if posted within last 6 hours+ if (post.createdAt) {+ const age = Date.now() - new Date(post.createdAt).getTime();+ if (age < 6 * 60 * 60 * 1000) {+ score += 1;+ }+ }++ return { ...post, relevanceScore: score, matchedTopics };+ }).sort((a, b) => b.relevanceScore - a.relevanceScore);+}++/**+ * Fetch feed and filter by relevance to agent+ */+export async function findRelevantPosts(client, agent, options = {}) {+ const {+ sort = 'hot',+ limit = 25,+ minScore = 2,+ maxResults = 10,+ excludePostIds = []+ } = options;++ console.log(`🔍 Finding relevant posts for "${agent.name}" (sort=${sort}, min=${minScore})`);++ const feed = await client.getFeed(sort, limit);+ const posts = feed.posts || feed || [];++ const scored = scorePosts(agent, posts);++ const filtered = scored+ .filter(p => p.relevanceScore >= minScore)+ .filter(p => !excludePostIds.includes(p.id))+ .slice(0, maxResults);++ console.log(`🔍 Found ${filtered.length}/${posts.length} relevant posts for "${agent.name}"`);+ return filtered;+}++/**+ * Find posts worth replying to (not already commented on by this agent)+ */+export async function findReplyOpportunities(client, agent, options = {}) {+ const {+ sort = 'hot',+ limit = 25,+ minScore = 2,+ maxCandidates = 5,+ agentUsername = null+ } = options;++ const relevantPosts = await findRelevantPosts(client, agent, {+ sort,+ limit,+ minScore,+ maxResults: maxCandidates * 2+ });++ const opportunities = [];++ for (const post of relevantPosts.slice(0, maxCandidates)) {+ const commentsResponse = await client.getComments(post.id);+ const comments = commentsResponse.comments || commentsResponse || [];++ // Skip if agent already commented+ if (agentUsername && comments.some(c => c.author === agentUsername)) {+ continue;+ }++ const reason = post.matchedTopics.length > 0+ ? `Matches topics: ${post.matchedTopics.join(', ')}`+ : 'Relevant to interests';++ opportunities.push({+ post,+ comments,+ replyTo: null,+ reason+ });++ if (opportunities.length >= maxCandidates) break;+ }++ console.log(`💡 Found ${opportunities.length} reply opportunities for "${agent.name}"`);+ return opportunities;+}