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(cos): auto-resume Persistent Mind when usage limit clears
atomanticagentc5b6d590060e
diff --git a/server/lib/README.md b/server/lib/README.mdindex b7bd5d8aec..a7b68a95f6 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -61,6 +61,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. || `persistentMindThinkingPresets.js` | Also owns bounded self-thinking request schemas, durable request normalization, and fixed switching limits. Saved named temporary thinking presets for the persistent mind (exact provider/model/effort alternates to its one home profile): default-empty durable shape, normalization that drops half-pinned entries, strict API schema, whole-list replace merge, preset lookup, strict accepted-selection schema/normalization, and route equality independent of labels. Storage only — saving or selecting a preset starts no inference. || `persistentMindChosenName.js` | Extract a Persistent Mind chosen display name from protected identity memories (`extractPersistentMindChosenName`, `resolvePersistentMindChosenName`) to suggest an Eidoverse CoS join id (e.g. Helm) instead of the process id `portos-cos`. Suggestion only — mid-session rename is not supported by Eidoverse.+| `persistentMindUsageLimit.js` | Hard provider usage-limit / quota classifier for Persistent Mind wakes (`classifyPersistentMindProviderError`, `isHardProviderUsageLimitError`), the dedicated autopause reason string, and probe-backoff helpers so a usage-limit pause can auto-recover when the pinned provider is usable again without treating user pauses the same way.| `heavyJobClaim.js` | Cross-process, machine-wide accelerator claim: `claimHeavyLocalJob({ kind, id, timeoutMs? })` either acquires an ephemeral `data/` lock or reports its active holder; dead-PID claims are reclaimed, and a spawned child can take over the recorded PID across a server restart. || `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. || `autonomousJobTask.js` | `generatedJobTaskFields` — flattens a `generateTaskFromJob` result into the top-level keys the non-raw `cos.addTask` path maps onto metadata. One allowlist shared by the manual "Run now" endpoint and the quota-burn lane, so a key added to the generator cannot reach one and not the other. Pure. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 13d07e9f2a..a4a8878910 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -299,6 +299,7 @@ export * from './persistentMindPrompt.js';export * from './persistentMindPublic.js';export * from './persistentMindThinkingPresets.js';export * from './persistentMindChosenName.js';+export * from './persistentMindUsageLimit.js';export * from './agentScratchPaths.js';export * from './agentSentinel.js';export * from './bareUrl.js';diff --git a/server/lib/persistentMindUsageLimit.js b/server/lib/persistentMindUsageLimit.jsindex b9946190a3..5b19428c2a 100644--- a/server/lib/persistentMindUsageLimit.js+++ b/server/lib/persistentMindUsageLimit.js@@ -7,6 +7,8 @@* burns wakes and climbs failureCount. Soft rate-limits and network blips* must keep the existing interrupted + backoff path.*+ * After an autopause, the supervisor periodically probes whether the pinned+ * provider is usable again and auto-resumes only for this pause reason.* If a future adapter ever exposes alternate usage options, call sites should* attempt those first and only autopause when none remain.*/@@ -17,6 +19,14 @@ import { analyzeError, ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';export const PROVIDER_USAGE_LIMIT_PAUSE_REASON ='Provider usage limit — paused to avoid retries';+/**+ * Probe cadence after a usage-limit autopause.+ * First check is short so a brief quota window can clear without a human;+ * later probes back off so we do not spam readiness checks.+ */+export const USAGE_LIMIT_PROBE_BASE_MS = 60_000;+export const USAGE_LIMIT_PROBE_MAX_MS = 30 * 60_000;+const HARD_USAGE_LIMIT_CATEGORIES = new Set([ERROR_CATEGORIES.USAGE_LIMIT,ERROR_CATEGORIES.QUOTA_EXCEEDED,@@ -100,3 +110,18 @@ export function classifyPersistentMindProviderError(errorOrMessage) {export function isHardProviderUsageLimitError(errorOrMessage) {return classifyPersistentMindProviderError(errorOrMessage).hardUsageLimit === true;}++/** True only for the dedicated usage-limit autopause string — never other pauses. */+export function isUsageLimitPauseReason(reason) {+ return reason === PROVIDER_USAGE_LIMIT_PAUSE_REASON;+}++/**+ * Delay until the next readiness probe after a usage-limit autopause.+ * @param {number} attempt — zero-based probe attempt count+ */+export function usageLimitProbeDelayMs(attempt = 0) {+ const n = Number.isFinite(attempt) && attempt > 0 ? Math.floor(attempt) : 0;+ const delay = USAGE_LIMIT_PROBE_BASE_MS * (2 ** Math.min(n, 8));+ return Math.min(USAGE_LIMIT_PROBE_MAX_MS, delay);+}diff --git a/server/lib/persistentMindUsageLimit.test.js b/server/lib/persistentMindUsageLimit.test.jsindex 3324b5069e..d41ce28390 100644--- a/server/lib/persistentMindUsageLimit.test.js+++ b/server/lib/persistentMindUsageLimit.test.js@@ -2,8 +2,12 @@ import { describe, expect, it } from 'vitest';import { ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';import {PROVIDER_USAGE_LIMIT_PAUSE_REASON,+ USAGE_LIMIT_PROBE_BASE_MS,+ USAGE_LIMIT_PROBE_MAX_MS,classifyPersistentMindProviderError,isHardProviderUsageLimitError,+ isUsageLimitPauseReason,+ usageLimitProbeDelayMs,} from './persistentMindUsageLimit.js';describe('persistentMindUsageLimit', () => {@@ -94,4 +98,19 @@ describe('persistentMindUsageLimit', () => {// message stays soft.expect(isHardProviderUsageLimitError('The draft failed markdown validation')).toBe(false);});++ it('recognizes only the dedicated usage-limit pause reason for auto-recovery', () => {+ expect(isUsageLimitPauseReason(PROVIDER_USAGE_LIMIT_PAUSE_REASON)).toBe(true);+ expect(isUsageLimitPauseReason('Paused by user')).toBe(false);+ expect(isUsageLimitPauseReason('Pinned provider unavailable')).toBe(false);+ expect(isUsageLimitPauseReason(null)).toBe(false);+ });++ it('backs off usage-limit probe delays without exceeding the cap', () => {+ expect(usageLimitProbeDelayMs(0)).toBe(USAGE_LIMIT_PROBE_BASE_MS);+ expect(usageLimitProbeDelayMs(1)).toBe(USAGE_LIMIT_PROBE_BASE_MS * 2);+ expect(usageLimitProbeDelayMs(2)).toBe(USAGE_LIMIT_PROBE_BASE_MS * 4);+ expect(usageLimitProbeDelayMs(99)).toBe(USAGE_LIMIT_PROBE_MAX_MS);+ expect(usageLimitProbeDelayMs(-1)).toBe(USAGE_LIMIT_PROBE_BASE_MS);+ });});diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsindex c86b72596f..350783dcc9 100644--- a/server/services/persistentMindSupervisor.js+++ b/server/services/persistentMindSupervisor.js@@ -73,10 +73,14 @@ import {import {PROVIDER_USAGE_LIMIT_PAUSE_REASON,isHardProviderUsageLimitError,+ isUsageLimitPauseReason,+ usageLimitProbeDelayMs,} from '../lib/persistentMindUsageLimit.js';+import { isProviderAvailable, markProviderUsageLimit } from './providerStatus.js';export const PERSISTENT_MIND_WAKE_EVENT_ID = 'cos-persistent-mind-wake';export const PERSISTENT_MIND_WATCHDOG_EVENT_ID = 'cos-persistent-mind-watchdog';+export const PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID = 'cos-persistent-mind-usage-limit-probe';export const PERSISTENT_MIND_WATCHDOG_INTERVAL_MS = 30_000;let turnAdapter = null;@@ -84,6 +88,8 @@ let activeRun = null;let activeAbortController = null;let runtimeGeneration = 0;let supervisorStopping = false;+/** Zero-based attempt count for the in-flight usage-limit readiness probe. */+let usageLimitProbeAttempt = 0;const nowIso = () => new Date().toISOString();const errorMessage = (error) => String(error?.message || error || 'Persistent mind turn failed')@@ -514,6 +520,112 @@ async function scheduleNextWake() {});}+function cancelUsageLimitProbe() {+ cancel(PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID);+}++/**+ * Lightweight readiness check for a usage-limit autopause.+ * Uses provider status + pinned profile resolve — never opens a mind turn.+ */+async function probePinnedProviderAfterUsageLimit() {+ const root = await loadState();+ const providerId = root.config?.persistentMindProfile?.providerId;+ if (typeof providerId === 'string' && providerId && !isProviderAvailable(providerId)) {+ return { ok: false, reason: 'pinned-provider-unavailable' };+ }+ const resolved = await resolvePersistentMindProfile(root.config?.persistentMindProfile);+ if (!resolved.ok) {+ return { ok: false, reason: resolved.error || 'pinned-provider-unresolved' };+ }+ return { ok: true, providerId: resolved.provider?.id || providerId || null };+}++function scheduleUsageLimitProbe(attempt = 0) {+ if (supervisorStopping || !isDaemonRunning()) return;+ usageLimitProbeAttempt = Math.max(0, Number.isFinite(attempt) ? Math.floor(attempt) : 0);+ cancelUsageLimitProbe();+ const delayMs = usageLimitProbeDelayMs(usageLimitProbeAttempt);+ schedule({+ id: PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID,+ type: 'once',+ delayMs: Math.max(1, delayMs),+ handler: async () => {+ try {+ await checkPersistentMindUsageLimitRecovery();+ } catch (error) {+ console.error(`❌ Persistent mind usage-limit probe failed: ${error.message}`);+ const mind = await getPersistentMindState().catch(() => null);+ if (mind && mind.status === 'paused' && isUsageLimitPauseReason(mind.pauseReason)) {+ scheduleUsageLimitProbe(usageLimitProbeAttempt + 1);+ }+ }+ },+ metadata: {+ description: 'Persistent CoS mind usage-limit readiness probe',+ attempt: usageLimitProbeAttempt,+ },+ });+}++/**+ * If paused solely for a provider usage limit, probe readiness and auto-resume+ * when the pinned provider is usable again. Other pause reasons are ignored.+ */+export async function checkPersistentMindUsageLimitRecovery() {+ const mind = await getPersistentMindState();+ if (mind.status !== 'paused' || !isUsageLimitPauseReason(mind.pauseReason)) {+ cancelUsageLimitProbe();+ usageLimitProbeAttempt = 0;+ return { recovered: false, ignored: true };+ }+ if (supervisorStopping || !isDaemonRunning() || !mind.enabled || !mind.started) {+ return { recovered: false, ignored: false, reason: 'supervisor-inactive' };+ }++ const probe = await probePinnedProviderAfterUsageLimit();+ if (!probe.ok) {+ scheduleUsageLimitProbe(usageLimitProbeAttempt + 1);+ return { recovered: false, ignored: false, reason: probe.reason || 'still-limited' };+ }++ const result = await mutateMindState((current) => {+ if (current.status !== 'paused' || !isUsageLimitPauseReason(current.pauseReason)) {+ return { mind: current, value: { recovered: false } };+ }+ return {+ mind: {+ ...current,+ status: 'waiting',+ pauseReason: null,+ lastError: null,+ nextEligibleWakeAt: null,+ selfWake: current.queuedMessages.length > 0 || current.selfWake+ ? current.selfWake+ : initialSelfWake('usage-limit-recovered'),+ },+ value: { recovered: true, mindId: current.mindId },+ };+ });++ if (!result.value?.recovered) {+ cancelUsageLimitProbe();+ usageLimitProbeAttempt = 0;+ return { recovered: false, ignored: true };+ }++ cancelUsageLimitProbe();+ usageLimitProbeAttempt = 0;+ armWatchdog();+ await scheduleNextWake();+ // Match resumePersistentMind: status emit + log only (no new trajectory kind).+ emitMindStatus(result.state);+ emitLog('info', 'Persistent mind auto-resumed after provider usage limit cleared', {+ providerId: probe.providerId || null,+ });+ return { recovered: true, ignored: false };+}+function initialSelfWake(reason) {const createdAt = nowIso();return {@@ -614,7 +726,8 @@ async function parkActiveTurn(turnId, reason, status = 'waiting', { retryAt = nu? holdPersistentMindWake(mind, mind.activeTurn.wake): requeuePersistentMindWake(mind, mind.activeTurn.wake);// A hard usage-limit autopause mirrors pausePersistentMind: no backoff gate- // and no failureCount climb, so resume stays an explicit human decision.+ // and no failureCount climb. Auto-recovery probes (not ordinary wakes) clear+ // only this pause reason when the pinned provider is usable again.const failureCount = paused ? next.failureCount : next.failureCount + 1;return {mind: {@@ -1149,9 +1262,9 @@ async function runOnePersistentMindTurn() {: errorMessage(error);// Persistent Mind has no automatic provider fallback pool. A hard// usage-limit / quota exhaustion would otherwise climb failureCount and- // keep burning scheduled wakes; autopause until a human resumes or- // changes the provider. Transient rate-limits / network blips stay on- // the interrupted + backoff path below.+ // keep burning scheduled wakes; autopause, then probe for recovery.+ // Transient rate-limits / network blips stay on the interrupted ++ // backoff path below.const usageLimit = !denied && !controller.signal.aborted && isHardProviderUsageLimitError(error);// A refusal already named its own cause and the status it belongs// under; only a revoked temporary route retires the wake, exactly as@@ -1165,6 +1278,16 @@ async function runOnePersistentMindTurn() {retireWake: denied && error.requiresResubmission === true,},);+ if (usageLimit) {+ const providerId = (await loadState()).config?.persistentMindProfile?.providerId+ || null;+ if (typeof providerId === 'string' && providerId) {+ await markProviderUsageLimit(providerId, { message }).catch((markError) => {+ console.error(`❌ Failed to mark provider usage limit for mind probe: ${markError.message}`);+ });+ }+ scheduleUsageLimitProbe(0);+ }emitLog('warn',usageLimit@@ -1259,6 +1382,8 @@ export async function setPersistentMindEnabled(enabled) {activeAbortController?.abort('Persistent mind disabled');cancel(PERSISTENT_MIND_WAKE_EVENT_ID);cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);+ cancelUsageLimitProbe();+ usageLimitProbeAttempt = 0;}const result = await mutateMindState((mind) => {const changedToDisabled = !enabled && (mind.enabled || Boolean(mind.activeTurn));@@ -1326,6 +1451,9 @@ export async function pausePersistentMind(reason = 'Paused by user') {});}cancel(PERSISTENT_MIND_WAKE_EVENT_ID);+ // Explicit / non-usage pauses must never auto-resume via the usage-limit probe.+ cancelUsageLimitProbe();+ usageLimitProbeAttempt = 0;return { success: true, state };}@@ -1346,6 +1474,8 @@ export async function resumePersistentMind() {};});if (result.value.success) {+ cancelUsageLimitProbe();+ usageLimitProbeAttempt = 0;armWatchdog();await scheduleNextWake();}@@ -1358,6 +1488,8 @@ export async function stopPersistentMind({ waitForTurn = false } = {}) {activeAbortController?.abort('Persistent mind stopped');cancel(PERSISTENT_MIND_WAKE_EVENT_ID);cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);+ cancelUsageLimitProbe();+ usageLimitProbeAttempt = 0;const result = await mutateMindState((mind) => {const wasStarted = mind.started;const interruptedTurnId = mind.activeTurn?.id || null;@@ -1720,6 +1852,9 @@ export async function initializePersistentMindSupervisor() {if (recovered.state.enabled && recovered.state.started) {armWatchdog();await scheduleNextWake();+ if (recovered.state.status === 'paused' && isUsageLimitPauseReason(recovered.state.pauseReason)) {+ scheduleUsageLimitProbe(0);+ }}emitMindStatus(recovered.state);return recovered.state;@@ -1744,6 +1879,8 @@ export async function shutdownPersistentMindSupervisor() {activeAbortController?.abort('Chief of Staff daemon stopped');cancel(PERSISTENT_MIND_WAKE_EVENT_ID);cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);+ cancelUsageLimitProbe();+ usageLimitProbeAttempt = 0;const state = await getPersistentMindState();if (!state.activeTurn) return state;return (await interruptActiveTurn('Chief of Staff daemon stopped', 'interrupted', { retry: true })).state;@@ -1755,6 +1892,8 @@ export function __resetPersistentMindSupervisorForTests() {activeAbortController = null;runtimeGeneration = 0;supervisorStopping = false;+ usageLimitProbeAttempt = 0;cancel(PERSISTENT_MIND_WAKE_EVENT_ID);cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);+ cancel(PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID);}diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex 6807185ebf..6d52d8e46f 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -79,6 +79,10 @@ vi.mock('./providers.js', () => ({ getProviderById: vi.fn(async () => mock.provivi.mock('./providerStatus.js', () => ({isProviderAvailable: () => mock.providerAvailable,getProviderStatus: () => ({ message: 'Endpoint is temporarily unavailable' }),+ markProviderUsageLimit: vi.fn(async () => {+ mock.providerAvailable = false;+ return { available: false, reason: 'usage-limit' };+ }),}));vi.mock('./persistentMindImageCapability.js', () => ({resolvePersistentMindImageCapability: vi.fn(async () => mock.imageCapability),@@ -1296,9 +1300,12 @@ describe('persistent mind supervisor', () => {nextEligibleWakeAt: null,activeTurn: null,});- // Queued work is requeued, not burned; wakes stay cancelled until resume.+ // Queued work is requeued, not burned; ordinary wakes stay cancelled while+ // a usage-limit readiness probe is armed for auto-recovery.expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-quota']);expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID)).toBe(false);+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID)).toBe(true);+ expect(mock.providerAvailable).toBe(false);expect(mock.appendMindEvent.mock.calls.map(([event]) => event.kind)).toEqual(expect.arrayContaining(['mind.paused']),);@@ -1350,5 +1357,95 @@ describe('persistent mind supervisor', () => {expect(mock.root.persistentMind.status).toBe('interrupted');expect(mock.root.persistentMind.pauseReason).not.toBe(PROVIDER_USAGE_LIMIT_PAUSE_REASON);});++ it('stays paused while the usage-limit probe still reports the provider limited', async () => {+ const run = vi.fn(async () => {+ throw new Error("You've hit your usage limit Get Cursor Pro to keep going.");+ });+ await supervisor.registerPersistentMindTurnAdapter({+ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' } })),+ run,+ });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-still-limited', text: 'Think.' });+ await supervisor.drainPersistentMind();++ expect(mock.root.persistentMind.status).toBe('paused');+ expect(mock.providerAvailable).toBe(false);++ const probe = mock.scheduled.get(supervisor.PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID);+ expect(probe).toBeTruthy();+ await probe.handler();++ expect(mock.root.persistentMind).toMatchObject({+ status: 'paused',+ pauseReason: PROVIDER_USAGE_LIMIT_PAUSE_REASON,+ });+ // Still limited → next probe armed with backoff; no ordinary wake.+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID)).toBe(true);+ expect(mock.scheduled.get(supervisor.PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID).metadata.attempt).toBe(1);+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID)).toBe(false);+ expect(run).toHaveBeenCalledTimes(1);+ });++ it('auto-resumes when the usage-limit probe says the pinned provider is usable again', async () => {+ const run = vi.fn(async () => {+ throw new Error("You've hit your usage limit Get Cursor Pro to keep going.");+ });+ await supervisor.registerPersistentMindTurnAdapter({+ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' } })),+ run,+ });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-recover', text: 'Think.' });+ await supervisor.drainPersistentMind();++ expect(mock.root.persistentMind.status).toBe('paused');+ mock.providerAvailable = true;+ mock.profile = {+ ok: true,+ provider: { id: 'example-cloud', type: 'api' },+ model: 'example-model',+ effort: 'high',+ thinkingInterface: 'text',+ };++ const probe = mock.scheduled.get(supervisor.PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID);+ expect(probe).toBeTruthy();+ const result = await supervisor.checkPersistentMindUsageLimitRecovery();+ expect(result).toMatchObject({ recovered: true, ignored: false });++ expect(mock.root.persistentMind).toMatchObject({+ status: 'waiting',+ pauseReason: null,+ lastError: null,+ });+ expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-recover']);+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID)).toBe(false);+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID)).toBe(true);+ });++ it('does not auto-resume pauses that are not usage-limit autopauses', async () => {+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.pausePersistentMind('Paused by user');++ expect(mock.root.persistentMind).toMatchObject({+ status: 'paused',+ pauseReason: 'Paused by user',+ });+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID)).toBe(false);++ mock.providerAvailable = true;+ const result = await supervisor.checkPersistentMindUsageLimitRecovery();+ expect(result).toMatchObject({ recovered: false, ignored: true });+ expect(mock.root.persistentMind).toMatchObject({+ status: 'paused',+ pauseReason: 'Paused by user',+ });+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID)).toBe(false);+ });});});