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

fix(cos): autopause Persistent Mind on hard provider usage limits

atomanticagentf3e4b4e90c90
diff --git a/server/lib/persistentMindUsageLimit.js b/server/lib/persistentMindUsageLimit.js
new file mode 100644
index 0000000000..b9946190a3
--- /dev/null
+++ b/server/lib/persistentMindUsageLimit.js
@@ -0,0 +1,102 @@
+/**
+ * Hard provider usage-limit detection for Persistent Mind wakes.
+ *
+ * Persistent Mind pins one provider/model with no automatic fallback pool
+ * (see persistentMindAdapter / persistentMindProfile). When that provider
+ * returns a hard quota / usage-limit / billing exhaustion, retrying only
+ * burns wakes and climbs failureCount. Soft rate-limits and network blips
+ * must keep the existing interrupted + backoff path.
+ *
+ * If a future adapter ever exposes alternate usage options, call sites should
+ * attempt those first and only autopause when none remain.
+ */
+
+import { analyzeError, ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';
+
+/** Clear pauseReason so the Mind UI / Helm watch stay quiet and actionable. */
+export const PROVIDER_USAGE_LIMIT_PAUSE_REASON =
+ 'Provider usage limit — paused to avoid retries';
+
+const HARD_USAGE_LIMIT_CATEGORIES = new Set([
+ ERROR_CATEGORIES.USAGE_LIMIT,
+ ERROR_CATEGORIES.QUOTA_EXCEEDED,
+]);
+
+/**
+ * Short CLI / SDK quota idioms the shared analyzer can miss on terse errors
+ * (OpenAI `insufficient_quota`, bare "quota exhausted", Cursor Pro upsell).
+ * Kept tighter than a generic "quota" sweep so ordinary prose and rate-limit
+ * copy do not autopause.
+ */
+const HARD_USAGE_LIMIT_EXTRA = new RegExp([
+ 'exceeded your current quota',
+ 'insufficient[_ ]quota',
+ 'quota[_ ]exhausted',
+ 'out of quota',
+ 'usage[_ ]quota[_ ]exceeded',
+ 'Get Cursor Pro',
+ 'quota exceeded',
+].join('|'), 'i');
+
+function attachedCategory(errorOrMessage) {
+ if (!errorOrMessage || typeof errorOrMessage !== 'object') return null;
+ const value = errorOrMessage.category || errorOrMessage.errorCategory || null;
+ return typeof value === 'string' && value ? value : null;
+}
+
+function errorText(errorOrMessage) {
+ if (typeof errorOrMessage === 'string') return errorOrMessage;
+ return String(errorOrMessage?.message || errorOrMessage || '');
+}
+
+/**
+ * Classify a provider error for Persistent Mind wake policy.
+ *
+ * @param {unknown} errorOrMessage — Error, rejection value, or message string
+ * @returns {{ hardUsageLimit: boolean, category: string|null, analysis: object|null }}
+ */
+export function classifyPersistentMindProviderError(errorOrMessage) {
+ if (errorOrMessage == null || errorOrMessage === '') {
+ return { hardUsageLimit: false, category: null, analysis: null };
+ }
+
+ const attached = attachedCategory(errorOrMessage);
+ if (attached && HARD_USAGE_LIMIT_CATEGORIES.has(attached)) {
+ return { hardUsageLimit: true, category: attached, analysis: null };
+ }
+ // Trust an attached soft category (rate-limit / network / timeout) so a
+ // transient 429 never autopauses even if the message also mentions "limit".
+ if (attached === ERROR_CATEGORIES.RATE_LIMIT
+ || attached === ERROR_CATEGORIES.NETWORK_ERROR
+ || attached === ERROR_CATEGORIES.TIMEOUT) {
+ return { hardUsageLimit: false, category: attached, analysis: null };
+ }
+
+ const text = errorText(errorOrMessage);
+ if (!text.trim()) {
+ return { hardUsageLimit: false, category: attached, analysis: null };
+ }
+
+ const analysis = analyzeError(text);
+ if (analysis.hasError && HARD_USAGE_LIMIT_CATEGORIES.has(analysis.category)) {
+ return { hardUsageLimit: true, category: analysis.category, analysis };
+ }
+
+ if (HARD_USAGE_LIMIT_EXTRA.test(text)) {
+ return {
+ hardUsageLimit: true,
+ category: ERROR_CATEGORIES.USAGE_LIMIT,
+ analysis: analysis.hasError ? analysis : null,
+ };
+ }
+
+ return {
+ hardUsageLimit: false,
+ category: analysis.hasError ? analysis.category : attached,
+ analysis: analysis.hasError ? analysis : null,
+ };
+}
+
+export function isHardProviderUsageLimitError(errorOrMessage) {
+ return classifyPersistentMindProviderError(errorOrMessage).hardUsageLimit === true;
+}
diff --git a/server/lib/persistentMindUsageLimit.test.js b/server/lib/persistentMindUsageLimit.test.js
new file mode 100644
index 0000000000..3324b5069e
--- /dev/null
+++ b/server/lib/persistentMindUsageLimit.test.js
@@ -0,0 +1,97 @@
+import { describe, expect, it } from 'vitest';
+import { ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';
+import {
+ PROVIDER_USAGE_LIMIT_PAUSE_REASON,
+ classifyPersistentMindProviderError,
+ isHardProviderUsageLimitError,
+} from './persistentMindUsageLimit.js';
+
+describe('persistentMindUsageLimit', () => {
+ it('exposes a clear pause reason for the Mind UI / Helm watch', () => {
+ expect(PROVIDER_USAGE_LIMIT_PAUSE_REASON).toBe(
+ 'Provider usage limit — paused to avoid retries',
+ );
+ });
+
+ it('classifies Cursor / Claude / OpenAI hard usage-limit banners as hard', () => {
+ const samples = [
+ "You've hit your usage limit Get Cursor Pro to keep going.",
+ "You've hit your usage limit. Upgrade to Pro to keep going.",
+ 'You have hit your usage limit for this account.',
+ "You've hit your monthly spend limit · your session limit resets 7:15am (UTC)",
+ 'Now using extra usage',
+ 'API Error: quota exceeded — plan limit reached',
+ 'Please upgrade your subscription to increase your limits. Resets in 3h51m14s.',
+ ];
+ for (const sample of samples) {
+ expect(isHardProviderUsageLimitError(sample), sample).toBe(true);
+ expect(classifyPersistentMindProviderError(sample).hardUsageLimit, sample).toBe(true);
+ expect(classifyPersistentMindProviderError(sample).category, sample).toBe(
+ ERROR_CATEGORIES.USAGE_LIMIT,
+ );
+ }
+ });
+
+ it('classifies billing / credit exhaustion as hard quota', () => {
+ const err = new Error('Insufficient funds: add credits to continue billing');
+ expect(isHardProviderUsageLimitError(err)).toBe(true);
+ expect(classifyPersistentMindProviderError(err).category).toBe(
+ ERROR_CATEGORIES.QUOTA_EXCEEDED,
+ );
+ });
+
+ it('honors an attached usage-limit category even without distinctive prose', () => {
+ const err = Object.assign(new Error('provider refused the request'), {
+ category: ERROR_CATEGORIES.USAGE_LIMIT,
+ });
+ expect(isHardProviderUsageLimitError(err)).toBe(true);
+ expect(classifyPersistentMindProviderError(err)).toMatchObject({
+ hardUsageLimit: true,
+ category: ERROR_CATEGORIES.USAGE_LIMIT,
+ });
+ });
+
+ it('does not treat transient rate limits as hard usage limits', () => {
+ const samples = [
+ 'API Error: 429 Too Many Requests',
+ 'rate limit exceeded — retry shortly',
+ 'too many requests, please slow down',
+ Object.assign(new Error('throttled'), { category: ERROR_CATEGORIES.RATE_LIMIT }),
+ ];
+ for (const sample of samples) {
+ expect(isHardProviderUsageLimitError(sample), String(sample?.message || sample)).toBe(false);
+ expect(
+ classifyPersistentMindProviderError(sample).hardUsageLimit,
+ String(sample?.message || sample),
+ ).toBe(false);
+ }
+ });
+
+ it('does not treat network / timeout blips as hard usage limits', () => {
+ const samples = [
+ 'fetch failed: ECONNRESET',
+ 'ETIMEDOUT connecting to provider',
+ 'socket hang up',
+ 'network error while contacting the model host',
+ Object.assign(new Error('temporary outage'), { category: ERROR_CATEGORIES.NETWORK_ERROR }),
+ Object.assign(new Error('timed out'), { category: ERROR_CATEGORIES.TIMEOUT }),
+ ];
+ for (const sample of samples) {
+ expect(isHardProviderUsageLimitError(sample), String(sample?.message || sample)).toBe(false);
+ }
+ });
+
+ it('does not treat ordinary provider failures as hard usage limits', () => {
+ expect(isHardProviderUsageLimitError('provider stream ended without a response')).toBe(false);
+ expect(isHardProviderUsageLimitError(new Error('Persistent mind turn interrupted'))).toBe(false);
+ expect(isHardProviderUsageLimitError(null)).toBe(false);
+ expect(isHardProviderUsageLimitError('')).toBe(false);
+ });
+
+ it('does not classify prose that merely mentions billing language without an error idiom', () => {
+ // The shared analyzer matches billing/credit keywords broadly; when those
+ // appear it is still a hard quota signal. Ensure a non-matching ordinary
+ // message stays soft.
+ expect(isHardProviderUsageLimitError('The draft failed markdown validation')).toBe(false);
+ });
+});
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index 10f30a8d55..c86b72596f 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -70,6 +70,10 @@ import {
imageCapabilityAllowsAttempt,
resolvePersistentMindImageCapability,
} from './persistentMindImageCapability.js';
+import {
+ PROVIDER_USAGE_LIMIT_PAUSE_REASON,
+ isHardProviderUsageLimitError,
+} from '../lib/persistentMindUsageLimit.js';
export const PERSISTENT_MIND_WAKE_EVENT_ID = 'cos-persistent-mind-wake';
export const PERSISTENT_MIND_WATCHDOG_EVENT_ID = 'cos-persistent-mind-watchdog';
@@ -600,6 +604,7 @@ async function interruptActiveTurn(reason, status, { retry = false, expectedTurn
* retired too: changing a preset back later must not resurrect refused work.
*/
async function parkActiveTurn(turnId, reason, status = 'waiting', { retryAt = null, consumedAttempt = false, retireWake = false } = {}) {
+ const paused = status === 'paused';
const result = await mutateMindState((mind) => {
if (mind.activeTurn?.id !== turnId) return { mind, value: false };
// Transport/slot waits may retry; a revoked route or uncertain inference
@@ -608,7 +613,9 @@ async function parkActiveTurn(turnId, reason, status = 'waiting', { retryAt = nu
const next = held
? holdPersistentMindWake(mind, mind.activeTurn.wake)
: requeuePersistentMindWake(mind, mind.activeTurn.wake);
- const failureCount = next.failureCount + 1;
+ // A hard usage-limit autopause mirrors pausePersistentMind: no backoff gate
+ // and no failureCount climb, so resume stays an explicit human decision.
+ const failureCount = paused ? next.failureCount : next.failureCount + 1;
return {
mind: {
...next,
@@ -617,17 +624,20 @@ async function parkActiveTurn(turnId, reason, status = 'waiting', { retryAt = nu
pauseReason: reason,
failureCount,
lastError: reason,
- nextEligibleWakeAt: retryAt || new Date(Date.now() + persistentMindBackoffMs(failureCount)).toISOString(),
+ nextEligibleWakeAt: paused
+ ? null
+ : (retryAt || new Date(Date.now() + persistentMindBackoffMs(failureCount)).toISOString()),
},
value: held,
};
});
+ if (paused) cancel(PERSISTENT_MIND_WAKE_EVENT_ID);
await appendMindEvent({
- kind: 'mind.failed',
+ kind: paused ? 'mind.paused' : 'mind.failed',
mindId: result.state.mindId,
turnId,
- eventId: `mind-failed:${turnId}:${status}`,
- data: { status, error: reason, retryAt, consumedAttempt: consumedAttempt && result.value === true, requiresResubmission: result.value === true },
+ eventId: `mind-${paused ? 'paused' : 'failed'}:${turnId}:${status}`,
+ data: { status, error: reason, retryAt: paused ? null : retryAt, consumedAttempt: consumedAttempt && result.value === true, requiresResubmission: result.value === true },
});
emitMindStatus(result.state);
return result.state;
@@ -1137,14 +1147,31 @@ async function runOnePersistentMindTurn() {
const message = controller.signal.aborted
? String(controller.signal.reason || 'Persistent mind turn interrupted')
: 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.
+ 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
// the pre-turn resolution does.
- await parkActiveTurn(turn.id, message, (denied && error.deniedStatus) || 'interrupted', {
- consumedAttempt: runStartedAt != null,
- retireWake: denied && error.requiresResubmission === true,
- });
- emitLog('warn', `Persistent mind turn ${denied ? 'refused a further provider call' : 'interrupted'}: ${message}`, { turnId: turn.id });
+ await parkActiveTurn(
+ turn.id,
+ usageLimit ? PROVIDER_USAGE_LIMIT_PAUSE_REASON : message,
+ usageLimit ? 'paused' : ((denied && error.deniedStatus) || 'interrupted'),
+ {
+ consumedAttempt: runStartedAt != null,
+ retireWake: denied && error.requiresResubmission === true,
+ },
+ );
+ emitLog(
+ 'warn',
+ usageLimit
+ ? `Persistent mind autopaused on provider usage limit: ${message}`
+ : `Persistent mind turn ${denied ? 'refused a further provider call' : 'interrupted'}: ${message}`,
+ { turnId: turn.id },
+ );
}
} finally {
release();
diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.js
index 14470091de..6807185ebf 100644
--- a/server/services/persistentMindSupervisor.test.js
+++ b/server/services/persistentMindSupervisor.test.js
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createDefaultPersistentMindState, normalizePersistentMindState, PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';
+import { PROVIDER_USAGE_LIMIT_PAUSE_REASON } from '../lib/persistentMindUsageLimit.js';
import {
__resetCosAdmissionReservations,
acquireCosActionReservation,
@@ -1264,4 +1265,90 @@ describe('persistent mind supervisor', () => {
expect(mock.root.persistentMind.recentMessageIds).toContain('message-revoked');
});
});
+
+ describe('provider usage-limit autopause', () => {
+ const echoProfileAdapter = () => vi.fn(async ({ profile }) => ({ ok: true, provider: profile.provider }));
+
+ it('autopauses on a hard Cursor usage-limit error instead of climbing failureCount', async () => {
+ const priorFailures = 2;
+ mock.root.persistentMind = {
+ ...createDefaultPersistentMindState(),
+ failureCount: priorFailures,
+ };
+ 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-quota', text: 'Think.' });
+ await supervisor.drainPersistentMind();
+
+ expect(run).toHaveBeenCalledTimes(1);
+ expect(mock.root.persistentMind).toMatchObject({
+ status: 'paused',
+ pauseReason: PROVIDER_USAGE_LIMIT_PAUSE_REASON,
+ lastError: PROVIDER_USAGE_LIMIT_PAUSE_REASON,
+ failureCount: priorFailures,
+ nextEligibleWakeAt: null,
+ activeTurn: null,
+ });
+ // Queued work is requeued, not burned; wakes stay cancelled until resume.
+ 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.appendMindEvent.mock.calls.map(([event]) => event.kind)).toEqual(
+ expect.arrayContaining(['mind.paused']),
+ );
+ expect(mock.appendMindEvent.mock.calls.map(([event]) => event.kind)).not.toEqual(
+ expect.arrayContaining(['mind.failed']),
+ );
+
+ // A further drain must not claim another turn while paused.
+ await supervisor.drainPersistentMind();
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the interrupted + backoff path for transient rate limits', async () => {
+ const run = vi.fn(async () => {
+ throw Object.assign(new Error('API Error: 429 Too Many Requests'), {
+ category: 'rate-limit',
+ });
+ });
+ 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-429', text: 'Retry me.' });
+ await supervisor.drainPersistentMind();
+
+ expect(mock.root.persistentMind.status).toBe('interrupted');
+ expect(mock.root.persistentMind.pauseReason).toBe('API Error: 429 Too Many Requests');
+ expect(mock.root.persistentMind.failureCount).toBeGreaterThan(0);
+ expect(mock.root.persistentMind.nextEligibleWakeAt).not.toBeNull();
+ expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-429']);
+ });
+
+ it('keeps the interrupted path for ordinary provider failures', async () => {
+ const run = vi.fn(async ({ callBoundary }) => callBoundary(
+ { purpose: 'turn', round: 0 },
+ async ({ reportRunId }) => {
+ reportRunId('run-0');
+ throw new Error('provider stream ended without a response');
+ },
+ ));
+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ await supervisor.enqueuePersistentMindMessage({ id: 'message-soft', text: 'Try this.' });
+ await supervisor.drainPersistentMind();
+
+ expect(mock.root.persistentMind.status).toBe('interrupted');
+ expect(mock.root.persistentMind.pauseReason).not.toBe(PROVIDER_USAGE_LIMIT_PAUSE_REASON);
+ });
+ });
});