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(mind): surface actionable pause when local context budget is too small

atomanticagentd296ad0bd128
diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsx
index 12bcd962d2..7196c12935 100644
--- a/client/src/components/cos/tabs/MindTab.jsx
+++ b/client/src/components/cos/tabs/MindTab.jsx
@@ -900,10 +900,29 @@ export default function MindTab() {
</div>
<p className="mt-3 text-sm text-port-text-muted">
{turnProgress.phase === 'stalled' ? 'No heartbeat from the current turn — checking whether it is still alive.'
- : turnProgress.phase === 'blocked' ? `${turnProgress.reason || 'Blocked'}${turnProgress.retryAt ? ' — the mind retries on its own; no action needed.' : '. No retry is scheduled.'}`
+ : turnProgress.phase === 'blocked' ? (state?.contextBudgetBlocked
+ ? `${turnProgress.reason || 'Local context window is too small for this wake'}. Raise provider numCtx under Settings → AI providers (or shrink Context), then Resume.`
+ : `${turnProgress.reason || 'Blocked'}${turnProgress.retryAt ? ' — the mind retries on its own; no action needed.' : '. No retry is scheduled.'}`)
: turnProgress.phase === 'thinking' ? `${turnProgress.stage || 'Working through the current turn'}.`
: state?.pauseReason || (state?.started ? 'Listening for messages and scheduled wakes.' : 'Configure the AI profile to begin.')}
</p>
+ {state?.contextBudgetBlocked && (
+ <div data-testid="mind-context-budget-actions" className="mt-2 flex flex-wrap gap-2 text-xs">
+ <button
+ type="button"
+ onClick={() => openPanel('context')}
+ className="rounded-lg border border-port-border px-2.5 py-1 font-medium text-port-text hover:border-port-accent hover:text-port-accent"
+ >
+ Open Context
+ </button>
+ <a
+ href="/settings?tab=providers"
+ className="rounded-lg border border-port-border px-2.5 py-1 font-medium text-port-text hover:border-port-accent hover:text-port-accent"
+ >
+ AI providers (numCtx)
+ </a>
+ </div>
+ )}
{turnProgress.detail && (
<p data-testid="mind-turn-progress-detail" className={`mt-1 text-xs ${turnProgress.phase === 'stalled' || turnProgress.phase === 'blocked' ? 'text-port-warning' : 'text-port-text-muted'}`}>
{turnProgress.detail}
diff --git a/client/src/lib/mindTurnProgress.js b/client/src/lib/mindTurnProgress.js
index 4aac964d35..c0dc2fbd3c 100644
--- a/client/src/lib/mindTurnProgress.js
+++ b/client/src/lib/mindTurnProgress.js
@@ -105,7 +105,9 @@ export function describeMindTurnProgress({ state, runtime, events } = {}) {
const thinking = state?.status === 'thinking' && Boolean(trimmed(state?.activeTurnId));
// A degraded/interrupted wake is as opaque as a quota pause: both stop making
// progress and both retry on their own, so both get the retry time inline.
- const blocked = state?.usageLimited === true || ['degraded', 'interrupted'].includes(state?.status);
+ const blocked = state?.usageLimited === true
+ || state?.contextBudgetBlocked === true
+ || ['degraded', 'interrupted'].includes(state?.status);
const stalled = thinking && inference?.heartbeatStale === true;
const phase = blocked ? 'blocked' : stalled ? 'stalled' : thinking ? 'thinking' : 'idle';
const busy = phase === 'thinking' || phase === 'stalled';
@@ -134,7 +136,11 @@ export function describeMindTurnProgress({ state, runtime, events } = {}) {
retryAt: phase !== 'blocked' ? null
: state?.usageLimited === true
? trimmed(runtime?.usageLimitRetryAt)
- : trimmed(state?.nextEligibleWakeAt),
+ // Context-budget autopauses clear nextEligibleWakeAt and do not probe;
+ // never invent a retry time that would imply the mind will recover alone.
+ : state?.contextBudgetBlocked === true
+ ? null
+ : trimmed(state?.nextEligibleWakeAt),
reason: phase === 'blocked' ? trimmed(state?.pauseReason) : null,
detail: parts.length > 0 ? parts.join(' · ') : null,
};
diff --git a/client/src/lib/mindTurnProgress.test.js b/client/src/lib/mindTurnProgress.test.js
index eccdf263c4..93383b3532 100644
--- a/client/src/lib/mindTurnProgress.test.js
+++ b/client/src/lib/mindTurnProgress.test.js
@@ -131,6 +131,25 @@ describe('describeMindTurnProgress', () => {
expect(describeMindTurnProgress({ state: { status: 'waiting', started: true } }).phase).toBe('idle');
expect(describeMindTurnProgress({}).phase).toBe('idle');
});
+
+ it('treats a context-budget autopause as blocked with no invented retry time', () => {
+ const state = {
+ status: 'paused',
+ started: true,
+ activeTurnId: null,
+ usageLimited: false,
+ contextBudgetBlocked: true,
+ pauseReason: 'Local context window too small: known 12288-token context is below the 15104-token request budget. Raise provider numCtx (Settings → AI providers) or shrink mind context, then resume.',
+ nextEligibleWakeAt: null,
+ };
+ const progress = describeMindTurnProgress({
+ state,
+ runtime: { usageLimitRetryAt: '2026-09-01T09:00:00.000Z' },
+ });
+ expect(progress.phase).toBe('blocked');
+ expect(progress.retryAt).toBeNull();
+ expect(progress.reason).toMatch(/12288/);
+ });
});
describe('mindTurnStage', () => {
diff --git a/server/lib/README.md b/server/lib/README.md
index c066c60bba..c57e43fae2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -73,6 +73,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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` | Validate and resolve an authoritative chosen-name identity memory, frame first-wake naming, and extract legacy chosen names from protected identity memories (`extractPersistentMindChosenName`, `resolvePersistentMindChosenName`) to drive the Eidoverse CoS join id (e.g. Helm). Presence reconnects on its next world action when the chosen name changes.
| `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.
+| `persistentMindContextBudget.js` | Local context-budget / known-window-below-request-budget classifier for Persistent Mind wakes (`isContextBudgetFitnessError`, `publicContextBudgetReason`), plus actionable pause copy that keeps token counts and a numCtx recovery hint without exposing prompts or secrets.
| `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.js
index 89f7a1e248..a0eda9519b 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -330,6 +330,7 @@ export * from './persistentMindPublic.js';
export * from './persistentMindThinkingPresets.js';
export * from './persistentMindChosenName.js';
export * from './persistentMindUsageLimit.js';
+export * from './persistentMindContextBudget.js';
export * from './agentScratchPaths.js';
export * from './agentSentinel.js';
export * from './bareUrl.js';
diff --git a/server/lib/persistentMindContextBudget.js b/server/lib/persistentMindContextBudget.js
new file mode 100644
index 0000000000..a2af291dc9
--- /dev/null
+++ b/server/lib/persistentMindContextBudget.js
@@ -0,0 +1,110 @@
+/**
+ * Local provider context-budget / fitness failures for Persistent Mind wakes.
+ *
+ * When the pinned local window (numCtx / known context) is below the wake's
+ * request token budget, retrying the same wake only climbs failureCount and
+ * surfaces a vague "Provider unavailable or wake failed" in the public mind
+ * state. That class of failure is not transient: the operator (or a granted
+ * local-context tool) must raise numCtx or shrink the mind context.
+ *
+ * Soft transport failures stay on the interrupted + backoff path. Secrets and
+ * prompt bodies never appear in the public pause copy — only the two token
+ * counts when the providerStatus message already named them.
+ */
+
+/** Prefix shared by every stored/public context-budget pause reason. */
+export const CONTEXT_BUDGET_PAUSE_REASON_PREFIX =
+ 'Local context window too small';
+
+const KNOWN_BELOW_BUDGET_RE =
+ /known\s+(\d+)[-\s]?token\s+context\s+is\s+below\s+the\s+(\d+)[-\s]?token\s+request\s+budget/i;
+
+/** Matches promptRunner's CONTEXT_LENGTH_CATEGORY on refused-before-dispatch errors. */
+const CONTEXT_LENGTH_CATEGORIES = new Set(['context-length', 'context_length', 'context-window']);
+
+function errorText(errorOrMessage) {
+ if (typeof errorOrMessage === 'string') return errorOrMessage;
+ return String(errorOrMessage?.message || errorOrMessage || '');
+}
+
+function attachedCategory(errorOrMessage) {
+ if (!errorOrMessage || typeof errorOrMessage !== 'object') return null;
+ const value = errorOrMessage.errorAnalysis?.category
+ || errorOrMessage.category
+ || errorOrMessage.errorCategory
+ || null;
+ return typeof value === 'string' && value ? value : null;
+}
+
+/**
+ * Parse known/required token counts from a providerStatus / promptRunner message.
+ * @returns {{ known: number, required: number } | null}
+ */
+export function parseContextBudgetTokens(errorOrMessage) {
+ const text = errorText(errorOrMessage);
+ const match = text.match(KNOWN_BELOW_BUDGET_RE);
+ if (!match) return null;
+ const known = Number(match[1]);
+ const required = Number(match[2]);
+ if (!Number.isFinite(known) || !Number.isFinite(required) || known <= 0 || required <= 0) {
+ return null;
+ }
+ return { known, required };
+}
+
+/**
+ * Human-actionable pause copy. Includes both token counts when present and
+ * points at provider numCtx / mind context controls — never prompts or secrets.
+ */
+export function formatContextBudgetPauseReason({ known = null, required = null } = {}) {
+ const counts = Number.isFinite(known) && Number.isFinite(required) && known > 0 && required > 0
+ ? `known ${known}-token context is below the ${required}-token request budget`
+ : 'known context is below the request token budget';
+ return `${CONTEXT_BUDGET_PAUSE_REASON_PREFIX}: ${counts}. Raise provider numCtx (Settings → AI providers) or shrink mind context, then resume.`;
+}
+
+export function contextBudgetPauseReasonFrom(errorOrMessage) {
+ const tokens = parseContextBudgetTokens(errorOrMessage);
+ return formatContextBudgetPauseReason(tokens || {});
+}
+
+/**
+ * True for the non-transient local context-fitness class: known window below
+ * request budget (message and/or attached context-length category).
+ */
+export function isContextBudgetFitnessError(errorOrMessage) {
+ if (errorOrMessage == null || errorOrMessage === '') return false;
+ if (parseContextBudgetTokens(errorOrMessage)) return true;
+ const category = attachedCategory(errorOrMessage);
+ // promptRunner stamps CONTEXT_LENGTH_CATEGORY on refuse-before-dispatch
+ // errors; trust that signal even when the message is terse.
+ if (category && CONTEXT_LENGTH_CATEGORIES.has(category)) return true;
+ return false;
+}
+
+/**
+ * True when durable pauseReason / lastError is (or clearly describes) a
+ * context-budget autopause — including raw providerStatus messages still
+ * stored from before this classifier existed.
+ */
+export function isContextBudgetPauseReason(reason) {
+ if (typeof reason !== 'string' || !reason.trim()) return false;
+ if (reason.startsWith(CONTEXT_BUDGET_PAUSE_REASON_PREFIX)) return true;
+ return parseContextBudgetTokens(reason) != null;
+}
+
+/**
+ * Public-safe pause / lastError text for a context-budget failure.
+ * Re-formats raw provider messages so the UI never depends on a provider
+ * name prefix while still keeping the numbers when present.
+ */
+export function publicContextBudgetReason(reasonOrError) {
+ if (reasonOrError == null || reasonOrError === '') return null;
+ if (typeof reasonOrError === 'string' && reasonOrError.startsWith(CONTEXT_BUDGET_PAUSE_REASON_PREFIX)) {
+ return reasonOrError;
+ }
+ if (!isContextBudgetFitnessError(reasonOrError) && !isContextBudgetPauseReason(reasonOrError)) {
+ return null;
+ }
+ return contextBudgetPauseReasonFrom(reasonOrError);
+}
diff --git a/server/lib/persistentMindContextBudget.test.js b/server/lib/persistentMindContextBudget.test.js
new file mode 100644
index 0000000000..f1b72fbbee
--- /dev/null
+++ b/server/lib/persistentMindContextBudget.test.js
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+import {
+ CONTEXT_BUDGET_PAUSE_REASON_PREFIX,
+ contextBudgetPauseReasonFrom,
+ formatContextBudgetPauseReason,
+ isContextBudgetFitnessError,
+ isContextBudgetPauseReason,
+ parseContextBudgetTokens,
+ publicContextBudgetReason,
+} from './persistentMindContextBudget.js';
+
+describe('persistentMindContextBudget', () => {
+ const sample = 'Ollama (qwen3:8b): known 12288-token context is below the 15104-token request budget';
+
+ it('parses known/required token counts from the providerStatus budget message', () => {
+ expect(parseContextBudgetTokens(sample)).toEqual({ known: 12288, required: 15104 });
+ expect(parseContextBudgetTokens('unrelated failure')).toBeNull();
+ });
+
+ it('classifies the budget message and attached context-length category as fitness errors', () => {
+ expect(isContextBudgetFitnessError(sample)).toBe(true);
+ expect(isContextBudgetFitnessError(new Error(sample))).toBe(true);
+ expect(isContextBudgetFitnessError(Object.assign(new Error('prompt too large'), {
+ errorAnalysis: { category: 'context-length', message: 'prompt too large' },
+ }))).toBe(true);
+ expect(isContextBudgetFitnessError('provider stream ended without a response')).toBe(false);
+ expect(isContextBudgetFitnessError(Object.assign(new Error('rate limited'), {
+ category: 'rate-limit',
+ }))).toBe(false);
+ });
+
+ it('formats an actionable pause reason with numbers and a numCtx recovery hint', () => {
+ const reason = formatContextBudgetPauseReason({ known: 12288, required: 15104 });
+ expect(reason.startsWith(CONTEXT_BUDGET_PAUSE_REASON_PREFIX)).toBe(true);
+ expect(reason).toContain('12288');
+ expect(reason).toContain('15104');
+ expect(reason).toMatch(/numCtx/i);
+ expect(isContextBudgetPauseReason(reason)).toBe(true);
+ expect(isContextBudgetPauseReason(sample)).toBe(true);
+ expect(isContextBudgetPauseReason('Paused from the Mind page')).toBe(false);
+ expect(isContextBudgetPauseReason(null)).toBe(false);
+ });
+
+ it('builds the public reason from raw or already-formatted errors without leaking extras', () => {
+ expect(publicContextBudgetReason(sample)).toBe(contextBudgetPauseReasonFrom(sample));
+ expect(publicContextBudgetReason(contextBudgetPauseReasonFrom(sample))).toBe(
+ contextBudgetPauseReasonFrom(sample),
+ );
+ expect(publicContextBudgetReason('provider stream ended')).toBeNull();
+ expect(publicContextBudgetReason(null)).toBeNull();
+ });
+});
diff --git a/server/lib/persistentMindPublic.js b/server/lib/persistentMindPublic.js
index 5d158cb60f..8999209b05 100644
--- a/server/lib/persistentMindPublic.js
+++ b/server/lib/persistentMindPublic.js
@@ -3,13 +3,23 @@
import { nextPersistentMindWakeAt } from './persistentMind.js';
import { normalizePersistentMindThinkingSelection } from './persistentMindThinkingPresets.js';
import { isUsageLimitPauseReason } from './persistentMindUsageLimit.js';
+import {
+ isContextBudgetPauseReason,
+ publicContextBudgetReason,
+} from './persistentMindContextBudget.js';
const publicReason = (state) => {
- if (!state.pauseReason) return null;
// A quota autopause is NOT a user action. Saying "Paused by user" there is the
// exact confusion this projection exists to prevent: the page would blame the
// human for a provider limit it will retry out of on its own.
if (isUsageLimitPauseReason(state.pauseReason)) return 'Provider usage limit reached';
+ // Context-budget / known-window-below-request failures are similarly not a
+ // user pause, and the numbers are safe to show so the operator can raise
+ // numCtx instead of staring at "Provider unavailable or wake failed".
+ const contextBudget = publicContextBudgetReason(state.pauseReason)
+ || publicContextBudgetReason(state.lastError);
+ if (contextBudget) return contextBudget;
+ if (!state.pauseReason) return null;
if (state.status === 'paused') return 'Paused by user';
if (state.status === 'degraded' || state.status === 'interrupted') return 'Provider unavailable or wake failed';
return 'Waiting for the next eligible wake';
@@ -65,6 +75,10 @@ export function publicPersistentMindState(state = {}) {
// an ordinary user pause so it can say "blocked, retrying at X" rather than
// leaving a quota stall indistinguishable from a deliberate stop.
usageLimited: isUsageLimitPauseReason(state.pauseReason),
+ // Non-transient local fitness block: the page must not look like a vague
+ // provider outage, and must not imply an automatic retry is coming.
+ contextBudgetBlocked: isContextBudgetPauseReason(state.pauseReason)
+ || isContextBudgetPauseReason(state.lastError),
queuedMessageCount: queuedMessages.length,
// How many of those queued messages will spend a borrowed (possibly
// account-backed) route, so the page can say that a pause is holding paid
@@ -78,6 +92,13 @@ export function publicPersistentMindState(state = {}) {
nextEligibleWakeAt: typeof state.nextEligibleWakeAt === 'string' ? state.nextEligibleWakeAt : null,
nextWakeAt: nextWakeAt == null ? null : new Date(nextWakeAt).toISOString(),
failureCount: Number.isInteger(state.failureCount) ? state.failureCount : 0,
- lastError: state.lastError ? 'The last wake did not complete; local diagnostics have details' : null,
+ lastError: (() => {
+ if (!state.lastError) return null;
+ const contextBudget = publicContextBudgetReason(state.lastError)
+ || publicContextBudgetReason(state.pauseReason);
+ // Safe: only token counts + recovery hint — never prompts or API keys.
+ if (contextBudget) return contextBudget;
+ return 'The last wake did not complete; local diagnostics have details';
+ })(),
};
}
diff --git a/server/lib/persistentMindPublic.test.js b/server/lib/persistentMindPublic.test.js
index fc6fd7c5d5..363678e0ea 100644
--- a/server/lib/persistentMindPublic.test.js
+++ b/server/lib/persistentMindPublic.test.js
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import { createDefaultPersistentMindState, normalizePersistentMindState } from './persistentMind.js';
import { publicPersistentMindState } from './persistentMindPublic.js';
import { PROVIDER_USAGE_LIMIT_PAUSE_REASON } from './persistentMindUsageLimit.js';
+import { contextBudgetPauseReasonFrom } from './persistentMindContextBudget.js';
const selection = {
id: 'deep-think',
@@ -193,4 +194,40 @@ describe('public persistent mind state', () => {
expect(projected.lastError).toBe('The last wake did not complete; local diagnostics have details');
expect(JSON.stringify(projected)).not.toContain('sk-EXAMPLE');
});
+
+ it('surfaces an actionable context-budget pauseReason with token counts instead of the vague provider copy', () => {
+ const raw = 'Ollama (qwen3:8b): known 12288-token context is below the 15104-token request budget';
+ const projected = publicPersistentMindState(normalizePersistentMindState({
+ ...createDefaultPersistentMindState(),
+ enabled: true,
+ started: true,
+ status: 'interrupted',
+ pauseReason: raw,
+ lastError: raw,
+ failureCount: 3,
+ }));
+
+ expect(projected.contextBudgetBlocked).toBe(true);
+ expect(projected.pauseReason).toMatch(/12288/);
+ expect(projected.pauseReason).toMatch(/15104/);
+ expect(projected.pauseReason).toMatch(/numCtx/i);
+ expect(projected.pauseReason).not.toBe('Provider unavailable or wake failed');
+ expect(projected.lastError).toBe(projected.pauseReason);
+ expect(projected.usageLimited).toBe(false);
+ expect(JSON.stringify(projected)).not.toContain('sk-');
+ });
+
+ it('does not blame the user when a context-budget failure was stored as a pause', () => {
+ const reason = contextBudgetPauseReasonFrom('known 8192-token context is below the 20000-token request budget');
+ const projected = publicPersistentMindState(normalizePersistentMindState({
+ ...createDefaultPersistentMindState(),
+ status: 'paused',
+ pauseReason: reason,
+ lastError: reason,
+ }));
+
+ expect(projected.contextBudgetBlocked).toBe(true);
+ expect(projected.pauseReason).toBe(reason);
+ expect(projected.pauseReason).not.toBe('Paused by user');
+ });
});
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index e79388d6e4..c07377098f 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -75,6 +75,10 @@ import {
isUsageLimitPauseReason,
usageLimitProbeDelayMs,
} from '../lib/persistentMindUsageLimit.js';
+import {
+ contextBudgetPauseReasonFrom,
+ isContextBudgetFitnessError,
+} from '../lib/persistentMindContextBudget.js';
import { isProviderAvailable, markProviderUsageLimit } from './providerStatus.js';
export const PERSISTENT_MIND_WAKE_EVENT_ID = 'cos-persistent-mind-wake';
@@ -784,7 +788,16 @@ async function runClaimedPersistentMindTurn(turn, mind) {
const adapterPrepared = await turnAdapter.prepare({ wake: turn.wake, signal: controller.signal, profile });
if (!await turnCanContinue(turn.id, generation, controller.signal)) return;
if (!adapterPrepared?.ok || !adapterPrepared.provider) {
- await parkActiveTurn(turn.id, adapterPrepared?.error || 'Persistent mind provider is unavailable', 'degraded', { retryAt: adapterPrepared?.retryAt || null });
+ const prepareError = adapterPrepared?.error || 'Persistent mind provider is unavailable';
+ if (isContextBudgetFitnessError(prepareError)) {
+ await parkActiveTurn(
+ turn.id,
+ contextBudgetPauseReasonFrom(prepareError),
+ 'paused',
+ );
+ return;
+ }
+ await parkActiveTurn(turn.id, prepareError, 'degraded', { retryAt: adapterPrepared?.retryAt || null });
return;
}
// Existing adapters only named their transport provider; missing model or
@@ -969,13 +982,21 @@ async function runClaimedPersistentMindTurn(turn, mind) {
// Transient rate-limits / network blips stay on the interrupted +
// backoff path below.
const usageLimit = !denied && !controller.signal.aborted && isHardProviderUsageLimitError(error);
+ // Local context-budget / known-window-below-request failures are not
+ // transient: retrying the same wake only climbs failureCount. Autopause
+ // with an actionable reason (token counts + numCtx hint) and wait for
+ // the operator to raise the window or shrink mind context.
+ const contextBudget = !denied && !controller.signal.aborted && !usageLimit
+ && isContextBudgetFitnessError(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,
- usageLimit ? PROVIDER_USAGE_LIMIT_PAUSE_REASON : message,
- usageLimit ? 'paused' : ((denied && error.deniedStatus) || 'interrupted'),
+ usageLimit
+ ? PROVIDER_USAGE_LIMIT_PAUSE_REASON
+ : (contextBudget ? contextBudgetPauseReasonFrom(error) : message),
+ (usageLimit || contextBudget) ? 'paused' : ((denied && error.deniedStatus) || 'interrupted'),
{
consumedAttempt: runStartedAt != null,
retireWake: denied && error.requiresResubmission === true,
@@ -995,7 +1016,9 @@ async function runClaimedPersistentMindTurn(turn, mind) {
'warn',
usageLimit
? `Persistent mind autopaused on provider usage limit: ${message}`
- : `Persistent mind turn ${denied ? 'refused a further provider call' : 'interrupted'}: ${message}`,
+ : contextBudget
+ ? `Persistent mind autopaused on local context budget: ${message}`
+ : `Persistent mind turn ${denied ? 'refused a further provider call' : 'interrupted'}: ${message}`,
{ turnId: turn.id },
);
}
diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.js
index ffcfd0de58..a33d300f31 100644
--- a/server/services/persistentMindSupervisor.test.js
+++ b/server/services/persistentMindSupervisor.test.js
@@ -1,6 +1,7 @@
import { afterEach, 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 { contextBudgetPauseReasonFrom } from '../lib/persistentMindContextBudget.js';
import {
__resetCosAdmissionReservations,
acquireCosActionReservation,
@@ -1525,7 +1526,7 @@ describe('persistent mind supervisor', () => {
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 () => {
+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');
@@ -1546,6 +1547,51 @@ describe('persistent mind supervisor', () => {
expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID)).toBe(false);
});
});
+
+ describe('local context-budget autopause', () => {
+ const echoProfileAdapter = () => vi.fn(async ({ profile }) => ({ ok: true, provider: profile.provider }));
+
+ it('autopauses on a known-context-below-request-budget error instead of climbing failureCount', async () => {
+ const priorFailures = 2;
+ mock.root.persistentMind = {
+ ...createDefaultPersistentMindState(),
+ failureCount: priorFailures,
+ };
+ const budgetMessage = 'Ollama (qwen3:8b): known 12288-token context is below the 15104-token request budget';
+ const run = vi.fn(async () => {
+ throw Object.assign(new Error(budgetMessage), {
+ errorAnalysis: { category: 'context-length', message: budgetMessage },
+ });
+ });
+ await supervisor.registerPersistentMindTurnAdapter({
+ prepare: echoProfileAdapter(),
+ run,
+ });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ await supervisor.enqueuePersistentMindMessage({ id: 'message-budget', text: 'Think.' });
+ await supervisor.drainPersistentMind();
+
+ expect(run).toHaveBeenCalledTimes(1);
+ const expectedReason = contextBudgetPauseReasonFrom(budgetMessage);
+ expect(mock.root.persistentMind).toMatchObject({
+ status: 'paused',
+ pauseReason: expectedReason,
+ lastError: expectedReason,
+ failureCount: priorFailures,
+ nextEligibleWakeAt: null,
+ activeTurn: null,
+ });
+ expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-budget']);
+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID)).toBe(false);
+ // No usage-limit probe — recovery is an operator numCtx / context change.
+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID)).toBe(false);
+
+ await supervisor.drainPersistentMind();
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+ });
+
describe('usage-limit retry time', () => {
const PROBE_ID = 'cos-persistent-mind-usage-limit-probe';
beforeEach(() => mock.events.clear());