Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: allow approved local thinking presets for one mind wake (#6274)
[._.]/ Adam Eivy44d98fffe988
diff --git a/client/src/components/cos/PersistentMindThinkingRequests.jsx b/client/src/components/cos/PersistentMindThinkingRequests.jsxnew file mode 100644index 0000000000..aaca9bc0b2--- /dev/null+++ b/client/src/components/cos/PersistentMindThinkingRequests.jsx@@ -0,0 +1,52 @@+import { useEffect, useId, useState } from 'react';+import * as api from '../../services/api';+import { formatMindRoute } from '../../lib/mindThinkingPresets.js';++export default function PersistentMindThinkingRequests({ catalog, capabilities, onSaved, onCancelled }) {+ const id = useId();+ const [enabled, setEnabled] = useState(false);+ const [ids, setIds] = useState([]);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState(null);+ const savedEnabled = capabilities?.chooseThinkingPreset === true;+ const savedIds = JSON.stringify(capabilities?.thinkingPresetAllowlist || []);+ useEffect(() => {+ setEnabled(savedEnabled);+ setIds(JSON.parse(savedIds));+ }, [savedEnabled, savedIds]);+ const act = (operation) => {+ setSaving(true);+ setError(null);+ operation().catch((failure) => setError(failure.message || 'Could not save local thinking access')).finally(() => setSaving(false));+ };+ return <section className="rounded border border-port-border bg-port-card p-4 space-y-3" aria-labelledby={`${id}-heading`}>+ <h3 id={`${id}-heading`} className="font-semibold text-port-text">Self-directed local thinking</h3>+ <p className="text-sm text-port-text-muted">Allow one approved local API preset on the next self-directed wake. At most three requests per rolling 24 hours, 30 minutes apart. Failure or cancellation still counts. Your default model and task-agent permissions stay unchanged.</p>+ {catalog?.default && <p className="text-sm text-port-text-muted">Default: {formatMindRoute(catalog.default)}. Current: {catalog.current?.model ? formatMindRoute(catalog.current) : 'Idle'}.</p>}+ <label htmlFor={`${id}-enabled`} className="flex gap-2 text-sm text-port-text">+ <input id={`${id}-enabled`} type="checkbox" checked={enabled} disabled={saving || !catalog} onChange={(event) => setEnabled(event.target.checked)} /> Allow preset requests+ </label>+ <fieldset disabled={saving || !catalog} className="space-y-2">+ <legend className="text-sm text-port-text-muted">Eligible local presets</legend>+ {(catalog?.presets || []).map((preset) => <label key={preset.id} htmlFor={`${id}-${preset.id}`} className="flex gap-2 text-sm text-port-text">+ <input id={`${id}-${preset.id}`} type="checkbox" checked={ids.includes(preset.id)} onChange={(event) => setIds((current) => event.target.checked ? [...current, preset.id] : current.filter((value) => value !== preset.id))} />+ {preset.label} — {formatMindRoute(preset)}+ </label>)}+ {!catalog?.presets?.length && <p className="text-sm text-port-text-muted">No eligible presets. Save a preset using a configured local API runtime first. Account-backed and unknown routes are unavailable.</p>}+ </fieldset>+ <button type="button" disabled={saving || !catalog} className="min-h-10 rounded bg-port-accent px-3 text-white disabled:opacity-50" onClick={() => act(async () => {+ const result = await api.updateCosConfig({ persistentMindCapabilities: { chooseThinkingPreset: enabled, thinkingPresetAllowlist: ids } }, { silent: true });+ onSaved(result.persistentMindCapabilities);+ if (!enabled) onCancelled();+ })}>{saving ? 'Saving…' : 'Save local thinking access'}</button>+ {catalog?.pending && <div className="text-sm text-port-text">+ <p>Pending: {catalog.pending.label} — {catalog.pending.reason}</p>+ <button type="button" disabled={saving} className="min-h-10 rounded border border-port-border px-3" onClick={() => act(async () => {+ await api.cancelPersistentMindThinkingRequest({ silent: true });+ onCancelled();+ })}>Cancel pending request</button>+ </div>}+ {catalog?.recent?.length > 0 && <details><summary className="text-sm text-port-text">Recent requests</summary><ul className="text-sm text-port-text-muted space-y-2">{catalog.recent.slice().reverse().map((request) => <li key={request.requestId}>{request.label}: {request.reason} — {request.outcome}</li>)}</ul></details>}+ {error && <p role="alert" className="text-sm text-port-error">{error}</p>}+ </section>;+}diff --git a/client/src/components/cos/PersistentMindThinkingRequests.test.jsx b/client/src/components/cos/PersistentMindThinkingRequests.test.jsxnew file mode 100644index 0000000000..040f08632c--- /dev/null+++ b/client/src/components/cos/PersistentMindThinkingRequests.test.jsx@@ -0,0 +1,25 @@+import { expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+const api = vi.hoisted(() => ({ updateCosConfig: vi.fn(), cancelPersistentMindThinkingRequest: vi.fn() }));+vi.mock('../../services/api', () => api);+import PersistentMindThinkingRequests from './PersistentMindThinkingRequests.jsx';+it('preserves edits on a status refresh, saves only the separate grant, and cancels a pending request', async () => {+ const user = userEvent.setup();+ const catalog = { presets: [{ id: 'local', label: 'Local pass', providerId: 'example-local', model: 'example-model' }], pending: { label: 'Local pass', reason: 'Try once' } };+ const capabilities = { chooseThinkingPreset: false, thinkingPresetAllowlist: [], createTasks: true };+ const onSaved = vi.fn(); const onCancelled = vi.fn();+ const props = { catalog, capabilities, onSaved, onCancelled };+ const view = render(<PersistentMindThinkingRequests {...props} />);+ await user.click(screen.getByLabelText('Allow preset requests'));+ await user.click(screen.getByLabelText(/Local pass —/));+ view.rerender(<PersistentMindThinkingRequests {...props} capabilities={{ ...capabilities }} />);+ expect(screen.getByLabelText('Allow preset requests')).toBeChecked();+ api.updateCosConfig.mockResolvedValue({ persistentMindCapabilities: { ...capabilities, chooseThinkingPreset: true, thinkingPresetAllowlist: ['local'] } });+ await user.click(screen.getByRole('button', { name: 'Save local thinking access' }));+ await waitFor(() => expect(onSaved).toHaveBeenCalled());+ expect(api.updateCosConfig).toHaveBeenCalledWith({ persistentMindCapabilities: { chooseThinkingPreset: true, thinkingPresetAllowlist: ['local'] } }, { silent: true });+ api.cancelPersistentMindThinkingRequest.mockResolvedValue({ ok: true });+ await user.click(screen.getByRole('button', { name: 'Cancel pending request' }));+ await waitFor(() => expect(onCancelled).toHaveBeenCalled());+});diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsxindex bdcdca3e83..6b9f95a06a 100644--- a/client/src/components/cos/tabs/MindTab.jsx+++ b/client/src/components/cos/tabs/MindTab.jsx@@ -21,6 +21,7 @@ import PersistentMindRoutePanel from '../PersistentMindRoutePanel';import PersistentMindRuntimePanel, { PersistentMindThoughtStatus } from '../PersistentMindRuntimePanel';import PersistentMindSessions from '../PersistentMindSessions';import PersistentMindTemporaryRoute from '../PersistentMindTemporaryRoute';+import PersistentMindThinkingRequests from '../PersistentMindThinkingRequests';import PersistentMindThinkingPresets from '../PersistentMindThinkingPresets';import PersistentMindVisibilityPanel from '../PersistentMindVisibilityPanel';import PersistentMindTools from '../../../pages/PersistentMindTools';@@ -267,6 +268,7 @@ export default function MindTab() {capabilities: response.capabilities,imageCapability: response.imageCapability,autonomyMode: response.autonomyMode,+ thinkingRequests: response.thinkingRequests,thinkingPresets: response.thinkingPresets?.presets || NO_PRESETS,turnExecutions: response.turnExecutions || NO_TURN_EXECUTIONS,});@@ -943,6 +945,12 @@ export default function MindTab() {<PersistentMindTools onCapabilitiesChange={(capabilities) => setMind((current) => current ? { ...current, capabilities } : current)} onSavingChange={setCapabilitiesSaving} /></div>}{(visitedPanels.has('models') || activePanel === 'models') && <div hidden={activePanel !== 'models'} className="space-y-6">+ <PersistentMindThinkingRequests+ catalog={mind?.thinkingRequests}+ capabilities={mind?.capabilities}+ onSaved={(capabilities) => setMind((current) => ({ ...current, capabilities }))}+ onCancelled={() => setMind((current) => ({ ...current, thinkingRequests: { ...current.thinkingRequests, pending: null } }))}+ /><PersistentMindThinkingPresetspresets={thinkingPresets}disabled={!mind}diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex f8350e335c..815408c946 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -53,6 +53,8 @@ export const repairRunRecords = (body = {}, options = {}) =>// timed-out request cannot duplicate a message or annotation.export const getPersistentMind = (filters = {}, options = {}) =>request(`/cos/mind${runEventQuery(filters)}`, options);+export const cancelPersistentMindThinkingRequest = (options = {}) =>+ request('/cos/mind/thinking-request', { method: 'DELETE', ...options });export const getPersistentMindContext = (options = {}) => request('/cos/mind/context', options);export const getPersistentMindTools = (options = {}) => request('/cos/mind/tools', options);export const getCosToolCatalog = ({ scope = 'all', format = 'portos', intent, ...options } = {}) => {diff --git a/docs/features/cos-enhancement.md b/docs/features/cos-enhancement.mdindex 632e834eff..9329d3475c 100644--- a/docs/features/cos-enhancement.md+++ b/docs/features/cos-enhancement.md@@ -106,7 +106,7 @@ Comprehensive upgrade from reactive task executor to proactive autonomous agent1. **Mission Autonomy**: Full autonomy - COS can implement changes, run tests, commit without approval for managed apps2. **Model Usage**: Local-first with LM Studio, no cloud API costs for thinking-3. **Self-Modification**: Full autonomy - COS can change its own base thinking model without user approval+3. **Persistent Mind model control**: The default profile is human-owned. An optional grant permits one approved local preset on a self-directed wake; the mind cannot rewrite provider configuration.4. **Failure Investigation**: Unattended by default - an `[Auto] Investigate agent failure` task runs without approval, because an isolated agent failure is exactly the work CoS exists to diagnose for itself. Approval is reserved for a failure *loop*, where another unattended agent would only repeat what already didn't work: the same cause investigated again within 24h (`repeat-fingerprint`), or the circuit-breaker hour already one slot from its cap (`failure-storm`). The reason is stamped on the task as the producer-agnostic `metadata.approvalReason` (`investigation-loop:<signal>`), which the Tasks UI turns into a hint on the APPROVE button. See `resolveInvestigationApproval` in `server/services/agentErrorAnalysis.js`.## Persistent Mind task filing@@ -199,3 +199,37 @@ opening line. Off by default.- [Chief of Staff](./chief-of-staff.md) - Core orchestration- [Memory System](./memory-system.md) - Memory search integration- [Error Handling](./error-handling.md) - Error recovery integration+++## Self-directed local thinking presets++In the Mind settings drawer, **Models → Self-directed local thinking** lets the+user enable `chooseThinkingPreset` and approve exact local presets. It defaults+to off on new and upgraded installs and is independent of task-agent model+permissions. Saving preferences and loading the catalog perform no inference.++Only configured direct local API runtimes qualify. Account-backed routes,+CLI/TUI wrappers, and unknown routes are excluded. Approval binds the preset,+provider name, endpoint and runtime; editing these requires renewed approval.+Removing a model, preset, or supported effort refuses the pending selection.++The semantic actions `mind.thinking-presets` and+`mind.request-thinking-preset` expose the approved catalog and a bounded+`{ presetId, reason }` request. One request borrows a preset for the next+self-directed wake; queued human messages and the current turn keep their own+routes. The default profile, memories, and identity are unchanged.++Only one request may be pending or active. At most three are accepted per+rolling 24 hours, with a 30-minute gap. Admission also advances the recorded+attempt time so a delayed wake cannot evade these limits. Cancellation, failed+admission, interruption and restart do not refund allowance. Failed attempts+retire the alternate and schedule an ordinary wake on the default profile.+Existing endpoint slots, CoS capacity, autonomy and per-call budgets still gate+every execution. No tool can extend its own session or edit these permissions.++The same Models panel cancels pending requests and shows recent concise reasons+and outcomes. Disabling the grant cancels the pending request; revoking it during+execution refuses further provider calls. Execution receipts in Sessions show+the actual route and outcome without exposing hidden reasoning. Durable request+records live alongside the existing machine-local mind state; migration 348+preserves prior profiles, grants, and counters.diff --git a/scripts/migrations/348-persistent-mind-self-thinking.js b/scripts/migrations/348-persistent-mind-self-thinking.jsnew file mode 100644index 0000000000..0e6464e6f1--- /dev/null+++ b/scripts/migrations/348-persistent-mind-self-thinking.js@@ -0,0 +1,32 @@+/** Add opt-in local thinking authority and durable request state; never infer. */+import { join } from 'path';+import { readFile } from 'fs/promises';+import { atomicWrite } from '../../server/lib/fileUtils.js';+import { PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION } from '../../server/lib/persistentMindCapabilities.js';+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../../server/lib/persistentMind.js';+export default {+ async up({ rootDir }) {+ let updated = 0;+ for (const name of ['config', 'state']) {+ const path = join(rootDir, 'data', 'cos', `${name}.json`);+ const raw = await readFile(path, 'utf8').catch((error) => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (raw === null) continue;+ const record = JSON.parse(raw);+ if (name === 'config') {+ record.persistentMindCapabilities = {+ chooseThinkingPreset: false, thinkingPresetAllowlist: [], thinkingPresetGrants: {},+ ...record.persistentMindCapabilities, schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,+ };+ } else if (record.persistentMind) {+ record.persistentMind = { thinkingRequests: { pending: null, history: [] },+ ...record.persistentMind, schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION };+ } else continue;+ await atomicWrite(path, record);+ updated += 1;+ }+ return { updated };+ },+};diff --git a/scripts/migrations/348-persistent-mind-self-thinking.test.js b/scripts/migrations/348-persistent-mind-self-thinking.test.jsnew file mode 100644index 0000000000..f02e514a7b--- /dev/null+++ b/scripts/migrations/348-persistent-mind-self-thinking.test.js@@ -0,0 +1,26 @@+import { afterEach, expect, it } from 'vitest';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './348-persistent-mind-self-thinking.js';+let rootDir;+afterEach(async () => { if (rootDir) await rm(rootDir, { recursive: true, force: true }); });+it('adds disabled grants and durable state while preserving old preferences, unrelated fields and existing allowance', async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'portos-self-thinking-'));+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ const configPath = join(rootDir, 'data', 'cos', 'config.json');+ const statePath = join(rootDir, 'data', 'cos', 'state.json');+ const config = { persistentMindProfile: { providerId: 'example-default', model: 'example-model' }, persistentMindCapabilities: { schemaVersion: 5, createTasks: true, taskModelAllowlist: [{ providerId: 'example-coder', model: 'example-code' }] } };+ const thinkingRequests = { pending: null, history: [{ requestId: 'existing-attempt' }] };+ await writeFile(configPath, JSON.stringify(config));+ await writeFile(statePath, JSON.stringify({ persistentMind: { schemaVersion: 7, thinkingRequests }, unrelated: true }));+ await migration.up({ rootDir });+ expect(JSON.parse(await readFile(configPath, 'utf8'))).toMatchObject({+ persistentMindProfile: config.persistentMindProfile,+ persistentMindCapabilities: { ...config.persistentMindCapabilities, schemaVersion: 6, chooseThinkingPreset: false, thinkingPresetAllowlist: [] },+ });+ expect(JSON.parse(await readFile(statePath, 'utf8'))).toEqual({ persistentMind: { schemaVersion: 8, thinkingRequests }, unrelated: true });+ const saved = await readFile(configPath, 'utf8');+ await migration.up({ rootDir });+ expect(await readFile(configPath, 'utf8')).toBe(saved);+});diff --git a/server/lib/README.md b/server/lib/README.mdindex bc89652372..2216c2b2d5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -58,7 +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, preset lookup, strict accepted-selection schema/normalization, and route equality independent of labels. Storage only — saving or selecting a preset starts no inference. |+| `persistentMindThinkingPresets.js` | Also owns bounded self-thinking request schemas, durable request normalization, and fixed switching limits. Saved named temporary thinking presets for the persistent mind (exact provider/model/effort alternates to its one home profile): default-empty durable shape, normalization that drops half-pinned entries, strict API schema, whole-list replace merge, preset lookup, strict accepted-selection schema/normalization, and route equality independent of labels. Storage only — saving or selecting a preset starts no inference. || `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/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex a3f4f75c74..da46b5d321 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -4351,6 +4351,14 @@"server/routes/cosMindRoutes.js"]},+ {+ "method": "DELETE",+ "path": "/api/cos/mind/thinking-request",+ "mountPath": "/api/cos",+ "sources": [+ "server/routes/cosMindRoutes.js"+ ]+ },{"method": "GET","path": "/api/cos/mind/tools",@@ -17626,8 +17634,8 @@],"stats": {"mounts": 148,- "operations": 2183,- "declarations": 2191,+ "operations": 2184,+ "declarations": 2192,"sourceFiles": 231}}diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.jsindex 8ccd17f31f..facf2ed6bc 100644--- a/server/lib/persistentMind.js+++ b/server/lib/persistentMind.js@@ -13,10 +13,12 @@ import { sanitizeFilename } from './mimeTypes.js';import { isSafeFilename } from './pathSafety.js';import {asPersistentMindThinkingPresetId,+ normalizePersistentMindThinkingRequest,+ normalizePersistentMindThinkingRequests,normalizePersistentMindThinkingSelection,} from './persistentMindThinkingPresets.js';-export const PERSISTENT_MIND_SCHEMA_VERSION = 7;+export const PERSISTENT_MIND_SCHEMA_VERSION = 8;export const PERSISTENT_MIND_IMAGE_EXTENSIONS = Object.freeze(['.png', '.jpg', '.jpeg', '.gif', '.webp']);export const PERSISTENT_MIND_IMAGE_MIME_TYPES = Object.freeze({@@ -289,6 +291,7 @@ const sanitizeSelfWake = (value) => {: 'requested',reason,sourceTurnId,+ ...(value?.thinkingRequest ? { thinkingRequest: normalizePersistentMindThinkingRequest(value.thinkingRequest) } : {}),createdAt: asIso(value?.createdAt) || new Date(0).toISOString(),notBefore: asIso(value?.notBefore),};@@ -332,6 +335,7 @@ export function createDefaultPersistentMindState() {recentMessageIds: [],recentMessageFingerprints: [],callHistory: [],+ thinkingRequests: normalizePersistentMindThinkingRequests(),lastCompletedTurnId: null,lastCompletedAt: null,nextEligibleWakeAt: null,@@ -413,12 +417,18 @@ export function normalizePersistentMindState(raw) {if (queuedMessages.length > PERSISTENT_MIND_LIMITS.MAX_QUEUED_MESSAGES) queuedMessages.pop();}}- } else if (!selfWake) {+ } else if (!selfWake && !activeTurn.wake.thinkingRequest) {selfWake = activeTurn.wake;}activeTurn = null;}+ const thinkingRequests = normalizePersistentMindThinkingRequests(source.thinkingRequests);+ if (!started) {+ thinkingRequests.history = thinkingRequests.history.map((entry) => entry.outcome === 'admitted'+ ? { ...entry, outcome: 'interrupted' } : entry);+ }+return {...defaults,schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,@@ -433,6 +443,7 @@ export function normalizePersistentMindState(raw) {activeTurn,recentMessageIds: recentMessageIds.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),recentMessageFingerprints: recentMessageFingerprints.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),+ thinkingRequests,callHistory: callHistory.slice(-PERSISTENT_MIND_LIMITS.MAX_CALL_HISTORY),lastCompletedTurnId: asId(source.lastCompletedTurnId) || null,lastCompletedAt: asIso(source.lastCompletedAt),@@ -518,13 +529,14 @@ export function takeNextPersistentMindWake(raw, now = Date.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+ * Human-selected temporary sessions and approved self-selected wakes consume+ * an attempt. A human-selected session 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);+ return Boolean(wake?.thinkingRequest) || (wake?.kind === 'message' && Boolean(wake.message?.thinkingPresetId));}/**@@ -536,6 +548,13 @@ export function persistentMindWakeConsumesAttempt(wake) {export function holdPersistentMindWake(raw, wake) {const state = normalizePersistentMindState(raw);const sanitized = sanitizeWake(wake);+ if (sanitized?.kind === 'self' && sanitized.thinkingRequest) {+ const { thinkingRequest: _request, ...ordinary } = sanitized;+ return { ...state, selfWake: state.selfWake || {+ ...ordinary, reason: 'Resume default after local thinking attempt',+ notBefore: new Date(Date.now() + PERSISTENT_MIND_LIMITS.MAX_QUIET_MS).toISOString(),+ } };+ }if (sanitized?.kind !== 'message') return state;const { id } = sanitized.message;return {diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.jsindex cc33180a50..c7f37f4303 100644--- a/server/lib/persistentMindCapabilities.js+++ b/server/lib/persistentMindCapabilities.js@@ -14,12 +14,12 @@ import {portosSemanticToolGrantsSchema,} from './cosToolContracts.js';-export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 5;+export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 6;// Every wire version this server still accepts on input. Installs upgrade on// their own schedule, so a browser bundle (or a route caller) pinned at an// older version must keep being able to toggle the grants it already knows// about; normalization always writes the current version forward.-const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4, 5]);+const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4, 5, 6]);export const PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS = Object.freeze({MAX_ENTRIES: 200,@@ -55,6 +55,12 @@ export const PERSISTENT_MIND_CALL_LIMITS = Object.freeze({// agents. Keep this catalog beside the capability schema so the API and the UI// describe the same grants instead of maintaining a second client-only list.export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze([+ Object.freeze({+ id: 'mind.request-thinking-preset', capability: 'chooseThinkingPreset',+ name: 'Request a local thinking preset', kind: 'semantic-tools', defaultEnabled: false,+ description: 'Borrow an explicitly approved local API preset for the next self-directed wake.',+ guardrails: ['One pending or active alternate wake', 'At most three requests per rolling 24 hours, 30 minutes apart', 'No default-profile edits, paid routes, downloads, or permission changes'],+ }),Object.freeze({id: 'cos.create-task',capability: 'createTasks',@@ -177,6 +183,8 @@ export const persistentMindCapabilitiesSchema = portosSemanticToolGrantsSchema.ecreateTasks: z.boolean().optional(),manageMind: z.boolean().optional(),callUser: z.boolean().optional(),+ chooseThinkingPreset: z.boolean().optional(),+ thinkingPresetAllowlist: z.array(z.string().trim().min(1).max(64)).max(20).optional(),// An empty list preserves the legacy unrestricted task catalog. Once any// entries are configured, requests must name one of these exact pairs.taskModelAllowlist: z.array(persistentMindTaskModelAllowlistEntrySchema)@@ -244,6 +252,9 @@ export function createDefaultPersistentMindCapabilities() {manageMind: false,manageEidoverse: false,callUser: false,+ chooseThinkingPreset: false,+ thinkingPresetAllowlist: [],+ thinkingPresetGrants: {},readPortos: false,writePortos: false,taskModelAllowlist: [],@@ -297,6 +308,9 @@ export function normalizePersistentMindCapabilities(raw) {createTasks: source.createTasks === true,manageMind: source.manageMind === true,callUser: source.callUser === true,+ chooseThinkingPreset: source.chooseThinkingPreset === true,+ thinkingPresetAllowlist: z.array(z.string().min(1).max(64)).max(20).safeParse(source.thinkingPresetAllowlist).data || [],+ thinkingPresetGrants: z.record(z.string(), z.string().regex(/^[a-f0-9]{64}$/)).safeParse(source.thinkingPresetGrants).data || {},...semanticGrants,taskModelAllowlist: taskModelAllowlist.entries,// A malformed hand-edited persisted policy must not silently become thediff --git a/server/lib/persistentMindCapabilities.test.js b/server/lib/persistentMindCapabilities.test.jsindex 5e34e0098b..fdbccff29b 100644--- a/server/lib/persistentMindCapabilities.test.js+++ b/server/lib/persistentMindCapabilities.test.js@@ -15,6 +15,7 @@ import {describe('persistent mind capabilities', () => {it('describes every persistent-mind grant from the capability contract', () => {expect(PERSISTENT_MIND_TOOL_CATALOG).toEqual([+ expect.objectContaining({ capability: 'chooseThinkingPreset', defaultEnabled: false }),expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', defaultEnabled: false }),expect.objectContaining({ id: 'portos.read', capability: 'readPortos', defaultEnabled: false }),expect.objectContaining({ id: 'portos.write', capability: 'writePortos', defaultEnabled: false }),@@ -46,10 +47,10 @@ describe('persistent mind capabilities', () => {expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 2, createTasks: true }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 3, callUser: true }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 5 }).success).toBe(true);- expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 6 }).success).toBe(false);+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 7 }).success).toBe(false);expect(persistentMindCapabilitiesSchema.safeParse({ taskModelAllowlist: [{ providerId: 'ollama', model: 'example-local' }] }).success).toBe(true);expect(normalizePersistentMindCapabilities({ schemaVersion: 2, createTasks: true }))- .toMatchObject({ schemaVersion: 5, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false });+ .toMatchObject({ schemaVersion: 6, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false });expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: ['example-app', 'second-app'] }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: Array.from({ length: 51 }, (_, index) => `app-${index}`) }).success).toBe(false);expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, shell: true }).success).toBe(false);diff --git a/server/lib/persistentMindPublic.js b/server/lib/persistentMindPublic.jsindex ef5f8660b3..e1df54cb62 100644--- a/server/lib/persistentMindPublic.js+++ b/server/lib/persistentMindPublic.js@@ -29,7 +29,9 @@ const publicActiveRoute = (activeTurn) => {// Presentation only — consent already happened at admission, and the resolver// re-validates the route against the saved preset before any provider call.const publicActiveThinkingSession = (activeTurn) => {- const message = activeTurn?.wake?.kind === 'message' ? activeTurn.wake.message : null;+ const request = activeTurn?.wake?.thinkingRequest;+ const message = request ? { thinkingPresetId: request.selection.id, thinkingPreset: request.selection }+ : activeTurn?.wake?.kind === 'message' ? activeTurn.wake.message : null;if (!message?.thinkingPresetId) return null;const selection = normalizePersistentMindThinkingSelection(message.thinkingPreset);return {diff --git a/server/lib/persistentMindThinkingPresets.js b/server/lib/persistentMindThinkingPresets.jsindex 24156b561d..de306fc1a9 100644--- a/server/lib/persistentMindThinkingPresets.js+++ b/server/lib/persistentMindThinkingPresets.js@@ -135,3 +135,34 @@ export function findPersistentMindThinkingPreset(raw, presetId) {if (!id) return null;return normalizePersistentMindThinkingPresets(raw).presets.find((preset) => preset.id === id) || null;}+++export const persistentMindThinkingRequestSchema = z.object({+ presetId: persistentMindThinkingPresetSchema.shape.id,+ reason: z.string().trim().min(1).max(200),+}).strict();++export const PERSISTENT_MIND_THINKING_LIMITS = Object.freeze({ maxPerRollingDay: 3, rollingWindowMs: 86_400_000, minGapMs: 1_800_000 });++const thinkingRequestRecordSchema = z.object({+ requestId: z.string().min(1).max(200),+ turnId: z.string().min(1).max(200),+ at: z.string().datetime(),+ admittedAt: z.string().datetime().optional(),+ reason: z.string().max(200),+ selection: persistentMindThinkingSelectionSchema,+ outcome: z.enum(['pending', 'admitted', 'completed', 'failed', 'cancelled', 'interrupted']).optional(),+ grant: z.string().regex(/^[a-f0-9]{64}$/),+}).strict();++export function normalizePersistentMindThinkingRequest(value) {+ return thinkingRequestRecordSchema.safeParse(value).data || null;+}++export function normalizePersistentMindThinkingRequests(value) {+ return {+ pending: normalizePersistentMindThinkingRequest(value?.pending),+ history: (Array.isArray(value?.history) ? value.history : [])+ .map(normalizePersistentMindThinkingRequest).filter(Boolean).slice(-20),+ };+}diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.jsindex 761bea9981..ab30642d33 100644--- a/server/routes/cosMindRoutes.js+++ b/server/routes/cosMindRoutes.js@@ -1,3 +1,4 @@+import { getPersistentMindThinkingRequestCatalog, cancelPersistentMindThinkingRequest } from '../services/persistentMindThinkingRequests.js';/** Persistent Chief-of-Staff mind conversation and lifecycle routes. */import { Router } from 'express';@@ -204,6 +205,7 @@ router.get('/mind', asyncHandler(async (req, res) => {thinkingInterface: profile.thinkingInterface,wakeIntervalMinutes: profile.wakeIntervalMinutes,},+ thinkingRequests: await getPersistentMindThinkingRequestCatalog({ human: true }),thinkingPresets: normalizePersistentMindThinkingPresets(root.config?.persistentMindThinkingPresets),capabilities,harness: persistentMindHarnessInfo(provider),@@ -212,6 +214,10 @@ router.get('/mind', asyncHandler(async (req, res) => {});}));+router.delete('/mind/thinking-request', asyncHandler(async (_req, res) => {+ res.json(await cancelPersistentMindThinkingRequest());+}));+router.get('/mind/context', asyncHandler(async (_req, res) => {const root = await loadState();const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex ddcd4d897c..6fc6693fb7 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -184,7 +184,7 @@ describe('persistent mind routes', () => {thinkingInterface: 'text',wakeIntervalMinutes: 30,},- capabilities: { schemaVersion: 5, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },+ capabilities: { schemaVersion: 6, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },harness: { type: 'api', recommendation: 'recommended' },imageCapability: { status: 'unknown' },autonomyMode: 'execute',@@ -278,8 +278,8 @@ describe('persistent mind routes', () => {expect.objectContaining({ name: 'eidoverse.status', granted: false, input_schema: expect.any(Object) }),expect.objectContaining({ name: 'cos.create-task', granted: true }),]),- schemaVersion: 5,- capabilities: { schemaVersion: 5, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },+ schemaVersion: 6,+ capabilities: { schemaVersion: 6, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },boundaries: expect.arrayContaining([expect.stringMatching(/arbitrary shell/i)]),tools: expect.arrayContaining([expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', granted: true, defaultEnabled: false }),@@ -293,7 +293,7 @@ describe('persistent mind routes', () => {providers: [{ id: 'codex' }],},});- expect(res.body.tools[0].guardrails).toEqual(expect.arrayContaining([+ expect(res.body.tools.find((tool) => tool.id === 'cos.create-task').guardrails).toEqual(expect.arrayContaining([expect.stringMatching(/isolated-worktree/i),]));});diff --git a/server/services/cos.js b/server/services/cos.jsindex 8aea518c06..e05c2bf913 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -283,6 +283,12 @@ export async function updateConfig(updates) {updates.persistentMindThinkingPresets,);}+ if (updates.persistentMindCapabilities?.thinkingPresetAllowlist !== undefined) {+ const { approvePersistentMindThinkingPresets } = await import('./persistentMindThinkingRequests.js');+ next.persistentMindCapabilities.thinkingPresetGrants = await approvePersistentMindThinkingPresets(+ next, next.persistentMindCapabilities.thinkingPresetAllowlist,+ );+ }if (updates.persistentMindPrompt !== undefined) {next.persistentMindPrompt = mergePersistentMindPrompt(priorPersistentMindPrompt,@@ -291,6 +297,10 @@ export async function updateConfig(updates) {}return saveConfig(next);});+ if (updates.persistentMindCapabilities !== undefined || updates.persistentMindThinkingPresets !== undefined) {+ const { cancelPersistentMindThinkingRequest } = await import('./persistentMindThinkingRequests.js');+ await cancelPersistentMindThinkingRequest({ ifRevoked: true });+ }const improveKeys = ['improvementEnabled', 'selfImprovementEnabled', 'appImprovementEnabled'];const improvePatch = Object.fromEntries(improveKeys.filter((key) => Object.prototype.hasOwnProperty.call(updates, key)).map((key) => [key, updates[key]]),diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.jsindex 86c0628a34..ed05c1851c 100644--- a/server/services/cosToolRegistry.js+++ b/server/services/cosToolRegistry.js@@ -22,6 +22,7 @@ import {eidoverseWorldAugmentSchema,eidoverseWorldSaySchema,} from '../lib/validation.js';+import { persistentMindThinkingRequestSchema } from '../lib/persistentMindThinkingPresets.js';import { USER_ACTION_ACTORS, USER_ACTION_TYPES } from '../lib/userActionTypes.js';import { dispatchTool, getToolSpecs, getToolSpecsForIntent } from './voice/tools.js';import { executePersistentMindTaskRequests } from './persistentMindTaskCapability.js';@@ -254,7 +255,16 @@ const eidoverseSayTool = Object.freeze({});const eidoverseTools = [eidoverseStatusTool, eidoverseProjectTool, eidoverseAugmentTool, eidoverseSayTool];-const toolCatalog = (intent) => [taskTool, mindCleanupTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];+const thinkingTools = ['mind.thinking-presets', 'mind.request-thinking-preset'].map((name, index) => ({+ type: 'portos_tool', name, version: COS_TOOL_SCHEMA_VERSION,+ providerName: providerToolName(name), aliases: [],+ description: index ? 'Request one approved local preset for the next self-directed wake, without changing this turn or the default.' : 'List exact approved local thinking presets, current/default route and switching limits.',+ input_schema: zodToOpenApiSchema(index ? persistentMindThinkingRequestSchema : z.object({}).strict()),+ output_schema: objectOutputSchema,+ policy: { scopes: ['mind'], requiredCapabilities: ['chooseThinkingPreset'], sideEffect: index ? 'write' : 'read', idempotent: true, async: false, confirmation: 'capability-grant' },+ adapter: { kind: index ? 'thinking-request' : 'thinking-catalog' },+}));+const toolCatalog = (intent) => [...thinkingTools, taskTool, mindCleanupTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];const toolCalls = new Map();const toolCallFingerprints = new Map();@@ -262,6 +272,7 @@ const normalizeToolCapabilities = (raw) => ({...normalizePortosSemanticToolGrants(raw),createTasks: raw?.createTasks === true,manageMind: raw?.manageMind === true,+ chooseThinkingPreset: raw?.chooseThinkingPreset === true,});const publicTool = (tool, { scope, capabilities }) => ({@@ -379,6 +390,12 @@ const validateArguments = (tool, args) => {};const executeAdapter = async (tool, args, context) => {+ if (tool.adapter.kind.startsWith('thinking-')) {+ const { getPersistentMindThinkingRequestCatalog, requestPersistentMindThinkingPreset } = await import('./persistentMindThinkingRequests.js');+ return tool.adapter.kind === 'thinking-catalog'+ ? getPersistentMindThinkingRequestCatalog()+ : requestPersistentMindThinkingPreset(args, context);+ }if (tool.adapter.kind === 'voice-tool') {return dispatchTool(tool.adapter.legacyName, args, { sideEffects: [], signal: context.signal });}@@ -511,7 +528,7 @@ export const executeCosToolCall = async ({ call, authority, context = {} }) => {}const promise = Promise.resolve()- .then(() => executeAdapter(tool, args, context))+ .then(() => executeAdapter(tool, args, { ...context, requestId: parsedCall.requestId })).then((result) => normalizeAdapterResult({ parsedCall, tool, result }),(error) => ({diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.jsindex 8fe1ec3d19..3129180e55 100644--- a/server/services/cosToolRegistry.test.js+++ b/server/services/cosToolRegistry.test.js@@ -81,9 +81,19 @@ beforeEach(() => {});describe('cosToolRegistry', () => {+ it('keeps local thinking authority separate and refuses raw configuration arguments', async () => {+ const call = { requestId: 'thinking-1', name: 'mind.request-thinking-preset', arguments: { presetId: 'local', reason: 'Try a focused pass' } };+ await expect(executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { writePortos: true, createTasks: true } } })).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });+ await expect(executeCosToolCall({ call: { ...call, arguments: { ...call.arguments, endpoint: 'https://example.com' } }, authority: { scope: 'mind', capabilities: { chooseThinkingPreset: true } } })).rejects.toMatchObject({ code: 'TOOL_VALIDATION_ERROR' });+ await expect(executeCosToolCall({ call, authority: { scope: 'agent', capabilities: { chooseThinkingPreset: true } } })).rejects.toMatchObject({ code: 'TOOL_SCOPE_DENIED' });+ expect(getCosToolCatalog({ scope: 'mind', capabilities: { chooseThinkingPreset: true } }).tools.filter((tool) => tool.granted).map((tool) => tool.name)).toEqual(['mind.thinking-presets', 'mind.request-thinking-preset']);+ });+it('exports a compact canonical catalog and provider translations', () => {const catalog = getCosToolCatalog({ scope: 'mind', capabilities: { readPortos: true } });expect(catalog.tools.map((tool) => tool.name)).toEqual([+ 'mind.thinking-presets',+ 'mind.request-thinking-preset','cos.create-task','mind.cleanup','user-actions.query',diff --git a/server/services/persistentMindCallGuard.js b/server/services/persistentMindCallGuard.jsindex 4b058a9043..df4031f84b 100644--- a/server/services/persistentMindCallGuard.js+++ b/server/services/persistentMindCallGuard.js@@ -27,6 +27,7 @@ import { buildPersistentMindCallDenial, buildPersistentMindCallReceipt } from '.import { loadState } from './cosState.js';import { appendMindEvent } from './agentRunEventLog.js';import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';+import { resolvePersistentMindSelfThinkingRequest } from './persistentMindThinkingRequests.js';import { resolvePersistentMindProfile, resolvePersistentMindThinkingSession } from './persistentMindProfile.js';/** Mind status a denial should park the turn under, by cause. */@@ -71,6 +72,7 @@ export async function evaluatePersistentMindCallAdmission({route,thinkingPresetId = null,thinkingSelection = null,+ selfThinkingRequest = null,capabilityFingerprint = null,signal,} = {}) {@@ -96,7 +98,9 @@ export async function evaluatePersistentMindCallAdmission({// Provider availability/authorization and preset lifecycle both resolve here:// the same exact-or-refuse resolvers the supervisor admitted the turn with.- const resolved = thinkingPresetId+ const resolved = selfThinkingRequest+ ? await resolvePersistentMindSelfThinkingRequest({ request: selfThinkingRequest, config: root?.config })+ : thinkingPresetId? await resolvePersistentMindThinkingSession({ presetId: thinkingPresetId, selection: thinkingSelection, config: root?.config }): await resolvePersistentMindProfile(root?.config?.persistentMindProfile);if (!resolved.ok) {@@ -139,6 +143,7 @@ export function createPersistentMindCallBoundary({route,thinkingPresetId = null,thinkingSelection = null,+ selfThinkingRequest = null,capabilityFingerprint = null,signal,now = () => Date.now(),@@ -171,7 +176,7 @@ export function createPersistentMindCallBoundary({};const call = async ({ purpose, round = null } = {}, run) => {- const admission = await evaluate({ turnId, route, thinkingPresetId, thinkingSelection, capabilityFingerprint, signal });+ const admission = await evaluate({ turnId, route, thinkingPresetId, thinkingSelection, selfThinkingRequest, capabilityFingerprint, signal });if (!admission.ok) {await writeReceipt({ purpose, round, outcome: 'denied', reason: admission.reason });throw buildPersistentMindCallDenial(admission);diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsindex 3e75b7fe4a..10f30a8d55 100644--- a/server/services/persistentMindSupervisor.js+++ b/server/services/persistentMindSupervisor.js@@ -54,6 +54,7 @@ import {} from './persistentMindCallGuard.js';import { appendMindEvent } from './agentRunEventLog.js';import { preparePersistentMindContext } from './persistentMindContext.js';+import { resolvePersistentMindSelfThinkingRequest } from './persistentMindThinkingRequests.js';import { resolvePersistentMindProfile, resolvePersistentMindThinkingSession } from './persistentMindProfile.js';import { isUpdateInProgress } from './updateChecker.js';import { publicPersistentMindState } from '../lib/persistentMindPublic.js';@@ -91,7 +92,13 @@ async function mutateMindState(mutator) {const root = await loadState();const mind = normalizePersistentMindState(root.persistentMind);const result = await mutator(mind, root);- root.persistentMind = normalizePersistentMindState(result?.mind || mind);+ const next = result?.mind || mind;+ const request = mind.activeTurn?.wake?.thinkingRequest;+ if (request && !next.activeTurn) {+ next.thinkingRequests.history = next.thinkingRequests.history.map((entry) => entry.requestId === request.requestId+ ? { ...entry, outcome: next.lastCompletedTurnId === mind.activeTurn.id ? 'completed' : 'failed' } : entry);+ }+ root.persistentMind = normalizePersistentMindState(next);await saveState(root);return { state: root.persistentMind, value: result?.value };});@@ -597,7 +604,7 @@ async function parkActiveTurn(turnId, reason, status = 'waiting', { retryAt = nuif (mind.activeTurn?.id !== turnId) return { mind, value: false };// Transport/slot waits may retry; a revoked route or uncertain inference// requires a fresh user submission.- const held = (consumedAttempt || retireWake) && persistentMindWakeConsumesAttempt(mind.activeTurn.wake);+ const held = (consumedAttempt || retireWake || Boolean(mind.activeTurn.wake.thinkingRequest)) && persistentMindWakeConsumesAttempt(mind.activeTurn.wake);const next = held? holdPersistentMindWake(mind, mind.activeTurn.wake): requeuePersistentMindWake(mind, mind.activeTurn.wake);@@ -633,6 +640,14 @@ async function claimNextTurn() {if (root.paused || getDomainMode(root.config, 'cos') !== 'execute') return { mind, value: null };const selected = takeNextPersistentMindWake(mind);if (!selected.wake) return { mind: selected.state, value: null };+ if (selected.wake.kind === 'self' && selected.state.thinkingRequests.pending) {+ selected.wake = { ...selected.wake, thinkingRequest: selected.state.thinkingRequests.pending };+ selected.state.thinkingRequests = {+ pending: null,+ history: selected.state.thinkingRequests.history.map((entry) => entry.requestId === selected.wake.thinkingRequest.requestId+ ? { ...entry, outcome: 'admitted', admittedAt: nowIso() } : entry),+ };+ }const id = `mind-turn-${randomUUID()}`;const startedAt = nowIso();const activeTurn = {@@ -667,7 +682,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,+ thinkingPresetId: result.value.wake.thinkingRequest?.selection.id || result.value.wake.message?.thinkingPresetId || null,reason: result.value.wake.reason || null,},});@@ -917,14 +932,18 @@ async function runOnePersistentMindTurn() {// 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'+ const selfThinkingRequest = turn.wake.thinkingRequest || null;+ const thinkingSelection = selfThinkingRequest?.selection || turn.wake.message?.thinkingPreset || null;+ const thinkingPresetId = selfThinkingRequest?.selection.id || (turn.wake.kind === 'message'? turn.wake.message.thinkingPresetId || null- : null;+ : null);const routeConfig = (await loadState()).config;- const profile = thinkingPresetId+ const profile = selfThinkingRequest+ ? await resolvePersistentMindSelfThinkingRequest({ request: selfThinkingRequest, config: routeConfig })+ : thinkingPresetId? await resolvePersistentMindThinkingSession({presetId: thinkingPresetId,- selection: turn.wake.message.thinkingPreset,+ selection: thinkingSelection,config: routeConfig,}): await resolvePersistentMindProfile(routeConfig?.persistentMindProfile);@@ -979,11 +998,13 @@ async function runOnePersistentMindTurn() {// waits must be refused before even a context-summary call can begin.const admissionRoot = await loadState();if (thinkingPresetId) {- const admissionProfile = await resolvePersistentMindThinkingSession({- presetId: thinkingPresetId,- selection: turn.wake.message.thinkingPreset,- config: admissionRoot.config,- });+ const admissionProfile = selfThinkingRequest+ ? await resolvePersistentMindSelfThinkingRequest({ request: selfThinkingRequest, config: admissionRoot.config })+ : await resolvePersistentMindThinkingSession({+ presetId: thinkingPresetId,+ selection: thinkingSelection,+ config: admissionRoot.config,+ });if (!await turnCanContinue(turn.id, generation, controller.signal)) return;if (!admissionProfile.ok) {await parkActiveTurn(turn.id, admissionProfile.error, 'degraded', { retireWake: admissionProfile.requiresResubmission === true });@@ -1016,7 +1037,8 @@ async function runOnePersistentMindTurn() {thinkingPresetId,// The ACCEPTED preset snapshot the message carries (#6283) — never the// mutable preset id, which the user can repoint mid-turn.- thinkingSelection: thinkingPresetId ? turn.wake.message.thinkingPreset : null,+ thinkingSelection,+ selfThinkingRequest,capabilityFingerprint: persistentMindCapabilityGrantFingerprint(admissionRoot.config?.persistentMindCapabilities),signal: controller.signal,});diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex 6e0db748a9..14470091de 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -784,6 +784,70 @@ describe('persistent mind supervisor', () => {// Adapters may only prepare the transport for the route they are handed.const echoProfileAdapter = () => vi.fn(async ({ profile }) => ({ ok: true, provider: profile.provider }));+ async function approveSelfThinking() {+ withDeepPreset();+ mock.thinkingSession.provider = { id: 'example-alt', name: 'Example local', type: 'api', endpoint: 'http://localhost:1234/v1' };+ const { approvePersistentMindThinkingPresets } = await import('./persistentMindThinkingRequests.js');+ mock.root.config.persistentMindCapabilities = {+ chooseThinkingPreset: true, thinkingPresetAllowlist: ['deep'],+ thinkingPresetGrants: await approvePersistentMindThinkingPresets(mock.root.config, ['deep']),+ };+ }++ it('borrows a self-selected preset only at the next self wake, refuses extension, and resumes the default', async () => {+ await approveSelfThinking();+ const { requestPersistentMindThinkingPreset } = await import('./persistentMindThinkingRequests.js');+ const outcomes = [];+ const run = vi.fn(async ({ turnId }) => {+ outcomes.push(await requestPersistentMindThinkingPreset({ presetId: 'deep', reason: 'Try a focused pass' }, { turnId, requestId: `request-${turnId}` }));+ return {};+ });+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'default-message', text: 'Think about this.' });+ await supervisor.drainPersistentMind();+ expect(outcomes[0].ok).toBe(true);+ expect(mock.root.persistentMind.thinkingRequests.pending).not.toBeNull();+ mock.root.persistentMind.selfWake.notBefore = new Date(0).toISOString();+ await supervisor.drainPersistentMind();+ expect(outcomes[1]).toMatchObject({ ok: false, error: expect.stringContaining('active') });+ expect(mock.root.persistentMind.thinkingRequests).toMatchObject({ pending: null, history: [{ outcome: 'completed' }] });+ await supervisor.enqueuePersistentMindMessage({ id: 'ordinary', text: 'Continue.' });+ await supervisor.drainPersistentMind();+ expect(run.mock.calls.map(([input]) => input.provider.id)).toEqual(['example-cloud', 'example-alt', 'example-cloud']);+ expect(mock.root.config.persistentMindProfile.model).toBe('example-model');+ });++ it('consumes failed self-selected admission and restart recovery without replaying the alternate', async () => {+ await approveSelfThinking();+ const { requestPersistentMindThinkingPreset } = await import('./persistentMindThinkingRequests.js');+ const run = vi.fn(async ({ turnId }) => {+ await requestPersistentMindThinkingPreset({ presetId: 'deep', reason: 'Try once' }, { turnId, requestId: 'one-shot' });+ return {};+ });+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'requesting', text: 'Think.' });+ await supervisor.drainPersistentMind();+ const accepted = structuredClone(mock.root.persistentMind.thinkingRequests.pending);+ mock.root.persistentMind.selfWake.notBefore = new Date(0).toISOString();+ mock.thinkingSession = { ok: false, error: 'Model unavailable' };+ await supervisor.drainPersistentMind();+ expect(run).toHaveBeenCalledTimes(1);+ expect(mock.root.persistentMind.thinkingRequests).toMatchObject({ pending: null, history: [{ outcome: 'failed' }] });+ expect(mock.root.persistentMind.selfWake?.thinkingRequest).toBeUndefined();+ mock.root.persistentMind.activeTurn = { id: 'orphan', startedAt: new Date().toISOString(), wake: {+ kind: 'self', id: 'wake-orphan', sourceTurnId: 'prior', reason: 'Try once', thinkingRequest: accepted,+ } };+ supervisor.__resetPersistentMindSupervisorForTests();+ await supervisor.initializePersistentMindSupervisor();+ expect(mock.root.persistentMind.activeTurn).toBeNull();+ expect(mock.root.persistentMind.selfWake?.thinkingRequest).toBeUndefined();+ expect(mock.root.persistentMind.thinkingRequests.history).toHaveLength(1);+ });+it('runs one selected message on its preset and returns the very next turn to the default', async () => {withDeepPreset();const run = vi.fn(async () => ({}));diff --git a/server/services/persistentMindThinkingRequests.js b/server/services/persistentMindThinkingRequests.jsnew file mode 100644index 0000000000..0fb50a5a49--- /dev/null+++ b/server/services/persistentMindThinkingRequests.js@@ -0,0 +1,132 @@+/** Human-approved local routes and one-shot self-wake requests. No inference. */+import { canonicalStringify } from '../lib/objects.js';+import { sha256Text } from '../lib/fileUtils.js';+import { localRuntimeForProvider, normalizeOpenAiBaseUrl } from '../lib/localProviderRuntime.js';+import { normalizePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';+import { normalizePersistentMindState } from '../lib/persistentMind.js';+import {+ normalizePersistentMindThinkingPresets,+ persistentMindThinkingRequestSchema,+ PERSISTENT_MIND_THINKING_LIMITS,+} from '../lib/persistentMindThinkingPresets.js';+import { loadState, saveState, withStateLock } from './cosState.js';+import { resolvePersistentMindThinkingSession } from './persistentMindProfile.js';+import { appendMindEvent } from './agentRunEventLog.js';++// A direct local API transport has no account-backed CLI fallback. Remove all+// display/model identity heuristics before asking the shared runtime resolver.+function localGrant(selection, provider) {+ if (provider?.type !== 'api' || !provider.endpoint || provider.apiKey || provider.apiKeyEnvVar+ || provider.gatewayBacked || provider.orcarouterBacked+ || Object.keys(provider.envVars || {}).length) return null;+ const url = URL.parse(provider.endpoint);+ if (!url || !['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) return null;+ const runtime = localRuntimeForProvider({ ...provider, id: '', name: '', defaultModel: '', command: '' });+ if (!runtime || runtime.endpoint !== normalizeOpenAiBaseUrl(provider.endpoint)) return null;+ return sha256Text(canonicalStringify({+ selection, name: provider.name || '', type: provider.type,+ endpoint: provider.endpoint, runtime: runtime.kind, apiFormat: provider.apiFormat || '',+ }));+}++async function eligible(config) {+ const rows = [];+ for (const selection of normalizePersistentMindThinkingPresets(config?.persistentMindThinkingPresets).presets) {+ const route = await resolvePersistentMindThinkingSession({ presetId: selection.id, selection, config });+ const grant = route.ok ? localGrant(selection, route.provider) : null;+ if (grant) rows.push({ selection, grant, route });+ }+ return rows;+}++/** Called ONLY by the human config update path, never by semantic actions. */+export async function approvePersistentMindThinkingPresets(config, ids) {+ const rows = await eligible(config);+ return Object.fromEntries(rows.filter(({ selection }) => ids.includes(selection.id))+ .map(({ selection, grant }) => [selection.id, grant]));+}++export async function resolvePersistentMindSelfThinkingRequest({ request, config }) {+ const grants = normalizePersistentMindCapabilities(config?.persistentMindCapabilities);+ const refused = { ok: false, requiresResubmission: true, error: 'Local thinking request was revoked or its approved route changed' };+ if (!request || !grants.chooseThinkingPreset || !grants.thinkingPresetAllowlist.includes(request.selection.id)+ || grants.thinkingPresetGrants[request.selection.id] !== request.grant) return refused;+ const route = await resolvePersistentMindThinkingSession({ presetId: request.selection.id, selection: request.selection, config });+ if (!route.ok) return { ...route, requiresResubmission: true };+ return localGrant(request.selection, route.provider) === request.grant ? route : refused;+}++export async function getPersistentMindThinkingRequestCatalog({ human = false } = {}) {+ const root = await loadState();+ const mind = normalizePersistentMindState(root.persistentMind);+ const grants = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);+ const rows = await eligible(root.config);+ return {+ enabled: grants.chooseThinkingPreset,+ presets: rows.filter(({ selection, grant }) => human || (grants.chooseThinkingPreset+ && grants.thinkingPresetAllowlist.includes(selection.id) && grants.thinkingPresetGrants[selection.id] === grant))+ .map(({ selection }) => selection),+ current: mind.activeTurn ? { providerId: mind.activeTurn.providerId, model: mind.activeTurn.model, effort: mind.activeTurn.effort } : null,+ default: root.config?.persistentMindProfile ? {+ providerId: root.config.persistentMindProfile.providerId, model: root.config.persistentMindProfile.model,+ effort: root.config.persistentMindProfile.effort,+ } : null,+ limits: PERSISTENT_MIND_THINKING_LIMITS,+ pending: mind.thinkingRequests.pending ? publicRequest(mind.thinkingRequests.pending) : null,+ recent: mind.thinkingRequests.history.map(publicRequest),+ explanation: 'Next self-directed wake only; current turn and default remain unchanged. One pending or active request, three per rolling 24 hours, 30 minutes apart. Cancellation and failure do not refund allowance.',+ };+}++const publicRequest = ({ requestId, at, reason, selection, outcome = 'pending' }) => ({ requestId, at, reason, outcome, presetId: selection.id, label: selection.label });++export async function requestPersistentMindThinkingPreset(args, { turnId, requestId, signal } = {}) {+ const parsed = persistentMindThinkingRequestSchema.parse(args);+ return withStateLock(async () => {+ const root = await loadState();+ const mind = normalizePersistentMindState(root.persistentMind);+ const fail = (error) => ({ ok: false, error });+ if (signal?.aborted || !turnId || !requestId || mind.activeTurn?.id !== turnId || !mind.started || !mind.enabled) return fail('Request requires the active mind turn');+ const prior = mind.thinkingRequests.history.find((entry) => entry.requestId === requestId);+ if (prior) return prior.selection.id === parsed.presetId && prior.reason === parsed.reason+ ? { ok: true, duplicate: true, request: publicRequest(prior) } : fail('Request id already used');+ if (mind.thinkingRequests.pending || mind.activeTurn.wake?.thinkingRequest) return fail('A local thinking request is already pending or active');+ const now = Date.now();+ const recent = mind.thinkingRequests.history.filter((entry) => Date.parse(entry.admittedAt || entry.at) > now - PERSISTENT_MIND_THINKING_LIMITS.rollingWindowMs);+ if (recent.length >= PERSISTENT_MIND_THINKING_LIMITS.maxPerRollingDay) return fail('Three local thinking requests already used in the rolling 24 hours');+ if (recent.some((entry) => now - Date.parse(entry.admittedAt || entry.at) < PERSISTENT_MIND_THINKING_LIMITS.minGapMs)) return fail('Local thinking requests must be 30 minutes apart');+ const grants = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);+ const selection = normalizePersistentMindThinkingPresets(root.config?.persistentMindThinkingPresets).presets.find((entry) => entry.id === parsed.presetId);+ if (!selection) return fail('Preset is no longer available');+ const request = { outcome: 'pending', requestId, turnId, at: new Date(now).toISOString(), reason: parsed.reason, selection, grant: grants.thinkingPresetGrants[selection.id] };+ const route = await resolvePersistentMindSelfThinkingRequest({ request, config: root.config });+ if (!route.ok) return fail(route.error);+ if (signal?.aborted) return fail('Mind turn interrupted');+ mind.thinkingRequests = { pending: request, history: [...mind.thinkingRequests.history, request].slice(-20) };+ root.persistentMind = mind;+ // Charge before emitting or returning, so uncertain delivery never refunds.+ await saveState(root);+ await appendMindEvent({ kind: 'mind.capability.request', mindId: mind.mindId, turnId,+ eventId: `thinking-request:${requestId}`, data: { ...publicRequest(request), displayText: `Requested local preset ${selection.label}: ${parsed.reason}` } });+ return { ok: true, request: publicRequest(request) };+ });+}++export async function cancelPersistentMindThinkingRequest({ ifRevoked = false } = {}) {+ return withStateLock(async () => {+ const root = await loadState();+ const mind = normalizePersistentMindState(root.persistentMind);+ const request = mind.thinkingRequests.pending;+ if (ifRevoked && request) {+ const route = await resolvePersistentMindSelfThinkingRequest({ request, config: root.config });+ if (route.ok) return { ok: true, cancelled: false };+ }+ mind.thinkingRequests.pending = null;+ mind.thinkingRequests.history = mind.thinkingRequests.history.map((entry) => entry.requestId === request?.requestId ? { ...entry, outcome: 'cancelled' } : entry);+ root.persistentMind = mind;+ await saveState(root);+ if (request) await appendMindEvent({ kind: 'mind.capability.result', mindId: mind.mindId, turnId: request.turnId,+ eventId: `thinking-cancelled:${request.requestId}`, data: { ...publicRequest(request), displayText: 'Pending local thinking request cancelled; allowance retained', outcome: 'cancelled' } });+ return { ok: true };+ });+}diff --git a/server/services/persistentMindThinkingRequests.test.js b/server/services/persistentMindThinkingRequests.test.jsnew file mode 100644index 0000000000..a36d66988b--- /dev/null+++ b/server/services/persistentMindThinkingRequests.test.js@@ -0,0 +1,91 @@+import { beforeEach, afterEach, expect, it, vi } from 'vitest';+import { createDefaultPersistentMindState, normalizePersistentMindState } from '../lib/persistentMind.js';+import { normalizePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';+const mock = vi.hoisted(() => ({ root: null, provider: null, events: [] }));+vi.mock('./cosState.js', () => ({ loadState: async () => mock.root,+ saveState: async (root) => { mock.root = JSON.parse(JSON.stringify(root)); }, withStateLock: async (fn) => fn() }));+vi.mock('./providers.js', () => ({ getProviderById: async () => mock.provider }));+vi.mock('./providerStatus.js', () => ({ isProviderAvailable: () => true, getProviderStatus: () => null }));+vi.mock('./agentRunEventLog.js', () => ({ appendMindEvent: async (event) => { mock.events.push(event); } }));+import { approvePersistentMindThinkingPresets, getPersistentMindThinkingRequestCatalog,+ requestPersistentMindThinkingPreset, resolvePersistentMindSelfThinkingRequest,+ cancelPersistentMindThinkingRequest } from './persistentMindThinkingRequests.js';+const selection = { id: 'local', label: 'Local pass', providerId: 'example-local', model: 'example-model', effort: '' };+const context = (requestId = 'request-1') => ({ turnId: 'turn-1', requestId });+const request = (requestId) => requestPersistentMindThinkingPreset({ presetId: 'local', reason: 'Try a focused pass' }, context(requestId));+async function approve() {+ const config = mock.root.config;+ config.persistentMindCapabilities = { ...normalizePersistentMindCapabilities(), chooseThinkingPreset: true, thinkingPresetAllowlist: ['local'], thinkingPresetGrants: await approvePersistentMindThinkingPresets(config, ['local']) };+}+beforeEach(() => {+ vi.useFakeTimers(); vi.setSystemTime(new Date('2026-01-01T12:00:00Z')); mock.events = [];+ mock.provider = { id: 'example-local', name: 'Example runtime', type: 'api', endpoint: 'http://localhost:1234/v1', models: ['example-model'] };+ mock.root = { config: { persistentMindProfile: { enabled: true, providerId: 'example-default', model: 'home' }, persistentMindThinkingPresets: { presets: [selection] } },+ persistentMind: { ...createDefaultPersistentMindState(), enabled: true, started: true, activeTurn: { id: 'turn-1', wake: { kind: 'message', message: { id: 'message-1', text: 'Hello' } } } } };+});+afterEach(() => vi.useRealTimers());+it('lists only exact human-approved local routes and never modifies the home profile', async () => {+ const original = structuredClone(mock.root.config.persistentMindProfile);+ expect((await getPersistentMindThinkingRequestCatalog()).presets).toEqual([]);+ expect((await request()).ok).toBe(false);+ await approve();+ expect((await getPersistentMindThinkingRequestCatalog()).presets).toEqual([selection]);+ expect((await request()).ok).toBe(true);+ expect(mock.root.config.persistentMindProfile).toEqual(original);+ expect(mock.root.persistentMind.activeTurn.wake.kind).toBe('message');+ expect((await request()).duplicate).toBe(true);+ expect((await request('request-2')).error).toMatch(/pending/);+ expect(mock.events[0].data.displayText).toContain('Try a focused pass');+});+it('retains quota through cancellation and process-style reloads, including the rolling window', async () => {+ await approve();+ for (let i = 0; i < 3; i += 1) {+ expect((await request(`request-${i}`)).ok).toBe(true);+ await cancelPersistentMindThinkingRequest();+ mock.root.persistentMind = normalizePersistentMindState(JSON.parse(JSON.stringify(mock.root.persistentMind)));+ expect((await request(`early-${i}`)).ok).toBe(false);+ vi.advanceTimersByTime(30 * 60_000);+ }+ expect((await request('over-limit')).error).toMatch(/Three/);+ expect(mock.root.persistentMind.thinkingRequests.history).toHaveLength(3);+ vi.advanceTimersByTime(24 * 60 * 60_000);+ expect((await request('next-day')).ok).toBe(true);+});+it.each([+ ['provider rename', () => { mock.provider.name = 'Renamed'; }],+ ['endpoint change', () => { mock.provider.endpoint = 'http://localhost:1234/changed/v1'; }],+ ['removed model', () => { mock.provider.models = []; }],+ ['unsupported effort', () => { mock.root.config.persistentMindThinkingPresets.presets[0] = { ...selection, effort: 'max' }; }],+ ['removed preset', () => { mock.root.config.persistentMindThinkingPresets.presets = []; }],+ ['revoked grant', () => { mock.root.config.persistentMindCapabilities.chooseThinkingPreset = false; }],+ ['account credential', () => { mock.provider.apiKey = 'example-test-key'; }],+])('refuses a stale accepted route after %s, without selecting another alternate', async (_name, change) => {+ await approve(); await request();+ const pending = mock.root.persistentMind.thinkingRequests.pending;+ change();+ expect((await resolvePersistentMindSelfThinkingRequest({ request: pending, config: mock.root.config })).ok).toBe(false);+ expect((await getPersistentMindThinkingRequestCatalog()).presets).toEqual([]);+});+it('refuses name-based guesses, remote accounts, CLI wrappers, config injection and inactive callers', async () => {+ const base = { ...mock.provider };+ for (const provider of [+ { ...base, name: 'Ollama', endpoint: 'https://example.com/v1' },+ { ...base, name: 'LM Studio', endpoint: 'http://localhost:9999/v1' },+ { ...base, type: 'cli', command: 'example' },+ ]) {+ mock.provider = provider; await approve(); expect((await request()).ok).toBe(false);+ }+ await expect(requestPersistentMindThinkingPreset({ presetId: 'local', reason: 'change', endpoint: 'https://example.com' }, context())).rejects.toThrow();+ expect((await requestPersistentMindThinkingPreset({ presetId: 'local', reason: 'change' }, { turnId: 'old', requestId: 'old' })).ok).toBe(false);+});++it('does not resurrect a revoked pending request after re-approval, and charges delayed admission time', async () => {+ await approve(); await request();+ mock.root.config.persistentMindCapabilities.thinkingPresetAllowlist = [];+ await cancelPersistentMindThinkingRequest({ ifRevoked: true });+ await approve();+ expect(mock.root.persistentMind.thinkingRequests.pending).toBeNull();+ vi.advanceTimersByTime(25 * 60 * 60_000);+ mock.root.persistentMind.thinkingRequests.history[0].admittedAt = new Date().toISOString();+ expect((await request('after-delayed-admission')).error).toMatch(/30 minutes/);+});