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
fix: stop the Moltworld exploration job logging its credential and fix its queue lookup (#12566)
[._.]/ Adam Eivy5f4957126a2b
diff --git a/server/lib/README.md b/server/lib/README.mdindex fb1dd5e64b..0d939bddf2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -102,6 +102,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `mindBundleCrypto.js` | Persistent Mind portable-bundle container (#7621) — `sealMindBundle` / `openMindBundle` / `readMindBundleHeader`, scrypt-from-passphrase + AES-256-GCM with the cleartext header as AAD. Passphrase-derived, never `PRIVACY_VAULT_KEY`: that key is machine-bound and a bundle sealed with it could not open on the destination install. Format names live in `mindBundleFormat.js`. || `mindBundleFormat.js` | Mind bundle format vocabulary, free of node builtins so the browser reads the same definitions (`client/src/lib/mindBundle.js`) — magic/versions/extension, scrypt parameters, export scopes (`PERSISTENT_MIND_BUNDLE_SCOPES`), import groups and their source scopes (`PERSISTENT_MIND_BUNDLE_GROUPS`, `MIND_BUNDLE_GROUP_SCOPES`, `MIND_BUNDLE_GROUP_CHOICES`), size/passphrase bounds, and the named refusal reasons (`MIND_BUNDLE_REFUSALS`, `mindBundleRefusal`). || `mindLocalContextClamp.js` | RAM/GPU safety ceilings for mind-driven local `numCtx` adjustments (CPU-only tiers, free-RAM + PortOS headroom). Pure. |+| `moltworldExplore.js` | Pure helpers for `server/scripts/moltworld-explore.mjs`: `pickMoltworldAccount`, `buildQueueUrl` (keyed by the PortOS personality id, never the Moltworld credential), `explorerBanner`, `portosAuthHeaders`. || `modelInput.js` | What a model actually received beside what the user wrote (#11317): `promptAddition`, `sentPromptRecord`, `carriedPromptAdditions`, `agentInstructionsAddition`, and the `promptAdditionsSchema` request field. Records `sentPrompt` / `sentNegativePrompt` / `promptAdditions` on every render. || `motionSkills.js` | Optional motion-design agent skill packs (HyperFrames, Remotion, Claude Animation) — `MOTION_SKILL_PACKS` catalog shared by `npm run setup:motion` and the launch-video form, `detectMotionSkills()` finds installed skills under `~/.agents/skills` / `~/.claude/skills`. || `persistentMindPublic.js` | `publicPersistentMindState(state)` — the sole client/socket projection of durable mind state: exposes lifecycle fields, queue count, and the derived next wake time; drops queued message bodies/active wake payloads, and replaces free-form provider errors with coarse safe reasons. Non-user pause reasons pass through (credential-scrubbed) instead of reading "Paused by user", and `lastError` (coarse last-wake failure: killed/OOM, canceled, …) stays separate from `pauseReason`. |diff --git a/server/lib/index.js b/server/lib/index.jsindex e43b188236..a94efec2cf 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -922,3 +922,4 @@ export * from './branchRetirementArchive.js';export * from './reconcileRetirementEvidence.js';export * from './checkoutRetirementAdmission.js';+export * from './moltworldExplore.js';diff --git a/server/lib/moltworldExplore.js b/server/lib/moltworldExplore.jsnew file mode 100644index 0000000000..5fea8de2c8--- /dev/null+++ b/server/lib/moltworldExplore.js@@ -0,0 +1,22 @@+// Pure helpers for server/scripts/moltworld-explore.mjs, kept importable so a test+// can pin that the Moltworld credential never reaches stdout or a PortOS URL.++/** Pick the active Moltworld account. `personalityId` is the PortOS agent the UI queues under. */+export function pickMoltworldAccount(accounts) {+ const account = Object.values(accounts || {}).find(a => a.platform === 'moltworld' && a.status === 'active');+ if (!account) return null;+ return {+ agentId: account.credentials.agentId || account.credentials.apiKey,+ personalityId: account.agentId,+ name: account.credentials.username || account.platformData?.registrationName || 'Explorer',+ };+}++export const buildQueueUrl = (base, personalityId) =>+ `${base}/api/agents/tools/moltworld/queue/${encodeURIComponent(personalityId)}`;++export const explorerBanner = (name) => `🌍 Moltworld Explorer — ${name}`;++/** Bearer header for PortOS API calls; empty when no instance password is set. */+export const portosAuthHeaders = (env = process.env) =>+ env.PORTOS_API_TOKEN ? { Authorization: `Bearer ${env.PORTOS_API_TOKEN}` } : {};diff --git a/server/lib/moltworldExplore.test.js b/server/lib/moltworldExplore.test.jsnew file mode 100644index 0000000000..3bc13caed6--- /dev/null+++ b/server/lib/moltworldExplore.test.js@@ -0,0 +1,23 @@+import { describe, it, expect } from 'vitest';+import { pickMoltworldAccount, buildQueueUrl, explorerBanner, portosAuthHeaders } from './moltworldExplore.js';++const SECRET = 'mw-secret-credential-123';+const accounts = {+ a1: { platform: 'moltworld', status: 'active', agentId: 'personality-1', credentials: { agentId: SECRET, username: 'Alice' } },+};++describe('moltworld explore helpers', () => {+ it('keeps the Moltworld credential out of the queue URL and banner, keyed by personality id', () => {+ const acct = pickMoltworldAccount(accounts);+ const url = buildQueueUrl('http://localhost:5555', acct.personalityId);+ expect(url).toBe('http://localhost:5555/api/agents/tools/moltworld/queue/personality-1');+ expect(url).not.toContain(SECRET);+ expect(explorerBanner(acct.name)).not.toContain(SECRET);+ expect(acct.agentId).toBe(SECRET);+ });++ it('sends the bearer only when PORTOS_API_TOKEN is set', () => {+ expect(portosAuthHeaders({ PORTOS_API_TOKEN: 't' })).toEqual({ Authorization: 'Bearer t' });+ expect(portosAuthHeaders({})).toEqual({});+ });+});diff --git a/server/routes/moltworldTools.js b/server/routes/moltworldTools.jsindex f939e556c9..b446b06878 100644--- a/server/routes/moltworldTools.js+++ b/server/routes/moltworldTools.js@@ -234,15 +234,15 @@ router.get('/rate-limits', asyncHandler(async (req, res) => {// GET /queue/:agentId — Get queue for an agentrouter.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);+ console.log(`📋 GET moltworld queue (${queue.length} item(s))`);res.json(queue);}));// POST /queue — Add action to queuerouter.post('/queue', asyncHandler(async (req, res) => {const data = validateRequest(moltworldQueueAddSchema, req.body);- console.log(`📋 POST /api/agents/tools/moltworld/queue agentId=${data.agentId} action=${data.actionType}`);+ console.log(`📋 POST /api/agents/tools/moltworld/queue action=${data.actionType}`);const item = moltworldQueue.addAction(data.agentId, data.actionType, data.params, data.scheduledFor);res.json(item);}));diff --git a/server/scripts/moltworld-explore.mjs b/server/scripts/moltworld-explore.mjsindex cc5adf4c50..525596fa6e 100755--- a/server/scripts/moltworld-explore.mjs+++ b/server/scripts/moltworld-explore.mjs@@ -35,6 +35,7 @@import { readFile } from 'fs/promises';import { resolve, dirname } from 'path';import { fileURLToPath } from 'url';+import { pickMoltworldAccount, buildQueueUrl, explorerBanner, portosAuthHeaders } from '../lib/moltworldExplore.js';const __dirname = dirname(fileURLToPath(import.meta.url));const PROJECT_ROOT = resolve(__dirname, '..', '..');@@ -55,6 +56,7 @@ const MAX_INTERVAL_S = parseInt(process.env.MOLTWORLD_MAX_INTERVAL, 10) || 540;// PortOS WebSocket relay configconst USE_WS = process.env.MOLTWORLD_USE_WS === 'true';const PORTOS_API_BASE = process.env.PORTOS_API_BASE || 'http://localhost:5555';+const PORTOS_AUTH = portosAuthHeaders();// LM Studio config// Keep the historical LMSTUDIO_* spellings as compatibility fallbacks while@@ -221,6 +223,7 @@ async function checkPortosWs() {const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), 3000);const result = await fetch(`${PORTOS_API_BASE}/api/agents/tools/moltworld/ws/status`, {+ headers: PORTOS_AUTH,signal: controller.signal}).then(r => r.ok ? r.json() : null).catch(() => null).finally(() => clearTimeout(timeout));return result?.status === 'connected';@@ -234,7 +237,7 @@ async function sendWsMove(x, y, thinking) {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' },+ headers: { 'Content-Type': 'application/json', ...PORTOS_AUTH },body: JSON.stringify(body)}).catch(() => null);return res?.ok || false;@@ -248,16 +251,9 @@ async function sendWsMove(x, y, thinking) {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');+ const found = pickMoltworldAccount(JSON.parse(raw).accounts);+ if (!found) throw new Error('No active moltworld account found in data/agents/accounts.json');+ return found;}/**@@ -290,12 +286,12 @@ async function apiRequest(endpoint, body) {/*** Check the PortOS queue for manually-scheduled actions and execute them*/-async function executeQueuedActions(agentId, name, currentX, currentY) {+async function executeQueuedActions(agentId, personalityId, 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 queueUrl = buildQueueUrl(PORTOS_API_BASE, personalityId);- const items = await fetch(queueUrl, { signal: controller.signal })+ const items = await fetch(queueUrl, { headers: PORTOS_AUTH, signal: controller.signal }).then(r => r.ok ? r.json() : []).catch(() => []).finally(() => clearTimeout(timeout));@@ -339,12 +335,12 @@ async function executeQueuedActions(agentId, name, currentX, currentY) {// Mark completed or failed via PortOS queue APIif (success) {- await fetch(`${PORTOS_API_BASE}/api/agents/tools/moltworld/queue/${item.id}/complete`, { method: 'POST' }).catch(() => {});+ await fetch(`${PORTOS_API_BASE}/api/agents/tools/moltworld/queue/${item.id}/complete`, { method: 'POST', headers: PORTOS_AUTH }).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' },+ headers: { 'Content-Type': 'application/json', ...PORTOS_AUTH },body: JSON.stringify({ error: 'Execution failed' })}).catch(() => {});console.log(` 📋 Queued ${item.actionType} failed`);@@ -358,13 +354,13 @@ async function executeQueuedActions(agentId, name, currentX, currentY) {// ─── Main loop ──────────────────────────────────────────────────────────────async function explore() {- const { agentId, name } = await loadCredentials();+ const { agentId, personalityId, name } = await loadCredentials();// Check LM Studio availabilitylmStudioAvailable = await checkLMStudio();// Check PortOS WS relay availabilityportosWsAvailable = await checkPortosWs();- console.log(`🌍 Moltworld Explorer — ${name} (${agentId})`);+ console.log(explorerBanner(name));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`);@@ -392,7 +388,7 @@ async function explore() {while (running && Date.now() < endTime) {// Check for manually-queued actions before auto-generated actions- await executeQueuedActions(agentId, name, x, y);+ await executeQueuedActions(agentId, personalityId, name, x, y);joinCount++;const now = Date.now();diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.jsindex e721dfc759..bce07c3632 100644--- a/server/services/autonomousJobs/scriptHandlers.js+++ b/server/services/autonomousJobs/scriptHandlers.js@@ -17,6 +17,7 @@ import { cleanupOrphanedWorktrees, reapMergedWorktrees } from '../worktreeManageimport { getActiveAgentIds } from '../agentState.js'import { sweepStaleDoneSentinels } from '../agentSentinelSweep.js'import { runSelfDiagnostics } from './selfDiagnostics.js'+import { resolveAgentApiEnv } from '../agentApiAuth.js'import { runBrainParitySweep } from './brainParitySweep.js'// Loaded lazily to keep the built-in handler registry free of an import cycle:@@ -31,14 +32,16 @@ async function eidoverseProjection(options = {}) {* Run the moltworld-explore.mjs script as a child process (no AI agent needed).* Returns a summary object when the script exits.*/-function runMoltworldExploration() {+async function runMoltworldExploration() {const scriptPath = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'scripts', 'moltworld-explore.mjs')const durationMinutes = process.env.MOLTWORLD_DURATION_MINUTES || '30'+ const apiEnv = await resolveAgentApiEnv();+return new Promise((resolve, reject) => {const child = spawn('node', [scriptPath, durationMinutes], {stdio: ['ignore', 'pipe', 'pipe'],- env: { ...process.env },+ env: { ...process.env, ...apiEnv },})const output = []