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: let one Persistent Mind message run on a saved alternate model (#6273)

[._.]/ Adam Eivyd93e3a445bf2
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index 7d88f68861..93d2736bf0 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -89,6 +89,7 @@ The `selectModelForTask` function routes tasks to appropriate model tiers:
| domainAutonomy | execute per domain | Off, dry-run, or execute policy for each automatic-work domain |
| domainBudgets | unlimited | Optional daily action and runtime caps per domain |
| persistentMindProfile.enabled | false | Configure a persistent-mind profile without starting it |
+| persistentMindThinkingPresets.presets | [] | Saved named alternates (exact provider/model/effort) one message may borrow for a single turn. Empty by default; storing one changes nothing about the route the mind wakes on |
| avatarStyle | svg | Default CoS UI avatar style (`svg`, `ascii`, `core`, the 3D styles, or a `rigged-<modelId>` record) |
## API Endpoints
diff --git a/scripts/migrations/342-persistent-mind-thinking-presets.js b/scripts/migrations/342-persistent-mind-thinking-presets.js
new file mode 100644
index 0000000000..6dc82bb217
--- /dev/null
+++ b/scripts/migrations/342-persistent-mind-thinking-presets.js
@@ -0,0 +1,74 @@
+/**
+ * Introduce saved temporary thinking presets for the Persistent Mind (#6273).
+ *
+ * Two independent stamps, each gated on the file it reads:
+ *
+ * - `data/cos/config.json` gains an empty `persistentMindThinkingPresets` list.
+ * An absent list already normalizes to empty, so this changes no behavior; it
+ * means an install that never opens the Mind page still reads as migrated
+ * rather than pending forever, and it makes the new setting visible to anyone
+ * inspecting the config file.
+ * - `data/cos/state.json` records the bumped Persistent Mind schema version,
+ * because a queued or active message may now carry a `thinkingPresetId`.
+ *
+ * Nothing is derived and nothing is seeded: an existing list is never replaced,
+ * and the home profile's provider/model/effort selection is untouched. An
+ * install that rolls back to a reader without temporary sessions simply drops
+ * the field, and the message answers on the unchanged default route.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../../server/lib/persistentMind.js';
+import { createDefaultPersistentMindThinkingPresets } from '../../server/lib/persistentMindThinkingPresets.js';
+import { atomicWrite, safeJSONParse } from '../../server/lib/fileUtils.js';
+
+const readRecord = async (path) => {
+ const raw = await readFile(path, 'utf8').catch((error) => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ if (raw == null) return { missing: true };
+ const parsed = safeJSONParse(raw, null, { logError: false });
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
+ ? { record: parsed }
+ : { invalid: true };
+};
+
+async function stampConfig(rootDir) {
+ const configPath = join(rootDir, 'data', 'cos', 'config.json');
+ const { record: config, missing, invalid } = await readRecord(configPath);
+ if (missing || invalid) return false;
+ if (config.persistentMindThinkingPresets && typeof config.persistentMindThinkingPresets === 'object') return false;
+ await atomicWrite(configPath, {
+ ...config,
+ persistentMindThinkingPresets: createDefaultPersistentMindThinkingPresets(),
+ });
+ return true;
+}
+
+async function stampMindSchemaVersion(rootDir) {
+ const statePath = join(rootDir, 'data', 'cos', 'state.json');
+ const { record: state, missing, invalid } = await readRecord(statePath);
+ if (missing || invalid) return false;
+ const mind = state.persistentMind;
+ if (!mind || typeof mind !== 'object' || Array.isArray(mind)) return false;
+ if (mind.schemaVersion === PERSISTENT_MIND_SCHEMA_VERSION) return false;
+ await atomicWrite(statePath, {
+ ...state,
+ persistentMind: { ...mind, schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION },
+ });
+ return true;
+}
+
+export default {
+ async up({ rootDir }) {
+ const configStamped = await stampConfig(rootDir);
+ const stateStamped = await stampMindSchemaVersion(rootDir);
+ const updated = Number(configStamped) + Number(stateStamped);
+ if (updated > 0) {
+ console.log(`🧠 migration 342: prepared ${updated} Persistent Mind file(s) for temporary thinking sessions`);
+ }
+ return updated > 0 ? { updated } : { updated: 0, reason: 'already-applied' };
+ },
+};
diff --git a/scripts/migrations/342-persistent-mind-thinking-presets.test.js b/scripts/migrations/342-persistent-mind-thinking-presets.test.js
new file mode 100644
index 0000000000..16fd24d6ee
--- /dev/null
+++ b/scripts/migrations/342-persistent-mind-thinking-presets.test.js
@@ -0,0 +1,62 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './342-persistent-mind-thinking-presets.js';
+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../../server/lib/persistentMind.js';
+
+let rootDir;
+
+afterEach(async () => {
+ if (rootDir) await rm(rootDir, { recursive: true, force: true });
+ rootDir = null;
+});
+
+const configPath = () => join(rootDir, 'data', 'cos', 'config.json');
+const statePath = () => join(rootDir, 'data', 'cos', 'state.json');
+const readJson = async (path) => JSON.parse(await readFile(path, 'utf8'));
+
+describe('migration 342 — persistent mind thinking presets', () => {
+ beforeEach(async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-mind-thinking-presets-'));
+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });
+ });
+
+ it('adds an empty preset list without touching the pinned home profile', async () => {
+ await writeFile(configPath(), JSON.stringify({
+ maxConcurrentAgents: 3,
+ persistentMindProfile: { enabled: true, providerId: 'example-provider', model: 'example-model', effort: 'high' },
+ }));
+ await writeFile(statePath(), JSON.stringify({
+ persistentMind: { schemaVersion: 5, enabled: true, futureField: 'preserve' },
+ }));
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 2 });
+ expect(await readJson(configPath())).toMatchObject({
+ maxConcurrentAgents: 3,
+ persistentMindProfile: { enabled: true, providerId: 'example-provider', model: 'example-model', effort: 'high' },
+ persistentMindThinkingPresets: { schemaVersion: 1, presets: [] },
+ });
+ expect(await readJson(statePath())).toMatchObject({
+ persistentMind: { schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION, enabled: true, futureField: 'preserve' },
+ });
+ });
+
+ it('never replaces presets a user already saved', async () => {
+ const presets = { schemaVersion: 1, presets: [{ id: 'deep', label: 'Deep', providerId: 'example-provider', model: 'example-model', effort: 'max' }] };
+ await writeFile(configPath(), JSON.stringify({ persistentMindThinkingPresets: presets }));
+ await writeFile(statePath(), JSON.stringify({ persistentMind: { schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION } }));
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });
+ expect((await readJson(configPath())).persistentMindThinkingPresets).toEqual(presets);
+ });
+
+ it('leaves missing, invalid, or mind-less files untouched', async () => {
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });
+
+ await writeFile(configPath(), '{broken');
+ await writeFile(statePath(), JSON.stringify({ agents: {} }));
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });
+ expect(await readFile(configPath(), 'utf8')).toBe('{broken');
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index a257259b42..a987f9f6d9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -58,6 +58,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `persistentMindProfile.js` | Versioned, default-off persistent-mind provider profile (`enabled`, provider/model/effort, text interface, maximum quiet interval), its strict API schema, duration resolver, and safe partial-update merge that clears model/effort on a provider switch. |
| `persistentMindPrompt.js` | Editable persistent-mind identity and operating-instructions schema/defaults; saving it never starts inference. |
| `persistentMindPublic.js` | `publicPersistentMindState(state)` — the sole client/socket projection of durable mind state: exposes lifecycle fields, queue count, and the derived next wake time; drops queued message bodies/active wake payloads, and replaces free-form provider errors with coarse safe reasons. |
+| `persistentMindThinkingPresets.js` | 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, and preset lookup. Storage only — saving or selecting a preset starts no inference. |
| `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. |
| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). Pure — no storage, no provider I/O. |
diff --git a/server/lib/index.js b/server/lib/index.js
index f162910f2b..047e677b9e 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -265,6 +265,7 @@ export * from './persistentMindTrajectory.js';
export * from './persistentMindProfile.js';
export * from './persistentMindPrompt.js';
export * from './persistentMindPublic.js';
+export * from './persistentMindThinkingPresets.js';
export * from './agentScratchPaths.js';
export * from './agentSentinel.js';
export * from './bareUrl.js';
diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.js
index 530e200378..61d1259273 100644
--- a/server/lib/persistentMind.js
+++ b/server/lib/persistentMind.js
@@ -11,8 +11,9 @@ import { PERSISTENT_MIND_ID } from './persistentMindTrajectory.js';
import { MAX_SCREENSHOT_BYTES } from './uploadLimits.js';
import { sanitizeFilename } from './mimeTypes.js';
import { isSafeFilename } from './pathSafety.js';
+import { asPersistentMindThinkingPresetId } from './persistentMindThinkingPresets.js';
-export const PERSISTENT_MIND_SCHEMA_VERSION = 5;
+export const PERSISTENT_MIND_SCHEMA_VERSION = 6;
export const PERSISTENT_MIND_IMAGE_EXTENSIONS = Object.freeze(['.png', '.jpg', '.jpeg', '.gif', '.webp']);
export const PERSISTENT_MIND_IMAGE_MIME_TYPES = Object.freeze({
@@ -173,17 +174,27 @@ export function normalizePersistentMindMessageImage(value) {
};
}
-/** Hash the bounded message content used to validate retries after completion. */
+/**
+ * Hash the bounded message content used to validate retries after completion.
+ *
+ * A temporary thinking-session selection is part of the content: retrying the
+ * same text on a different (possibly account-billed) model is a different
+ * request, not the same one. The key is omitted entirely when no override was
+ * chosen so fingerprints recorded before temporary sessions existed still match
+ * byte-for-byte, and an in-flight idempotent retry survives the upgrade.
+ */
export function persistentMindMessageFingerprint(value) {
const images = Array.isArray(value?.images)
? value.images.map((image) => (typeof image === 'string' ? image : image?.attachmentId))
.map(asAttachmentId)
.filter(Boolean)
: [];
+ const thinkingPresetId = asPersistentMindThinkingPresetId(value?.thinkingPresetId);
return createHash('sha256')
.update(JSON.stringify({
text: asBoundedString(value?.text, PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS),
images,
+ ...(thinkingPresetId ? { thinkingPresetId } : {}),
}))
.digest('hex');
}
@@ -217,10 +228,15 @@ const sanitizeMessage = (value) => {
if (images.length >= PERSISTENT_MIND_LIMITS.MAX_MESSAGE_IMAGES) break;
}
if (!id || (!text && images.length === 0)) return null;
+ const thinkingPresetId = asPersistentMindThinkingPresetId(value?.thinkingPresetId);
return {
id,
text,
...(images.length > 0 ? { images } : {}),
+ // Absent on every ordinary message. Kept on the durable queued/active record
+ // so a requeue or a restart replays the route the user actually chose,
+ // instead of quietly answering on the home profile.
+ ...(thinkingPresetId ? { thinkingPresetId } : {}),
createdAt: asIso(value?.createdAt) || new Date(0).toISOString(),
};
};
@@ -358,9 +374,24 @@ export function normalizePersistentMindState(raw) {
if (!started && activeTurn) {
if (activeTurn.wake.kind === 'message') {
const message = activeTurn.wake.message;
- if (!seenQueued.has(message.id) && !recentMessageIds.includes(message.id)) {
- queuedMessages.unshift(message);
- if (queuedMessages.length > PERSISTENT_MIND_LIMITS.MAX_QUEUED_MESSAGES) queuedMessages.pop();
+ if (!recentMessageIds.includes(message.id)) {
+ if (message.thinkingPresetId) {
+ // A temporary session may already have spent a billed call before the
+ // process stopped, and nothing on disk can say whether it did.
+ // Recovering it as queued work would silently repeat that spend on the
+ // next boot, so it is recorded as consumed and left for the user to
+ // resend deliberately.
+ const queuedIndex = queuedMessages.findIndex((queued) => queued.id === message.id);
+ if (queuedIndex >= 0) queuedMessages.splice(queuedIndex, 1);
+ recentMessageIds.push(message.id);
+ recentMessageFingerprints.push({
+ id: message.id,
+ fingerprint: persistentMindMessageFingerprint(message),
+ });
+ } else if (!seenQueued.has(message.id)) {
+ queuedMessages.unshift(message);
+ if (queuedMessages.length > PERSISTENT_MIND_LIMITS.MAX_QUEUED_MESSAGES) queuedMessages.pop();
+ }
}
} else if (!selfWake) {
selfWake = activeTurn.wake;
@@ -464,6 +495,41 @@ export function takeNextPersistentMindWake(raw, now = Date.now()) {
return { state: { ...state, selfWake: null }, wake: state.selfWake, dueAt: now };
}
+/**
+ * Does abandoning this wake risk repeating work the user may already be billed for?
+ *
+ * Only an explicitly selected temporary thinking session does: it is the one
+ * route the user opted into per-message, and it may sit on an account-backed
+ * provider. The home profile is the mind's ordinary heartbeat, so a self-wake
+ * or an ordinary message still requeues and retries as before.
+ */
+export function persistentMindWakeConsumesAttempt(wake) {
+ return wake?.kind === 'message' && Boolean(wake.message?.thinkingPresetId);
+}
+
+/**
+ * Retire a wake WITHOUT requeueing it, recording its id and fingerprint so an
+ * idempotent client retry reads as a completed duplicate rather than as new
+ * work. Resuming a temporary session is then an explicit user decision (a fresh
+ * message id), never an automatic replay.
+ */
+export function holdPersistentMindWake(raw, wake) {
+ const state = normalizePersistentMindState(raw);
+ const sanitized = sanitizeWake(wake);
+ if (sanitized?.kind !== 'message') return state;
+ const { id } = sanitized.message;
+ return {
+ ...state,
+ queuedMessages: state.queuedMessages.filter((message) => message.id !== id),
+ recentMessageIds: [...state.recentMessageIds.filter((entry) => entry !== id), id]
+ .slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),
+ recentMessageFingerprints: [
+ ...state.recentMessageFingerprints.filter((entry) => entry.id !== id),
+ { id, fingerprint: persistentMindMessageFingerprint(sanitized.message) },
+ ].slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),
+ };
+}
+
export function requeuePersistentMindWake(raw, wake) {
const state = normalizePersistentMindState(raw);
const sanitized = sanitizeWake(wake);
diff --git a/server/lib/persistentMind.test.js b/server/lib/persistentMind.test.js
index 3ace92053f..1e40564ee3 100644
--- a/server/lib/persistentMind.test.js
+++ b/server/lib/persistentMind.test.js
@@ -2,6 +2,9 @@ import { describe, expect, it } from 'vitest';
import {
PERSISTENT_MIND_LIMITS,
createDefaultPersistentMindState,
+ holdPersistentMindWake,
+ persistentMindMessageFingerprint,
+ persistentMindWakeConsumesAttempt,
nextPersistentMindWakeAt,
normalizePersistentMindState,
persistentMindBackoffMs,
@@ -267,4 +270,66 @@ describe('persistent mind state', () => {
expect(Object.keys(smuggled.callHistory[0]).sort()).toEqual(['at', 'reason', 'source']);
expect(normalizePersistentMindState({ callHistory: [{ reason: 'no timestamp' }, { at: 'not-a-date' }] }).callHistory).toEqual([]);
});
+
+ it('keeps a message-level temporary thinking session durable and out of the default route', () => {
+ const message = { id: 'message-1', text: 'Try the deep model.', thinkingPresetId: 'deep', createdAt: iso(1) };
+ const state = normalizePersistentMindState({ enabled: true, started: true, queuedMessages: [message] });
+ expect(state.queuedMessages[0].thinkingPresetId).toBe('deep');
+
+ // Hand-edited or downgraded state cannot smuggle in an unusable selection.
+ expect(normalizePersistentMindState({
+ enabled: true, started: true, queuedMessages: [{ ...message, thinkingPresetId: '../escape' }],
+ }).queuedMessages[0].thinkingPresetId).toBeUndefined();
+
+ // The selection is content: the same text on another model is a different
+ // request, but a message without one must hash exactly as it always did.
+ expect(persistentMindMessageFingerprint(message))
+ .not.toBe(persistentMindMessageFingerprint({ ...message, thinkingPresetId: 'fast' }));
+ expect(persistentMindMessageFingerprint({ id: 'message-1', text: 'Try the deep model.' }))
+ .toBe(persistentMindMessageFingerprint({ id: 'message-1', text: 'Try the deep model.', thinkingPresetId: '' }));
+ });
+
+ it('never automatically replays a temporary session whose provider span may already have opened', () => {
+ const temporary = { kind: 'message', message: { id: 'paid-1', text: 'Deep pass please.', thinkingPresetId: 'deep', createdAt: iso(1) } };
+ const ordinary = { kind: 'message', message: { id: 'plain-1', text: 'Ordinary.', createdAt: iso(1) } };
+ expect(persistentMindWakeConsumesAttempt(temporary)).toBe(true);
+ expect(persistentMindWakeConsumesAttempt(ordinary)).toBe(false);
+ expect(persistentMindWakeConsumesAttempt({ kind: 'self', id: 'wake-1' })).toBe(false);
+
+ const base = { enabled: true, started: true };
+ // An ordinary interrupted message still retries on its own.
+ expect(requeuePersistentMindWake(base, ordinary).queuedMessages.map((m) => m.id)).toEqual(['plain-1']);
+
+ const held = holdPersistentMindWake(base, temporary);
+ expect(held.queuedMessages).toEqual([]);
+ expect(held.recentMessageIds).toEqual(['paid-1']);
+ expect(held.recentMessageFingerprints).toEqual([
+ { id: 'paid-1', fingerprint: persistentMindMessageFingerprint(temporary.message) },
+ ]);
+ // The recorded fingerprint is the one an idempotent same-id retry computes,
+ // so the retry reads as a completed duplicate instead of new paid work.
+ expect(held.recentMessageFingerprints[0].fingerprint)
+ .not.toBe(persistentMindMessageFingerprint({ ...temporary.message, thinkingPresetId: 'fast' }));
+ });
+
+ it('retires, rather than requeues, a temporary session that a restart found mid-turn', () => {
+ const message = { id: 'paid-1', text: 'Deep pass please.', thinkingPresetId: 'deep', createdAt: iso(1) };
+ const recovered = normalizePersistentMindState({
+ enabled: true,
+ started: false,
+ activeTurn: { id: 'mind-turn-1', wake: { kind: 'message', message }, startedAt: iso(1) },
+ });
+ expect(recovered.activeTurn).toBeNull();
+ expect(recovered.queuedMessages).toEqual([]);
+ expect(recovered.recentMessageIds).toEqual(['paid-1']);
+
+ // An ordinary message keeps its free, automatic restart recovery.
+ const ordinary = normalizePersistentMindState({
+ enabled: true,
+ started: false,
+ activeTurn: { id: 'mind-turn-2', wake: { kind: 'message', message: { id: 'plain-1', text: 'Ordinary.', createdAt: iso(1) } }, startedAt: iso(1) },
+ });
+ expect(ordinary.queuedMessages.map((item) => item.id)).toEqual(['plain-1']);
+ expect(ordinary.recentMessageIds).toEqual([]);
+ });
});
diff --git a/server/lib/persistentMindThinkingPresets.js b/server/lib/persistentMindThinkingPresets.js
new file mode 100644
index 0000000000..03936d71bc
--- /dev/null
+++ b/server/lib/persistentMindThinkingPresets.js
@@ -0,0 +1,116 @@
+/**
+ * Named temporary thinking presets for the persistent CoS mind.
+ *
+ * `persistentMindProfile.js` owns the mind's ONE home route — the identity it
+ * wakes on by default. This module owns the user's saved alternates: exact
+ * provider/model/effort routes that a single explicitly-selected message may
+ * borrow for one turn. A preset is inert storage. Saving, editing, or removing
+ * one never starts a mind, never contacts a provider, and never changes which
+ * route the next ordinary message or scheduled wake takes.
+ *
+ * Presets are deliberately NOT a fallback pool. Resolution is exact-or-refuse
+ * (`services/persistentMindProfile.js`), because a mind answering on a route
+ * the user did not select is a different identity, not a recovery.
+ */
+
+import { z } from 'zod';
+import { EFFORT_LEVELS } from './providerModels.js';
+
+export const PERSISTENT_MIND_THINKING_PRESETS_SCHEMA_VERSION = 1;
+
+export const PERSISTENT_MIND_THINKING_PRESET_LIMITS = Object.freeze({
+ MAX_PRESETS: 20,
+ ID_MAX: 64,
+ LABEL_MAX: 80,
+ PROVIDER_ID_MAX: 100,
+ MODEL_MAX: 200,
+});
+
+const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
+
+export const persistentMindThinkingPresetSchema = z.object({
+ id: z.string().trim().min(1).max(PERSISTENT_MIND_THINKING_PRESET_LIMITS.ID_MAX).regex(ID_PATTERN),
+ label: z.string().trim().max(PERSISTENT_MIND_THINKING_PRESET_LIMITS.LABEL_MAX).optional(),
+ providerId: z.string().trim().min(1).max(PERSISTENT_MIND_THINKING_PRESET_LIMITS.PROVIDER_ID_MAX),
+ model: z.string().trim().min(1).max(PERSISTENT_MIND_THINKING_PRESET_LIMITS.MODEL_MAX),
+ // Empty is the UI's explicit "provider default effort" sentinel, mirroring
+ // the home profile so one selector can drive both.
+ effort: z.union([z.literal(''), z.enum(EFFORT_LEVELS)]).optional(),
+}).strict();
+
+export const persistentMindThinkingPresetsSchema = z.object({
+ schemaVersion: z.literal(PERSISTENT_MIND_THINKING_PRESETS_SCHEMA_VERSION).optional(),
+ // A list PATCH replaces the whole list: there is no stable way to express
+ // "remove this one entry" through a merge, and a partial merge would silently
+ // resurrect a preset the user just deleted.
+ presets: z.array(persistentMindThinkingPresetSchema)
+ .max(PERSISTENT_MIND_THINKING_PRESET_LIMITS.MAX_PRESETS),
+}).strict();
+
+export function createDefaultPersistentMindThinkingPresets() {
+ return {
+ schemaVersion: PERSISTENT_MIND_THINKING_PRESETS_SCHEMA_VERSION,
+ presets: [],
+ };
+}
+
+const text = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
+
+/**
+ * Coerce a preset reference to the exact stored id, or null.
+ *
+ * Exported so the durable message record validates a selection against the
+ * same rule the preset list itself enforces, rather than re-deriving it.
+ */
+export function asPersistentMindThinkingPresetId(value) {
+ const id = text(value, PERSISTENT_MIND_THINKING_PRESET_LIMITS.ID_MAX);
+ return ID_PATTERN.test(id) ? id : null;
+}
+
+const sanitizePreset = (value) => {
+ const id = asPersistentMindThinkingPresetId(value?.id);
+ const providerId = text(value?.providerId, PERSISTENT_MIND_THINKING_PRESET_LIMITS.PROVIDER_ID_MAX);
+ const model = text(value?.model, PERSISTENT_MIND_THINKING_PRESET_LIMITS.MODEL_MAX);
+ // A preset without an exact route cannot be resolved without inventing one,
+ // so it is dropped rather than stored as a half-pin.
+ if (!id || !providerId || !model) return null;
+ const effort = text(value?.effort, 20);
+ return {
+ id,
+ label: text(value?.label, PERSISTENT_MIND_THINKING_PRESET_LIMITS.LABEL_MAX) || `${providerId} / ${model}`,
+ providerId,
+ model,
+ effort: EFFORT_LEVELS.includes(effort) ? effort : '',
+ };
+};
+
+/** Normalize legacy or hand-edited config without inventing a route. */
+export function normalizePersistentMindThinkingPresets(raw) {
+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
+ const presets = [];
+ const seen = new Set();
+ for (const candidate of Array.isArray(source.presets) ? source.presets : []) {
+ const preset = sanitizePreset(candidate);
+ if (!preset || seen.has(preset.id)) continue;
+ seen.add(preset.id);
+ presets.push(preset);
+ if (presets.length >= PERSISTENT_MIND_THINKING_PRESET_LIMITS.MAX_PRESETS) break;
+ }
+ return { schemaVersion: PERSISTENT_MIND_THINKING_PRESETS_SCHEMA_VERSION, presets };
+}
+
+/** Apply a settings patch. An absent `presets` key preserves the stored list. */
+export function mergePersistentMindThinkingPresets(previous, update) {
+ const prior = normalizePersistentMindThinkingPresets(previous);
+ const patch = update && typeof update === 'object' && !Array.isArray(update) ? update : {};
+ return normalizePersistentMindThinkingPresets(
+ Array.isArray(patch.presets) ? { presets: patch.presets } : prior,
+ );
+}
+
+/** Look up one saved preset. Returns null for an unknown or removed id. */
+export function findPersistentMindThinkingPreset(raw, presetId) {
+ const id = asPersistentMindThinkingPresetId(presetId);
+ if (!id) return null;
+ return normalizePersistentMindThinkingPresets(raw).presets.find((preset) => preset.id === id) || null;
+}
diff --git a/server/lib/persistentMindThinkingPresets.test.js b/server/lib/persistentMindThinkingPresets.test.js
new file mode 100644
index 0000000000..9c45b6529e
--- /dev/null
+++ b/server/lib/persistentMindThinkingPresets.test.js
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+import {
+ createDefaultPersistentMindThinkingPresets,
+ findPersistentMindThinkingPreset,
+ mergePersistentMindThinkingPresets,
+ normalizePersistentMindThinkingPresets,
+ PERSISTENT_MIND_THINKING_PRESET_LIMITS,
+ persistentMindThinkingPresetsSchema,
+} from './persistentMindThinkingPresets.js';
+
+const preset = (overrides = {}) => ({
+ id: 'deep',
+ label: 'Deep pass',
+ providerId: 'example-provider',
+ model: 'example-model',
+ effort: 'max',
+ ...overrides,
+});
+
+describe('persistent mind thinking presets', () => {
+ it('ships no presets, so an upgraded install keeps exactly its pinned default route', () => {
+ expect(createDefaultPersistentMindThinkingPresets()).toEqual({ schemaVersion: 1, presets: [] });
+ expect(normalizePersistentMindThinkingPresets(undefined)).toEqual({ schemaVersion: 1, presets: [] });
+ expect(normalizePersistentMindThinkingPresets({ presets: 'not-a-list' })).toEqual({ schemaVersion: 1, presets: [] });
+ });
+
+ it('drops half-pinned entries rather than storing a route that has to be guessed', () => {
+ const { presets } = normalizePersistentMindThinkingPresets({
+ presets: [
+ preset(),
+ preset({ id: 'no-model', model: '' }),
+ preset({ id: 'no-provider', providerId: ' ' }),
+ preset({ id: '../escape' }),
+ preset({ id: '' }),
+ ],
+ });
+ expect(presets.map((entry) => entry.id)).toEqual(['deep']);
+ });
+
+ it('never turns an unusable effort into a pin, and names an unlabeled preset by its route', () => {
+ const { presets } = normalizePersistentMindThinkingPresets({
+ presets: [preset({ effort: 'turbo' }), preset({ id: 'plain', label: ' ', effort: undefined })],
+ });
+ expect(presets[0].effort).toBe('');
+ expect(presets[1]).toMatchObject({ label: 'example-provider / example-model', effort: '' });
+ });
+
+ it('keeps the first of a duplicated id and caps the stored list', () => {
+ const { presets } = normalizePersistentMindThinkingPresets({
+ presets: [
+ preset({ model: 'first-model' }),
+ preset({ model: 'second-model' }),
+ ...Array.from({ length: 40 }, (_, index) => preset({ id: `extra-${index}` })),
+ ],
+ });
+ expect(presets[0].model).toBe('first-model');
+ expect(presets).toHaveLength(PERSISTENT_MIND_THINKING_PRESET_LIMITS.MAX_PRESETS);
+ });
+
+ it('replaces the whole list on a list patch so a delete cannot be resurrected by a merge', () => {
+ const stored = { presets: [preset(), preset({ id: 'fast', model: 'fast-model' })] };
+ expect(mergePersistentMindThinkingPresets(stored, { presets: [preset()] }).presets.map((p) => p.id))
+ .toEqual(['deep']);
+ expect(mergePersistentMindThinkingPresets(stored, { presets: [] }).presets).toEqual([]);
+ // An unrelated settings PATCH must not clear presets the user saved.
+ expect(mergePersistentMindThinkingPresets(stored, {}).presets.map((p) => p.id)).toEqual(['deep', 'fast']);
+ });
+
+ it('looks up only an exact saved id', () => {
+ const stored = { presets: [preset()] };
+ expect(findPersistentMindThinkingPreset(stored, 'deep')).toMatchObject({ providerId: 'example-provider' });
+ expect(findPersistentMindThinkingPreset(stored, ' deep ')).toMatchObject({ id: 'deep' });
+ expect(findPersistentMindThinkingPreset(stored, 'removed')).toBeNull();
+ expect(findPersistentMindThinkingPreset(stored, '')).toBeNull();
+ expect(findPersistentMindThinkingPreset(stored, null)).toBeNull();
+ });
+
+ it('rejects an unusable preset at the API boundary instead of silently normalizing it away', () => {
+ expect(persistentMindThinkingPresetsSchema.safeParse({ presets: [preset()] }).success).toBe(true);
+ expect(persistentMindThinkingPresetsSchema.safeParse({ presets: [preset({ effort: '' })] }).success).toBe(true);
+ expect(persistentMindThinkingPresetsSchema.safeParse({ presets: [preset({ effort: 'turbo' })] }).success).toBe(false);
+ expect(persistentMindThinkingPresetsSchema.safeParse({ presets: [preset({ model: '' })] }).success).toBe(false);
+ expect(persistentMindThinkingPresetsSchema.safeParse({ presets: [preset({ id: 'has space' })] }).success).toBe(false);
+ expect(persistentMindThinkingPresetsSchema.safeParse({ presets: [preset()], extra: true }).success).toBe(false);
+ expect(persistentMindThinkingPresetsSchema.safeParse({
+ presets: Array.from({ length: PERSISTENT_MIND_THINKING_PRESET_LIMITS.MAX_PRESETS + 1 }, (_, i) => preset({ id: `p${i}` })),
+ }).success).toBe(false);
+ });
+});
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.js
index 2b6cbb1452..0842b33458 100644
--- a/server/routes/cosMindRoutes.js
+++ b/server/routes/cosMindRoutes.js
@@ -19,6 +19,10 @@ import {
parsePersistentMindCursor,
} from '../lib/persistentMindTrajectory.js';
import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
+import {
+ normalizePersistentMindThinkingPresets,
+ persistentMindThinkingPresetSchema,
+} from '../lib/persistentMindThinkingPresets.js';
import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
import { publicPersistentMindState } from '../lib/persistentMindPublic.js';
import { validateRequest } from '../lib/validation.js';
@@ -77,6 +81,9 @@ const messageSchema = z.object({
id: idempotencyId,
text: messageText,
images: z.array(imageReference).max(PERSISTENT_MIND_LIMITS.MAX_MESSAGE_IMAGES).optional(),
+ // "Send with another model": one saved preset, for this message's single turn
+ // only. Absent means the mind's unchanged default route.
+ thinkingPresetId: persistentMindThinkingPresetSchema.shape.id.optional(),
}).strict().superRefine((value, ctx) => {
const images = Array.isArray(value.images) ? value.images : [];
const ids = images.map((image) => typeof image === 'string' ? image : image.attachmentId);
@@ -181,6 +188,7 @@ router.get('/mind', asyncHandler(async (req, res) => {
thinkingInterface: profile.thinkingInterface,
wakeIntervalMinutes: profile.wakeIntervalMinutes,
},
+ thinkingPresets: normalizePersistentMindThinkingPresets(root.config?.persistentMindThinkingPresets),
capabilities,
harness: persistentMindHarnessInfo(provider),
imageCapability,
diff --git a/server/routes/cosStatusRoutes.js b/server/routes/cosStatusRoutes.js
index fc55099ac4..cce050c4f7 100644
--- a/server/routes/cosStatusRoutes.js
+++ b/server/routes/cosStatusRoutes.js
@@ -19,6 +19,7 @@ import { AVATAR_STYLE_IDS } from '../../client/src/lib/avatarStyles.js';
import { BUDGET_LIMIT_FIELDS } from '../lib/domainBudgets.js';
import { persistentMindCapabilitiesSchema } from '../lib/persistentMindCapabilities.js';
import { persistentMindProfileSchema } from '../lib/persistentMindProfile.js';
+import { persistentMindThinkingPresetsSchema } from '../lib/persistentMindThinkingPresets.js';
import { persistentMindPromptSchema } from '../lib/persistentMindPrompt.js';
const router = Router();
@@ -71,6 +72,9 @@ export const cosConfigSchema = z.object({
// A durable reasoning route for the persistent mind. It is separate from
// `alwaysOn`: saving or enabling this profile never starts background work.
persistentMindProfile: persistentMindProfileSchema.optional(),
+ // Saved alternates one message may borrow for a single turn. Storing them
+ // changes nothing about the route the mind wakes on by default.
+ persistentMindThinkingPresets: persistentMindThinkingPresetsSchema.optional(),
persistentMindPrompt: persistentMindPromptSchema.optional(),
// Separate opt-in action grant: an enabled reasoning profile does not imply
// authority to create and execute agent tasks.
diff --git a/server/services/cos.js b/server/services/cos.js
index 59028bf592..8aea518c06 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -39,6 +39,7 @@ import { normalizeDomainBudgets, remainingActionBudget } from '../lib/domainBudg
import { mergePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';
import { mergePersistentMindProfile, normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
import { mergePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
+import { mergePersistentMindThinkingPresets } from '../lib/persistentMindThinkingPresets.js';
import { getDomainBudgetStatus } from './domainUsage.js';
import { pendingCosActionReservations } from './cosAdmissionReservations.js';
// Dependency-free leaf holding the shared agent maps + the runner-mode flag,
@@ -246,6 +247,7 @@ export async function updateConfig(updates) {
const priorPersistentMindCapabilities = current.persistentMindCapabilities;
const priorPersistentMindProfile = current.persistentMindProfile;
const priorPersistentMindPrompt = current.persistentMindPrompt;
+ const priorPersistentMindThinkingPresets = current.persistentMindThinkingPresets;
const next = { ...current, ...updates };
if (updates.domainAutonomy !== undefined) {
next.domainAutonomy = normalizeDomainAutonomy({
@@ -275,6 +277,12 @@ export async function updateConfig(updates) {
updates.persistentMindCapabilities,
);
}
+ if (updates.persistentMindThinkingPresets !== undefined) {
+ next.persistentMindThinkingPresets = mergePersistentMindThinkingPresets(
+ priorPersistentMindThinkingPresets,
+ updates.persistentMindThinkingPresets,
+ );
+ }
if (updates.persistentMindPrompt !== undefined) {
next.persistentMindPrompt = mergePersistentMindPrompt(
priorPersistentMindPrompt,
diff --git a/server/services/cosState.js b/server/services/cosState.js
index 1441dcbb46..0b6f8dea23 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -16,6 +16,10 @@ import { createDefaultPersistentMindState, normalizePersistentMindState } from '
import { createDefaultPersistentMindCapabilities, normalizePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';
import { createDefaultPersistentMindProfile, normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
import { createDefaultPersistentMindPrompt, normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
+import {
+ createDefaultPersistentMindThinkingPresets,
+ normalizePersistentMindThinkingPresets,
+} from '../lib/persistentMindThinkingPresets.js';
import { DEFAULT_ALWAYS_APPROVE_KINDS } from './taskLearning/safetyKind.js';
export const STATE_FILE = join(PATHS.cos, 'state.json');
@@ -88,6 +92,7 @@ export const DEFAULT_CONFIG = {
// Persisting a profile is not consent to wake the mind. Fresh and upgraded
// installs stay disabled until the user explicitly starts it.
persistentMindProfile: createDefaultPersistentMindProfile(),
+ persistentMindThinkingPresets: createDefaultPersistentMindThinkingPresets(),
persistentMindPrompt: createDefaultPersistentMindPrompt(),
// Action grants are independent of the provider profile. Existing and fresh
// conversation-only installs never gain task-creation authority on upgrade.
@@ -207,6 +212,7 @@ function mergeStoredConfig(storedConfig) {
...persistedConfig,
persistentMindCapabilities: normalizePersistentMindCapabilities(persistedConfig.persistentMindCapabilities),
persistentMindProfile: normalizePersistentMindProfile(persistedConfig.persistentMindProfile),
+ persistentMindThinkingPresets: normalizePersistentMindThinkingPresets(persistedConfig.persistentMindThinkingPresets),
persistentMindPrompt: normalizePersistentMindPrompt(persistedConfig.persistentMindPrompt),
};
}
diff --git a/server/services/persistentMindProfile.js b/server/services/persistentMindProfile.js
index d66a94f13a..ec5d54b8bb 100644
--- a/server/services/persistentMindProfile.js
+++ b/server/services/persistentMindProfile.js
@@ -1,14 +1,19 @@
/**
- * Resolve the persistent mind's pinned text-reasoning profile.
+ * Resolve the persistent mind's pinned text-reasoning route.
*
* This deliberately has no fallback path. A mind waking on a different
* provider/model than the one the user selected would violate their inference
* choice. Identity and memory remain independent of that selection. It also does not start a model, fetch a catalog, or generate
* text: it only reads the already-configured provider and status services.
+ *
+ * Two routes resolve through the same exact-or-refuse check: the home profile
+ * every ordinary message and scheduled wake uses, and a saved thinking preset
+ * that one explicitly selected message borrows for a single turn.
*/
import { effortLevelsForProvider } from '../lib/providerModels.js';
import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
+import { findPersistentMindThinkingPreset } from '../lib/persistentMindThinkingPresets.js';
import { getProviderById } from './providers.js';
import { getProviderStatus, isProviderAvailable } from './providerStatus.js';
@@ -17,39 +22,81 @@ const providerModelIds = (provider) => (provider?.models || [])
.filter(Boolean);
/**
- * Resolve a configured profile to one exact provider route, or a visible
- * failure suitable for the supervisor's degraded state.
+ * Validate one exact provider/model/effort selection against the live registry.
+ * Every failure is a refusal: nothing here may substitute a nearby route.
*/
-export async function resolvePersistentMindProfile(rawProfile) {
- const profile = normalizePersistentMindProfile(rawProfile);
- if (!profile.enabled) return { ok: false, error: 'Persistent mind profile is disabled' };
- if (!profile.providerId || !profile.model) {
- return { ok: false, error: 'Persistent mind profile requires a provider and model' };
- }
+async function resolveExactRoute({ providerId, model, effort, noun, incompleteError }) {
+ if (!providerId || !model) return { ok: false, error: incompleteError };
- const provider = await getProviderById(profile.providerId);
+ const provider = await getProviderById(providerId);
if (!provider || provider.enabled === false) {
- return { ok: false, error: `Pinned provider "${profile.providerId}" is unavailable` };
+ return { ok: false, error: `${noun} provider "${providerId}" is unavailable` };
}
if (!isProviderAvailable(provider.id)) {
const status = getProviderStatus(provider.id);
- return { ok: false, error: status?.message || `Pinned provider "${provider.id}" is unavailable` };
+ return { ok: false, error: status?.message || `${noun} provider "${provider.id}" is unavailable` };
}
const models = providerModelIds(provider);
- if (models.length > 0 && !models.includes(profile.model)) {
- return { ok: false, error: `Pinned model "${profile.model}" is not available from provider "${provider.id}"` };
+ if (models.length > 0 && !models.includes(model)) {
+ return { ok: false, error: `${noun} model "${model}" is not available from provider "${provider.id}"` };
}
- const supportedEfforts = effortLevelsForProvider(provider, profile.model);
- if (profile.effort && (!supportedEfforts || !supportedEfforts.includes(profile.effort))) {
- return { ok: false, error: `Pinned effort "${profile.effort}" is not supported by provider "${provider.id}"` };
+ const supportedEfforts = effortLevelsForProvider(provider, model);
+ if (effort && (!supportedEfforts || !supportedEfforts.includes(effort))) {
+ return { ok: false, error: `${noun} effort "${effort}" is not supported by provider "${provider.id}"` };
}
- return {
- ok: true,
- provider,
+ return { ok: true, provider, model, effort: effort || null };
+}
+
+/**
+ * Resolve a configured profile to one exact provider route, or a visible
+ * failure suitable for the supervisor's degraded state.
+ */
+export async function resolvePersistentMindProfile(rawProfile) {
+ const profile = normalizePersistentMindProfile(rawProfile);
+ if (!profile.enabled) return { ok: false, error: 'Persistent mind profile is disabled' };
+ const route = await resolveExactRoute({
+ providerId: profile.providerId,
model: profile.model,
- effort: profile.effort || null,
+ effort: profile.effort,
+ noun: 'Pinned',
+ incompleteError: 'Persistent mind profile requires a provider and model',
+ });
+ if (!route.ok) return route;
+ return { ...route, temporary: false, presetId: null, presetLabel: null, thinkingInterface: profile.thinkingInterface };
+}
+
+/**
+ * Resolve one message's temporary thinking session.
+ *
+ * The home profile still gates admission: a temporary session borrows a model,
+ * never authority. A removed preset, a retired model, or an effort the provider
+ * dropped is a refusal — the turn must not quietly answer on the default route
+ * the user was deliberately stepping away from.
+ */
+export async function resolvePersistentMindThinkingSession({ presetId, config } = {}) {
+ const profile = normalizePersistentMindProfile(config?.persistentMindProfile);
+ if (!profile.enabled) return { ok: false, error: 'Persistent mind profile is disabled' };
+ const preset = findPersistentMindThinkingPreset(config?.persistentMindThinkingPresets, presetId);
+ if (!preset) {
+ return { ok: false, error: `Temporary thinking preset "${presetId}" is no longer available` };
+ }
+ const route = await resolveExactRoute({
+ providerId: preset.providerId,
+ model: preset.model,
+ effort: preset.effort,
+ noun: `Temporary thinking preset "${preset.label}"`,
+ // Unreachable: normalization drops a preset without both, so this is the
+ // belt-and-braces refusal rather than a route the resolver could invent.
+ incompleteError: `Temporary thinking preset "${preset.label}" requires a provider and model`,
+ });
+ if (!route.ok) return route;
+ return {
+ ...route,
+ temporary: true,
+ presetId: preset.id,
+ presetLabel: preset.label,
thinkingInterface: profile.thinkingInterface,
};
}
diff --git a/server/services/persistentMindProfile.test.js b/server/services/persistentMindProfile.test.js
index 64c7001a12..cab73a0c86 100644
--- a/server/services/persistentMindProfile.test.js
+++ b/server/services/persistentMindProfile.test.js
@@ -14,7 +14,7 @@ vi.mock('./providerStatus.js', () => ({
getProviderStatus: vi.fn(() => mocks.status),
}));
-const { resolvePersistentMindProfile } = await import('./persistentMindProfile.js');
+const { resolvePersistentMindProfile, resolvePersistentMindThinkingSession } = await import('./persistentMindProfile.js');
const profile = { enabled: true, providerId: 'local', model: 'reasoner', effort: '', thinkingInterface: 'text' };
@@ -54,3 +54,55 @@ describe('resolvePersistentMindProfile', () => {
.toMatchObject({ ok: false, error: /not supported/ });
});
});
+
+describe('resolvePersistentMindThinkingSession', () => {
+ const config = {
+ persistentMindProfile: profile,
+ persistentMindThinkingPresets: {
+ presets: [
+ { id: 'deep', label: 'Deep pass', providerId: 'local', model: 'reasoner', effort: '' },
+ { id: 'retired', label: 'Retired', providerId: 'local', model: 'removed-model', effort: '' },
+ { id: 'strained', label: 'Strained', providerId: 'local', model: 'reasoner', effort: 'high' },
+ ],
+ },
+ };
+
+ beforeEach(() => {
+ mocks.provider = { id: 'local', type: 'api', models: ['reasoner'] };
+ mocks.available = true;
+ mocks.status = { message: 'offline' };
+ });
+
+ it('borrows one exact alternate route while the mind keeps its own identity', async () => {
+ await expect(resolvePersistentMindThinkingSession({ presetId: 'deep', config })).resolves.toMatchObject({
+ ok: true,
+ temporary: true,
+ presetId: 'deep',
+ presetLabel: 'Deep pass',
+ provider: { id: 'local' },
+ model: 'reasoner',
+ effort: null,
+ thinkingInterface: 'text',
+ });
+ });
+
+ it('refuses instead of quietly answering on the default the user stepped away from', async () => {
+ await expect(resolvePersistentMindThinkingSession({ presetId: 'removed', config })).resolves
+ .toEqual({ ok: false, error: 'Temporary thinking preset "removed" is no longer available' });
+ await expect(resolvePersistentMindThinkingSession({ presetId: 'retired', config })).resolves
+ .toMatchObject({ ok: false, error: /not available from provider/ });
+ await expect(resolvePersistentMindThinkingSession({ presetId: 'strained', config })).resolves
+ .toMatchObject({ ok: false, error: /not supported/ });
+
+ mocks.available = false;
+ await expect(resolvePersistentMindThinkingSession({ presetId: 'deep', config })).resolves
+ .toEqual({ ok: false, error: 'offline' });
+ });
+
+ it('borrows a model, never authority: a disabled profile admits no temporary session', async () => {
+ await expect(resolvePersistentMindThinkingSession({
+ presetId: 'deep',
+ config: { ...config, persistentMindProfile: { ...profile, enabled: false } },
+ })).resolves.toEqual({ ok: false, error: 'Persistent mind profile is disabled' });
+ });
+});
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index 4216ea41be..3f6fe08c69 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -17,6 +17,7 @@ import {
PERSISTENT_MIND_LIMITS,
PERSISTENT_MIND_IMAGE_EXTENSIONS,
createDefaultPersistentMindState,
+ holdPersistentMindWake,
isPersistentMindAttachmentId,
normalizePersistentMindAttachment,
normalizePersistentMindMessageImage,
@@ -25,6 +26,7 @@ import {
persistentMindMessageFingerprint,
persistentMindBackoffMs,
persistentMindTurnIsStale,
+ persistentMindWakeConsumesAttempt,
publicPersistentMindAttachment,
requeuePersistentMindWake,
takeNextPersistentMindWake,
@@ -46,11 +48,15 @@ import { acquireLocalEndpointProviderSlot } from './cosLocalEndpointSlots.js';
import { acquireCosActionReservation, acquireCosGlobalSlot } from './cosAdmissionReservations.js';
import { appendMindEvent } from './agentRunEventLog.js';
import { preparePersistentMindContext } from './persistentMindContext.js';
-import { resolvePersistentMindProfile } from './persistentMindProfile.js';
+import { resolvePersistentMindProfile, resolvePersistentMindThinkingSession } from './persistentMindProfile.js';
import { isUpdateInProgress } from './updateChecker.js';
import { publicPersistentMindState } from '../lib/persistentMindPublic.js';
import { normalizePersistentMindProfile, persistentMindWakeIntervalMs } from '../lib/persistentMindProfile.js';
import { getProviderById } from './providers.js';
+import {
+ findPersistentMindThinkingPreset,
+ PERSISTENT_MIND_THINKING_PRESET_LIMITS,
+} from '../lib/persistentMindThinkingPresets.js';
import {
imageCapabilityAllowsAttempt,
resolvePersistentMindImageCapability,
@@ -134,12 +140,13 @@ const claimedAttachmentsForMessage = (mind, messageId) => mind.pendingAttachment
))
.map(({ attachment }) => attachment);
-const messageFromAttachments = ({ id, text, createdAt, attachments }) => ({
+const messageFromAttachments = ({ id, text, createdAt, attachments, thinkingPresetId }) => ({
id,
text,
...(attachments.length > 0 ? {
images: attachments.map(normalizePersistentMindMessageImage).filter(Boolean),
} : {}),
+ ...(thinkingPresetId ? { thinkingPresetId } : {}),
createdAt,
});
@@ -522,7 +529,15 @@ async function interruptActiveTurn(reason, status, { retry = false, expectedTurn
}
const interrupted = Boolean(mind.activeTurn);
let next = mind;
- if (mind.activeTurn) next = requeuePersistentMindWake(next, mind.activeTurn.wake);
+ if (mind.activeTurn) {
+ // An interrupted temporary thinking session is an uncertain consumed
+ // attempt: the abort races whatever the provider already started, and no
+ // durable record can say whether that call was billed. Retire it instead
+ // of requeueing, so resuming it stays an explicit user decision.
+ next = persistentMindWakeConsumesAttempt(mind.activeTurn.wake)
+ ? holdPersistentMindWake(next, mind.activeTurn.wake)
+ : requeuePersistentMindWake(next, mind.activeTurn.wake);
+ }
const failureCount = retry ? next.failureCount + 1 : next.failureCount;
return {
mind: {
@@ -554,10 +569,21 @@ async function interruptActiveTurn(reason, status, { retry = false, expectedTurn
return { state: result.state, interrupted: result.value?.interrupted === true };
}
-async function parkActiveTurn(turnId, reason, status = 'waiting', retryAt = null) {
+/**
+ * Return a claimed turn to the queue with a visible reason.
+ *
+ * `consumedAttempt` says the provider span had already opened, so a temporary
+ * thinking session must not be replayed automatically. Every refusal decided
+ * before that point — an unresolvable route, an unavailable adapter, a busy
+ * local endpoint — spent nothing and still requeues normally.
+ */
+async function parkActiveTurn(turnId, reason, status = 'waiting', { retryAt = null, consumedAttempt = false } = {}) {
const result = await mutateMindState((mind) => {
- if (mind.activeTurn?.id !== turnId) return { mind };
- const next = requeuePersistentMindWake(mind, mind.activeTurn.wake);
+ if (mind.activeTurn?.id !== turnId) return { mind, value: false };
+ const held = consumedAttempt && persistentMindWakeConsumesAttempt(mind.activeTurn.wake);
+ const next = held
+ ? holdPersistentMindWake(mind, mind.activeTurn.wake)
+ : requeuePersistentMindWake(mind, mind.activeTurn.wake);
const failureCount = next.failureCount + 1;
return {
mind: {
@@ -569,6 +595,7 @@ async function parkActiveTurn(turnId, reason, status = 'waiting', retryAt = null
lastError: reason,
nextEligibleWakeAt: retryAt || new Date(Date.now() + persistentMindBackoffMs(failureCount)).toISOString(),
},
+ value: held,
};
});
await appendMindEvent({
@@ -576,7 +603,7 @@ async function parkActiveTurn(turnId, reason, status = 'waiting', retryAt = null
mindId: result.state.mindId,
turnId,
eventId: `mind-failed:${turnId}:${status}`,
- data: { status, error: reason, retryAt },
+ data: { status, error: reason, retryAt, consumedAttempt: result.value === true },
});
emitMindStatus(result.state);
return result.state;
@@ -623,6 +650,7 @@ async function claimNextTurn() {
wakeKind: result.value.wake.kind,
wakeId: result.value.wake.id || null,
messageId: result.value.wake.message?.id || null,
+ thinkingPresetId: result.value.wake.message?.thinkingPresetId || null,
reason: result.value.wake.reason || null,
},
});
@@ -745,6 +773,7 @@ async function completeTurn(turnId, result, generation) {
providerId: result?.providerId || null,
model: result?.model || null,
effort: result?.effort || null,
+ thinkingPresetId: result?.thinkingPresetId || null,
summaryText: typeof result?.summary === 'string' ? result.summary : null,
},
});
@@ -864,10 +893,22 @@ async function runOnePersistentMindTurn() {
let release = () => {};
let runStartedAt = null;
try {
- // The profile is resolved before an adapter can run. This is a read-only
+ // The route is resolved before an adapter can run. This is a read-only
// catalog/status check: no alternate provider, model pull, or generation
// is allowed while deciding whether the pinned mind can wake.
- const profile = await resolvePersistentMindProfile(root.config?.persistentMindProfile);
+ //
+ // A message the user explicitly sent with another model resolves its saved
+ // preset here instead of the home profile. Only that one message carries
+ // it: the next ordinary message and every scheduled wake read the
+ // unchanged default, because the selection lives on the message rather
+ // than in config. A preset that has since been removed, retired, or
+ // narrowed is a refusal — never a silent return to the default route.
+ const thinkingPresetId = turn.wake.kind === 'message'
+ ? turn.wake.message.thinkingPresetId || null
+ : null;
+ const profile = thinkingPresetId
+ ? await resolvePersistentMindThinkingSession({ presetId: thinkingPresetId, config: root.config })
+ : await resolvePersistentMindProfile(root.config?.persistentMindProfile);
if (!profile.ok) {
await parkActiveTurn(turn.id, profile.error, 'degraded');
return;
@@ -877,7 +918,7 @@ async function runOnePersistentMindTurn() {
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', adapterPrepared?.retryAt || null);
+ await parkActiveTurn(turn.id, adapterPrepared?.error || 'Persistent mind provider is unavailable', 'degraded', { retryAt: adapterPrepared?.retryAt || null });
return;
}
// Existing adapters only named their transport provider; missing model or
@@ -947,6 +988,7 @@ async function runOnePersistentMindTurn() {
providerId: prepared.provider.id,
model: prepared.model || null,
effort: prepared.effort || null,
+ thinkingPresetId,
contextChars: context.chars,
contextSummaryState: context.summaryState,
},
@@ -992,6 +1034,7 @@ async function runOnePersistentMindTurn() {
providerId: prepared.provider.id,
model: prepared.model || null,
effort: prepared.effort || null,
+ thinkingPresetId,
summaryText: typeof result?.summary === 'string' ? result.summary : null,
responseChars: typeof result?.output === 'string' ? result.output.length : null,
success: true,
@@ -1002,13 +1045,14 @@ async function runOnePersistentMindTurn() {
providerId: prepared.provider.id,
model: prepared.model || null,
effort: prepared.effort || null,
+ thinkingPresetId,
}, generation);
} catch (error) {
if (generation === runtimeGeneration) {
const message = controller.signal.aborted
? String(controller.signal.reason || 'Persistent mind turn interrupted')
: errorMessage(error);
- await parkActiveTurn(turn.id, message, 'interrupted');
+ await parkActiveTurn(turn.id, message, 'interrupted', { consumedAttempt: runStartedAt != null });
emitLog('warn', `Persistent mind turn interrupted: ${message}`, { turnId: turn.id });
}
} finally {
@@ -1226,20 +1270,46 @@ export async function stopPersistentMind({ waitForTurn = false } = {}) {
return { success: true };
}
-export async function enqueuePersistentMindMessage({ id = randomUUID(), text, images, createdAt = nowIso() } = {}) {
+export async function enqueuePersistentMindMessage({
+ id = randomUUID(),
+ text,
+ images,
+ thinkingPresetId,
+ createdAt = nowIso(),
+} = {}) {
const messageId = typeof id === 'string' ? id.trim().slice(0, 200) : '';
const messageText = normalizeMessageText(text);
const attachmentIds = normalizeRequestedAttachmentIds(images);
+ const presetId = typeof thinkingPresetId === 'string'
+ ? thinkingPresetId.trim().slice(0, PERSISTENT_MIND_THINKING_PRESET_LIMITS.ID_MAX)
+ : '';
if (!messageId || attachmentIds === null || (!messageText && attachmentIds.length === 0)) {
return attachmentFailure('Message id and text or at least one image are required', { code: 'VALIDATION_ERROR' });
}
- if (attachmentIds.length > 0) {
+ if (presetId || attachmentIds.length > 0) {
const root = await loadState();
const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
- const provider = profile.providerId ? await getProviderById(profile.providerId) : null;
- const imageCapability = await resolvePersistentMindImageCapability({ provider, model: profile.model });
- if (!imageCapabilityAllowsAttempt(imageCapability, provider)) {
- return attachmentFailure(imageCapability.reason, { code: 'IMAGE_CAPABILITY_UNSUPPORTED', status: 422 });
+ // Admission reads the saved preset list only — a lookup, never a provider
+ // call, model pull, or generation. Selecting a model must stay free.
+ const preset = presetId
+ ? findPersistentMindThinkingPreset(root.config?.persistentMindThinkingPresets, presetId)
+ : null;
+ if (presetId && !preset) {
+ return attachmentFailure(`Temporary thinking preset "${presetId}" is not available`, {
+ code: 'THINKING_PRESET_UNAVAILABLE',
+ status: 422,
+ });
+ }
+ if (attachmentIds.length > 0) {
+ // Images are checked against the route this message will actually take,
+ // so a text-only alternate cannot accept an image it can never read.
+ const routeProviderId = preset ? preset.providerId : profile.providerId;
+ const routeModel = preset ? preset.model : profile.model;
+ const provider = routeProviderId ? await getProviderById(routeProviderId) : null;
+ const imageCapability = await resolvePersistentMindImageCapability({ provider, model: routeModel });
+ if (!imageCapabilityAllowsAttempt(imageCapability, provider)) {
+ return attachmentFailure(imageCapability.reason, { code: 'IMAGE_CAPABILITY_UNSUPPORTED', status: 422 });
+ }
}
}
const messageCreatedAt = typeof createdAt === 'string' && Number.isFinite(Date.parse(createdAt))
@@ -1262,6 +1332,7 @@ export async function enqueuePersistentMindMessage({ id = randomUUID(), text, im
const requestedFingerprint = persistentMindMessageFingerprint({
text: messageText,
images: attachmentIds,
+ thinkingPresetId: presetId,
});
const recentFingerprint = mind.recentMessageFingerprints.find((entry) => entry.id === messageId)?.fingerprint;
const existingImageIds = existingMessage
@@ -1295,6 +1366,15 @@ export async function enqueuePersistentMindMessage({ id = randomUUID(), text, im
}),
};
}
+ if (existingMessage && (existingMessage.thinkingPresetId || '') !== presetId) {
+ return {
+ mind,
+ value: attachmentFailure('A retry must use the same Persistent Mind thinking preset', {
+ code: 'IDEMPOTENCY_CONFLICT',
+ status: 409,
+ }),
+ };
+ }
if (!sameAttachmentIds(existingImageIds, attachmentIds)) {
return {
mind,
@@ -1317,6 +1397,7 @@ export async function enqueuePersistentMindMessage({ id = randomUUID(), text, im
text: messageText,
createdAt: messageCreatedAt,
attachments: resolved.attachments,
+ thinkingPresetId: presetId,
}),
},
};
@@ -1364,6 +1445,7 @@ export async function enqueuePersistentMindMessage({ id = randomUUID(), text, im
text: messageText,
createdAt: messageCreatedAt,
attachments: resolved.attachments,
+ thinkingPresetId: presetId,
});
return {
mind: {
@@ -1389,6 +1471,7 @@ export async function enqueuePersistentMindMessage({ id = randomUUID(), text, im
messageId,
displayText: acceptedMessage.text,
textChars: acceptedMessage.text.length,
+ thinkingPresetId: acceptedMessage.thinkingPresetId || null,
imageCount: Array.isArray(acceptedMessage.images) ? acceptedMessage.images.length : 0,
images: Array.isArray(acceptedMessage.images)
? acceptedMessage.images.map(normalizePersistentMindMessageImage).filter(Boolean)
diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.js
index a40a81fbb6..cb548608ec 100644
--- a/server/services/persistentMindSupervisor.test.js
+++ b/server/services/persistentMindSupervisor.test.js
@@ -25,6 +25,7 @@ const mock = vi.hoisted(() => ({
thinkingInterface: 'text',
},
imageCapability: { status: 'supported', reason: 'Supported.' },
+ thinkingSession: null,
}));
vi.mock('./cosState.js', () => ({
@@ -66,6 +67,7 @@ vi.mock('./persistentMindContext.js', () => ({
vi.mock('./persistentMindProfile.js', () => ({
resolvePersistentMindProfile: vi.fn(async () => mock.profile),
+ resolvePersistentMindThinkingSession: vi.fn(async () => mock.thinkingSession),
}));
vi.mock('./providers.js', () => ({ getProviderById: vi.fn(async () => mock.profile.provider) }));
vi.mock('./persistentMindImageCapability.js', () => ({
@@ -115,6 +117,16 @@ describe('persistent mind supervisor', () => {
thinkingInterface: 'text',
};
mock.imageCapability = { status: 'supported', reason: 'Supported.' };
+ mock.thinkingSession = {
+ ok: true,
+ temporary: true,
+ presetId: 'deep',
+ presetLabel: 'Deep pass',
+ provider: { id: 'example-alt', type: 'api' },
+ model: 'alt-model',
+ effort: 'max',
+ thinkingInterface: 'text',
+ };
mock.acquireSlot.mockReset();
mock.acquireSlot.mockResolvedValue({ ok: true, release: vi.fn() });
mock.appendMindEvent.mockClear();
@@ -751,4 +763,100 @@ describe('persistent mind supervisor', () => {
expect(second.success).toBe(true);
expect(mock.root.persistentMind.selfWake.reason).toBe('newest');
});
+
+ const withDeepPreset = () => {
+ mock.root.config.persistentMindThinkingPresets = {
+ presets: [{ id: 'deep', label: 'Deep pass', providerId: 'example-alt', model: 'alt-model', effort: 'max' }],
+ };
+ };
+ // Adapters may only prepare the transport for the route they are handed.
+ const echoProfileAdapter = () => vi.fn(async ({ profile }) => ({ ok: true, provider: profile.provider }));
+
+ it('runs one selected message on its preset and returns the very next turn to the default', async () => {
+ withDeepPreset();
+ const run = vi.fn(async () => ({}));
+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+
+ expect(await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Deep pass please.', thinkingPresetId: 'deep' }))
+ .toEqual({ success: true, duplicate: false, messageId: 'message-1' });
+ await supervisor.enqueuePersistentMindMessage({ id: 'message-2', text: 'Back to normal.' });
+
+ await supervisor.drainPersistentMind();
+ await supervisor.drainPersistentMind();
+
+ expect(run).toHaveBeenCalledTimes(2);
+ expect(run.mock.calls[0][0]).toMatchObject({ provider: { id: 'example-alt' }, model: 'alt-model', effort: 'max' });
+ expect(run.mock.calls[1][0]).toMatchObject({ provider: { id: 'example-cloud' }, model: 'example-model', effort: 'high' });
+ // The selection lives on the message, so the stored default is untouched.
+ expect(mock.root.config.persistentMindProfile).toMatchObject({ providerId: 'example-cloud', model: 'example-model' });
+
+ const modelRequests = mock.appendMindEvent.mock.calls
+ .map(([event]) => event)
+ .filter((event) => event.kind === 'mind.model.request');
+ expect(modelRequests.map((event) => event.data.thinkingPresetId)).toEqual(['deep', null]);
+ });
+
+ it('refuses a message naming a preset the user removed, and will not let a retry swap models', async () => {
+ withDeepPreset();
+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run: vi.fn() });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+
+ expect(await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Deep pass please.', thinkingPresetId: 'removed' }))
+ .toMatchObject({ success: false, code: 'THINKING_PRESET_UNAVAILABLE', status: 422 });
+ expect(mock.root.persistentMind.queuedMessages).toEqual([]);
+
+ await supervisor.enqueuePersistentMindMessage({ id: 'message-2', text: 'Deep pass please.', thinkingPresetId: 'deep' });
+ expect(await supervisor.enqueuePersistentMindMessage({ id: 'message-2', text: 'Deep pass please.', thinkingPresetId: 'deep' }))
+ .toEqual({ success: true, duplicate: true, messageId: 'message-2' });
+ expect(await supervisor.enqueuePersistentMindMessage({ id: 'message-2', text: 'Deep pass please.' }))
+ .toMatchObject({ success: false, code: 'IDEMPOTENCY_CONFLICT', status: 409 });
+ });
+
+ it('degrades visibly rather than falling back when a temporary preset no longer resolves', async () => {
+ withDeepPreset();
+ mock.thinkingSession = { ok: false, error: 'Temporary thinking preset "Deep pass" model "alt-model" is not available from provider "example-alt"' };
+ const run = vi.fn();
+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Deep pass please.', thinkingPresetId: 'deep' });
+ await supervisor.drainPersistentMind();
+
+ expect(run).not.toHaveBeenCalled();
+ expect(mock.root.persistentMind.status).toBe('degraded');
+ expect(mock.root.persistentMind.pauseReason).toMatch(/Temporary thinking preset/);
+ // Nothing was spent, so the message stays queued for the user to fix the preset.
+ expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-1']);
+ });
+
+ it('never auto-replays a temporary session interrupted after its provider span opened', async () => {
+ withDeepPreset();
+ const run = vi.fn(({ signal }) => new Promise((_resolve, reject) => {
+ signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true });
+ }));
+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Deep pass please.', thinkingPresetId: 'deep' });
+ const drain = supervisor.drainPersistentMind();
+ await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1));
+
+ mock.root.persistentMind.activeTurn.heartbeatAt = new Date(
+ Date.now() - PERSISTENT_MIND_LIMITS.WATCHDOG_STALE_MS
+ ).toISOString();
+ await expect(supervisor.checkPersistentMindWatchdog()).resolves.toEqual({ interrupted: true });
+ await drain;
+
+ expect(mock.root.persistentMind.queuedMessages).toEqual([]);
+ expect(mock.root.persistentMind.recentMessageIds).toEqual(['message-1']);
+ // An idempotent client retry reads as a completed duplicate, so a second
+ // drain cannot repeat work the provider may already have billed.
+ expect(await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Deep pass please.', thinkingPresetId: 'deep' }))
+ .toEqual({ success: true, duplicate: true, messageId: 'message-1' });
+ await supervisor.drainPersistentMind();
+ expect(run).toHaveBeenCalledTimes(1);
+ });
});