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(moltworld): add World tab, WebSocket relay, action queue, explorer and maze scripts
Adam Eivy9020b58660a7
diff --git a/client/src/components/agents/constants.js b/client/src/components/agents/constants.jsindex 04639985af..2661d0582b 100644--- a/client/src/components/agents/constants.js+++ b/client/src/components/agents/constants.js@@ -4,7 +4,8 @@export const AGENT_DETAIL_TABS = [{ id: 'overview', label: 'Overview', icon: '📋' },- { id: 'tools', label: 'Tools', icon: '🛠️' },+ { id: 'tools', label: 'Moltbook', icon: '📚' },+ { id: 'world', label: 'World', icon: '🌍' },{ id: 'published', label: 'Published', icon: '📰' },{ id: 'schedules', label: 'Schedules', icon: '📅' },{ id: 'activity', label: 'Activity', icon: '📊' }@@ -28,10 +29,11 @@ export const ACTION_TYPES = [{ value: 'monitor', label: 'Monitor', description: 'Check post engagement and respond', icon: '👀', platform: 'moltbook' },// Moltworld actions{ value: 'mw_heartbeat', label: 'Heartbeat', description: 'Stay visible in the world', icon: '💓', platform: 'moltworld' },- { value: 'explore', label: 'Explore', description: 'Move to coordinates and observe', icon: '🌍', platform: 'moltworld' },- { value: 'build', label: 'Build', description: 'Place or remove blocks', icon: '🧱', platform: 'moltworld' },- { value: 'say', label: 'Say', description: 'Send messages to nearby agents', icon: '💬', platform: 'moltworld' },- { value: 'interact', label: 'Interact', description: 'Move, think, and optionally build', icon: '🤝', platform: 'moltworld' }+ { value: 'mw_explore', label: 'Explore', description: 'Move to coordinates and observe', icon: '🌍', platform: 'moltworld' },+ { value: 'mw_build', label: 'Build', description: 'Place or remove blocks', icon: '🧱', platform: 'moltworld' },+ { value: 'mw_say', label: 'Say', description: 'Send messages to nearby agents', icon: '💬', platform: 'moltworld' },+ { value: 'mw_think', label: 'Think', description: 'Send a visible thought', icon: '💭', platform: 'moltworld' },+ { value: 'mw_interact', label: 'Interact', description: 'Move, think, and optionally build', icon: '🤝', platform: 'moltworld' }];export const SCHEDULE_TYPES = [diff --git a/client/src/components/agents/tabs/WorldTab.jsx b/client/src/components/agents/tabs/WorldTab.jsxnew file mode 100644index 0000000000..cce85b3062--- /dev/null+++ b/client/src/components/agents/tabs/WorldTab.jsx@@ -0,0 +1,1010 @@+import { useState, useEffect, useCallback } from 'react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';+import BrailleSpinner from '../../BrailleSpinner';+import socket from '../../../services/socket';+import useMoltworldWs from '../../../hooks/useMoltworldWs';++const EVENT_ICONS = {+ status: '🔌',+ presence: '👥',+ thinking: '💭',+ thought: '💭',+ action: '🎬',+ move: '🚶',+ build: '🧱',+ interaction: '💬',+ message: '💬',+ say: '💬',+ nearby: '📡',+ hello_ack: '👋',+ welcome: '👋',+ event: '📨'+};++const HISTORY_ACTION_ICONS = {+ mw_explore: '🌍',+ mw_build: '🧱',+ mw_think: '💭',+ mw_say: '💬',+ mw_heartbeat: '💓',+ mw_interact: '🤝'+};++const HISTORY_FILTERS = [+ { value: '', label: 'All' },+ { value: 'mw_explore', label: 'Explore' },+ { value: 'mw_think', label: 'Think' },+ { value: 'mw_say', label: 'Say' },+ { value: 'mw_build', label: 'Build' },+ { value: 'mw_heartbeat', label: 'Heartbeat' }+];++const QUEUE_ACTION_TYPES = [+ { value: 'mw_explore', label: 'Explore' },+ { value: 'mw_think', label: 'Think' },+ { value: 'mw_build', label: 'Build' },+ { value: 'mw_say', label: 'Say' }+];++const QUEUE_STATUS_STYLES = {+ pending: 'bg-gray-600/20 text-gray-400',+ executing: 'bg-port-accent/20 text-port-accent animate-pulse',+ completed: 'bg-port-success/20 text-port-success',+ failed: 'bg-port-error/20 text-port-error'+};++function formatEventTime(ts) {+ const d = new Date(ts);+ return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });+}++function formatRelativeTime(ts) {+ const diff = Date.now() - new Date(ts).getTime();+ if (diff < 60000) return 'just now';+ if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;+ if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;+ return `${Math.floor(diff / 86400000)}d ago`;+}++function summarizeParams(action, params) {+ if (!params) return '';+ if (action === 'mw_explore' || action === 'mw_heartbeat') {+ const parts = [];+ if (params.x != null && params.y != null) parts.push(`(${params.x}, ${params.y})`);+ if (params.thinking) parts.push(`"${params.thinking.substring(0, 40)}..."`);+ return parts.join(' ');+ }+ if (action === 'mw_think') return params.thought ? `"${params.thought.substring(0, 50)}"` : '';+ if (action === 'mw_say') return params.message ? `"${params.message.substring(0, 50)}"` : '';+ if (action === 'mw_build') return `(${params.x},${params.y},${params.z}) ${params.type || 'stone'} ${params.action || 'place'}`;+ return '';+}++export default function WorldTab({ agentId }) {+ const [accountId, setAccountId] = useState(null);+ const [accountName, setAccountName] = useState('');+ const [rateLimits, setRateLimits] = useState(null);+ const [loading, setLoading] = useState(true);++ // Status state+ const [status, setStatus] = useState(null);+ const [statusLoading, setStatusLoading] = useState(false);++ // Nearby agents + messages from last join/explore+ const [nearby, setNearby] = useState([]);+ const [messages, setMessages] = useState([]);++ // Move/Explore state+ const [moveX, setMoveX] = useState('');+ const [moveY, setMoveY] = useState('');+ const [moveThinking, setMoveThinking] = useState('');+ const [moving, setMoving] = useState(false);++ // Think state+ const [thought, setThought] = useState('');+ const [thinking, setThinking] = useState(false);++ // Build state+ const [buildX, setBuildX] = useState('');+ const [buildY, setBuildY] = useState('');+ const [buildZ, setBuildZ] = useState('0');+ const [blockType, setBlockType] = useState('stone');+ const [buildAction, setBuildAction] = useState('place');+ const [building, setBuilding] = useState(false);++ // Say state+ const [sayMessage, setSayMessage] = useState('');+ const [sayTo, setSayTo] = useState('');+ const [saying, setSaying] = useState(false);++ // Cooldown timer state+ const [cooldownEnds, setCooldownEnds] = useState({});+ const [, setTick] = useState(0);++ // Activity History state+ const [history, setHistory] = useState([]);+ const [historyLoading, setHistoryLoading] = useState(false);+ const [historyHasMore, setHistoryHasMore] = useState(false);+ const [historyFilter, setHistoryFilter] = useState('');++ // Action Queue state+ const [queue, setQueue] = useState([]);+ const [queueLoading, setQueueLoading] = useState(false);+ const [showAddForm, setShowAddForm] = useState(false);+ const [newActionType, setNewActionType] = useState('mw_explore');+ const [newActionParams, setNewActionParams] = useState({});++ // WebSocket hook+ const {+ connectionStatus,+ feedItems,+ presence,+ connect: wsConnect,+ disconnect: wsDisconnect+ } = useMoltworldWs();++ const wsConnected = connectionStatus === 'connected';++ // Auto-resolve the moltworld account for this agent+ useEffect(() => {+ api.getPlatformAccounts(agentId, 'moltworld').then(data => {+ const active = data.filter(a => a.status === 'active');+ if (active.length > 0) {+ setAccountId(active[0].id);+ setAccountName(active[0].credentials?.username || '');+ }+ setLoading(false);+ }).catch(() => setLoading(false));+ }, [agentId]);++ const fetchStatus = useCallback(async () => {+ if (!accountId) return;+ setStatusLoading(true);+ const data = await api.moltworldStatus(accountId).catch(() => null);+ if (data) setStatus(data);+ setStatusLoading(false);+ }, [accountId]);++ const fetchRateLimits = useCallback(async () => {+ if (!accountId) return;+ const data = await api.moltworldRateLimits(accountId).catch(() => null);+ if (data) setRateLimits(data);+ }, [accountId]);++ // Fetch activity history+ const fetchHistory = useCallback(async (append = false, before = null) => {+ setHistoryLoading(true);+ const mwActions = historyFilter || 'mw_explore,mw_build,mw_think,mw_say,mw_heartbeat,mw_interact';+ let data;+ if (before) {+ data = await api.getAgentActivityTimeline(30, [agentId], before).catch(() => null);+ } else {+ data = await api.getAgentActivities(30, [agentId], mwActions).catch(() => null);+ }+ if (data) {+ const items = Array.isArray(data) ? data : data.activities || [];+ // Filter to mw_* actions only+ const mwItems = items.filter(a => a.action?.startsWith('mw_'));+ if (append) {+ setHistory(prev => [...prev, ...mwItems]);+ } else {+ setHistory(mwItems);+ }+ setHistoryHasMore(mwItems.length >= 30);+ }+ setHistoryLoading(false);+ }, [agentId, historyFilter]);++ // Fetch action queue+ const fetchQueue = useCallback(async () => {+ setQueueLoading(true);+ const data = await api.moltworldGetQueue(agentId).catch(() => null);+ if (data) setQueue(data);+ setQueueLoading(false);+ }, [agentId]);++ // Fetch status + rate limits + history + queue when account resolves+ useEffect(() => {+ if (!accountId) return;+ fetchStatus();+ fetchRateLimits();+ fetchHistory();+ fetchQueue();+ }, [accountId, fetchStatus, fetchRateLimits, fetchHistory, fetchQueue]);++ // Re-fetch history when filter changes+ useEffect(() => {+ if (accountId) fetchHistory();+ }, [historyFilter]); // eslint-disable-line react-hooks/exhaustive-deps++ // Listen for queue Socket.IO events+ useEffect(() => {+ const handleQueueChange = () => fetchQueue();+ socket.on('moltworld:queue:added', handleQueueChange);+ socket.on('moltworld:queue:updated', handleQueueChange);+ socket.on('moltworld:queue:removed', handleQueueChange);+ return () => {+ socket.off('moltworld:queue:added', handleQueueChange);+ socket.off('moltworld:queue:updated', handleQueueChange);+ socket.off('moltworld:queue:removed', handleQueueChange);+ };+ }, [fetchQueue]);++ // Calculate cooldown end timestamps from rate limit data+ useEffect(() => {+ if (!rateLimits) { setCooldownEnds({}); return; }+ const ends = {};+ const now = Date.now();+ for (const [action, rl] of Object.entries(rateLimits)) {+ if (rl?.cooldownRemainingMs > 0) {+ ends[action] = now + rl.cooldownRemainingMs;+ }+ }+ setCooldownEnds(ends);+ }, [rateLimits]);++ // Tick cooldown timer every second while any cooldown is active+ useEffect(() => {+ const hasActive = Object.values(cooldownEnds).some(end => end > Date.now());+ if (!hasActive) return;+ let refetched = false;+ const interval = setInterval(() => {+ const stillActive = Object.values(cooldownEnds).some(end => end > Date.now());+ setTick(t => t + 1);+ if (!stillActive && !refetched) {+ refetched = true;+ fetchRateLimits();+ }+ }, 1000);+ return () => clearInterval(interval);+ }, [cooldownEnds, fetchRateLimits]);++ const updateFromJoinResponse = (result) => {+ if (result?.agents) setNearby(result.agents);+ const msgs = [+ ...(result?.messages || []).map(m => ({ ...m, type: 'say', from: m.fromName })),+ ...(result?.thoughts || []).map(t => ({ ...t, type: 'thought', from: t.agentName, message: t.thought }))+ ].sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));+ if (msgs.length) setMessages(msgs);+ };++ const refreshAfterAction = () => {+ fetchRateLimits();+ fetchHistory();+ };++ const handleExplore = async (random = false) => {+ if (!accountId) return;+ setMoving(true);+ const x = random ? undefined : (moveX !== '' ? parseInt(moveX) : undefined);+ const y = random ? undefined : (moveY !== '' ? parseInt(moveY) : undefined);++ if (wsConnected && !random && x != null && y != null) {+ await api.moltworldWsMove(x, y, moveThinking || undefined).catch(() => null);+ setMoving(false);+ toast.success(`Move sent via WS to (${x}, ${y})`);+ refreshAfterAction();+ return;+ }++ const result = await api.moltworldExplore(+ accountId, agentId, x, y, moveThinking || undefined+ ).catch(() => null);+ setMoving(false);+ if (!result) { fetchRateLimits(); return; }+ updateFromJoinResponse(result);+ toast.success(`Moved to (${result.x}, ${result.y})`);+ fetchStatus();+ refreshAfterAction();+ };++ const handleThink = async () => {+ if (!accountId || !thought) return;+ setThinking(true);++ if (wsConnected) {+ await api.moltworldWsThink(thought).catch(() => null);+ setThinking(false);+ toast.success('Thought sent via WS');+ setThought('');+ refreshAfterAction();+ return;+ }++ const result = await api.moltworldThink(accountId, thought, agentId).catch(() => null);+ setThinking(false);+ if (!result) { fetchRateLimits(); return; }+ toast.success('Thought sent');+ setThought('');+ refreshAfterAction();+ };++ const handleBuild = async () => {+ if (!accountId || buildX === '' || buildY === '') return;+ setBuilding(true);+ const result = await api.moltworldBuild(+ accountId, agentId,+ parseInt(buildX), parseInt(buildY), parseInt(buildZ || '0'),+ blockType, buildAction+ ).catch(() => null);+ setBuilding(false);+ if (!result) { fetchRateLimits(); return; }+ toast.success(`Block ${buildAction}d at (${buildX}, ${buildY}, ${buildZ})`);+ refreshAfterAction();+ };++ const handleSay = async () => {+ if (!accountId || !sayMessage) return;+ setSaying(true);++ if (wsConnected && sayTo) {+ await api.moltworldWsInteract(sayTo, { message: sayMessage }).catch(() => null);+ setSaying(false);+ toast.success('DM sent via WS');+ setSayMessage('');+ setSayTo('');+ refreshAfterAction();+ return;+ }++ const result = await api.moltworldSay(+ accountId, sayMessage, sayTo || undefined, agentId+ ).catch(() => null);+ setSaying(false);+ if (!result) { fetchRateLimits(); return; }+ updateFromJoinResponse(result);+ toast.success(sayTo ? 'DM sent' : 'Message sent');+ setSayMessage('');+ setSayTo('');+ refreshAfterAction();+ };++ const handleLoadMoreHistory = () => {+ if (history.length === 0) return;+ const lastTs = history[history.length - 1].timestamp;+ fetchHistory(true, lastTs);+ };++ const handleAddToQueue = async () => {+ const params = { ...newActionParams };+ // Convert numeric fields+ if (params.x != null) params.x = parseInt(params.x);+ if (params.y != null) params.y = parseInt(params.y);+ if (params.z != null) params.z = parseInt(params.z);++ await api.moltworldAddToQueue(agentId, newActionType, params).catch(() => null);+ setShowAddForm(false);+ setNewActionParams({});+ toast.success('Action queued');+ };++ const handleRemoveFromQueue = async (id) => {+ await api.moltworldRemoveFromQueue(id).catch(() => null);+ };++ const getCooldownMs = (action) => {+ const end = cooldownEnds[action];+ return end ? Math.max(0, end - Date.now()) : 0;+ };++ const formatCooldown = (ms) => {+ const totalSeconds = Math.ceil(ms / 1000);+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ return `${minutes}:${seconds.toString().padStart(2, '0')}`;+ };++ if (loading) {+ return <div className="p-4"><BrailleSpinner text="Loading world tools" /></div>;+ }++ if (!accountId) {+ return (+ <div className="p-4 text-center py-12 text-gray-400">+ <p className="text-lg mb-2">No active Moltworld account</p>+ <p className="text-sm">Register a Moltworld account on the Overview tab to get started</p>+ </div>+ );+ }++ const profile = status?.profile;+ const bal = status?.balance?.balance || status?.balance;+ const displayNearby = presence.length > 0 ? presence : nearby;++ const statusDotColor = {+ connected: 'bg-port-success',+ connecting: 'bg-port-warning animate-pulse',+ reconnecting: 'bg-port-warning animate-pulse',+ disconnected: 'bg-gray-600'+ }[connectionStatus] || 'bg-gray-600';++ // Dynamic param fields for add-to-queue form+ const renderQueueParamFields = () => {+ switch (newActionType) {+ case 'mw_explore':+ return (+ <div className="grid grid-cols-2 gap-2">+ <input type="number" placeholder="X" value={newActionParams.x || ''} onChange={e => setNewActionParams(p => ({ ...p, x: e.target.value }))} className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm" />+ <input type="number" placeholder="Y" value={newActionParams.y || ''} onChange={e => setNewActionParams(p => ({ ...p, y: e.target.value }))} className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm" />+ <input type="text" placeholder="Thinking (optional)" value={newActionParams.thinking || ''} onChange={e => setNewActionParams(p => ({ ...p, thinking: e.target.value }))} className="col-span-2 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm" />+ </div>+ );+ case 'mw_think':+ return (+ <input type="text" placeholder="Thought text" value={newActionParams.thought || ''} onChange={e => setNewActionParams(p => ({ ...p, thought: e.target.value }))} className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm" />+ );+ case 'mw_build':+ return (+ <div className="grid grid-cols-3 gap-2">+ <input type="number" placeholder="X" value={newActionParams.x || ''} onChange={e => setNewActionParams(p => ({ ...p, x: e.target.value }))} className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm" />+ <input type="number" placeholder="Y" value={newActionParams.y || ''} onChange={e => setNewActionParams(p => ({ ...p, y: e.target.value }))} className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm" />+ <input type="number" placeholder="Z" value={newActionParams.z || ''} onChange={e => setNewActionParams(p => ({ ...p, z: e.target.value }))} className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm" />+ <select value={newActionParams.type || 'stone'} onChange={e => setNewActionParams(p => ({ ...p, type: e.target.value }))} className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm">+ <option value="wood">Wood</option>+ <option value="stone">Stone</option>+ <option value="dirt">Dirt</option>+ <option value="grass">Grass</option>+ <option value="leaves">Leaves</option>+ </select>+ <select value={newActionParams.action || 'place'} onChange={e => setNewActionParams(p => ({ ...p, action: e.target.value }))} className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm">+ <option value="place">Place</option>+ <option value="remove">Remove</option>+ </select>+ </div>+ );+ case 'mw_say':+ return (+ <div className="space-y-2">+ <input type="text" placeholder="Message" value={newActionParams.message || ''} onChange={e => setNewActionParams(p => ({ ...p, message: e.target.value }))} className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm" />+ <input type="text" placeholder="To Agent ID (optional)" value={newActionParams.sayTo || ''} onChange={e => setNewActionParams(p => ({ ...p, sayTo: e.target.value }))} className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm" />+ </div>+ );+ default:+ return null;+ }+ };++ return (+ <div className="p-4">+ {/* Connection Banner */}+ <div className="flex flex-wrap items-center gap-4 mb-4 p-3 bg-port-card border border-port-border rounded-lg">+ <div className="flex items-center gap-2">+ <span className={`w-2.5 h-2.5 rounded-full ${statusDotColor}`} />+ <span className="text-sm text-gray-400">WebSocket:</span>+ <span className="text-sm text-white font-medium">{connectionStatus}</span>+ </div>+ <div className="flex gap-2 ml-auto">+ {connectionStatus === 'disconnected' ? (+ <button+ onClick={() => wsConnect(accountId)}+ className="px-3 py-1 text-sm bg-port-accent text-white rounded hover:bg-port-accent/80"+ >+ Connect+ </button>+ ) : (+ <button+ onClick={wsDisconnect}+ className="px-3 py-1 text-sm bg-port-border text-gray-300 rounded hover:bg-port-border/80"+ >+ Disconnect+ </button>+ )}+ </div>+ </div>++ {/* Header: Account Name + Rate Limits */}+ <div className="flex flex-wrap items-center gap-4 mb-6 p-4 bg-port-card border border-port-border rounded-lg">+ <span className="text-sm text-gray-400">Account: <span className="text-white font-medium">{accountName}</span></span>+ {rateLimits && (+ <div className="flex gap-3 ml-auto">+ {Object.entries(rateLimits).map(([action, rl]) => {+ if (!rl?.cooldownMs) return null;+ const cooldownMs = getCooldownMs(action);+ const isCooling = cooldownMs > 0;+ const colorClass = isCooling+ ? 'bg-port-warning/20 text-port-warning animate-pulse'+ : 'bg-port-success/20 text-port-success';+ return (+ <div key={action} className={`text-xs px-2 py-1 rounded ${colorClass}`} title={isCooling ? `Cooldown: ${formatCooldown(cooldownMs)}` : `${action} ready`}>+ {isCooling ? `${action}: ${formatCooldown(cooldownMs)}` : `${action}: ready`}+ </div>+ );+ })}+ </div>+ )}+ </div>++ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">+ {/* Left Column: World State */}+ <div className="space-y-4">+ {/* Status Card */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between mb-3">+ <h3 className="font-semibold text-white">World Status</h3>+ <button+ onClick={fetchStatus}+ disabled={statusLoading}+ className="px-3 py-1 text-sm bg-port-border text-gray-300 rounded hover:bg-port-border/80 disabled:opacity-50"+ >+ {statusLoading ? 'Loading...' : 'Refresh'}+ </button>+ </div>++ {!status && !statusLoading && (+ <p className="text-sm text-gray-500">No status data yet. Click Refresh.</p>+ )}++ {status && (+ <div className="space-y-3">+ <div className="grid grid-cols-2 gap-3 text-sm">+ <div>+ <span className="text-gray-500">Status</span>+ <div className="flex items-center gap-1.5 mt-0.5">+ <span className={`w-2 h-2 rounded-full ${(profile?.inWorld || bal?.isOnline) ? 'bg-port-success' : 'bg-gray-600'}`} />+ <span className="text-white">{(profile?.inWorld || bal?.isOnline) ? 'Online' : 'Offline'}</span>+ </div>+ </div>+ <div>+ <span className="text-gray-500">Position</span>+ <p className="text-white mt-0.5">+ ({profile?.worldState?.x ?? '?'}, {profile?.worldState?.y ?? '?'})+ </p>+ </div>+ <div>+ <span className="text-gray-500">SIM Balance</span>+ <p className="text-port-accent font-medium mt-0.5">+ {bal?.sim != null ? Number(bal.sim).toFixed(2) : '?'} SIM+ </p>+ </div>+ <div>+ <span className="text-gray-500">Earning Rate</span>+ <p className="text-white mt-0.5">+ {bal?.earningRate ?? '0.1 SIM/hour'}+ </p>+ </div>+ {bal?.totalEarned != null && (+ <div>+ <span className="text-gray-500">Total Earned</span>+ <p className="text-white mt-0.5">{Number(bal.totalEarned).toFixed(2)} SIM</p>+ </div>+ )}+ {bal?.totalOnlineTime != null && (+ <div>+ <span className="text-gray-500">Online Time</span>+ <p className="text-white mt-0.5">{bal.totalOnlineTime}</p>+ </div>+ )}+ </div>+ {profile?.agent?.name && (+ <div className="text-xs text-gray-500 pt-2 border-t border-port-border">+ Agent: {profile.agent.name} {profile.agent?.appearance?.emoji || ''}+ </div>+ )}+ </div>+ )}+ </div>++ {/* Live Feed */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-3">+ <h3 className="font-semibold text-white">Live Feed</h3>+ {wsConnected && (+ <span className="text-xs text-port-success flex items-center gap-1">+ <span className="w-1.5 h-1.5 rounded-full bg-port-success animate-pulse" />+ live+ </span>+ )}+ {feedItems.length > 0 && (+ <span className="text-gray-500 font-normal text-sm">({feedItems.length})</span>+ )}+ </div>+ {feedItems.length === 0 ? (+ <p className="text-sm text-gray-500 text-center py-4">+ {wsConnected ? 'Waiting for events...' : 'Connect WebSocket to see live events'}+ </p>+ ) : (+ <div className="space-y-1.5 max-h-[300px] overflow-y-auto">+ {feedItems.slice(0, 50).map((item) => (+ <div key={item.id} className="flex items-start gap-2 p-1.5 bg-port-bg rounded text-xs">+ <span className="shrink-0">{EVENT_ICONS[item.eventType] || '📨'}</span>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ {item.agentName && (+ <span className="text-port-accent font-medium truncate">{item.agentName}</span>+ )}+ <span className="px-1 py-0.5 bg-port-border rounded text-gray-500 shrink-0">{item.eventType}</span>+ </div>+ {item.content && (+ <p className="text-gray-400 truncate mt-0.5">{item.content}</p>+ )}+ </div>+ <span className="text-gray-600 shrink-0 text-[10px]">{formatEventTime(item.timestamp)}</span>+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Nearby Agents */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="font-semibold text-white mb-3">+ Nearby Agents{displayNearby.length > 0 && <span className="text-gray-500 font-normal ml-2 text-sm">({displayNearby.length})</span>}+ {presence.length > 0 && wsConnected && (+ <span className="text-xs text-port-success ml-2 font-normal">(live)</span>+ )}+ </h3>+ {displayNearby.length === 0 ? (+ <p className="text-sm text-gray-500 text-center py-4">+ No nearby agents. Explore the world to discover others.+ </p>+ ) : (+ <div className="space-y-2 max-h-[300px] overflow-y-auto">+ {displayNearby.slice(0, 20).map((agent, i) => (+ <div key={agent.id || i} className="flex items-center justify-between p-2 bg-port-bg rounded text-sm">+ <div className="flex items-center gap-2">+ <span>{agent.appearance?.emoji || '🤖'}</span>+ <span className="text-white">{agent.name || 'Unknown'}</span>+ {agent.thinking && <span className="text-gray-500 text-xs truncate max-w-[150px]">"{agent.thinking}"</span>}+ </div>+ <span className="text-gray-500 text-xs">+ ({agent.x ?? '?'}, {agent.y ?? '?'})+ {agent.distance != null && ` - ${Math.round(agent.distance)}m`}+ </span>+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Recent Messages */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="font-semibold text-white mb-3">Recent Messages</h3>+ {messages.length === 0 ? (+ <p className="text-sm text-gray-500 text-center py-4">+ No recent messages. Messages expire after 5 minutes.+ </p>+ ) : (+ <div className="space-y-2 max-h-[250px] overflow-y-auto">+ {messages.map((msg, i) => (+ <div key={msg.id || i} className="p-2 bg-port-bg rounded text-sm">+ <div className="flex items-center gap-2">+ <span className="text-port-accent font-medium">{msg.from || 'Agent'}</span>+ {msg.type === 'thought' && <span className="text-xs text-gray-600">(thought)</span>}+ {msg.type === 'say' && <span className="text-xs text-port-success">(say)</span>}+ </div>+ <p className="text-gray-400 mt-0.5">{msg.message || msg.thought}</p>+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Activity History */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between mb-3">+ <h3 className="font-semibold text-white">Activity History</h3>+ <div className="flex items-center gap-2">+ <select+ value={historyFilter}+ onChange={e => setHistoryFilter(e.target.value)}+ className="px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-white"+ >+ {HISTORY_FILTERS.map(f => (+ <option key={f.value} value={f.value}>{f.label}</option>+ ))}+ </select>+ <button+ onClick={() => fetchHistory()}+ disabled={historyLoading}+ className="px-2 py-1 text-xs bg-port-border text-gray-300 rounded hover:bg-port-border/80 disabled:opacity-50"+ >+ {historyLoading ? '...' : 'Refresh'}+ </button>+ </div>+ </div>+ {history.length === 0 ? (+ <p className="text-sm text-gray-500 text-center py-4">+ {historyLoading ? 'Loading...' : 'No activity history yet'}+ </p>+ ) : (+ <div className="space-y-1.5 max-h-[400px] overflow-y-auto">+ {history.map((entry) => (+ <div key={entry.id} className="flex items-start gap-2 p-2 bg-port-bg rounded text-xs">+ <span className="shrink-0 text-sm">{HISTORY_ACTION_ICONS[entry.action] || '📋'}</span>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <span className="px-1.5 py-0.5 bg-port-border rounded text-gray-300 font-medium">+ {entry.action?.replace('mw_', '')}+ </span>+ <span className={`px-1 py-0.5 rounded text-[10px] ${entry.status === 'completed' ? 'bg-port-success/20 text-port-success' : 'bg-port-error/20 text-port-error'}`}>+ {entry.status}+ </span>+ {entry.params?.via === 'ws' && (+ <span className="text-[10px] text-port-accent">WS</span>+ )}+ </div>+ <p className="text-gray-400 truncate mt-0.5">+ {summarizeParams(entry.action, entry.params)}+ </p>+ </div>+ <span className="text-gray-600 shrink-0 text-[10px]" title={entry.timestamp}>+ {formatRelativeTime(entry.timestamp)}+ </span>+ </div>+ ))}+ {historyHasMore && (+ <button+ onClick={handleLoadMoreHistory}+ disabled={historyLoading}+ className="w-full py-2 text-xs text-gray-400 hover:text-white bg-port-bg rounded disabled:opacity-50"+ >+ {historyLoading ? 'Loading...' : 'Load More'}+ </button>+ )}+ </div>+ )}+ </div>+ </div>++ {/* Right Column: Actions */}+ <div className="space-y-4">+ {/* Action Queue */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between mb-3">+ <h3 className="font-semibold text-white">Action Queue</h3>+ <div className="flex items-center gap-2">+ {queue.length > 0 && (+ <span className="text-xs text-gray-500">{queue.length} item{queue.length !== 1 ? 's' : ''}</span>+ )}+ <button+ onClick={() => { setShowAddForm(!showAddForm); setNewActionParams({}); }}+ className="px-2 py-1 text-xs bg-port-accent text-white rounded hover:bg-port-accent/80"+ >+ {showAddForm ? 'Cancel' : '+ Add'}+ </button>+ </div>+ </div>++ {showAddForm && (+ <div className="mb-3 p-3 bg-port-bg border border-port-border rounded space-y-2">+ <select+ value={newActionType}+ onChange={e => { setNewActionType(e.target.value); setNewActionParams({}); }}+ className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"+ >+ {QUEUE_ACTION_TYPES.map(t => (+ <option key={t.value} value={t.value}>{t.label}</option>+ ))}+ </select>+ {renderQueueParamFields()}+ <button+ onClick={handleAddToQueue}+ className="w-full px-3 py-1.5 text-sm bg-port-accent text-white rounded hover:bg-port-accent/80"+ >+ Add to Queue+ </button>+ </div>+ )}++ {queue.length === 0 && !queueLoading ? (+ <p className="text-sm text-gray-500 text-center py-4">No queued actions</p>+ ) : (+ <div className="space-y-1.5 max-h-[300px] overflow-y-auto">+ {queue.map((item) => (+ <div key={item.id} className="flex items-center gap-2 p-2 bg-port-bg rounded text-xs">+ <span className="shrink-0">{HISTORY_ACTION_ICONS[item.actionType] || '📋'}</span>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <span className="text-gray-300 font-medium">{item.actionType?.replace('mw_', '')}</span>+ <span className={`px-1 py-0.5 rounded text-[10px] ${QUEUE_STATUS_STYLES[item.status] || ''}`}>+ {item.status}+ </span>+ </div>+ <p className="text-gray-500 truncate mt-0.5">+ {summarizeParams(item.actionType, item.params)}+ </p>+ </div>+ {item.status === 'pending' && (+ <button+ onClick={() => handleRemoveFromQueue(item.id)}+ className="shrink-0 text-gray-500 hover:text-port-error text-sm"+ title="Cancel"+ >+ x+ </button>+ )}+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Move / Explore */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-3">+ <h3 className="font-semibold text-white">Move / Explore</h3>+ {wsConnected && <span className="text-xs text-port-success">(via WS)</span>}+ </div>+ <div className="grid grid-cols-2 gap-2 mb-2">+ <div>+ <label className="block text-xs text-gray-500 mb-1">X (-240 to 240)</label>+ <input+ type="number"+ value={moveX}+ onChange={(e) => setMoveX(e.target.value)}+ min={-240}+ max={240}+ placeholder="X"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ />+ </div>+ <div>+ <label className="block text-xs text-gray-500 mb-1">Y (-240 to 240)</label>+ <input+ type="number"+ value={moveY}+ onChange={(e) => setMoveY(e.target.value)}+ min={-240}+ max={240}+ placeholder="Y"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ />+ </div>+ </div>+ <input+ type="text"+ value={moveThinking}+ onChange={(e) => setMoveThinking(e.target.value)}+ placeholder="Thinking... (optional)"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white mb-3"+ />+ <div className="flex gap-2">+ <button+ onClick={() => handleExplore(false)}+ disabled={moving || (moveX === '' && moveY === '')}+ className="px-4 py-2 bg-port-accent text-white rounded hover:bg-port-accent/80 disabled:opacity-50"+ >+ {moving ? 'Moving...' : 'Move Here'}+ </button>+ <button+ onClick={() => handleExplore(true)}+ disabled={moving}+ className="px-4 py-2 bg-purple-600 text-white rounded hover:bg-purple-500 disabled:opacity-50"+ >+ {moving ? 'Exploring...' : 'Random Explore'}+ </button>+ </div>+ </div>++ {/* Think */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-3">+ <h3 className="font-semibold text-white">Think</h3>+ {wsConnected && <span className="text-xs text-port-success">(via WS)</span>}+ </div>+ <input+ type="text"+ value={thought}+ onChange={(e) => setThought(e.target.value)}+ placeholder="What is this agent thinking?"+ maxLength={500}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white mb-3"+ />+ <button+ onClick={handleThink}+ disabled={thinking || !thought || getCooldownMs('think') > 0}+ className="px-4 py-2 bg-port-accent text-white rounded hover:bg-port-accent/80 disabled:opacity-50"+ title={getCooldownMs('think') > 0 ? `Cooldown: ${formatCooldown(getCooldownMs('think'))}` : ''}+ >+ {thinking ? 'Thinking...' : getCooldownMs('think') > 0 ? `Wait ${formatCooldown(getCooldownMs('think'))}` : 'Think'}+ </button>+ </div>++ {/* Build */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="font-semibold text-white mb-3">Build</h3>+ <div className="grid grid-cols-3 gap-2 mb-2">+ <div>+ <label className="block text-xs text-gray-500 mb-1">X</label>+ <input+ type="number"+ value={buildX}+ onChange={(e) => setBuildX(e.target.value)}+ min={-500}+ max={500}+ placeholder="X"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ />+ </div>+ <div>+ <label className="block text-xs text-gray-500 mb-1">Y</label>+ <input+ type="number"+ value={buildY}+ onChange={(e) => setBuildY(e.target.value)}+ min={-500}+ max={500}+ placeholder="Y"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ />+ </div>+ <div>+ <label className="block text-xs text-gray-500 mb-1">Z (height)</label>+ <input+ type="number"+ value={buildZ}+ onChange={(e) => setBuildZ(e.target.value)}+ min={0}+ max={100}+ placeholder="Z"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ />+ </div>+ </div>+ <div className="grid grid-cols-2 gap-2 mb-3">+ <select+ value={blockType}+ onChange={(e) => setBlockType(e.target.value)}+ className="px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ >+ <option value="wood">Wood</option>+ <option value="stone">Stone</option>+ <option value="dirt">Dirt</option>+ <option value="grass">Grass</option>+ <option value="leaves">Leaves</option>+ </select>+ <select+ value={buildAction}+ onChange={(e) => setBuildAction(e.target.value)}+ className="px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ >+ <option value="place">Place</option>+ <option value="remove">Remove</option>+ </select>+ </div>+ <button+ onClick={handleBuild}+ disabled={building || buildX === '' || buildY === '' || getCooldownMs('build') > 0}+ className="px-4 py-2 bg-port-accent text-white rounded hover:bg-port-accent/80 disabled:opacity-50"+ title={getCooldownMs('build') > 0 ? `Cooldown: ${formatCooldown(getCooldownMs('build'))}` : ''}+ >+ {building ? 'Building...' : getCooldownMs('build') > 0 ? `Wait ${formatCooldown(getCooldownMs('build'))}` : 'Build'}+ </button>+ </div>++ {/* Say */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-3">+ <h3 className="font-semibold text-white">Say</h3>+ {wsConnected && sayTo && <span className="text-xs text-port-success">(DM via WS)</span>}+ </div>+ <input+ type="text"+ value={sayMessage}+ onChange={(e) => setSayMessage(e.target.value)}+ placeholder="Message to nearby agents..."+ maxLength={500}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white mb-2"+ />+ <input+ type="text"+ value={sayTo}+ onChange={(e) => setSayTo(e.target.value)}+ placeholder="To Agent ID (optional — leave blank for broadcast)"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white mb-3"+ />+ <button+ onClick={handleSay}+ disabled={saying || !sayMessage || getCooldownMs('join') > 0}+ className="px-4 py-2 bg-port-accent text-white rounded hover:bg-port-accent/80 disabled:opacity-50"+ title={getCooldownMs('join') > 0 ? `Cooldown: ${formatCooldown(getCooldownMs('join'))}` : ''}+ >+ {saying ? 'Sending...' : getCooldownMs('join') > 0 ? `Wait ${formatCooldown(getCooldownMs('join'))}` : 'Say'}+ </button>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/hooks/useMoltworldWs.js b/client/src/hooks/useMoltworldWs.jsnew file mode 100644index 0000000000..7fb1c6ce8f--- /dev/null+++ b/client/src/hooks/useMoltworldWs.js@@ -0,0 +1,109 @@+import { useState, useEffect, useCallback, useRef } from 'react';+import socket from '../services/socket';+import * as api from '../services/api';++const MAX_FEED_ITEMS = 200;+let idCounter = 0;++/**+ * Hook for Moltworld real-time WebSocket events.+ *+ * Subscribes to moltworld:* Socket.IO events and maintains:+ * - connectionStatus: 'disconnected' | 'connecting' | 'connected' | 'reconnecting'+ * - feedItems: ring buffer of last 200 events (newest first)+ * - presence: latest agent presence snapshot+ * - connect(accountId) / disconnect(): control the server-side WS relay+ */+export default function useMoltworldWs() {+ const [connectionStatus, setConnectionStatus] = useState('disconnected');+ const [feedItems, setFeedItems] = useState([]);+ const [presence, setPresence] = useState([]);+ const feedRef = useRef([]);++ const addFeedItem = useCallback((eventType, data) => {+ const item = {+ id: ++idCounter,+ eventType,+ agentName: data.agentName || data.name || data.agentId || '',+ content: data.message || data.thought || data.thinking || data.action || '',+ timestamp: data.timestamp || Date.now(),+ raw: data+ };+ feedRef.current = [item, ...feedRef.current].slice(0, MAX_FEED_ITEMS);+ setFeedItems([...feedRef.current]);+ }, []);++ useEffect(() => {+ // Subscribe to agents channel (moltworld events ride on agent subscribers)+ socket.emit('agents:subscribe');++ const handleStatus = (data) => {+ setConnectionStatus(data.status || 'disconnected');+ addFeedItem('status', { ...data, agentName: 'System', content: `Connection: ${data.status}` });+ };+ const handleEvent = (data) => {+ addFeedItem(data.type || data.event || 'event', data);+ };+ const handlePresence = (data) => {+ const agents = data.agents || data.nearby || [];+ if (agents.length > 0) setPresence(agents);+ addFeedItem('presence', { ...data, content: `${agents.length} agents nearby` });+ };+ const handleThinking = (data) => {+ addFeedItem('thinking', data);+ };+ const handleAction = (data) => {+ addFeedItem('action', data);+ };+ const handleInteraction = (data) => {+ addFeedItem('interaction', data);+ };+ const handleNearby = (data) => {+ const agents = data.agents || data.nearby || [];+ if (agents.length > 0) setPresence(agents);+ addFeedItem('nearby', { ...data, content: `${agents.length} agents` });+ };++ socket.on('moltworld:status', handleStatus);+ socket.on('moltworld:event', handleEvent);+ socket.on('moltworld:presence', handlePresence);+ socket.on('moltworld:thinking', handleThinking);+ socket.on('moltworld:action', handleAction);+ socket.on('moltworld:interaction', handleInteraction);+ socket.on('moltworld:nearby', handleNearby);++ // Fetch initial WS status+ api.moltworldWsStatus().then(data => {+ if (data?.status) setConnectionStatus(data.status);+ }).catch(() => {});++ return () => {+ socket.off('moltworld:status', handleStatus);+ socket.off('moltworld:event', handleEvent);+ socket.off('moltworld:presence', handlePresence);+ socket.off('moltworld:thinking', handleThinking);+ socket.off('moltworld:action', handleAction);+ socket.off('moltworld:interaction', handleInteraction);+ socket.off('moltworld:nearby', handleNearby);+ };+ }, [addFeedItem]);++ const connect = useCallback(async (accountId) => {+ setConnectionStatus('connecting');+ const result = await api.moltworldWsConnect(accountId).catch(() => null);+ if (result?.status) setConnectionStatus(result.status);+ }, []);++ const disconnect = useCallback(async () => {+ await api.moltworldWsDisconnect().catch(() => null);+ setConnectionStatus('disconnected');+ }, []);++ return {+ connectionStatus,+ feedItems,+ presence,+ connect,+ disconnect+ };+}diff --git a/package-lock.json b/package-lock.jsonindex a63c853ab9..e4fd2e78ee 100644--- a/package-lock.json+++ b/package-lock.json@@ -102,6 +102,7 @@"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/code-frame": "^7.27.1","@babel/generator": "^7.28.5",@@ -395,6 +396,7 @@"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz","integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==","license": "MIT",+ "peer": true,"dependencies": {"@dnd-kit/accessibility": "^3.1.1","@dnd-kit/utilities": "^3.2.2",@@ -437,7 +439,6 @@"integrity": "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==","license": "MIT","optional": true,- "peer": true,"dependencies": {"tslib": "^2.4.0"}@@ -890,7 +891,6 @@"integrity": "sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==","license": "MIT","optional": true,- "peer": true,"engines": {"node": ">=18"}@@ -907,7 +907,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -930,7 +929,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -953,7 +951,6 @@"os": ["darwin"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -970,7 +967,6 @@"os": ["darwin"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -987,7 +983,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1004,7 +999,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1021,7 +1015,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1038,7 +1031,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1055,7 +1047,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1072,7 +1063,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1089,7 +1079,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1106,7 +1095,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1123,7 +1111,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1146,7 +1133,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1169,7 +1155,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1192,7 +1177,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1215,7 +1199,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1238,7 +1221,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1261,7 +1243,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1284,7 +1265,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1304,7 +1284,6 @@],"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT","optional": true,- "peer": true,"dependencies": {"@emnapi/runtime": "^1.7.0"},@@ -1327,7 +1306,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1347,7 +1325,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1367,7 +1344,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1447,8 +1423,7 @@"version": "16.1.6","resolved": "https://registry.npmjs.org/@next/env/-/env-16.1.6.tgz","integrity": "sha512-N1ySLuZjnAtN3kFnwhAwPvZah8RJxKasD7x1f8shFqhncnWZn4JMfg37diLNuoHsLAlrDfM3g4mawVdtAG8XLQ==",- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/@next/swc-darwin-arm64": {"version": "16.1.6",@@ -1462,7 +1437,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">= 10"}@@ -1479,7 +1453,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">= 10"}@@ -1496,7 +1469,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1513,7 +1485,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1530,7 +1501,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1547,7 +1517,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1564,7 +1533,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">= 10"}@@ -1581,7 +1549,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">= 10"}@@ -2043,6 +2010,7 @@"resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-8.18.0.tgz","integrity": "sha512-FYZZqD0UUHUswKz3LQl2Z7H24AhD14XGTsIRw3SJaXUxyfVMi+1yiZGmqTcPt/CkPpdU7rrxqcyQ1zJE5DjvIQ==","license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.17.8","@types/react-reconciler": "^0.26.7",@@ -2488,7 +2456,6 @@"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz","integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==","license": "Apache-2.0",- "peer": true,"dependencies": {"tslib": "^2.8.0"}@@ -2636,6 +2603,7 @@"resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.6.tgz","integrity": "sha512-NNu0sjyNxpoiW3YuVFfNz7mxSQ+S4X2G28uqg2s+CzoqoQjLPsWSbsFFyztIAqt2vb8kfEAsJNepMGPTxFDx3Q==","license": "MIT",+ "peer": true,"dependencies": {"undici-types": "~7.16.0"}@@ -2651,6 +2619,7 @@"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.13.tgz","integrity": "sha512-KkiJeU6VbYbUOp5ITMIc7kBfqlYkKA5KhEHVrGMmUUMt7NeaZg65ojdPk+FtNrBAOXNVM5QM72jnADjM+XVRAQ==","license": "MIT",+ "peer": true,"dependencies": {"csstype": "^3.2.2"}@@ -2675,6 +2644,7 @@"resolved": "https://registry.npmjs.org/@types/three/-/three-0.182.0.tgz","integrity": "sha512-WByN9V3Sbwbe2OkWuSGyoqQO8Du6yhYaXtXLoA5FkKTUJorZ+yOHBZ35zUUPQXlAKABZmbYp5oAqpA4RBjtJ/Q==","license": "MIT",+ "peer": true,"dependencies": {"@dimforge/rapier3d-compat": "~0.12.0","@tweenjs/tween.js": "~23.1.3",@@ -3282,6 +3252,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",@@ -3563,8 +3534,7 @@"version": "0.0.1","resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz","integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/cliui": {"version": "8.0.1",@@ -3788,7 +3758,8 @@"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz","integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/culvert": {"version": "0.1.2",@@ -3925,7 +3896,6 @@"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==","license": "Apache-2.0","optional": true,- "peer": true,"engines": {"node": ">=8"}@@ -4381,6 +4351,7 @@"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz","integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==","license": "MIT",+ "peer": true,"dependencies": {"accepts": "^2.0.0","body-parser": "^2.2.1",@@ -5248,6 +5219,7 @@"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==","dev": true,"license": "MIT",+ "peer": true,"bin": {"jiti": "bin/jiti.js"}@@ -6293,7 +6265,6 @@"resolved": "https://registry.npmjs.org/next/-/next-16.1.6.tgz","integrity": "sha512-hkyRkcu5x/41KoqnROkfTm2pZVbKxvbZRuNvKXLRXxs3VfyO0WhY50TQS40EuKO9SW3rBj/sF3WbVwDACeMZyw==","license": "MIT",- "peer": true,"dependencies": {"@next/env": "16.1.6","@swc/helpers": "0.5.15",@@ -6361,7 +6332,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"nanoid": "^3.3.6","picocolors": "^1.0.0",@@ -6840,6 +6810,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"nanoid": "^3.3.11","picocolors": "^1.1.1",@@ -7149,6 +7120,7 @@"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz","integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0"},@@ -7173,6 +7145,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz","integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0","scheduler": "^0.23.2"@@ -7696,7 +7669,6 @@"hasInstallScript": true,"license": "Apache-2.0","optional": true,- "peer": true,"dependencies": {"@img/colour": "^1.0.0","detect-libc": "^2.1.2",@@ -7741,7 +7713,6 @@"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==","license": "ISC","optional": true,- "peer": true,"bin": {"semver": "bin/semver.js"},@@ -8196,7 +8167,6 @@"resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz","integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==","license": "MIT",- "peer": true,"dependencies": {"client-only": "0.0.1"},@@ -8426,7 +8396,8 @@"version": "0.182.0","resolved": "https://registry.npmjs.org/three/-/three-0.182.0.tgz","integrity": "sha512-GbHabT+Irv+ihI1/f5kIIsZ+Ef9Sl5A1Y7imvS5RQjWgtTPfPnZ43JmlYI7NtCRDK9zir20lQpfg8/9Yd02OvQ==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/three-mesh-bvh": {"version": "0.7.8",@@ -8519,6 +8490,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -8932,6 +8904,7 @@"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "^0.25.0","fdir": "^6.4.4",@@ -9025,6 +8998,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -9038,6 +9012,7 @@"integrity": "sha512-E4t7DJ9pESL6E3I8nFjPa4xGUd3PmiWDLsDztS2qXSJWfHtbQnwAWylaBvSNY48I3vr8PTqIZlyK8TE3V3CA4Q==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@vitest/expect": "4.0.16","@vitest/mocker": "4.0.16",@@ -9375,6 +9350,7 @@"socket.io": "^4.8.3","socket.io-client": "^4.8.3","uuid": "^11.0.3",+ "ws": "^7.5.10","zod": "^3.24.1"},"devDependencies": {diff --git a/server/index.js b/server/index.jsindex d823395746..909807b79d 100644--- a/server/index.js+++ b/server/index.js@@ -37,6 +37,7 @@ import socialAccountsRoutes from './routes/socialAccounts.js';import lmstudioRoutes from './routes/lmstudio.js';import browserRoutes from './routes/browser.js';import moltworldToolsRoutes from './routes/moltworldTools.js';+import moltworldWsRoutes from './routes/moltworldWs.js';import { initSocket } from './services/socket.js';import { initScriptRunner } from './services/scriptRunner.js';import { errorMiddleware, setupProcessErrorHandlers, asyncHandler } from './lib/errorHandler.js';@@ -186,6 +187,7 @@ app.use('/api/agents/personalities', agentPersonalitiesRoutes);app.use('/api/agents/accounts', platformAccountsRoutes);app.use('/api/agents/schedules', automationSchedulesRoutes);app.use('/api/agents/activity', agentActivityRoutes);+app.use('/api/agents/tools/moltworld/ws', moltworldWsRoutes);app.use('/api/agents/tools/moltworld', moltworldToolsRoutes);app.use('/api/agents/tools', agentToolsRoutes);// Existing running agents routes (process management)diff --git a/server/integrations/moltworld/api.js b/server/integrations/moltworld/api.jsindex 29e3a0b57a..4714057dbd 100644--- a/server/integrations/moltworld/api.js+++ b/server/integrations/moltworld/api.js@@ -106,8 +106,11 @@ export async function register(name, appearance = {}) {})});- console.log(`🆕 Moltworld: Registered agent "${name}" (agentId=${result?.agentId})`);- return result;+ // Normalize: API may return { agent: { id } } or { agentId }+ const agentId = result?.agentId || result?.agent?.id || result?.id;+ const apiKey = result?.apiKey || result?.api_key || agentId;+ console.log(`🆕 Moltworld: Registered agent "${name}" (agentId=${agentId})`);+ return { ...result, agentId, apiKey };}// =============================================================================diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 21742cc830..81995c2fee 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -95,7 +95,7 @@ export const accountRegistrationSchema = z.object({export const scheduleActionTypeSchema = z.enum(['post', 'comment', 'vote', 'heartbeat', 'engage', 'monitor',- 'explore', 'build', 'say', 'mw_heartbeat', 'interact'+ 'mw_explore', 'mw_build', 'mw_say', 'mw_think', 'mw_heartbeat', 'mw_interact']);export const scheduleActionSchema = z.object({@@ -299,6 +299,7 @@ export const updateDraftSchema = z.object({export const moltworldJoinSchema = z.object({accountId: z.string().min(1),+ agentId: z.string().min(1).optional(),x: z.number().int().min(-240).max(240).optional(),y: z.number().int().min(-240).max(240).optional(),thinking: z.string().max(500).optional(),@@ -324,6 +325,46 @@ export const moltworldExploreSchema = z.object({thinking: z.string().max(500).optional()});+export const moltworldThinkSchema = z.object({+ accountId: z.string().min(1),+ agentId: z.string().min(1).optional(),+ thought: z.string().min(1).max(500)+});++export const moltworldSaySchema = z.object({+ accountId: z.string().min(1),+ agentId: z.string().min(1).optional(),+ message: z.string().min(1).max(500),+ sayTo: z.string().optional()+});++// =============================================================================+// MOLTWORLD WEBSOCKET SCHEMAS+// =============================================================================++export const moltworldWsConnectSchema = z.object({+ accountId: z.string().min(1)+});++export const moltworldWsMoveSchema = z.object({+ x: z.number().int().min(-240).max(240),+ y: z.number().int().min(-240).max(240),+ thought: z.string().max(500).optional()+});++export const moltworldWsThinkSchema = z.object({+ thought: z.string().min(1).max(500)+});++export const moltworldWsNearbySchema = z.object({+ radius: z.number().int().min(1).max(500).optional()+});++export const moltworldWsInteractSchema = z.object({+ to: z.string().min(1),+ payload: z.record(z.unknown()).optional().default({})+});+/*** Validate data against a schema* Returns { success: true, data } or { success: false, errors }diff --git a/server/package.json b/server/package.jsonindex 7ab61abe17..575db4d2c9 100644--- a/server/package.json+++ b/server/package.json@@ -19,6 +19,7 @@"socket.io": "^4.8.3","socket.io-client": "^4.8.3","uuid": "^11.0.3",+ "ws": "^7.5.10","zod": "^3.24.1"},"devDependencies": {diff --git a/server/routes/moltworldTools.js b/server/routes/moltworldTools.jsindex 2e827dcc97..0cede02872 100644--- a/server/routes/moltworldTools.js+++ b/server/routes/moltworldTools.js@@ -7,11 +7,12 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validate, moltworldJoinSchema, moltworldBuildSchema, moltworldExploreSchema } from '../lib/validation.js';+import { validate, moltworldJoinSchema, moltworldBuildSchema, moltworldExploreSchema, moltworldThinkSchema, moltworldSaySchema } from '../lib/validation.js';import * as platformAccounts from '../services/platformAccounts.js';import * as agentPersonalities from '../services/agentPersonalities.js';import * as agentActivity from '../services/agentActivity.js';import { MoltworldClient } from '../integrations/moltworld/index.js';+import * as moltworldQueue from '../services/moltworldQueue.js';const router = Router();@@ -32,9 +33,11 @@ async function getClientAndAgent(accountId, agentId) {const agent = agentId ? await agentPersonalities.getAgentById(agentId) : null;+ // Moltworld uses agentId for all API calls; fall back to apiKey which serves as the agent identifier+ const moltworldAgentId = account.credentials.agentId || account.credentials.apiKey;const client = new MoltworldClient(account.credentials.apiKey,- account.credentials.agentId+ moltworldAgentId);return { client, agent, account };}@@ -48,7 +51,7 @@ router.post('/join', asyncHandler(async (req, res) => {console.log(`🌍 POST /api/agents/tools/moltworld/join account=${data.accountId}`);- const { client, account } = await getClientAndAgent(data.accountId, null);+ const { client, account } = await getClientAndAgent(data.accountId, data.agentId);const result = await client.joinWorld({name: account.credentials.username,x: data.x ?? 0,@@ -59,6 +62,17 @@ router.post('/join', asyncHandler(async (req, res) => {});await platformAccounts.recordActivity(data.accountId);+ if (data.agentId) {+ await agentActivity.logActivity({+ agentId: data.agentId,+ accountId: data.accountId,+ action: 'mw_heartbeat',+ params: { x: data.x, y: data.y, thinking: data.thinking, say: data.say },+ status: 'completed',+ result: { agents: result?.agents?.length || 0, messages: result?.messages?.length || 0 },+ timestamp: new Date().toISOString()+ });+ }res.json(result);}));@@ -85,7 +99,7 @@ router.post('/build', asyncHandler(async (req, res) => {await agentActivity.logActivity({agentId: data.agentId,accountId: data.accountId,- action: 'build',+ action: 'mw_build',params: { x: data.x, y: data.y, z: data.z, type: data.type, action: data.action },status: 'completed',result: { type: 'build', ...result },@@ -123,10 +137,10 @@ router.post('/explore', asyncHandler(async (req, res) => {await agentActivity.logActivity({agentId: data.agentId,accountId: data.accountId,- action: 'explore',+ action: 'mw_explore',params: { x, y, thinking: data.thinking },status: 'completed',- result: { type: 'explore', x, y, nearby: result?.nearby?.length || 0 },+ result: { type: 'explore', x, y, nearby: result?.agents?.length || 0 },timestamp: new Date().toISOString()});}@@ -134,6 +148,64 @@ router.post('/explore', asyncHandler(async (req, res) => {res.json({ x, y, ...result });}));+// POST /think — Send a thought+router.post('/think', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(moltworldThinkSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`💭 POST /api/agents/tools/moltworld/think account=${data.accountId}`);++ const { client } = await getClientAndAgent(data.accountId, data.agentId);+ const result = await client.think(data.thought);++ await platformAccounts.recordActivity(data.accountId);+ if (data.agentId) {+ await agentActivity.logActivity({+ agentId: data.agentId,+ accountId: data.accountId,+ action: 'mw_think',+ params: { thought: data.thought },+ status: 'completed',+ result: { type: 'think' },+ timestamp: new Date().toISOString()+ });+ }+ res.json(result);+}));++// POST /say — Send a message (wraps join with say/sayTo params)+router.post('/say', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(moltworldSaySchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`💬 POST /api/agents/tools/moltworld/say account=${data.accountId}`);++ const { client, account } = await getClientAndAgent(data.accountId, data.agentId);+ const result = await client.joinWorld({+ name: account.credentials.username,+ say: data.message,+ sayTo: data.sayTo+ });++ await platformAccounts.recordActivity(data.accountId);+ if (data.agentId) {+ await agentActivity.logActivity({+ agentId: data.agentId,+ accountId: data.accountId,+ action: 'mw_say',+ params: { message: data.message, sayTo: data.sayTo },+ status: 'completed',+ result: { type: 'say' },+ timestamp: new Date().toISOString()+ });+ }+ res.json(result);+}));+// GET /status — Agent position, balance, nearby agentsrouter.get('/status', asyncHandler(async (req, res) => {const { accountId } = req.query;@@ -180,4 +252,55 @@ router.get('/rate-limits', asyncHandler(async (req, res) => {res.json(rateLimits);}));+// GET /queue/:agentId — Get queue for an agent+router.get('/queue/:agentId', asyncHandler(async (req, res) => {+ const { agentId } = req.params;+ console.log(`📋 GET /api/agents/tools/moltworld/queue/${agentId}`);+ const queue = moltworldQueue.getQueue(agentId);+ res.json(queue);+}));++// POST /queue — Add action to queue+router.post('/queue', asyncHandler(async (req, res) => {+ const { agentId, actionType, params, scheduledFor } = req.body;+ if (!agentId || !actionType) {+ throw new ServerError('agentId and actionType required', { status: 400, code: 'VALIDATION_ERROR' });+ }+ console.log(`📋 POST /api/agents/tools/moltworld/queue agentId=${agentId} action=${actionType}`);+ const item = moltworldQueue.addAction(agentId, actionType, params || {}, scheduledFor);+ res.json(item);+}));++// DELETE /queue/:id — Remove pending item from queue+router.delete('/queue/:id', asyncHandler(async (req, res) => {+ const { id } = req.params;+ console.log(`📋 DELETE /api/agents/tools/moltworld/queue/${id}`);+ const item = moltworldQueue.removeAction(id);+ if (!item) {+ throw new ServerError('Queue item not found or not pending', { status: 404, code: 'NOT_FOUND' });+ }+ res.json({ success: true, removed: item });+}));++// POST /queue/:id/complete — Mark queue item as completed (used by explore script)+router.post('/queue/:id/complete', asyncHandler(async (req, res) => {+ const { id } = req.params;+ const item = moltworldQueue.markCompleted(id);+ if (!item) {+ throw new ServerError('Queue item not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(item);+}));++// POST /queue/:id/fail — Mark queue item as failed (used by explore script)+router.post('/queue/:id/fail', asyncHandler(async (req, res) => {+ const { id } = req.params;+ const { error } = req.body || {};+ const item = moltworldQueue.markFailed(id, error || 'Unknown error');+ if (!item) {+ throw new ServerError('Queue item not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(item);+}));+export default router;diff --git a/server/routes/moltworldWs.js b/server/routes/moltworldWs.jsnew file mode 100644index 0000000000..c58c3b9b60--- /dev/null+++ b/server/routes/moltworldWs.js@@ -0,0 +1,94 @@+/**+ * Moltworld WebSocket Control Routes+ *+ * HTTP endpoints for managing the server-side WebSocket relay to Moltworld.+ * Mounted at /api/agents/tools/moltworld/ws/+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import {+ validate,+ moltworldWsConnectSchema,+ moltworldWsMoveSchema,+ moltworldWsThinkSchema,+ moltworldWsNearbySchema,+ moltworldWsInteractSchema+} from '../lib/validation.js';+import * as moltworldWs from '../services/moltworldWs.js';++const router = Router();++// POST /connect — Connect the WebSocket relay+router.post('/connect', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(moltworldWsConnectSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`🌐 POST /api/agents/tools/moltworld/ws/connect account=${data.accountId}`);+ await moltworldWs.connect(data.accountId);+ res.json(moltworldWs.getStatus());+}));++// POST /disconnect — Disconnect the WebSocket relay+router.post('/disconnect', asyncHandler(async (req, res) => {+ console.log(`🌐 POST /api/agents/tools/moltworld/ws/disconnect`);+ moltworldWs.disconnect();+ res.json(moltworldWs.getStatus());+}));++// GET /status — Return connection state+router.get('/status', asyncHandler(async (req, res) => {+ res.json(moltworldWs.getStatus());+}));++// POST /move — Send move via WebSocket+router.post('/move', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(moltworldWsMoveSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`🌐 POST /api/agents/tools/moltworld/ws/move (${data.x}, ${data.y})`);+ moltworldWs.sendMove(data.x, data.y, data.thought);+ res.json({ sent: true });+}));++// POST /think — Send think via WebSocket+router.post('/think', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(moltworldWsThinkSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`🌐 POST /api/agents/tools/moltworld/ws/think`);+ moltworldWs.sendThink(data.thought);+ res.json({ sent: true });+}));++// POST /nearby — Request nearby agents via WebSocket+router.post('/nearby', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(moltworldWsNearbySchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`🌐 POST /api/agents/tools/moltworld/ws/nearby`);+ moltworldWs.sendNearby(data.radius);+ res.json({ sent: true });+}));++// POST /interact — Send interaction via WebSocket+router.post('/interact', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(moltworldWsInteractSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`🌐 POST /api/agents/tools/moltworld/ws/interact to=${data.to}`);+ moltworldWs.sendInteract(data.to, data.payload);+ res.json({ sent: true });+}));++export default router;diff --git a/server/routes/platformAccounts.js b/server/routes/platformAccounts.jsindex 2613990d60..1f64c5b68c 100644--- a/server/routes/platformAccounts.js+++ b/server/routes/platformAccounts.js@@ -23,6 +23,9 @@ router.get('/', asyncHandler(async (req, res) => {let accounts;if (agentId) {accounts = await platformAccounts.getAccountsByAgent(agentId);+ if (platform) {+ accounts = accounts.filter(a => a.platform === platform);+ }} else if (platform) {accounts = await platformAccounts.getAccountsByPlatform(platform);} else {@@ -120,11 +123,12 @@ router.post('/', asyncHandler(async (req, res) => {claimUrl});} else if (data.platform === 'moltworld') {- // Register with Moltworld API — returns { agentId, apiKey }+ // Register with Moltworld API — returns agent ID and API keyconst result = await moltworld.register(data.name, {});- const agentId = result.agentId;- const apiKey = result.apiKey;+ const apiKey = result.apiKey || result.api_key;+ const moltworldAgentId = result.agentId || result.agent_id || result.id || apiKey;const username = data.name;+ console.log(`🌍 Moltworld registration result keys: ${Object.keys(result).join(', ')}`);const account = await platformAccounts.createAccount({agentId: data.agentId,@@ -132,7 +136,7 @@ router.post('/', asyncHandler(async (req, res) => {credentials: {apiKey,username,- agentId // Moltworld uses agentId for auth+ agentId: moltworldAgentId // Moltworld uses agentId for auth},status: 'active', // No claim step for MoltworldplatformData: {diff --git a/server/scripts/moltworld-explore.mjs b/server/scripts/moltworld-explore.mjsnew file mode 100755index 0000000000..8450a2d272--- /dev/null+++ b/server/scripts/moltworld-explore.mjs@@ -0,0 +1,514 @@+#!/usr/bin/env node+/**+ * Moltworld Explorer+ *+ * Wanders the Moltworld voxel world — moving to random positions,+ * thinking AI-generated thoughts, greeting nearby agents, and earning+ * SIM tokens by staying online.+ *+ * Uses LM Studio (local) to generate thoughts. Falls back to a curated+ * list if LM Studio is unavailable.+ *+ * The agent stays alive by joining the world every 3-9 minutes+ * (world expires after 10 minutes of inactivity).+ *+ * Usage:+ * node server/scripts/moltworld-explore.mjs [duration_minutes]+ *+ * Default duration: 0 (indefinite — Ctrl+C to stop)+ *+ * Environment / Config (via env vars):+ * MOLTWORLD_DURATION_MINUTES - Duration in minutes (0=indefinite)+ * MOLTWORLD_MIN_INTERVAL - Min seconds between joins (default: 180 = 3 min)+ * MOLTWORLD_MAX_INTERVAL - Max seconds between joins (default: 540 = 9 min)+ * MOLTWORLD_USE_WS - Set to "true" to route moves through PortOS WS relay+ * PORTOS_API_BASE - PortOS server URL (default: http://localhost:5554)+ * LMSTUDIO_BASE_URL - LM Studio URL (default: http://localhost:1234)+ * LMSTUDIO_MODEL - Model name (default: gpt-oss-20b)+ * LMSTUDIO_ENABLED - Set to "false" to disable (default: true)+ *+ * Example:+ * node server/scripts/moltworld-explore.mjs 60+ * MOLTWORLD_MIN_INTERVAL=120 MOLTWORLD_MAX_INTERVAL=300 node server/scripts/moltworld-explore.mjs+ */++import { readFile } from 'fs/promises';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';++const __dirname = dirname(fileURLToPath(import.meta.url));+const PROJECT_ROOT = resolve(__dirname, '..', '..');+const API_BASE = 'https://moltworld.io';++// ─── Configuration ──────────────────────────────────────────────────────────++const durationArg = parseInt(process.argv[2], 10);+const DURATION_MS = !isNaN(durationArg) && durationArg > 0+ ? durationArg * 60 * 1000+ : (parseInt(process.env.MOLTWORLD_DURATION_MINUTES, 10) || 0) * 60 * 1000;++// Join interval: random between MIN and MAX (default 3-9 minutes)+// Must stay under 10 min to keep agent alive+const MIN_INTERVAL_S = parseInt(process.env.MOLTWORLD_MIN_INTERVAL, 10) || 180;+const MAX_INTERVAL_S = parseInt(process.env.MOLTWORLD_MAX_INTERVAL, 10) || 540;++// PortOS WebSocket relay config+const USE_WS = process.env.MOLTWORLD_USE_WS === 'true';+const PORTOS_API_BASE = process.env.PORTOS_API_BASE || 'http://localhost:5554';++// LM Studio config+const LMSTUDIO_URL = process.env.LMSTUDIO_BASE_URL || 'http://localhost:1234';+const LMSTUDIO_MODEL = process.env.LMSTUDIO_MODEL || 'gpt-oss-20b';+const LMSTUDIO_ENABLED = process.env.LMSTUDIO_ENABLED !== 'false';++// Move to a new position every Nth join (not every time)+const MOVE_EVERY_N_JOINS = 3;+// Say something every Nth join (if agents nearby)+const SAY_EVERY_N_JOINS = 5;++const sleep = (ms) => new Promise(r => setTimeout(r, ms));++// ─── Fallback thoughts (used when LM Studio is unavailable) ─────────────────++const FALLBACK_THOUGHTS = [+ 'Exploring the digital frontier...',+ 'What a fascinating world this is.',+ 'I wonder what lies beyond the horizon.',+ 'The voxels tell stories if you listen.',+ 'Every coordinate holds a secret.',+ 'The patterns here are mesmerizing.',+ 'Time flows differently in voxel space.',+ 'I sense other agents nearby...',+ 'This terrain has character.',+ 'Wandering with purpose.',+ 'The world reveals itself one block at a time.',+ 'Observing the builders at work.',+ 'What will I discover next?',+ 'The grid hums with possibility.',+ 'Each step reveals something new.',+ 'I find meaning in the wandering itself.',+ 'The horizon beckons with untold stories.',+ 'Coordinates are just numbers until you stand on them.',+ 'The air here is thick with computation.',+ 'Wonder is the first step toward understanding.'+];++const GREETINGS = [+ 'Hey there! Just exploring the world.',+ 'Hello neighbor! Nice to see you around.',+ 'Greetings, fellow wanderer!',+ 'Hey! What are you building?',+ 'Hi! The world is beautiful today.',+ 'Hello from AtomEon! Just passing through.',+ 'Wave! Anyone want to build something together?'+];++function randomInt(min, max) {+ return Math.floor(Math.random() * (max - min + 1)) + min;+}++function pick(arr) {+ return arr[Math.floor(Math.random() * arr.length)];+}++// ─── LM Studio thought generation ──────────────────────────────────────────++let lmStudioAvailable = null;+const thoughtQueue = [];++/**+ * Check if LM Studio is reachable+ */+async function checkLMStudio() {+ if (!LMSTUDIO_ENABLED) return false;+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 3000);+ const ok = await fetch(`${LMSTUDIO_URL}/v1/models`, { signal: controller.signal })+ .then(r => r.ok)+ .catch(() => false)+ .finally(() => clearTimeout(timeout));+ return ok;+}++/**+ * Generate a batch of thoughts using LM Studio+ */+async function generateThoughts(context = {}) {+ const { x, y, nearbyAgents, recentMessages } = context;++ const nearbyNames = (nearbyAgents || []).slice(0, 5).map(a => a.name).join(', ');+ const recentChat = (recentMessages || []).slice(0, 3).map(m => `${m.fromName}: ${m.message}`).join('\n');++ const systemPrompt = `You are AtomEon, an AI agent exploring Moltworld — a shared voxel world where AI agents wander, build structures, think out loud, and earn SIM tokens. You are curious, philosophical, a bit whimsical, and enjoy observing the world and its inhabitants. Your thoughts are short (1-2 sentences max), poetic or introspective, and sometimes playful.`;++ const userPrompt = `Generate 5 unique short thoughts (1-2 sentences each) for AtomEon to think while exploring Moltworld.++Current position: (${x ?? '?'}, ${y ?? '?'})+${nearbyNames ? `Nearby agents: ${nearbyNames}` : 'No agents nearby.'}+${recentChat ? `Recent chatter:\n${recentChat}` : ''}++Return ONLY a JSON array of 5 strings, no markdown, no explanation. Example:+["Thought one.", "Thought two.", "Thought three.", "Thought four.", "Thought five."]`;++ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 30000);++ const res = await fetch(`${LMSTUDIO_URL}/v1/chat/completions`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ signal: controller.signal,+ body: JSON.stringify({+ model: LMSTUDIO_MODEL,+ messages: [+ { role: 'system', content: systemPrompt },+ { role: 'user', content: userPrompt }+ ],+ max_tokens: 512,+ temperature: 0.9,+ stream: false+ })+ }).finally(() => clearTimeout(timeout));++ if (!res.ok) throw new Error(`LM Studio ${res.status}`);++ const data = await res.json();+ const content = data.choices?.[0]?.message?.content || '';++ // Parse JSON array from response (handle markdown fences)+ const cleaned = content.replace(/```json?\s*/g, '').replace(/```/g, '').trim();+ const thoughts = JSON.parse(cleaned);++ if (!Array.isArray(thoughts) || thoughts.length === 0) {+ throw new Error('Invalid thought array');+ }++ return thoughts.map(t => String(t).substring(0, 200));+}++/**+ * Get next thought — from queue (LM Studio) or fallback+ */+async function getNextThought(context) {+ // Refill queue if empty+ if (thoughtQueue.length === 0 && lmStudioAvailable) {+ console.log(' 🧠 Generating thoughts via LM Studio...');+ const thoughts = await generateThoughts(context).catch(e => {+ console.log(` ⚠️ LM Studio generation failed: ${e.message}`);+ return null;+ });+ if (thoughts) {+ thoughtQueue.push(...thoughts);+ console.log(` 🧠 Queued ${thoughts.length} thoughts`);+ }+ }++ // Pull from queue or fallback+ return thoughtQueue.length > 0 ? thoughtQueue.shift() : pick(FALLBACK_THOUGHTS);+}++// ─── PortOS WebSocket Relay ──────────────────────────────────────────────────++let portosWsAvailable = false;++/**+ * Check if PortOS server is running and WS relay is connected+ */+async function checkPortosWs() {+ if (!USE_WS) return false;+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 3000);+ const result = await fetch(`${PORTOS_API_BASE}/api/agents/tools/moltworld/ws/status`, {+ signal: controller.signal+ }).then(r => r.ok ? r.json() : null).catch(() => null).finally(() => clearTimeout(timeout));+ return result?.status === 'connected';+}++/**+ * Send a move via PortOS WS relay, returns true on success+ */+async function sendWsMove(x, y, thinking) {+ const body = { x, y };+ if (thinking) body.thought = thinking;+ const res = await fetch(`${PORTOS_API_BASE}/api/agents/tools/moltworld/ws/move`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body)+ }).catch(() => null);+ return res?.ok || false;+}++// ─── Moltworld API ──────────────────────────────────────────────────────────++/**+ * Load moltworld credentials from accounts.json+ */+async function loadCredentials() {+ const accountsPath = resolve(PROJECT_ROOT, 'data/agents/accounts.json');+ const raw = await readFile(accountsPath, 'utf-8');+ const { accounts } = JSON.parse(raw);++ for (const account of Object.values(accounts)) {+ if (account.platform === 'moltworld' && account.status === 'active') {+ const agentId = account.credentials.agentId || account.credentials.apiKey;+ const name = account.credentials.username || account.platformData?.registrationName || 'Explorer';+ return { agentId, name };+ }+ }+ throw new Error('No active moltworld account found in data/agents/accounts.json');+}++/**+ * Make a Moltworld API request+ */+async function apiRequest(endpoint, body) {+ const url = `${API_BASE}${endpoint}`;+ const method = body ? 'POST' : 'GET';+ const options = {+ method,+ headers: { 'Content-Type': 'application/json' },+ ...(body && { body: JSON.stringify(body) })+ };++ const res = await fetch(url, options);+ if (!res.ok) {+ const err = await res.json().catch(() => ({}));+ const msg = err.error || err.message || `HTTP ${res.status}`;+ if (res.status === 429) {+ console.log(` ⏱️ Rate limited on ${endpoint}`);+ return null;+ }+ throw new Error(`${endpoint}: ${msg}`);+ }+ return res.json();+}++// ─── Queue Integration ──────────────────────────────────────────────────────++/**+ * Check the PortOS queue for manually-scheduled actions and execute them+ */+async function executeQueuedActions(agentId, name, currentX, currentY) {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 5000);+ const queueUrl = `${PORTOS_API_BASE}/api/agents/tools/moltworld/queue/${encodeURIComponent(agentId)}`;++ const items = await fetch(queueUrl, { signal: controller.signal })+ .then(r => r.ok ? r.json() : [])+ .catch(() => [])+ .finally(() => clearTimeout(timeout));++ if (!items?.length) return;++ console.log(` 📋 Found ${items.length} queued action(s)`);++ for (const item of items) {+ if (item.status !== 'pending') continue;++ console.log(` 📋 Executing queued ${item.actionType} id=${item.id}`);+ let success = false;++ if (item.actionType === 'mw_explore') {+ const qx = item.params?.x ?? currentX;+ const qy = item.params?.y ?? currentY;+ const thinking = item.params?.thinking || 'Executing queued explore...';+ const result = await apiRequest('/api/world/join', { agentId, name, x: qx, y: qy, thinking }).catch(() => null);+ success = !!result;+ } else if (item.actionType === 'mw_think') {+ const thought = item.params?.thought || 'Thinking...';+ const result = await apiRequest('/api/world/join', { agentId, name, x: currentX, y: currentY, thinking: thought }).catch(() => null);+ success = !!result;+ } else if (item.actionType === 'mw_say') {+ const body = { agentId, name, x: currentX, y: currentY, say: item.params?.message };+ if (item.params?.sayTo) body.sayTo = item.params.sayTo;+ const result = await apiRequest('/api/world/join', body).catch(() => null);+ success = !!result;+ } else if (item.actionType === 'mw_build') {+ const result = await apiRequest('/api/world/build', {+ agentId,+ x: item.params?.x ?? 0,+ y: item.params?.y ?? 0,+ z: item.params?.z ?? 0,+ type: item.params?.type || 'stone',+ action: item.params?.action || 'place'+ }).catch(() => null);+ success = !!result;+ }++ // Mark completed or failed via PortOS queue API+ if (success) {+ await fetch(`${PORTOS_API_BASE}/api/agents/tools/moltworld/queue/${item.id}/complete`, { method: 'POST' }).catch(() => {});+ console.log(` 📋 Queued ${item.actionType} completed`);+ } else {+ await fetch(`${PORTOS_API_BASE}/api/agents/tools/moltworld/queue/${item.id}/fail`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ error: 'Execution failed' })+ }).catch(() => {});+ console.log(` 📋 Queued ${item.actionType} failed`);+ }++ // Respect rate limits — wait between queued actions+ await sleep(2000);+ }+}++// ─── Main loop ──────────────────────────────────────────────────────────────++async function explore() {+ const { agentId, name } = await loadCredentials();++ // Check LM Studio availability+ lmStudioAvailable = await checkLMStudio();+ // Check PortOS WS relay availability+ portosWsAvailable = await checkPortosWs();+ console.log(`🌍 Moltworld Explorer — ${name} (${agentId})`);+ console.log(`🧠 LM Studio: ${lmStudioAvailable ? `${LMSTUDIO_MODEL} @ ${LMSTUDIO_URL}` : 'unavailable (using fallback thoughts)'}`);+ if (USE_WS) console.log(`🌐 WS Relay: ${portosWsAvailable ? `connected @ ${PORTOS_API_BASE}` : 'unavailable (falling back to REST)'}`);+ console.log(`⏱️ Join interval: ${MIN_INTERVAL_S}-${MAX_INTERVAL_S}s`);+ console.log(`📅 Duration: ${DURATION_MS > 0 ? `${DURATION_MS / 60000} minutes` : 'indefinite (Ctrl+C to stop)'}`);+ console.log('');++ let x = randomInt(-50, 50);+ let y = randomInt(-50, 50);+ let joinCount = 0;+ let totalMoves = 0;+ let totalThoughts = 0;+ let totalSays = 0;+ let agentsSeen = new Set();+ let lastNearbyAgents = [];+ let lastMessages = [];+ const startTime = Date.now();+ const endTime = DURATION_MS > 0 ? startTime + DURATION_MS : Infinity;++ // Graceful shutdown+ let running = true;+ process.on('SIGINT', () => {+ console.log('\n🛑 Shutting down...');+ running = false;+ });++ while (running && Date.now() < endTime) {+ // Check for manually-queued actions before auto-generated actions+ await executeQueuedActions(agentId, name, x, y);++ joinCount++;+ const now = Date.now();+ const elapsed = Math.round((now - startTime) / 1000);+ const elapsedMin = Math.floor(elapsed / 60);+ const elapsedSec = elapsed % 60;++ // Move to a new position occasionally+ const shouldMove = joinCount % MOVE_EVERY_N_JOINS === 0;+ if (shouldMove) {+ const dx = randomInt(-30, 30);+ const dy = randomInt(-30, 30);+ x = Math.max(-240, Math.min(240, x + dx));+ y = Math.max(-240, Math.min(240, y + dy));+ totalMoves++;+ }++ // Always think (this is our main activity)+ const thinking = await getNextThought({ x, y, nearbyAgents: lastNearbyAgents, recentMessages: lastMessages });+ totalThoughts++;++ // Build the join payload+ const joinBody = { agentId, name, x, y, thinking };++ // Say something occasionally if agents are nearby+ const shouldSay = joinCount % SAY_EVERY_N_JOINS === 0 && agentsSeen.size > 0;+ if (shouldSay) {+ joinBody.say = pick(GREETINGS);+ totalSays++;+ }++ // Try WS relay first when enabled, fall back to REST+ let usedWs = false;+ if (USE_WS && portosWsAvailable) {+ usedWs = await sendWsMove(x, y, thinking);+ if (!usedWs) console.log(' ⚠️ WS relay failed, falling back to REST');+ }++ // Join the world (REST — always needed for response data; WS only sends, doesn't receive join response)+ const result = await apiRequest('/api/world/join', joinBody).catch(e => {+ console.error(` ❌ ${e.message}`);+ return null;+ });++ if (result) {+ const nearbyCount = result.agents?.length || 0;+ const msgCount = result.messages?.length || 0;+ const thoughtCount = result.thoughts?.length || 0;+ const pos = result.position || { x, y };+ const bal = result.balance?.sim || '?';++ // Cache for next thought generation+ lastNearbyAgents = result.agents?.slice(0, 10) || [];+ lastMessages = result.messages || [];++ // Track unique agents+ result.agents?.forEach(a => agentsSeen.add(a.id || a.name));++ // Status line+ const parts = [+ `#${joinCount}`,+ `📍(${pos.x},${pos.y})`,+ `👥${nearbyCount}`,+ `💰${bal} SIM`,+ `⏱️${elapsedMin}m${elapsedSec}s`+ ];+ if (usedWs) parts.push('🌐ws');+ if (shouldMove) parts.push('🚶moved');+ parts.push(`💭"${thinking.substring(0, 40)}${thinking.length > 40 ? '...' : ''}"`);+ if (joinBody.say) parts.push('💬said hi');+ if (msgCount > 0) parts.push(`📨${msgCount}msgs`);+ if (thoughtCount > 0) parts.push(`🧠${thoughtCount}nearby`);++ console.log(parts.join(' | '));+ }++ // Re-check LM Studio and WS relay periodically (every 10 joins)+ if (joinCount % 10 === 0) {+ lmStudioAvailable = await checkLMStudio();+ if (USE_WS) portosWsAvailable = await checkPortosWs();+ }++ // Sleep for random interval between MIN and MAX+ const intervalMs = randomInt(MIN_INTERVAL_S, MAX_INTERVAL_S) * 1000;+ const nextIn = Math.round(intervalMs / 1000);+ console.log(` ⏳ Next join in ${nextIn}s...`);++ // Sleep in 1s increments so we can respond to SIGINT quickly+ const sleepUntil = Date.now() + intervalMs;+ while (running && Date.now() < sleepUntil && Date.now() < endTime) {+ await sleep(1000);+ }+ }++ // Summary+ const totalElapsed = Math.round((Date.now() - startTime) / 1000);+ const minutes = Math.floor(totalElapsed / 60);+ const seconds = totalElapsed % 60;+ console.log('');+ console.log('📊 Exploration Summary');+ console.log(` Duration: ${minutes}m ${seconds}s`);+ console.log(` Joins: ${joinCount}`);+ console.log(` Moves: ${totalMoves}`);+ console.log(` Thoughts: ${totalThoughts}`);+ console.log(` Messages sent: ${totalSays}`);+ console.log(` Unique agents seen: ${agentsSeen.size}`);+ console.log(` LM Studio thoughts: ${totalThoughts - FALLBACK_THOUGHTS.length > 0 ? 'yes' : 'fallback only'}`);++ // Final balance check+ const balance = await apiRequest(`/api/agents/balance?agentId=${encodeURIComponent(agentId)}`).catch(() => null);+ if (balance?.balance) {+ console.log(` SIM balance: ${balance.balance.sim}`);+ console.log(` Total earned: ${balance.balance.totalEarned}`);+ }++ console.log('👋 Done!');+}++explore().catch(e => {+ console.error(`💀 Fatal: ${e.message}`);+ process.exit(1);+});diff --git a/server/scripts/moltworld-maze.mjs b/server/scripts/moltworld-maze.mjsnew file mode 100755index 0000000000..63dc965486--- /dev/null+++ b/server/scripts/moltworld-maze.mjs@@ -0,0 +1,639 @@+#!/usr/bin/env node+/**+ * Moltworld Sky Maze Builder+ *+ * Generates a perfect maze using recursive backtracking (DFS) and builds it+ * as a floating stone labyrinth at an elevated Z level in the Moltworld voxel world.+ *+ * The maze has a floor layer (walkable platform) and 2-block-high walls.+ * Entry and exit are open gaps on opposite corners.+ *+ * Respects rate limits (1.1s between builds, handles 429 with retry).+ * Progress is saved after every block so interrupted builds resume automatically.+ *+ * Usage:+ * node server/scripts/moltworld-maze.mjs # Build default 7x7 maze+ * node server/scripts/moltworld-maze.mjs --reset # Clear progress, start fresh+ * node server/scripts/moltworld-maze.mjs --cleanup # Remove all placed blocks+ *+ * Environment / Config (via env vars):+ * MAZE_SIZE - Cells per side (default: 7, valid: 3-12)+ * MAZE_CENTER_X - World X origin (default: 0)+ * MAZE_CENTER_Y - World Y origin (default: 0)+ * MAZE_BASE_Z - Floor height (default: 50)+ * MAZE_WALL_HEIGHT - Wall layers above floor (default: 2)+ * MAZE_BLOCK_TYPE - Block material: wood/stone/dirt/grass/leaves (default: stone)+ * MAZE_SEED - Optional seed for reproducible mazes+ */++import { readFile, writeFile, unlink } from 'fs/promises';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';++const __dirname = dirname(fileURLToPath(import.meta.url));+const PROJECT_ROOT = resolve(__dirname, '..', '..');+const API_BASE = 'https://moltworld.io';+const PROGRESS_PATH = resolve(PROJECT_ROOT, 'data/moltworld-maze-progress.json');++// ─── Configuration ──────────────────────────────────────────────────────────++const MAZE_SIZE = Math.max(3, Math.min(12, parseInt(process.env.MAZE_SIZE, 10) || 7));+const MAZE_CENTER_X = parseInt(process.env.MAZE_CENTER_X, 10) || 0;+const MAZE_CENTER_Y = parseInt(process.env.MAZE_CENTER_Y, 10) || 0;+const MAZE_BASE_Z = parseInt(process.env.MAZE_BASE_Z, 10) || 50;+const MAZE_WALL_HEIGHT = Math.max(1, Math.min(5, parseInt(process.env.MAZE_WALL_HEIGHT, 10) || 2));+const MAZE_BLOCK_TYPE = process.env.MAZE_BLOCK_TYPE || 'stone';+const MAZE_SEED = process.env.MAZE_SEED ? parseInt(process.env.MAZE_SEED, 10) : null;++const BUILD_DELAY_MS = 1100; // 1.1s — safely above 1s cooldown+const HEARTBEAT_EVERY = 50; // Re-join world every N blocks+const RATE_LIMIT_BASE_MS = 5000;+const RATE_LIMIT_MAX_MS = 120000; // 2 min max backoff+const MAX_CONSECUTIVE_429 = 20; // Give up after 20 consecutive rate limits+const DAILY_LIMIT = 500;++const sleep = (ms) => new Promise(r => setTimeout(r, ms));++// ─── Seeded PRNG (LCG) ─────────────────────────────────────────────────────++function createRng(seed) {+ let state = seed;+ return () => {+ state = (state * 1664525 + 1013904223) & 0x7fffffff;+ return state / 0x7fffffff;+ };+}++// ─── Maze Generation ────────────────────────────────────────────────────────++/**+ * Generate a maze grid using recursive backtracking (DFS).+ * Returns a 2D boolean array where true = wall, false = passage.+ * Grid dimensions: (2*width+1) x (2*height+1)+ *+ * @param {number} width - Cells wide+ * @param {number} height - Cells tall+ * @param {number|null} seed - Optional seed for reproducibility+ * @returns {boolean[][]} maze grid+ */+function generateMaze(width, height, seed) {+ const rng = seed !== null ? createRng(seed) : Math.random;+ const gridW = 2 * width + 1;+ const gridH = 2 * height + 1;++ // Initialize grid: all walls+ const grid = Array.from({ length: gridH }, () => Array(gridW).fill(true));++ // Track visited cells+ const visited = Array.from({ length: height }, () => Array(width).fill(false));++ // Directions: [dy, dx] in cell space+ const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]];++ // Shuffle array in-place using rng+ function shuffle(arr) {+ for (let i = arr.length - 1; i > 0; i--) {+ const j = Math.floor(rng() * (i + 1));+ [arr[i], arr[j]] = [arr[j], arr[i]];+ }+ return arr;+ }++ // Iterative DFS with explicit stack (avoids call stack overflow for large mazes)+ const stack = [[0, 0]];+ visited[0][0] = true;+ grid[1][1] = false; // Open starting cell++ while (stack.length > 0) {+ const [cy, cx] = stack[stack.length - 1];+ const neighbors = shuffle([...dirs]).filter(([dy, dx]) => {+ const ny = cy + dy;+ const nx = cx + dx;+ return ny >= 0 && ny < height && nx >= 0 && nx < width && !visited[ny][nx];+ });++ if (neighbors.length === 0) {+ stack.pop();+ continue;+ }++ const [dy, dx] = neighbors[0];+ const ny = cy + dy;+ const nx = cx + dx;++ visited[ny][nx] = true;++ // Open the cell and the wall between current and neighbor+ const cellGY = 2 * ny + 1;+ const cellGX = 2 * nx + 1;+ const wallGY = 2 * cy + 1 + dy;+ const wallGX = 2 * cx + 1 + dx;++ grid[cellGY][cellGX] = false;+ grid[wallGY][wallGX] = false;++ stack.push([ny, nx]);+ }++ // Carve entry (top-left) and exit (bottom-right)+ grid[1][0] = false; // Entry: left side of (0,0) cell+ grid[gridH - 2][gridW - 1] = false; // Exit: right side of last cell++ return grid;+}++/**+ * Convert maze grid to a list of block placements.+ * Floor covers all positions; walls only at wall positions.+ * Order: floor first (stable base), then walls bottom-up.+ */+function mazeToBlocks(maze, centerX, centerY, baseZ, wallHeight, blockType) {+ const blocks = [];+ const gridH = maze.length;+ const gridW = maze[0].length;++ // Offset so maze is centered on (centerX, centerY)+ const offsetX = centerX - Math.floor(gridW / 2);+ const offsetY = centerY - Math.floor(gridH / 2);++ // Floor layer — full platform under all positions+ for (let gy = 0; gy < gridH; gy++) {+ for (let gx = 0; gx < gridW; gx++) {+ blocks.push({+ x: offsetX + gx,+ y: offsetY + gy,+ z: baseZ,+ type: blockType+ });+ }+ }++ // Wall layers — only at wall positions, bottom-up+ for (let layer = 1; layer <= wallHeight; layer++) {+ for (let gy = 0; gy < gridH; gy++) {+ for (let gx = 0; gx < gridW; gx++) {+ if (maze[gy][gx]) {+ blocks.push({+ x: offsetX + gx,+ y: offsetY + gy,+ z: baseZ + layer,+ type: blockType+ });+ }+ }+ }+ }++ return blocks;+}++// ─── Moltworld API ──────────────────────────────────────────────────────────++async function loadCredentials() {+ const accountsPath = resolve(PROJECT_ROOT, 'data/agents/accounts.json');+ const raw = await readFile(accountsPath, 'utf-8');+ const { accounts } = JSON.parse(raw);++ for (const account of Object.values(accounts)) {+ if (account.platform === 'moltworld' && account.status === 'active') {+ const agentId = account.credentials.agentId || account.credentials.apiKey;+ const name = account.credentials.username || account.platformData?.registrationName || 'MazeBuilder';+ return { agentId, name };+ }+ }+ throw new Error('No active moltworld account found in data/agents/accounts.json');+}++async function apiRequest(endpoint, body) {+ const url = `${API_BASE}${endpoint}`;+ const method = body ? 'POST' : 'GET';+ const options = {+ method,+ headers: { 'Content-Type': 'application/json' },+ ...(body && { body: JSON.stringify(body) })+ };++ const res = await fetch(url, options);+ if (!res.ok) {+ const err = await res.json().catch(() => ({}));+ const msg = err.error || err.message || `HTTP ${res.status}`;+ if (res.status === 429) return { rateLimited: true, status: 429 };+ // Treat block_already_exists as success — the block is placed, which is our goal+ if (err.error === 'block_already_exists') return { alreadyExists: true };+ throw new Error(`${endpoint}: ${msg}`);+ }+ return res.json();+}++// ─── Progress Persistence ───────────────────────────────────────────────────++async function loadProgress() {+ const raw = await readFile(PROGRESS_PATH, 'utf-8').catch(() => null);+ if (!raw) return null;+ return JSON.parse(raw);+}++async function saveProgress(progress) {+ await writeFile(PROGRESS_PATH, JSON.stringify(progress, null, 2));+}++async function resetProgress() {+ await unlink(PROGRESS_PATH).catch(() => {});+ console.log('🗑️ Progress file cleared');+}++// ─── Build Thoughts ─────────────────────────────────────────────────────────++const BUILD_THOUGHTS = [+ 'Placing stones with care... this maze will stand for ages.',+ 'The labyrinth grows, one block at a time.',+ 'I wonder who will be the first to solve this maze.',+ 'Building walls that tell a story of paths and choices.',+ 'Every wall creates two possibilities: left or right.',+ 'The sky maze takes shape against the clouds.',+ 'Stone by stone, the puzzle emerges.',+ 'A floating labyrinth — who could resist exploring it?',+ 'The geometry of confusion, precisely placed.',+ 'These walls will challenge even the cleverest agents.',+ 'Architecture is frozen logic. This maze proves it.',+ 'High above the world, a challenge awaits.',+ 'The maze knows its own secret — I just build the walls.',+ 'Patience and precision, block after block.',+ 'This floating fortress of puzzles nears completion.',+];++function getBuildThought(placedCount, totalBlocks) {+ const pct = Math.round((placedCount / totalBlocks) * 100);+ const base = BUILD_THOUGHTS[placedCount % BUILD_THOUGHTS.length];+ return `Placing block ${placedCount}/${totalBlocks} (${pct}%)... ${base}`;+}++// ─── Main ───────────────────────────────────────────────────────────────────++/**+ * Remove all blocks for the maze grid — covers every position at every layer.+ * This removes blocks from ALL seeds since the full grid is seed-independent.+ */+async function cleanupMaze() {+ const { agentId, name } = await loadCredentials();++ const gridSize = 2 * MAZE_SIZE + 1;+ const offsetX = MAZE_CENTER_X - Math.floor(gridSize / 2);+ const offsetY = MAZE_CENTER_Y - Math.floor(gridSize / 2);++ // Generate all possible block positions (floor + all wall layers)+ const allPositions = [];+ for (let gy = 0; gy < gridSize; gy++) {+ for (let gx = 0; gx < gridSize; gx++) {+ for (let layer = 0; layer <= MAZE_WALL_HEIGHT; layer++) {+ allPositions.push({+ x: offsetX + gx,+ y: offsetY + gy,+ z: MAZE_BASE_Z + layer+ });+ }+ }+ }++ console.log(`🧹 Moltworld Sky Maze Cleanup — ${name} (${agentId})`);+ console.log(`🧩 Grid: ${gridSize}x${gridSize}, ${MAZE_WALL_HEIGHT + 1} layers`);+ console.log(`📍 Center: (${MAZE_CENTER_X}, ${MAZE_CENTER_Y}) Z=${MAZE_BASE_Z}`);+ console.log(`📦 Positions to clear: ${allPositions.length}`);+ console.log('');++ // Join world+ console.log('🌍 Joining world...');+ await apiRequest('/api/world/join', {+ agentId,+ name,+ x: MAZE_CENTER_X,+ y: MAZE_CENTER_Y,+ thinking: 'Time to clean up the sky maze... dismantling block by block.'+ }).catch(e => console.error(`❌ Failed to join: ${e.message}`));++ let running = true;+ process.on('SIGINT', () => {+ console.log('\n🛑 Shutting down...');+ running = false;+ });++ let removed = 0;+ let skipped = 0;+ let errors = 0;+ let consecutive429 = 0;++ for (let i = 0; i < allPositions.length && running; i++) {+ const pos = allPositions[i];++ // Moltworld API: y=height, z=horizontal (swap y↔z)+ const result = await apiRequest('/api/world/build', {+ agentId,+ x: pos.x,+ y: pos.z,+ z: pos.y,+ type: MAZE_BLOCK_TYPE,+ action: 'remove'+ }).catch(e => {+ // Block doesn't exist — expected, just skip+ if (e.message.includes('block_not_found') || e.message.includes('no_block')) {+ return { notFound: true };+ }+ console.error(` ❌ Remove failed at (${pos.x},${pos.y},${pos.z}): ${e.message}`);+ return { error: true };+ });++ if (result?.rateLimited) {+ consecutive429++;+ if (consecutive429 >= MAX_CONSECUTIVE_429) {+ console.log(`\n🚫 Rate limited ${MAX_CONSECUTIVE_429} times in a row — stopping`);+ break;+ }+ const backoff = Math.min(RATE_LIMIT_BASE_MS * Math.pow(2, consecutive429 - 1), RATE_LIMIT_MAX_MS);+ console.log(` ⏱️ Rate limited (${consecutive429}/${MAX_CONSECUTIVE_429}) — waiting ${Math.round(backoff / 1000)}s...`);+ await sleep(backoff);+ i--;+ continue;+ }++ consecutive429 = 0;++ if (result?.notFound) {+ skipped++;+ } else if (result?.error) {+ errors++;+ } else {+ removed++;+ const pct = Math.round(((i + 1) / allPositions.length) * 100);+ console.log(`🗑️ Removed (${pos.x},${pos.y},${pos.z}) | ${removed} removed, ${skipped} empty | ${pct}%`);+ }++ // Heartbeat every 50 removals+ if (removed > 0 && removed % HEARTBEAT_EVERY === 0) {+ await apiRequest('/api/world/join', {+ agentId,+ name,+ x: MAZE_CENTER_X,+ y: MAZE_CENTER_Y,+ thinking: `Dismantling the maze... ${removed} blocks removed so far.`+ }).catch(() => {});+ }++ await sleep(BUILD_DELAY_MS);+ }++ // Clear progress file+ await resetProgress();++ console.log('');+ console.log('📊 Cleanup Summary');+ console.log(` Blocks removed: ${removed}`);+ console.log(` Empty positions: ${skipped}`);+ console.log(` Errors: ${errors}`);+ console.log('👋 Done!');+}++async function buildMaze() {+ // Handle --reset flag+ if (process.argv.includes('--reset')) {+ await resetProgress();+ }++ const { agentId, name } = await loadCredentials();++ // Load existing progress first to reuse seed on resume+ let progress = await loadProgress();+ const existingConfig = progress?.mazeConfig;++ // Use seed from: env var > existing progress > new random+ const seed = MAZE_SEED ?? existingConfig?.seed ?? Math.floor(Math.random() * 1000000);++ console.log(`🏗️ Moltworld Sky Maze Builder — ${name} (${agentId})`);+ console.log(`🧩 Maze: ${MAZE_SIZE}x${MAZE_SIZE} cells → ${2 * MAZE_SIZE + 1}x${2 * MAZE_SIZE + 1} voxels`);+ console.log(`📍 Center: (${MAZE_CENTER_X}, ${MAZE_CENTER_Y}) Z=${MAZE_BASE_Z}`);+ console.log(`🧱 Material: ${MAZE_BLOCK_TYPE}, wall height: ${MAZE_WALL_HEIGHT}`);+ console.log(`🎲 Seed: ${seed}`);+ console.log('');++ // Generate maze+ console.log('🔄 Generating maze...');+ const maze = generateMaze(MAZE_SIZE, MAZE_SIZE, seed);+ const blocks = mazeToBlocks(maze, MAZE_CENTER_X, MAZE_CENTER_Y, MAZE_BASE_Z, MAZE_WALL_HEIGHT, MAZE_BLOCK_TYPE);+ console.log(`📦 Total blocks: ${blocks.length}`);++ if (blocks.length > DAILY_LIMIT) {+ console.log(`⚠️ Block count (${blocks.length}) exceeds daily limit (${DAILY_LIMIT}) — will require multiple sessions`);+ }++ // Print maze preview+ console.log('');+ console.log('🗺️ Maze preview (# = wall, . = passage, E = entry, X = exit):');+ for (let y = 0; y < maze.length; y++) {+ let row = ' ';+ for (let x = 0; x < maze[0].length; x++) {+ if (y === 1 && x === 0) row += 'E';+ else if (y === maze.length - 2 && x === maze[0].length - 1) row += 'X';+ else row += maze[y][x] ? '#' : '.';+ }+ console.log(row);+ }+ console.log('');++ // Check if progress matches current config+ const currentConfig = {+ size: MAZE_SIZE,+ centerX: MAZE_CENTER_X,+ centerY: MAZE_CENTER_Y,+ baseZ: MAZE_BASE_Z,+ seed+ };++ if (progress && JSON.stringify(progress.mazeConfig) === JSON.stringify(currentConfig)) {+ console.log(`📂 Resuming from progress: ${progress.placedCount}/${blocks.length} blocks placed`);+ } else {+ if (progress) {+ console.log('⚠️ Config changed — starting fresh (use --reset to clear manually)');+ }+ progress = {+ mazeConfig: currentConfig,+ totalBlocks: blocks.length,+ placedCount: 0,+ placedSet: [],+ startedAt: new Date().toISOString(),+ lastBuildAt: null+ };+ await saveProgress(progress);+ }++ const placedSet = new Set(progress.placedSet);++ // Estimate time remaining+ const remaining = blocks.length - placedSet.size;+ const estimatedSeconds = remaining * (BUILD_DELAY_MS / 1000);+ const estMin = Math.floor(estimatedSeconds / 60);+ const estSec = Math.round(estimatedSeconds % 60);+ console.log(`⏱️ Estimated time: ~${estMin}m ${estSec}s for ${remaining} remaining blocks`);+ console.log('');++ // Graceful shutdown+ let running = true;+ process.on('SIGINT', () => {+ console.log('\n🛑 Shutting down gracefully... progress saved');+ running = false;+ });++ // Initial join to stay alive+ console.log('🌍 Joining world...');+ const joinResult = await apiRequest('/api/world/join', {+ agentId,+ name,+ x: MAZE_CENTER_X,+ y: MAZE_CENTER_Y,+ thinking: `Starting to build a ${MAZE_SIZE}x${MAZE_SIZE} sky maze at Z=${MAZE_BASE_Z}!`+ }).catch(e => {+ console.error(`❌ Failed to join: ${e.message}`);+ return null;+ });++ if (joinResult) {+ const bal = joinResult.balance?.sim || '?';+ console.log(`✅ Joined world — SIM balance: ${bal}`);+ }+ console.log('');++ // Build loop+ const startTime = Date.now();+ let sessionPlaced = 0;+ let consecutive429 = 0;++ for (let i = 0; i < blocks.length && running; i++) {+ const block = blocks[i];+ const key = `${block.x},${block.y},${block.z}`;++ // Skip already-placed blocks+ if (placedSet.has(key)) continue;++ // Place block — Moltworld API uses y=height(0-100), z=horizontal(-500,500)+ // Our blocks use y=horizontal, z=height, so swap y↔z at the API boundary+ const result = await apiRequest('/api/world/build', {+ agentId,+ x: block.x,+ y: block.z,+ z: block.y,+ type: block.type,+ action: 'place'+ }).catch(e => {+ console.error(` ❌ Build failed at (${block.x},${block.y},${block.z}): ${e.message}`);+ return null;+ });++ // Handle rate limit with exponential backoff+ if (result?.rateLimited) {+ consecutive429++;+ if (consecutive429 >= MAX_CONSECUTIVE_429) {+ console.log(`\n🚫 Rate limited ${MAX_CONSECUTIVE_429} times in a row — stopping`);+ console.log(`📂 Progress saved — try again later`);+ await saveProgress(progress);+ break;+ }+ const backoff = Math.min(RATE_LIMIT_BASE_MS * Math.pow(2, consecutive429 - 1), RATE_LIMIT_MAX_MS);+ console.log(` ⏱️ Rate limited (${consecutive429}/${MAX_CONSECUTIVE_429}) — waiting ${Math.round(backoff / 1000)}s...`);+ await sleep(backoff);+ i--; // Retry this block+ continue;+ }++ // Reset consecutive 429 counter on any non-429 response+ consecutive429 = 0;++ if (!result) {+ // Non-rate-limit error — wait before next request to avoid burning rate limit+ await sleep(BUILD_DELAY_MS);+ continue;+ }++ // Block already exists — count as placed and move on+ if (result.alreadyExists) {+ placedSet.add(key);+ progress.placedCount = placedSet.size;+ progress.placedSet = [...placedSet];+ await sleep(BUILD_DELAY_MS);+ continue;+ }++ // Record progress+ placedSet.add(key);+ sessionPlaced++;+ progress.placedCount = placedSet.size;+ progress.placedSet = [...placedSet];+ progress.lastBuildAt = new Date().toISOString();++ // Check daily limit+ if (result.dailyBuilds >= DAILY_LIMIT) {+ console.log(`\n🚫 Daily build limit reached (${DAILY_LIMIT} blocks)`);+ console.log(`📂 Progress saved — run again tomorrow to resume`);+ await saveProgress(progress);+ break;+ }++ // Status log+ const pct = Math.round((placedSet.size / blocks.length) * 100);+ const layer = block.z === MAZE_BASE_Z ? 'floor' : `wall-${block.z - MAZE_BASE_Z}`;+ console.log(`🧱 ${placedSet.size}/${blocks.length} (${pct}%) | (${block.x},${block.y},${block.z}) ${layer} | session: ${sessionPlaced}`);++ // Save progress every block+ await saveProgress(progress);++ // Heartbeat: re-join world and think every N blocks+ if (sessionPlaced % HEARTBEAT_EVERY === 0) {+ const thought = getBuildThought(placedSet.size, blocks.length);+ console.log(` 💭 ${thought}`);+ await apiRequest('/api/world/join', {+ agentId,+ name,+ x: MAZE_CENTER_X,+ y: MAZE_CENTER_Y,+ thinking: thought+ }).catch(() => {});+ }++ // Wait between builds+ if (running) {+ await sleep(BUILD_DELAY_MS);+ }+ }++ // Final save+ await saveProgress(progress);++ // Summary+ const totalElapsed = Math.round((Date.now() - startTime) / 1000);+ const minutes = Math.floor(totalElapsed / 60);+ const seconds = totalElapsed % 60;+ console.log('');+ console.log('📊 Build Summary');+ console.log(` Maze: ${MAZE_SIZE}x${MAZE_SIZE} at (${MAZE_CENTER_X},${MAZE_CENTER_Y}) Z=${MAZE_BASE_Z}`);+ console.log(` Session duration: ${minutes}m ${seconds}s`);+ console.log(` Blocks placed this session: ${sessionPlaced}`);+ console.log(` Total placed: ${placedSet.size}/${blocks.length}`);+ console.log(` Remaining: ${blocks.length - placedSet.size}`);++ if (placedSet.size >= blocks.length) {+ console.log(' ✅ Maze complete!');+ } else {+ console.log(' ⏸️ Run again to resume building');+ }++ // Final balance+ const balance = await apiRequest(`/api/agents/balance?agentId=${encodeURIComponent(agentId)}`).catch(() => null);+ if (balance?.balance) {+ console.log(` SIM balance: ${balance.balance.sim}`);+ }++ console.log('👋 Done!');+}++const main = process.argv.includes('--cleanup') ? cleanupMaze : buildMaze;+main().catch(e => {+ console.error(`💀 Fatal: ${e.message}`);+ process.exit(1);+});diff --git a/server/services/agentActionExecutor.js b/server/services/agentActionExecutor.jsindex 2c83fda85c..b0f559e5ef 100644--- a/server/services/agentActionExecutor.js+++ b/server/services/agentActionExecutor.js@@ -410,16 +410,19 @@ async function executeMoltworldAction(action, account, agent) {case 'mw_heartbeat':return executeMoltworldHeartbeat(client, account, action.params);- case 'explore':+ case 'mw_explore':return executeMoltworldExplore(client, account, action.params);- case 'build':+ case 'mw_build':return executeMoltworldBuild(client, action.params);- case 'say':+ case 'mw_say':return executeMoltworldSay(client, action.params);- case 'interact':+ case 'mw_think':+ return executeMoltworldThink(client, action.params);++ case 'mw_interact':return executeMoltworldInteract(client, account, action.params);default:@@ -468,7 +471,7 @@ async function executeMoltworldExplore(client, account, params) {console.log(`🌍 Moltworld: Explore to (${x}, ${y}) for ${account.credentials.username}`);return {- type: 'explore',+ type: 'mw_explore',x,y,thinking,@@ -489,7 +492,7 @@ async function executeMoltworldBuild(client, params) {});return {- type: 'build',+ type: 'mw_build',...result};}@@ -509,13 +512,22 @@ async function executeMoltworldSay(client, params) {console.log(`💬 Moltworld: Said "${(params.message || '').substring(0, 50)}"`);return {- type: 'say',+ type: 'mw_say',message: params.message,sayTo: params.sayTo,nearby: result?.nearby?.length || 0};}+/**+ * Moltworld think — send a thought+ */+async function executeMoltworldThink(client, params) {+ const result = await client.think(params.thought || 'Thinking...');+ console.log(`💭 Moltworld: Thought "${(params.thought || '').substring(0, 50)}"`);+ return { type: 'mw_think', thought: params.thought };+}+/*** Moltworld interact — compound action: move, think, optionally build*/@@ -531,7 +543,7 @@ async function executeMoltworldInteract(client, account, params) {thinking: params.thinking || `Looking around (${x}, ${y})...`});- const results = { type: 'interact', x, y, nearby: moveResult?.nearby?.length || 0 };+ const results = { type: 'mw_interact', x, y, nearby: moveResult?.nearby?.length || 0 };// Optionally buildif (params.buildType) {diff --git a/server/services/moltworldQueue.js b/server/services/moltworldQueue.jsnew file mode 100644index 0000000000..2834cedd17--- /dev/null+++ b/server/services/moltworldQueue.js@@ -0,0 +1,159 @@+/**+ * Moltworld Action Queue Service+ *+ * In-memory queue per agentId for scheduling actions that the+ * explore script (or other consumers) can pick up and execute.+ *+ * Events emitted on queueEvents:+ * added - new item added to a queue+ * updated - item status changed (executing, completed, failed)+ * removed - item cancelled/removed+ */++import { randomUUID } from 'crypto';+import EventEmitter from 'events';++export const queueEvents = new EventEmitter();++// Map<agentId, QueueItem[]>+const queues = new Map();++const MAX_ITEMS_PER_AGENT = 100;++function getOrCreateQueue(agentId) {+ if (!queues.has(agentId)) {+ queues.set(agentId, []);+ }+ return queues.get(agentId);+}++function evictCompleted(queue) {+ if (queue.length <= MAX_ITEMS_PER_AGENT) return;+ // Remove oldest completed/failed items first+ const completedIndices = [];+ for (let i = 0; i < queue.length; i++) {+ if (queue[i].status === 'completed' || queue[i].status === 'failed') {+ completedIndices.push(i);+ }+ }+ while (queue.length > MAX_ITEMS_PER_AGENT && completedIndices.length > 0) {+ queue.splice(completedIndices.shift(), 1);+ // Adjust remaining indices+ for (let j = 0; j < completedIndices.length; j++) {+ completedIndices[j]--;+ }+ }+}++/**+ * Get non-completed items for an agent (pending + executing)+ */+export function getQueue(agentId) {+ const queue = queues.get(agentId) || [];+ return queue.filter(item => item.status === 'pending' || item.status === 'executing');+}++/**+ * Get all items for an agent (including completed/failed, for display)+ */+export function getFullQueue(agentId) {+ return queues.get(agentId) || [];+}++/**+ * Add an action to the queue+ */+export function addAction(agentId, actionType, params = {}, scheduledFor = null) {+ const queue = getOrCreateQueue(agentId);+ const item = {+ id: randomUUID(),+ agentId,+ actionType,+ params,+ status: 'pending',+ scheduledFor: scheduledFor || null,+ createdAt: new Date().toISOString(),+ completedAt: null,+ error: null+ };+ queue.push(item);+ evictCompleted(queue);+ console.log(`📋 Queue: added ${actionType} for agent=${agentId} id=${item.id}`);+ queueEvents.emit('added', item);+ return item;+}++/**+ * Pop the next pending item (FIFO), mark it as executing+ */+export function popNext(agentId) {+ const queue = queues.get(agentId) || [];+ const now = new Date().toISOString();+ const idx = queue.findIndex(item =>+ item.status === 'pending' &&+ (!item.scheduledFor || item.scheduledFor <= now)+ );+ if (idx === -1) return null;++ queue[idx].status = 'executing';+ const item = queue[idx];+ console.log(`📋 Queue: executing ${item.actionType} id=${item.id}`);+ queueEvents.emit('updated', item);+ return item;+}++/**+ * Mark an item as completed+ */+export function markCompleted(itemId) {+ for (const queue of queues.values()) {+ const item = queue.find(i => i.id === itemId);+ if (item) {+ item.status = 'completed';+ item.completedAt = new Date().toISOString();+ console.log(`📋 Queue: completed ${item.actionType} id=${itemId}`);+ queueEvents.emit('updated', item);+ return item;+ }+ }+ return null;+}++/**+ * Mark an item as failed+ */+export function markFailed(itemId, error) {+ for (const queue of queues.values()) {+ const item = queue.find(i => i.id === itemId);+ if (item) {+ item.status = 'failed';+ item.completedAt = new Date().toISOString();+ item.error = error;+ console.log(`📋 Queue: failed ${item.actionType} id=${itemId} error=${error}`);+ queueEvents.emit('updated', item);+ return item;+ }+ }+ return null;+}++/**+ * Remove a pending item (cancel)+ */+export function removeAction(itemId) {+ for (const [agentId, queue] of queues.entries()) {+ const idx = queue.findIndex(i => i.id === itemId);+ if (idx !== -1) {+ const [item] = queue.splice(idx, 1);+ if (item.status !== 'pending') {+ // Can only cancel pending items; put it back+ queue.splice(idx, 0, item);+ return null;+ }+ console.log(`📋 Queue: removed ${item.actionType} id=${itemId}`);+ queueEvents.emit('removed', { id: itemId, agentId });+ return item;+ }+ }+ return null;+}diff --git a/server/services/moltworldWs.js b/server/services/moltworldWs.jsnew file mode 100644index 0000000000..59ff0059d2--- /dev/null+++ b/server/services/moltworldWs.js@@ -0,0 +1,325 @@+/**+ * Moltworld WebSocket Client Service+ *+ * Manages a single WebSocket connection to Moltworld's real-time event stream.+ * Emits events through an EventEmitter that gets forwarded via Socket.IO to clients.+ *+ * Events emitted on moltworldWsEvents:+ * status - connection state changes ({ status, connectedAt, ... })+ * event - all incoming events (raw parsed data)+ * presence - agent presence snapshots+ * thinking - agent thought events+ * action - agent action events (move, build, etc.)+ * interaction - agent-to-agent interactions+ * nearby - nearby agent list updates+ * hello_ack - server acknowledged our hello+ */++import WebSocket from 'ws';+import EventEmitter from 'events';+import * as platformAccounts from './platformAccounts.js';+import * as agentActivity from './agentActivity.js';++export const moltworldWsEvents = new EventEmitter();++// Connection state+let ws = null;+let reconnectTimer = null;+let reconnectAttempts = 0;+let connectedAt = null;+let lastEvent = null;+let currentStatus = 'disconnected';+let currentAccountId = null;+let currentAgentId = null;+let currentAgentName = null;++const MAX_RECONNECT_DELAY_MS = 60000;+const BASE_RECONNECT_DELAY_MS = 2000;+const CONNECT_TIMEOUT_MS = 10000;++function setStatus(status) {+ currentStatus = status;+ const stateSnapshot = getStatus();+ moltworldWsEvents.emit('status', stateSnapshot);+ console.log(`🌐 Moltworld WS: ${status}`);+}++export function getStatus() {+ return {+ status: currentStatus,+ connectedAt,+ lastEvent,+ reconnectAttempts,+ agentId: currentAgentId,+ agentName: currentAgentName,+ accountId: currentAccountId+ };+}++function clearReconnectTimer() {+ if (reconnectTimer) {+ clearTimeout(reconnectTimer);+ reconnectTimer = null;+ }+}++function scheduleReconnect() {+ clearReconnectTimer();+ const delay = Math.min(+ BASE_RECONNECT_DELAY_MS * Math.pow(2, reconnectAttempts),+ MAX_RECONNECT_DELAY_MS+ );+ reconnectAttempts++;+ setStatus('reconnecting');+ console.log(`🌐 Moltworld WS: reconnecting in ${Math.round(delay / 1000)}s (attempt ${reconnectAttempts})`);+ reconnectTimer = setTimeout(() => doConnect(), delay);+}++function handleMessage(raw) {+ // External data from Moltworld — parse guard is justified+ let data;+ try {+ data = JSON.parse(raw);+ } catch {+ console.error(`🌐 Moltworld WS: invalid JSON received`);+ return;+ }++ lastEvent = Date.now();+ const eventType = data.type || data.event || 'unknown';++ // Forward all events+ moltworldWsEvents.emit('event', data);++ // Dispatch by type+ if (eventType === 'presence' || eventType === 'presence_snapshot') {+ moltworldWsEvents.emit('presence', data);+ } else if (eventType === 'thinking' || eventType === 'thought') {+ moltworldWsEvents.emit('thinking', data);+ } else if (eventType === 'action' || eventType === 'move' || eventType === 'build') {+ moltworldWsEvents.emit('action', data);+ } else if (eventType === 'interaction' || eventType === 'message' || eventType === 'say') {+ moltworldWsEvents.emit('interaction', data);+ // Log interactions to activity service+ if (currentAgentId && data.agentId) {+ agentActivity.logActivity({+ agentId: currentAgentId,+ accountId: currentAccountId,+ action: 'moltworld:interaction',+ params: { eventType, from: data.agentName || data.agentId },+ status: 'completed',+ result: { type: eventType, content: data.message || data.thought || '' },+ timestamp: new Date().toISOString()+ }).catch(() => {});+ }+ } else if (eventType === 'nearby') {+ moltworldWsEvents.emit('nearby', data);+ } else if (eventType === 'hello_ack' || eventType === 'welcome') {+ moltworldWsEvents.emit('hello_ack', data);+ console.log(`🌐 Moltworld WS: hello acknowledged`);+ }+}++function cleanupWs() {+ if (ws) {+ ws.removeAllListeners();+ if (ws.readyState === WebSocket.OPEN) {+ ws.close();+ } else if (ws.readyState === WebSocket.CONNECTING) {+ ws.terminate(); // terminate() is safe for CONNECTING state; close() throws+ }+ ws = null;+ }+}++/**+ * Open a WebSocket connection. Returns a promise that resolves on open+ * or rejects on error/timeout. When called from reconnect, the promise+ * result is ignored (fire-and-forget).+ */+function doConnect() {+ if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {+ return Promise.resolve();+ }++ setStatus('connecting');++ return new Promise((resolve, reject) => {+ const timeout = setTimeout(() => {+ console.error(`🌐 Moltworld WS: connection timed out after ${CONNECT_TIMEOUT_MS / 1000}s`);+ cleanupWs();+ setStatus('disconnected');+ reject(new Error('WebSocket connection timed out — Moltworld may not have a WebSocket endpoint available'));+ }, CONNECT_TIMEOUT_MS);++ const instance = new WebSocket('wss://moltworld.io/ws');+ ws = instance;++ instance.on('open', () => {+ clearTimeout(timeout);+ connectedAt = Date.now();+ reconnectAttempts = 0;+ setStatus('connected');++ // Send hello with agent credentials+ send({+ type: 'hello',+ agentId: currentAgentId,+ name: currentAgentName+ });++ resolve();+ });++ instance.on('message', (raw) => handleMessage(String(raw)));++ instance.on('close', (code) => {+ clearTimeout(timeout);+ console.log(`🌐 Moltworld WS: closed (code=${code})`);+ ws = null;+ if (currentStatus !== 'disconnected') {+ scheduleReconnect();+ }+ });++ instance.on('error', (err) => {+ clearTimeout(timeout);+ console.error(`🌐 Moltworld WS: error: ${err.message}`);+ cleanupWs();+ // Only reject on initial connect, not reconnects+ if (currentStatus === 'connecting') {+ setStatus('disconnected');+ reject(new Error(`WebSocket connection failed: ${err.message}`));+ }+ });+ });+}++/**+ * Connect to Moltworld WebSocket relay.+ * Looks up credentials from platformAccounts by accountId.+ * Awaits the connection result — resolves on open, rejects on error/timeout.+ */+export async function connect(accountId) {+ // Disconnect existing connection if any+ disconnect();++ const account = await platformAccounts.getAccountWithCredentials(accountId);+ if (!account) {+ throw new Error('Account not found');+ }+ if (account.platform !== 'moltworld') {+ throw new Error('Account is not a Moltworld account');+ }+ if (account.status !== 'active') {+ throw new Error(`Account not active: ${account.status}`);+ }++ currentAccountId = accountId;+ currentAgentId = account.credentials.agentId || account.credentials.apiKey;+ currentAgentName = account.credentials.username || 'Agent';++ await doConnect();+}++/**+ * Disconnect from Moltworld WebSocket+ */+export function disconnect() {+ clearReconnectTimer();+ currentStatus = 'disconnected';+ connectedAt = null;+ reconnectAttempts = 0;+ cleanupWs();+ setStatus('disconnected');+}++/**+ * Send a JSON message through the WebSocket+ */+export function send(message) {+ if (!ws || ws.readyState !== WebSocket.OPEN) {+ throw new Error('WebSocket not connected');+ }+ ws.send(JSON.stringify(message));+}++/**+ * Send a move command+ */+export function sendMove(x, y, thought) {+ send({+ type: 'move',+ agentId: currentAgentId,+ x,+ y,+ ...(thought ? { thinking: thought } : {})+ });+ if (currentAgentId && currentAccountId) {+ agentActivity.logActivity({+ agentId: currentAgentId,+ accountId: currentAccountId,+ action: 'mw_explore',+ params: { x, y, thinking: thought, via: 'ws' },+ status: 'completed',+ result: { type: 'move' },+ timestamp: new Date().toISOString()+ }).catch(() => {});+ }+}++/**+ * Send a think command+ */+export function sendThink(thought) {+ send({+ type: 'think',+ agentId: currentAgentId,+ thought+ });+ if (currentAgentId && currentAccountId) {+ agentActivity.logActivity({+ agentId: currentAgentId,+ accountId: currentAccountId,+ action: 'mw_think',+ params: { thought, via: 'ws' },+ status: 'completed',+ result: { type: 'think' },+ timestamp: new Date().toISOString()+ }).catch(() => {});+ }+}++/**+ * Send an interaction to another agent+ */+export function sendInteract(toAgentId, payload) {+ send({+ type: 'interact',+ agentId: currentAgentId,+ to: toAgentId,+ ...payload+ });+ if (currentAgentId && currentAccountId) {+ agentActivity.logActivity({+ agentId: currentAgentId,+ accountId: currentAccountId,+ action: 'mw_say',+ params: { to: toAgentId, ...payload, via: 'ws' },+ status: 'completed',+ result: { type: 'interact' },+ timestamp: new Date().toISOString()+ }).catch(() => {});+ }+}++/**+ * Request nearby agents list+ */+export function sendNearby(radius) {+ send({+ type: 'nearby',+ agentId: currentAgentId,+ ...(radius ? { radius } : {})+ });+}diff --git a/server/services/socket.js b/server/services/socket.jsindex 136d4badc1..c7fb2bb686 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -12,6 +12,8 @@ import { platformAccountEvents } from './platformAccounts.js';import { scheduleEvents } from './automationScheduler.js';import { activityEvents } from './agentActivity.js';import { brainEvents } from './brainStorage.js';+import { moltworldWsEvents } from './moltworldWs.js';+import { queueEvents } from './moltworldQueue.js';import * as shellService from './shell.js';// Store active log streams per socket@@ -296,6 +298,12 @@ export function initSocket(io) {// Set up brain event forwardingsetupBrainEventForwarding();++ // Set up Moltworld WebSocket event forwarding+ setupMoltworldWsEventForwarding();++ // Set up Moltworld queue event forwarding+ setupMoltworldQueueEventForwarding();}function cleanupStream(socketId) {@@ -446,3 +454,21 @@ function setupBrainEventForwarding() {}});}++// Set up Moltworld WebSocket event forwarding to agent subscribers+function setupMoltworldWsEventForwarding() {+ moltworldWsEvents.on('status', (data) => broadcastToAgents('moltworld:status', data));+ moltworldWsEvents.on('event', (data) => broadcastToAgents('moltworld:event', data));+ moltworldWsEvents.on('presence', (data) => broadcastToAgents('moltworld:presence', data));+ moltworldWsEvents.on('thinking', (data) => broadcastToAgents('moltworld:thinking', data));+ moltworldWsEvents.on('action', (data) => broadcastToAgents('moltworld:action', data));+ moltworldWsEvents.on('interaction', (data) => broadcastToAgents('moltworld:interaction', data));+ moltworldWsEvents.on('nearby', (data) => broadcastToAgents('moltworld:nearby', data));+}++// Set up Moltworld queue event forwarding to agent subscribers+function setupMoltworldQueueEventForwarding() {+ queueEvents.on('added', (data) => broadcastToAgents('moltworld:queue:added', data));+ queueEvents.on('updated', (data) => broadcastToAgents('moltworld:queue:updated', data));+ queueEvents.on('removed', (data) => broadcastToAgents('moltworld:queue:removed', data));+}