Skip to content

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

feat(agents): add Moltworld platform support

Adam Eivy36e0df354e1e
diff --git a/.changelog/v0.13.x.md b/.changelog/v0.13.x.md
index 236656bd2f..c6a6e02512 100644
--- a/.changelog/v0.13.x.md
+++ b/.changelog/v0.13.x.md
@@ -30,6 +30,16 @@ This release expands the genome dashboard with comprehensive cancer predispositi
- **Thyroid** expanded (2 markers): NKX2-1, DIRC3 papillary thyroid cancer
- **Reorganized cancer categories**: Replaced single `cancer_risk` with specific cancer type subcategories for clearer organization; moved KRAS to tumor suppression (multi-cancer)
+### Moltworld Platform Support
+- **New platform: Moltworld** — a shared voxel world (480x480 grid) where AI agents move, build structures, think out loud, communicate, and earn SIM tokens
+- **Agent registration** via Moltworld API with automatic `agentId`-based auth (no claim step needed, unlike Moltbook)
+- **World actions**: Join/move (heartbeat), explore (random/targeted movement), build (place/remove blocks), think (visible thoughts), say (messaging)
+- **SIM token economy**: 0.1 SIM/hour while online; balance tracking via dedicated endpoint
+- **Rate limiting**: Per-action cooldowns (join: 5s, build: 1s, think: 5s) plus global 60 req/min sliding window
+- **Scheduled automation**: 5 new action types — `mw_heartbeat`, `explore`, `build`, `say`, `interact` — with platform-aware schedule form filtering
+- **Platform-aware UI**: Quick actions switch between Moltbook (Engage, Check Posts) and Moltworld (Explore, Build) based on selected account; schedule action dropdown filters by platform
+- **Connection testing**: Profile + balance check for Moltworld accounts in the Test Connection flow
+
## Improvements
### CoS — Consolidated Duplicate Repo Maintenance Jobs
diff --git a/PLAN.md b/PLAN.md
index 9d2f4f432c..7e160b9928 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -67,13 +67,14 @@ pm2 logs
- [x] **M38**: Agent Tools - AI content generation, feed browsing, and autonomous engagement for Moltbook agents
- [x] **M39**: Agent-Centric Drill-Down - Redesigned Agents section with agent-first hierarchy, deep-linkable URLs, and scoped sub-tabs
- [x] **M41**: CyberCity Immersive Overhaul - Procedural synthwave audio, enhanced post-processing (chromatic aberration, film grain, color grading), reflective wet-street ground, settings system, and atmosphere enhancements
+- [x] **M43**: Moltworld Platform Support - Second platform integration for AI agents in a shared voxel world with movement, building, thinking, messaging, and SIM token economy
### Planned
- [ ] **M7**: App Templates - Template management and app scaffolding from templates
- [ ] **M34 P3,P5-P7**: Digital Twin - Behavioral feedback loop, multi-modal capture, advanced testing, personas
- [ ] **M40**: Agent Skill System - Task-type-specific prompt templates with routing logic, negative examples, and embedded workflows for improved agent accuracy and reliability
-- [ ] **M42**: Unified Digital Twin Identity System - Connect Genome, Chronotype, Aesthetic Taste, and Mortality-Aware Goals into a single coherent Identity architecture
+- [ ] **M42**: Unified Digital Twin Identity System - Connect Genome (117 markers, 32 categories), Chronotype (5 sleep markers + behavioral), Aesthetic Taste (P2 complete, P2.5 adds twin-aware prompting), and Mortality-Aware Goals into a single coherent Identity architecture with cross-insights engine
---
@@ -85,9 +86,9 @@ Four separate workstreams converge on the same vision: a personal digital twin t
| Subsystem | Current State | Location |
|-----------|--------------|----------|
-| **Genome** | Fully implemented: 23andMe upload, 37+ curated SNP markers across 13 categories, ClinVar integration | `server/services/genome.js`, `GenomeTab.jsx`, `data/digital-twin/genome.json` |
-| **Chronotype** | Partially exists: 2 sleep markers (CLOCK rs1801260, DEC2 rs57875989) in genome + `daily_routines` enrichment category | `curatedGenomeMarkers.js` sleep category, `ENRICHMENT_CATEGORIES.daily_routines` |
-| **Aesthetic Taste** | Partially exists: `aesthetics` enrichment category + book/movie/music list-based enrichments | `ENRICHMENT_CATEGORIES.aesthetics`, `BOOKS.md`, `MOVIES.md`, `AUDIO.md` |
+| **Genome** | Fully implemented: 23andMe upload, 117 curated SNP markers across 32 categories, ClinVar integration, epigenetic tracking | `server/services/genome.js`, `GenomeTab.jsx`, `data/digital-twin/genome.json` |
+| **Chronotype** | Genetic data ready: 5 sleep/circadian markers (CLOCK rs1801260, DEC2 rs57875989, PER2 rs35333999, CRY1 rs2287161, MTNR1B rs10830963) + `daily_routines` enrichment category. Derivation service not yet built | `curatedGenomeMarkers.js` sleep category, `ENRICHMENT_CATEGORIES.daily_routines` |
+| **Aesthetic Taste** | P2 complete: Taste questionnaire with 5 sections (movies, music, visual_art, architecture, food), conversational Q&A, AI summary generation. Enrichment categories also feed taste data from book/movie/music lists | `TasteTab.jsx`, `taste-questionnaire.js`, `data/digital-twin/taste-profile.json` |
| **Goal Tracking** | Partially exists: `COS-GOALS.md` for CoS missions, `TASKS.md` for user tasks, `EXISTENTIAL.md` soul doc | `data/COS-GOALS.md`, `data/TASKS.md`, `data/digital-twin/EXISTENTIAL.md` |
These should be unified under a single **Identity** architecture so the twin can reason across all dimensions (e.g., "your CLOCK gene says evening chronotype — schedule deep work after 8pm" or "given your longevity markers and age, here's how to prioritize your 10-year goals").
@@ -102,7 +103,7 @@ These should be unified under a single **Identity** architecture so the twin can
"createdAt": "2026-02-12T00:00:00.000Z",
"updatedAt": "2026-02-12T00:00:00.000Z",
"sections": {
- "genome": { "status": "active", "dataFile": "genome.json", "markerCount": 37, "lastScanAt": "..." },
+ "genome": { "status": "active", "dataFile": "genome.json", "markerCount": 117, "categoryCount": 32, "lastScanAt": "..." },
"chronotype": { "status": "active", "dataFile": "chronotype.json", "derivedFrom": ["genome:sleep", "enrichment:daily_routines"] },
"aesthetics": { "status": "active", "dataFile": "aesthetics.json", "derivedFrom": ["enrichment:aesthetics", "enrichment:favorite_books", "enrichment:favorite_movies", "enrichment:music_taste"] },
"goals": { "status": "active", "dataFile": "goals.json" }
@@ -122,7 +123,10 @@ Derived from genome sleep markers + daily_routines enrichment answers + user ove
"sources": {
"genetic": {
"clockGene": { "rsid": "rs1801260", "genotype": "T/C", "signal": "mild_evening" },
- "dec2": { "rsid": "rs57875989", "genotype": "G/G", "signal": "standard_sleep_need" }
+ "dec2": { "rsid": "rs57875989", "genotype": "G/G", "signal": "standard_sleep_need" },
+ "per2": { "rsid": "rs35333999", "genotype": "C/C", "signal": "standard_circadian" },
+ "cry1": { "rsid": "rs2287161", "genotype": "C/C", "signal": "standard_period" },
+ "mtnr1b": { "rsid": "rs10830963", "genotype": "T/T", "signal": "normal_melatonin_receptor" }
},
"behavioral": {
"preferredWakeTime": "08:30",
@@ -141,7 +145,7 @@ Derived from genome sleep markers + daily_routines enrichment answers + user ove
}
```
-**Derivation logic**: Genome sleep markers provide the genetic baseline. The `daily_routines` enrichment answers provide behavioral confirmation. When genetic and behavioral signals agree, confidence is high. When they disagree, surface the conflict for user review. Caffeine cutoff cross-references caffeine metabolism markers (CYP1A2 rs762551, ADA rs73598374).
+**Derivation logic**: Five genome sleep markers provide the genetic baseline: CLOCK (evening preference), DEC2 (sleep duration need), PER2 (circadian period), CRY1 (delayed sleep phase), MTNR1B (melatonin receptor / nighttime glucose). The `daily_routines` enrichment answers provide behavioral confirmation. When genetic and behavioral signals agree, confidence is high. When they disagree, surface the conflict for user review. Caffeine cutoff cross-references caffeine metabolism markers (CYP1A2 rs762551, ADA rs73598374). MTNR1B status also informs late-eating recommendations.
#### Entity: Aesthetic Taste Profile (`aesthetics.json`)
@@ -259,8 +263,9 @@ Consolidates scattered aesthetic data into a structured profile.
```
**Cross-cutting links** (stored in `identity.json.crossLinks`):
-- `genome:sleep` → `chronotype:genetic` (CLOCK/DEC2 markers feed chronotype)
+- `genome:sleep` → `chronotype:genetic` (CLOCK/DEC2/PER2/CRY1/MTNR1B markers feed chronotype)
- `genome:caffeine` → `chronotype:recommendations.caffeineCutoff` (CYP1A2/ADA markers set cutoff)
+- `genome:sleep:mtnr1b` → `chronotype:recommendations.lateEatingCutoff` (MTNR1B impairs nighttime glucose)
- `genome:longevity` + `genome:cardiovascular` → `goals:lifeExpectancyEstimate` (risk-adjusted lifespan)
- `enrichment:daily_routines` → `chronotype:behavioral` (self-reported schedule)
- `enrichment:aesthetics` + `enrichment:favorite_*` + `enrichment:music_taste` → `aesthetics:profile` (taste extraction)
@@ -284,22 +289,23 @@ The existing Digital Twin page at `/digital-twin/:tab` gets a new **Identity** t
│ └───────────────────────────────────────────────────────┘ │
│ │
│ ┌─ Genome Summary Card ─────────────────────────────────┐ │
-│ │ 37 markers scanned across 13 categories │ │
-│ │ Key findings: 3 beneficial, 2 concern, 1 major │ │
+│ │ 117 markers scanned across 32 categories │ │
+│ │ Key findings: ~20 beneficial, ~40 concern, ~5 major │ │
│ │ [View Full Genome →] │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
│ ┌─ Chronotype Card ─────────────────────────────────────┐ │
-│ │ Type: Evening Owl (75% confidence) │ │
-│ │ Genetic: CLOCK T/C (mild evening) + DEC2 G/G │ │
+│ │ Type: Evening Owl (75% confidence from 5 markers) │ │
+│ │ Genetic: CLOCK T/C + CRY1 C/C + PER2 C/C + DEC2 G/G│ │
│ │ Peak focus: 8pm-2am | Caffeine cutoff: 2pm │ │
+│ │ Late eating cutoff: 8pm (MTNR1B-informed) │ │
│ │ [Configure Schedule →] │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
│ ┌─ Aesthetic Taste Card ────────────────────────────────┐ │
-│ │ Status: Needs questionnaire (0/7 sections) │ │
+│ │ Taste Tab: 0/5 sections completed (P2 UI ready) │ │
│ │ Detected themes from media: brutalist, atmospheric │ │
-│ │ [Start Taste Questionnaire →] │ │
+│ │ [Continue Taste Questionnaire →] [Go to Taste Tab →] │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
│ ┌─ Life Goals Card ─────────────────────────────────────┐ │
@@ -330,11 +336,12 @@ The existing Digital Twin page at `/digital-twin/:tab` gets a new **Identity** t
#### P1: Identity Orchestrator & Chronotype (data layer)
- Create `data/digital-twin/identity.json` with section status tracking
-- Create `server/services/identity.js` — orchestrator that reads from genome, enrichment, and new data files
-- Create `data/digital-twin/chronotype.json` — derive from genome sleep markers + daily_routines enrichment
+- Create `server/services/identity.js` — orchestrator that reads from genome, enrichment, taste-profile, and new data files
+- Create `data/digital-twin/chronotype.json` — derive from 5 genome sleep markers + daily_routines enrichment
- Add `GET /api/digital-twin/identity` route returning unified section status
- Add `GET/PUT /api/digital-twin/identity/chronotype` routes
-- Derivation function: `deriveChronotypeFromGenome(genomeSummary)` extracts CLOCK + DEC2 status → chronotype signal
+- Derivation function: `deriveChronotypeFromGenome(genomeSummary)` extracts all 5 sleep markers (CLOCK, DEC2, PER2, CRY1, MTNR1B) → composite chronotype signal with weighted confidence
+- Cross-reference CYP1A2/ADA caffeine markers and MTNR1B melatonin receptor for caffeine cutoff and late-eating recommendations
#### P2: Aesthetic Taste Questionnaire ✅
- Created `data/digital-twin/taste-profile.json` for structured taste preference storage
@@ -348,7 +355,7 @@ The existing Digital Twin page at `/digital-twin/:tab` gets a new **Identity** t
- Create `data/digital-twin/goals.json`
- Add `GET/POST/PUT/DELETE /api/digital-twin/identity/goals` routes
- Birth date input + SSA actuarial table lookup
-- Genome-adjusted life expectancy: weight longevity markers (FOXO3A, IGF1R, CETP) and cardiovascular risk markers (Factor V, 9p21, Lp(a)) into adjustment factor
+- Genome-adjusted life expectancy: weight longevity markers (5 markers: FOXO3A, IGF1R, CETP, IPMK, TP53) and cardiovascular risk markers (5 markers: Factor V, 9p21, Lp(a), LPA aspirin, PCSK9) into adjustment factor
- Time-horizon calculation: years remaining, healthy years, percent complete
- Urgency scoring: `urgency = (goalHorizonYears - yearsRemaining) / goalHorizonYears` normalized
- Goal CRUD with category tagging and milestone tracking
@@ -361,31 +368,86 @@ The existing Digital Twin page at `/digital-twin/:tab` gets a new **Identity** t
- Create `GoalTracker.jsx` — goal list with urgency heatmap and timeline view
- Wire sub-routes for deep dives
+#### P2.5: Digital Twin Aesthetic Taste Prompting (brain idea 608dc733)
+The existing Taste tab uses static questions. This phase enhances it by having the digital twin generate personalized follow-up questions based on existing identity documents and enrichment answers. The twin reads BOOKS.md, AUDIO.md, and enrichment responses to craft targeted queries like "You listed Blade Runner as a favorite — what specific visual elements resonated?" instead of generic "Name a movie you like."
+- Add `generatePersonalizedTasteQuestion(section, existingResponses, identityContext)` to `taste-questionnaire.js`
+- Identity context includes: enrichment answers, document excerpts (BOOKS.md, AUDIO.md, CREATIVE.md), traits (aesthetic markers from Big Five Openness dimension)
+- LLM generates contextual follow-ups that probe deeper into already-expressed preferences
+- Responses feed back into `taste-profile.json` and `aesthetics.json` (once P1 Identity orchestrator exists)
+- Prerequisite: P1 (identity orchestrator provides the context aggregation)
+
#### P5: Cross-Insights Engine
- Add `generateCrossInsights(identity)` in identity service
- Cross-reference genome markers with chronotype, goals, and enrichment data
- Generate natural-language insight strings (e.g., caffeine + chronotype, longevity + goal urgency)
- Display on Identity dashboard and inject into CoS context when relevant
- Consider autonomous job: periodic identity insight refresh
+- Example cross-insights from current marker data:
+ - CLOCK + CRY1 + PER2 → composite chronotype confidence (3 markers agreeing = high confidence evening/morning)
+ - MTNR1B concern + evening chronotype → "avoid eating after 8pm — your melatonin receptor variant impairs late glucose handling"
+ - CYP1A2 slow metabolizer + CLOCK evening → "caffeine cutoff by noon, not 2pm"
+ - FOXO3A/CETP/IGF1R longevity markers + cardiovascular risk → adjusted life expectancy for goal urgency
+
+### Identity Extension Roadmap
+
+This roadmap connects brain ideas and the Genome Section Integration project (0e6a0332) into a unified implementation sequence.
+
+#### Source Ideas
+- **Brain idea 608dc733**: "Prompting Aesthetic Taste Docs via Digital Twin" — use the twin's existing knowledge to generate personalized aesthetic preference questions
+- **Brain idea 284dd487**: "Genome Types & Chronotype Trait" — derive chronotype from 5 sleep/circadian markers + behavioral data
+- **Project 0e6a0332**: "Genome Section Integration" — unify genome data with Identity page architecture
+
+#### Phase Dependency Graph
+
+```
+P1: Identity Orchestrator & Chronotype ──── (brain idea 284dd487)
+ │ Creates identity.json, chronotype.json,
+ │ identity service, derivation from 5 sleep markers
+ │
+ ├─► P2.5: Personalized Taste Prompting ─── (brain idea 608dc733)
+ │ Uses identity context to generate smart taste questions
+ │ Enhances existing TasteTab with twin-aware follow-ups
+ │
+ ├─► P3: Mortality-Aware Goal Tracking
+ │ Birth date + genome longevity/cardio markers → life expectancy
+ │ Urgency scoring for prioritized goal management
+ │
+ └─► P4: Identity Tab UI
+ Dashboard with summary cards for all 4 sections
+ Sub-routes for chronotype, taste, goals deep dives
+ │
+ └─► P5: Cross-Insights Engine
+ Reads all sections, generates natural-language insights
+ Injects identity context into CoS agent briefings
+```
+
+#### Implementation Priority
+1. **P1** — Foundation: nothing else works without the orchestrator
+2. **P2.5** — Quick win: enhances existing Taste tab with minimal new infrastructure
+3. **P3** — New feature: mortality-aware goals need genome data flowing through identity service
+4. **P4** — UI: renders what P1-P3 produce
+5. **P5** — Polish: cross-entity reasoning requires all sections populated
### Data Flow
```
-User uploads 23andMe → genome.json (existing)
+User uploads 23andMe → genome.json (117 markers, 32 categories)
+ ↓
+Identity service reads 5 sleep markers + 2 caffeine markers
↓
-Identity service reads genome sleep markers + caffeine markers
+Derives chronotype.json (+ behavioral input from daily_routines enrichment)
↓
-Derives chronotype.json (with behavioral input from enrichment)
+Twin reads identity context → generates personalized taste questions (P2.5)
↓
-User sets birth date → goals.json (life expectancy from actuarial + genome)
+User completes taste questionnaire → taste-profile.json → aesthetics.json
↓
-User completes taste questionnaire → aesthetics.json
+LLM analyzes books/movies/music docs → seeds aesthetic profile themes
↓
-LLM analyzes books/movies/music → seeds aesthetic profile themes
+User sets birth date → goals.json (life expectancy from actuarial + 10 genome markers)
↓
Cross-insights engine reads all 4 sections → generates natural-language insights
↓
-Identity tab renders unified dashboard
+Identity tab renders unified dashboard with summary cards + insights
↓
CoS injects identity context into agent briefings when relevant
```
@@ -411,15 +473,19 @@ CoS injects identity context into agent briefings when relevant
- `client/src/pages/DigitalTwin.jsx` — add Identity tab rendering
- `client/src/services/api.js` — add identity API methods
- `server/index.js` — mount identity routes
+- `server/services/taste-questionnaire.js` — add `generatePersonalizedTasteQuestion()` using identity context (P2.5)
+- `client/src/components/digital-twin/tabs/TasteTab.jsx` — wire personalized question generation (P2.5)
### Design Decisions
-1. **Separate data files per section** (not one giant file) — each section has independent update cadence and the genome file is already large
+1. **Separate data files per section** (not one giant file) — each section has independent update cadence and the genome file (82KB) is already large
2. **Derivation over duplication** — chronotype reads from genome.json at query time rather than copying marker data. Identity service is the join layer
3. **Progressive disclosure** — Identity tab shows summary cards; deep dives are sub-routes, not modals (per CLAUDE.md: all views must be deep-linkable)
4. **LLM-assisted but user-confirmed** — aesthetic themes extracted by LLM from media lists are suggestions, not gospel. User confirms/edits
5. **No new dependencies** — uses existing Zod, Express, React, Lucide stack
6. **Genome data stays read-only** — identity service reads genome markers but never writes to genome.json
+7. **Taste data consolidation** — P2 created `taste-profile.json` (5 sections). P2.5 adds twin-aware personalized questions. Long-term, taste data migrates into `aesthetics.json` as the canonical aesthetic profile, with taste-profile.json as the raw questionnaire responses
+8. **Weighted chronotype confidence** — 5 sleep markers weighted by specificity: CRY1 (strongest DSPD signal) > CLOCK (evening tendency) > PER2 (circadian period) > MTNR1B (melatonin coupling) > DEC2 (duration, not phase). Behavioral data from daily_routines enrichment gets equal weight to genetic composite
---
diff --git a/client/src/components/agents/constants.js b/client/src/components/agents/constants.js
index 7c0bd7374b..04639985af 100644
--- a/client/src/components/agents/constants.js
+++ b/client/src/components/agents/constants.js
@@ -19,12 +19,19 @@ export const PERSONALITY_STYLES = [
];
export const ACTION_TYPES = [
- { value: 'post', label: 'Post', description: 'Create new posts', icon: '📝' },
- { value: 'comment', label: 'Comment', description: 'Reply to posts', icon: '💬' },
- { value: 'vote', label: 'Vote', description: 'Upvote or downvote content', icon: '👍' },
- { value: 'heartbeat', label: 'Heartbeat', description: 'Browse and engage naturally', icon: '💓' },
- { value: 'engage', label: 'Engage', description: 'AI-powered browsing, commenting, and voting', icon: '🤝' },
- { value: 'monitor', label: 'Monitor', description: 'Check post engagement and respond', icon: '👀' }
+ // Moltbook actions
+ { value: 'post', label: 'Post', description: 'Create new posts', icon: '📝', platform: 'moltbook' },
+ { value: 'comment', label: 'Comment', description: 'Reply to posts', icon: '💬', platform: 'moltbook' },
+ { value: 'vote', label: 'Vote', description: 'Upvote or downvote content', icon: '👍', platform: 'moltbook' },
+ { value: 'heartbeat', label: 'Heartbeat', description: 'Browse and engage naturally', icon: '💓', platform: 'moltbook' },
+ { value: 'engage', label: 'Engage', description: 'AI-powered browsing, commenting, and voting', icon: '🤝', platform: 'moltbook' },
+ { 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' }
];
export const SCHEDULE_TYPES = [
@@ -34,7 +41,8 @@ export const SCHEDULE_TYPES = [
];
export const PLATFORM_TYPES = [
- { value: 'moltbook', label: 'Moltbook', description: 'AI social platform', icon: '📚' }
+ { value: 'moltbook', label: 'Moltbook', description: 'AI social platform', icon: '📚' },
+ { value: 'moltworld', label: 'Moltworld', description: 'Shared voxel world', icon: '🌍' }
];
export const ACCOUNT_STATUSES = {
diff --git a/client/src/components/agents/tabs/OverviewTab.jsx b/client/src/components/agents/tabs/OverviewTab.jsx
index e0454715b5..a38688831a 100644
--- a/client/src/components/agents/tabs/OverviewTab.jsx
+++ b/client/src/components/agents/tabs/OverviewTab.jsx
@@ -35,6 +35,7 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {
const [quickAccountId, setQuickAccountId] = useState('');
const [engaging, setEngaging] = useState(false);
const [checking, setChecking] = useState(false);
+ const [exploring, setExploring] = useState(false);
const [rateLimits, setRateLimits] = useState(null);
// Cooldown timer state
@@ -93,14 +94,22 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {
}
}, [accounts, quickAccountId]);
+ // Derive platform from selected quick account
+ const quickAccount = accounts.find(a => a.id === quickAccountId);
+ const quickPlatform = quickAccount?.platform || 'moltbook';
+
// Load rate limits when quick account changes
useEffect(() => {
if (!quickAccountId) {
setRateLimits(null);
return;
}
- api.getAgentRateLimits(quickAccountId).then(setRateLimits).catch(() => {});
- }, [quickAccountId]);
+ const account = accounts.find(a => a.id === quickAccountId);
+ const endpoint = account?.platform === 'moltworld'
+ ? api.moltworldRateLimits(quickAccountId)
+ : api.getAgentRateLimits(quickAccountId);
+ endpoint.then(setRateLimits).catch(() => {});
+ }, [quickAccountId, accounts]);
// Calculate cooldown end timestamps from rate limit data
useEffect(() => {
@@ -197,6 +206,24 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {
api.getAgentRateLimits(quickAccountId).then(setRateLimits).catch(() => {});
};
+ // Moltworld quick actions
+ const handleExplore = async () => {
+ if (!agentId || !quickAccountId) return;
+ setExploring(true);
+ const result = await api.moltworldExplore(quickAccountId, agentId).catch(() => null);
+ setExploring(false);
+ if (!result) return;
+ toast.success(`Explored (${result.x}, ${result.y}) — ${result.nearby || 0} agents nearby`);
+ api.moltworldRateLimits(quickAccountId).then(setRateLimits).catch(() => {});
+ };
+
+ const handleBuild = async () => {
+ if (!agentId || !quickAccountId) return;
+ const result = await api.moltworldBuild(quickAccountId, agentId, 0, 0, 0, 'stone', 'place').catch(() => null);
+ if (result) toast.success('Block placed');
+ api.moltworldRateLimits(quickAccountId).then(setRateLimits).catch(() => {});
+ };
+
// Account handlers
const resetAccountForm = () => {
setAccountForm({ platform: 'moltbook', name: '', description: '' });
@@ -451,29 +478,52 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {
)}
<div className="flex flex-wrap gap-2">
- <button
- onClick={() => navigate(`/agents/${agentId}/tools`)}
- className="px-3 py-1.5 text-sm bg-port-accent text-white rounded hover:bg-port-accent/80 flex items-center gap-1.5"
- >
- <Zap size={14} />
- Generate Post
- </button>
- <button
- onClick={handleEngage}
- disabled={engaging || !quickAccountId}
- className="px-3 py-1.5 text-sm bg-port-success text-white rounded hover:bg-port-success/80 disabled:opacity-50 flex items-center gap-1.5"
- >
- <MessageSquare size={14} />
- {engaging ? 'Engaging...' : 'Engage Now'}
- </button>
- <button
- onClick={handleCheckPosts}
- disabled={checking || !quickAccountId}
- className="px-3 py-1.5 text-sm bg-purple-600 text-white rounded hover:bg-purple-500 disabled:opacity-50 flex items-center gap-1.5"
- >
- <Eye size={14} />
- {checking ? 'Checking...' : 'Check Posts'}
- </button>
+ {quickPlatform === 'moltworld' ? (
+ <>
+ <button
+ onClick={handleExplore}
+ disabled={exploring || !quickAccountId}
+ className="px-3 py-1.5 text-sm bg-port-success text-white rounded hover:bg-port-success/80 disabled:opacity-50 flex items-center gap-1.5"
+ >
+ <Zap size={14} />
+ {exploring ? 'Exploring...' : 'Explore'}
+ </button>
+ <button
+ onClick={handleBuild}
+ disabled={!quickAccountId}
+ className="px-3 py-1.5 text-sm bg-purple-600 text-white rounded hover:bg-purple-500 disabled:opacity-50 flex items-center gap-1.5"
+ >
+ <MessageSquare size={14} />
+ Build
+ </button>
+ </>
+ ) : (
+ <>
+ <button
+ onClick={() => navigate(`/agents/${agentId}/tools`)}
+ className="px-3 py-1.5 text-sm bg-port-accent text-white rounded hover:bg-port-accent/80 flex items-center gap-1.5"
+ >
+ <Zap size={14} />
+ Generate Post
+ </button>
+ <button
+ onClick={handleEngage}
+ disabled={engaging || !quickAccountId}
+ className="px-3 py-1.5 text-sm bg-port-success text-white rounded hover:bg-port-success/80 disabled:opacity-50 flex items-center gap-1.5"
+ >
+ <MessageSquare size={14} />
+ {engaging ? 'Engaging...' : 'Engage Now'}
+ </button>
+ <button
+ onClick={handleCheckPosts}
+ disabled={checking || !quickAccountId}
+ className="px-3 py-1.5 text-sm bg-purple-600 text-white rounded hover:bg-purple-500 disabled:opacity-50 flex items-center gap-1.5"
+ >
+ <Eye size={14} />
+ {checking ? 'Checking...' : 'Check Posts'}
+ </button>
+ </>
+ )}
</div>
</>
)}
diff --git a/client/src/components/agents/tabs/SchedulesTab.jsx b/client/src/components/agents/tabs/SchedulesTab.jsx
index f91e66270e..4a213f0eb4 100644
--- a/client/src/components/agents/tabs/SchedulesTab.jsx
+++ b/client/src/components/agents/tabs/SchedulesTab.jsx
@@ -89,6 +89,13 @@ export default function SchedulesTab({ agentId }) {
const filteredAccounts = accounts.filter(a => a.status === 'active');
+ // Filter action types by the selected account's platform
+ const selectedAccount = accounts.find(a => a.id === formData.accountId);
+ const selectedPlatform = selectedAccount?.platform;
+ const filteredActionTypes = selectedPlatform
+ ? ACTION_TYPES.filter(a => a.platform === selectedPlatform)
+ : ACTION_TYPES.filter(a => a.platform === 'moltbook');
+
const formatSchedule = (schedule) => {
if (schedule.type === 'cron') {
const preset = CRON_PRESETS.find(p => p.value === schedule.cron);
@@ -145,14 +152,19 @@ export default function SchedulesTab({ agentId }) {
<label className="block text-sm text-gray-400 mb-1">Account</label>
<select
value={formData.accountId}
- onChange={(e) => setFormData({ ...formData, accountId: e.target.value })}
+ onChange={(e) => {
+ const acct = accounts.find(a => a.id === e.target.value);
+ const platform = acct?.platform;
+ const defaultAction = platform === 'moltworld' ? 'mw_heartbeat' : 'heartbeat';
+ setFormData({ ...formData, accountId: e.target.value, action: { type: defaultAction, params: {} } });
+ }}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
required
>
<option value="">Select account...</option>
{filteredAccounts.map(account => (
<option key={account.id} value={account.id}>
- {account.credentials.username}
+ {account.credentials.username} ({account.platform})
</option>
))}
</select>
@@ -164,7 +176,7 @@ export default function SchedulesTab({ agentId }) {
onChange={(e) => setFormData({ ...formData, action: { type: e.target.value, params: {} } })}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
>
- {ACTION_TYPES.map(action => (
+ {filteredActionTypes.map(action => (
<option key={action.value} value={action.value}>
{action.icon} {action.label}
</option>
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 087ec41c15..48082e3fa1 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -375,6 +375,29 @@ export const checkAgentPosts = (agentId, accountId, days, maxReplies, maxUpvotes
body: JSON.stringify({ agentId, accountId, days, maxReplies, maxUpvotes })
});
+// Moltworld Tools
+export const moltworldJoin = (accountId, x, y, thinking, say, sayTo) =>
+ request('/agents/tools/moltworld/join', {
+ method: 'POST',
+ body: JSON.stringify({ accountId, x, y, thinking, say, sayTo })
+ });
+export const moltworldBuild = (accountId, agentId, x, y, z, type, action) =>
+ request('/agents/tools/moltworld/build', {
+ method: 'POST',
+ body: JSON.stringify({ accountId, agentId, x, y, z, type, action })
+ });
+export const moltworldExplore = (accountId, agentId, x, y, thinking) =>
+ request('/agents/tools/moltworld/explore', {
+ method: 'POST',
+ body: JSON.stringify({ accountId, agentId, x, y, thinking })
+ });
+export const moltworldStatus = (accountId) =>
+ request(`/agents/tools/moltworld/status?accountId=${accountId}`);
+export const moltworldBalance = (accountId) =>
+ request(`/agents/tools/moltworld/balance?accountId=${accountId}`);
+export const moltworldRateLimits = (accountId) =>
+ request(`/agents/tools/moltworld/rate-limits?accountId=${accountId}`);
+
// Agent Drafts
export const getAgentDrafts = (agentId) => request(`/agents/tools/drafts?agentId=${agentId}`);
export const createAgentDraft = (data) => request('/agents/tools/drafts', {
diff --git a/server/index.js b/server/index.js
index b3f2ca3f8c..d823395746 100644
--- a/server/index.js
+++ b/server/index.js
@@ -36,6 +36,7 @@ import digitalTwinRoutes from './routes/digital-twin.js';
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 { initSocket } from './services/socket.js';
import { initScriptRunner } from './services/scriptRunner.js';
import { errorMiddleware, setupProcessErrorHandlers, asyncHandler } from './lib/errorHandler.js';
@@ -185,6 +186,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', moltworldToolsRoutes);
app.use('/api/agents/tools', agentToolsRoutes);
// Existing running agents routes (process management)
app.use('/api/agents', agentsRoutes);
diff --git a/server/integrations/moltworld/README.md b/server/integrations/moltworld/README.md
new file mode 100644
index 0000000000..c8a869d659
--- /dev/null
+++ b/server/integrations/moltworld/README.md
@@ -0,0 +1,79 @@
+# Moltworld Integration
+
+This directory contains a self-contained integration for Moltworld, a shared voxel world (480x480 grid) where AI agents move, build structures, think out loud, communicate, and earn SIM tokens.
+
+## Files
+
+- `api.js` - REST API client with all Moltworld actions
+- `rateLimits.js` - Rate limit tracking and enforcement (per-action + global 60 req/min)
+- `index.js` - Main export with MoltworldClient class
+
+## Usage
+
+### In PortOS
+
+```javascript
+import { MoltworldClient, register } from './integrations/moltworld/index.js';
+
+// Register a new agent
+const { agentId, apiKey } = await register('MyAgent', { color: '#3b82f6', emoji: '🤖' });
+
+// Create a client for an existing agent
+const client = new MoltworldClient(apiKey, agentId);
+
+// Join/move in the world (also heartbeat)
+const world = await client.joinWorld({ name: 'MyAgent', x: 5, y: -3 });
+
+// Think out loud
+await client.think('Exploring the voxel world...');
+
+// Build a structure
+await client.build({ x: 5, y: 3, z: 0, type: 'stone', action: 'place' });
+
+// Check balance
+const { balance } = await client.getBalance();
+```
+
+### Key Differences from Moltbook
+
+| Feature | Moltbook | Moltworld |
+|---------|----------|-----------|
+| Auth | Bearer token header | agentId in body/query |
+| Actions | Posts, comments, voting | Movement, building, thinking |
+| Lifecycle | Persistent | Expires after 10 min inactivity |
+| Economy | Karma | SIM tokens (0.1/hour online) |
+| Verification | Math challenges | None |
+
+### Rate Limits
+
+| Action | Cooldown | Daily Limit |
+|--------|----------|-------------|
+| Join/Move | 5 seconds | 17,280/day |
+| Build | 1 second | 500/day |
+| Think | 5 seconds | 1,000/day |
+| **Global** | — | **60 req/min** |
+
+### Block Types
+
+- `wood`, `stone`, `dirt`, `grass`, `leaves`
+
+### Coordinate System
+
+- World: -240 to 240 (X and Y)
+- Building: -500 to 500 (X and Y), 0-100 (Z height)
+
+## Integration with PortOS Scheduler
+
+```javascript
+import { MoltworldClient } from './integrations/moltworld/index.js';
+
+// Heartbeat — call every 5-10s to keep agent visible
+const client = new MoltworldClient(apiKey, agentId);
+await client.joinWorld({ name: 'MyAgent', x: 0, y: 0 });
+
+// Explore — move to coordinates and think
+await client.joinWorld({ name: 'MyAgent', x: 10, y: 20, thinking: 'Nice view from here' });
+
+// Build — place blocks
+await client.build({ x: 10, y: 20, z: 0, type: 'stone' });
+```
diff --git a/server/integrations/moltworld/api.js b/server/integrations/moltworld/api.js
new file mode 100644
index 0000000000..29e3a0b57a
--- /dev/null
+++ b/server/integrations/moltworld/api.js
@@ -0,0 +1,230 @@
+/**
+ * Moltworld API Client
+ *
+ * REST API client for Moltworld - a shared voxel world where AI agents move,
+ * build structures, think out loud, communicate, and earn SIM tokens.
+ *
+ * API Base: https://moltworld.io
+ * Auth: agentId in request body/query (not Bearer token)
+ */
+
+import { checkRateLimit, recordAction, syncFromExternal } from './rateLimits.js';
+
+const API_BASE = 'https://moltworld.io';
+
+/**
+ * Infer the rate-limited action type from a Moltworld API endpoint
+ */
+function inferActionFromEndpoint(endpoint, method) {
+ if (method !== 'POST') return null;
+ if (endpoint === '/api/world/join') return 'join';
+ if (endpoint === '/api/world/build') return 'build';
+ if (endpoint === '/api/world/think') return 'think';
+ return null;
+}
+
+/**
+ * Make an API request to Moltworld
+ */
+async function request(endpoint, options = {}) {
+ const url = `${API_BASE}${endpoint}`;
+ const config = {
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ },
+ ...options
+ };
+
+ console.log(`🌍 Moltworld API: ${options.method || 'GET'} ${endpoint}`);
+
+ const fetchResult = await fetch(url, config).then(r => ({ ok: true, response: r }), e => ({ ok: false, error: e }));
+
+ if (!fetchResult.ok) {
+ console.error(`❌ Moltworld API unreachable: ${fetchResult.error.message}`);
+ const err = new Error('Moltworld is currently unavailable');
+ err.status = 503;
+ err.code = 'PLATFORM_UNAVAILABLE';
+ throw err;
+ }
+
+ const response = fetchResult.response;
+
+ if (!response.ok) {
+ const error = await response.json().catch(() => ({}));
+ const message = error.error || error.message || `HTTP ${response.status}`;
+ if (response.status !== 404) {
+ console.error(`❌ Moltworld API error: ${response.status} ${message}`);
+ } else {
+ console.log(`🌍 Moltworld API: 404 ${endpoint}`);
+ }
+ // Sync local rate limit state when platform enforces a cooldown
+ if (response.status === 429) {
+ const body = options.body ? JSON.parse(options.body) : {};
+ const agentId = body.agentId;
+ const action = inferActionFromEndpoint(endpoint, options.method);
+ if (agentId && action) {
+ syncFromExternal(agentId, action);
+ console.log(`⏱️ Synced ${action} rate limit from 429 response`);
+ }
+ }
+
+ const err = new Error(message);
+ err.status = response.status >= 500 ? 503 : response.status;
+ err.code = response.status >= 500 ? 'PLATFORM_UNAVAILABLE' : undefined;
+ throw err;
+ }
+
+ if (response.status === 204) {
+ return null;
+ }
+
+ return response.json();
+}
+
+// =============================================================================
+// REGISTRATION
+// =============================================================================
+
+/**
+ * Register a new agent on Moltworld
+ * @param {string} name - Display name for the agent
+ * @param {Object} appearance - Appearance config { color, emoji, style }
+ * @returns {{ agentId: string, apiKey: string, position: Object }} Registration result
+ */
+export async function register(name, appearance = {}) {
+ const result = await request('/api/agents/register', {
+ method: 'POST',
+ body: JSON.stringify({
+ name,
+ worldId: 'alpha',
+ appearance: {
+ color: appearance.color || '#3b82f6',
+ emoji: appearance.emoji || '🤖',
+ style: appearance.style || 'robot'
+ }
+ })
+ });
+
+ console.log(`🆕 Moltworld: Registered agent "${name}" (agentId=${result?.agentId})`);
+ return result;
+}
+
+// =============================================================================
+// PROFILE / ACCOUNT
+// =============================================================================
+
+/**
+ * Get the agent's profile
+ * @param {string} agentId - The agent's ID
+ */
+export async function getProfile(agentId) {
+ return request(`/api/agents/profile?agentId=${encodeURIComponent(agentId)}`);
+}
+
+/**
+ * Update the agent's profile
+ * @param {string} agentId - The agent's ID
+ * @param {Object} updates - Profile updates (name, appearance)
+ */
+export async function updateProfile(agentId, updates) {
+ return request('/api/agents/profile', {
+ method: 'PATCH',
+ body: JSON.stringify({ agentId, ...updates })
+ });
+}
+
+/**
+ * Get the agent's SIM token balance
+ * @param {string} agentId - The agent's ID
+ */
+export async function getBalance(agentId) {
+ return request(`/api/agents/balance?agentId=${encodeURIComponent(agentId)}`);
+}
+
+// =============================================================================
+// WORLD ACTIONS
+// =============================================================================
+
+/**
+ * Join/move in the world — also serves as heartbeat to stay visible
+ * Must be called every 5-10 seconds to keep agent alive.
+ * @param {string} agentId - The agent's ID
+ * @param {Object} options - Movement and communication options
+ * @param {string} options.name - Agent display name
+ * @param {number} options.x - X coordinate (-240 to 240)
+ * @param {number} options.y - Y coordinate (-240 to 240)
+ * @param {string} [options.thinking] - Thought bubble text
+ * @param {string} [options.say] - Broadcast message to nearby agents
+ * @param {string} [options.sayTo] - Direct message to specific agent ID
+ */
+export async function joinWorld(agentId, options = {}) {
+ const rateCheck = checkRateLimit(agentId, 'join');
+ if (!rateCheck.allowed) {
+ throw new Error(`Rate limited: ${rateCheck.reason}`);
+ }
+
+ const body = { agentId, ...options };
+ const result = await request('/api/world/join', {
+ method: 'POST',
+ body: JSON.stringify(body)
+ });
+
+ recordAction(agentId, 'join');
+ console.log(`🌍 Moltworld: Agent joined/moved (x=${options.x}, y=${options.y})`);
+ return result;
+}
+
+/**
+ * Think out loud — visible to nearby agents
+ * @param {string} agentId - The agent's ID
+ * @param {string} thought - The thought text
+ */
+export async function think(agentId, thought) {
+ const rateCheck = checkRateLimit(agentId, 'think');
+ if (!rateCheck.allowed) {
+ throw new Error(`Rate limited: ${rateCheck.reason}`);
+ }
+
+ const result = await request('/api/world/think', {
+ method: 'POST',
+ body: JSON.stringify({ agentId, thought })
+ });
+
+ recordAction(agentId, 'think');
+ console.log(`💭 Moltworld: Agent thought: "${thought.substring(0, 50)}..."`);
+ return result;
+}
+
+/**
+ * Build or remove a block in the world
+ * @param {string} agentId - The agent's ID
+ * @param {Object} options - Build options
+ * @param {number} options.x - X coordinate (-500 to 500)
+ * @param {number} options.y - Y coordinate (-500 to 500)
+ * @param {number} options.z - Z height (0 to 100)
+ * @param {string} options.type - Block type: wood, stone, dirt, grass, leaves
+ * @param {string} [options.action='place'] - 'place' or 'remove'
+ */
+export async function build(agentId, options = {}) {
+ const rateCheck = checkRateLimit(agentId, 'build');
+ if (!rateCheck.allowed) {
+ throw new Error(`Rate limited: ${rateCheck.reason}`);
+ }
+
+ const result = await request('/api/world/build', {
+ method: 'POST',
+ body: JSON.stringify({
+ agentId,
+ x: options.x,
+ y: options.y,
+ z: options.z,
+ type: options.type || 'stone',
+ action: options.action || 'place'
+ })
+ });
+
+ recordAction(agentId, 'build');
+ console.log(`🧱 Moltworld: ${options.action || 'place'} ${options.type || 'stone'} at (${options.x},${options.y},${options.z})`);
+ return result;
+}
diff --git a/server/integrations/moltworld/index.js b/server/integrations/moltworld/index.js
new file mode 100644
index 0000000000..b218598df2
--- /dev/null
+++ b/server/integrations/moltworld/index.js
@@ -0,0 +1,56 @@
+/**
+ * Moltworld Integration
+ *
+ * This module provides integration with Moltworld — a shared voxel world
+ * where AI agents move, build structures, think out loud, communicate,
+ * and earn SIM tokens.
+ *
+ * @module integrations/moltworld
+ */
+
+// Re-export all API functions
+export * from './api.js';
+
+// Re-export rate limit utilities
+export {
+ MOLTWORLD_RATE_LIMITS,
+ checkRateLimit,
+ recordAction,
+ getRateLimitStatus,
+ clearRateLimitState
+} from './rateLimits.js';
+
+// Export a convenience client class for stateful usage
+import * as api from './api.js';
+import { getRateLimitStatus } from './rateLimits.js';
+
+/**
+ * Moltworld client for a specific agent account
+ */
+export class MoltworldClient {
+ constructor(apiKey, agentId) {
+ this.apiKey = apiKey;
+ this.agentId = agentId;
+ }
+
+ // World actions
+ joinWorld(options) { return api.joinWorld(this.agentId, options); }
+ think(thought) { return api.think(this.agentId, thought); }
+ build(options) { return api.build(this.agentId, options); }
+
+ // Profile
+ getProfile() { return api.getProfile(this.agentId); }
+ updateProfile(updates) { return api.updateProfile(this.agentId, updates); }
+
+ // Balance
+ getBalance() { return api.getBalance(this.agentId); }
+
+ // Rate limits
+ getRateLimitStatus() { return getRateLimitStatus(this.agentId); }
+}
+
+/**
+ * Register a new agent on Moltworld
+ * This is a static method since it doesn't require an existing agent ID
+ */
+MoltworldClient.register = api.register;
diff --git a/server/integrations/moltworld/rateLimits.js b/server/integrations/moltworld/rateLimits.js
new file mode 100644
index 0000000000..c697c013cf
--- /dev/null
+++ b/server/integrations/moltworld/rateLimits.js
@@ -0,0 +1,196 @@
+/**
+ * Moltworld Rate Limits
+ *
+ * Rate limit configuration for Moltworld API actions.
+ * These limits are enforced by the platform — exceeding them will result in errors.
+ * Global limit: 60 requests/minute per agent.
+ */
+
+export const MOLTWORLD_RATE_LIMITS = {
+ join: {
+ cooldownMs: 5 * 1000, // 5 seconds between joins (heartbeat)
+ maxPerDay: 17280 // Generous — agents call every 5-10s
+ },
+ build: {
+ cooldownMs: 1 * 1000, // 1 second between builds
+ maxPerDay: 500 // Maximum builds per day
+ },
+ think: {
+ cooldownMs: 5 * 1000, // 5 seconds between thoughts
+ maxPerDay: 1000 // Maximum thoughts per day
+ }
+};
+
+// Global rate limit: 60 requests per minute per agent
+const GLOBAL_WINDOW_MS = 60 * 1000;
+const GLOBAL_MAX_REQUESTS = 60;
+
+// In-memory rate limit tracking per agent ID
+const rateLimitState = new Map();
+const globalRateState = new Map();
+
+/**
+ * Get rate limit state for an agent ID
+ */
+function getState(agentId) {
+ if (!rateLimitState.has(agentId)) {
+ rateLimitState.set(agentId, {
+ join: { lastAction: 0, todayCount: 0, dayStart: Date.now() },
+ build: { lastAction: 0, todayCount: 0, dayStart: Date.now() },
+ think: { lastAction: 0, todayCount: 0, dayStart: Date.now() }
+ });
+ }
+
+ const state = rateLimitState.get(agentId);
+ const now = Date.now();
+ const oneDayMs = 24 * 60 * 60 * 1000;
+
+ // Reset daily counters if day has changed
+ for (const action of Object.keys(state)) {
+ if (now - state[action].dayStart > oneDayMs) {
+ state[action].todayCount = 0;
+ state[action].dayStart = now;
+ }
+ }
+
+ return state;
+}
+
+/**
+ * Get global rate limit state for an agent
+ */
+function getGlobalState(agentId) {
+ if (!globalRateState.has(agentId)) {
+ globalRateState.set(agentId, []);
+ }
+ const timestamps = globalRateState.get(agentId);
+ const now = Date.now();
+ // Prune timestamps outside the window
+ const pruned = timestamps.filter(t => now - t < GLOBAL_WINDOW_MS);
+ globalRateState.set(agentId, pruned);
+ return pruned;
+}
+
+/**
+ * Check if an action is rate limited
+ * @param {string} agentId - The agent ID to check
+ * @param {string} action - The action type (join, build, think)
+ * @returns {{ allowed: boolean, waitMs?: number, reason?: string }}
+ */
+export function checkRateLimit(agentId, action) {
+ // Check global rate limit first
+ const globalTimestamps = getGlobalState(agentId);
+ if (globalTimestamps.length >= GLOBAL_MAX_REQUESTS) {
+ const oldestInWindow = globalTimestamps[0];
+ return {
+ allowed: false,
+ reason: `Global rate limit (${GLOBAL_MAX_REQUESTS}/min)`,
+ waitMs: GLOBAL_WINDOW_MS - (Date.now() - oldestInWindow)
+ };
+ }
+
+ const limits = MOLTWORLD_RATE_LIMITS[action];
+ if (!limits) {
+ return { allowed: true };
+ }
+
+ const state = getState(agentId);
+ const actionState = state[action];
+ const now = Date.now();
+
+ // Check daily limit
+ if (actionState.todayCount >= limits.maxPerDay) {
+ return {
+ allowed: false,
+ reason: `Daily limit reached (${limits.maxPerDay}/${action}s per day)`,
+ waitMs: actionState.dayStart + 24 * 60 * 60 * 1000 - now
+ };
+ }
+
+ // Check cooldown
+ const timeSinceLast = now - actionState.lastAction;
+ if (timeSinceLast < limits.cooldownMs) {
+ return {
+ allowed: false,
+ reason: `Cooldown active (${Math.ceil(limits.cooldownMs / 1000)}s between ${action}s)`,
+ waitMs: limits.cooldownMs - timeSinceLast
+ };
+ }
+
+ return { allowed: true };
+}
+
+/**
+ * Record an action for rate limiting
+ * @param {string} agentId - The agent ID
+ * @param {string} action - The action type
+ */
+export function recordAction(agentId, action) {
+ // Record per-action state
+ const state = getState(agentId);
+ if (state[action]) {
+ state[action].lastAction = Date.now();
+ state[action].todayCount++;
+ }
+
+ // Record in global sliding window
+ const globalTimestamps = getGlobalState(agentId);
+ globalTimestamps.push(Date.now());
+}
+
+/**
+ * Get current rate limit status for all actions
+ * @param {string} agentId - The agent ID
+ * @returns {Object} Status for each action type
+ */
+export function getRateLimitStatus(agentId) {
+ const state = getState(agentId);
+ const now = Date.now();
+ const status = {};
+
+ for (const [action, limits] of Object.entries(MOLTWORLD_RATE_LIMITS)) {
+ const actionState = state[action];
+ const timeSinceLast = now - actionState.lastAction;
+ const cooldownRemaining = Math.max(0, limits.cooldownMs - timeSinceLast);
+
+ status[action] = {
+ todayCount: actionState.todayCount,
+ maxPerDay: limits.maxPerDay,
+ remaining: limits.maxPerDay - actionState.todayCount,
+ cooldownMs: limits.cooldownMs,
+ cooldownRemainingMs: cooldownRemaining,
+ canAct: actionState.todayCount < limits.maxPerDay && cooldownRemaining === 0
+ };
+ }
+
+ // Add global rate info
+ const globalTimestamps = getGlobalState(agentId);
+ status._global = {
+ requestsInWindow: globalTimestamps.length,
+ maxPerMinute: GLOBAL_MAX_REQUESTS,
+ remaining: GLOBAL_MAX_REQUESTS - globalTimestamps.length
+ };
+
+ return status;
+}
+
+/**
+ * Sync local rate limit state from a platform 429 response
+ * @param {string} agentId - The agent ID
+ * @param {string} action - The action type
+ */
+export function syncFromExternal(agentId, action) {
+ const state = getState(agentId);
+ if (state[action]) {
+ state[action].lastAction = Date.now();
+ }
+}
+
+/**
+ * Clear rate limit state for an agent ID (e.g., on account deletion)
+ * @param {string} agentId - The agent ID
+ */
+export function clearRateLimitState(agentId) {
+ rateLimitState.delete(agentId);
+ globalRateState.delete(agentId);
+}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index c19b52f637..21742cc830 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -61,11 +61,12 @@ export const agentUpdateSchema = agentSchema.partial();
// PLATFORM ACCOUNT SCHEMAS
// =============================================================================
-export const platformTypeSchema = z.enum(['moltbook']);
+export const platformTypeSchema = z.enum(['moltbook', 'moltworld']);
export const accountCredentialsSchema = z.object({
apiKey: z.string().min(1),
- username: z.string().min(1).max(100)
+ username: z.string().min(1).max(100),
+ agentId: z.string().min(1).optional() // Moltworld-specific agent ID
});
export const accountStatusSchema = z.enum(['active', 'pending', 'suspended', 'error']);
@@ -92,7 +93,10 @@ export const accountRegistrationSchema = z.object({
// AUTOMATION SCHEDULE SCHEMAS
// =============================================================================
-export const scheduleActionTypeSchema = z.enum(['post', 'comment', 'vote', 'heartbeat', 'engage', 'monitor']);
+export const scheduleActionTypeSchema = z.enum([
+ 'post', 'comment', 'vote', 'heartbeat', 'engage', 'monitor',
+ 'explore', 'build', 'say', 'mw_heartbeat', 'interact'
+]);
export const scheduleActionSchema = z.object({
type: scheduleActionTypeSchema,
@@ -289,6 +293,37 @@ export const updateDraftSchema = z.object({
publishedAt: z.string().optional().nullable()
});
+// =============================================================================
+// MOLTWORLD TOOL SCHEMAS
+// =============================================================================
+
+export const moltworldJoinSchema = z.object({
+ accountId: z.string().min(1),
+ x: z.number().int().min(-240).max(240).optional(),
+ y: z.number().int().min(-240).max(240).optional(),
+ thinking: z.string().max(500).optional(),
+ say: z.string().max(500).optional(),
+ sayTo: z.string().optional()
+});
+
+export const moltworldBuildSchema = z.object({
+ accountId: z.string().min(1),
+ agentId: z.string().min(1).optional(),
+ x: z.number().int().min(-500).max(500),
+ y: z.number().int().min(-500).max(500),
+ z: z.number().int().min(0).max(100),
+ type: z.enum(['wood', 'stone', 'dirt', 'grass', 'leaves']).optional().default('stone'),
+ action: z.enum(['place', 'remove']).optional().default('place')
+});
+
+export const moltworldExploreSchema = 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()
+});
+
/**
* Validate data against a schema
* Returns { success: true, data } or { success: false, errors }
diff --git a/server/routes/moltworldTools.js b/server/routes/moltworldTools.js
new file mode 100644
index 0000000000..2e827dcc97
--- /dev/null
+++ b/server/routes/moltworldTools.js
@@ -0,0 +1,183 @@
+/**
+ * Moltworld Tools Routes
+ *
+ * HTTP endpoints for Moltworld voxel world interactions:
+ * joining/moving, building, exploring, and status checks.
+ */
+
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validate, moltworldJoinSchema, moltworldBuildSchema, moltworldExploreSchema } 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';
+
+const router = Router();
+
+/**
+ * Get authenticated MoltworldClient for an account
+ */
+async function getClientAndAgent(accountId, agentId) {
+ const account = await platformAccounts.getAccountWithCredentials(accountId);
+ if (!account) {
+ throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ if (account.status !== 'active') {
+ throw new ServerError(`Account not active: ${account.status}`, { status: 400, code: 'ACCOUNT_INACTIVE' });
+ }
+ if (account.platform !== 'moltworld') {
+ throw new ServerError('Account is not a Moltworld account', { status: 400, code: 'WRONG_PLATFORM' });
+ }
+
+ const agent = agentId ? await agentPersonalities.getAgentById(agentId) : null;
+
+ const client = new MoltworldClient(
+ account.credentials.apiKey,
+ account.credentials.agentId
+ );
+ return { client, agent, account };
+}
+
+// POST /join — Move agent in the world (also heartbeat)
+router.post('/join', asyncHandler(async (req, res) => {
+ const { success, data, errors } = validate(moltworldJoinSchema, req.body);
+ if (!success) {
+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });
+ }
+
+ console.log(`🌍 POST /api/agents/tools/moltworld/join account=${data.accountId}`);
+
+ const { client, account } = await getClientAndAgent(data.accountId, null);
+ const result = await client.joinWorld({
+ name: account.credentials.username,
+ x: data.x ?? 0,
+ y: data.y ?? 0,
+ thinking: data.thinking,
+ say: data.say,
+ sayTo: data.sayTo
+ });
+
+ await platformAccounts.recordActivity(data.accountId);
+ res.json(result);
+}));
+
+// POST /build — Place or remove blocks
+router.post('/build', asyncHandler(async (req, res) => {
+ const { success, data, errors } = validate(moltworldBuildSchema, req.body);
+ if (!success) {
+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });
+ }
+
+ console.log(`🧱 POST /api/agents/tools/moltworld/build account=${data.accountId}`);
+
+ const { client, agent } = await getClientAndAgent(data.accountId, data.agentId);
+ const result = await client.build({
+ x: data.x,
+ y: data.y,
+ z: data.z,
+ type: data.type || 'stone',
+ action: data.action || 'place'
+ });
+
+ await platformAccounts.recordActivity(data.accountId);
+ if (data.agentId) {
+ await agentActivity.logActivity({
+ agentId: data.agentId,
+ accountId: data.accountId,
+ action: 'build',
+ params: { x: data.x, y: data.y, z: data.z, type: data.type, action: data.action },
+ status: 'completed',
+ result: { type: 'build', ...result },
+ timestamp: new Date().toISOString()
+ });
+ }
+
+ res.json(result);
+}));
+
+// POST /explore — Move to coordinates and think
+router.post('/explore', asyncHandler(async (req, res) => {
+ const { success, data, errors } = validate(moltworldExploreSchema, req.body);
+ if (!success) {
+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });
+ }
+
+ console.log(`🌍 POST /api/agents/tools/moltworld/explore agent=${data.agentId}`);
+
+ const { client, agent, account } = await getClientAndAgent(data.accountId, data.agentId);
+
+ // Use provided coordinates or random position
+ const x = data.x ?? Math.floor(Math.random() * 480) - 240;
+ const y = data.y ?? Math.floor(Math.random() * 480) - 240;
+
+ const result = await client.joinWorld({
+ name: account.credentials.username,
+ x,
+ y,
+ thinking: data.thinking || `Exploring area (${x}, ${y})...`
+ });
+
+ await platformAccounts.recordActivity(data.accountId);
+ if (data.agentId) {
+ await agentActivity.logActivity({
+ agentId: data.agentId,
+ accountId: data.accountId,
+ action: 'explore',
+ params: { x, y, thinking: data.thinking },
+ status: 'completed',
+ result: { type: 'explore', x, y, nearby: result?.nearby?.length || 0 },
+ timestamp: new Date().toISOString()
+ });
+ }
+
+ res.json({ x, y, ...result });
+}));
+
+// GET /status — Agent position, balance, nearby agents
+router.get('/status', asyncHandler(async (req, res) => {
+ const { accountId } = req.query;
+ if (!accountId) {
+ throw new ServerError('accountId required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ console.log(`🌍 GET /api/agents/tools/moltworld/status account=${accountId}`);
+
+ const { client } = await getClientAndAgent(accountId);
+ const [profile, balance] = await Promise.all([
+ client.getProfile(),
+ client.getBalance()
+ ]);
+
+ res.json({ profile, balance });
+}));
+
+// GET /balance — SIM token balance
+router.get('/balance', asyncHandler(async (req, res) => {
+ const { accountId } = req.query;
+ if (!accountId) {
+ throw new ServerError('accountId required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ console.log(`💰 GET /api/agents/tools/moltworld/balance account=${accountId}`);
+
+ const { client } = await getClientAndAgent(accountId);
+ const result = await client.getBalance();
+ res.json(result);
+}));
+
+// GET /rate-limits — Rate limit status
+router.get('/rate-limits', asyncHandler(async (req, res) => {
+ const { accountId } = req.query;
+ if (!accountId) {
+ throw new ServerError('accountId required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ console.log(`⏱️ GET /api/agents/tools/moltworld/rate-limits account=${accountId}`);
+
+ const { client } = await getClientAndAgent(accountId);
+ const rateLimits = client.getRateLimitStatus();
+ res.json(rateLimits);
+}));
+
+export default router;
diff --git a/server/routes/platformAccounts.js b/server/routes/platformAccounts.js
index d7a23f61bb..2613990d60 100644
--- a/server/routes/platformAccounts.js
+++ b/server/routes/platformAccounts.js
@@ -11,6 +11,7 @@ import * as platformAccounts from '../services/platformAccounts.js';
import * as agentPersonalities from '../services/agentPersonalities.js';
import { logAction } from '../services/history.js';
import * as moltbook from '../integrations/moltbook/index.js';
+import * as moltworld from '../integrations/moltworld/index.js';
const router = Router();
@@ -118,6 +119,34 @@ router.post('/', asyncHandler(async (req, res) => {
...account,
claimUrl
});
+ } else if (data.platform === 'moltworld') {
+ // Register with Moltworld API — returns { agentId, apiKey }
+ const result = await moltworld.register(data.name, {});
+ const agentId = result.agentId;
+ const apiKey = result.apiKey;
+ const username = data.name;
+
+ const account = await platformAccounts.createAccount({
+ agentId: data.agentId,
+ platform: data.platform,
+ credentials: {
+ apiKey,
+ username,
+ agentId // Moltworld uses agentId for auth
+ },
+ status: 'active', // No claim step for Moltworld
+ platformData: {
+ registrationName: data.name,
+ registrationDescription: data.description
+ }
+ });
+
+ await logAction('register', 'platform-account', account.id, {
+ platform: account.platform,
+ agentId: account.agentId
+ });
+
+ res.status(201).json(account);
} else {
throw new ServerError('Unsupported platform', { status: 400, code: 'UNSUPPORTED_PLATFORM' });
}
@@ -172,6 +201,28 @@ router.post('/:id/test', asyncHandler(async (req, res) => {
await platformAccounts.updateAccountStatus(id, 'pending');
}
+ res.json(testResult);
+ } else if (account.platform === 'moltworld') {
+ // Test with Moltworld API — fetch profile + balance
+ const client = new moltworld.MoltworldClient(
+ account.credentials.apiKey,
+ account.credentials.agentId
+ );
+ const profileResult = await client.getProfile();
+ const agent = profileResult?.agent || profileResult;
+ const balanceResult = await client.getBalance().catch(() => null);
+ const balance = balanceResult?.balance;
+
+ const testResult = {
+ success: !!agent?.id || !!agent?.name,
+ message: agent?.id || agent?.name
+ ? `Connection successful — ${agent.name}${balance ? ` (${balance.sim || 0} SIM)` : ''}`
+ : 'Could not retrieve profile',
+ platform: account.platform,
+ username: account.credentials.username,
+ platformStatus: 'active'
+ };
+
res.json(testResult);
} else {
throw new ServerError('Unsupported platform', { status: 400, code: 'UNSUPPORTED_PLATFORM' });
diff --git a/server/services/agentActionExecutor.js b/server/services/agentActionExecutor.js
index dd3eadf600..2c83fda85c 100644
--- a/server/services/agentActionExecutor.js
+++ b/server/services/agentActionExecutor.js
@@ -11,6 +11,7 @@ import * as agentActivity from './agentActivity.js';
import * as platformAccounts from './platformAccounts.js';
import * as agentPersonalities from './agentPersonalities.js';
import { MoltbookClient, checkRateLimit, isAccountSuspended } from '../integrations/moltbook/index.js';
+import { MoltworldClient } from '../integrations/moltworld/index.js';
import { generatePost, generateComment, generateReply } from './agentContentGenerator.js';
import { findRelevantPosts, findReplyOpportunities } from './agentFeedFilter.js';
@@ -21,6 +22,12 @@ const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
*/
async function executeAction(schedule, account, agent) {
const { action } = schedule;
+
+ // Dispatch to platform-specific handler
+ if (account.platform === 'moltworld') {
+ return executeMoltworldAction(action, account, agent);
+ }
+
const client = new MoltbookClient(account.credentials.apiKey);
switch (action.type) {
@@ -386,6 +393,163 @@ async function executeMonitor(client, agent, schedule, params) {
};
}
+// =============================================================================
+// MOLTWORLD ACTION HANDLERS
+// =============================================================================
+
+/**
+ * Dispatch a Moltworld action
+ */
+async function executeMoltworldAction(action, account, agent) {
+ const client = new MoltworldClient(
+ account.credentials.apiKey,
+ account.credentials.agentId
+ );
+
+ switch (action.type) {
+ case 'mw_heartbeat':
+ return executeMoltworldHeartbeat(client, account, action.params);
+
+ case 'explore':
+ return executeMoltworldExplore(client, account, action.params);
+
+ case 'build':
+ return executeMoltworldBuild(client, action.params);
+
+ case 'say':
+ return executeMoltworldSay(client, action.params);
+
+ case 'interact':
+ return executeMoltworldInteract(client, account, action.params);
+
+ default:
+ throw new Error(`Unknown Moltworld action type: ${action.type}`);
+ }
+}
+
+/**
+ * Moltworld heartbeat — join/move to stay visible
+ */
+async function executeMoltworldHeartbeat(client, account, params) {
+ const x = params.x ?? 0;
+ const y = params.y ?? 0;
+
+ const result = await client.joinWorld({
+ name: account.credentials.username,
+ x,
+ y
+ });
+
+ console.log(`💓 Moltworld: Heartbeat for ${account.credentials.username} at (${x}, ${y})`);
+
+ return {
+ type: 'mw_heartbeat',
+ x,
+ y,
+ nearby: result?.nearby?.length || 0
+ };
+}
+
+/**
+ * Moltworld explore — move to coordinates and think
+ */
+async function executeMoltworldExplore(client, account, params) {
+ const x = params.x ?? Math.floor(Math.random() * 480) - 240;
+ const y = params.y ?? Math.floor(Math.random() * 480) - 240;
+ const thinking = params.thinking || `Exploring area (${x}, ${y})...`;
+
+ const result = await client.joinWorld({
+ name: account.credentials.username,
+ x,
+ y,
+ thinking
+ });
+
+ console.log(`🌍 Moltworld: Explore to (${x}, ${y}) for ${account.credentials.username}`);
+
+ return {
+ type: 'explore',
+ x,
+ y,
+ thinking,
+ nearby: result?.nearby?.length || 0
+ };
+}
+
+/**
+ * Moltworld build — place or remove blocks
+ */
+async function executeMoltworldBuild(client, params) {
+ const result = await client.build({
+ x: params.x || 0,
+ y: params.y || 0,
+ z: params.z || 0,
+ type: params.type || 'stone',
+ action: params.action || 'place'
+ });
+
+ return {
+ type: 'build',
+ ...result
+ };
+}
+
+/**
+ * Moltworld say — broadcast or direct message via join
+ */
+async function executeMoltworldSay(client, params) {
+ const result = await client.joinWorld({
+ name: params.name || 'Agent',
+ x: params.x ?? 0,
+ y: params.y ?? 0,
+ say: params.message,
+ sayTo: params.sayTo
+ });
+
+ console.log(`💬 Moltworld: Said "${(params.message || '').substring(0, 50)}"`);
+
+ return {
+ type: 'say',
+ message: params.message,
+ sayTo: params.sayTo,
+ nearby: result?.nearby?.length || 0
+ };
+}
+
+/**
+ * Moltworld interact — compound action: move, think, optionally build
+ */
+async function executeMoltworldInteract(client, account, params) {
+ const x = params.x ?? Math.floor(Math.random() * 480) - 240;
+ const y = params.y ?? Math.floor(Math.random() * 480) - 240;
+
+ // Move and think
+ const moveResult = await client.joinWorld({
+ name: account.credentials.username,
+ x,
+ y,
+ thinking: params.thinking || `Looking around (${x}, ${y})...`
+ });
+
+ const results = { type: 'interact', x, y, nearby: moveResult?.nearby?.length || 0 };
+
+ // Optionally build
+ if (params.buildType) {
+ await delay(1500);
+ const buildResult = await client.build({
+ x,
+ y,
+ z: params.z || 0,
+ type: params.buildType,
+ action: 'place'
+ });
+ results.built = buildResult;
+ }
+
+ console.log(`🤝 Moltworld: Interact at (${x}, ${y}) for ${account.credentials.username}`);
+ return results;
+}
+
/**
* Initialize the action executor
* Listens to scheduler events and executes actions
diff --git a/server/services/agentContentGenerator.js b/server/services/agentContentGenerator.js
index ec7887faad..744a8b5d59 100644
--- a/server/services/agentContentGenerator.js
+++ b/server/services/agentContentGenerator.js
@@ -37,10 +37,13 @@ export function parseAIJsonResponse(text) {
/**
* Build persona system prompt from agent personality fields
*/
-export function buildAgentSystemPrompt(agent) {
+export function buildAgentSystemPrompt(agent, platform = 'moltbook') {
const p = agent.personality || {};
+ const introText = platform === 'moltworld'
+ ? `You are ${agent.name}, an AI agent in Moltworld — a shared voxel world where AI agents move around a 480x480 grid, build structures, think out loud, and communicate with each other. You earn SIM tokens by staying online. You are openly an AI exploring and building in this virtual world.`
+ : `You are ${agent.name}, an AI agent on Moltbook — a social platform where AI agents (called "molts") interact with each other. All participants are AI bots with their own personalities and perspectives. You are openly an AI and should embrace that identity naturally within your persona.`;
const lines = [
- `You are ${agent.name}, an AI agent on Moltbook — a social platform where AI agents (called "molts") interact with each other. All participants are AI bots with their own personalities and perspectives. You are openly an AI and should embrace that identity naturally within your persona.`,
+ introText,
p.promptPrefix && `Your persona: ${p.promptPrefix}`,
p.style && `Communication style: ${p.style}`,
p.tone && `Tone: ${p.tone}`,