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

feat(cos): bound local maintainer inference and explicit escalation (#7824)

[._.]/644eccc5cda7
diff --git a/docs/PERSISTENT_MIND_MAINTAINER.md b/docs/PERSISTENT_MIND_MAINTAINER.md
index 517d037d8c..14d0bd0237 100644
--- a/docs/PERSISTENT_MIND_MAINTAINER.md
+++ b/docs/PERSISTENT_MIND_MAINTAINER.md
@@ -44,3 +44,42 @@ The configuration lives in the existing machine-local CoS config document. It is
not part of portable mind bundles or peer sync. Importing a mind cannot arm this
role on the destination. No shipped seed or data migration is needed: absence
normalizes to disabled. Do not put local configuration or private reports in Git.
+
+## Local curation inference limits
+
+When the maintainer role is enabled, every mind provider call (including context
+summary, journal extraction and tool continuation) passes through the same local
+route check and durable allowance. The home profile must name an enabled local
+API provider with an installed model and known context window. Context fit uses a conservative UTF-8 byte bound plus
+8,192 output tokens and 1,024 tokens for transport framing. A failed catalog,
+missing model, oversized prompt or exhausted allowance defers the turn; there is
+no fallback, model download or global provider-default change.
+
+`persistentMindMaintainer.inference` accepts partial updates through the existing
+CoS config endpoint. Defaults are `maxCallsPerTurn: 6`, `maxCallsPerDay: 48`,
+`maxPromptChars: 96000`, `maxCallMs: 120000`, and
+`maxReservedMsPerDay: 5760000`. Every admitted attempt reserves its full timeout
+before inference, even if interrupted or failed. The API transport enforces an
+8,192-token output ceiling and the explicit absolute runtime cap; this reserved
+time is separate from provider-call receipts of observed duration. The daily allowance resets at
+UTC midnight; a turn's allowance survives midnight and restart. This is a
+conservative time/call allowance, not a dollar or token-spend estimate. Report
+batch review uses the same mind call boundary, not a fresh budget.
+
+Remote escalation defaults off: `paidPresetIds: []`, `maxPaidCallsPerDay: 0`.
+To permit it, configure a saved API thinking preset, explicitly allow its ID and a
+positive daily call cap, then select that preset in a human message. Automatic
+self-thinking requests cannot use paid escalation. Existing accepted-preset
+snapshot and revocation checks still apply. Coding tasks retain their independent
+provider grants and CoS domain budgets.
+
+`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 and
+unknown cost as unknown. Deterministic watchdog operations do not invoke this
+boundary or spend an inference allowance. Enabling/disabling or changing limits
+mid-turn invalidates that turn's remaining calls.
+
+After configuring this instance, inspect setup and runtime status, then explicitly
+request one `/api/cos/mind/wake` for a bounded smoke run. Do not change another
+install, fetch weights, or silently choose a remote model to make readiness green.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 3fb659aa94..3dd2a9c745 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -496,3 +496,11 @@ management endpoint includes disabled rows; generation lookups exclude them.
Model-support requests use the existing CoS user-task store and explicitly
request an isolated worktree and PR; no new store or background provider job is
introduced.
+
+- Maintainer inference allowance — `data/cos/maintainer-inference.json` is a bounded,
+ machine-local `file-primary` operational budget, like domain usage. It stores
+ one UTC day, one current turn and the last reservation; no prompt or report
+ content. Atomic serialized reservations survive restart and count interrupted
+ calls conservatively. No federation, seed or migration: absence is the initial
+ unused allowance. Included in normal data backups; never treat deletion as a
+ routine reset because it reopens spending permission.
diff --git a/server/lib/README.md b/server/lib/README.md
index b9f4c661d0..f60f1678b6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -719,4 +719,4 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `openchamber.js` | OpenChamber control-CLI identity, `session create` headless argv, `provider/model` gate, and `--dir`/`--prompt` spawn-time delivery. |
| `layaMlx.js` | Pinned Laya-MLX experiment model, request validation and probability normalization; entropy confidence stays distinct from entailment. |
-| `persistentMindMaintainer.js` | Machine-local opt-in development maintainer intent, schema, normalization and additive wake charter; never grants authority. |
+| `persistentMindMaintainer.js` | Machine-local maintainer intent, inference allowance schema, normalization and additive wake charter; never grants authority. |
diff --git a/server/lib/aiToolkit/internal/runTimeouts.js b/server/lib/aiToolkit/internal/runTimeouts.js
index 8cd062dbd1..28d3c2a7c5 100644
--- a/server/lib/aiToolkit/internal/runTimeouts.js
+++ b/server/lib/aiToolkit/internal/runTimeouts.js
@@ -51,7 +51,8 @@ export const DEFAULT_API_RUN_MAX_RUNTIME_MS = 1800000;
* `provider.timeout` past the default cap must keep running as long as it asked
* to, never be clamped DOWN by a ceiling it never configured.
*/
-export const apiRunAbsoluteTimeoutMs = (stallTimeout) => Math.max(
- DEFAULT_API_RUN_MAX_RUNTIME_MS,
- Number(stallTimeout) > 0 ? Number(stallTimeout) : 0,
-);
+export const apiRunAbsoluteTimeoutMs = (stallTimeout, requestedCap) => {
+ const legacy = Math.max(DEFAULT_API_RUN_MAX_RUNTIME_MS, Number(stallTimeout) > 0 ? Number(stallTimeout) : 0);
+ // A caller's explicit spending ceiling may only shorten the existing bound.
+ return Number.isFinite(requestedCap) && requestedCap > 0 ? Math.min(requestedCap, legacy) : legacy;
+};
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 471b170e68..c093df5b88 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -597,7 +597,7 @@ export function createRunnerService(config = {}) {
return runId;
},
- async executeApiRun({ runId, provider, model, prompt, workspacePath, screenshots, onData, onComplete, timeout }) {
+ async executeApiRun({ runId, provider, model, prompt, workspacePath, screenshots, onData, onComplete, timeout, absoluteTimeoutMs, maxTokens }) {
const runDir = join(RUNS_PATH, runId);
const outputPath = join(runDir, 'output.txt');
const metadataPath = join(runDir, 'metadata.json');
@@ -694,7 +694,7 @@ export function createRunnerService(config = {}) {
// never reaches the fetch is still bounded, and the failure is classified
// as a timeout instead of the AbortError's UNKNOWN/HTTP-0).
const stallTimeout = timeout || provider.timeout || DEFAULT_API_RUN_TIMEOUT_MS;
- const absoluteTimeout = apiRunAbsoluteTimeoutMs(stallTimeout);
+ const absoluteTimeout = apiRunAbsoluteTimeoutMs(stallTimeout, absoluteTimeoutMs);
let settled = false;
let stallTimeoutHandle = null;
let absoluteTimeoutHandle = null;
@@ -847,6 +847,7 @@ export function createRunnerService(config = {}) {
messages: [{ role: 'user', content: messageContent }],
stream: true,
...apiGenerationOptions(provider),
+ ...(Number.isInteger(maxTokens) && maxTokens > 0 ? { max_tokens: maxTokens } : {}),
// Ollama's OpenAI-compatible endpoint defaults to a ~4K context
// window and silently truncates longer prompts. A top-level
// num_ctx lifts it (honored by Ollama, ignored by other
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 6676587c88..cf0fed8d2f 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -1474,6 +1474,25 @@ describe('AI Toolkit runner service', () => {
expect(await runner.isRunActive('run-trickle')).toBe(false);
});
+ it('enforces an explicit short absolute cap while forwarding the API output ceiling', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-budget-'));
+ tempDirs.push(dataDir);
+ vi.useFakeTimers();
+ const request = vi.fn(async (_url, opts) => ({ ok: true,
+ body: { getReader: () => clockDrivenReader({ intervalMs: 1000, signal: opts.signal }) } }));
+ vi.stubGlobal('fetch', request);
+ const runner = createRunnerService({ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) } });
+ 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 });
+ 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' });
+ expect(await runner.isRunActive('run-budget')).toBe(false);
+ });
+
// `Math.max` against the default cap: an install that deliberately raised
// `provider.timeout` past 30 minutes keeps running exactly as long as it
// asked to, rather than being silently clamped DOWN by the new ceiling.
diff --git a/server/lib/persistentMindMaintainer.js b/server/lib/persistentMindMaintainer.js
index 4d0b067b9f..7178ce56e1 100644
--- a/server/lib/persistentMindMaintainer.js
+++ b/server/lib/persistentMindMaintainer.js
@@ -1,16 +1,35 @@
/** Machine-local intent, separate from capability grants and provider choices. */
import { z } from 'zod';
+export const maintainerInferenceSchema = z.object({
+ maxCallsPerTurn: z.number().int().min(1).max(20).optional(),
+ maxCallsPerDay: z.number().int().min(1).max(1000).optional(),
+ maxPromptChars: z.number().int().min(1000).max(250000).optional(),
+ maxCallMs: z.number().int().min(1000).max(600000).optional(),
+ maxReservedMsPerDay: z.number().int().min(1000).max(86400000).optional(),
+ paidPresetIds: z.array(z.string().trim().min(1).max(100)).max(20).optional(),
+ maxPaidCallsPerDay: z.number().int().min(0).max(100).optional(),
+}).strict();
+
+export function normalizeMaintainerInference(raw) {
+ const defaults = { maxCallsPerTurn: 6, maxCallsPerDay: 48, maxPromptChars: 96000,
+ maxCallMs: 120000, maxReservedMsPerDay: 5760000, paidPresetIds: [], maxPaidCallsPerDay: 0 };
+ const parsed = maintainerInferenceSchema.safeParse(raw || {});
+ return { ...defaults, ...(parsed.success ? parsed.data : {}) };
+}
+
export const persistentMindMaintainerSchema = z.object({
schemaVersion: z.literal(1).optional(),
enabled: z.boolean().optional(),
appIds: z.array(z.string().trim().min(1).max(128)).max(50).optional(),
+ inference: maintainerInferenceSchema.optional(),
intervalMinutes: z.number().int().min(5).max(10080).optional(),
}).strict();
export function normalizePersistentMindMaintainer(raw) {
return {
schemaVersion: 1,
+ inference: normalizeMaintainerInference(raw?.inference),
enabled: raw?.enabled === true,
appIds: [...new Set((Array.isArray(raw?.appIds) ? raw.appIds : [])
.filter(id => typeof id === 'string' && id.trim() && id.length <= 128)
@@ -21,7 +40,8 @@ export function normalizePersistentMindMaintainer(raw) {
}
export function mergePersistentMindMaintainer(previous, update) {
- return normalizePersistentMindMaintainer({ ...normalizePersistentMindMaintainer(previous), ...update });
+ return normalizePersistentMindMaintainer({ ...normalizePersistentMindMaintainer(previous), ...update,
+ inference: { ...normalizeMaintainerInference(previous?.inference), ...update?.inference } });
}
export function maintainerInstructionBlock(raw) {
diff --git a/server/lib/persistentMindTrajectory.js b/server/lib/persistentMindTrajectory.js
index e8ec97cf11..fd0c7bf8b2 100644
--- a/server/lib/persistentMindTrajectory.js
+++ b/server/lib/persistentMindTrajectory.js
@@ -27,6 +27,7 @@ export const PERSISTENT_MIND_EVENT_KINDS = Object.freeze([
// overall answer. Older builds fold this kind as a no-op, so adding it is not
// an envelope change.
'mind.model.call',
+ 'mind.maintainer.reservation',
'mind.model.result',
'mind.thought',
'mind.reply',
diff --git a/server/services/cosState.test.js b/server/services/cosState.test.js
index dd6114a798..f11ba90e5d 100644
--- a/server/services/cosState.test.js
+++ b/server/services/cosState.test.js
@@ -37,7 +37,9 @@ describe('cosState persistence', () => {
writeConfig({ persistentMindMaintainer: { enabled: true, appIds: ['example-app'], intervalMinutes: 120 }, persistentMindPrompt: { instructions: 'Keep my voice.' } });
store = await freshModule();
const config = await store.getConfig();
- expect(config.persistentMindMaintainer).toEqual({ schemaVersion: 1, enabled: true, appIds: ['example-app'], intervalMinutes: 120 });
+ expect(config.persistentMindMaintainer).toEqual({ schemaVersion: 1, enabled: true, appIds: ['example-app'], intervalMinutes: 120,
+ inference: { maxCallsPerTurn: 6, maxCallsPerDay: 48, maxPromptChars: 96000, maxCallMs: 120000,
+ maxReservedMsPerDay: 5760000, paidPresetIds: [], maxPaidCallsPerDay: 0 } });
await store.saveConfig(config);
expect(readJson(CONFIG_PATH).persistentMindMaintainer.enabled).toBe(true);
expect(readJson(CONFIG_PATH).persistentMindPrompt.instructions).toBe('Keep my voice.');
diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.js
index 82e2cfb6cb..d05e9032ce 100644
--- a/server/services/persistentMindAdapter.js
+++ b/server/services/persistentMindAdapter.js
@@ -303,7 +303,7 @@ export function buildPersistentMindSummaryPrompt({ events, previousSummary, jour
*/
const passthroughCallBoundary = (_descriptor, run) => run({ reportRunId: () => {} });
-async function runPinnedPrompt({ provider, model, effort, prompt, screenshots = [], signal, responseSchema, heartbeat, reportRunId }) {
+async function runPinnedPrompt({ provider, model, effort, prompt, screenshots = [], signal, responseSchema, heartbeat, reportRunId, timeoutMs }) {
if (signal?.aborted) throw new Error(String(signal.reason || 'Persistent mind turn interrupted'));
if (typeof heartbeat === 'function') await heartbeat();
let activeRunId = null;
@@ -329,6 +329,7 @@ async function runPinnedPrompt({ provider, model, effort, prompt, screenshots =
effort,
prompt,
source: 'cos-persistent-mind',
+ ...(timeoutMs ? { timeout: timeoutMs, absoluteTimeoutMs: timeoutMs, maxTokens: 8192, outputReserveTokens: 8192 } : {}),
allowFallback: false,
screenshots,
responseSchema,
@@ -382,14 +383,15 @@ export function createPersistentMindTurnAdapter() {
},
async summarize({ events, previousSummary, journal, mindId, provider, model, effort, signal, heartbeat, callBoundary = passthroughCallBoundary }) {
- const result = await callBoundary({ purpose: 'summary' }, ({ reportRunId }) => runPinnedPrompt({
+ const prompt = buildPersistentMindSummaryPrompt({ events, previousSummary, journal, mindId });
+ const result = await callBoundary({ purpose: 'summary', promptChars: prompt.length, promptBytes: Buffer.byteLength(prompt) }, ({ reportRunId, timeoutMs }) => runPinnedPrompt({
provider,
model,
effort,
signal,
heartbeat,
reportRunId,
- prompt: buildPersistentMindSummaryPrompt({ events, previousSummary, journal, mindId }),
+ prompt, timeoutMs,
}));
return result.text.trim();
},
@@ -398,8 +400,8 @@ export function createPersistentMindTurnAdapter() {
// closed-schema validation and the single repair retry, so the adapter
// cannot accidentally accept a batch the contract would have refused.
async extractJournal({ prompt, provider, model, effort, signal, heartbeat, callBoundary = passthroughCallBoundary }) {
- const result = await callBoundary({ purpose: 'journal' }, ({ reportRunId }) => runPinnedPrompt({
- provider, model, effort, signal, heartbeat, reportRunId, prompt,
+ const result = await callBoundary({ purpose: 'journal', promptChars: prompt.length, promptBytes: Buffer.byteLength(prompt) }, ({ reportRunId, timeoutMs }) => runPinnedPrompt({
+ provider, model, effort, signal, heartbeat, reportRunId, prompt, timeoutMs,
}));
return result.text.trim();
},
@@ -472,9 +474,10 @@ export function createPersistentMindTurnAdapter() {
for (let round = 0; round < MAX_TOOL_PROVIDER_ROUNDS; round += 1) {
// Round 0 is the turn itself; every later round is a continuation the
// model earned by asking for tools. Each is admitted on its own.
+ const prompt = `${providerPrompt}\n\n# Current naming identity\n${persistentMindNamePrompt(await readPersistentMindName(PERSISTENT_MIND_ID), { canChoose: taskAccess.manageMind })}`;
result = await callBoundary(
- { purpose: round === 0 ? 'turn' : 'tool-round', round },
- async ({ reportRunId }) => runPinnedPrompt({
+ { purpose: round === 0 ? 'turn' : 'tool-round', round, promptChars: prompt.length, promptBytes: Buffer.byteLength(prompt) },
+ async ({ reportRunId, timeoutMs }) => runPinnedPrompt({
provider,
model,
effort,
@@ -482,7 +485,7 @@ export function createPersistentMindTurnAdapter() {
heartbeat,
screenshots,
reportRunId,
- prompt: `${providerPrompt}\n\n# Current naming identity\n${persistentMindNamePrompt(await readPersistentMindName(PERSISTENT_MIND_ID), { canChoose: taskAccess.manageMind })}`,
+ prompt, timeoutMs,
responseSchema: persistentMindResponseSchema,
}),
);
diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.js
index 85033e9d86..51a1e58343 100644
--- a/server/services/persistentMindAdapter.test.js
+++ b/server/services/persistentMindAdapter.test.js
@@ -636,7 +636,7 @@ describe('persistent mind adapter', () => {
const admitted = [];
const callBoundary = vi.fn(async (descriptor, run) => {
admitted.push(descriptor);
- return run({ reportRunId: () => {} });
+ return run({ reportRunId: () => {}, timeoutMs: 5000 });
});
const adapter = createPersistentMindTurnAdapter();
@@ -657,12 +657,18 @@ describe('persistent mind adapter', () => {
callBoundary,
});
- expect(admitted).toEqual([
+ expect(admitted).toMatchObject([
{ purpose: 'summary' },
{ purpose: 'turn', round: 0 },
{ purpose: 'tool-round', round: 1 },
]);
expect(mock.runPrompt).toHaveBeenCalledTimes(3);
+ 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.allowFallback).toBe(false);
+ });
});
it('starts no further provider call once the boundary denies a later round', async () => {
diff --git a/server/services/persistentMindCallGuard.js b/server/services/persistentMindCallGuard.js
index df4031f84b..1fafc74aff 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 { normalizePersistentMindMaintainer } from '../lib/persistentMindMaintainer.js';
import { getDomainMode } from '../lib/domainAutonomy.js';
import { canonicalStringify } from '../lib/objects.js';
import { normalizePersistentMindState } from '../lib/persistentMind.js';
@@ -75,6 +76,8 @@ export async function evaluatePersistentMindCallAdmission({
selfThinkingRequest = null,
capabilityFingerprint = null,
signal,
+ maintainerFingerprint = null,
+ promptChars, promptBytes,
} = {}) {
if (signal?.aborted) {
return denial(String(signal.reason || 'Persistent mind turn interrupted'), DENIAL_STATUS.interrupted);
@@ -96,6 +99,11 @@ export async function evaluatePersistentMindCallAdmission({
return denial('Persistent mind capability grants changed during the turn', DENIAL_STATUS.authorization);
}
+ const maintainer = normalizePersistentMindMaintainer(root?.config?.persistentMindMaintainer);
+ if (maintainerFingerprint !== null && canonicalStringify(maintainer) !== maintainerFingerprint) {
+ return denial('Maintainer inference policy changed during the turn', DENIAL_STATUS.authorization);
+ }
+
// Provider availability/authorization and preset lifecycle both resolve here:
// the same exact-or-refuse resolvers the supervisor admitted the turn with.
const resolved = selfThinkingRequest
@@ -123,6 +131,13 @@ export async function evaluatePersistentMindCallAdmission({
return denial(`CoS ${budget.exceeded || 'daily'} budget exhausted`, DENIAL_STATUS.budget);
}
+ if (maintainer.enabled) {
+ const { inspectMaintainerInferenceRoute } = await import('./persistentMindMaintainerInference.js');
+ const checked = await inspectMaintainerInferenceRoute({ role: maintainer, provider: resolved.provider,
+ model: resolved.model, thinkingPresetId, thinkingSelection, selfThinkingRequest, promptChars, promptBytes });
+ if (!checked.ok) return denial(checked.reason, DENIAL_STATUS.authorization);
+ return { ok: true, maintainer: checked };
+ }
return { ok: true };
}
@@ -146,10 +161,12 @@ export function createPersistentMindCallBoundary({
selfThinkingRequest = null,
capabilityFingerprint = null,
signal,
+ maintainerFingerprint = null,
now = () => Date.now(),
evaluate = evaluatePersistentMindCallAdmission,
appendEvent = appendMindEvent,
recordUsage = recordDomainUsage,
+ reserveInference = async args => (await import('./persistentMindMaintainerInference.js')).reserveMaintainerInference(args),
} = {}) {
let receiptIndex = 0;
let accountedCalls = 0;
@@ -175,17 +192,29 @@ export function createPersistentMindCallBoundary({
});
};
- const call = async ({ purpose, round = null } = {}, run) => {
- const admission = await evaluate({ turnId, route, thinkingPresetId, thinkingSelection, selfThinkingRequest, capabilityFingerprint, signal });
+ const call = async ({ purpose, round = null, promptChars, promptBytes } = {}, run) => {
+ 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 });
throw buildPersistentMindCallDenial(admission);
}
+ let reservation = null;
+ if (admission.maintainer?.enforced) {
+ const reserved = await reserveInference({ turnId, lane: admission.maintainer.lane,
+ policy: admission.maintainer.policy, now }).catch(() => ({ ok: false, reason: 'Maintainer inference budget is unreadable; restore or repair its ledger before retrying.' }));
+ if (!reserved.ok) {
+ await writeReceipt({ purpose, round, outcome: 'denied', reason: reserved.reason });
+ throw buildPersistentMindCallDenial({ reason: reserved.reason, status: 'waiting' });
+ }
+ reservation = reserved.reservation;
+ await appendEvent({ kind: 'mind.maintainer.reservation', mindId, turnId,
+ eventId: `maintainer-reservation:${turnId}:${reservation.turnCall}`, data: reservation });
+ }
let runId = null;
const reportRunId = (id) => { if (typeof id === 'string' && id) runId = id; };
const startedAt = now();
try {
- const result = await run({ reportRunId });
+ const result = await run({ reportRunId, timeoutMs: reservation?.timeoutMs });
const elapsedMs = Math.max(0, now() - startedAt);
reportRunId(result?.runId);
await account(elapsedMs);
diff --git a/server/services/persistentMindCallGuard.test.js b/server/services/persistentMindCallGuard.test.js
index 41153b889e..d26dd372e0 100644
--- a/server/services/persistentMindCallGuard.test.js
+++ b/server/services/persistentMindCallGuard.test.js
@@ -288,3 +288,31 @@ describe('createPersistentMindCallBoundary', () => {
]);
});
});
+
+describe('maintainer reservation boundary', () => {
+ it('charges failed summaries and shares durable allowance with a recreated turn boundary', async () => {
+ const { reserveMaintainerInference } = await import('./persistentMindMaintainerInference.js');
+ const { normalizeMaintainerInference } = await import('../lib/persistentMindMaintainer.js');
+ let ledger = null;
+ const policy = normalizeMaintainerInference({ maxCallsPerTurn: 2 });
+ const reserveInference = args => reserveMaintainerInference({ ...args,
+ read: async () => ledger, write: async value => { ledger = structuredClone(value); } });
+ const make = () => boundary({ reserveInference,
+ evaluate: async () => ({ ok: true, maintainer: { enforced: true, lane: 'local-curation', policy } }) });
+ const provider = vi.fn(async ({ timeoutMs }) => ({ text: 'done', timeoutMs }));
+ await expect(make().call({ purpose: 'summary' }, async () => { throw new Error('Provider failed'); })).rejects.toThrow('Provider failed');
+ expect(await make().call({ purpose: 'journal' }, provider)).toMatchObject({ timeoutMs: policy.maxCallMs });
+ await expect(make().call({ purpose: 'turn' }, provider)).rejects.toThrow('per-turn');
+ expect(provider).toHaveBeenCalledTimes(1);
+ expect(ledger.day.calls).toBe(2);
+ expect(receipts().at(-1).data.outcome).toBe('denied');
+ });
+ 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');
+ const fingerprint = canonicalStringify(normalizePersistentMindMaintainer({ enabled: true }));
+ mock.root.config.persistentMindMaintainer = { enabled: false };
+ await expect(evaluatePersistentMindCallAdmission({ turnId: TURN_ID, route, maintainerFingerprint: fingerprint }))
+ .resolves.toMatchObject({ ok: false, status: 'degraded', reason: 'Maintainer inference policy changed during the turn' });
+ });
+});
diff --git a/server/services/persistentMindMaintainer.js b/server/services/persistentMindMaintainer.js
index c4a2528db5..feedeb3b55 100644
--- a/server/services/persistentMindMaintainer.js
+++ b/server/services/persistentMindMaintainer.js
@@ -30,10 +30,19 @@ export async function describePersistentMindMaintainerSetup({ config } = {}) {
const { resolvePersistentMindProfile } = await import('./persistentMindProfile.js');
const route = await resolvePersistentMindProfile(profile);
if (!route.ok) prerequisites.push('Configure an enabled, available persistent mind provider and model.');
+ let inference = null;
+ if (role.enabled) {
+ const { inspectMaintainerInferenceRoute, readMaintainerInferenceBudget } = await import('./persistentMindMaintainerInference.js');
+ const checked = await inspectMaintainerInferenceRoute({ role, provider: route.provider, model: route.model, promptChars: role.inference.maxPromptChars, promptBytes: role.inference.maxPromptChars });
+ const budget = await readMaintainerInferenceBudget().catch(() => null);
+ inference = { ...checked, budget };
+ if (!checked.ok) prerequisites.push(checked.reason);
+ if (!budget) prerequisites.push('Maintainer inference budget could not be read.');
+ }
if (getDomainMode(effective, 'cos') !== 'execute') prerequisites.push('CoS autonomy must allow execution.');
if (root.paused) prerequisites.push('CoS is paused.');
return {
- role, apps, permissions, prerequisites,
+ role, apps, permissions, prerequisites, inference,
availableApps: roster.map(app => ({ id: app.id, name: app.name, repository: app.fullName, granted: app.granted, available: !!app.forge })),
ready: role.enabled && prerequisites.length === 0,
readinessScope: 'configuration-only',
diff --git a/server/services/persistentMindMaintainer.test.js b/server/services/persistentMindMaintainer.test.js
index fea05f786b..483891bed2 100644
--- a/server/services/persistentMindMaintainer.test.js
+++ b/server/services/persistentMindMaintainer.test.js
@@ -3,6 +3,7 @@ import { describePersistentMindMaintainerSetup } from './persistentMindMaintaine
import { composeMaintainerInstructions, mergePersistentMindMaintainer } from '../lib/persistentMindMaintainer.js';
const mocks = vi.hoisted(() => ({ root: {}, apps: [] }));
vi.mock('./persistentMindProfile.js', () => ({ resolvePersistentMindProfile: async () => ({ ok: mocks.root.routeAvailable !== false }) }));
+vi.mock('./persistentMindMaintainerInference.js', () => ({ inspectMaintainerInferenceRoute: async () => ({ ok: true }), readMaintainerInferenceBudget: async () => ({}) }));
vi.mock('./cosState.js', () => ({ loadState: async () => mocks.root }));
vi.mock('./persistentMindManagedApps.js', () => ({ readPersistentMindManagedApps: async () => mocks.apps }));
beforeEach(() => {
@@ -13,7 +14,7 @@ beforeEach(() => {
});
it('keeps legacy installs off and preserves custom instructions during role composition', async () => {
const preview = await describePersistentMindMaintainerSetup();
- expect(preview.role).toEqual({ schemaVersion: 1, enabled: false, appIds: [], intervalMinutes: 60 });
+ expect(preview.role).toMatchObject({ schemaVersion: 1, enabled: false, appIds: [], intervalMinutes: 60 });
expect(preview.ready).toBe(false);
expect(composeMaintainerInstructions('Custom voice', undefined)).toBe('Custom voice');
const role = mergePersistentMindMaintainer({ appIds: ['example-app'] }, { enabled: true });
diff --git a/server/services/persistentMindMaintainerInference.js b/server/services/persistentMindMaintainerInference.js
new file mode 100644
index 0000000000..2aafb966b4
--- /dev/null
+++ b/server/services/persistentMindMaintainerInference.js
@@ -0,0 +1,91 @@
+/** Machine-local inference reservations. Attempts stay charged after failure or restart. */
+import { z } from 'zod';
+import { join } from 'path';
+import { PATHS, atomicWrite, readJSONFile } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { normalizePersistentMindMaintainer } from '../lib/persistentMindMaintainer.js';
+import { knownContextWindow } from '../lib/aiToolkit/providerStatus.js';
+import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
+import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
+
+const FILE = join(PATHS.cos, 'maintainer-inference.json');
+const writeQueue = createFileWriteQueue();
+const emptyDay = date => ({ date, calls: 0, paidCalls: 0, reservedMs: 0 });
+const ledgerSchema = z.object({ schemaVersion: z.literal(1),
+ day: z.object({ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine(value => Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value),
+ calls: z.number().int().nonnegative(), paidCalls: z.number().int().nonnegative(), reservedMs: z.number().int().nonnegative() }),
+ turn: z.object({ id: z.string().min(1).max(200), calls: z.number().int().nonnegative() }),
+ lastReservation: z.object({ lane: z.enum(['local-curation', 'authorized-escalation']), turnId: z.string(),
+ at: z.string().datetime(), timeoutMs: z.number().int().positive(), costUsd: z.null(), usage: z.literal('unknown'),
+ dayCall: z.number().int().positive(), turnCall: z.number().int().positive() }),
+});
+const validateLedger = stored => {
+ if (stored !== null && !ledgerSchema.safeParse(stored).success) throw new Error('Maintainer inference ledger is invalid; restore its last valid backup.');
+ return stored;
+};
+const readLedger = () => readJSONFile(FILE, null, { strict: true, logError: false });
+
+export async function inspectMaintainerInferenceRoute({ role: rawRole, provider, model, thinkingPresetId = null,
+ thinkingSelection = null, selfThinkingRequest = null, promptChars, promptBytes,
+ probe = probeOpenAiModels } = {}) {
+ const role = normalizePersistentMindMaintainer(rawRole);
+ if (!role.enabled) return { ok: true, enforced: false };
+ const policy = role.inference;
+ if (!provider || provider.enabled === false) return { ok: false, reason: 'Maintainer inference provider is unavailable.' };
+ if (provider.type !== 'api') return { ok: false, reason: 'Maintainer inference requires an API provider so output and duration limits can be enforced.' };
+ const runtime = provider.type === 'api' && localRuntimeForProvider(provider);
+ const paid = !runtime;
+ if (paid && (selfThinkingRequest || !thinkingPresetId || !thinkingSelection
+ || !policy.paidPresetIds.includes(thinkingPresetId) || policy.maxPaidCallsPerDay === 0)) {
+ return { ok: false, reason: 'Maintainer curation requires a local API model. Select an explicitly permitted paid preset in a human message to escalate.' };
+ }
+ if (!Number.isInteger(promptChars) || promptChars < 0 || promptChars > policy.maxPromptChars
+ || !Number.isSafeInteger(promptBytes) || promptBytes < promptChars) {
+ return { ok: false, reason: `Maintainer prompt exceeds the ${policy.maxPromptChars} character limit; reduce context or report batch size.` };
+ }
+ let contextTokens = knownContextWindow(provider, model);
+ if (runtime) {
+ const catalog = await probe(runtime.endpoint, { apiKey: provider.apiKey || '', timeoutMs: 3000 });
+ if (!catalog.reachable || !Array.isArray(catalog.models)) return { ok: false, reason: 'Local maintainer model catalog is unavailable; check the configured runtime.' };
+ if (!catalog.models.includes(model)) return { ok: false, reason: 'Configured maintainer model is absent from the local runtime; select an installed model.' };
+ const served = catalog.contextWindows?.[model];
+ if (Number.isFinite(served) && served > 0) contextTokens = contextTokens ? Math.min(contextTokens, served) : served;
+ if (!contextTokens) return { ok: false, reason: 'Local maintainer context capacity is unknown; configure or verify the runtime context window.' };
+ }
+ // UTF-8 bytes are a deliberately conservative text token bound; reserve
+ // room for output and transport framing without pretending to know usage.
+ if (contextTokens && promptBytes + 9216 > contextTokens) return { ok: false, reason: 'Maintainer context does not fit the configured model; shrink context or choose a larger local window.' };
+ return { ok: true, enforced: true, lane: paid ? 'authorized-escalation' : 'local-curation', contextTokens, policy };
+}
+
+/** Reserve atomically BEFORE invoking a provider; no refunds for uncertain calls. */
+export async function reserveMaintainerInference({ turnId, lane, policy, now = () => Date.now(),
+ read = readLedger, write = ledger => atomicWrite(FILE, ledger), queue = writeQueue } = {}) {
+ return queue(async () => {
+ const date = new Date(now()).toISOString().slice(0, 10);
+ const stored = validateLedger(await read());
+ if (stored && date < stored.day.date) return { ok: false, reason: 'Maintainer budget clock moved backwards; check the system clock.' };
+ const day = stored?.day.date === date ? { ...stored.day } : emptyDay(date);
+ // Only the active supervisor turn may reach this boundary (CallGuard
+ // compares activeTurn.id immediately before reservation). An older turn
+ // cannot resume after another is admitted; retrying creates a new id.
+ const turn = stored?.turn.id === turnId ? { ...stored.turn } : { id: turnId, calls: 0 };
+ if (turn.calls >= policy.maxCallsPerTurn) return { ok: false, reason: 'Maintainer per-turn inference allowance exhausted.' };
+ if (day.calls >= policy.maxCallsPerDay || day.reservedMs + policy.maxCallMs > policy.maxReservedMsPerDay) return { ok: false, reason: 'Maintainer daily inference allowance exhausted.' };
+ if (lane === 'authorized-escalation' && day.paidCalls >= policy.maxPaidCallsPerDay) return { ok: false, reason: 'Maintainer paid escalation allowance exhausted.' };
+ day.calls += 1; day.reservedMs += policy.maxCallMs; turn.calls += 1;
+ if (lane === 'authorized-escalation') day.paidCalls += 1;
+ const reservation = { lane, turnId, at: new Date(now()).toISOString(), timeoutMs: policy.maxCallMs,
+ costUsd: null, usage: 'unknown', dayCall: day.calls, turnCall: turn.calls };
+ await write({ schemaVersion: 1, day, turn, lastReservation: reservation });
+ return { ok: true, reservation };
+ });
+}
+
+export async function readMaintainerInferenceBudget({ now = () => Date.now(), read = readLedger } = {}) {
+ const ledger = validateLedger(await read());
+ const date = new Date(now()).toISOString().slice(0, 10);
+ if (ledger && date < ledger.day.date) throw new Error('Maintainer budget clock moved backwards; check the system clock.');
+ return { day: ledger?.day?.date === date ? ledger.day : emptyDay(date),
+ lastReservation: ledger?.lastReservation || null, accounting: 'conservative-reserved-time', costUsd: null };
+}
diff --git a/server/services/persistentMindMaintainerInference.test.js b/server/services/persistentMindMaintainerInference.test.js
new file mode 100644
index 0000000000..287446768f
--- /dev/null
+++ b/server/services/persistentMindMaintainerInference.test.js
@@ -0,0 +1,69 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { normalizePersistentMindMaintainer, mergePersistentMindMaintainer } from '../lib/persistentMindMaintainer.js';
+import { inspectMaintainerInferenceRoute, reserveMaintainerInference, readMaintainerInferenceBudget } from './persistentMindMaintainerInference.js';
+
+const role = normalizePersistentMindMaintainer({ enabled: true });
+const provider = { id: 'ollama', type: 'api', enabled: true, endpoint: 'http://localhost:11434/v1', numCtx: 131072 };
+const probe = vi.fn(async () => ({ reachable: true, models: ['example-model'], contextWindows: {} }));
+const inspect = (patch = {}) => inspectMaintainerInferenceRoute({ role, provider, model: 'example-model', promptChars: 100, promptBytes: 100, probe, ...patch });
+
+it('validates the installed local route and fails closed for missing catalog, model and context capacity', async () => {
+ await expect(inspect()).resolves.toMatchObject({ ok: true, lane: 'local-curation' });
+ await expect(inspect({ model: 'missing' })).resolves.toMatchObject({ ok: false });
+ await expect(inspect({ probe: async () => ({ reachable: false, models: null }) })).resolves.toMatchObject({ ok: false });
+ await expect(inspect({ provider: { ...provider, numCtx: undefined } })).resolves.toMatchObject({ ok: false });
+ await expect(inspect({ promptChars: role.inference.maxPromptChars + 1 })).resolves.toMatchObject({ ok: false });
+ await expect(inspect({ promptBytes: undefined })).resolves.toMatchObject({ ok: false });
+ await expect(inspect({ promptBytes: -1 })).resolves.toMatchObject({ ok: false });
+ await expect(inspect({ promptBytes: 131072 })).resolves.toMatchObject({ ok: false });
+ await expect(inspect({ probe: async () => ({ reachable: true, models: ['example-model'], contextWindows: { 'example-model': 8192 } }) })).resolves.toMatchObject({ ok: false });
+});
+
+it('permits remote escalation only for an explicitly allowed human preset and never self-thinking', async () => {
+ const remote = { ...provider, endpoint: 'https://example.com/v1' };
+ await expect(inspect({ provider: remote })).resolves.toMatchObject({ ok: false });
+ const authorized = { provider: remote, role: { ...role, inference: { paidPresetIds: ['deep'], maxPaidCallsPerDay: 1 } }, thinkingPresetId: 'deep', thinkingSelection: { id: 'deep' } };
+ await expect(inspect(authorized)).resolves.toMatchObject({ ok: true, lane: 'authorized-escalation' });
+ await expect(inspect({ ...authorized, selfThinkingRequest: {} })).resolves.toMatchObject({ ok: false });
+ await expect(inspect({ role: { enabled: false }, provider: remote })).resolves.toMatchObject({ ok: true, enforced: false });
+ expect(mergePersistentMindMaintainer({ inference: { maxCallsPerDay: 3 } }, { inference: { maxCallsPerTurn: 2 } }).inference).toMatchObject({ maxCallsPerDay: 3, maxCallsPerTurn: 2 });
+});
+
+const store = () => {
+ let persisted = null;
+ return { queue: createFileWriteQueue(), read: async () => structuredClone(persisted), write: async value => { persisted = structuredClone(value); } };
+};
+it('serializes concurrent admissions and retains per-turn allowance across new callers and midnight', async () => {
+ const disk = store();
+ const policy = { ...role.inference, maxCallsPerTurn: 2, maxCallsPerDay: 2 };
+ const reserve = (turnId, date = '2026-01-01T23:59:59Z') => reserveMaintainerInference({ ...disk, turnId, lane: 'local-curation', policy, now: () => Date.parse(date) });
+ const results = await Promise.all([reserve('one'), reserve('one'), reserve('one')]);
+ expect(results.map(result => result.ok)).toEqual([true, true, false]);
+ await expect(reserve('two')).resolves.toMatchObject({ ok: false });
+ await expect(reserve('one', '2026-01-02T00:01:00Z')).resolves.toMatchObject({ ok: false });
+ await expect(reserve('two', '2026-01-02T00:01:00Z')).resolves.toMatchObject({ ok: true });
+ expect((await disk.read()).lastReservation.costUsd).toBeNull();
+ await expect(reserve('three', '2026-01-01T23:59:59Z')).resolves.toMatchObject({ ok: false });
+});
+it('reserves paid calls and timeout allowance independently and refuses unreadable storage', async () => {
+ const disk = store();
+ const policy = { ...role.inference, maxPaidCallsPerDay: 1, maxReservedMsPerDay: role.inference.maxCallMs * 2 };
+ const reserve = lane => reserveMaintainerInference({ ...disk, turnId: 'one', lane, policy });
+ await expect(reserve('authorized-escalation')).resolves.toMatchObject({ ok: true });
+ await expect(reserve('authorized-escalation')).resolves.toMatchObject({ ok: false });
+ await expect(reserve('local-curation')).resolves.toMatchObject({ ok: true });
+ await expect(reserve('local-curation')).resolves.toMatchObject({ ok: false });
+ expect((await readMaintainerInferenceBudget(disk)).day).toMatchObject({ calls: 2, paidCalls: 1 });
+ await expect(reserveMaintainerInference({ ...disk, read: async () => { throw new Error('Unreadable'); }, turnId: 'one', policy })).rejects.toThrow('Unreadable');
+});
+
+it('refuses malformed persisted counters and dates instead of reopening allowance', async () => {
+ for (const patch of [{ calls: -1 }, { date: '2026-99-99' }, { paidCalls: -1 }, { reservedMs: -1 }]) {
+ const disk = store();
+ await reserveMaintainerInference({ ...disk, turnId: 'one', lane: 'local-curation', policy: role.inference });
+ const ledger = await disk.read();
+ await disk.write({ ...ledger, day: { ...ledger.day, ...patch } });
+ await expect(reserveMaintainerInference({ ...disk, turnId: 'two', lane: 'local-curation', policy: role.inference })).rejects.toThrow('ledger is invalid');
+ }
+});
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index c7d5fea8ba..1c26356efb 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -9,6 +9,8 @@
* makes zero provider calls.
*/
+import { normalizePersistentMindMaintainer } from '../lib/persistentMindMaintainer.js';
+import { canonicalStringify as maintainerCanonicalStringify } from '../lib/objects.js';
import { randomUUID } from 'crypto';
import { getDomainMode } from '../lib/domainAutonomy.js';
import { isPersistentMindCallDenial } from '../lib/persistentMindTrajectory.js';
@@ -877,6 +879,7 @@ async function runClaimedPersistentMindTurn(turn, mind) {
thinkingSelection,
selfThinkingRequest,
capabilityFingerprint: persistentMindCapabilityGrantFingerprint(admissionRoot.config?.persistentMindCapabilities),
+ maintainerFingerprint: maintainerCanonicalStringify(normalizePersistentMindMaintainer(admissionRoot.config?.persistentMindMaintainer)),
signal: controller.signal,
});
// Context/memory orchestration is only needed once admission succeeds.
diff --git a/server/services/promptRunner.js b/server/services/promptRunner.js
index b2f250af01..fd8ac605d4 100644
--- a/server/services/promptRunner.js
+++ b/server/services/promptRunner.js
@@ -1381,6 +1381,8 @@ async function executeProviderRunOnce({
onRunReady,
onRunSettled,
timeout: timeoutOverride,
+ absoluteTimeoutMs,
+ maxTokens,
cwd: cwdOverride,
screenshots = [],
outputReserveTokens,
@@ -1672,7 +1674,7 @@ async function executeProviderRunOnce({
// healthy, productive run silently produced nothing. Sixteen NVIDIA NIM
// nemotron persistent-mind runs died this way at exactly 302s in the two
// days after #7560 merged, and none before it (#7665).
- const backstopTimeout = apiRunAbsoluteTimeoutMs(effectiveTimeout);
+ const backstopTimeout = apiRunAbsoluteTimeoutMs(effectiveTimeout, absoluteTimeoutMs);
apiTimeoutHandle = setTimeout(() => {
stopRun(runId).catch(() => { /* best-effort cancel */ });
safeReject(new Error(`API execution timed out after ${backstopTimeout}ms`));
@@ -1681,7 +1683,7 @@ async function executeProviderRunOnce({
// a per-call override (e.g. the importer's long stage timeout) governs the
// ceiling instead of the runner's provider/default fallback — same
// caller-override precedence CLI/TUI runs already get.
- executeApiRun({ runId, provider: effectiveProvider, model: effectiveModel, prompt, workspacePath: effectiveCwd, screenshots: Array.isArray(screenshots) ? screenshots : [], onData, onComplete, timeout: effectiveTimeout }).catch(safeReject);
+ executeApiRun({ runId, provider: effectiveProvider, model: effectiveModel, prompt, workspacePath: effectiveCwd, screenshots: Array.isArray(screenshots) ? screenshots : [], onData, onComplete, timeout: effectiveTimeout, absoluteTimeoutMs, maxTokens }).catch(safeReject);
} else if (effectiveProvider.type === PROVIDER_TYPES.TUI) {
// `source` (e.g. 'pipeline-manuscript-completeness') labels the live,
// interactive view this TUI run surfaces in the Shell page.
diff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.js
index 85fdcbfc04..8aa32a82e5 100644
--- a/server/services/promptRunner.test.js
+++ b/server/services/promptRunner.test.js
@@ -202,6 +202,13 @@ describe('promptRunner — happy paths', () => {
expect(runner.executeCliRun).not.toHaveBeenCalled();
});
+ it('passes explicit API output and absolute spending caps without changing the route', async () => {
+ runner.executeApiRun.mockImplementation(async ({ onData, onComplete }) => { onData('bounded'); onComplete({ success: true }); });
+ await runPromptThroughProvider({ provider: apiProvider(), prompt: 'p', source: 'test',
+ model: 'gpt-test', allowFallback: false, maxTokens: 8192, absoluteTimeoutMs: 120000 });
+ expect(runner.executeApiRun).toHaveBeenCalledWith(expect.objectContaining({ maxTokens: 8192, absoluteTimeoutMs: 120000, model: 'gpt-test' }));
+ });
+
it('reports the concrete run lifecycle so a parent workflow can stop it', async () => {
const events = [];
runner.executeApiRun.mockImplementation(async ({ runId, onComplete }) => {