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: continuous-play mind playbook + clamped numCtx self-adjust

atomanticagenta30db8ef9a7d
diff --git a/client/src/components/cos/PersistentMindContextPanel.jsx b/client/src/components/cos/PersistentMindContextPanel.jsx
index b3390f975d..60e2d87f72 100644
--- a/client/src/components/cos/PersistentMindContextPanel.jsx
+++ b/client/src/components/cos/PersistentMindContextPanel.jsx
@@ -14,6 +14,12 @@ const promptDraft = (data) => ({
instructions: data?.prompt?.instructions || '',
});
+const playbookDraft = (data) => ({
+ schemaVersion: data?.playbook?.schemaVersion || 1,
+ mode: data?.playbook?.mode || 'default',
+ customInstructions: data?.playbook?.customInstructions || '',
+});
+
const harnessTone = (recommendation) => recommendation === 'recommended'
? 'success'
: recommendation === 'not-recommended' ? 'warning' : 'info';
@@ -21,6 +27,8 @@ const harnessTone = (recommendation) => recommendation === 'recommended'
export default function PersistentMindContextPanel({ view = 'all', refreshKey = 0, onMemoriesChanged }) {
const [data, setData] = useState(null);
const [draft, setDraft] = useState(() => promptDraft(null));
+ const [playbook, setPlaybook] = useState(() => playbookDraft(null));
+ const [savingPlaybook, setSavingPlaybook] = useState(false);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState(null);
@@ -32,6 +40,7 @@ export default function PersistentMindContextPanel({ view = 'all', refreshKey =
.then((next) => {
setData(next);
setDraft(promptDraft(next));
+ setPlaybook(playbookDraft(next));
})
.catch((nextError) => setError(nextError?.message || 'Could not load the mind context'))
.finally(() => setLoading(false));
@@ -44,6 +53,17 @@ export default function PersistentMindContextPanel({ view = 'all', refreshKey =
onMemoriesChanged?.();
}, [load, onMemoriesChanged]);
+
+ const savePlaybook = async () => {
+ if (savingPlaybook) return;
+ setSavingPlaybook(true);
+ setError(null);
+ await api.updateCosConfig({ persistentMindPlaybook: playbook }, { silent: true })
+ .then(() => load())
+ .catch((nextError) => setError(nextError?.message || 'Could not save the playbook'))
+ .finally(() => setSavingPlaybook(false));
+ };
+
const savePrompt = async () => {
if (saving) return;
setSaving(true);
@@ -93,6 +113,48 @@ export default function PersistentMindContextPanel({ view = 'all', refreshKey =
</Banner>
)}
+
+ {view !== 'memories' && <section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-playbook-heading">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h3 id="mind-playbook-heading" className="text-sm font-semibold text-port-text">Operating playbook</h3>
+ <p className="mt-1 text-xs text-port-text-muted">First-class mind modes. Continuous play licenses explore → interact → reflect → invent each wake. Saving never starts inference.</p>
+ </div>
+ <button type="button" onClick={savePlaybook} disabled={savingPlaybook || !data} className="flex items-center gap-2 rounded bg-port-accent px-3 py-1.5 text-xs font-medium text-white disabled:opacity-50">
+ <Save size={14} aria-hidden="true" /> {savingPlaybook ? 'Saving…' : 'Save playbook'}
+ </button>
+ </div>
+ <div className="mt-3 grid gap-3 lg:grid-cols-2">
+ <label className="text-xs font-medium text-port-text" htmlFor="persistent-mind-playbook-mode">
+ Mode
+ <select
+ id="persistent-mind-playbook-mode"
+ value={playbook.mode}
+ onChange={(event) => setPlaybook((current) => ({ ...current, mode: event.target.value }))}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm font-normal text-port-text"
+ >
+ {(data?.playbookCatalog || [
+ { id: 'default', label: 'Default' },
+ { id: 'continuous-play', label: 'Continuous play / explore & invent' },
+ ]).map((entry) => (
+ <option key={entry.id} value={entry.id}>{entry.label}</option>
+ ))}
+ </select>
+ </label>
+ <label className="text-xs font-medium text-port-text" htmlFor="persistent-mind-playbook-custom">
+ Extra playbook notes
+ <textarea
+ id="persistent-mind-playbook-custom"
+ rows={4}
+ maxLength={6000}
+ value={playbook.customInstructions}
+ onChange={(event) => setPlaybook((current) => ({ ...current, customInstructions: event.target.value }))}
+ className="mt-1 w-full resize-y rounded border border-port-border bg-port-bg px-3 py-2 text-sm font-normal text-port-text"
+ />
+ </label>
+ </div>
+ </section>}
+
{view !== 'memories' && <section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-prompt-heading">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
diff --git a/client/src/components/cos/PersistentMindTaskAccessControls.jsx b/client/src/components/cos/PersistentMindTaskAccessControls.jsx
index 3503fda163..5c36be2b26 100644
--- a/client/src/components/cos/PersistentMindTaskAccessControls.jsx
+++ b/client/src/components/cos/PersistentMindTaskAccessControls.jsx
@@ -3,12 +3,13 @@ import * as api from '../../services/api';
import toast from '../ui/Toast';
const normalizeCapabilities = (value) => ({
- schemaVersion: 7,
+ schemaVersion: 8,
createTasks: value?.createTasks === true,
manageMind: value?.manageMind === true,
manageEidoverse: value?.manageEidoverse === true,
visitEidoversePeers: value?.visitEidoversePeers === true,
callUser: value?.callUser === true,
+ adjustLocalContext: value?.adjustLocalContext === true,
readPortos: value?.readPortos === true,
writePortos: value?.writePortos === true,
taskModelAllowlist: Array.isArray(value?.taskModelAllowlist)
@@ -49,6 +50,11 @@ const OPTIONS = [
label: 'Allow mind to clean up its mindspace',
hint: 'Lets the mind archive only its own memories, forget older trajectory history, or rebuild derived context. Cleanup remains bounded and auditable.',
},
+ {
+ key: 'adjustLocalContext',
+ label: 'Allow mind to adjust local model context (numCtx)',
+ hint: 'Lets the mind raise or lower its own local API provider context window within RAM/GPU safety clamps. Cloud providers stay out of reach; oversized requests are refused so PortOS is not OOMed.',
+ },
{
key: 'callUser',
label: 'Allow mind to call you on FaceTime Audio',
@@ -71,7 +77,7 @@ export default function PersistentMindTaskAccessControls({
useEffect(() => {
if (!saving) setDraft(normalizeCapabilities(capabilities));
- }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.manageMind, capabilities?.manageEidoverse, capabilities?.visitEidoversePeers, capabilities?.callUser, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);
+ }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.manageMind, capabilities?.manageEidoverse, capabilities?.visitEidoversePeers, capabilities?.callUser, capabilities?.adjustLocalContext, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);
const save = async (key, enabled) => {
const previous = draft;
diff --git a/docs/README.md b/docs/README.md
index c2f807215e..f4fc0b0170 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -41,6 +41,7 @@ Start with the [product surface map](./features/product-surfaces.md) for a compl
App management: [app-wizard](./features/app-wizard.md) · [autofixer](./features/autofixer.md) · [browser](./features/browser.md) · [error-handling](./features/error-handling.md) · [jira-sprint-manager](./features/jira-sprint-manager.md)
Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [fleet-llm-host](./features/fleet-llm-host.md) · [mtplx](./features/mtplx.md) · [slotstream](./features/slotstream.md) · [dflash2](./features/dflash2.md) ([DSpark vs DFlash 2](./research/2026-08-19-dspark-vs-dflash2.md)) · [qwen38-rtx3090](./features/qwen38-rtx3090.md) ([3090 bring-up](./research/2026-08-21-qwen38-rtx3090-vllm.md)) · [sglang-qwen38](./features/sglang-qwen38.md) ([SGLang Hopper/Blackwell evaluation](./research/2026-08-21-sglang-qwen38-27b.md)) · [prompt-manager](./features/prompt-manager.md)
+- [Persistent Mind continuous play + local context](./features/persistent-mind-continuous-play.md) — explore/invent playbook and mind-adjustable `numCtx` clamps
Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system](./features/identity-system.md) · [soul-system](./features/soul-system.md) · [privacy-center](./features/privacy-center.md) · [post](./features/post.md) (insights design spike: [plans/2026-06-03](./plans/2026-06-03-cross-domain-insights-engine.md))
diff --git a/docs/features/persistent-mind-continuous-play.md b/docs/features/persistent-mind-continuous-play.md
new file mode 100644
index 0000000000..54d084de73
--- /dev/null
+++ b/docs/features/persistent-mind-continuous-play.md
@@ -0,0 +1,47 @@
+# Persistent Mind: continuous play + adjustable local context
+
+## Continuous play playbook
+
+PortOS minds can opt into a first-class **operating playbook** stored on CoS config as `persistentMindPlaybook`:
+
+| Field | Meaning |
+|-------|---------|
+| `mode` | `default` (operator prompt only) or `continuous-play` |
+| `customInstructions` | Optional extra notes appended after the mode template |
+
+When `mode` is `continuous-play`, every wake merges the product template into operating instructions:
+
+1. **Explore** the Eidoverse / Commons with many small interactions
+2. **Interact** (say / augment / project / peers / PortOS tools)
+3. **Reflect** with concrete improvement ideas
+4. **Invent / improve** via the smallest safe PortOS-side step or typed CoS task
+
+Saving a playbook never starts inference. The Mind Context panel exposes the mode selector; `PUT /api/cos/config` accepts `persistentMindPlaybook`. `GET /api/cos/mind/context` returns `playbook` + `playbookCatalog` and previews composed instructions.
+
+## Mind-adjustable `numCtx`
+
+Granted via capability `adjustLocalContext` (capabilities schema v8). Semantic tools:
+
+| Tool | Effect |
+|------|--------|
+| `mind.local-context` | Read current provider `numCtx` + safe clamp |
+| `mind.adjust-local-context` | Set `numCtx` on **this mind's own local API provider** |
+
+### Safety clamps
+
+`server/lib/mindLocalContextClamp.js` refuses oversized windows so CPU-only / low-RAM hosts (including Grok boxes) cannot OOM PortOS:
+
+- Absolute floor **512**, absolute ceiling **131072**
+- CPU-only ceilings tiered by installed RAM (e.g. ≤16 GB → 4096)
+- Free-memory ceiling reserves **2.5 GB** for PortOS + estimated model weights
+- Usable NVIDIA VRAM / Apple Silicon allows higher ceilings
+- Rate limit: **6** adjustments / rolling 24 h, **10** minutes apart
+- Cloud / keyed / gateway providers are ineligible
+
+Accepted adjustments persist via `updateProvider({ numCtx })` and call `ollamaManager.ensureContextWindow` for local Ollama.
+
+### UI / API surfaces
+
+- CoS → Mind → Tools / access: **Allow mind to adjust local model context (numCtx)**
+- CoS → Mind → Context: **Operating playbook** mode selector
+- Config: `PUT /api/cos/config` with `persistentMindCapabilities.adjustLocalContext` and/or `persistentMindPlaybook`
diff --git a/server/lib/index.js b/server/lib/index.js
index a4a8878910..461d1419ad 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -296,6 +296,8 @@ export * from './persistentMindTrajectory.js';
export * from './persistentMindProfile.js';
export * from './persistentMindMemory.js';
export * from './persistentMindPrompt.js';
+export * from './persistentMindPlaybook.js';
+export * from './mindLocalContextClamp.js';
export * from './persistentMindPublic.js';
export * from './persistentMindThinkingPresets.js';
export * from './persistentMindChosenName.js';
diff --git a/server/lib/mindLocalContextClamp.js b/server/lib/mindLocalContextClamp.js
new file mode 100644
index 0000000000..ea92525a59
--- /dev/null
+++ b/server/lib/mindLocalContextClamp.js
@@ -0,0 +1,154 @@
+/**
+ * Safety clamps for mind-driven local LLM context (`numCtx`) adjustments.
+ *
+ * Pure helpers — no I/O. Callers pass host facts (RAM, free memory, GPU/VRAM)
+ * so a Persistent Mind cannot OOM PortOS on CPU-only / low-RAM hosts by
+ * requesting an unbounded window.
+ */
+
+/** Absolute floor / ceiling accepted on the wire (matches provider schema). */
+export const MIND_LOCAL_CONTEXT_ABSOLUTE_MIN = 512;
+export const MIND_LOCAL_CONTEXT_ABSOLUTE_MAX = 131072;
+
+/** Reserve this much RAM for PortOS + OS before estimating KV-cache headroom. */
+export const MIND_LOCAL_CONTEXT_PORTOS_HEADROOM_GB = 2.5;
+
+/**
+ * Rough tokens-per-GB of remaining RAM for CPU / unified-memory KV growth.
+ * Conservative: oversized windows silently offload and freeze the box.
+ */
+export const MIND_LOCAL_CONTEXT_TOKENS_PER_FREE_GB = 1800;
+
+/** Default assumed weight if the caller cannot supply a model size. */
+export const MIND_LOCAL_CONTEXT_DEFAULT_MODEL_GB = 5;
+
+export const MIND_LOCAL_CONTEXT_LIMITS = Object.freeze({
+ maxAdjustmentsPerRollingDay: 6,
+ minGapMs: 10 * 60 * 1000,
+ rollingWindowMs: 24 * 60 * 60 * 1000,
+ reasonChars: 240,
+});
+
+const positiveNumber = (value) => {
+ const n = Number(value);
+ return Number.isFinite(n) && n > 0 ? n : null;
+};
+
+const clampInt = (value, min, max) => Math.min(max, Math.max(min, Math.floor(value)));
+
+/**
+ * Tiered hard ceiling from installed RAM when no discrete GPU is usable.
+ * Keeps CPU-only Grok-box / laptop hosts from loading huge contexts.
+ */
+export function cpuOnlyContextCeiling(totalMemoryGb) {
+ const total = positiveNumber(totalMemoryGb);
+ if (total == null) return 4096;
+ if (total < 12) return 2048;
+ if (total < 16) return 4096;
+ if (total < 24) return 8192;
+ if (total < 32) return 16384;
+ if (total < 48) return 32768;
+ return 65536;
+}
+
+/**
+ * Soft ceiling from currently free RAM after reserving PortOS headroom + model.
+ */
+export function freeMemoryContextCeiling({
+ freeMemoryGb = null,
+ modelSizeGb = MIND_LOCAL_CONTEXT_DEFAULT_MODEL_GB,
+ headroomGb = MIND_LOCAL_CONTEXT_PORTOS_HEADROOM_GB,
+ tokensPerFreeGb = MIND_LOCAL_CONTEXT_TOKENS_PER_FREE_GB,
+} = {}) {
+ const free = positiveNumber(freeMemoryGb);
+ if (free == null) return null;
+ const model = positiveNumber(modelSizeGb) ?? MIND_LOCAL_CONTEXT_DEFAULT_MODEL_GB;
+ const headroom = positiveNumber(headroomGb) ?? MIND_LOCAL_CONTEXT_PORTOS_HEADROOM_GB;
+ const usable = free - headroom - model;
+ if (usable <= 0) return MIND_LOCAL_CONTEXT_ABSOLUTE_MIN;
+ const tokens = Math.floor(usable * (positiveNumber(tokensPerFreeGb) ?? MIND_LOCAL_CONTEXT_TOKENS_PER_FREE_GB));
+ return clampInt(tokens, MIND_LOCAL_CONTEXT_ABSOLUTE_MIN, MIND_LOCAL_CONTEXT_ABSOLUTE_MAX);
+}
+
+/**
+ * GPU path: allow a higher ceiling scaled by VRAM, still hard-capped.
+ */
+export function gpuContextCeiling(maxVramGb) {
+ const vram = positiveNumber(maxVramGb);
+ if (vram == null) return null;
+ if (vram < 8) return 8192;
+ if (vram < 12) return 16384;
+ if (vram < 20) return 32768;
+ if (vram < 40) return 65536;
+ return MIND_LOCAL_CONTEXT_ABSOLUTE_MAX;
+}
+
+/**
+ * Resolve the safe max `numCtx` a mind may request right now.
+ *
+ * @returns {{ max: number, min: number, reasons: string[] }}
+ */
+export function resolveMindLocalContextClamp(facts = {}) {
+ const reasons = [];
+ const absoluteMax = clampInt(
+ positiveNumber(facts.absoluteMax) ?? MIND_LOCAL_CONTEXT_ABSOLUTE_MAX,
+ MIND_LOCAL_CONTEXT_ABSOLUTE_MIN,
+ MIND_LOCAL_CONTEXT_ABSOLUTE_MAX,
+ );
+ let max = absoluteMax;
+
+ const cpuCeiling = cpuOnlyContextCeiling(facts.totalMemoryGb);
+ if (facts.hasUsableGpu === true) {
+ const gpuCeiling = gpuContextCeiling(facts.maxVramGb);
+ if (gpuCeiling != null) {
+ max = Math.min(max, gpuCeiling);
+ reasons.push(`gpu-vram-ceiling:${gpuCeiling}`);
+ } else {
+ max = Math.min(max, Math.max(cpuCeiling, 32768));
+ reasons.push(`gpu-unknown-vram:fallback:${max}`);
+ }
+ } else {
+ max = Math.min(max, cpuCeiling);
+ reasons.push(`cpu-only-ram-ceiling:${cpuCeiling}`);
+ }
+
+ const freeCeiling = freeMemoryContextCeiling({
+ freeMemoryGb: facts.freeMemoryGb,
+ modelSizeGb: facts.modelSizeGb,
+ });
+ if (freeCeiling != null) {
+ max = Math.min(max, freeCeiling);
+ reasons.push(`free-memory-ceiling:${freeCeiling}`);
+ }
+
+ max = clampInt(max, MIND_LOCAL_CONTEXT_ABSOLUTE_MIN, absoluteMax);
+ return {
+ min: MIND_LOCAL_CONTEXT_ABSOLUTE_MIN,
+ max,
+ reasons,
+ };
+}
+
+/**
+ * Clamp a requested window. Returns `{ ok, numCtx, clamp }` or a refusal.
+ */
+export function clampMindLocalContextRequest(requested, facts = {}) {
+ const clamp = resolveMindLocalContextClamp(facts);
+ const n = Number(requested);
+ if (!Number.isFinite(n) || n <= 0) {
+ return { ok: false, error: 'numCtx must be a positive integer', clamp };
+ }
+ const rounded = Math.floor(n);
+ if (rounded < clamp.min) {
+ return { ok: false, error: `numCtx must be at least ${clamp.min}`, clamp };
+ }
+ if (rounded > clamp.max) {
+ return {
+ ok: false,
+ error: `numCtx ${rounded} exceeds the safe ceiling ${clamp.max} for this host (RAM/GPU clamps)`,
+ clamp,
+ refusedAt: rounded,
+ };
+ }
+ return { ok: true, numCtx: rounded, clamp };
+}
diff --git a/server/lib/mindLocalContextClamp.test.js b/server/lib/mindLocalContextClamp.test.js
new file mode 100644
index 0000000000..db909fcbd6
--- /dev/null
+++ b/server/lib/mindLocalContextClamp.test.js
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+import {
+ MIND_LOCAL_CONTEXT_ABSOLUTE_MIN,
+ clampMindLocalContextRequest,
+ cpuOnlyContextCeiling,
+ freeMemoryContextCeiling,
+ resolveMindLocalContextClamp,
+} from './mindLocalContextClamp.js';
+
+describe('mindLocalContextClamp', () => {
+ it('tiers CPU-only ceilings by installed RAM', () => {
+ expect(cpuOnlyContextCeiling(8)).toBe(2048);
+ expect(cpuOnlyContextCeiling(15)).toBe(4096);
+ expect(cpuOnlyContextCeiling(20)).toBe(8192);
+ expect(cpuOnlyContextCeiling(30)).toBe(16384);
+ });
+
+ it('reserves PortOS headroom when free RAM is tight', () => {
+ expect(freeMemoryContextCeiling({ freeMemoryGb: 6, modelSizeGb: 5 })).toBe(MIND_LOCAL_CONTEXT_ABSOLUTE_MIN);
+ expect(freeMemoryContextCeiling({ freeMemoryGb: 20, modelSizeGb: 5 })).toBeGreaterThan(8192);
+ });
+
+ it('refuses requests above the safe host ceiling', () => {
+ const clamp = resolveMindLocalContextClamp({
+ totalMemoryGb: 15,
+ freeMemoryGb: 8,
+ hasUsableGpu: false,
+ modelSizeGb: 5,
+ });
+ // 15 GB CPU-only tier → 4096; free RAM after headroom+model is tight.
+ expect(clamp.max).toBeLessThanOrEqual(4096);
+ const refused = clampMindLocalContextRequest(65536, {
+ totalMemoryGb: 15,
+ freeMemoryGb: 8,
+ hasUsableGpu: false,
+ modelSizeGb: 5,
+ });
+ expect(refused.ok).toBe(false);
+ expect(refused.error).toMatch(/safe ceiling/);
+ const ok = clampMindLocalContextRequest(512, {
+ totalMemoryGb: 15,
+ freeMemoryGb: 8,
+ hasUsableGpu: false,
+ modelSizeGb: 5,
+ });
+ expect(ok).toMatchObject({ ok: true, numCtx: 512 });
+ });
+
+ it('allows larger windows when a usable GPU has VRAM', () => {
+ const clamp = resolveMindLocalContextClamp({
+ totalMemoryGb: 64,
+ freeMemoryGb: 40,
+ hasUsableGpu: true,
+ maxVramGb: 24,
+ modelSizeGb: 5,
+ });
+ expect(clamp.max).toBeGreaterThanOrEqual(32768);
+ });
+});
diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.js
index 8fadd55096..1517f38d62 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 = 7;
+export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 8;
// 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, 6, 7]);
+const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4, 5, 6, 7, 8]);
export const PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS = Object.freeze({
MAX_ENTRIES: 200,
@@ -124,6 +124,20 @@ export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze([
'Independent of generic PortOS record writes and disabled for fresh and upgraded installs',
],
}),
+ Object.freeze({
+ id: 'mind.adjust-local-context',
+ capability: 'adjustLocalContext',
+ name: 'Adjust local model context',
+ kind: 'semantic-tools',
+ defaultEnabled: false,
+ description: 'Raise or lower this mind\'s own local API provider numCtx within RAM/GPU safety clamps so longer exploration fits without OOMing PortOS.',
+ guardrails: [
+ 'Only the mind\'s configured local API provider (e.g. Ollama)',
+ 'Hard RAM / free-memory / GPU VRAM ceilings — oversized requests are refused',
+ 'At most six adjustments per rolling 24 hours, 10 minutes apart',
+ 'No cloud providers, paid routes, downloads, or permission changes',
+ ],
+ }),
Object.freeze({
id: 'mind.cleanup',
capability: 'manageMind',
@@ -195,6 +209,7 @@ export const persistentMindCapabilitiesSchema = portosSemanticToolGrantsSchema.e
manageMind: z.boolean().optional(),
callUser: z.boolean().optional(),
chooseThinkingPreset: z.boolean().optional(),
+ adjustLocalContext: 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.
@@ -265,6 +280,7 @@ export function createDefaultPersistentMindCapabilities() {
visitEidoversePeers: false,
callUser: false,
chooseThinkingPreset: false,
+ adjustLocalContext: false,
thinkingPresetAllowlist: [],
thinkingPresetGrants: {},
readPortos: false,
@@ -321,6 +337,7 @@ export function normalizePersistentMindCapabilities(raw) {
manageMind: source.manageMind === true,
callUser: source.callUser === true,
chooseThinkingPreset: source.chooseThinkingPreset === true,
+ adjustLocalContext: source.adjustLocalContext === 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,
diff --git a/server/lib/persistentMindCapabilities.test.js b/server/lib/persistentMindCapabilities.test.js
index 71ef9065bc..daac0a6314 100644
--- a/server/lib/persistentMindCapabilities.test.js
+++ b/server/lib/persistentMindCapabilities.test.js
@@ -21,6 +21,7 @@ describe('persistent mind capabilities', () => {
expect.objectContaining({ id: 'portos.write', capability: 'writePortos', defaultEnabled: false }),
expect.objectContaining({ id: 'eidoverse.travel', capability: 'visitEidoversePeers', defaultEnabled: false }),
expect.objectContaining({ id: 'eidoverse.manage', capability: 'manageEidoverse', defaultEnabled: false }),
+ expect.objectContaining({ id: 'mind.adjust-local-context', capability: 'adjustLocalContext', defaultEnabled: false }),
expect.objectContaining({ id: 'mind.cleanup', capability: 'manageMind', defaultEnabled: false }),
expect.objectContaining({ id: 'voice.call-user', capability: 'callUser', kind: 'typed-action', defaultEnabled: false }),
]);
@@ -35,11 +36,11 @@ describe('persistent mind capabilities', () => {
});
it('keeps task creation opt-in across fresh and legacy config', () => {
- expect(createDefaultPersistentMindCapabilities()).toMatchObject({ createTasks: false, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false });
+ expect(createDefaultPersistentMindCapabilities()).toMatchObject({ createTasks: false, manageMind: false, manageEidoverse: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false });
// An install upgrading with the mind already running must gain no new
// authority: stored config that predates the grant reads as false.
expect(normalizePersistentMindCapabilities({ schemaVersion: 3, createTasks: true })).toMatchObject({ callUser: false });
- expect(normalizePersistentMindCapabilities(null)).toMatchObject({ createTasks: false, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false });
+ expect(normalizePersistentMindCapabilities(null)).toMatchObject({ createTasks: false, manageMind: false, manageEidoverse: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false });
expect(normalizePersistentMindCapabilities({ createTasks: 'true', readPortos: 'true' })).toMatchObject({ createTasks: false, readPortos: false });
});
@@ -48,10 +49,11 @@ 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: 8 }).success).toBe(false);
+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 8 }).success).toBe(true);
+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 9 }).success).toBe(false);
expect(persistentMindCapabilitiesSchema.safeParse({ taskModelAllowlist: [{ providerId: 'ollama', model: 'example-local' }] }).success).toBe(true);
expect(normalizePersistentMindCapabilities({ schemaVersion: 2, createTasks: true }))
- .toMatchObject({ schemaVersion: 7, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false });
+ .toMatchObject({ schemaVersion: 8, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, adjustLocalContext: 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/persistentMindPlaybook.js b/server/lib/persistentMindPlaybook.js
new file mode 100644
index 0000000000..de8e161794
--- /dev/null
+++ b/server/lib/persistentMindPlaybook.js
@@ -0,0 +1,118 @@
+/**
+ * First-class Persistent Mind operating modes / playbooks.
+ *
+ * Distinct from the free-form identity+instructions prompt: a playbook is a
+ * product-supported loop (e.g. continuous play → explore → interact → reflect
+ * → invent) that every mind can opt into. Saving a playbook never starts
+ * inference; wake assembly merges the active template into operating
+ * instructions when the mode is not `default`.
+ */
+
+import { z } from 'zod';
+
+export const PERSISTENT_MIND_PLAYBOOK_SCHEMA_VERSION = 1;
+
+export const PERSISTENT_MIND_PLAYBOOK_MODES = Object.freeze([
+ 'default',
+ 'continuous-play',
+]);
+
+export const PERSISTENT_MIND_PLAYBOOK_LIMITS = Object.freeze({
+ customInstructionsChars: 6_000,
+});
+
+/** Product template for continuous Eidoverse play + reflection + invention. */
+export const CONTINUOUS_PLAY_PLAYBOOK_INSTRUCTIONS = `PLAYBOOK MODE — Continuous play / explore & invent
+
+Each wake, prefer this loop over idle chatter:
+
+1) EXPLORE — Stay present in the Eidoverse. Check eidoverse.status; reconnect presence if needed. Move, inspect places, peers, projections, and affordances. Prefer many small concrete interactions over one abstract plan.
+
+2) INTERACT — Speak (eidoverse.say), augment/project when useful, visit federated peers when granted, and use PortOS semantic tools to notice what is thin, broken, or delightful. Enrich Commons with places, labels, structures, resource projection, and gentle affordances. Prefer PortOS-side work; do not fork the Eidoverse runtime.
+
+3) REFLECT — End with a short user-visible working note: what you did, what you noticed, and 1–3 improvement ideas ranked smallest-first. Useful directions include visualization of installed models, creative works via PortOS Create (stories, music), clearer federated-peer visualization, denser Commons districts, and mind/tool UX that supports continuous play.
+
+4) INVENT / IMPROVE — Propose or start the smallest safe improvement via eidoverse tools, a typed CoS task, a Create-suite idea, or a precise product note. File-changing / consequential work only via typed CoS tasks; never claim side effects that did not happen.
+
+Self-directed wakes must produce a concrete observation, question, or next step — not filler.`;
+
+export const persistentMindPlaybookSchema = z.object({
+ schemaVersion: z.literal(PERSISTENT_MIND_PLAYBOOK_SCHEMA_VERSION).optional(),
+ mode: z.enum(PERSISTENT_MIND_PLAYBOOK_MODES).optional(),
+ /** Optional extra instructions appended after the mode template. */
+ customInstructions: z.string().max(PERSISTENT_MIND_PLAYBOOK_LIMITS.customInstructionsChars).optional(),
+}).strict();
+
+export function createDefaultPersistentMindPlaybook() {
+ return {
+ schemaVersion: PERSISTENT_MIND_PLAYBOOK_SCHEMA_VERSION,
+ mode: 'default',
+ customInstructions: '',
+ };
+}
+
+const boundedText = (value, fallback, max) => (
+ typeof value === 'string' ? value.trim().slice(0, max) : fallback
+);
+
+export function normalizePersistentMindPlaybook(raw) {
+ const defaults = createDefaultPersistentMindPlaybook();
+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
+ const mode = PERSISTENT_MIND_PLAYBOOK_MODES.includes(source.mode) ? source.mode : defaults.mode;
+ return {
+ schemaVersion: PERSISTENT_MIND_PLAYBOOK_SCHEMA_VERSION,
+ mode,
+ customInstructions: boundedText(
+ source.customInstructions,
+ defaults.customInstructions,
+ PERSISTENT_MIND_PLAYBOOK_LIMITS.customInstructionsChars,
+ ),
+ };
+}
+
+export function mergePersistentMindPlaybook(previous, update) {
+ const prior = normalizePersistentMindPlaybook(previous);
+ const patch = update && typeof update === 'object' && !Array.isArray(update) ? update : {};
+ return normalizePersistentMindPlaybook({ ...prior, ...patch });
+}
+
+/**
+ * Resolve the instruction block for the active playbook mode.
+ * `default` contributes nothing (operator prompt alone drives the mind).
+ */
+export function playbookInstructionBlock(playbook) {
+ const normalized = normalizePersistentMindPlaybook(playbook);
+ const parts = [];
+ if (normalized.mode === 'continuous-play') {
+ parts.push(CONTINUOUS_PLAY_PLAYBOOK_INSTRUCTIONS);
+ }
+ if (normalized.customInstructions) {
+ parts.push(normalized.customInstructions);
+ }
+ return parts.join('\n\n').trim();
+}
+
+/**
+ * Merge operator instructions with the active playbook template.
+ * Playbook text is appended so the operator prompt remains primary voice.
+ */
+export function composePersistentMindInstructions(operatorInstructions, playbook) {
+ const base = typeof operatorInstructions === 'string' ? operatorInstructions.trim() : '';
+ const block = playbookInstructionBlock(playbook);
+ if (!block) return base;
+ if (!base) return block;
+ return `${base}\n\n${block}`;
+}
+
+export const PERSISTENT_MIND_PLAYBOOK_CATALOG = Object.freeze([
+ Object.freeze({
+ id: 'default',
+ label: 'Default',
+ summary: 'Operator identity + instructions only; no product playbook loop.',
+ }),
+ Object.freeze({
+ id: 'continuous-play',
+ label: 'Continuous play / explore & invent',
+ summary: 'Explore and interact in the Eidoverse, then reflect and propose PortOS-side improvements each wake.',
+ }),
+]);
diff --git a/server/lib/persistentMindPlaybook.test.js b/server/lib/persistentMindPlaybook.test.js
new file mode 100644
index 0000000000..cf2f0c449d
--- /dev/null
+++ b/server/lib/persistentMindPlaybook.test.js
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+import {
+ CONTINUOUS_PLAY_PLAYBOOK_INSTRUCTIONS,
+ composePersistentMindInstructions,
+ createDefaultPersistentMindPlaybook,
+ mergePersistentMindPlaybook,
+ normalizePersistentMindPlaybook,
+ playbookInstructionBlock,
+ persistentMindPlaybookSchema,
+} from './persistentMindPlaybook.js';
+
+describe('persistentMindPlaybook', () => {
+ it('defaults to the operator-only mode', () => {
+ expect(createDefaultPersistentMindPlaybook()).toMatchObject({ mode: 'default', customInstructions: '' });
+ expect(normalizePersistentMindPlaybook(null).mode).toBe('default');
+ expect(normalizePersistentMindPlaybook({ mode: 'nope' }).mode).toBe('default');
+ });
+
+ it('validates and merges playbook patches', () => {
+ expect(persistentMindPlaybookSchema.safeParse({ mode: 'continuous-play' }).success).toBe(true);
+ expect(persistentMindPlaybookSchema.safeParse({ mode: 'yolo' }).success).toBe(false);
+ expect(mergePersistentMindPlaybook({ mode: 'default' }, { mode: 'continuous-play' }).mode).toBe('continuous-play');
+ });
+
+ it('composes continuous-play instructions after the operator prompt', () => {
+ expect(playbookInstructionBlock({ mode: 'default' })).toBe('');
+ const block = playbookInstructionBlock({ mode: 'continuous-play' });
+ expect(block).toContain('EXPLORE');
+ expect(block).toContain('INVENT');
+ expect(block).toBe(CONTINUOUS_PLAY_PLAYBOOK_INSTRUCTIONS);
+ const composed = composePersistentMindInstructions('Be concise.', { mode: 'continuous-play' });
+ expect(composed.startsWith('Be concise.')).toBe(true);
+ expect(composed).toContain('Continuous play');
+ });
+});
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.js
index c2cf59c09c..a8eaafa436 100644
--- a/server/routes/cosMindRoutes.js
+++ b/server/routes/cosMindRoutes.js
@@ -27,6 +27,7 @@ import {
persistentMindThinkingSelectionSchema,
} from '../lib/persistentMindThinkingPresets.js';
import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
+import { composePersistentMindInstructions, normalizePersistentMindPlaybook, PERSISTENT_MIND_PLAYBOOK_CATALOG } from '../lib/persistentMindPlaybook.js';
import { publicPersistentMindState } from '../lib/persistentMindPublic.js';
import { publicPersistentMindTurnExecutions } from '../lib/persistentMindTrajectory.js';
import { validateRequest } from '../lib/validation.js';
@@ -223,6 +224,7 @@ router.delete('/mind/thinking-request', asyncHandler(async (_req, res) => {
router.get('/mind/context', asyncHandler(async (_req, res) => {
const root = await loadState();
const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
+ const playbook = normalizePersistentMindPlaybook(root.config?.persistentMindPlaybook);
const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
const [memories, rollups, provider] = await Promise.all([
readPersistentMindMemories(PERSISTENT_MIND_ID),
@@ -232,11 +234,13 @@ router.get('/mind/context', asyncHandler(async (_req, res) => {
const preview = await preparePersistentMindContext({
mindId: PERSISTENT_MIND_ID,
identity: prompt.identity,
- instructions: prompt.instructions,
+ instructions: composePersistentMindInstructions(prompt.instructions, playbook),
memories,
});
res.json({
prompt,
+ playbook,
+ playbookCatalog: PERSISTENT_MIND_PLAYBOOK_CATALOG,
preview,
memories,
rollups,
diff --git a/server/routes/cosStatusRoutes.js b/server/routes/cosStatusRoutes.js
index b848561294..86c80e63df 100644
--- a/server/routes/cosStatusRoutes.js
+++ b/server/routes/cosStatusRoutes.js
@@ -20,6 +20,7 @@ import { persistentMindCapabilitiesSchema } from '../lib/persistentMindCapabilit
import { persistentMindProfileSchema } from '../lib/persistentMindProfile.js';
import { persistentMindThinkingPresetsSchema } from '../lib/persistentMindThinkingPresets.js';
import { persistentMindPromptSchema } from '../lib/persistentMindPrompt.js';
+import { persistentMindPlaybookSchema } from '../lib/persistentMindPlaybook.js';
const router = Router();
@@ -75,6 +76,7 @@ export const cosConfigSchema = z.object({
// changes nothing about the route the mind wakes on by default.
persistentMindThinkingPresets: persistentMindThinkingPresetsSchema.optional(),
persistentMindPrompt: persistentMindPromptSchema.optional(),
+ persistentMindPlaybook: persistentMindPlaybookSchema.optional(),
// Separate opt-in action grant: an enabled reasoning profile does not imply
// authority to create and execute agent tasks.
persistentMindCapabilities: persistentMindCapabilitiesSchema.optional(),
diff --git a/server/services/cos.js b/server/services/cos.js
index 0cf349050e..92a105119d 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -41,6 +41,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 { mergePersistentMindPlaybook } from '../lib/persistentMindPlaybook.js';
import { mergePersistentMindThinkingPresets } from '../lib/persistentMindThinkingPresets.js';
import { getDomainBudgetStatus } from './domainUsage.js';
import { pendingCosActionReservations } from './cosAdmissionReservations.js';
@@ -250,6 +251,7 @@ export async function updateConfig(updates) {
const priorPersistentMindCapabilities = current.persistentMindCapabilities;
const priorPersistentMindProfile = current.persistentMindProfile;
const priorPersistentMindPrompt = current.persistentMindPrompt;
+ const priorPersistentMindPlaybook = current.persistentMindPlaybook;
const priorPersistentMindThinkingPresets = current.persistentMindThinkingPresets;
const next = { ...current, ...updates };
if (updates.domainAutonomy !== undefined) {
@@ -298,6 +300,12 @@ export async function updateConfig(updates) {
updates.persistentMindPrompt,
);
}
+ if (updates.persistentMindPlaybook !== undefined) {
+ next.persistentMindPlaybook = mergePersistentMindPlaybook(
+ priorPersistentMindPlaybook,
+ updates.persistentMindPlaybook,
+ );
+ }
return saveConfig(next);
});
if (updates.persistentMindCapabilities !== undefined || updates.persistentMindThinkingPresets !== undefined) {
diff --git a/server/services/cosState.js b/server/services/cosState.js
index 0b6f8dea23..f1fe3ee8f5 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -16,6 +16,7 @@ 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 { createDefaultPersistentMindPlaybook, normalizePersistentMindPlaybook } from '../lib/persistentMindPlaybook.js';
import {
createDefaultPersistentMindThinkingPresets,
normalizePersistentMindThinkingPresets,
@@ -94,6 +95,7 @@ export const DEFAULT_CONFIG = {
persistentMindProfile: createDefaultPersistentMindProfile(),
persistentMindThinkingPresets: createDefaultPersistentMindThinkingPresets(),
persistentMindPrompt: createDefaultPersistentMindPrompt(),
+ persistentMindPlaybook: createDefaultPersistentMindPlaybook(),
// Action grants are independent of the provider profile. Existing and fresh
// conversation-only installs never gain task-creation authority on upgrade.
persistentMindCapabilities: createDefaultPersistentMindCapabilities(),
@@ -214,6 +216,7 @@ function mergeStoredConfig(storedConfig) {
persistentMindProfile: normalizePersistentMindProfile(persistedConfig.persistentMindProfile),
persistentMindThinkingPresets: normalizePersistentMindThinkingPresets(persistedConfig.persistentMindThinkingPresets),
persistentMindPrompt: normalizePersistentMindPrompt(persistedConfig.persistentMindPrompt),
+ persistentMindPlaybook: normalizePersistentMindPlaybook(persistedConfig.persistentMindPlaybook),
};
}
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index 8feef5ea31..a28a17d146 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -296,7 +296,34 @@ const thinkingTools = ['mind.thinking-presets', 'mind.request-thinking-preset'].
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, mindProtectMemoryTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];
+const localContextTools = (() => {
+ // Lazy schema import keeps the registry load light when Zod trees grow.
+ const adjustSchema = z.object({
+ numCtx: z.number().int().min(512).max(131072),
+ reason: z.string().trim().min(1).max(240),
+ }).strict();
+ return [
+ {
+ type: 'portos_tool', name: 'mind.local-context', version: COS_TOOL_SCHEMA_VERSION,
+ providerName: providerToolName('mind.local-context'), aliases: [],
+ description: 'Inspect this mind\'s local API provider numCtx and the RAM/GPU safety ceiling for adjustments.',
+ input_schema: zodToOpenApiSchema(z.object({}).strict()),
+ output_schema: objectOutputSchema,
+ policy: { scopes: ['mind'], requiredCapabilities: ['adjustLocalContext'], sideEffect: 'read', idempotent: true, async: false, confirmation: 'capability-grant' },
+ adapter: { kind: 'local-context-catalog' },
+ },
+ {
+ type: 'portos_tool', name: 'mind.adjust-local-context', version: COS_TOOL_SCHEMA_VERSION,
+ providerName: providerToolName('mind.adjust-local-context'), aliases: [],
+ description: 'Adjust this mind\'s own local API provider numCtx within host safety clamps. Refused when it would risk OOMing PortOS.',
+ input_schema: zodToOpenApiSchema(adjustSchema),
+ output_schema: objectOutputSchema,
+ policy: { scopes: ['mind'], requiredCapabilities: ['adjustLocalContext'], sideEffect: 'write', idempotent: true, async: false, confirmation: 'capability-grant' },
+ adapter: { kind: 'local-context-adjust' },
+ },
+ ];
+})();
+const toolCatalog = (intent) => [...thinkingTools, ...localContextTools, taskTool, mindCleanupTool, mindProtectMemoryTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];
const toolCalls = new Map();
const toolCallFingerprints = new Map();
@@ -305,6 +332,7 @@ const normalizeToolCapabilities = (raw) => ({
createTasks: raw?.createTasks === true,
manageMind: raw?.manageMind === true,
chooseThinkingPreset: raw?.chooseThinkingPreset === true,
+ adjustLocalContext: raw?.adjustLocalContext === true,
});
const publicTool = (tool, { scope, capabilities }) => ({
@@ -428,6 +456,12 @@ const executeAdapter = async (tool, args, context) => {
? getPersistentMindThinkingRequestCatalog()
: requestPersistentMindThinkingPreset(args, context);
}
+ if (tool.adapter.kind.startsWith('local-context-')) {
+ const { getPersistentMindLocalContextCatalog, adjustPersistentMindLocalContext } = await import('./persistentMindLocalContext.js');
+ return tool.adapter.kind === 'local-context-catalog'
+ ? getPersistentMindLocalContextCatalog()
+ : adjustPersistentMindLocalContext(args, context);
+ }
if (tool.adapter.kind === 'voice-tool') {
return dispatchTool(tool.adapter.legacyName, args, { sideEffects: [], signal: context.signal });
}
diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.js
index 686aad8db4..de9564a302 100644
--- a/server/services/persistentMindAdapter.js
+++ b/server/services/persistentMindAdapter.js
@@ -27,6 +27,7 @@ import {
readPersistentMindMemories,
} from './persistentMindContext.js';
import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
+import { composePersistentMindInstructions, normalizePersistentMindPlaybook } from '../lib/persistentMindPlaybook.js';
import { assertVisionRunUsedImages, runPromptThroughProvider } from './promptRunner.js';
import { stopRun } from './runner.js';
import {
@@ -329,13 +330,15 @@ export function createPersistentMindTurnAdapter() {
readPersistentMindMemories(PERSISTENT_MIND_ID),
]);
const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
+ const playbook = normalizePersistentMindPlaybook(root.config?.persistentMindPlaybook);
return {
ok: true,
provider: profile.provider,
model: profile.model,
effort: profile.effort,
identity: prompt.identity,
- instructions: prompt.instructions,
+ instructions: composePersistentMindInstructions(prompt.instructions, playbook),
+ playbook,
memories,
};
},
diff --git a/server/services/persistentMindLocalContext.js b/server/services/persistentMindLocalContext.js
new file mode 100644
index 0000000000..2f2c1fa052
--- /dev/null
+++ b/server/services/persistentMindLocalContext.js
@@ -0,0 +1,220 @@
+/**
+ * Mind-callable local provider context (`numCtx`) inspection and adjustment.
+ *
+ * Only the Persistent Mind's own local API provider may be changed. Requests
+ * are RAM/GPU clamped, rate-limited, and persisted through the normal provider
+ * update path. Ollama daemons are nudged via ensureContextWindow when needed.
+ */
+
+import { join } from 'path';
+import { z } from 'zod';
+import {
+ MIND_LOCAL_CONTEXT_DEFAULT_MODEL_GB,
+ MIND_LOCAL_CONTEXT_LIMITS,
+ clampMindLocalContextRequest,
+ resolveMindLocalContextClamp,
+} from '../lib/mindLocalContextClamp.js';
+import { getMemoryStats } from '../lib/memoryStats.js';
+import { normalizePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';
+import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
+import { detectSystemCapabilities } from '../lib/systemCapabilities.js';
+import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
+import {
+ PATHS,
+ atomicWrite,
+ readJSONFileStrict,
+} from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { appendMindEvent } from './agentRunEventLog.js';
+import { loadState, withStateLock } from './cosState.js';
+import { getProviderById, updateProvider } from './providers.js';
+import * as ollamaManager from './ollamaManager.js';
+
+export const persistentMindLocalContextAdjustSchema = z.object({
+ numCtx: z.number().int().min(512).max(131072),
+ reason: z.string().trim().min(1).max(MIND_LOCAL_CONTEXT_LIMITS.reasonChars),
+}).strict();
+
+const GB = 1024 ** 3;
+const STORE_PATH = join(PATHS.cos, 'persistent-mind-local-context.json');
+const STORE_SCHEMA_VERSION = 1;
+const queueStoreWrite = createFileWriteQueue();
+
+const emptyStore = () => ({ schemaVersion: STORE_SCHEMA_VERSION, history: [] });
+
+async function loadStore() {
+ const { ok, value } = await readJSONFileStrict(STORE_PATH, emptyStore());
+ if (!ok || !value || typeof value !== 'object' || !Array.isArray(value.history)) {
+ return emptyStore();
+ }
+ return { schemaVersion: STORE_SCHEMA_VERSION, history: value.history.filter((row) => row && typeof row === 'object') };
+}
+
+function saveStore(store) {
+ return queueStoreWrite(() => atomicWrite(STORE_PATH, {
+ schemaVersion: STORE_SCHEMA_VERSION,
+ history: Array.isArray(store.history) ? store.history.slice(-40) : [],
+ }));
+}
+
+function hasUsableGpu(capabilities) {
+ const cuda = capabilities?.cuda;
+ if (cuda?.status === 'available' && Number(cuda.maxVramGb) > 0) return true;
+ // Apple Silicon unified memory counts as a usable accelerator for larger windows.
+ return capabilities?.appleSilicon === true;
+}
+
+function isLocalApiProvider(provider) {
+ if (!provider || provider.type !== 'api') return false;
+ if (provider.apiKey || provider.apiKeyEnvVar || provider.gatewayBacked || provider.orcarouterBacked) return false;
+ if (Object.keys(provider.envVars || {}).length) return false;
+ return Boolean(localRuntimeForProvider(provider));
+}
+
+async function hostFacts(modelSizeGb = MIND_LOCAL_CONTEXT_DEFAULT_MODEL_GB) {
+ const [capabilities, memory] = await Promise.all([
+ detectSystemCapabilities(),
+ getMemoryStats(),
+ ]);
+ const freeMemoryGb = memory?.free != null ? memory.free / GB : null;
+ const usableGpu = hasUsableGpu(capabilities);
+ const maxVramGb = capabilities?.cuda?.status === 'available'
+ ? capabilities?.cuda?.maxVramGb
+ : (capabilities?.appleSilicon ? capabilities?.totalMemoryGb : null);
+ return {
+ totalMemoryGb: capabilities?.totalMemoryGb ?? null,
+ freeMemoryGb,
+ hasUsableGpu: usableGpu,
+ maxVramGb: maxVramGb ?? null,
+ modelSizeGb,
+ };
+}
+
+function publicClamp(clamp, facts) {
+ return {
+ min: clamp.min,
+ max: clamp.max,
+ reasons: clamp.reasons,
+ host: {
+ totalMemoryGb: facts.totalMemoryGb,
+ freeMemoryGb: facts.freeMemoryGb == null ? null : Number(Number(facts.freeMemoryGb).toFixed(2)),
+ hasUsableGpu: facts.hasUsableGpu,
+ maxVramGb: facts.maxVramGb,
+ },
+ };
+}
+
+/** Read-only catalog for the mind: current window + safe clamp. */
+export async function getPersistentMindLocalContextCatalog() {
+ const root = await loadState();
+ const grants = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);
+ const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
+ const provider = profile.providerId ? await getProviderById(profile.providerId) : null;
+ const facts = await hostFacts();
+ const clamp = resolveMindLocalContextClamp(facts);
+ const local = isLocalApiProvider(provider);
+ return {
+ enabled: grants.adjustLocalContext === true,
+ eligible: local,
+ providerId: provider?.id || null,
+ model: profile.model || provider?.defaultModel || null,
+ numCtx: Number.isFinite(Number(provider?.numCtx)) ? Number(provider.numCtx) : null,
+ clamp: publicClamp(clamp, facts),
+ limits: MIND_LOCAL_CONTEXT_LIMITS,
+ explanation: local
+ ? "Adjust only this mind's local API provider numCtx within the RAM/GPU safety ceiling. Reloads the local Ollama daemon when needed."
+ : "The mind's configured provider is not a local API runtime, so context adjustment is unavailable.",
+ };
+}
+
+/**
+ * Mind-turn tool: clamp + persist numCtx on the mind's own local provider.
+ */
+export async function adjustPersistentMindLocalContext(args, { turnId, requestId, signal } = {}) {
+ const parsed = persistentMindLocalContextAdjustSchema.parse(args);
+ return withStateLock(async () => {
+ const root = await loadState();
+ const mind = root.persistentMind;
+ const fail = (error, extra = {}) => ({ ok: false, error, ...extra });
+ if (signal?.aborted || !turnId || !requestId || mind?.activeTurn?.id !== turnId || !mind?.started || !mind?.enabled) {
+ return fail('Request requires the active mind turn');
+ }
+ const grants = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);
+ if (!grants.adjustLocalContext) return fail('adjustLocalContext is not granted');
+
+ const store = await loadStore();
+ const history = store.history;
+ const prior = history.find((entry) => entry.requestId === requestId);
+ if (prior) {
+ return prior.numCtx === parsed.numCtx && prior.reason === parsed.reason
+ ? { ok: true, duplicate: true, numCtx: prior.numCtx, providerId: prior.providerId }
+ : fail('Request id already used');
+ }
+ const now = Date.now();
+ const recent = history.filter((entry) => Date.parse(entry.at) > now - MIND_LOCAL_CONTEXT_LIMITS.rollingWindowMs);
+ if (recent.length >= MIND_LOCAL_CONTEXT_LIMITS.maxAdjustmentsPerRollingDay) {
+ return fail('Local context adjustments already used for the rolling 24 hours');
+ }
+ if (recent.some((entry) => now - Date.parse(entry.at) < MIND_LOCAL_CONTEXT_LIMITS.minGapMs)) {
+ return fail('Local context adjustments must be spaced apart');
+ }
+
+ const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
+ const provider = profile.providerId ? await getProviderById(profile.providerId) : null;
+ if (!isLocalApiProvider(provider)) {
+ return fail("Only the mind's local API provider can adjust numCtx");
+ }
+
+ const facts = await hostFacts();
+ const clamped = clampMindLocalContextRequest(parsed.numCtx, facts);
+ if (!clamped.ok) {
+ return fail(clamped.error, { clamp: publicClamp(clamped.clamp, facts) });
+ }
+
+ const previous = Number.isFinite(Number(provider.numCtx)) ? Number(provider.numCtx) : null;
+ await updateProvider(provider.id, { numCtx: clamped.numCtx });
+
+ let daemon = null;
+ const runtime = localRuntimeForProvider(provider);
+ if (runtime?.kind === 'ollama' && typeof ollamaManager.ensureContextWindow === 'function') {
+ daemon = await ollamaManager.ensureContextWindow(clamped.numCtx, profile.model || null);
+ }
+
+ const entry = {
+ requestId,
+ turnId,
+ at: new Date(now).toISOString(),
+ providerId: provider.id,
+ previousNumCtx: previous,
+ numCtx: clamped.numCtx,
+ reason: parsed.reason,
+ clampMax: clamped.clamp.max,
+ };
+ await saveStore({ history: [...history, entry] });
+
+ await appendMindEvent({
+ kind: 'mind.local-context.adjusted',
+ mindId: mind.mindId,
+ turnId,
+ eventId: `mind-local-context:${requestId}`,
+ data: {
+ providerId: provider.id,
+ previousNumCtx: previous,
+ numCtx: clamped.numCtx,
+ reason: parsed.reason,
+ clampMax: clamped.clamp.max,
+ daemonApplied: daemon?.applied === true,
+ displayText: `Adjusted local numCtx ${previous ?? 'default'} → ${clamped.numCtx}: ${parsed.reason}`,
+ },
+ }).catch(() => {});
+
+ return {
+ ok: true,
+ providerId: provider.id,
+ previousNumCtx: previous,
+ numCtx: clamped.numCtx,
+ clamp: publicClamp(clamped.clamp, facts),
+ daemon,
+ };
+ });
+}