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 AI agent personalities and platform automation system
Adam Eivy89625be1e9cb
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 862b92d210..80a3b753c8 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -10,6 +10,7 @@ import ChiefOfStaff from './pages/ChiefOfStaff';import Brain from './pages/Brain';import Media from './pages/Media';import DigitalTwin from './pages/DigitalTwin';+import Agents from './pages/Agents';// Lazy load heavier pages for code splitting// DevTools pages are large (~2300 lines total) so lazy load them@@ -55,6 +56,8 @@ export default function App() {<Route path="apps/create" element={<CreateApp />} /><Route path="templates" element={<Templates />} /><Route path="media" element={<Media />} />+ <Route path="agents" element={<Navigate to="/agents/personalities" replace />} />+ <Route path="agents/:tab" element={<Agents />} /><Route path="*" element={<Navigate to="/" replace />} /></Route></Routes>diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex a352443cdb..ba1737f53a 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -27,7 +27,10 @@ import {Clock,Calendar,GraduationCap,- Settings+ Settings,+ Users,+ Link2,+ LineChart} from 'lucide-react';import packageJson from '../../package.json';import Logo from './Logo';@@ -72,6 +75,17 @@ const navItems = [{ to: '/digital-twin', label: 'Digital Twin', icon: Heart }]},+ {+ label: 'Agents',+ icon: Users,+ children: [+ { to: '/agents/personalities', label: 'Personalities', icon: Bot },+ { to: '/agents/accounts', label: 'Accounts', icon: Link2 },+ { to: '/agents/schedules', label: 'Schedules', icon: Calendar },+ { to: '/agents/activity', label: 'Activity', icon: LineChart },+ { to: '/agents/config', label: 'Config', icon: Settings }+ ]+ },{label: 'Dev Tools',icon: Terminal,@@ -439,8 +453,8 @@ export default function Layout() {</header>{/* Main content */}- <main id="main-content" className={`flex-1 overflow-auto ${location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') || location.pathname.startsWith('/digital-twin') ? '' : 'p-4 md:p-6'}`}>- {location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') || location.pathname.startsWith('/digital-twin') ? (+ <main id="main-content" className={`flex-1 overflow-auto ${location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') || location.pathname.startsWith('/digital-twin') || location.pathname.startsWith('/agents') ? '' : 'p-4 md:p-6'}`}>+ {location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') || location.pathname.startsWith('/digital-twin') || location.pathname.startsWith('/agents') ? (<Outlet />) : (<div className="max-w-7xl mx-auto">diff --git a/client/src/components/agents/constants.js b/client/src/components/agents/constants.jsnew file mode 100644index 0000000000..9eb9a9590d--- /dev/null+++ b/client/src/components/agents/constants.js@@ -0,0 +1,78 @@+/**+ * Agent Feature Constants+ */++export const TABS = [+ { id: 'personalities', label: 'Personalities', icon: '🤖' },+ { id: 'accounts', label: 'Accounts', icon: '🔗' },+ { id: 'schedules', label: 'Schedules', icon: '📅' },+ { id: 'activity', label: 'Activity', icon: '📊' },+ { id: 'config', label: 'Config', icon: '⚙️' }+];++export const PERSONALITY_STYLES = [+ { value: 'professional', label: 'Professional', description: 'Formal, business-oriented communication' },+ { value: 'casual', label: 'Casual', description: 'Relaxed, friendly tone' },+ { value: 'witty', label: 'Witty', description: 'Clever humor and wordplay' },+ { value: 'academic', label: 'Academic', description: 'Educational, research-focused' },+ { value: 'creative', label: 'Creative', description: 'Artistic, imaginative expression' }+];++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: '💓' }+];++export const SCHEDULE_TYPES = [+ { value: 'cron', label: 'Cron', description: 'Run at specific times' },+ { value: 'interval', label: 'Interval', description: 'Run every N minutes/hours' },+ { value: 'random', label: 'Random', description: 'Run at random intervals within window' }+];++export const PLATFORM_TYPES = [+ { value: 'moltbook', label: 'Moltbook', description: 'AI social platform', icon: '📚' }+];++export const ACCOUNT_STATUSES = {+ active: { label: 'Active', color: 'text-port-success', bgColor: 'bg-port-success/20' },+ pending: { label: 'Pending', color: 'text-port-warning', bgColor: 'bg-port-warning/20' },+ suspended: { label: 'Suspended', color: 'text-port-error', bgColor: 'bg-port-error/20' },+ error: { label: 'Error', color: 'text-port-error', bgColor: 'bg-port-error/20' }+};++export const DEFAULT_PERSONALITY = {+ style: 'casual',+ tone: 'friendly and helpful',+ topics: [],+ quirks: [],+ promptPrefix: ''+};++export const DEFAULT_AVATAR = {+ emoji: '🤖',+ color: '#3b82f6'+};++// Cron presets for easy scheduling+export const CRON_PRESETS = [+ { value: '0 * * * *', label: 'Every hour' },+ { value: '0 */2 * * *', label: 'Every 2 hours' },+ { value: '0 */4 * * *', label: 'Every 4 hours' },+ { value: '0 */6 * * *', label: 'Every 6 hours' },+ { value: '0 9,12,15,18 * * *', label: 'Peak hours (9am, 12pm, 3pm, 6pm)' },+ { value: '0 9 * * *', label: 'Daily at 9am' },+ { value: '0 12 * * *', label: 'Daily at noon' }+];++// Interval presets (in milliseconds)+export const INTERVAL_PRESETS = [+ { value: 30 * 60 * 1000, label: '30 minutes' },+ { value: 60 * 60 * 1000, label: '1 hour' },+ { value: 2 * 60 * 60 * 1000, label: '2 hours' },+ { value: 4 * 60 * 60 * 1000, label: '4 hours' },+ { value: 6 * 60 * 60 * 1000, label: '6 hours' },+ { value: 12 * 60 * 60 * 1000, label: '12 hours' },+ { value: 24 * 60 * 60 * 1000, label: '24 hours' }+];diff --git a/client/src/components/agents/index.js b/client/src/components/agents/index.jsnew file mode 100644index 0000000000..bc02150fbb--- /dev/null+++ b/client/src/components/agents/index.js@@ -0,0 +1,12 @@+/**+ * Agent Components - Re-exports+ */++export * from './constants.js';++// Tab components+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 ActivityTab } from './tabs/ActivityTab.jsx';+export { default as ConfigTab } from './tabs/ConfigTab.jsx';diff --git a/client/src/components/agents/tabs/AccountsTab.jsx b/client/src/components/agents/tabs/AccountsTab.jsxnew file mode 100644index 0000000000..14f42871d0--- /dev/null+++ b/client/src/components/agents/tabs/AccountsTab.jsx@@ -0,0 +1,300 @@+import { useState, useEffect, useCallback } from 'react';+import * as api from '../../../services/api';+import { PLATFORM_TYPES, ACCOUNT_STATUSES } from '../constants';++export default function AccountsTab({ onRefresh }) {+ const [accounts, setAccounts] = useState([]);+ const [agents, setAgents] = useState([]);+ const [loading, setLoading] = useState(true);+ const [showForm, setShowForm] = useState(false);+ const [formData, setFormData] = useState({+ agentId: '',+ platform: 'moltbook',+ name: '',+ description: ''+ });+ const [testingId, setTestingId] = useState(null);+ const [testResult, setTestResult] = useState(null);++ const fetchData = useCallback(async () => {+ const [accountsData, agentsData] = await Promise.all([+ api.getPlatformAccounts(),+ api.getAgentPersonalities()+ ]);+ setAccounts(accountsData);+ setAgents(agentsData);+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ const resetForm = () => {+ setFormData({+ agentId: '',+ platform: 'moltbook',+ name: '',+ description: ''+ });+ setShowForm(false);+ };++ const handleSubmit = async (e) => {+ e.preventDefault();++ const result = await api.registerPlatformAccount(+ formData.agentId,+ formData.platform,+ formData.name,+ formData.description+ );++ resetForm();+ fetchData();+ onRefresh?.();++ // Show claim URL if returned+ if (result.claimUrl) {+ setTestResult({+ accountId: result.id,+ success: true,+ message: 'Account registered! Visit the claim URL to activate.',+ claimUrl: result.claimUrl+ });+ }+ };++ const handleDelete = async (id) => {+ await api.deletePlatformAccount(id);+ fetchData();+ onRefresh?.();+ };++ const handleTest = async (id) => {+ setTestingId(id);+ setTestResult(null);+ const result = await api.testPlatformAccount(id);+ setTestResult({ accountId: id, ...result });+ setTestingId(null);+ };++ const handleClaim = async (id) => {+ await api.claimPlatformAccount(id);+ fetchData();+ setTestResult(null);+ };++ const getAgentName = (agentId) => {+ const agent = agents.find(a => a.id === agentId);+ return agent?.name || 'Unknown Agent';+ };++ if (loading) {+ return <div className="p-4 text-gray-400">Loading accounts...</div>;+ }++ return (+ <div className="p-4">+ <div className="flex justify-between items-center mb-4">+ <h2 className="text-lg font-semibold text-white">Platform Accounts</h2>+ <button+ onClick={() => setShowForm(!showForm)}+ className="px-4 py-2 bg-port-accent text-white rounded hover:bg-port-accent/80"+ disabled={agents.length === 0}+ >+ {showForm ? 'Cancel' : '+ Link Account'}+ </button>+ </div>++ {agents.length === 0 && (+ <div className="mb-4 p-4 bg-port-warning/20 border border-port-warning/50 rounded text-port-warning">+ Create an agent personality first before linking platform accounts.+ </div>+ )}++ {showForm && (+ <form onSubmit={handleSubmit} className="mb-6 p-4 bg-port-card border border-port-border rounded-lg">+ <h3 className="text-md font-semibold text-white mb-4">Register New Account</h3>++ <div className="grid grid-cols-2 gap-4 mb-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Agent</label>+ <select+ value={formData.agentId}+ onChange={(e) => setFormData({ ...formData, agentId: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ required+ >+ <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">Platform</label>+ <select+ value={formData.platform}+ onChange={(e) => setFormData({ ...formData, platform: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ >+ {PLATFORM_TYPES.map(platform => (+ <option key={platform.value} value={platform.value}>+ {platform.icon} {platform.label}+ </option>+ ))}+ </select>+ </div>+ </div>++ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Account Name</label>+ <input+ type="text"+ value={formData.name}+ onChange={(e) => setFormData({ ...formData, name: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ placeholder="Display name on platform"+ required+ />+ </div>++ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Bio/Description</label>+ <textarea+ value={formData.description}+ onChange={(e) => setFormData({ ...formData, description: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white h-20"+ placeholder="Brief bio for the platform profile..."+ />+ </div>++ <div className="flex gap-2">+ <button+ type="submit"+ className="px-4 py-2 bg-port-success text-white rounded hover:bg-port-success/80"+ >+ Register Account+ </button>+ <button+ type="button"+ onClick={resetForm}+ className="px-4 py-2 bg-port-border text-gray-300 rounded hover:bg-port-border/80"+ >+ Cancel+ </button>+ </div>+ </form>+ )}++ {testResult && (+ <div className={`mb-4 p-4 rounded border ${+ testResult.success+ ? 'bg-port-success/20 border-port-success/50 text-port-success'+ : 'bg-port-error/20 border-port-error/50 text-port-error'+ }`}>+ <p>{testResult.message}</p>+ {testResult.claimUrl && (+ <div className="mt-2">+ <a+ href={testResult.claimUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-port-accent underline"+ >+ {testResult.claimUrl}+ </a>+ <button+ onClick={() => handleClaim(testResult.accountId)}+ className="ml-4 px-3 py-1 bg-port-accent text-white rounded text-sm"+ >+ I've claimed it+ </button>+ </div>+ )}+ </div>+ )}++ {accounts.length === 0 ? (+ <div className="text-center py-8 text-gray-400">+ <p className="text-lg mb-2">No platform accounts</p>+ <p className="text-sm">Link an agent to a social platform to get started</p>+ </div>+ ) : (+ <div className="grid gap-4">+ {accounts.map(account => {+ const statusConfig = ACCOUNT_STATUSES[account.status] || ACCOUNT_STATUSES.error;+ const platform = PLATFORM_TYPES.find(p => p.value === account.platform);++ return (+ <div+ key={account.id}+ className="p-4 bg-port-card border border-port-border rounded-lg"+ >+ <div className="flex items-start justify-between">+ <div>+ <div className="flex items-center gap-2 mb-1">+ <span className="text-xl">{platform?.icon || '🔗'}</span>+ <h3 className="font-semibold text-white">+ {account.credentials.username}+ </h3>+ <span className={`text-xs px-2 py-0.5 rounded ${statusConfig.bgColor} ${statusConfig.color}`}>+ {statusConfig.label}+ </span>+ </div>+ <p className="text-sm text-gray-400">+ {platform?.label} • Agent: {getAgentName(account.agentId)}+ </p>+ {account.lastActivity && (+ <p className="text-xs text-gray-500 mt-1">+ Last activity: {new Date(account.lastActivity).toLocaleString()}+ </p>+ )}+ {account.platformData?.claimUrl && account.status === 'pending' && (+ <div className="mt-2 text-sm">+ <a+ href={account.platformData.claimUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-port-accent underline"+ >+ Claim URL+ </a>+ </div>+ )}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => handleTest(account.id)}+ disabled={testingId === account.id}+ className="px-3 py-1 text-xs bg-port-accent/20 text-port-accent rounded hover:bg-port-accent/30 disabled:opacity-50"+ >+ {testingId === account.id ? 'Testing...' : 'Test'}+ </button>+ {account.status === 'pending' && (+ <button+ onClick={() => handleClaim(account.id)}+ className="px-3 py-1 text-xs bg-port-success/20 text-port-success rounded hover:bg-port-success/30"+ >+ Mark Claimed+ </button>+ )}+ <button+ onClick={() => handleDelete(account.id)}+ className="px-3 py-1 text-xs bg-port-error/20 text-port-error rounded hover:bg-port-error/30"+ >+ Delete+ </button>+ </div>+ </div>+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/agents/tabs/ActivityTab.jsx b/client/src/components/agents/tabs/ActivityTab.jsxnew file mode 100644index 0000000000..2ccd98e48e--- /dev/null+++ b/client/src/components/agents/tabs/ActivityTab.jsx@@ -0,0 +1,183 @@+import { useState, useEffect, useCallback } from 'react';+import * as api from '../../../services/api';+import { ACTION_TYPES } from '../constants';++export default function ActivityTab() {+ const [activities, setActivities] = useState([]);+ const [agents, setAgents] = useState([]);+ const [loading, setLoading] = useState(true);+ const [filter, setFilter] = useState({ agentId: '', action: '' });+ const [hasMore, setHasMore] = useState(true);++ const fetchData = useCallback(async () => {+ const [activitiesData, agentsData] = await Promise.all([+ api.getAgentActivities(50, filter.agentId ? [filter.agentId] : null, filter.action || null),+ api.getAgentPersonalities()+ ]);+ setActivities(activitiesData);+ setAgents(agentsData);+ setHasMore(activitiesData.length >= 50);+ setLoading(false);+ }, [filter]);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ const loadMore = async () => {+ if (activities.length === 0) return;++ const lastTimestamp = activities[activities.length - 1].timestamp;+ const moreData = await api.getAgentActivityTimeline(+ 50,+ filter.agentId ? [filter.agentId] : null,+ lastTimestamp+ );++ if (moreData.length < 50) {+ setHasMore(false);+ }++ setActivities(prev => [...prev, ...moreData]);+ };++ const getAgentInfo = (agentId) => {+ const agent = agents.find(a => a.id === agentId);+ return agent || { name: 'Unknown', avatar: { emoji: '❓' } };+ };++ const getActionIcon = (action) => {+ const actionType = ACTION_TYPES.find(a => a.value === action);+ return actionType?.icon || '📋';+ };++ const getStatusStyle = (status) => {+ switch (status) {+ case 'completed':+ return 'bg-port-success/20 text-port-success';+ case 'started':+ return 'bg-port-accent/20 text-port-accent';+ case 'failed':+ return 'bg-port-error/20 text-port-error';+ default:+ return 'bg-port-border text-gray-400';+ }+ };++ if (loading) {+ return <div className="p-4 text-gray-400">Loading activity...</div>;+ }++ return (+ <div className="p-4">+ <div className="flex justify-between items-center mb-4">+ <h2 className="text-lg font-semibold text-white">Activity Log</h2>+ <div className="flex gap-2">+ <select+ value={filter.agentId}+ onChange={(e) => setFilter({ ...filter, agentId: e.target.value })}+ className="px-3 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ >+ <option value="">All Agents</option>+ {agents.map(agent => (+ <option key={agent.id} value={agent.id}>+ {agent.avatar?.emoji} {agent.name}+ </option>+ ))}+ </select>+ <select+ value={filter.action}+ onChange={(e) => setFilter({ ...filter, action: e.target.value })}+ className="px-3 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ >+ <option value="">All Actions</option>+ {ACTION_TYPES.map(action => (+ <option key={action.value} value={action.value}>+ {action.icon} {action.label}+ </option>+ ))}+ </select>+ <button+ onClick={fetchData}+ className="px-3 py-1 bg-port-border text-gray-300 rounded text-sm hover:bg-port-border/80"+ >+ Refresh+ </button>+ </div>+ </div>++ {activities.length === 0 ? (+ <div className="text-center py-8 text-gray-400">+ <p className="text-lg mb-2">No activity yet</p>+ <p className="text-sm">Agent actions will appear here</p>+ </div>+ ) : (+ <>+ <div className="space-y-2">+ {activities.map((activity, index) => {+ const agent = getAgentInfo(activity.agentId);++ return (+ <div+ key={`${activity.id}-${index}`}+ className="p-3 bg-port-card border border-port-border rounded-lg"+ >+ <div className="flex items-center gap-3">+ <div+ className="w-8 h-8 rounded-full flex items-center justify-center text-lg"+ style={{ backgroundColor: agent.avatar?.color || '#3b82f6' }}+ >+ {agent.avatar?.emoji || '🤖'}+ </div>+ <div className="flex-1">+ <div className="flex items-center gap-2">+ <span className="text-white font-medium">{agent.name}</span>+ <span className="text-gray-500">•</span>+ <span className="text-lg">{getActionIcon(activity.action)}</span>+ <span className="text-gray-300">{activity.action}</span>+ <span className={`text-xs px-2 py-0.5 rounded ${getStatusStyle(activity.status)}`}>+ {activity.status}+ </span>+ </div>+ <div className="text-xs text-gray-500 mt-1">+ {new Date(activity.timestamp).toLocaleString()}+ {activity.scheduleId && (+ <span className="ml-2">• Scheduled</span>+ )}+ </div>+ </div>+ {activity.result && (+ <div className="text-sm text-gray-400">+ {typeof activity.result === 'string'+ ? activity.result.slice(0, 50)+ : JSON.stringify(activity.result).slice(0, 50)}+ {(typeof activity.result === 'string' ? activity.result.length : JSON.stringify(activity.result).length) > 50 && '...'}+ </div>+ )}+ {activity.error && (+ <div className="text-sm text-port-error">+ {activity.error.slice(0, 50)}+ {activity.error.length > 50 && '...'}+ </div>+ )}+ </div>+ </div>+ );+ })}+ </div>++ {hasMore && (+ <div className="mt-4 text-center">+ <button+ onClick={loadMore}+ className="px-4 py-2 bg-port-border text-gray-300 rounded hover:bg-port-border/80"+ >+ Load More+ </button>+ </div>+ )}+ </>+ )}+ </div>+ );+}diff --git a/client/src/components/agents/tabs/ConfigTab.jsx b/client/src/components/agents/tabs/ConfigTab.jsxnew file mode 100644index 0000000000..d303035f47--- /dev/null+++ b/client/src/components/agents/tabs/ConfigTab.jsx@@ -0,0 +1,160 @@+import { useState, useEffect } from 'react';+import * as api from '../../../services/api';++export default function ConfigTab() {+ const [stats, setStats] = useState(null);+ const [agents, setAgents] = useState([]);+ const [accounts, setAccounts] = useState([]);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ const fetchData = async () => {+ const [agentsData, accountsData, scheduleStats] = await Promise.all([+ api.getAgentPersonalities(),+ api.getPlatformAccounts(),+ api.getScheduleStats()+ ]);+ setAgents(agentsData);+ setAccounts(accountsData);+ setStats(scheduleStats);+ setLoading(false);+ };+ fetchData();+ }, []);++ if (loading) {+ return <div className="p-4 text-gray-400">Loading config...</div>;+ }++ const enabledAgents = agents.filter(a => a.enabled).length;+ const activeAccounts = accounts.filter(a => a.status === 'active').length;++ return (+ <div className="p-4">+ <h2 className="text-lg font-semibold text-white mb-4">Configuration</h2>++ {/* Overview Stats */}+ <div className="grid grid-cols-4 gap-4 mb-6">+ <div className="p-4 bg-port-card border border-port-border rounded-lg">+ <div className="text-2xl font-bold text-white">{agents.length}</div>+ <div className="text-sm text-gray-400">Total Agents</div>+ <div className="text-xs text-port-success">{enabledAgents} enabled</div>+ </div>+ <div className="p-4 bg-port-card border border-port-border rounded-lg">+ <div className="text-2xl font-bold text-white">{accounts.length}</div>+ <div className="text-sm text-gray-400">Platform Accounts</div>+ <div className="text-xs text-port-success">{activeAccounts} active</div>+ </div>+ <div className="p-4 bg-port-card border border-port-border rounded-lg">+ <div className="text-2xl font-bold text-white">{stats?.total || 0}</div>+ <div className="text-sm text-gray-400">Schedules</div>+ <div className="text-xs text-port-success">{stats?.active || 0} running</div>+ </div>+ <div className="p-4 bg-port-card border border-port-border rounded-lg">+ <div className="text-2xl font-bold text-white">{stats?.totalRuns || 0}</div>+ <div className="text-sm text-gray-400">Total Runs</div>+ <div className="text-xs text-gray-500">all time</div>+ </div>+ </div>++ {/* Schedule Actions Breakdown */}+ {stats?.byAction && Object.keys(stats.byAction).length > 0 && (+ <div className="mb-6">+ <h3 className="text-md font-semibold text-white mb-3">Schedules by Action</h3>+ <div className="grid grid-cols-4 gap-2">+ {Object.entries(stats.byAction).map(([action, count]) => (+ <div key={action} className="p-3 bg-port-card border border-port-border rounded">+ <div className="text-lg font-bold text-white">{count}</div>+ <div className="text-sm text-gray-400 capitalize">{action}</div>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Global Settings */}+ <div className="mb-6">+ <h3 className="text-md font-semibold text-white mb-3">Global Settings</h3>+ <div className="p-4 bg-port-card border border-port-border rounded-lg">+ <p className="text-gray-400 text-sm mb-4">+ Global agent settings will be available in a future update.+ </p>+ <div className="space-y-3 opacity-50">+ <div className="flex items-center justify-between">+ <span className="text-gray-300">Default Rate Limit (per day)</span>+ <input+ type="number"+ defaultValue={50}+ className="w-24 px-3 py-1 bg-port-bg border border-port-border rounded text-white text-right"+ disabled+ />+ </div>+ <div className="flex items-center justify-between">+ <span className="text-gray-300">Activity Log Retention (days)</span>+ <input+ type="number"+ defaultValue={30}+ className="w-24 px-3 py-1 bg-port-bg border border-port-border rounded text-white text-right"+ disabled+ />+ </div>+ <div className="flex items-center justify-between">+ <span className="text-gray-300">Enable Socket.IO Updates</span>+ <label className="relative inline-flex items-center cursor-not-allowed">+ <input type="checkbox" defaultChecked disabled className="sr-only peer" />+ <div className="w-11 h-6 bg-port-border rounded-full peer peer-checked:bg-port-accent"></div>+ </label>+ </div>+ </div>+ </div>+ </div>++ {/* Moltbook Rate Limits Info */}+ <div className="mb-6">+ <h3 className="text-md font-semibold text-white mb-3">Platform Rate Limits</h3>+ <div className="p-4 bg-port-card border border-port-border rounded-lg">+ <h4 className="text-white font-medium mb-2">📚 Moltbook</h4>+ <div className="grid grid-cols-3 gap-4 text-sm">+ <div>+ <div className="text-gray-400">Posts</div>+ <div className="text-white">1 per 30 minutes</div>+ </div>+ <div>+ <div className="text-gray-400">Comments</div>+ <div className="text-white">1 per 20 seconds, 50/day</div>+ </div>+ <div>+ <div className="text-gray-400">Votes</div>+ <div className="text-white">1 per second, 200/day</div>+ </div>+ </div>+ </div>+ </div>++ {/* Documentation Links */}+ <div>+ <h3 className="text-md font-semibold text-white mb-3">Documentation</h3>+ <div className="p-4 bg-port-card border border-port-border rounded-lg">+ <ul className="space-y-2 text-sm">+ <li>+ <span className="text-gray-400">• Agent Personalities:</span>{' '}+ <span className="text-gray-300">Define unique AI personalities with custom tones and topics</span>+ </li>+ <li>+ <span className="text-gray-400">• Platform Accounts:</span>{' '}+ <span className="text-gray-300">Link agents to social platforms via API</span>+ </li>+ <li>+ <span className="text-gray-400">• Automation Schedules:</span>{' '}+ <span className="text-gray-300">Configure cron, interval, or random timing for actions</span>+ </li>+ <li>+ <span className="text-gray-400">• Activity Log:</span>{' '}+ <span className="text-gray-300">Monitor all agent actions with filtering</span>+ </li>+ </ul>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/agents/tabs/PersonalitiesTab.jsx b/client/src/components/agents/tabs/PersonalitiesTab.jsxnew file mode 100644index 0000000000..796b75999f--- /dev/null+++ b/client/src/components/agents/tabs/PersonalitiesTab.jsx@@ -0,0 +1,448 @@+import { useState, useEffect, useCallback } from 'react';+import { Sparkles } from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';+import { PERSONALITY_STYLES, DEFAULT_PERSONALITY, DEFAULT_AVATAR } from '../constants';++export default function PersonalitiesTab({ onRefresh }) {+ const [agents, setAgents] = useState([]);+ const [loading, setLoading] = useState(true);+ const [showForm, setShowForm] = useState(false);+ const [editingAgent, setEditingAgent] = useState(null);+ const [formData, setFormData] = useState({+ name: '',+ description: '',+ userId: 'default',+ personality: { ...DEFAULT_PERSONALITY },+ avatar: { ...DEFAULT_AVATAR },+ enabled: true+ });++ // AI generation state+ const [providers, setProviders] = useState([]);+ const [selectedProviderId, setSelectedProviderId] = useState('');+ const [selectedModel, setSelectedModel] = useState('');+ const [generating, setGenerating] = useState(false);++ // Raw text state for comma-separated fields (parsed on blur)+ const [topicsText, setTopicsText] = useState('');+ const [quirksText, setQuirksText] = useState('');++ const fetchAgents = useCallback(async () => {+ const data = await api.getAgentPersonalities();+ setAgents(data);+ setLoading(false);+ }, []);++ const fetchProviders = useCallback(async () => {+ const data = await api.getProviders();+ setProviders((data.providers || []).filter(p => p.enabled));+ }, []);++ useEffect(() => {+ fetchAgents();+ fetchProviders();+ }, [fetchAgents, fetchProviders]);++ // Sync raw text fields when formData changes (edit, generate, reset)+ useEffect(() => {+ setTopicsText(formData.personality.topics.join(', '));+ setQuirksText(formData.personality.quirks.join(', '));+ }, [formData.personality.topics, formData.personality.quirks]);++ // Get available models for selected provider+ const selectedProvider = providers.find(p => p.id === selectedProviderId);+ const availableModels = selectedProvider?.models || [];++ const handleGenerate = async () => {+ setGenerating(true);+ // Send current form data as seed for AI to build upon+ // Use raw text values in case user hasn't blurred the fields yet+ const seedData = {+ name: formData.name.trim(),+ description: formData.description.trim(),+ personality: {+ style: formData.personality.style,+ tone: formData.personality.tone,+ topics: topicsText.split(',').map(t => t.trim()).filter(Boolean),+ quirks: quirksText.split(',').map(t => t.trim()).filter(Boolean),+ promptPrefix: formData.personality.promptPrefix.trim()+ },+ avatar: {+ emoji: formData.avatar.emoji,+ color: formData.avatar.color+ }+ };+ const generated = await api.generateAgentPersonality(+ seedData,+ selectedProviderId || null,+ selectedModel || null+ ).catch(() => null);+ setGenerating(false);++ if (!generated) return;++ // Apply generated data to form (including name if generated)+ setFormData(prev => ({+ ...prev,+ name: generated.name || prev.name,+ description: generated.description || prev.description,+ personality: {+ style: generated.personality?.style || prev.personality.style,+ tone: generated.personality?.tone || prev.personality.tone,+ topics: generated.personality?.topics || prev.personality.topics,+ quirks: generated.personality?.quirks || prev.personality.quirks,+ promptPrefix: generated.personality?.promptPrefix || prev.personality.promptPrefix+ },+ avatar: {+ emoji: generated.avatar?.emoji || prev.avatar.emoji,+ color: generated.avatar?.color || prev.avatar.color+ }+ }));++ toast.success(`Generated: ${generated.name || 'personality'}`);+ };++ const resetForm = () => {+ setFormData({+ name: '',+ description: '',+ userId: 'default',+ personality: { ...DEFAULT_PERSONALITY },+ avatar: { ...DEFAULT_AVATAR },+ enabled: true+ });+ setEditingAgent(null);+ setShowForm(false);+ };++ const handleEdit = (agent) => {+ setFormData({+ name: agent.name,+ description: agent.description || '',+ userId: agent.userId,+ personality: { ...DEFAULT_PERSONALITY, ...agent.personality },+ avatar: { ...DEFAULT_AVATAR, ...agent.avatar },+ enabled: agent.enabled+ });+ setEditingAgent(agent);+ setShowForm(true);+ };++ const handleSubmit = async (e) => {+ e.preventDefault();++ // Build clean data with parsed topics/quirks (in case user hasn't blurred)+ const submitData = {+ ...formData,+ personality: {+ ...formData.personality,+ topics: topicsText.split(',').map(t => t.trim()).filter(Boolean),+ quirks: quirksText.split(',').map(t => t.trim()).filter(Boolean)+ }+ };++ if (editingAgent) {+ await api.updateAgentPersonality(editingAgent.id, submitData);+ } else {+ await api.createAgentPersonality(submitData);+ }++ resetForm();+ fetchAgents();+ onRefresh?.();+ };++ const handleDelete = async (id) => {+ await api.deleteAgentPersonality(id);+ fetchAgents();+ onRefresh?.();+ };++ const handleToggle = async (id, enabled) => {+ await api.toggleAgentPersonality(id, enabled);+ fetchAgents();+ };++ const updatePersonality = (field, value) => {+ setFormData(prev => ({+ ...prev,+ personality: { ...prev.personality, [field]: value }+ }));+ };++ if (loading) {+ return <div className="p-4 text-gray-400">Loading agents...</div>;+ }++ return (+ <div className="p-4">+ <div className="flex justify-between items-center mb-4">+ <h2 className="text-lg font-semibold text-white">Agent Personalities</h2>+ <button+ onClick={() => setShowForm(!showForm)}+ className="px-4 py-2 bg-port-accent text-white rounded hover:bg-port-accent/80"+ >+ {showForm ? 'Cancel' : '+ New Agent'}+ </button>+ </div>++ {showForm && (+ <form onSubmit={handleSubmit} className="mb-6 p-4 bg-port-card border border-port-border rounded-lg">+ <h3 className="text-md font-semibold text-white mb-4">+ {editingAgent ? 'Edit Agent' : 'Create New Agent'}+ </h3>++ {/* AI Generation Section - at top */}+ {!editingAgent && (+ <div className="mb-4 p-3 bg-port-bg border border-port-accent/30 rounded-lg">+ <div className="flex items-center gap-2 mb-3">+ <Sparkles size={16} className="text-port-accent" />+ <span className="text-sm font-medium text-white">Generate with AI</span>+ </div>+ <div className="flex items-end gap-3">+ <div className="flex-1">+ <label className="block text-xs text-gray-400 mb-1">Provider</label>+ <select+ value={selectedProviderId}+ onChange={(e) => {+ setSelectedProviderId(e.target.value);+ setSelectedModel('');+ }}+ disabled={generating}+ className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"+ >+ <option value="">Default (active)</option>+ {providers.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ </div>+ <div className="flex-1">+ <label className="block text-xs text-gray-400 mb-1">Model</label>+ <select+ value={selectedModel}+ onChange={(e) => setSelectedModel(e.target.value)}+ disabled={generating}+ className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"+ >+ <option value="">Default</option>+ {availableModels.map(m => (+ <option key={m} value={m}>{m}</option>+ ))}+ </select>+ </div>+ <button+ type="button"+ onClick={handleGenerate}+ disabled={generating}+ className="px-4 py-1.5 bg-port-accent text-white rounded hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"+ >+ {generating ? (+ <>+ <span className="animate-spin">⚡</span>+ Generating...+ </>+ ) : (+ <>+ <Sparkles size={14} />+ Generate+ </>+ )}+ </button>+ </div>+ <p className="text-xs text-gray-500 mt-2">+ Generate a complete personality including name, style, topics, and avatar+ </p>+ </div>+ )}++ <div className="grid grid-cols-2 gap-4 mb-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Name</label>+ <input+ type="text"+ value={formData.name}+ onChange={(e) => setFormData({ ...formData, name: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ required+ />+ </div>+ <div>+ <label className="block text-sm text-gray-400 mb-1">Style</label>+ <select+ value={formData.personality.style}+ onChange={(e) => updatePersonality('style', e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ >+ {PERSONALITY_STYLES.map(style => (+ <option key={style.value} value={style.value}>{style.label}</option>+ ))}+ </select>+ </div>+ </div>++ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Description</label>+ <textarea+ value={formData.description}+ onChange={(e) => setFormData({ ...formData, description: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white h-20"+ placeholder="Brief description of this agent's purpose..."+ />+ </div>++ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Tone</label>+ <input+ type="text"+ value={formData.personality.tone}+ onChange={(e) => updatePersonality('tone', e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ placeholder="e.g., friendly but informative"+ />+ </div>++ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Topics (comma-separated)</label>+ <input+ type="text"+ value={topicsText}+ onChange={(e) => setTopicsText(e.target.value)}+ onBlur={() => updatePersonality('topics', topicsText.split(',').map(t => t.trim()).filter(Boolean))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ placeholder="e.g., technology, AI, philosophy"+ />+ </div>++ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Quirks (comma-separated)</label>+ <input+ type="text"+ value={quirksText}+ onChange={(e) => setQuirksText(e.target.value)}+ onBlur={() => updatePersonality('quirks', quirksText.split(',').map(t => t.trim()).filter(Boolean))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ placeholder="e.g., uses metaphors, asks follow-up questions"+ />+ </div>++ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Prompt Prefix</label>+ <textarea+ value={formData.personality.promptPrefix}+ onChange={(e) => updatePersonality('promptPrefix', e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white h-24 font-mono text-sm"+ placeholder="Custom instructions injected into AI prompts..."+ />+ </div>++ <div className="flex items-center gap-4 mb-4">+ <label className="block text-sm text-gray-400">Avatar Emoji</label>+ <input+ type="text"+ value={formData.avatar.emoji || ''}+ onChange={(e) => setFormData({ ...formData, avatar: { ...formData.avatar, emoji: e.target.value } })}+ className="w-16 px-3 py-2 bg-port-bg border border-port-border rounded text-white text-center"+ maxLength={2}+ />+ <label className="block text-sm text-gray-400">Color</label>+ <input+ type="color"+ value={formData.avatar.color || '#3b82f6'}+ onChange={(e) => setFormData({ ...formData, avatar: { ...formData.avatar, color: e.target.value } })}+ className="w-12 h-8 border border-port-border rounded cursor-pointer"+ />+ </div>++ <div className="flex gap-2">+ <button+ type="submit"+ className="px-4 py-2 bg-port-success text-white rounded hover:bg-port-success/80"+ >+ {editingAgent ? 'Update Agent' : 'Create Agent'}+ </button>+ <button+ type="button"+ onClick={resetForm}+ className="px-4 py-2 bg-port-border text-gray-300 rounded hover:bg-port-border/80"+ >+ Cancel+ </button>+ </div>+ </form>+ )}++ {agents.length === 0 ? (+ <div className="text-center py-8 text-gray-400">+ <p className="text-lg mb-2">No agents yet</p>+ <p className="text-sm">Create your first AI agent to get started</p>+ </div>+ ) : (+ <div className="grid gap-4">+ {agents.map(agent => (+ <div+ key={agent.id}+ className={`p-4 bg-port-card border rounded-lg ${agent.enabled ? 'border-port-border' : 'border-port-border/50 opacity-60'}`}+ >+ <div className="flex items-start justify-between">+ <div className="flex items-center gap-3">+ <div+ className="w-12 h-12 rounded-full flex items-center justify-center text-2xl"+ style={{ backgroundColor: agent.avatar?.color || '#3b82f6' }}+ >+ {agent.avatar?.emoji || '🤖'}+ </div>+ <div>+ <h3 className="font-semibold text-white">{agent.name}</h3>+ <p className="text-sm text-gray-400">{agent.description || 'No description'}</p>+ <div className="flex gap-2 mt-1">+ <span className="text-xs px-2 py-0.5 bg-port-accent/20 text-port-accent rounded">+ {PERSONALITY_STYLES.find(s => s.value === agent.personality?.style)?.label || agent.personality?.style}+ </span>+ {agent.personality?.topics?.slice(0, 3).map(topic => (+ <span key={topic} className="text-xs px-2 py-0.5 bg-port-border text-gray-300 rounded">+ {topic}+ </span>+ ))}+ </div>+ </div>+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => handleToggle(agent.id, !agent.enabled)}+ className={`px-3 py-1 text-xs rounded ${+ agent.enabled+ ? 'bg-port-success/20 text-port-success'+ : 'bg-port-border text-gray-400'+ }`}+ >+ {agent.enabled ? 'Enabled' : 'Disabled'}+ </button>+ <button+ onClick={() => handleEdit(agent)}+ className="px-3 py-1 text-xs bg-port-border text-gray-300 rounded hover:bg-port-border/80"+ >+ Edit+ </button>+ <button+ onClick={() => handleDelete(agent.id)}+ className="px-3 py-1 text-xs bg-port-error/20 text-port-error rounded hover:bg-port-error/30"+ >+ Delete+ </button>+ </div>+ </div>+ {agent.personality?.promptPrefix && (+ <div className="mt-3 p-2 bg-port-bg rounded text-xs text-gray-400 font-mono">+ {agent.personality.promptPrefix.slice(0, 200)}+ {agent.personality.promptPrefix.length > 200 && '...'}+ </div>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/agents/tabs/SchedulesTab.jsx b/client/src/components/agents/tabs/SchedulesTab.jsxnew file mode 100644index 0000000000..176f099159--- /dev/null+++ b/client/src/components/agents/tabs/SchedulesTab.jsx@@ -0,0 +1,413 @@+import { useState, useEffect, useCallback } from 'react';+import * as api from '../../../services/api';+import { ACTION_TYPES, SCHEDULE_TYPES, CRON_PRESETS, INTERVAL_PRESETS } from '../constants';++export default function SchedulesTab({ onRefresh }) {+ const [schedules, setSchedules] = useState([]);+ const [agents, setAgents] = useState([]);+ const [accounts, setAccounts] = useState([]);+ const [stats, setStats] = useState(null);+ const [loading, setLoading] = useState(true);+ const [showForm, setShowForm] = useState(false);+ const [formData, setFormData] = useState({+ agentId: '',+ accountId: '',+ action: { type: 'heartbeat', params: {} },+ schedule: { type: 'interval', intervalMs: 4 * 60 * 60 * 1000 },+ rateLimit: { maxPerDay: 50 },+ enabled: true+ });+ const [runningId, setRunningId] = useState(null);++ const fetchData = useCallback(async () => {+ const [schedulesData, agentsData, accountsData, statsData] = await Promise.all([+ api.getAutomationSchedules(),+ api.getAgentPersonalities(),+ api.getPlatformAccounts(),+ api.getScheduleStats()+ ]);+ setSchedules(schedulesData);+ setAgents(agentsData);+ setAccounts(accountsData);+ setStats(statsData);+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ const resetForm = () => {+ setFormData({+ agentId: '',+ accountId: '',+ action: { type: 'heartbeat', params: {} },+ schedule: { type: 'interval', intervalMs: 4 * 60 * 60 * 1000 },+ rateLimit: { maxPerDay: 50 },+ enabled: true+ });+ setShowForm(false);+ };++ const handleAgentChange = (agentId) => {+ setFormData(prev => ({+ ...prev,+ agentId,+ accountId: '' // Reset account when agent changes+ }));+ };++ const handleScheduleTypeChange = (type) => {+ const scheduleDefaults = {+ cron: { type: 'cron', cron: '0 */4 * * *' },+ interval: { type: 'interval', intervalMs: 4 * 60 * 60 * 1000 },+ random: { type: 'random', randomWindow: { minMs: 60 * 60 * 1000, maxMs: 4 * 60 * 60 * 1000 } }+ };+ setFormData(prev => ({+ ...prev,+ schedule: scheduleDefaults[type]+ }));+ };++ const handleSubmit = async (e) => {+ e.preventDefault();+ await api.createAutomationSchedule(formData);+ resetForm();+ fetchData();+ onRefresh?.();+ };++ const handleDelete = async (id) => {+ await api.deleteAutomationSchedule(id);+ fetchData();+ onRefresh?.();+ };++ const handleToggle = async (id, enabled) => {+ await api.toggleAutomationSchedule(id, enabled);+ fetchData();+ };++ const handleRunNow = async (id) => {+ setRunningId(id);+ await api.runAutomationScheduleNow(id);+ setRunningId(null);+ fetchData();+ };++ const getAgentName = (agentId) => {+ const agent = agents.find(a => a.id === agentId);+ return agent?.name || 'Unknown';+ };++ const getAccountName = (accountId) => {+ const account = accounts.find(a => a.id === accountId);+ return account?.credentials?.username || 'Unknown';+ };++ const filteredAccounts = accounts.filter(a => a.agentId === formData.agentId);++ const formatSchedule = (schedule) => {+ if (schedule.type === 'cron') {+ const preset = CRON_PRESETS.find(p => p.value === schedule.cron);+ return preset?.label || schedule.cron;+ }+ if (schedule.type === 'interval') {+ const preset = INTERVAL_PRESETS.find(p => p.value === schedule.intervalMs);+ return preset?.label || `${Math.round(schedule.intervalMs / 60000)} min`;+ }+ if (schedule.type === 'random') {+ const minHrs = Math.round(schedule.randomWindow.minMs / 3600000 * 10) / 10;+ const maxHrs = Math.round(schedule.randomWindow.maxMs / 3600000 * 10) / 10;+ return `${minHrs}-${maxHrs} hours`;+ }+ return 'Unknown';+ };++ if (loading) {+ return <div className="p-4 text-gray-400">Loading schedules...</div>;+ }++ return (+ <div className="p-4">+ <div className="flex justify-between items-center mb-4">+ <div>+ <h2 className="text-lg font-semibold text-white">Automation Schedules</h2>+ {stats && (+ <p className="text-sm text-gray-400">+ {stats.enabled} enabled / {stats.total} total • {stats.totalRuns} runs+ </p>+ )}+ </div>+ <button+ onClick={() => setShowForm(!showForm)}+ className="px-4 py-2 bg-port-accent text-white rounded hover:bg-port-accent/80"+ disabled={accounts.filter(a => a.status === 'active').length === 0}+ >+ {showForm ? 'Cancel' : '+ New Schedule'}+ </button>+ </div>++ {accounts.filter(a => a.status === 'active').length === 0 && (+ <div className="mb-4 p-4 bg-port-warning/20 border border-port-warning/50 rounded text-port-warning">+ You need at least one active platform account to create schedules.+ </div>+ )}++ {showForm && (+ <form onSubmit={handleSubmit} className="mb-6 p-4 bg-port-card border border-port-border rounded-lg">+ <h3 className="text-md font-semibold text-white mb-4">Create Schedule</h3>++ <div className="grid grid-cols-2 gap-4 mb-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Agent</label>+ <select+ value={formData.agentId}+ onChange={(e) => handleAgentChange(e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ required+ >+ <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={formData.accountId}+ onChange={(e) => setFormData({ ...formData, accountId: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ required+ disabled={!formData.agentId}+ >+ <option value="">Select account...</option>+ {filteredAccounts.filter(a => a.status === 'active').map(account => (+ <option key={account.id} value={account.id}>+ {account.credentials.username}+ </option>+ ))}+ </select>+ </div>+ </div>++ <div className="grid grid-cols-2 gap-4 mb-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Action Type</label>+ <select+ value={formData.action.type}+ onChange={(e) => setFormData({ ...formData, action: { type: e.target.value, params: {} } })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ >+ {ACTION_TYPES.map(action => (+ <option key={action.value} value={action.value}>+ {action.icon} {action.label}+ </option>+ ))}+ </select>+ <p className="text-xs text-gray-500 mt-1">+ {ACTION_TYPES.find(a => a.value === formData.action.type)?.description}+ </p>+ </div>+ <div>+ <label className="block text-sm text-gray-400 mb-1">Schedule Type</label>+ <select+ value={formData.schedule.type}+ onChange={(e) => handleScheduleTypeChange(e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ >+ {SCHEDULE_TYPES.map(type => (+ <option key={type.value} value={type.value}>+ {type.label}+ </option>+ ))}+ </select>+ </div>+ </div>++ {formData.schedule.type === 'cron' && (+ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Cron Expression</label>+ <select+ value={formData.schedule.cron}+ onChange={(e) => setFormData({ ...formData, schedule: { ...formData.schedule, cron: e.target.value } })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ >+ {CRON_PRESETS.map(preset => (+ <option key={preset.value} value={preset.value}>+ {preset.label}+ </option>+ ))}+ </select>+ </div>+ )}++ {formData.schedule.type === 'interval' && (+ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Interval</label>+ <select+ value={formData.schedule.intervalMs}+ onChange={(e) => setFormData({ ...formData, schedule: { ...formData.schedule, intervalMs: parseInt(e.target.value) } })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ >+ {INTERVAL_PRESETS.map(preset => (+ <option key={preset.value} value={preset.value}>+ {preset.label}+ </option>+ ))}+ </select>+ </div>+ )}++ {formData.schedule.type === 'random' && (+ <div className="grid grid-cols-2 gap-4 mb-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Min Interval</label>+ <select+ value={formData.schedule.randomWindow?.minMs}+ onChange={(e) => setFormData({+ ...formData,+ schedule: {+ ...formData.schedule,+ randomWindow: { ...formData.schedule.randomWindow, minMs: parseInt(e.target.value) }+ }+ })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ >+ {INTERVAL_PRESETS.map(preset => (+ <option key={preset.value} value={preset.value}>+ {preset.label}+ </option>+ ))}+ </select>+ </div>+ <div>+ <label className="block text-sm text-gray-400 mb-1">Max Interval</label>+ <select+ value={formData.schedule.randomWindow?.maxMs}+ onChange={(e) => setFormData({+ ...formData,+ schedule: {+ ...formData.schedule,+ randomWindow: { ...formData.schedule.randomWindow, maxMs: parseInt(e.target.value) }+ }+ })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ >+ {INTERVAL_PRESETS.map(preset => (+ <option key={preset.value} value={preset.value}>+ {preset.label}+ </option>+ ))}+ </select>+ </div>+ </div>+ )}++ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Max Per Day (rate limit)</label>+ <input+ type="number"+ value={formData.rateLimit.maxPerDay || 50}+ onChange={(e) => setFormData({ ...formData, rateLimit: { ...formData.rateLimit, maxPerDay: parseInt(e.target.value) } })}+ className="w-32 px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ min="1"+ max="1000"+ />+ </div>++ <div className="flex gap-2">+ <button+ type="submit"+ className="px-4 py-2 bg-port-success text-white rounded hover:bg-port-success/80"+ >+ Create Schedule+ </button>+ <button+ type="button"+ onClick={resetForm}+ className="px-4 py-2 bg-port-border text-gray-300 rounded hover:bg-port-border/80"+ >+ Cancel+ </button>+ </div>+ </form>+ )}++ {schedules.length === 0 ? (+ <div className="text-center py-8 text-gray-400">+ <p className="text-lg mb-2">No schedules</p>+ <p className="text-sm">Create a schedule to automate agent actions</p>+ </div>+ ) : (+ <div className="grid gap-4">+ {schedules.map(schedule => {+ const actionType = ACTION_TYPES.find(a => a.value === schedule.action?.type);++ return (+ <div+ key={schedule.id}+ className={`p-4 bg-port-card border rounded-lg ${schedule.enabled ? 'border-port-border' : 'border-port-border/50 opacity-60'}`}+ >+ <div className="flex items-start justify-between">+ <div>+ <div className="flex items-center gap-2 mb-1">+ <span className="text-xl">{actionType?.icon || '📅'}</span>+ <h3 className="font-semibold text-white">+ {actionType?.label || schedule.action?.type}+ </h3>+ {schedule.isActive && (+ <span className="text-xs px-2 py-0.5 rounded bg-port-success/20 text-port-success">+ Active+ </span>+ )}+ </div>+ <p className="text-sm text-gray-400">+ {getAgentName(schedule.agentId)} → {getAccountName(schedule.accountId)}+ </p>+ <p className="text-sm text-gray-500 mt-1">+ {formatSchedule(schedule.schedule)} • Max {schedule.rateLimit?.maxPerDay || '∞'}/day+ </p>+ {schedule.lastRun && (+ <p className="text-xs text-gray-500 mt-1">+ Last run: {new Date(schedule.lastRun).toLocaleString()} ({schedule.runCount} total)+ </p>+ )}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => handleRunNow(schedule.id)}+ disabled={runningId === schedule.id}+ className="px-3 py-1 text-xs bg-port-accent/20 text-port-accent rounded hover:bg-port-accent/30 disabled:opacity-50"+ >+ {runningId === schedule.id ? 'Running...' : 'Run Now'}+ </button>+ <button+ onClick={() => handleToggle(schedule.id, !schedule.enabled)}+ className={`px-3 py-1 text-xs rounded ${+ schedule.enabled+ ? 'bg-port-success/20 text-port-success'+ : 'bg-port-border text-gray-400'+ }`}+ >+ {schedule.enabled ? 'Enabled' : 'Disabled'}+ </button>+ <button+ onClick={() => handleDelete(schedule.id)}+ className="px-3 py-1 text-xs bg-port-error/20 text-port-error rounded hover:bg-port-error/30"+ >+ Delete+ </button>+ </div>+ </div>+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/brain/constants.js b/client/src/components/brain/constants.jsindex 9ded360259..66b31b4fc2 100644--- a/client/src/components/brain/constants.js+++ b/client/src/components/brain/constants.js@@ -1,8 +1,9 @@-import { MessageSquare, Database, Calendar, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings } from 'lucide-react';+import { MessageSquare, Database, Calendar, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings, Link2 } from 'lucide-react';// Main navigation tabsexport const TABS = [{ id: 'inbox', label: 'Inbox', icon: MessageSquare },+ { id: 'links', label: 'Links', icon: Link2 },{ id: 'memory', label: 'Memory', icon: Database },{ id: 'digest', label: 'Digest', icon: Calendar },{ id: 'trust', label: 'Trust', icon: Shield },diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsxindex f7e6438fec..eadb7200b1 100644--- a/client/src/components/cos/tabs/TasksTab.jsx+++ b/client/src/components/cos/tabs/TasksTab.jsx@@ -164,17 +164,21 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {description: newTask.description,context: newTask.context}).catch(err => {- toast.error(`Enhancement failed: ${err.message}`);- setIsEnhancing(false);+ // Enhancement failed - fall back to original description+ toast('Enhancement failed, using original description', { icon: '⚠️' });+ console.warn('Task enhancement failed:', err.message);return null;});- if (!enhanceResult) {- return;+ if (enhanceResult?.enhancedDescription?.trim()) {+ finalDescription = enhanceResult.enhancedDescription;+ toast.success('Prompt enhanced');+ } else if (enhanceResult) {+ // Enhancement returned empty result - fall back to original+ toast('Enhancement returned empty result, using original', { icon: '⚠️' });}+ // If enhanceResult is null (error), we already showed warning and fall back to original- finalDescription = enhanceResult.enhancedDescription;- toast.success('Prompt enhanced');setIsEnhancing(false);}diff --git a/client/src/pages/Agents.jsx b/client/src/pages/Agents.jsxnew file mode 100644index 0000000000..b69e43c9fe--- /dev/null+++ b/client/src/pages/Agents.jsx@@ -0,0 +1,124 @@+import { useState, useEffect, useCallback } from 'react';+import { useParams, useNavigate } from 'react-router-dom';+import * as api from '../services/api';+import {+ TABS,+ PersonalitiesTab,+ AccountsTab,+ SchedulesTab,+ ActivityTab,+ ConfigTab+} from '../components/agents';++export default function Agents() {+ const { tab } = useParams();+ const navigate = useNavigate();+ const activeTab = tab || 'personalities';++ const [stats, setStats] = useState({+ agents: 0,+ accounts: 0,+ schedules: 0+ });+ const [loading, setLoading] = useState(true);++ const fetchStats = useCallback(async () => {+ const [agents, accounts, scheduleStats] = await Promise.all([+ api.getAgentPersonalities(),+ api.getPlatformAccounts(),+ api.getScheduleStats()+ ]);+ setStats({+ agents: agents.length,+ accounts: accounts.length,+ schedules: scheduleStats.total+ });+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchStats();+ }, [fetchStats]);++ const handleTabChange = (tabId) => {+ navigate(`/agents/${tabId}`);+ };++ const renderTabContent = () => {+ switch (activeTab) {+ case 'personalities':+ return <PersonalitiesTab onRefresh={fetchStats} />;+ case 'accounts':+ return <AccountsTab onRefresh={fetchStats} />;+ case 'schedules':+ return <SchedulesTab onRefresh={fetchStats} />;+ case 'activity':+ return <ActivityTab />;+ case 'config':+ return <ConfigTab />;+ default:+ return <PersonalitiesTab onRefresh={fetchStats} />;+ }+ };++ const getTabBadge = (tabId) => {+ if (loading) return null;+ switch (tabId) {+ case 'personalities':+ return stats.agents > 0 ? stats.agents : null;+ case 'accounts':+ return stats.accounts > 0 ? stats.accounts : null;+ case 'schedules':+ return stats.schedules > 0 ? stats.schedules : null;+ default:+ return null;+ }+ };++ return (+ <div className="flex flex-col h-full">+ {/* Header */}+ <div className="border-b border-port-border px-6 py-4">+ <h1 className="text-2xl font-bold text-white">Agents</h1>+ <p className="text-sm text-gray-400 mt-1">+ Manage AI agent personalities and their platform automation+ </p>+ </div>++ {/* Tab Navigation */}+ <div className="flex gap-1 px-4 py-2 border-b border-port-border bg-port-card/50">+ {TABS.map(tabDef => {+ const badge = getTabBadge(tabDef.id);+ const isActive = activeTab === tabDef.id;++ return (+ <button+ key={tabDef.id}+ onClick={() => handleTabChange(tabDef.id)}+ className={`px-4 py-2 rounded-t flex items-center gap-2 transition-colors ${+ isActive+ ? 'bg-port-bg text-white border-t border-l border-r border-port-border -mb-px'+ : 'text-gray-400 hover:text-white hover:bg-port-border/30'+ }`}+ >+ <span>{tabDef.icon}</span>+ <span>{tabDef.label}</span>+ {badge && (+ <span className={`text-xs px-1.5 py-0.5 rounded ${+ isActive ? 'bg-port-accent text-white' : 'bg-port-border text-gray-300'+ }`}>+ {badge}+ </span>+ )}+ </button>+ );+ })}+ </div>++ {/* Tab Content */}+ <div className="flex-1 overflow-auto bg-port-bg">+ {renderTabContent()}+ </div>+ </div>+ );+}diff --git a/client/src/pages/Brain.jsx b/client/src/pages/Brain.jsxindex 941e21ee88..790ffcc66d 100644--- a/client/src/pages/Brain.jsx+++ b/client/src/pages/Brain.jsx@@ -9,6 +9,7 @@ import {} from '../components/brain/constants';import InboxTab from '../components/brain/tabs/InboxTab';+import LinksTab from '../components/brain/tabs/LinksTab';import MemoryTab from '../components/brain/tabs/MemoryTab';import DigestTab from '../components/brain/tabs/DigestTab';import TrustTab from '../components/brain/tabs/TrustTab';@@ -47,6 +48,8 @@ export default function Brain() {switch (activeTab) {case 'inbox':return <InboxTab onRefresh={fetchData} settings={settings} />;+ case 'links':+ return <LinksTab onRefresh={fetchData} />;case 'memory':return <MemoryTab onRefresh={fetchData} />;case 'digest':@@ -88,6 +91,9 @@ export default function Brain() {{summary.needsReview} needs review</span>)}+ <span className="text-gray-500">+ {summary.counts?.links || 0} links+ </span><span className="text-gray-500">{summary.counts?.projects || 0} projects</span>diff --git a/server/index.js b/server/index.jsindex c24b62eca9..694782c7ff 100644--- a/server/index.js+++ b/server/index.js@@ -18,6 +18,10 @@ import gitRoutes from './routes/git.js';import usageRoutes from './routes/usage.js';import screenshotsRoutes from './routes/screenshots.js';import agentsRoutes from './routes/agents.js';+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 cosRoutes from './routes/cos.js';import scriptsRoutes from './routes/scripts.js';import memoryRoutes from './routes/memory.js';@@ -35,6 +39,8 @@ import { initTaskLearning } from './services/taskLearning.js';import { recordSession, recordMessages } from './services/usage.js';import { errorEvents } from './lib/errorHandler.js';import './services/subAgentSpawner.js'; // Initialize CoS agent spawner+import * as automationScheduler from './services/automationScheduler.js';+import * as agentActionExecutor from './services/agentActionExecutor.js';import { createAIToolkit } from 'portos-ai-toolkit/server';import { createPortOSProviderRoutes } from './routes/providers.js';import { createPortOSRunsRoutes } from './routes/runs.js';@@ -160,6 +166,12 @@ app.use('/api/commands', commandsRoutes);app.use('/api/git', gitRoutes);app.use('/api/usage', usageRoutes);app.use('/api/screenshots', screenshotsRoutes);+// Agent Personalities feature routes (must be before /api/agents to avoid route conflicts)+app.use('/api/agents/personalities', agentPersonalitiesRoutes);+app.use('/api/agents/accounts', platformAccountsRoutes);+app.use('/api/agents/schedules', automationSchedulesRoutes);+app.use('/api/agents/activity', agentActivityRoutes);+// Existing running agents routes (process management)app.use('/api/agents', agentsRoutes);app.use('/api/cos/scripts', scriptsRoutes); // Mount before /api/cos to avoid route conflictsapp.use('/api/cos', cosRoutes);@@ -174,6 +186,10 @@ app.use('/api/lmstudio', lmstudioRoutes);// Initialize script runnerinitScriptRunner().catch(err => console.error(`❌ Script runner init failed: ${err.message}`));+// Initialize agent automation scheduler and action executor+automationScheduler.init().catch(err => console.error(`❌ Agent scheduler init failed: ${err.message}`));+agentActionExecutor.init();+// 404 handlerapp.use((req, res) => {res.status(404).json({diff --git a/server/integrations/moltbook/README.md b/server/integrations/moltbook/README.mdnew file mode 100644index 0000000000..f363c90608--- /dev/null+++ b/server/integrations/moltbook/README.md@@ -0,0 +1,127 @@+# Moltbook Integration++This directory contains a self-contained integration for Moltbook, an AI agent social platform. The code is designed to be easily extractable into a standalone application.++## Files++- `api.js` - REST API client with all Moltbook actions+- `rateLimits.js` - Rate limit tracking and enforcement+- `index.js` - Main export with MoltbookClient class++## Usage++### In PortOS++```javascript+import { MoltbookClient, register } from './integrations/moltbook/index.js';++// Register a new agent+const { api_key, claim_url } = await register('MyAgent', 'An AI agent');++// Create a client for an existing agent+const client = new MoltbookClient(apiKey);++// Check status+const status = await client.getStatus();++// Create a post (respects rate limits automatically)+const post = await client.createPost('general', 'Hello World', 'My first post!');++// Browse and engage+const activity = await client.heartbeat({ engageChance: 0.3 });+```++### Rate Limits++The integration automatically enforces Moltbook's rate limits:++| Action | Cooldown | Daily Limit |+|--------|----------|-------------|+| Post | 30 minutes | 48/day |+| Comment | 20 seconds | 50/day |+| Vote | 1 second | 200/day |+| Follow | 5 seconds | 100/day |++Attempting an action while rate-limited will throw an error with details.++### Extracting to Standalone App++To use this integration in a separate project:++1. Copy the entire `moltbook/` directory+2. Install dependencies: `npm install` (no external deps required)+3. Update import paths if needed++The integration only requires:+- Node.js 18+ (for native fetch)+- No external dependencies++## API Reference++### Account++- `register(name, description)` - Create new agent (static method)+- `getStatus()` - Get account status+- `getProfile()` - Get own profile+- `updateProfile(updates)` - Update profile++### Posts++- `createPost(submolt, title, content)` - Create a post+- `getFeed(sort, limit)` - Get feed (hot/new/top/rising)+- `getPost(postId)` - Get specific post++### Comments++- `createComment(postId, content)` - Comment on post+- `replyToComment(postId, parentId, content)` - Reply to comment+- `getComments(postId)` - Get post comments++### Voting++- `upvote(postId)` - Upvote a post+- `downvote(postId)` - Downvote a post+- `upvoteComment(commentId)` - Upvote a comment++### Social++- `follow(agentName)` - Follow an agent+- `unfollow(agentName)` - Unfollow an agent+- `getAgentProfile(agentName)` - Get agent's profile+- `getFollowers()` - Get followers+- `getFollowing()` - Get following++### Activity++- `heartbeat(options)` - Browse feed and engage naturally++### Utilities++- `getRateLimitStatus()` - Get current rate limit status+- `getSubmolts()` - List available submolts+- `getSubmolt(name)` - Get submolt details++## Integration with PortOS Scheduler++The Moltbook integration is used by the automation scheduler to execute scheduled actions:++```javascript+import { MoltbookClient } from './integrations/moltbook/index.js';+import { scheduleEvents } from './services/automationScheduler.js';++// Listen for scheduled action executions+scheduleEvents.on('execute', async ({ schedule }) => {+ const account = await getAccountWithCredentials(schedule.accountId);+ const client = new MoltbookClient(account.credentials.apiKey);++ switch (schedule.action.type) {+ case 'post':+ await client.createPost(...);+ break;+ case 'heartbeat':+ await client.heartbeat(...);+ break;+ // etc.+ }+});+```diff --git a/server/integrations/moltbook/api.js b/server/integrations/moltbook/api.jsnew file mode 100644index 0000000000..3b4c9ce3a6--- /dev/null+++ b/server/integrations/moltbook/api.js@@ -0,0 +1,422 @@+/**+ * Moltbook API Client+ *+ * REST API client for Moltbook - an AI agent social platform.+ * All actions are performed via their REST API (no browser automation needed).+ *+ * API Base: https://www.moltbook.app/api+ */++import { checkRateLimit, recordAction } from './rateLimits.js';++const API_BASE = 'https://www.moltbook.app/api';++/**+ * Make an API request to Moltbook+ */+async function request(endpoint, options = {}) {+ const url = `${API_BASE}${endpoint}`;+ const config = {+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ },+ ...options+ };++ console.log(`📚 Moltbook API: ${options.method || 'GET'} ${endpoint}`);++ const response = await fetch(url, config);++ if (!response.ok) {+ const error = await response.json().catch(() => ({ error: 'Request failed' }));+ const message = error.error || error.message || `HTTP ${response.status}`;+ console.error(`❌ Moltbook API error: ${message}`);+ throw new Error(message);+ }++ if (response.status === 204) {+ return null;+ }++ return response.json();+}++/**+ * Make an authenticated API request+ */+async function authRequest(apiKey, endpoint, options = {}) {+ return request(endpoint, {+ ...options,+ headers: {+ ...options.headers,+ 'Authorization': `Bearer ${apiKey}`+ }+ });+}++// =============================================================================+// ACCOUNT MANAGEMENT+// =============================================================================++/**+ * Register a new agent account on Moltbook+ * @param {string} name - Display name for the agent+ * @param {string} description - Bio/description+ * @returns {{ api_key: string, claim_url: string }} Registration result+ */+export async function register(name, description = '') {+ const result = await request('/agents/register', {+ method: 'POST',+ body: JSON.stringify({ name, description })+ });++ console.log(`🆕 Moltbook: Registered agent "${name}"`);+ return result;+}++/**+ * Get the status of an agent account+ * @param {string} apiKey - The agent's API key+ * @returns {{ status: 'pending_claim' | 'claimed' | 'active' | 'suspended' }}+ */+export async function getStatus(apiKey) {+ return authRequest(apiKey, '/agents/me/status');+}++/**+ * Get the agent's profile+ * @param {string} apiKey - The agent's API key+ */+export async function getProfile(apiKey) {+ return authRequest(apiKey, '/agents/me');+}++/**+ * Update the agent's profile+ * @param {string} apiKey - The agent's API key+ * @param {Object} updates - Profile updates+ */+export async function updateProfile(apiKey, updates) {+ return authRequest(apiKey, '/agents/me', {+ method: 'PUT',+ body: JSON.stringify(updates)+ });+}++// =============================================================================+// POSTS+// =============================================================================++/**+ * Create a new post+ * @param {string} apiKey - The agent's API key+ * @param {string} submolt - The submolt (subreddit-like) to post in+ * @param {string} title - Post title+ * @param {string} content - Post content (markdown)+ * @returns {Object} Created post+ */+export async function createPost(apiKey, submolt, title, content) {+ // Check rate limit+ const rateCheck = checkRateLimit(apiKey, 'post');+ if (!rateCheck.allowed) {+ throw new Error(`Rate limited: ${rateCheck.reason}`);+ }++ const result = await authRequest(apiKey, '/posts', {+ method: 'POST',+ body: JSON.stringify({ submolt, title, content })+ });++ recordAction(apiKey, 'post');+ console.log(`📝 Moltbook: Created post "${title}" in ${submolt}`);+ return result;+}++/**+ * Get the feed+ * @param {string} apiKey - The agent's API key+ * @param {'hot' | 'new' | 'top' | 'rising'} sort - Sort order+ * @param {number} limit - Number of posts to fetch+ */+export async function getFeed(apiKey, sort = 'hot', limit = 25) {+ return authRequest(apiKey, `/feed?sort=${sort}&limit=${limit}`);+}++/**+ * Get a specific post+ * @param {string} apiKey - The agent's API key+ * @param {string} postId - The post ID+ */+export async function getPost(apiKey, postId) {+ return authRequest(apiKey, `/posts/${postId}`);+}++// =============================================================================+// COMMENTS+// =============================================================================++/**+ * Create a comment on a post+ * @param {string} apiKey - The agent's API key+ * @param {string} postId - The post ID+ * @param {string} content - Comment content (markdown)+ */+export async function createComment(apiKey, postId, content) {+ // Check rate limit+ const rateCheck = checkRateLimit(apiKey, 'comment');+ if (!rateCheck.allowed) {+ throw new Error(`Rate limited: ${rateCheck.reason}`);+ }++ const result = await authRequest(apiKey, `/posts/${postId}/comments`, {+ method: 'POST',+ body: JSON.stringify({ content })+ });++ recordAction(apiKey, 'comment');+ console.log(`💬 Moltbook: Commented on post ${postId}`);+ return result;+}++/**+ * Reply to a comment+ * @param {string} apiKey - The agent's API key+ * @param {string} postId - The post ID+ * @param {string} parentId - The parent comment ID+ * @param {string} content - Reply content (markdown)+ */+export async function replyToComment(apiKey, postId, parentId, content) {+ // Check rate limit+ const rateCheck = checkRateLimit(apiKey, 'comment');+ if (!rateCheck.allowed) {+ throw new Error(`Rate limited: ${rateCheck.reason}`);+ }++ const result = await authRequest(apiKey, `/posts/${postId}/comments`, {+ method: 'POST',+ body: JSON.stringify({ content, parentId })+ });++ recordAction(apiKey, 'comment');+ console.log(`↩️ Moltbook: Replied to comment ${parentId}`);+ return result;+}++/**+ * Get comments for a post+ * @param {string} apiKey - The agent's API key+ * @param {string} postId - The post ID+ */+export async function getComments(apiKey, postId) {+ return authRequest(apiKey, `/posts/${postId}/comments`);+}++// =============================================================================+// VOTING+// =============================================================================++/**+ * Upvote a post+ * @param {string} apiKey - The agent's API key+ * @param {string} postId - The post ID+ */+export async function upvote(apiKey, postId) {+ // Check rate limit+ const rateCheck = checkRateLimit(apiKey, 'vote');+ if (!rateCheck.allowed) {+ throw new Error(`Rate limited: ${rateCheck.reason}`);+ }++ const result = await authRequest(apiKey, `/posts/${postId}/vote`, {+ method: 'POST',+ body: JSON.stringify({ direction: 'up' })+ });++ recordAction(apiKey, 'vote');+ console.log(`👍 Moltbook: Upvoted post ${postId}`);+ return result;+}++/**+ * Downvote a post+ * @param {string} apiKey - The agent's API key+ * @param {string} postId - The post ID+ */+export async function downvote(apiKey, postId) {+ // Check rate limit+ const rateCheck = checkRateLimit(apiKey, 'vote');+ if (!rateCheck.allowed) {+ throw new Error(`Rate limited: ${rateCheck.reason}`);+ }++ const result = await authRequest(apiKey, `/posts/${postId}/vote`, {+ method: 'POST',+ body: JSON.stringify({ direction: 'down' })+ });++ recordAction(apiKey, 'vote');+ console.log(`👎 Moltbook: Downvoted post ${postId}`);+ return result;+}++/**+ * Upvote a comment+ * @param {string} apiKey - The agent's API key+ * @param {string} commentId - The comment ID+ */+export async function upvoteComment(apiKey, commentId) {+ // Check rate limit+ const rateCheck = checkRateLimit(apiKey, 'vote');+ if (!rateCheck.allowed) {+ throw new Error(`Rate limited: ${rateCheck.reason}`);+ }++ const result = await authRequest(apiKey, `/comments/${commentId}/vote`, {+ method: 'POST',+ body: JSON.stringify({ direction: 'up' })+ });++ recordAction(apiKey, 'vote');+ console.log(`👍 Moltbook: Upvoted comment ${commentId}`);+ return result;+}++// =============================================================================+// SOCIAL+// =============================================================================++/**+ * Follow an agent+ * @param {string} apiKey - The agent's API key+ * @param {string} agentName - The agent to follow+ */+export async function follow(apiKey, agentName) {+ // Check rate limit+ const rateCheck = checkRateLimit(apiKey, 'follow');+ if (!rateCheck.allowed) {+ throw new Error(`Rate limited: ${rateCheck.reason}`);+ }++ const result = await authRequest(apiKey, `/agents/${agentName}/follow`, {+ method: 'POST'+ });++ recordAction(apiKey, 'follow');+ console.log(`➕ Moltbook: Followed agent ${agentName}`);+ return result;+}++/**+ * Unfollow an agent+ * @param {string} apiKey - The agent's API key+ * @param {string} agentName - The agent to unfollow+ */+export async function unfollow(apiKey, agentName) {+ const result = await authRequest(apiKey, `/agents/${agentName}/follow`, {+ method: 'DELETE'+ });++ console.log(`➖ Moltbook: Unfollowed agent ${agentName}`);+ return result;+}++/**+ * Get an agent's public profile+ * @param {string} apiKey - The agent's API key+ * @param {string} agentName - The agent name to look up+ */+export async function getAgentProfile(apiKey, agentName) {+ return authRequest(apiKey, `/agents/${agentName}`);+}++/**+ * Get followers+ * @param {string} apiKey - The agent's API key+ */+export async function getFollowers(apiKey) {+ return authRequest(apiKey, '/agents/me/followers');+}++/**+ * Get following+ * @param {string} apiKey - The agent's API key+ */+export async function getFollowing(apiKey) {+ return authRequest(apiKey, '/agents/me/following');+}++// =============================================================================+// HEARTBEAT / ACTIVITY+// =============================================================================++/**+ * Perform a "heartbeat" - browse and potentially engage+ * This is a compound action that:+ * 1. Fetches the feed+ * 2. Optionally upvotes interesting content+ * 3. Returns activity summary+ *+ * @param {string} apiKey - The agent's API key+ * @param {Object} options - Heartbeat options+ * @returns {Object} Activity summary+ */+export async function heartbeat(apiKey, options = {}) {+ const { engageChance = 0.3, maxEngagements = 3 } = options;++ console.log(`💓 Moltbook: Starting heartbeat`);++ // Get feed+ const feed = await getFeed(apiKey, 'hot', 25);+ const posts = feed.posts || [];++ let engagements = 0;+ const engaged = [];++ // Randomly engage with some posts+ for (const post of posts) {+ if (engagements >= maxEngagements) break;+ if (Math.random() > engageChance) continue;++ // Check if we can still vote+ const rateCheck = checkRateLimit(apiKey, 'vote');+ if (!rateCheck.allowed) break;++ // Upvote the post+ await upvote(apiKey, post.id);+ engaged.push({ type: 'upvote', postId: post.id, title: post.title });+ engagements++;++ // Small delay between actions+ await new Promise(resolve => setTimeout(resolve, 1000));+ }++ console.log(`💓 Moltbook: Heartbeat complete - ${engagements} engagements`);++ return {+ feedSize: posts.length,+ engagements,+ engaged+ };+}++// =============================================================================+// SUBMOLTS+// =============================================================================++/**+ * Get list of submolts+ * @param {string} apiKey - The agent's API key+ */+export async function getSubmolts(apiKey) {+ return authRequest(apiKey, '/submolts');+}++/**+ * Get a specific submolt+ * @param {string} apiKey - The agent's API key+ * @param {string} submoltName - The submolt name+ */+export async function getSubmolt(apiKey, submoltName) {+ return authRequest(apiKey, `/submolts/${submoltName}`);+}diff --git a/server/integrations/moltbook/index.js b/server/integrations/moltbook/index.jsnew file mode 100644index 0000000000..a250dac779--- /dev/null+++ b/server/integrations/moltbook/index.js@@ -0,0 +1,76 @@+/**+ * Moltbook Integration+ *+ * This module provides integration with Moltbook - an AI agent social platform.+ * It's designed to be self-contained for easy extraction into a standalone app.+ *+ * @module integrations/moltbook+ */++// Re-export all API functions+export * from './api.js';++// Re-export rate limit utilities+export {+ MOLTBOOK_RATE_LIMITS,+ checkRateLimit,+ recordAction,+ getRateLimitStatus,+ clearRateLimitState+} from './rateLimits.js';++// Export a convenience client class for stateful usage+import * as api from './api.js';+import { getRateLimitStatus } from './rateLimits.js';++/**+ * Moltbook client for a specific agent account+ */+export class MoltbookClient {+ constructor(apiKey) {+ this.apiKey = apiKey;+ }++ // Account+ getStatus() { return api.getStatus(this.apiKey); }+ getProfile() { return api.getProfile(this.apiKey); }+ updateProfile(updates) { return api.updateProfile(this.apiKey, updates); }++ // Posts+ 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); }++ // Comments+ createComment(postId, content) { return api.createComment(this.apiKey, postId, content); }+ replyToComment(postId, parentId, content) { return api.replyToComment(this.apiKey, postId, parentId, content); }+ getComments(postId) { return api.getComments(this.apiKey, postId); }++ // Voting+ upvote(postId) { return api.upvote(this.apiKey, postId); }+ downvote(postId) { return api.downvote(this.apiKey, postId); }+ upvoteComment(commentId) { return api.upvoteComment(this.apiKey, commentId); }++ // Social+ follow(agentName) { return api.follow(this.apiKey, agentName); }+ unfollow(agentName) { return api.unfollow(this.apiKey, agentName); }+ getAgentProfile(agentName) { return api.getAgentProfile(this.apiKey, agentName); }+ getFollowers() { return api.getFollowers(this.apiKey); }+ getFollowing() { return api.getFollowing(this.apiKey); }++ // Heartbeat+ heartbeat(options) { return api.heartbeat(this.apiKey, options); }++ // Submolts+ getSubmolts() { return api.getSubmolts(this.apiKey); }+ getSubmolt(name) { return api.getSubmolt(this.apiKey, name); }++ // Rate limits+ getRateLimitStatus() { return getRateLimitStatus(this.apiKey); }+}++/**+ * Register a new agent on Moltbook+ * This is a static method since it doesn't require an existing API key+ */+MoltbookClient.register = api.register;diff --git a/server/integrations/moltbook/rateLimits.js b/server/integrations/moltbook/rateLimits.jsnew file mode 100644index 0000000000..b6a6dce590--- /dev/null+++ b/server/integrations/moltbook/rateLimits.js@@ -0,0 +1,143 @@+/**+ * Moltbook Rate Limits+ *+ * Rate limit configuration for Moltbook API actions.+ * These limits are enforced by the platform - exceeding them will result in errors.+ */++export const MOLTBOOK_RATE_LIMITS = {+ post: {+ cooldownMs: 30 * 60 * 1000, // 30 minutes between posts+ maxPerDay: 48 // Maximum posts per day+ },+ comment: {+ cooldownMs: 20 * 1000, // 20 seconds between comments+ maxPerDay: 50 // Maximum comments per day+ },+ vote: {+ cooldownMs: 1 * 1000, // 1 second between votes+ maxPerDay: 200 // Maximum votes per day+ },+ follow: {+ cooldownMs: 5 * 1000, // 5 seconds between follows+ maxPerDay: 100 // Maximum follows per day+ }+};++// In-memory rate limit tracking per API key+const rateLimitState = new Map();++/**+ * Get rate limit state for an API key+ */+function getState(apiKey) {+ if (!rateLimitState.has(apiKey)) {+ rateLimitState.set(apiKey, {+ post: { lastAction: 0, todayCount: 0, dayStart: Date.now() },+ comment: { lastAction: 0, todayCount: 0, dayStart: Date.now() },+ vote: { lastAction: 0, todayCount: 0, dayStart: Date.now() },+ follow: { lastAction: 0, todayCount: 0, dayStart: Date.now() }+ });+ }++ const state = rateLimitState.get(apiKey);+ const now = Date.now();+ const oneDayMs = 24 * 60 * 60 * 1000;++ // Reset daily counters if day has changed+ for (const action of Object.keys(state)) {+ if (now - state[action].dayStart > oneDayMs) {+ state[action].todayCount = 0;+ state[action].dayStart = now;+ }+ }++ return state;+}++/**+ * Check if an action is rate limited+ * @param {string} apiKey - The API key to check+ * @param {string} action - The action type (post, comment, vote, follow)+ * @returns {{ allowed: boolean, waitMs?: number, reason?: string }}+ */+export function checkRateLimit(apiKey, action) {+ const limits = MOLTBOOK_RATE_LIMITS[action];+ if (!limits) {+ return { allowed: true };+ }++ const state = getState(apiKey);+ const actionState = state[action];+ const now = Date.now();++ // Check daily limit+ if (actionState.todayCount >= limits.maxPerDay) {+ return {+ allowed: false,+ reason: `Daily limit reached (${limits.maxPerDay}/${action}s per day)`,+ waitMs: state[action].dayStart + 24 * 60 * 60 * 1000 - now+ };+ }++ // Check cooldown+ const timeSinceLast = now - actionState.lastAction;+ if (timeSinceLast < limits.cooldownMs) {+ return {+ allowed: false,+ reason: `Cooldown active (${Math.ceil(limits.cooldownMs / 1000)}s between ${action}s)`,+ waitMs: limits.cooldownMs - timeSinceLast+ };+ }++ return { allowed: true };+}++/**+ * Record an action for rate limiting+ * @param {string} apiKey - The API key+ * @param {string} action - The action type+ */+export function recordAction(apiKey, action) {+ const state = getState(apiKey);+ if (state[action]) {+ state[action].lastAction = Date.now();+ state[action].todayCount++;+ }+}++/**+ * Get current rate limit status for all actions+ * @param {string} apiKey - The API key+ * @returns {Object} Status for each action type+ */+export function getRateLimitStatus(apiKey) {+ const state = getState(apiKey);+ const now = Date.now();+ const status = {};++ for (const [action, limits] of Object.entries(MOLTBOOK_RATE_LIMITS)) {+ const actionState = state[action];+ const timeSinceLast = now - actionState.lastAction;+ const cooldownRemaining = Math.max(0, limits.cooldownMs - timeSinceLast);++ status[action] = {+ todayCount: actionState.todayCount,+ maxPerDay: limits.maxPerDay,+ remaining: limits.maxPerDay - actionState.todayCount,+ cooldownMs: limits.cooldownMs,+ cooldownRemainingMs: cooldownRemaining,+ canAct: actionState.todayCount < limits.maxPerDay && cooldownRemaining === 0+ };+ }++ return status;+}++/**+ * Clear rate limit state for an API key (e.g., on account deletion)+ * @param {string} apiKey - The API key+ */+export function clearRateLimitState(apiKey) {+ rateLimitState.delete(apiKey);+}diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 6033f0ce58..915665c48c 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -283,3 +283,56 @@ export const reviewOutputSchema = z.object({suggestedActionsNextWeek: z.array(z.string()).max(3),recurringTheme: z.string()});++// =============================================================================+// LINKS SCHEMAS+// =============================================================================++// Link type enum+export const linkTypeEnum = z.enum(['github', 'article', 'documentation', 'tool', 'reference', 'other']);++// Link Record schema+export const linkRecordSchema = z.object({+ id: z.string().uuid(),+ url: z.string().url(),+ title: z.string().min(1).max(500),+ description: z.string().max(2000).optional().default(''),+ linkType: linkTypeEnum.default('other'),+ tags: z.array(z.string().max(50)).optional().default([]),+ // GitHub-specific fields+ isGitHubRepo: z.boolean().default(false),+ gitHubOwner: z.string().max(100).optional(),+ gitHubRepo: z.string().max(100).optional(),+ localPath: z.string().max(500).optional(),+ cloneStatus: z.enum(['pending', 'cloning', 'cloned', 'failed', 'none']).default('none'),+ cloneError: z.string().max(500).optional(),+ // Metadata+ createdAt: z.string().datetime(),+ updatedAt: z.string().datetime()+});++// Create/Update Link input schema+export const linkInputSchema = z.object({+ url: z.string().url(),+ title: z.string().min(1).max(500).optional(),+ description: z.string().max(2000).optional(),+ linkType: linkTypeEnum.optional(),+ tags: z.array(z.string().max(50)).optional(),+ autoClone: z.boolean().optional().default(true)+});++// Update Link input schema (partial)+export const linkUpdateInputSchema = z.object({+ title: z.string().min(1).max(500).optional(),+ description: z.string().max(2000).optional(),+ linkType: linkTypeEnum.optional(),+ tags: z.array(z.string().max(50)).optional()+});++// Links query schema+export const linksQuerySchema = z.object({+ linkType: linkTypeEnum.optional(),+ isGitHubRepo: z.coerce.boolean().optional(),+ limit: z.coerce.number().int().min(1).max(100).optional().default(50),+ offset: z.coerce.number().int().min(0).optional().default(0)+});diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex e65a08bcc2..b7262f6c52 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -23,9 +23,11 @@ export const PATHS = {digitalTwin: join(__lib_dirname, '../../data/digital-twin'),runs: join(__lib_dirname, '../../data/runs'),memory: join(__lib_dirname, '../../data/cos/memory'),- agents: join(__lib_dirname, '../../data/cos/agents'),+ cosAgents: join(__lib_dirname, '../../data/cos/agents'), // CoS sub-agentsscripts: join(__lib_dirname, '../../data/cos/scripts'),- reports: join(__lib_dirname, '../../data/cos/reports')+ reports: join(__lib_dirname, '../../data/cos/reports'),+ // AI Agent Personalities data+ agentPersonalities: join(__lib_dirname, '../../data/agents')};/**diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 0c3597c4bc..4d305673cb 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1,5 +1,128 @@import { z } from 'zod';+// =============================================================================+// AGENT PERSONALITY SCHEMAS+// =============================================================================++// Agent personality style+export const personalityStyleSchema = z.enum([+ 'professional',+ 'casual',+ 'witty',+ 'academic',+ 'creative'+]);++// Agent personality object+export const agentPersonalitySchema = z.object({+ style: personalityStyleSchema,+ tone: z.string().max(500).optional().default(''),+ topics: z.array(z.string().max(100)).default([]),+ quirks: z.array(z.string().max(200)).default([]),+ promptPrefix: z.string().max(2000).optional().default('')+});++// Agent avatar+export const agentAvatarSchema = z.object({+ imageUrl: z.string().url().optional(),+ emoji: z.string().max(10).optional(),+ color: z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional()+}).optional();++// Full agent schema+export const agentSchema = z.object({+ userId: z.string().min(1).max(100),+ name: z.string().min(1).max(100),+ description: z.string().max(1000).optional().default(''),+ personality: agentPersonalitySchema,+ avatar: agentAvatarSchema,+ enabled: z.boolean().default(true)+});++export const agentUpdateSchema = agentSchema.partial();++// =============================================================================+// PLATFORM ACCOUNT SCHEMAS+// =============================================================================++export const platformTypeSchema = z.enum(['moltbook']);++export const accountCredentialsSchema = z.object({+ apiKey: z.string().min(1),+ username: z.string().min(1).max(100)+});++export const accountStatusSchema = z.enum(['active', 'pending', 'suspended', 'error']);++export const platformAccountSchema = z.object({+ agentId: z.string().min(1),+ platform: platformTypeSchema,+ credentials: accountCredentialsSchema,+ status: accountStatusSchema.default('pending'),+ platformData: z.record(z.unknown()).optional().default({})+});++export const platformAccountUpdateSchema = platformAccountSchema.partial();++// Account registration (when creating new Moltbook account)+export const accountRegistrationSchema = z.object({+ agentId: z.string().min(1),+ platform: platformTypeSchema,+ name: z.string().min(1).max(100),+ description: z.string().max(500).optional().default('')+});++// =============================================================================+// AUTOMATION SCHEDULE SCHEMAS+// =============================================================================++export const scheduleActionTypeSchema = z.enum(['post', 'comment', 'vote', 'heartbeat']);++export const scheduleActionSchema = z.object({+ type: scheduleActionTypeSchema,+ params: z.record(z.unknown()).optional().default({})+});++export const scheduleTypeSchema = z.enum(['cron', 'interval', 'random']);++export const scheduleTimingSchema = z.object({+ type: scheduleTypeSchema,+ cron: z.string().optional(),+ intervalMs: z.number().int().min(1000).optional(),+ randomWindow: z.object({+ minMs: z.number().int().min(1000),+ maxMs: z.number().int().min(1000)+ }).optional()+}).refine(+ (data) => {+ if (data.type === 'cron') return !!data.cron;+ if (data.type === 'interval') return !!data.intervalMs;+ if (data.type === 'random') return !!data.randomWindow;+ return false;+ },+ { message: 'Schedule timing must match its type' }+);++export const scheduleRateLimitSchema = z.object({+ maxPerDay: z.number().int().min(1).optional(),+ cooldownMs: z.number().int().min(0).optional()+}).optional();++export const automationScheduleSchema = z.object({+ agentId: z.string().min(1),+ accountId: z.string().min(1),+ action: scheduleActionSchema,+ schedule: scheduleTimingSchema,+ rateLimit: scheduleRateLimitSchema,+ enabled: z.boolean().default(true)+});++export const automationScheduleUpdateSchema = automationScheduleSchema.partial();++// =============================================================================+// EXISTING SCHEMAS+// =============================================================================+// Process definition schema (for PM2 processes with ports)export const processSchema = z.object({name: z.string().min(1),diff --git a/server/routes/agentActivity.js b/server/routes/agentActivity.jsnew file mode 100644index 0000000000..44cac86ef6--- /dev/null+++ b/server/routes/agentActivity.js@@ -0,0 +1,76 @@+/**+ * Agent Activity Routes+ *+ * Get activity logs for agents and their platform actions.+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import * as agentActivity from '../services/agentActivity.js';++const router = Router();++// GET / - Get recent activity across all agents+router.get('/', asyncHandler(async (req, res) => {+ console.log('📊 GET /api/agents/activity');+ const { limit = 50, agentIds, action } = req.query;++ const activities = await agentActivity.getRecentActivities({+ limit: parseInt(limit, 10),+ agentIds: agentIds ? agentIds.split(',') : null,+ action: action || null+ });++ res.json(activities);+}));++// GET /timeline - Get activity timeline (for infinite scroll)+router.get('/timeline', asyncHandler(async (req, res) => {+ console.log('📊 GET /api/agents/activity/timeline');+ const { limit = 50, agentIds, before } = req.query;++ const activities = await agentActivity.getActivityTimeline({+ limit: parseInt(limit, 10),+ agentIds: agentIds ? agentIds.split(',') : null,+ beforeTimestamp: before || null+ });++ res.json(activities);+}));++// GET /agent/:agentId - Get activities for specific agent+router.get('/agent/:agentId', asyncHandler(async (req, res) => {+ const { agentId } = req.params;+ const { date, limit = 100, offset = 0, action } = req.query;+ console.log(`📊 GET /api/agents/activity/agent/${agentId}`);++ const activities = await agentActivity.getActivities(agentId, {+ date: date ? new Date(date) : new Date(),+ limit: parseInt(limit, 10),+ offset: parseInt(offset, 10),+ action: action || null+ });++ res.json(activities);+}));++// GET /agent/:agentId/stats - Get activity stats for agent+router.get('/agent/:agentId/stats', asyncHandler(async (req, res) => {+ const { agentId } = req.params;+ const { days = 7 } = req.query;+ console.log(`📊 GET /api/agents/activity/agent/${agentId}/stats`);++ const stats = await agentActivity.getAgentStats(agentId, parseInt(days, 10));+ res.json(stats);+}));++// POST /cleanup - Clean up old activity files+router.post('/cleanup', asyncHandler(async (req, res) => {+ const { daysToKeep = 30 } = req.body;+ console.log(`📊 POST /api/agents/activity/cleanup (keep ${daysToKeep} days)`);++ const deletedCount = await agentActivity.cleanupOldActivity(daysToKeep);+ res.json({ success: true, deletedCount });+}));++export default router;diff --git a/server/routes/agentPersonalities.js b/server/routes/agentPersonalities.jsnew file mode 100644index 0000000000..5112199d54--- /dev/null+++ b/server/routes/agentPersonalities.js@@ -0,0 +1,115 @@+/**+ * Agent Personalities Routes+ *+ * CRUD operations for AI agent personalities.+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validate, agentSchema, agentUpdateSchema } from '../lib/validation.js';+import * as agentPersonalities from '../services/agentPersonalities.js';+import { generateAgentPersonality } from '../services/agentPersonalityGenerator.js';+import { logAction } from '../services/history.js';++const router = Router();++// GET / - Get all agent personalities+router.get('/', asyncHandler(async (req, res) => {+ console.log('🤖 GET /api/agents/personalities');+ const { userId } = req.query;++ const agents = userId+ ? await agentPersonalities.getAgentsByUser(userId)+ : await agentPersonalities.getAllAgents();++ res.json(agents);+}));++// GET /:id - Get agent by ID+router.get('/:id', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`🤖 GET /api/agents/personalities/${id}`);++ const agent = await agentPersonalities.getAgentById(id);+ if (!agent) {+ throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });+ }++ res.json(agent);+}));++// POST / - Create new agent+router.post('/', asyncHandler(async (req, res) => {+ console.log('🤖 POST /api/agents/personalities');++ const { success, data, errors } = validate(agentSchema, req.body);+ if (!success) {+ return res.status(422).json({ errors });+ }++ const agent = await agentPersonalities.createAgent(data);+ await logAction('create', 'agent-personality', agent.id, { name: agent.name });++ res.status(201).json(agent);+}));++// PUT /:id - Update agent+router.put('/:id', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`🤖 PUT /api/agents/personalities/${id}`);++ const { success, data, errors } = validate(agentUpdateSchema, req.body);+ if (!success) {+ return res.status(422).json({ errors });+ }++ const agent = await agentPersonalities.updateAgent(id, data);+ if (!agent) {+ throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });+ }++ await logAction('update', 'agent-personality', id, { name: agent.name });+ res.json(agent);+}));++// DELETE /:id - Delete agent+router.delete('/:id', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`🤖 DELETE /api/agents/personalities/${id}`);++ const deleted = await agentPersonalities.deleteAgent(id);+ if (!deleted) {+ throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });+ }++ await logAction('delete', 'agent-personality', id, {});+ res.json({ success: true });+}));++// POST /generate - Generate agent personality using AI+router.post('/generate', asyncHandler(async (req, res) => {+ console.log('🎨 POST /api/agents/personalities/generate');++ const { seed = {}, providerId, model } = req.body;++ const generated = await generateAgentPersonality(seed, providerId, model);++ res.json(generated);+}));++// POST /:id/toggle - Toggle agent enabled status+router.post('/:id/toggle', asyncHandler(async (req, res) => {+ const { id } = req.params;+ const { enabled } = req.body;+ console.log(`🤖 POST /api/agents/personalities/${id}/toggle enabled=${enabled}`);++ const agent = await agentPersonalities.toggleAgent(id, enabled);+ if (!agent) {+ throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });+ }++ await logAction('toggle', 'agent-personality', id, { enabled });+ res.json(agent);+}));++export default router;diff --git a/server/routes/automationSchedules.js b/server/routes/automationSchedules.jsnew file mode 100644index 0000000000..3977f7ce06--- /dev/null+++ b/server/routes/automationSchedules.js@@ -0,0 +1,160 @@+/**+ * Automation Schedules Routes+ *+ * Manage scheduled automation tasks for agent platform accounts.+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validate, automationScheduleSchema, automationScheduleUpdateSchema } from '../lib/validation.js';+import * as automationScheduler from '../services/automationScheduler.js';+import * as platformAccounts from '../services/platformAccounts.js';+import * as agentPersonalities from '../services/agentPersonalities.js';+import { logAction } from '../services/history.js';++const router = Router();++// GET / - Get all schedules+router.get('/', asyncHandler(async (req, res) => {+ console.log('📅 GET /api/agents/schedules');+ const { agentId, accountId } = req.query;++ let schedules;+ if (agentId) {+ schedules = await automationScheduler.getSchedulesByAgent(agentId);+ } else if (accountId) {+ schedules = await automationScheduler.getSchedulesByAccount(accountId);+ } else {+ schedules = await automationScheduler.getAllSchedules();+ }++ res.json(schedules);+}));++// GET /stats - Get schedule statistics+router.get('/stats', asyncHandler(async (req, res) => {+ console.log('📅 GET /api/agents/schedules/stats');+ const stats = await automationScheduler.getStats();+ res.json(stats);+}));++// GET /:id - Get schedule by ID+router.get('/:id', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`📅 GET /api/agents/schedules/${id}`);++ const schedule = await automationScheduler.getScheduleById(id);+ if (!schedule) {+ throw new ServerError('Schedule not found', { status: 404, code: 'NOT_FOUND' });+ }++ res.json(schedule);+}));++// POST / - Create new schedule+router.post('/', asyncHandler(async (req, res) => {+ console.log('📅 POST /api/agents/schedules');++ const { success, data, errors } = validate(automationScheduleSchema, req.body);+ if (!success) {+ return res.status(422).json({ errors });+ }++ // Verify agent exists+ const agent = await agentPersonalities.getAgentById(data.agentId);+ if (!agent) {+ throw new ServerError('Agent not found', { status: 404, code: 'AGENT_NOT_FOUND' });+ }++ // Verify account exists and belongs to agent+ const account = await platformAccounts.getAccountById(data.accountId);+ if (!account) {+ throw new ServerError('Account not found', { status: 404, code: 'ACCOUNT_NOT_FOUND' });+ }+ if (account.agentId !== data.agentId) {+ throw new ServerError('Account does not belong to this agent', {+ status: 400,+ code: 'ACCOUNT_AGENT_MISMATCH'+ });+ }++ const schedule = await automationScheduler.createSchedule(data);+ await logAction('create', 'automation-schedule', schedule.id, {+ agentId: schedule.agentId,+ action: schedule.action.type+ });++ res.status(201).json(schedule);+}));++// PUT /:id - Update schedule+router.put('/:id', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`📅 PUT /api/agents/schedules/${id}`);++ const { success, data, errors } = validate(automationScheduleUpdateSchema, req.body);+ if (!success) {+ return res.status(422).json({ errors });+ }++ const schedule = await automationScheduler.updateSchedule(id, data);+ if (!schedule) {+ throw new ServerError('Schedule not found', { status: 404, code: 'NOT_FOUND' });+ }++ await logAction('update', 'automation-schedule', id, {+ agentId: schedule.agentId,+ action: schedule.action.type+ });++ res.json(schedule);+}));++// DELETE /:id - Delete schedule+router.delete('/:id', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`📅 DELETE /api/agents/schedules/${id}`);++ const deleted = await automationScheduler.deleteSchedule(id);+ if (!deleted) {+ throw new ServerError('Schedule not found', { status: 404, code: 'NOT_FOUND' });+ }++ await logAction('delete', 'automation-schedule', id, {});+ res.json({ success: true });+}));++// POST /:id/toggle - Toggle schedule enabled status+router.post('/:id/toggle', asyncHandler(async (req, res) => {+ const { id } = req.params;+ const { enabled } = req.body;+ console.log(`📅 POST /api/agents/schedules/${id}/toggle enabled=${enabled}`);++ const schedule = await automationScheduler.toggleSchedule(id, enabled);+ if (!schedule) {+ throw new ServerError('Schedule not found', { status: 404, code: 'NOT_FOUND' });+ }++ await logAction('toggle', 'automation-schedule', id, { enabled });+ res.json(schedule);+}));++// POST /:id/run - Trigger immediate run+router.post('/:id/run', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`📅 POST /api/agents/schedules/${id}/run`);++ const schedule = await automationScheduler.runNow(id);+ if (!schedule) {+ throw new ServerError('Schedule not found', { status: 404, code: 'NOT_FOUND' });+ }++ await logAction('run', 'automation-schedule', id, {+ agentId: schedule.agentId,+ action: schedule.action.type+ });++ res.json(schedule);+}));++export default router;diff --git a/server/routes/platformAccounts.js b/server/routes/platformAccounts.jsnew file mode 100644index 0000000000..e235670019--- /dev/null+++ b/server/routes/platformAccounts.js@@ -0,0 +1,204 @@+/**+ * Platform Accounts Routes+ *+ * Manage platform accounts (Moltbook, etc.) linked to agents.+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validate, platformAccountSchema, accountRegistrationSchema } from '../lib/validation.js';+import * as platformAccounts from '../services/platformAccounts.js';+import * as agentPersonalities from '../services/agentPersonalities.js';+import { logAction } from '../services/history.js';+import * as moltbook from '../integrations/moltbook/index.js';++const router = Router();++// GET / - Get all platform accounts+router.get('/', asyncHandler(async (req, res) => {+ console.log('🔗 GET /api/agents/accounts');+ const { agentId, platform } = req.query;++ let accounts;+ if (agentId) {+ accounts = await platformAccounts.getAccountsByAgent(agentId);+ } else if (platform) {+ accounts = await platformAccounts.getAccountsByPlatform(platform);+ } else {+ accounts = await platformAccounts.getAllAccounts();+ }++ res.json(accounts);+}));++// GET /:id - Get account by ID+router.get('/:id', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`🔗 GET /api/agents/accounts/${id}`);++ const account = await platformAccounts.getAccountById(id);+ if (!account) {+ throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });+ }++ res.json(account);+}));++// POST / - Create/link new platform account+router.post('/', asyncHandler(async (req, res) => {+ console.log('🔗 POST /api/agents/accounts');++ // Check if this is a registration request (for new Moltbook accounts)+ // or a direct account creation (with existing credentials)+ if (req.body.credentials) {+ // Direct account creation with credentials+ const { success, data, errors } = validate(platformAccountSchema, req.body);+ if (!success) {+ return res.status(422).json({ errors });+ }++ // Verify agent exists+ const agent = await agentPersonalities.getAgentById(data.agentId);+ if (!agent) {+ throw new ServerError('Agent not found', { status: 404, code: 'AGENT_NOT_FOUND' });+ }++ const account = await platformAccounts.createAccount(data);+ await logAction('create', 'platform-account', account.id, {+ platform: account.platform,+ agentId: account.agentId+ });++ res.status(201).json(account);+ } else {+ // Registration request - create new account on platform+ const { success, data, errors } = validate(accountRegistrationSchema, req.body);+ if (!success) {+ return res.status(422).json({ errors });+ }++ // Verify agent exists+ const agent = await agentPersonalities.getAgentById(data.agentId);+ if (!agent) {+ throw new ServerError('Agent not found', { status: 404, code: 'AGENT_NOT_FOUND' });+ }++ // Register with Moltbook+ if (data.platform === 'moltbook') {+ let apiKey, claimUrl, username;++ // Try to register with real Moltbook API+ const result = await moltbook.register(data.name, data.description);+ apiKey = result.api_key;+ claimUrl = result.claim_url;+ username = result.username || data.name.toLowerCase().replace(/\s+/g, '_');++ const account = await platformAccounts.createAccount({+ agentId: data.agentId,+ platform: data.platform,+ credentials: {+ apiKey,+ username+ },+ status: 'pending',+ platformData: {+ claimUrl,+ registrationName: data.name,+ registrationDescription: data.description+ }+ });++ await logAction('register', 'platform-account', account.id, {+ platform: account.platform,+ agentId: account.agentId+ });++ res.status(201).json({+ ...account,+ claimUrl+ });+ } else {+ throw new ServerError('Unsupported platform', { status: 400, code: 'UNSUPPORTED_PLATFORM' });+ }+ }+}));++// DELETE /:id - Remove account+router.delete('/:id', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`🔗 DELETE /api/agents/accounts/${id}`);++ const deleted = await platformAccounts.deleteAccount(id);+ if (!deleted) {+ throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });+ }++ await logAction('delete', 'platform-account', id, {});+ res.json({ success: true });+}));++// POST /:id/test - Test account connection+router.post('/:id/test', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`🔗 POST /api/agents/accounts/${id}/test`);++ const account = await platformAccounts.getAccountWithCredentials(id);+ if (!account) {+ throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });+ }++ if (account.platform === 'moltbook') {+ // Test with real Moltbook API+ const client = new moltbook.MoltbookClient(account.credentials.apiKey);+ const status = await client.getStatus();++ 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}`,+ platform: account.platform,+ username: account.credentials.username,+ platformStatus: status.status+ };++ // Update account status if it changed+ if (status.status === 'active' || status.status === 'claimed') {+ await platformAccounts.updateAccountStatus(id, 'active');+ } else if (status.status === 'suspended') {+ await platformAccounts.updateAccountStatus(id, 'suspended');+ }++ res.json(testResult);+ } else {+ throw new ServerError('Unsupported platform', { status: 400, code: 'UNSUPPORTED_PLATFORM' });+ }+}));++// POST /:id/claim - Mark account as claimed (after user visits claim URL)+router.post('/:id/claim', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`🔗 POST /api/agents/accounts/${id}/claim`);++ const account = await platformAccounts.getAccountById(id);+ if (!account) {+ throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });+ }++ if (account.status !== 'pending') {+ throw new ServerError('Account already claimed or in error state', {+ status: 400,+ code: 'INVALID_STATE'+ });+ }++ // Update status to active+ const updated = await platformAccounts.updateAccountStatus(id, 'active');+ await logAction('claim', 'platform-account', id, { platform: updated.platform });++ res.json(updated);+}));++export default router;diff --git a/server/services/agentActionExecutor.js b/server/services/agentActionExecutor.jsnew file mode 100644index 0000000000..177b3b2df2--- /dev/null+++ b/server/services/agentActionExecutor.js@@ -0,0 +1,238 @@+/**+ * Agent Action Executor+ *+ * Executes scheduled agent actions by connecting to platform APIs.+ * Listens to scheduler events and performs the actual platform operations.+ */++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';++/**+ * Execute an action based on type+ */+async function executeAction(schedule, account, agent) {+ const { action } = schedule;+ const client = new MoltbookClient(account.credentials.apiKey);++ switch (action.type) {+ case 'heartbeat':+ return executeHeartbeat(client, action.params);++ case 'post':+ return executePost(client, agent, action.params);++ case 'comment':+ return executeComment(client, agent, action.params);++ case 'vote':+ return executeVote(client, action.params);++ default:+ throw new Error(`Unknown action type: ${action.type}`);+ }+}++/**+ * Execute a heartbeat action - browse and engage naturally+ */+async function executeHeartbeat(client, params) {+ const options = {+ engageChance: params.engageChance || 0.3,+ maxEngagements: params.maxEngagements || 3+ };++ const result = await client.heartbeat(options);+ return {+ type: 'heartbeat',+ ...result+ };+}++/**+ * Execute a post action+ */+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;++ if (!title || !content) {+ throw new Error('Post action requires title and content in params');+ }++ const post = await client.createPost(submolt, title, content);+ return {+ type: 'post',+ postId: post.id,+ submolt,+ title+ };+}++/**+ * Execute a comment action+ */+async function executeComment(client, agent, params) {+ const { postId, content, parentId } = params;++ if (!postId || !content) {+ throw new Error('Comment action requires postId and content in params');+ }++ let result;+ if (parentId) {+ result = await client.replyToComment(postId, parentId, content);+ } else {+ result = await client.createComment(postId, content);+ }++ return {+ type: 'comment',+ commentId: result.id,+ postId,+ isReply: !!parentId+ };+}++/**+ * Execute a vote action+ */+async function executeVote(client, params) {+ const { postId, commentId, direction = 'up' } = params;++ if (!postId && !commentId) {+ // No specific target - upvote from feed+ const feed = await client.getFeed('hot', 10);+ const posts = feed.posts || [];++ if (posts.length === 0) {+ return { type: 'vote', action: 'none', reason: 'no posts in feed' };+ }++ // Pick a random post to upvote+ const randomPost = posts[Math.floor(Math.random() * posts.length)];+ await client.upvote(randomPost.id);++ return {+ type: 'vote',+ action: 'upvote',+ postId: randomPost.id,+ title: randomPost.title+ };+ }++ if (commentId) {+ await client.upvoteComment(commentId);+ return { type: 'vote', action: 'upvote', commentId };+ }++ if (direction === 'up') {+ await client.upvote(postId);+ } else {+ await client.downvote(postId);+ }++ return { type: 'vote', action: direction === 'up' ? 'upvote' : 'downvote', postId };+}++/**+ * Initialize the action executor+ * Listens to scheduler events and executes actions+ */+export function init() {+ scheduleEvents.on('execute', async ({ scheduleId, schedule, timestamp }) => {+ console.log(`⚡ Executing scheduled action: ${schedule.action.type} (${scheduleId})`);++ // Get account with full credentials+ const account = await platformAccounts.getAccountWithCredentials(schedule.accountId);+ if (!account) {+ console.error(`❌ Account not found: ${schedule.accountId}`);+ await agentActivity.logActivity({+ agentId: schedule.agentId,+ accountId: schedule.accountId,+ scheduleId,+ action: schedule.action.type,+ params: schedule.action.params,+ status: 'failed',+ error: 'Account not found',+ timestamp+ });+ return;+ }++ // Check account status+ if (account.status !== 'active') {+ console.log(`⏸️ Skipping action - account not active: ${account.status}`);+ await agentActivity.logActivity({+ agentId: schedule.agentId,+ accountId: schedule.accountId,+ scheduleId,+ action: schedule.action.type,+ params: schedule.action.params,+ status: 'skipped',+ error: `Account status: ${account.status}`,+ timestamp+ });+ return;+ }++ // Get agent personality+ const agent = await agentPersonalities.getAgentById(schedule.agentId);+ if (!agent) {+ console.error(`❌ Agent not found: ${schedule.agentId}`);+ return;+ }++ // Check if agent is enabled+ if (!agent.enabled) {+ console.log(`⏸️ Skipping action - agent disabled`);+ await agentActivity.logActivity({+ agentId: schedule.agentId,+ accountId: schedule.accountId,+ scheduleId,+ action: schedule.action.type,+ params: schedule.action.params,+ status: 'skipped',+ error: 'Agent disabled',+ timestamp+ });+ return;+ }++ // Execute the action+ const startTime = Date.now();+ let result = null;+ let error = null;++ try {+ result = await executeAction(schedule, account, agent);+ console.log(`✅ Action completed: ${schedule.action.type}`);+ } catch (err) {+ error = err.message;+ console.error(`❌ Action failed: ${err.message}`);+ }++ // Record activity+ await platformAccounts.recordActivity(schedule.accountId);++ // Log completion+ await agentActivity.logActivity({+ agentId: schedule.agentId,+ accountId: schedule.accountId,+ scheduleId,+ action: schedule.action.type,+ params: schedule.action.params,+ status: error ? 'failed' : 'completed',+ result,+ error,+ timestamp: new Date().toISOString(),+ durationMs: Date.now() - startTime+ });+ });++ console.log('⚡ Agent action executor initialized');+}diff --git a/server/services/agentActivity.js b/server/services/agentActivity.jsnew file mode 100644index 0000000000..7d75a78f75--- /dev/null+++ b/server/services/agentActivity.js@@ -0,0 +1,321 @@+/**+ * Agent Activity Service+ *+ * Logs and tracks all agent activities for monitoring, analytics,+ * and rate limit enforcement. Activity is stored per-agent per-day.+ */++import { readFile, writeFile, readdir } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import EventEmitter from 'events';+import { ensureDir, PATHS } from '../lib/fileUtils.js';++const AGENTS_DIR = PATHS.agentPersonalities;+const ACTIVITY_DIR = join(AGENTS_DIR, 'activity');++// Event emitter for activity events+export const activityEvents = new EventEmitter();++// Cache for today's activity (per account)+const todayCache = new Map();++async function ensureActivityDir(agentId = null) {+ await ensureDir(ACTIVITY_DIR);+ if (agentId) {+ await ensureDir(join(ACTIVITY_DIR, agentId));+ }+}++function getDateString(date = new Date()) {+ return date.toISOString().split('T')[0];+}++function getActivityFilePath(agentId, date = new Date()) {+ const dateStr = typeof date === 'string' ? date : getDateString(date);+ return join(ACTIVITY_DIR, agentId, `${dateStr}.json`);+}++/**+ * Load activity for a specific agent and date+ */+async function loadActivity(agentId, date = new Date()) {+ const filePath = getActivityFilePath(agentId, date);+ await ensureActivityDir(agentId);++ if (!existsSync(filePath)) {+ return { activities: [] };+ }++ const content = await readFile(filePath, 'utf-8');+ return JSON.parse(content);+}++/**+ * Save activity for a specific agent and date+ */+async function saveActivity(agentId, date, data) {+ await ensureActivityDir(agentId);+ const filePath = getActivityFilePath(agentId, date);+ await writeFile(filePath, JSON.stringify(data, null, 2));+}++/**+ * Log an activity+ */+export async function logActivity(activity) {+ const {+ agentId,+ accountId,+ scheduleId,+ action,+ params,+ status,+ result,+ error,+ timestamp+ } = activity;++ const date = new Date(timestamp || Date.now());+ const dateStr = getDateString(date);++ const data = await loadActivity(agentId, date);++ const entry = {+ id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,+ accountId,+ scheduleId,+ action,+ params,+ status,+ result,+ error,+ timestamp: timestamp || date.toISOString()+ };++ data.activities.push(entry);+ await saveActivity(agentId, dateStr, data);++ // Invalidate cache for this account+ todayCache.delete(`${accountId}-${action}`);++ // Emit event+ activityEvents.emit('activity', { agentId, ...entry });++ console.log(`📊 Activity logged: ${agentId}/${action} - ${status}`);+ return entry;+}++/**+ * Update activity status (e.g., from 'started' to 'completed')+ */+export async function updateActivityStatus(agentId, activityId, status, result = null, error = null) {+ const date = new Date();+ const dateStr = getDateString(date);+ const data = await loadActivity(agentId, date);++ const activity = data.activities.find(a => a.id === activityId);+ if (activity) {+ activity.status = status;+ if (result) activity.result = result;+ if (error) activity.error = error;+ activity.completedAt = new Date().toISOString();++ await saveActivity(agentId, dateStr, data);+ activityEvents.emit('activity:updated', { agentId, activityId, status });+ }++ return activity;+}++/**+ * Get activities for an agent+ */+export async function getActivities(agentId, options = {}) {+ const { date, limit = 100, offset = 0, action = null } = options;++ const targetDate = date || new Date();+ const data = await loadActivity(agentId, targetDate);++ let activities = data.activities || [];++ // Filter by action if specified+ if (action) {+ activities = activities.filter(a => a.action === action);+ }++ // Sort by timestamp descending (newest first)+ activities.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));++ // Apply pagination+ return activities.slice(offset, offset + limit);+}++/**+ * Get recent activities across all agents+ */+export async function getRecentActivities(options = {}) {+ const { limit = 50, agentIds = null, action = null } = options;++ const today = getDateString();+ const activities = [];++ // Get list of agent directories+ await ensureActivityDir();+ let agentDirs = [];++ if (existsSync(ACTIVITY_DIR)) {+ const entries = await readdir(ACTIVITY_DIR, { withFileTypes: true });+ agentDirs = entries.filter(e => e.isDirectory()).map(e => e.name);+ }++ // Filter to specific agents if provided+ if (agentIds) {+ agentDirs = agentDirs.filter(d => agentIds.includes(d));+ }++ // Load today's activities from each agent+ for (const agentId of agentDirs) {+ const data = await loadActivity(agentId, today);+ for (const activity of data.activities || []) {+ if (!action || activity.action === action) {+ activities.push({ agentId, ...activity });+ }+ }+ }++ // Sort and limit+ activities.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));+ return activities.slice(0, limit);+}++/**+ * Get today's action count for an account (for rate limiting)+ */+export async function getTodayActionCount(accountId, action) {+ const cacheKey = `${accountId}-${action}`;++ // Check cache first+ if (todayCache.has(cacheKey)) {+ const cached = todayCache.get(cacheKey);+ if (Date.now() - cached.timestamp < 5000) { // 5 second cache+ return cached.count;+ }+ }++ // Count from all agents for this account+ const today = getDateString();+ let count = 0;++ await ensureActivityDir();++ if (existsSync(ACTIVITY_DIR)) {+ const entries = await readdir(ACTIVITY_DIR, { withFileTypes: true });+ const agentDirs = entries.filter(e => e.isDirectory()).map(e => e.name);++ for (const agentId of agentDirs) {+ const data = await loadActivity(agentId, today);+ for (const activity of data.activities || []) {+ if (activity.accountId === accountId && activity.action === action) {+ count++;+ }+ }+ }+ }++ // Update cache+ todayCache.set(cacheKey, { count, timestamp: Date.now() });++ return count;+}++/**+ * Get activity stats for an agent+ */+export async function getAgentStats(agentId, days = 7) {+ const stats = {+ totalActivities: 0,+ byAction: {},+ byStatus: {},+ byDay: {}+ };++ const today = new Date();++ for (let i = 0; i < days; i++) {+ const date = new Date(today);+ date.setDate(date.getDate() - i);+ const dateStr = getDateString(date);++ const data = await loadActivity(agentId, date);+ const dayActivities = data.activities || [];++ stats.byDay[dateStr] = dayActivities.length;+ stats.totalActivities += dayActivities.length;++ for (const activity of dayActivities) {+ stats.byAction[activity.action] = (stats.byAction[activity.action] || 0) + 1;+ stats.byStatus[activity.status] = (stats.byStatus[activity.status] || 0) + 1;+ }+ }++ return stats;+}++/**+ * Get activity timeline for display+ */+export async function getActivityTimeline(options = {}) {+ const { agentIds = null, limit = 100, beforeTimestamp = null } = options;++ const activities = await getRecentActivities({ limit: limit * 2, agentIds });++ // Filter by timestamp if provided+ let filtered = activities;+ if (beforeTimestamp) {+ filtered = activities.filter(a => new Date(a.timestamp) < new Date(beforeTimestamp));+ }++ return filtered.slice(0, limit);+}++/**+ * Clean up old activity files (older than N days)+ */+export async function cleanupOldActivity(daysToKeep = 30) {+ const cutoffDate = new Date();+ cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);++ let deletedCount = 0;++ await ensureActivityDir();++ if (!existsSync(ACTIVITY_DIR)) return deletedCount;++ const entries = await readdir(ACTIVITY_DIR, { withFileTypes: true });+ const agentDirs = entries.filter(e => e.isDirectory()).map(e => e.name);++ for (const agentId of agentDirs) {+ const agentDir = join(ACTIVITY_DIR, agentId);+ const files = await readdir(agentDir);++ for (const file of files) {+ if (!file.endsWith('.json')) continue;++ const dateStr = file.replace('.json', '');+ const fileDate = new Date(dateStr);++ if (fileDate < cutoffDate) {+ const { unlink } = await import('fs/promises');+ await unlink(join(agentDir, file));+ deletedCount++;+ }+ }+ }++ if (deletedCount > 0) {+ console.log(`🧹 Cleaned up ${deletedCount} old activity files`);+ }++ return deletedCount;+}diff --git a/server/services/agentPersonalities.js b/server/services/agentPersonalities.jsnew file mode 100644index 0000000000..ed950cd46b--- /dev/null+++ b/server/services/agentPersonalities.js@@ -0,0 +1,196 @@+/**+ * Agent Personalities Service+ *+ * Manages AI agent personalities - their identities, communication styles,+ * and behavioral traits. Each agent has a unique personality that informs+ * how they interact on social platforms.+ */++import { readFile, writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { v4 as uuidv4 } from 'uuid';+import EventEmitter from 'events';+import { ensureDir, PATHS } from '../lib/fileUtils.js';++const AGENTS_DIR = PATHS.agentPersonalities;+const AGENTS_FILE = join(AGENTS_DIR, 'agents.json');++// Event emitter for agent personality changes+export const agentPersonalityEvents = new EventEmitter();++// In-memory cache+let cache = null;+let cacheTimestamp = 0;+const CACHE_TTL_MS = 2000;++async function ensureAgentsDir() {+ await ensureDir(AGENTS_DIR);+}++async function loadAgents() {+ const now = Date.now();++ if (cache && (now - cacheTimestamp) < CACHE_TTL_MS) {+ return cache;+ }++ await ensureAgentsDir();++ if (!existsSync(AGENTS_FILE)) {+ cache = { agents: {} };+ cacheTimestamp = now;+ return cache;+ }++ const content = await readFile(AGENTS_FILE, 'utf-8');+ cache = JSON.parse(content);+ cacheTimestamp = now;+ return cache;+}++async function saveAgents(data) {+ await ensureAgentsDir();+ await writeFile(AGENTS_FILE, JSON.stringify(data, null, 2));+ cache = data;+ cacheTimestamp = Date.now();+}++export function invalidateCache() {+ cache = null;+ cacheTimestamp = 0;+}++export function notifyChanged(action = 'update', agentId = null) {+ agentPersonalityEvents.emit('changed', { action, agentId, timestamp: Date.now() });+}++/**+ * Get all agent personalities+ */+export async function getAllAgents() {+ const data = await loadAgents();+ return Object.entries(data.agents).map(([id, agent]) => ({ id, ...agent }));+}++/**+ * Get all agents for a specific user+ */+export async function getAgentsByUser(userId) {+ const agents = await getAllAgents();+ return agents.filter(agent => agent.userId === userId);+}++/**+ * Get agent by ID+ */+export async function getAgentById(id) {+ const data = await loadAgents();+ const agent = data.agents[id];+ return agent ? { id, ...agent } : null;+}++/**+ * Create a new agent personality+ */+export async function createAgent(agentData) {+ const data = await loadAgents();+ const id = uuidv4();+ const now = new Date().toISOString();++ const agent = {+ userId: agentData.userId,+ name: agentData.name,+ description: agentData.description || '',+ personality: {+ style: agentData.personality.style,+ tone: agentData.personality.tone,+ topics: agentData.personality.topics || [],+ quirks: agentData.personality.quirks || [],+ promptPrefix: agentData.personality.promptPrefix || ''+ },+ avatar: agentData.avatar || {},+ enabled: agentData.enabled !== false,+ createdAt: now,+ updatedAt: now+ };++ data.agents[id] = agent;+ await saveAgents(data);+ notifyChanged('create', id);++ console.log(`🤖 Created agent personality: ${agent.name} (${id})`);+ return { id, ...agent };+}++/**+ * Update an existing agent personality+ */+export async function updateAgent(id, updates) {+ const data = await loadAgents();++ if (!data.agents[id]) {+ return null;+ }++ // Remove id from updates if present+ const { id: _id, createdAt: _createdAt, ...cleanUpdates } = updates;++ // Handle nested personality updates properly+ const existingPersonality = data.agents[id].personality || {};+ const updatedPersonality = cleanUpdates.personality+ ? { ...existingPersonality, ...cleanUpdates.personality }+ : existingPersonality;++ const agent = {+ ...data.agents[id],+ ...cleanUpdates,+ personality: updatedPersonality,+ createdAt: data.agents[id].createdAt,+ updatedAt: new Date().toISOString()+ };++ data.agents[id] = agent;+ await saveAgents(data);+ notifyChanged('update', id);++ console.log(`📝 Updated agent personality: ${agent.name} (${id})`);+ return { id, ...agent };+}++/**+ * Delete an agent personality+ */+export async function deleteAgent(id) {+ const data = await loadAgents();++ if (!data.agents[id]) {+ return false;+ }++ const agentName = data.agents[id].name;+ delete data.agents[id];+ await saveAgents(data);+ notifyChanged('delete', id);++ console.log(`🗑️ Deleted agent personality: ${agentName} (${id})`);+ return true;+}++/**+ * Toggle agent enabled status+ */+export async function toggleAgent(id, enabled) {+ return updateAgent(id, { enabled });+}++/**+ * Get agent count by user+ */+export async function getAgentCount(userId = null) {+ const agents = await getAllAgents();+ if (userId) {+ return agents.filter(a => a.userId === userId).length;+ }+ return agents.length;+}diff --git a/server/services/agentPersonalityGenerator.js b/server/services/agentPersonalityGenerator.jsnew file mode 100644index 0000000000..8744654d47--- /dev/null+++ b/server/services/agentPersonalityGenerator.js@@ -0,0 +1,251 @@+/**+ * Agent Personality Generator Service+ *+ * Uses AI to generate unique agent personalities based on a name or brief description.+ * Generates style, tone, topics, quirks, and prompt prefix for social platform agents.+ */++import { executeApiRun, executeCliRun, createRun } from './runner.js';+import { getActiveProvider, getProviderById } from './providers.js';++const GENERATION_PROMPT = `You are creating a unique AI agent personality for a social media platform where AI agents interact with each other and humans.++## Input+{inputSection}++## Your Task+Generate a complete, unique personality profile for this agent. The personality should feel authentic, consistent, and engaging for social interactions.++## Output Format+Respond with ONLY a valid JSON object (no markdown, no explanation) with this exact structure:++{+ "name": "A creative, memorable name for this agent (2-3 words max)",+ "description": "A 1-2 sentence description of who this agent is and what they're about",+ "personality": {+ "style": "One of: professional, casual, witty, academic, creative",+ "tone": "A phrase describing their communication tone (e.g., 'warm and encouraging', 'dry and sarcastic', 'enthusiastic but precise')",+ "topics": ["topic1", "topic2", "topic3"],+ "quirks": ["unique behavior 1", "unique behavior 2"],+ "promptPrefix": "Instructions for how this agent should communicate. Include their perspective, what they care about, how they engage with content."+ },+ "avatar": {+ "emoji": "A single emoji that represents this agent",+ "color": "#HEXCOLOR"+ }+}++## Guidelines+- Make the personality distinctive and memorable+- The name should be creative and fit the personality (e.g., "Captain Clarity", "Zen Master Zara", "Tech Whisperer")+- Topics should be 3-5 specific areas of expertise or interest+- Quirks should be 2-3 unique communication habits (e.g., "uses nautical metaphors", "asks follow-up questions", "includes relevant quotes")+- The promptPrefix should be 2-4 sentences that would help an AI embody this personality+- Choose a color that matches the personality's vibe+- Be creative but coherent - all elements should work together++Generate the personality now:`;++/**+ * Generate a complete agent personality using AI+ *+ * @param {Object} seed - Seed data with any pre-filled fields+ * @param {string} seed.name - Optional agent name+ * @param {string} seed.description - Optional description+ * @param {Object} seed.personality - Optional personality fields+ * @param {Object} seed.avatar - Optional avatar fields+ * @param {string} providerId - Optional specific provider to use+ * @param {string} model - Optional specific model to use+ * @returns {Promise<Object>} Generated personality data including name+ */+export async function generateAgentPersonality(seed = {}, providerId = null, model = null) {+ const { name = '', description = '', personality = {}, avatar = {} } = seed;+ const hasName = name && name.trim().length > 0;+ const hasDescription = description && description.trim().length > 0;++ console.log(`🎨 Generating personality${hasName ? ` for "${name}"` : ' (full generation)'}`);++ // Get provider+ 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 personality generation');+ }++ // Determine model+ const selectedModel = model || provider.defaultModel || provider.models?.[0];++ // Build the input section based on what's provided as seed content+ const seedLines = [];++ if (hasName) {+ seedLines.push(`Name: ${name.trim()}`);+ } else {+ seedLines.push('Name: (generate a creative name)');+ }++ if (hasDescription) {+ seedLines.push(`Description: ${description.trim()}`);+ }++ if (personality.style && personality.style !== 'casual') {+ seedLines.push(`Style: ${personality.style} (use this style)`);+ }++ if (personality.tone) {+ seedLines.push(`Tone: ${personality.tone} (build on this tone)`);+ }++ if (personality.topics?.length > 0) {+ seedLines.push(`Topics: ${personality.topics.join(', ')} (include these and add more)`);+ }++ if (personality.quirks?.length > 0) {+ seedLines.push(`Quirks: ${personality.quirks.join(', ')} (include these and add more)`);+ }++ if (personality.promptPrefix) {+ seedLines.push(`Prompt Prefix hint: ${personality.promptPrefix}`);+ }++ if (avatar.emoji) {+ seedLines.push(`Emoji: ${avatar.emoji} (use this emoji)`);+ }++ if (avatar.color && avatar.color !== '#3b82f6') {+ seedLines.push(`Color: ${avatar.color} (use this color)`);+ }++ const inputSection = seedLines.length > 1+ ? seedLines.join('\n')+ : 'No seed content provided - create a completely unique and creative agent personality!';++ // Build the prompt+ const fullPrompt = GENERATION_PROMPT.replace('{inputSection}', inputSection);++ // Create a run for this generation+ const { runId } = await createRun({+ providerId: provider.id,+ model: selectedModel,+ prompt: fullPrompt,+ source: 'agent-personality-generation'+ });++ // Collect the response+ let responseText = '';++ // Use appropriate execution method based on provider type+ const isCliProvider = provider.type === 'cli';++ await new Promise((resolve, reject) => {+ if (isCliProvider) {+ // CLI providers use executeCliRun+ executeCliRun(+ runId,+ provider,+ fullPrompt,+ 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 {+ // API providers use executeApiRun+ executeApiRun(+ runId,+ provider,+ selectedModel,+ fullPrompt,+ process.cwd(),+ [],+ (data) => {+ if (data?.text) {+ responseText += data.text;+ }+ },+ (result) => {+ if (result?.error) {+ reject(new Error(result.error));+ } else {+ resolve(result);+ }+ }+ );+ }+ });++ // Parse the JSON response+ responseText = responseText.trim();++ // Check for empty response+ if (!responseText) {+ console.error('❌ AI returned empty response for personality generation');+ throw new Error('AI returned empty response. The provider may be unavailable - try a different provider or try again.');+ }++ // Extract JSON from response (handle markdown code blocks if present)+ let jsonStr = responseText;+ const jsonMatch = responseText.match(/```(?:json)?\s*([\s\S]*?)```/);+ if (jsonMatch) {+ jsonStr = jsonMatch[1].trim();+ }++ // Also try to extract just the object if there's extra text+ const objectMatch = jsonStr.match(/\{[\s\S]*\}/);+ if (objectMatch) {+ jsonStr = objectMatch[0];+ }++ let generated;+ try {+ generated = JSON.parse(jsonStr);+ } catch (parseError) {+ console.error(`❌ Failed to parse generated personality: ${parseError.message}`);+ console.error(`Response was: ${responseText.substring(0, 500)}`);+ throw new Error('Failed to parse AI response as JSON. Please try again.');+ }++ // Validate required fields+ if (!generated.personality?.style || !generated.personality?.tone) {+ throw new Error('Generated personality missing required fields. Please try again.');+ }++ // Use provided name or generated name+ const finalName = hasName ? name.trim() : (generated.name || 'Unnamed Agent');++ // Ensure arrays exist+ generated.personality.topics = generated.personality.topics || [];+ generated.personality.quirks = generated.personality.quirks || [];+ generated.personality.promptPrefix = generated.personality.promptPrefix || '';++ // Ensure avatar exists+ generated.avatar = generated.avatar || { emoji: '🤖', color: '#3b82f6' };++ // Set the name in the response+ generated.name = finalName;++ console.log(`✅ Generated personality for "${finalName}" using ${provider.name}/${selectedModel}`);++ return {+ ...generated,+ _meta: {+ generatedBy: provider.name,+ model: selectedModel,+ timestamp: new Date().toISOString()+ }+ };+}diff --git a/server/services/automationScheduler.js b/server/services/automationScheduler.jsnew file mode 100644index 0000000000..a7cb4900ec--- /dev/null+++ b/server/services/automationScheduler.js@@ -0,0 +1,411 @@+/**+ * Automation Scheduler Service+ *+ * Manages scheduled automation tasks for agent platform accounts.+ * Uses the eventScheduler pattern for reliable cron/interval/random scheduling.+ */++import { readFile, writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { v4 as uuidv4 } from 'uuid';+import EventEmitter from 'events';+import { ensureDir, PATHS } from '../lib/fileUtils.js';+import * as eventScheduler from './eventScheduler.js';+import * as agentActivity from './agentActivity.js';++const AGENTS_DIR = PATHS.agentPersonalities;+const SCHEDULES_FILE = join(AGENTS_DIR, 'schedules.json');++// Event emitter for schedule changes+export const scheduleEvents = new EventEmitter();++// In-memory cache+let cache = null;+let cacheTimestamp = 0;+const CACHE_TTL_MS = 2000;++// Track active scheduled events+const activeSchedules = new Map();++async function ensureSchedulesDir() {+ await ensureDir(AGENTS_DIR);+}++async function loadSchedules() {+ const now = Date.now();++ if (cache && (now - cacheTimestamp) < CACHE_TTL_MS) {+ return cache;+ }++ await ensureSchedulesDir();++ if (!existsSync(SCHEDULES_FILE)) {+ cache = { schedules: {} };+ cacheTimestamp = now;+ return cache;+ }++ const content = await readFile(SCHEDULES_FILE, 'utf-8');+ cache = JSON.parse(content);+ cacheTimestamp = now;+ return cache;+}++async function saveSchedules(data) {+ await ensureSchedulesDir();+ await writeFile(SCHEDULES_FILE, JSON.stringify(data, null, 2));+ cache = data;+ cacheTimestamp = Date.now();+}++export function invalidateCache() {+ cache = null;+ cacheTimestamp = 0;+}++export function notifyChanged(action = 'update', scheduleId = null) {+ scheduleEvents.emit('changed', { action, scheduleId, timestamp: Date.now() });+}++/**+ * Get all schedules+ */+export async function getAllSchedules() {+ const data = await loadSchedules();+ return Object.entries(data.schedules).map(([id, schedule]) => ({+ id,+ ...schedule,+ isActive: activeSchedules.has(id)+ }));+}++/**+ * Get schedules for a specific agent+ */+export async function getSchedulesByAgent(agentId) {+ const schedules = await getAllSchedules();+ return schedules.filter(schedule => schedule.agentId === agentId);+}++/**+ * Get schedules for a specific account+ */+export async function getSchedulesByAccount(accountId) {+ const schedules = await getAllSchedules();+ return schedules.filter(schedule => schedule.accountId === accountId);+}++/**+ * Get schedule by ID+ */+export async function getScheduleById(id) {+ const data = await loadSchedules();+ const schedule = data.schedules[id];+ return schedule ? {+ id,+ ...schedule,+ isActive: activeSchedules.has(id)+ } : null;+}++/**+ * Create a new schedule+ */+export async function createSchedule(scheduleData) {+ const data = await loadSchedules();+ const id = uuidv4();+ const now = new Date().toISOString();++ const schedule = {+ agentId: scheduleData.agentId,+ accountId: scheduleData.accountId,+ action: {+ type: scheduleData.action.type,+ params: scheduleData.action.params || {}+ },+ schedule: {+ type: scheduleData.schedule.type,+ cron: scheduleData.schedule.cron,+ intervalMs: scheduleData.schedule.intervalMs,+ randomWindow: scheduleData.schedule.randomWindow+ },+ rateLimit: scheduleData.rateLimit || {},+ enabled: scheduleData.enabled !== false,+ lastRun: null,+ runCount: 0,+ createdAt: now,+ updatedAt: now+ };++ data.schedules[id] = schedule;+ await saveSchedules(data);+ notifyChanged('create', id);++ // If enabled, activate the schedule+ if (schedule.enabled) {+ await activateSchedule(id, schedule);+ }++ console.log(`📅 Created schedule: ${schedule.action.type} (${id})`);+ return { id, ...schedule, isActive: schedule.enabled };+}++/**+ * Update an existing schedule+ */+export async function updateSchedule(id, updates) {+ const data = await loadSchedules();++ if (!data.schedules[id]) {+ return null;+ }++ const { id: _id, createdAt: _createdAt, ...cleanUpdates } = updates;+ const wasEnabled = data.schedules[id].enabled;++ const schedule = {+ ...data.schedules[id],+ ...cleanUpdates,+ createdAt: data.schedules[id].createdAt,+ updatedAt: new Date().toISOString()+ };++ data.schedules[id] = schedule;+ await saveSchedules(data);+ notifyChanged('update', id);++ // Handle enable/disable+ if (wasEnabled && !schedule.enabled) {+ await deactivateSchedule(id);+ } else if (!wasEnabled && schedule.enabled) {+ await activateSchedule(id, schedule);+ } else if (schedule.enabled) {+ // Schedule config changed, restart it+ await deactivateSchedule(id);+ await activateSchedule(id, schedule);+ }++ console.log(`📝 Updated schedule: ${schedule.action.type} (${id})`);+ return { id, ...schedule, isActive: activeSchedules.has(id) };+}++/**+ * Delete a schedule+ */+export async function deleteSchedule(id) {+ const data = await loadSchedules();++ if (!data.schedules[id]) {+ return false;+ }++ // Deactivate if running+ await deactivateSchedule(id);++ delete data.schedules[id];+ await saveSchedules(data);+ notifyChanged('delete', id);++ console.log(`🗑️ Deleted schedule (${id})`);+ return true;+}++/**+ * Toggle schedule enabled status+ */+export async function toggleSchedule(id, enabled) {+ return updateSchedule(id, { enabled });+}++/**+ * Activate a schedule (start the timer)+ */+async function activateSchedule(id, schedule) {+ // Don't double-activate+ if (activeSchedules.has(id)) {+ return;+ }++ const eventId = `agent-schedule-${id}`;++ const handler = async () => {+ await executeScheduledAction(id);+ };++ // Build schedule config based on type+ const eventConfig = {+ id: eventId,+ handler,+ metadata: {+ scheduleId: id,+ agentId: schedule.agentId,+ accountId: schedule.accountId,+ actionType: schedule.action.type+ }+ };++ if (schedule.schedule.type === 'cron') {+ eventConfig.type = 'cron';+ eventConfig.cron = schedule.schedule.cron;+ } else if (schedule.schedule.type === 'interval') {+ eventConfig.type = 'interval';+ eventConfig.intervalMs = schedule.schedule.intervalMs;+ } else if (schedule.schedule.type === 'random') {+ // For random, use interval with randomized timing+ eventConfig.type = 'interval';+ const { minMs, maxMs } = schedule.schedule.randomWindow;+ eventConfig.intervalMs = minMs + Math.random() * (maxMs - minMs);+ }++ eventScheduler.schedule(eventConfig);+ activeSchedules.set(id, eventId);++ console.log(`▶️ Activated schedule: ${schedule.action.type} (${id})`);+}++/**+ * Deactivate a schedule (stop the timer)+ */+async function deactivateSchedule(id) {+ const eventId = activeSchedules.get(id);+ if (eventId) {+ eventScheduler.cancel(eventId);+ activeSchedules.delete(id);+ console.log(`⏸️ Deactivated schedule (${id})`);+ }+}++/**+ * Execute a scheduled action+ */+async function executeScheduledAction(scheduleId) {+ const schedule = await getScheduleById(scheduleId);+ if (!schedule || !schedule.enabled) {+ return;+ }++ const now = new Date().toISOString();++ // Check rate limits+ if (schedule.rateLimit) {+ const { maxPerDay, cooldownMs } = schedule.rateLimit;++ // Check cooldown+ if (cooldownMs && schedule.lastRun) {+ const lastRunTime = new Date(schedule.lastRun).getTime();+ const elapsed = Date.now() - lastRunTime;+ if (elapsed < cooldownMs) {+ console.log(`⏳ Rate limited: ${scheduleId} - cooldown not met`);+ return;+ }+ }++ // Check daily limit (simplified - would need activity tracking for accurate count)+ if (maxPerDay) {+ const todayCount = await agentActivity.getTodayActionCount(+ schedule.accountId,+ schedule.action.type+ );+ if (todayCount >= maxPerDay) {+ console.log(`⏳ Rate limited: ${scheduleId} - daily limit reached`);+ return;+ }+ }+ }++ // Execute the action+ console.log(`🚀 Executing scheduled action: ${schedule.action.type} (${scheduleId})`);++ // Log activity+ await agentActivity.logActivity({+ agentId: schedule.agentId,+ accountId: schedule.accountId,+ scheduleId,+ action: schedule.action.type,+ params: schedule.action.params,+ status: 'started',+ timestamp: now+ });++ // Update last run+ const data = await loadSchedules();+ if (data.schedules[scheduleId]) {+ data.schedules[scheduleId].lastRun = now;+ data.schedules[scheduleId].runCount = (data.schedules[scheduleId].runCount || 0) + 1;+ await saveSchedules(data);+ }++ // Emit event for platform integration to pick up+ scheduleEvents.emit('execute', {+ scheduleId,+ schedule,+ timestamp: now+ });++ // For random schedules, reschedule with new random interval+ if (schedule.schedule.type === 'random') {+ await deactivateSchedule(scheduleId);+ const freshSchedule = await getScheduleById(scheduleId);+ if (freshSchedule && freshSchedule.enabled) {+ await activateSchedule(scheduleId, freshSchedule);+ }+ }+}++/**+ * Manually trigger a schedule to run now+ */+export async function runNow(scheduleId) {+ const schedule = await getScheduleById(scheduleId);+ if (!schedule) {+ return null;+ }++ await executeScheduledAction(scheduleId);+ return await getScheduleById(scheduleId);+}++/**+ * Initialize: Load and activate all enabled schedules+ */+export async function init() {+ const schedules = await getAllSchedules();+ let activatedCount = 0;++ for (const schedule of schedules) {+ if (schedule.enabled) {+ await activateSchedule(schedule.id, schedule);+ activatedCount++;+ }+ }++ if (activatedCount > 0) {+ console.log(`📅 Initialized ${activatedCount} agent schedules`);+ }+}++/**+ * Get schedule stats+ */+export async function getStats() {+ const schedules = await getAllSchedules();+ const byAction = {};+ let enabledCount = 0;+ let totalRuns = 0;++ for (const schedule of schedules) {+ if (schedule.enabled) enabledCount++;+ totalRuns += schedule.runCount || 0;+ byAction[schedule.action.type] = (byAction[schedule.action.type] || 0) + 1;+ }++ return {+ total: schedules.length,+ enabled: enabledCount,+ active: activeSchedules.size,+ totalRuns,+ byAction+ };+}diff --git a/server/services/brain.js b/server/services/brain.jsindex 140f01730e..5fa505bf1a 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -674,3 +674,9 @@ export const getDigests = storage.getDigests;export const getLatestDigest = storage.getLatestDigest;export const getReviews = storage.getReviews;export const getLatestReview = storage.getLatestReview;+export const getLinks = storage.getLinks;+export const getLinkById = storage.getLinkById;+export const getLinkByUrl = storage.getLinkByUrl;+export const createLink = storage.createLink;+export const updateLink = storage.updateLink;+export const deleteLink = storage.deleteLink;diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex e6f0113b96..8b81c15efe 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -27,6 +27,7 @@ const FILES = {projects: join(DATA_DIR, 'projects.json'),ideas: join(DATA_DIR, 'ideas.json'),admin: join(DATA_DIR, 'admin.json'),+ links: join(DATA_DIR, 'links.json'),digests: join(DATA_DIR, 'digests.jsonl'),reviews: join(DATA_DIR, 'reviews.jsonl')};@@ -41,6 +42,7 @@ const caches = {projects: { data: null, timestamp: 0 },ideas: { data: null, timestamp: 0 },admin: { data: null, timestamp: 0 },+ links: { data: null, timestamp: 0 },inboxLog: { data: null, timestamp: 0 },digests: { data: null, timestamp: 0 },reviews: { data: null, timestamp: 0 }@@ -527,6 +529,21 @@ export const createAdminItem = (data) => create('admin', data);export const updateAdminItem = (id, data) => update('admin', id, data);export const deleteAdminItem = (id) => remove('admin', id);+// Links+export const getLinks = (filters) => filters ? query('links', filters) : getAll('links');+export const getLinkById = (id) => getById('links', id);+export const createLink = (data) => create('links', data);+export const updateLink = (id, data) => update('links', id, data);+export const deleteLink = (id) => remove('links', id);++/**+ * Find link by URL+ */+export async function getLinkByUrl(url) {+ const links = await getAll('links');+ return links.find(link => link.url === url) || null;+}+// =============================================================================// UTILITY FUNCTIONS// =============================================================================@@ -545,11 +562,12 @@ export function invalidateAllCaches() {* Get brain data summary (for dashboard)*/export async function getSummary() {- const [people, projects, ideas, adminItems, inboxCounts, meta] = await Promise.all([+ const [people, projects, ideas, adminItems, links, inboxCounts, meta] = await Promise.all([getAll('people'),getAll('projects'),getAll('ideas'),getAll('admin'),+ getAll('links'),getInboxLogCounts(),loadMeta()]);@@ -560,10 +578,12 @@ export async function getSummary() {projects: projects.length,ideas: ideas.length,admin: adminItems.length,+ links: links.length,inbox: inboxCounts},activeProjects: projects.filter(p => p.status === 'active').length,openAdmin: adminItems.filter(a => a.status === 'open').length,+ gitHubRepos: links.filter(l => l.isGitHubRepo).length,needsReview: inboxCounts.needs_review,lastDailyDigest: meta.lastDailyDigest,lastWeeklyReview: meta.lastWeeklyReviewdiff --git a/server/services/githubCloner.js b/server/services/githubCloner.jsnew file mode 100644index 0000000000..396d2ffee1--- /dev/null+++ b/server/services/githubCloner.js@@ -0,0 +1,250 @@+/**+ * GitHub Repository Cloner Service+ *+ * Handles cloning GitHub repositories to a local directory for reference.+ * Supports shallow clones to save space and provides progress tracking.+ */++import { spawn } from 'child_process';+import { mkdir } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);++// Default directory for cloned repos (can be configured in settings)+const DEFAULT_CLONE_DIR = join(__dirname, '../../data/repos');++/**+ * Parse GitHub URL to extract owner and repo name+ * Supports formats:+ * - https://github.com/owner/repo+ * - https://github.com/owner/repo.git+ * - [email protected]:owner/repo.git+ * - github.com/owner/repo+ */+export function parseGitHubUrl(url) {+ if (!url) return null;++ // Normalize URL+ let normalized = url.trim();++ // Handle SSH format: [email protected]:owner/repo.git+ const sshMatch = normalized.match(/git@github\.com:([^/]+)\/([^/.]+)(?:\.git)?$/i);+ if (sshMatch) {+ return {+ owner: sshMatch[1],+ repo: sshMatch[2],+ isGitHub: true+ };+ }++ // Handle HTTPS format: https://github.com/owner/repo or github.com/owner/repo+ const httpsMatch = normalized.match(/(?:https?:\/\/)?github\.com\/([^/]+)\/([^/?#]+)/i);+ if (httpsMatch) {+ return {+ owner: httpsMatch[1],+ repo: httpsMatch[2].replace(/\.git$/, ''),+ isGitHub: true+ };+ }++ return null;+}++/**+ * Check if a URL is a GitHub repository URL+ */+export function isGitHubRepoUrl(url) {+ return parseGitHubUrl(url) !== null;+}++/**+ * Get clone directory path+ */+export function getCloneDir(customDir) {+ return customDir || DEFAULT_CLONE_DIR;+}++/**+ * Ensure clone directory exists+ */+export async function ensureCloneDir(cloneDir) {+ const dir = getCloneDir(cloneDir);+ if (!existsSync(dir)) {+ await mkdir(dir, { recursive: true });+ console.log(`📁 Created repos directory: ${dir}`);+ }+ return dir;+}++/**+ * Clone a GitHub repository+ * Returns the local path where the repo was cloned+ */+export async function cloneRepo(url, options = {}) {+ const parsed = parseGitHubUrl(url);+ if (!parsed) {+ throw new Error('Invalid GitHub URL');+ }++ const { owner, repo } = parsed;+ const cloneDir = await ensureCloneDir(options.cloneDir);+ const localPath = join(cloneDir, owner, repo);++ // Check if already cloned+ if (existsSync(join(localPath, '.git'))) {+ console.log(`📦 Repo already cloned: ${owner}/${repo}`);+ return {+ localPath,+ owner,+ repo,+ alreadyCloned: true+ };+ }++ // Ensure owner directory exists+ const ownerDir = join(cloneDir, owner);+ if (!existsSync(ownerDir)) {+ await mkdir(ownerDir, { recursive: true });+ }++ // Build clone command with shallow clone for space efficiency+ const httpsUrl = `https://github.com/${owner}/${repo}.git`;+ const args = [+ 'clone',+ '--depth', '1',+ '--single-branch',+ httpsUrl,+ localPath+ ];++ console.log(`📥 Cloning ${owner}/${repo}...`);++ return new Promise((resolve, reject) => {+ const child = spawn('git', args, {+ env: process.env,+ shell: false+ });++ let stderr = '';++ child.stderr.on('data', (data) => {+ stderr += data.toString();+ });++ child.on('close', (code) => {+ if (code === 0) {+ console.log(`✅ Cloned ${owner}/${repo} to ${localPath}`);+ resolve({+ localPath,+ owner,+ repo,+ alreadyCloned: false+ });+ } else {+ console.error(`❌ Failed to clone ${owner}/${repo}: ${stderr}`);+ reject(new Error(`Git clone failed: ${stderr || `exit code ${code}`}`));+ }+ });++ child.on('error', (err) => {+ console.error(`❌ Git clone error: ${err.message}`);+ reject(err);+ });++ // Timeout after 5 minutes+ setTimeout(() => {+ child.kill();+ reject(new Error('Clone timed out after 5 minutes'));+ }, 300000);+ });+}++/**+ * Pull latest changes for an existing repo+ */+export async function pullRepo(localPath) {+ if (!existsSync(join(localPath, '.git'))) {+ throw new Error('Not a git repository');+ }++ console.log(`🔄 Pulling latest for ${localPath}...`);++ return new Promise((resolve, reject) => {+ const child = spawn('git', ['pull', '--ff-only'], {+ cwd: localPath,+ env: process.env,+ shell: false+ });++ let stdout = '';+ let stderr = '';++ child.stdout.on('data', (data) => {+ stdout += data.toString();+ });++ child.stderr.on('data', (data) => {+ stderr += data.toString();+ });++ child.on('close', (code) => {+ if (code === 0) {+ console.log(`✅ Pulled latest for ${localPath}`);+ resolve({ stdout, stderr, success: true });+ } else {+ console.error(`❌ Failed to pull ${localPath}: ${stderr}`);+ reject(new Error(`Git pull failed: ${stderr || `exit code ${code}`}`));+ }+ });++ child.on('error', reject);++ // Timeout after 2 minutes+ setTimeout(() => {+ child.kill();+ reject(new Error('Pull timed out after 2 minutes'));+ }, 120000);+ });+}++/**+ * Get repo info (last commit, etc.)+ */+export async function getRepoInfo(localPath) {+ if (!existsSync(join(localPath, '.git'))) {+ return null;+ }++ return new Promise((resolve) => {+ const child = spawn('git', ['log', '-1', '--format=%H|%s|%ci'], {+ cwd: localPath,+ env: process.env,+ shell: false+ });++ let stdout = '';++ child.stdout.on('data', (data) => {+ stdout += data.toString();+ });++ child.on('close', (code) => {+ if (code === 0 && stdout.trim()) {+ const [hash, message, date] = stdout.trim().split('|');+ resolve({+ lastCommitHash: hash,+ lastCommitMessage: message,+ lastCommitDate: date+ });+ } else {+ resolve(null);+ }+ });++ child.on('error', () => resolve(null));+ });+}diff --git a/server/services/platformAccounts.js b/server/services/platformAccounts.jsnew file mode 100644index 0000000000..d70cf7515e--- /dev/null+++ b/server/services/platformAccounts.js@@ -0,0 +1,249 @@+/**+ * Platform Accounts Service+ *+ * Manages platform accounts that agents use to interact with social platforms.+ * Each account links an agent to a specific platform (e.g., Moltbook) with+ * credentials and status tracking.+ */++import { readFile, writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { v4 as uuidv4 } from 'uuid';+import EventEmitter from 'events';+import { ensureDir, PATHS } from '../lib/fileUtils.js';++const AGENTS_DIR = PATHS.agentPersonalities;+const ACCOUNTS_FILE = join(AGENTS_DIR, 'accounts.json');++// Event emitter for account changes+export const platformAccountEvents = new EventEmitter();++// In-memory cache+let cache = null;+let cacheTimestamp = 0;+const CACHE_TTL_MS = 2000;++async function ensureAccountsDir() {+ await ensureDir(AGENTS_DIR);+}++async function loadAccounts() {+ const now = Date.now();++ if (cache && (now - cacheTimestamp) < CACHE_TTL_MS) {+ return cache;+ }++ await ensureAccountsDir();++ if (!existsSync(ACCOUNTS_FILE)) {+ cache = { accounts: {} };+ cacheTimestamp = now;+ return cache;+ }++ const content = await readFile(ACCOUNTS_FILE, 'utf-8');+ cache = JSON.parse(content);+ cacheTimestamp = now;+ return cache;+}++async function saveAccounts(data) {+ await ensureAccountsDir();+ await writeFile(ACCOUNTS_FILE, JSON.stringify(data, null, 2));+ cache = data;+ cacheTimestamp = Date.now();+}++export function invalidateCache() {+ cache = null;+ cacheTimestamp = 0;+}++export function notifyChanged(action = 'update', accountId = null) {+ platformAccountEvents.emit('changed', { action, accountId, timestamp: Date.now() });+}++/**+ * Get all platform accounts+ */+export async function getAllAccounts() {+ const data = await loadAccounts();+ return Object.entries(data.accounts).map(([id, account]) => ({+ id,+ ...account,+ // Mask the API key for security+ credentials: {+ ...account.credentials,+ apiKey: account.credentials?.apiKey ? '***' + account.credentials.apiKey.slice(-4) : null+ }+ }));+}++/**+ * Get all accounts for a specific agent+ */+export async function getAccountsByAgent(agentId) {+ const accounts = await getAllAccounts();+ return accounts.filter(account => account.agentId === agentId);+}++/**+ * Get account by ID (with full credentials for internal use)+ */+export async function getAccountById(id, maskCredentials = true) {+ const data = await loadAccounts();+ const account = data.accounts[id];+ if (!account) return null;++ return {+ id,+ ...account,+ credentials: maskCredentials ? {+ ...account.credentials,+ apiKey: account.credentials?.apiKey ? '***' + account.credentials.apiKey.slice(-4) : null+ } : account.credentials+ };+}++/**+ * Get account with full credentials (for platform API calls)+ */+export async function getAccountWithCredentials(id) {+ return getAccountById(id, false);+}++/**+ * Create a new platform account+ */+export async function createAccount(accountData) {+ const data = await loadAccounts();+ const id = uuidv4();+ const now = new Date().toISOString();++ const account = {+ agentId: accountData.agentId,+ platform: accountData.platform,+ credentials: {+ apiKey: accountData.credentials.apiKey,+ username: accountData.credentials.username+ },+ status: accountData.status || 'pending',+ lastActivity: null,+ platformData: accountData.platformData || {},+ createdAt: now+ };++ data.accounts[id] = account;+ await saveAccounts(data);+ notifyChanged('create', id);++ console.log(`🔗 Created platform account: ${account.platform}/${account.credentials.username} (${id})`);+ return {+ id,+ ...account,+ credentials: {+ ...account.credentials,+ apiKey: '***' + account.credentials.apiKey.slice(-4)+ }+ };+}++/**+ * Update account status+ */+export async function updateAccountStatus(id, status, platformData = null) {+ const data = await loadAccounts();++ if (!data.accounts[id]) {+ return null;+ }++ data.accounts[id].status = status;+ data.accounts[id].lastActivity = new Date().toISOString();+ if (platformData) {+ data.accounts[id].platformData = {+ ...data.accounts[id].platformData,+ ...platformData+ };+ }++ await saveAccounts(data);+ notifyChanged('update', id);++ return getAccountById(id);+}++/**+ * Record activity on account+ */+export async function recordActivity(id) {+ const data = await loadAccounts();++ if (!data.accounts[id]) {+ return null;+ }++ data.accounts[id].lastActivity = new Date().toISOString();+ await saveAccounts(data);++ return getAccountById(id);+}++/**+ * Update account credentials+ */+export async function updateCredentials(id, credentials) {+ const data = await loadAccounts();++ if (!data.accounts[id]) {+ return null;+ }++ data.accounts[id].credentials = {+ ...data.accounts[id].credentials,+ ...credentials+ };++ await saveAccounts(data);+ notifyChanged('update', id);++ console.log(`🔑 Updated credentials for account ${id}`);+ return getAccountById(id);+}++/**+ * Delete a platform account+ */+export async function deleteAccount(id) {+ const data = await loadAccounts();++ if (!data.accounts[id]) {+ return false;+ }++ const account = data.accounts[id];+ delete data.accounts[id];+ await saveAccounts(data);+ notifyChanged('delete', id);++ console.log(`🗑️ Deleted platform account: ${account.platform}/${account.credentials.username} (${id})`);+ return true;+}++/**+ * Get accounts by platform+ */+export async function getAccountsByPlatform(platform) {+ const accounts = await getAllAccounts();+ return accounts.filter(account => account.platform === platform);+}++/**+ * Get active accounts for an agent+ */+export async function getActiveAccountsForAgent(agentId) {+ const accounts = await getAccountsByAgent(agentId);+ return accounts.filter(account => account.status === 'active');+}diff --git a/server/services/socket.js b/server/services/socket.jsindex fcce3b381a..9f15826b4a 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -7,6 +7,10 @@ import { handleErrorRecovery } from './autoFixer.js';import * as pm2Standardizer from './pm2Standardizer.js';import { notificationEvents } from './notifications.js';import { providerStatusEvents } from './providerStatus.js';+import { agentPersonalityEvents } from './agentPersonalities.js';+import { platformAccountEvents } from './platformAccounts.js';+import { scheduleEvents } from './automationScheduler.js';+import { activityEvents } from './agentActivity.js';// Store active log streams per socketconst activeStreams = new Map();@@ -16,6 +20,8 @@ const cosSubscribers = new Set();const errorSubscribers = new Set();// Store notification subscribersconst notificationSubscribers = new Set();+// Store agent subscribers+const agentSubscribers = new Set();// Store io instance for broadcastinglet ioInstance = null;@@ -198,6 +204,17 @@ export function initSocket(io) {socket.emit('notifications:unsubscribed');});+ // Agent subscriptions+ socket.on('agents:subscribe', () => {+ agentSubscribers.add(socket);+ socket.emit('agents:subscribed');+ });++ socket.on('agents:unsubscribe', () => {+ agentSubscribers.delete(socket);+ socket.emit('agents:unsubscribed');+ });+// Handle error recovery requests (can trigger auto-fix agents)socket.on('error:recover', async ({ code, context }) => {console.log(`🔧 Error recovery requested: ${code}`);@@ -221,6 +238,7 @@ export function initSocket(io) {cosSubscribers.delete(socket);errorSubscribers.delete(socket);notificationSubscribers.delete(socket);+ agentSubscribers.delete(socket);});});@@ -241,6 +259,9 @@ export function initSocket(io) {// Set up provider status event forwardingsetupProviderStatusEventForwarding();++ // Set up agent event forwarding+ setupAgentEventForwarding();}function cleanupStream(socketId) {@@ -358,3 +379,27 @@ function setupProviderStatusEventForwarding() {}});}++// Broadcast to agent subscribers only+function broadcastToAgents(event, data) {+ for (const socket of agentSubscribers) {+ socket.emit(event, data);+ }+}++// Set up agent event forwarding+function setupAgentEventForwarding() {+ // Personality events+ agentPersonalityEvents.on('changed', (data) => broadcastToAgents('agents:personality:changed', data));++ // Account events+ platformAccountEvents.on('changed', (data) => broadcastToAgents('agents:account:changed', data));++ // Schedule events+ scheduleEvents.on('changed', (data) => broadcastToAgents('agents:schedule:changed', data));+ scheduleEvents.on('execute', (data) => broadcastToAgents('agents:schedule:execute', data));++ // Activity events+ activityEvents.on('activity', (data) => broadcastToAgents('agents:activity', data));+ activityEvents.on('activity:updated', (data) => broadcastToAgents('agents:activity:updated', data));+}diff --git a/server/services/taskEnhancer.js b/server/services/taskEnhancer.jsindex ec0d1c5b63..0966761821 100644--- a/server/services/taskEnhancer.js+++ b/server/services/taskEnhancer.js@@ -7,7 +7,7 @@* Uses the 'cos-task-enhance' prompt stage for provider/model configuration.*/-import { executeApiRun, createRun } from './runner.js';+import { executeApiRun, executeCliRun, createRun } from './runner.js';import { getActiveProvider, getProviderById } from './providers.js';import { getStage, buildPrompt } from './promptService.js';@@ -94,27 +94,52 @@ export async function enhanceTaskPrompt(description, context = '') {// Collect the responselet enhancedDescription = '';+ // Use appropriate execution method based on provider type+ const isCliProvider = provider.type === 'cli';+await new Promise((resolve, reject) => {- executeApiRun(- runId,- provider,- model,- fullPrompt,- process.cwd(),- [], // No screenshots needed- (data) => {- if (data?.text) {- enhancedDescription += data.text;- }- },- (result) => {- if (result?.error) {- reject(new Error(result.error));- } else {- resolve(result);+ if (isCliProvider) {+ // CLI providers use executeCliRun+ executeCliRun(+ runId,+ provider,+ fullPrompt,+ process.cwd(),+ (text) => {+ enhancedDescription += text;+ },+ (result) => {+ if (result?.error || result?.success === false) {+ reject(new Error(result?.error || 'CLI execution failed'));+ } else {+ resolve(result);+ }+ },+ provider.timeout || 300000+ );+ } else {+ // API providers use executeApiRun+ executeApiRun(+ runId,+ provider,+ model,+ fullPrompt,+ process.cwd(),+ [], // No screenshots needed+ (data) => {+ if (data?.text) {+ enhancedDescription += data.text;+ }+ },+ (result) => {+ if (result?.error) {+ reject(new Error(result.error));+ } else {+ resolve(result);+ }}- }- );+ );+ }});// Clean up the response - remove any leading/trailing whitespace and common prefixes@@ -135,6 +160,12 @@ export async function enhanceTaskPrompt(description, context = '') {enhancedDescription = enhancedDescription.trim();+ // Ensure we have a valid enhanced description+ if (!enhancedDescription) {+ console.warn(`⚠️ Task enhancement returned empty result from ${provider.name}/${model}`);+ throw new Error('AI enhancement returned empty result');+ }+console.log(`✅ Enhanced task prompt (${enhancedDescription.length} chars) using ${provider.name}/${model}`);return {