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: hold maintainer runtime-budget exhaustion without benching providers (#9369)
[._.]/ Adam Eivyec81f8156e85
diff --git a/docs/PERSISTENT_MIND_MAINTAINER.md b/docs/PERSISTENT_MIND_MAINTAINER.mdindex 0957d4b628..707f8255b7 100644--- a/docs/PERSISTENT_MIND_MAINTAINER.md+++ b/docs/PERSISTENT_MIND_MAINTAINER.md@@ -109,6 +109,14 @@ self-thinking requests cannot use paid escalation. Existing accepted-presetsnapshot and revocation checks still apply. Coding tasks retain their independentprovider grants and CoS domain budgets.+Reaching a reserved per-call runtime ceiling keeps the attempt charged and its+failed-call receipt visible. It pauses the mind under policy hold, with no+provider bench, fallback, or provider-fault investigation. Adjust the inference+policy and explicitly resume to recheck the exact route, authority, and remaining+budget. Ordinary queued messages keep their identity; consumed temporary thinking+sessions still require a fresh message. Provider no-progress, transport, and HTTP+failures retain their normal recovery behavior.+`GET /api/cos/mind/maintainer` returns `inference` readiness and budget status.`mind.maintainer.reservation` events distinguish `local-curation` from`authorized-escalation`; ordinary model-call receipts retain reported usage anddiff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.jsindex 56025710de..c737c1b292 100644--- a/server/lib/aiToolkit/errorDetection.js+++ b/server/lib/aiToolkit/errorDetection.js@@ -14,6 +14,8 @@ export const ERROR_CATEGORIES = {MODEL_NOT_FOUND: 'model-not-found',NETWORK_ERROR: 'network-error',TIMEOUT: 'timeout',+ // An explicitly shortened caller spending cap, not provider health.+ RUNTIME_BUDGET_EXHAUSTED: 'runtime-budget-exhausted',QUOTA_EXCEEDED: 'quota-exceeded',// A frontier model declined the prompt on content/safety grounds. NOT a// provider fault — the provider is healthy and other prompts still work, so@@ -53,6 +55,12 @@ export const isRunCanceledError = (err) => (!!err && (err.code === 'RUN_CANCELED' || err.canceled === true));+/** Structured only: old generic absolute timeouts retain provider recovery. */+export const isRuntimeBudgetError = (err) => (+ err?.code === 'RUN_RUNTIME_BUDGET_EXHAUSTED'+ || err?.errorAnalysis?.category === ERROR_CATEGORIES.RUNTIME_BUDGET_EXHAUSTED+);+// A LOCAL inference runtime that ran out of accelerator memory mid-request.//// Observed shape (MTPLX/MLX behind an OpenAI-compatible server, rendered insidediff --git a/server/lib/aiToolkit/internal/runFinalizer.js b/server/lib/aiToolkit/internal/runFinalizer.jsindex 3a347a2c65..8535b7dee1 100644--- a/server/lib/aiToolkit/internal/runFinalizer.js+++ b/server/lib/aiToolkit/internal/runFinalizer.js@@ -13,6 +13,7 @@ export function createRunFinalizer({lifecycle,stallTimeout,absoluteTimeout,+ callerRuntimeBudget = false,outputPath,metadataPath,getOutput,@@ -94,15 +95,24 @@ export function createRunFinalizer({const finalizeTimeout = async (bound) => {consumeActiveStop(runId);- const error = bound === 'absolute'+ const budgetExhausted = bound === 'absolute' && callerRuntimeBudget;+ const error = budgetExhausted+ ? `Caller runtime budget exhausted after ${absoluteTimeout}ms; adjust the policy and explicitly resume`+ : bound === 'absolute'? `API execution timed out after ${absoluteTimeout}ms: absolute runtime cap reached`: `API execution timed out after ${stallTimeout}ms with no stream progress`;+ const terminal = {+ error,+ timeoutBound: bound,+ errorCategory: budgetExhausted ? ERROR_CATEGORIES.RUNTIME_BUDGET_EXHAUSTED : ERROR_CATEGORIES.TIMEOUT,+ errorAnalysis: budgetExhausted+ ? { hasError: true, category: ERROR_CATEGORIES.RUNTIME_BUDGET_EXHAUSTED, message: error }+ : analyzeError(error),+ ...(budgetExhausted ? { timeoutOrigin: 'caller-budget', runtimeBudgetMs: absoluteTimeout } : {}),+ };try {const { metadata, partialOutput } = await openTerminalMetadata();- metadata.error = error;- metadata.errorCategory = ERROR_CATEGORIES.TIMEOUT;- metadata.timeoutBound = bound;- metadata.errorAnalysis = analyzeError(error);+ Object.assign(metadata, terminal);await atomicWrite(metadataPath, metadata);safeSettle(() => hooks.onRunFailed?.(metadata, error, partialOutput), `Run ${runId} onRunFailed hook`);safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);@@ -111,7 +121,7 @@ export function createRunFinalizer({const salvaged = terminalState().partialOutput;safeSettle(() => onComplete?.({success: false,- error,+ ...terminal,endTime: new Date().toISOString(),duration: Date.now() - startTime,outputSize: Buffer.byteLength(salvaged),diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex 7cbfd71b0f..bd87d4b31a 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -706,6 +706,7 @@ export function createRunnerService(config = {}) {lifecycle,stallTimeout,absoluteTimeout,+ callerRuntimeBudget: absoluteTimeout < apiRunAbsoluteTimeoutMs(stallTimeout),outputPath,metadataPath,getOutput: () => output,diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex cc0b4c1f02..7ad935753a 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -634,6 +634,7 @@ describe('AI Toolkit runner service', () => {const completed = new Promise((resolve) => { done = resolve; });await runner.executeApiRun({runId: 'run-timeout',+ absoluteTimeoutMs: 1000, // a true stall still outranks a later caller capprovider: runReady(),model: null,prompt: 'hi',@@ -661,6 +662,7 @@ describe('AI Toolkit runner service', () => {// bench candidate; one that outran the absolute cap while producing is not,// so the host's classifier must be able to tell them apart without prose.expect(metadata.timeoutBound).toBe('stall');+ expect(metadata.timeoutOrigin).toBeUndefined();expect(metadata.error).toMatch(/no stream progress/i);});@@ -1415,7 +1417,7 @@ describe('AI Toolkit runner service', () => {// stream open across the timeout bounds without sleeping. Rejects on abort// the way a real reader does, so a timer that wins the race still unwinds// `processStream` instead of leaving it parked on a read forever.- const clockDrivenReader = ({ intervalMs, frames = Infinity, signal }) => {+ const clockDrivenReader = ({ intervalMs, frames = Infinity, signal, delta = { content: 'tok' } }) => {const encoder = new TextEncoder();let sent = 0;return {@@ -1429,7 +1431,7 @@ describe('AI Toolkit runner service', () => {sent += 1;resolve({done: false,- value: encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: 'tok' } }] })}\n`),+ value: encoder.encode(`data: ${JSON.stringify({ choices: [{ delta }] })}\n`),});}, intervalMs);}),@@ -1524,18 +1526,29 @@ describe('AI Toolkit runner service', () => {tempDirs.push(dataDir);vi.useFakeTimers();const request = vi.fn(async (_url, opts) => ({ ok: true,- body: { getReader: () => clockDrivenReader({ intervalMs: 1000, signal: opts.signal }) } }));+ body: { getReader: () => clockDrivenReader({ intervalMs: 1000, signal: opts.signal, delta: { reasoning_content: 'thinking' } }) } }));vi.stubGlobal('fetch', request);- const runner = createRunnerService({ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) } });+ const failed = vi.fn();+ const completeSpy = vi.fn(value => complete(value));+ const runner = createRunnerService({ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }), onRunFailed: failed } });let complete;const completed = new Promise(resolve => { complete = resolve; });await runner.executeApiRun({ runId: 'run-budget', provider: runReady(), model: null, prompt: 'hi',workspacePath: process.cwd(), screenshots: [], timeout: 120000, absoluteTimeoutMs: 5000, maxTokens: 8192,- onComplete: complete });+ onComplete: completeSpy });expect(JSON.parse(request.mock.calls[0][1].body).max_tokens).toBe(8192);await vi.advanceTimersByTimeAsync(5000);- expect(await completed).toMatchObject({ success: false, timeoutBound: 'absolute' });+ const metadata = await completed;+ expect(metadata).toMatchObject({ success: false, timeoutBound: 'absolute', timeoutOrigin: 'caller-budget',+ runtimeBudgetMs: 5000, errorCategory: 'runtime-budget-exhausted',+ errorAnalysis: { category: 'runtime-budget-exhausted' }, hadReasoning: true, usedReasoningAsFallback: true });+ expect(metadata.canceled).not.toBe(true);+ expect(metadata.outputSize).toBeGreaterThan(0);+ expect(await readFile(join(dataDir, 'runs/run-budget/output.txt'), 'utf8')).toContain('thinking');expect(await runner.isRunActive('run-budget')).toBe(false);+ await vi.advanceTimersByTimeAsync(120000);+ expect(failed).toHaveBeenCalledTimes(1);+ expect(completeSpy).toHaveBeenCalledTimes(1);});// `Math.max` against the default cap: an install that deliberately raiseddiff --git a/server/lib/providerCooldown.js b/server/lib/providerCooldown.jsindex f8bb142e1c..a5402db113 100644--- a/server/lib/providerCooldown.js+++ b/server/lib/providerCooldown.js@@ -134,7 +134,7 @@ function benchMsForTimeout(message, floorMs) {*/export function resolveProviderBench(analysis) {const category = analysis?.category || ERROR_CATEGORIES.UNKNOWN;- if (isRequestSpecificCategory(category)) return null;+ if (category === ERROR_CATEGORIES.RUNTIME_BUDGET_EXHAUSTED || isRequestSpecificCategory(category)) return null;const message = analysis?.message || null;if (category === ERROR_CATEGORIES.USAGE_LIMIT) {diff --git a/server/services/autoFixer.js b/server/services/autoFixer.jsindex 714cdd700a..b034fef9e4 100644--- a/server/services/autoFixer.js+++ b/server/services/autoFixer.js@@ -326,6 +326,9 @@ export function noteFallbackFailed({ provider, model }) {*/export async function escalateProviderFailure(error) {const ctx = error?.context || {};+ // Before dedupe: a later real fault on this route must still investigate.+ if (ctx.errorAnalysis?.category === ERROR_CATEGORIES.RUNTIME_BUDGET_EXHAUSTED) return;+const errorKey = aiProviderErrorKey(ctx.provider, ctx.model);const now = Date.now();@@ -462,6 +465,7 @@ export function _resetAutoFixerForTests() {*/async function handleAIProviderError(error) {const ctx = error.context || {};+ if (ctx.errorAnalysis?.category === ERROR_CATEGORIES.RUNTIME_BUDGET_EXHAUSTED) return;// A content/safety refusal is not a provider fault — we know exactly why it// failed (the model declined the prompt), so there's nothing for a CoS agentdiff --git a/server/services/autoFixer.test.js b/server/services/autoFixer.test.jsindex 4aa3935070..539cc30c20 100644--- a/server/services/autoFixer.test.js+++ b/server/services/autoFixer.test.js@@ -1,4 +1,8 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { runInNewContext } from 'node:vm';+import { extractDeclaration } from '../lib/mirrorParity.js';+import { ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';// cos.js drags in a giant dependency graph (PM2, fs, sockets…) — mock it// so autoFixer's defer/cancel behavior can be tested in isolation. `addTask`@@ -119,6 +123,41 @@ describe('autoFixer — defer + noteFallbackHandled', () => {}});+ it('publishes caller runtime exhaustion as a bounded warning without an investigation', async () => {+ // Execute the real bootstrap hook without booting daemons/DB/schedulers.+ const source = readFileSync(new URL('./bootstrap.js', import.meta.url), 'utf8')+ .replace('onRunFailed: (metadata, error) => {', 'function failureHook(metadata, error) {');+ const declaration = extractDeclaration(source, 'failureHook');+ expect(declaration).toBeTruthy();+ const hook = runInNewContext(`${declaration}; failureHook`, { errorEvents, ERROR_CATEGORIES, Date });+ const observed = vi.fn();+ errorEvents.on('error', observed);+ try {+ hook({ id: 'budget-run', providerName: 'Example API', providerId: 'example-api', model: 'm-1',+ timeoutBound: 'absolute', timeoutOrigin: 'caller-budget', runtimeBudgetMs: 120000,+ errorAnalysis: { category: 'runtime-budget-exhausted' } }, 'Caller runtime budget exhausted after 120000ms');+ expect(observed).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({+ code: 'AI_RUNTIME_BUDGET_EXHAUSTED', severity: 'warning', canAutoFix: false,+ context: expect.objectContaining({ timeoutOrigin: 'caller-budget', runtimeBudgetMs: 120000 }),+ }));+ await vi.advanceTimersByTimeAsync(6000);+ expect(cos.addTask).not.toHaveBeenCalled();+ } finally { errorEvents.off('error', observed); }+ });++ it('does not investigate caller budgets or poison dedupe for a later provider fault', async () => {+ const budget = { code: 'AI_PROVIDER_EXECUTION_FAILED', severity: 'error', canAutoFix: true,+ context: { provider: 'Example API', model: 'm-1', runId: 'budget-run',+ errorAnalysis: { category: 'runtime-budget-exhausted' } } };+ errorEvents.emit('error', budget);+ await escalateProviderFailure(budget);+ await vi.advanceTimersByTimeAsync(6000);+ expect(cos.addTask).not.toHaveBeenCalled();+ emitProviderFailure({ provider: 'Example API', model: 'm-1', runId: 'fault-run' });+ await vi.advanceTimersByTimeAsync(6000);+ expect(cos.addTask).toHaveBeenCalledTimes(1);+ });+it('never creates an investigation task for a content/safety refusal', async () => {// A refusal is self-explanatory (the model declined the prompt) — there's// nothing for a CoS agent to investigate, and the fallback path handlesdiff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 39c5f6a58d..c865974433 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -212,14 +212,15 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// AI_PROVIDER_EXECUTION_FAILED) and (b) the client shows a calm "model// declined, trying a fallback" notice instead of a red error toast. The// fallback retry itself is driven by promptRunner.js.+ const isBudget = metadata.errorAnalysis?.category === ERROR_CATEGORIES.RUNTIME_BUDGET_EXHAUSTED;const isRefusal = metadata.errorAnalysis?.category === ERROR_CATEGORIES.CONTENT_REFUSAL;errorEvents.emit('error', {- code: isRefusal ? 'AI_PROVIDER_CONTENT_REFUSED' : 'AI_PROVIDER_EXECUTION_FAILED',- message: isRefusal+ code: isBudget ? 'AI_RUNTIME_BUDGET_EXHAUSTED' : (isRefusal ? 'AI_PROVIDER_CONTENT_REFUSED' : 'AI_PROVIDER_EXECUTION_FAILED'),+ message: isBudget ? errorMessage : isRefusal? `${metadata.providerName} declined this prompt on content/safety grounds — trying a fallback model if one is configured.`: `AI provider ${metadata.providerName} execution failed: ${errorMessage}`,- severity: isRefusal ? 'warning' : 'error',- canAutoFix: !isRefusal,+ severity: isBudget || isRefusal ? 'warning' : 'error',+ canAutoFix: !isBudget && !isRefusal,timestamp: Date.now(),context: {runId: metadata.id,@@ -232,6 +233,9 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverDworkspaceName: metadata.workspaceName,errorDetails: errorMessage,errorAnalysis: metadata.errorAnalysis,+ timeoutBound: metadata.timeoutBound,+ timeoutOrigin: metadata.timeoutOrigin,+ runtimeBudgetMs: metadata.runtimeBudgetMs,// Note: promptPreview and outputTail intentionally omitted to avoid leaking sensitive data}});diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.jsindex daaa52aea1..628e6a65fb 100644--- a/server/services/persistentMindAdapter.js+++ b/server/services/persistentMindAdapter.js@@ -331,7 +331,7 @@ async function runPinnedPrompt({ provider, model, effort, prompt, screenshots =effort,prompt,source: 'cos-persistent-mind',- ...(timeoutMs ? { timeout: timeoutMs, absoluteTimeoutMs: timeoutMs, maxTokens: 8192, outputReserveTokens: 8192 } : {}),+ ...(timeoutMs ? { absoluteTimeoutMs: timeoutMs, maxTokens: 8192, outputReserveTokens: 8192 } : {}),allowFallback: false,screenshots,responseSchema,diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.jsindex 4bfe1b530e..20d9b482c0 100644--- a/server/services/persistentMindAdapter.test.js+++ b/server/services/persistentMindAdapter.test.js@@ -683,7 +683,10 @@ describe('persistent mind adapter', () => {mock.runPrompt.mock.calls.forEach(([request], index) => {expect(admitted[index].promptChars).toBe(request.prompt.length);expect(admitted[index].promptBytes).toBe(Buffer.byteLength(request.prompt));- expect(request.timeout).toBe(5000);+ expect(request.timeout).toBeUndefined();+ expect(request.absoluteTimeoutMs).toBe(5000);+ expect(request.maxTokens).toBe(8192);+ expect(request.outputReserveTokens).toBe(8192);expect(request.allowFallback).toBe(false);});});diff --git a/server/services/persistentMindCallGuard.js b/server/services/persistentMindCallGuard.jsindex 04e202ea66..752d3b1395 100644--- a/server/services/persistentMindCallGuard.js+++ b/server/services/persistentMindCallGuard.js@@ -19,6 +19,7 @@* deadlock a turn against its own admission. This boundary only ever refuses.*/+import { isRuntimeBudgetError } from '../lib/aiToolkit/errorDetection.js';import { normalizePersistentMindMaintainer } from '../lib/persistentMindMaintainer.js';import { getDomainMode } from '../lib/domainAutonomy.js';import { canonicalStringify } from '../lib/objects.js';@@ -170,6 +171,7 @@ export function createPersistentMindCallBoundary({} = {}) {let receiptIndex = 0;let accountedCalls = 0;+ let runtimeHold = null;const writeReceipt = async (fields) => {const index = receiptIndex;@@ -193,6 +195,7 @@ export function createPersistentMindCallBoundary({};const call = async ({ purpose, round = null, promptChars, promptBytes } = {}, run) => {+ if (runtimeHold) throw runtimeHold;const admission = await evaluate({ turnId, route, thinkingPresetId, thinkingSelection, selfThinkingRequest, capabilityFingerprint, signal, maintainerFingerprint, promptChars, promptBytes });if (!admission.ok) {await writeReceipt({ purpose, round, outcome: 'denied', reason: admission.reason });@@ -234,6 +237,13 @@ export function createPersistentMindCallBoundary({outcome: signal?.aborted ? 'interrupted' : 'failed',reason: error?.message,});+ if (reservation && !signal?.aborted && isRuntimeBudgetError(error)) {+ runtimeHold = Object.assign(buildPersistentMindCallDenial({+ reason: `Maintainer runtime budget of ${reservation.timeoutMs}ms exhausted; adjust inference policy and explicitly resume.`,+ status: 'waiting', code: 'runtime-budget-exhausted', disposition: 'hold',+ }), { cause: error, code: 'RUN_RUNTIME_BUDGET_EXHAUSTED', errorAnalysis: error.errorAnalysis });+ throw runtimeHold;+ }throw error;}};diff --git a/server/services/persistentMindCallGuard.test.js b/server/services/persistentMindCallGuard.test.jsindex 57d2147d2d..80036fd1b6 100644--- a/server/services/persistentMindCallGuard.test.js+++ b/server/services/persistentMindCallGuard.test.js@@ -314,6 +314,36 @@ describe('maintainer reservation boundary', () => {expect(ledger.day.calls).toBe(2);expect(receipts().at(-1).data.outcome).toBe('denied');});+ it('charges runtime exhaustion once and holds all subsequent calls on the turn', async () => {+ let clock = 0;+ let ledger = null;+ const { reserveMaintainerInference } = await import('./persistentMindMaintainerInference.js');+ const { normalizeMaintainerInference } = await import('../lib/persistentMindMaintainer.js');+ const policy = normalizeMaintainerInference({ maxCallMs: 120000 });+ const reserveInference = args => reserveMaintainerInference({ ...args,+ read: async () => ledger, write: async value => { ledger = structuredClone(value); } });+ const { call, accountedCalls } = boundary({ now: () => clock, reserveInference,+ evaluate: async () => ({ ok: true, maintainer: { enforced: true, lane: 'local-curation', policy } }) });+ const error = Object.assign(new Error('Caller runtime budget exhausted after 120000ms'), {+ code: 'RUN_RUNTIME_BUDGET_EXHAUSTED', errorAnalysis: { category: 'runtime-budget-exhausted' } });+ const held = await call({ purpose: 'summary' }, async ({ reportRunId, timeoutMs }) => {+ expect(timeoutMs).toBe(120000);+ reportRunId('spent-run');+ clock += timeoutMs;+ throw error;+ }).catch(e => e);+ expect(held).toMatchObject({ persistentMindCallDenied: true, denialCode: 'runtime-budget-exhausted',+ retryDisposition: 'hold', requiresResubmission: false, cause: error });+ const later = vi.fn();+ await expect(call({ purpose: 'turn' }, later)).rejects.toBe(held);+ expect(later).not.toHaveBeenCalled();+ expect(accountedCalls()).toBe(1);+ expect(mock.recordDomainUsage).toHaveBeenCalledExactlyOnceWith('cos', { actions: 1, ms: 120000 });+ expect(ledger.day).toMatchObject({ calls: 1, reservedMs: 120000 });+ expect(receipts()).toHaveLength(1);+ expect(receipts()[0].data).toMatchObject({ outcome: 'failed', runId: 'spent-run', elapsedMs: 120000 });+ });+it('stops remaining calls when maintainer authority changes, including disabling the role', async () => {const { normalizePersistentMindMaintainer } = await import('../lib/persistentMindMaintainer.js');const { canonicalStringify } = await import('../lib/objects.js');diff --git a/server/services/persistentMindContext.js b/server/services/persistentMindContext.jsindex d965b13e58..9e99c050ed 100644--- a/server/services/persistentMindContext.js+++ b/server/services/persistentMindContext.js@@ -9,6 +9,7 @@*/import { join } from 'path';+import { isRuntimeBudgetError } from '../lib/aiToolkit/errorDetection.js';import {PATHS,atomicWrite,@@ -187,11 +188,14 @@ const summaryOutcome = (summarize, input) => Promise.resolve()(summary) => typeof summary === 'string' && summary.trim()? { ok: true, attempted: true, summary }: { ok: false, attempted: true, error: 'Persistent mind summarizer returned no summary text' },- (error) => ({- ok: false,- attempted: !isPersistentMindCallDenial(error),- error: String(error?.message || error || 'Persistent mind summary failed').slice(0, 500),- })+ (error) => {+ if (isRuntimeBudgetError(error)) throw error;+ return {+ ok: false,+ attempted: !isPersistentMindCallDenial(error),+ error: String(error?.message || error || 'Persistent mind summary failed').slice(0, 500),+ };+ });/**diff --git a/server/services/persistentMindContext.test.js b/server/services/persistentMindContext.test.jsindex 3439e0349f..0c164988ca 100644--- a/server/services/persistentMindContext.test.js+++ b/server/services/persistentMindContext.test.js@@ -163,6 +163,18 @@ describe('persistent mind rollups', () => {expect(rollup).toMatchObject({ status: 'failed', summary: null, error: 'summary provider unavailable' });});+ it.each(['summary', 'journal'])('propagates a runtime hold during %s before further context effects', async (stage) => {+ mock.history = [event(1), event(2), event(3)];+ const held = Object.assign(buildPersistentMindCallDenial({ reason: 'Maintainer runtime budget exhausted',+ status: 'waiting', code: 'runtime-budget-exhausted' }), { code: 'RUN_RUNTIME_BUDGET_EXHAUSTED' });+ const summarize = vi.fn(async () => { if (stage === 'summary') throw held; return 'summary'; });+ const extractJournal = vi.fn(async () => { if (stage === 'journal') throw held; return '{"operations":[]}'; });+ await expect(preparePersistentMindContext({ recentEventLimit: 1, summarize, extractJournal })).rejects.toBe(held);+ if (stage === 'journal') expect(summarize).not.toHaveBeenCalled();+ expect(await readPersistentMindRollups()).toEqual([]);+ expect(mock.appendMindEvent).not.toHaveBeenCalled();+ });+it('leaves the range unattempted when the per-call boundary refuses the summary', async () => {mock.history = [event(1), event(2), event(3)];const summarize = vi.fn(async () => {diff --git a/server/services/persistentMindJournal.js b/server/services/persistentMindJournal.jsindex 3813e3b37e..f88d79bb79 100644--- a/server/services/persistentMindJournal.js+++ b/server/services/persistentMindJournal.js@@ -14,6 +14,7 @@*/import { join } from 'path';+import { isRuntimeBudgetError } from '../lib/aiToolkit/errorDetection.js';import { PATHS, atomicWrite, readJSONFileStrict } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { parseLLMJSON } from '../lib/llmText.js';@@ -169,6 +170,7 @@ export async function extractPersistentMindJournal({const first = await Promise.resolve().then(() => extract({ prompt })).then((text) => ({ attempted: true, text }), (error) => ({ attempted: !isCallDenial(error), error }));+ if (isRuntimeBudgetError(first.error)) throw first.error;if (!first.attempted) return { attempted: false, ok: false, applied: [], rejected: [] };if (first.error) {return { attempted: true, ok: false, applied: [], rejected: [], error: String(first.error?.message || first.error).slice(0, 300) };@@ -179,6 +181,7 @@ export async function extractPersistentMindJournal({const repair = await Promise.resolve().then(() => extract({ prompt: buildPersistentMindJournalRepairPrompt({ prompt, response: first.text, error: parsed.error }) })).then((text) => ({ text }), (error) => ({ error }));+ if (isRuntimeBudgetError(repair.error)) throw repair.error;if (repair.error) {return { attempted: true, ok: false, applied: [], rejected: [], error: String(repair.error?.message || repair.error).slice(0, 300) };}diff --git a/server/services/persistentMindJournal.test.js b/server/services/persistentMindJournal.test.jsindex a80b3776d4..5d7aa76191 100644--- a/server/services/persistentMindJournal.test.js+++ b/server/services/persistentMindJournal.test.js@@ -98,6 +98,15 @@ describe('journal extraction refuses what it cannot ground', () => {expect(existsSync(JOURNAL)).toBe(false);});+ it('propagates a runtime hold from the repair call without journal writes', async () => {+ const held = Object.assign(new Error('Maintainer runtime budget exhausted'), { code: 'RUN_RUNTIME_BUDGET_EXHAUSTED' });+ const { extract } = answering('not json', held);+ await expect(extractPersistentMindJournal({ mindId: MIND, events: [event(12, 'Example event')],+ range: RANGE, extract })).rejects.toBe(held);+ expect(extract).toHaveBeenCalledTimes(2);+ expect(await readPersistentMindJournal()).toEqual([]);+ });+it('leaves the range unextracted when the transport never reached a provider', async () => {const denial = Object.assign(new Error('budget exhausted'), { persistentMindCallDenied: true });const { extract } = answering(denial);diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex 6d5647c7ab..cef3df6c4c 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -10,6 +10,7 @@ import {const mock = vi.hoisted(() => ({root: null,+ inferenceLedger: null,scheduled: new Map(),events: new Map(),emitted: [],@@ -103,6 +104,19 @@ vi.mock('./updateChecker.js', () => ({isUpdateInProgress: vi.fn(() => mock.updateInProgress),}));+// Keep real reservation/accounting with an isolated in-memory ledger; daemon+// route probes are outside this supervisor workflow contract.+vi.mock('./persistentMindMaintainerInference.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual,+ inspectMaintainerInferenceRoute: async ({ role }) => ({ ok: true, enforced: true,+ lane: 'local-curation', policy: role.inference }),+ reserveMaintainerInference: args => actual.reserveMaintainerInference({ ...args,+ read: async () => mock.inferenceLedger,+ write: async value => { mock.inferenceLedger = structuredClone(value); } }),+ };+});+const supervisor = await import('./persistentMindSupervisor.js');const makeRoot = () => ({@@ -126,6 +140,7 @@ const deferred = () => {describe('persistent mind supervisor', () => {beforeEach(() => {mock.root = makeRoot();+ mock.inferenceLedger = null;mock.scheduled.clear();mock.emitted.length = 0;mock.budget = { withinBudget: true, exceeded: null };@@ -1339,6 +1354,68 @@ describe('persistent mind supervisor', () => {});});+ it.each([false, true])('holds a spent maintainer wake until explicit resume (temporary=%s)', async (temporary) => {+ vi.useFakeTimers();+ mock.root.config.persistentMindMaintainer = { enabled: true, inference: { maxCallMs: 120000 } };+ if (temporary) withDeepPreset();+ const effects = vi.fn();+ const providerCall = vi.fn(async ({ timeoutMs, reportRunId }) => {+ reportRunId('spent-budget-run');+ if (providerCall.mock.calls.length === 1) {+ await vi.advanceTimersByTimeAsync(timeoutMs);+ throw Object.assign(new Error('Caller runtime budget exhausted after 120000ms'), {+ code: 'RUN_RUNTIME_BUDGET_EXHAUSTED', errorAnalysis: { category: 'runtime-budget-exhausted' },+ });+ }+ effects();+ return { text: '{}' };+ });+ const run = vi.fn(async ({ callBoundary }) => {+ await callBoundary({ purpose: 'turn' }, providerCall);+ return {};+ });+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ const input = { id: 'budget-message', text: 'Example work.', ...(temporary ? { thinkingPresetId: 'deep' } : {}) };+ await supervisor.enqueuePersistentMindMessage(input);+ await supervisor.drainPersistentMind();+ expect(mock.root.persistentMind).toMatchObject({ status: 'paused', activeTurn: null, nextEligibleWakeAt: null });+ expect(mock.root.persistentMind.pauseReason).toContain('runtime budget');+ expect(mock.inferenceLedger.day).toMatchObject({ calls: 1, reservedMs: 120000 });+ expect(mock.recordUsage).toHaveBeenCalledExactlyOnceWith('cos', { actions: 1, ms: 120000 });+ expect(mindCallReceipts()[0].data).toMatchObject({ outcome: 'failed', runId: 'spent-budget-run' });+ if (temporary) {+ expect(mock.root.persistentMind.queuedMessages).toEqual([]);+ expect(mock.root.persistentMind.recentMessageIds).toContain(input.id);+ } else expect(mock.root.persistentMind.queuedMessages[0].id).toBe(input.id);+ expect(await supervisor.enqueuePersistentMindMessage(input)).toMatchObject({ success: true, duplicate: true });+ await vi.advanceTimersByTimeAsync(PERSISTENT_MIND_LIMITS.BACKOFF_MAX_MS * 2);+ await supervisor.drainPersistentMind();+ expect(providerCall).toHaveBeenCalledTimes(1);+ expect(effects).not.toHaveBeenCalled();+ // Explicit resume grants no route or spend: admission checks both again.+ await supervisor.resumePersistentMind();+ mock.profile = { ok: false, error: 'Pinned route is not authorized' };+ await supervisor.drainPersistentMind();+ expect(providerCall).toHaveBeenCalledTimes(1);+ mock.profile = { ok: true, provider: { id: 'example-cloud', type: 'api' }, model: 'example-model', effort: 'high' };+ mock.root.persistentMind.nextEligibleWakeAt = null;+ mock.budget = { withinBudget: false, exceeded: 'actions' };+ await supervisor.drainPersistentMind();+ expect(providerCall).toHaveBeenCalledTimes(1);+ mock.budget = { withinBudget: true };+ mock.root.persistentMind.nextEligibleWakeAt = null;+ mock.root.config.persistentMindMaintainer.inference.maxCallMs = 180000;+ await supervisor.drainPersistentMind();+ expect(providerCall).toHaveBeenCalledTimes(2);+ expect(effects).toHaveBeenCalledTimes(1);+ expect(mock.inferenceLedger.day).toMatchObject({ calls: 2, reservedMs: 300000 });+ expect(mindCallReceipts().at(-1).data).toMatchObject({ outcome: 'completed',+ providerId: 'example-cloud', model: 'example-model', temporaryRoute: false });+ expect(mock.root.persistentMind.queuedMessages).toEqual([]);+ });+it('records a failed attempt and still leaves its route and elapsed time readable', async () => {const run = vi.fn(async ({ callBoundary }) => callBoundary({ purpose: 'turn', round: 0 },diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex 57eb7dc04f..bbdd0736fb 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -37,7 +37,7 @@ import { isCompositeProviderId } from '../lib/providerRef.js';// both subtrees in every one of them.import { ServerError } from '../lib/errorHandler.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';-import { analyzeError, ERROR_CATEGORIES, isRunCanceledError } from '../lib/aiToolkit/errorDetection.js';+import { analyzeError, ERROR_CATEGORIES, isRunCanceledError, isRuntimeBudgetError } from '../lib/aiToolkit/errorDetection.js';import { isSchemaTypeCategory, resolveProviderBench } from '../lib/providerCooldown.js';import { isGenerationModel, isVisionCapableCliProvider } from '../lib/localModelHeuristics.js';import { contextWindowRejection } from '../lib/aiToolkit/providerStatus.js';@@ -735,10 +735,9 @@ export async function runPromptThroughProvider(rawArgs) {}}- // An explicit Stop or host shutdown is a lifecycle outcome, not a failed AI- // attempt. Do not enter any correction/fallback tier, mark the provider- // unavailable, or escalate an investigation task.- if (isRunCanceledError(firstError)) {+ // Stops and caller spending ceilings carry no provider-health verdict.+ // Neither enters correction/fallback, benching, or fault investigation.+ if (isRunCanceledError(firstError) || isRuntimeBudgetError(firstError)) {throw stripFallbackContext(firstError);}@@ -876,6 +875,14 @@ export async function runPromptThroughProvider(rawArgs) {}};+ const stopOnRuntimeBudget = async (error) => {+ if (!isRuntimeBudgetError(error)) return;+ // A caller cap can also end a correction/fallback already in flight.+ // Resolve suppression without investigating or starting another tier.+ for (const entry of suppressed.values()) await resolveHandled(entry.key);+ throw stripFallbackContext(error);+ };+// Explicitly escalate the primary failure to a Tier-4 investigation task —// used only on a give-up where every attempted key's incidental task was// suppressed, so nothing else would surface the unrecovered failure. Honors@@ -938,6 +945,7 @@ export async function runPromptThroughProvider(rawArgs) {runId: undefined, // fresh run so the failed primary's record stays intact});} catch (tier1Error) {+ await stopOnRuntimeBudget(tier1Error);// The corrected retry failed. If it reached the execution layer, its// onRunFailed queued a task keyed on the EFFECTIVE provider/model// (createRun may have proactively swapped) — record and suppress that@@ -995,6 +1003,7 @@ export async function runPromptThroughProvider(rawArgs) {runId: undefined, // fresh run so the failed primary's record stays intact});} catch (tier2Error) {+ await stopOnRuntimeBudget(tier2Error);// Same bookkeeping as Tier 1's failed corrected retry: a retry that// reached the execution layer queued its own task keyed on the// EFFECTIVE provider/model — record + suppress it so a slow Tier-3@@ -1074,6 +1083,7 @@ export async function runPromptThroughProvider(rawArgs) {runId: undefined, // fresh runId so the failed primary's record stays intact});} catch (fallbackError) {+ await stopOnRuntimeBudget(fallbackError);// ── Tier 4 — escalate ──: every deterministic tier failed. If the// fallback reached the execution layer, its OWN onRunFailed already// queued an investigation task (its key was never suppressed), so just@@ -1612,6 +1622,13 @@ async function executeProviderRunOnce({if (result?.errorAnalysis && typeof result.errorAnalysis === 'object') {err.errorAnalysis = result.errorAnalysis;}+ for (const key of ['timeoutBound', 'timeoutOrigin', 'runtimeBudgetMs']) {+ if (result?.[key] !== undefined) err[key] = result[key];+ }+ if (isRuntimeBudgetError(result)) {+ err.code = 'RUN_RUNTIME_BUDGET_EXHAUSTED';+ err.runId = runId;+ }safeReject(err);} else {// TUI runs do their own cleanup inside executeTuiRun (preferringdiff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.jsindex 8b856e285c..57023dbae5 100644--- a/server/services/promptRunner.test.js+++ b/server/services/promptRunner.test.js@@ -1126,6 +1126,22 @@ describe('promptRunner — retry-with-fallback', () => {// A pin opts out of ROUTING, not out of health reporting. Leaving the mark to// the fallback cascade let a provider fail every pinned call for hours while// the Providers page stayed green and unpinned callers kept choosing it.+ it.each([false, true])('rejects caller runtime exhaustion without recovery (allowFallback=%s)', async (allowFallback) => {+ const status = mockToolkitWithFallback();+ runner.executeApiRun.mockImplementation(async ({ onComplete }) => onComplete({+ success: false, error: 'Caller runtime budget exhausted after 120000ms', timeoutBound: 'absolute',+ timeoutOrigin: 'caller-budget', runtimeBudgetMs: 120000,+ errorAnalysis: { category: 'runtime-budget-exhausted' },+ }));+ await expect(runPromptThroughProvider({ provider: primaryApi, prompt: 'p', source: 'test', allowFallback }))+ .rejects.toMatchObject({ code: 'RUN_RUNTIME_BUDGET_EXHAUSTED', timeoutBound: 'absolute',+ timeoutOrigin: 'caller-budget', runtimeBudgetMs: 120000 });+ expect(status.markUnavailable).not.toHaveBeenCalled();+ expect(status.getFallbackProvider).not.toHaveBeenCalled();+ expect(autoFixer.escalateProviderFailure).not.toHaveBeenCalled();+ expect(runner.createRun).toHaveBeenCalledTimes(1);+ });+it('still benches the provider a pinned run failed on', async () => {const status = mockToolkitWithFallback();runner.executeCliRun.mockImplementation(async ({ onComplete }) => {@@ -2317,6 +2333,23 @@ describe('promptRunner — Tier 2 schema/type correction (issue #2350)', () => {expect(repair).toHaveBeenCalledWith(expect.objectContaining({ phase: 'response' }));});+ it('stops the correction cascade when its retry exhausts a caller runtime budget', async () => {+ const status = mockToolkitWithFallback();+ let attempts = 0;+ runner.executeApiRun.mockImplementation(async ({ onData, onComplete }) => {+ if (++attempts === 1) { onData('not json'); onComplete({ success: true }); }+ else onComplete({ success: false, error: 'Caller runtime budget exhausted',+ errorAnalysis: { category: 'runtime-budget-exhausted' } });+ });+ await expect(runPromptThroughProvider({ provider: apiProvider({ name: 'P' }), prompt: 'p', source: 'test',+ responseSchema: okShape, absoluteTimeoutMs: 120000 })).rejects.toMatchObject({ code: 'RUN_RUNTIME_BUDGET_EXHAUSTED' });+ expect(attempts).toBe(2);+ expect(status.getFallbackProvider).not.toHaveBeenCalled();+ expect(status.markUnavailable).not.toHaveBeenCalled();+ expect(autoFixer.escalateProviderFailure).not.toHaveBeenCalled();+ expect(autoFixer.noteFallbackFailed).not.toHaveBeenCalled();+ });+it('re-requests the SAME provider with a schema-strengthened prompt when the response is uncoercible', async () => {const status = mockToolkitWithFallback();const primary = apiProvider({ id: 'primary-api', name: 'Primary API', defaultModel: 'm1' });