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

fix(mind): fit persistent-mind wakes inside small local windows

atomanticagent14262e9a6681
diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.js
index cbd9329c85..50d6a860d1 100644
--- a/server/services/persistentMindAdapter.js
+++ b/server/services/persistentMindAdapter.js
@@ -37,7 +37,8 @@ import {
import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
import { composePersistentMindInstructions, normalizePersistentMindPlaybook } from '../lib/persistentMindPlaybook.js';
import { resolvePersistentMindPlaybookPhase } from './persistentMindPlaybookSignals.js';
-import { assertVisionRunUsedImages, runPromptThroughProvider } from './promptRunner.js';
+import { assertVisionRunUsedImages, resolveLocalPromptBudget, runPromptThroughProvider } from './promptRunner.js';
+import { CHARS_PER_TOKEN } from '../lib/contextBudget.js';
import { stopRun } from './runner.js';
import {
buildPersistentMindTaskCapabilityPrompt,
@@ -69,6 +70,23 @@ const { HEARTBEAT_INTERVAL_MS } = PERSISTENT_MIND_LIMITS;
const MAX_TOOL_PROVIDER_ROUNDS = 4;
const MAX_TOOL_RESULT_CHARS = 4_000;
const MAX_CONTINUATION_TOOL_PROMPT_CHARS = 24_000;
+// Every mind call declares this much answer room. On a local window the
+// prompt runner shrinks it to fit (localOutputReserveTokens) and caps
+// generation at the shrunk number.
+const PERSISTENT_MIND_OUTPUT_RESERVE_TOKENS = 8_192;
+// Local-window prompt fitting. chars/4 undercounts real tokenizers (qwen3
+// packed a 54K-char wake into 14,990 tokens, ~10% over the estimate), so the
+// fitted prompt targets 90% of the room the dispatch gate allows.
+const LOCAL_PROMPT_TOKENIZER_MARGIN = 0.9;
+// Share of the fitted prompt the recalled context (memories, journal, recent
+// history) may take on a local window; the rest is the response contract,
+// capabilities, tool catalog and in-wake tool results.
+const LOCAL_CONTEXT_PROMPT_SHARE = 0.25;
+// The narrowest tool catalog a local-window rebuild may fall to. Tools that
+// already ran stay in full (requiredToolNames); the rest stay discoverable.
+const MIN_LOCAL_TOOL_PROMPT_CHARS = 6_000;
+// Per-result caps tried in order when completed tool results must shrink.
+const TOOL_RESULT_COMPACTION_CAPS = [2_000, 1_000, 500, 200];
const MAX_MEMORY_CANDIDATES_PER_TURN = 5;
const memoryCandidateSchema = z.object({
@@ -110,6 +128,56 @@ const boundedToolResult = (result) => {
: { truncated: true, preview: serialized.slice(0, MAX_TOOL_RESULT_CHARS) };
};
+const compactToolResult = (toolResult, cap) => {
+ const compacted = { ...toolResult };
+ if (toolResult.result !== undefined) {
+ const serialized = JSON.stringify(toolResult.result);
+ if (serialized.length > cap) compacted.result = { truncated: true, preview: serialized.slice(0, cap) };
+ }
+ if (typeof toolResult.error === 'string' && toolResult.error.length > cap) compacted.error = toolResult.error.slice(0, cap);
+ return compacted;
+};
+
+/**
+ * Completed tool results shrunk to fit `maxChars` of JSON, for a local window
+ * that cannot hold them verbatim. Tries progressively smaller per-result
+ * previews, then falls back to one stub per call (`requestId`, `name`,
+ * `state`) so the model still knows what already ran and must not be repeated.
+ * Returns the input unchanged when it already fits.
+ *
+ * @param {Array<object>} results
+ * @param {number} maxChars
+ * @returns {Array<object>}
+ */
+export function compactToolResultsToFit(results, maxChars) {
+ if (JSON.stringify(results).length <= maxChars) return results;
+ for (const cap of TOOL_RESULT_COMPACTION_CAPS) {
+ const compacted = results.map((toolResult) => compactToolResult(toolResult, cap));
+ if (JSON.stringify(compacted).length <= maxChars) return compacted;
+ }
+ return results.map(({ requestId, name, state }) => ({ requestId, name, state, compacted: true }));
+}
+
+/**
+ * The char budget for a whole mind prompt on a LOCAL provider with a known
+ * window, or null (cloud, CLI, unknown window) to build exactly as before.
+ * `maxPromptChars` bounds every round's prompt; `contextMaxChars` bounds the
+ * recalled context assembled before the turn.
+ *
+ * @returns {Promise<{ contextWindow: number, outputReserveTokens: number, maxPromptChars: number, contextMaxChars: number }|null>}
+ */
+export async function resolvePersistentMindPromptBudget({ provider, model }) {
+ const local = await resolveLocalPromptBudget({ provider, model, outputReserveTokens: PERSISTENT_MIND_OUTPUT_RESERVE_TOKENS });
+ if (!local || local.maxPromptTokens <= 0) return null;
+ const maxPromptChars = Math.floor(local.maxPromptTokens * LOCAL_PROMPT_TOKENIZER_MARGIN) * CHARS_PER_TOKEN;
+ return {
+ contextWindow: local.contextWindow,
+ outputReserveTokens: local.outputReserveTokens,
+ maxPromptChars,
+ contextMaxChars: Math.floor(maxPromptChars * LOCAL_CONTEXT_PROMPT_SHARE),
+ };
+}
+
const toolRequestId = (turnId, call) => `mind-tool-${sha256Text(canonicalStringify(call.requestId
? { turnId, providerRequestId: call.requestId }
: { turnId, name: call.name, arguments: call.arguments })).slice(0, 32)}`;
@@ -336,7 +404,7 @@ async function runPinnedPrompt({ provider, model, effort, prompt, screenshots =
// Resident inference may be slow or silent while thinking. Stop remains explicit.
timeout: 0,
absoluteTimeoutMs: 0,
- outputReserveTokens: 8192,
+ outputReserveTokens: PERSISTENT_MIND_OUTPUT_RESERVE_TOKENS,
allowFallback: false,
screenshots,
responseSchema,
@@ -379,6 +447,9 @@ export function createPersistentMindTurnAdapter() {
const playbookPhase = playbook.mode === 'continuous-play'
? await resolvePersistentMindPlaybookPhase({ signal })
: null;
+ // A local window bounds the recalled context up front, so the wake
+ // prompt leaves room for the tool rounds that follow it.
+ const promptBudget = await resolvePersistentMindPromptBudget({ provider: profile.provider, model: profile.model });
return {
ok: true,
provider: profile.provider,
@@ -389,6 +460,7 @@ export function createPersistentMindTurnAdapter() {
playbook,
playbookPhase,
memories,
+ ...(promptBudget ? { contextMaxChars: promptBudget.contextMaxChars } : {}),
};
},
@@ -460,25 +532,64 @@ export function createPersistentMindTurnAdapter() {
// isUserTurn omitted so a multi-round turn can't age its own tools out
// from under itself.
const isUserTurn = wake?.kind === 'message';
- const toolCapabilityPrompt = await buildPersistentMindToolPrompt(taskAccess, await readPersistentMindRecipeCatalog(taskAccess), { turnId, isUserTurn, trace: true });
+ const recipeCatalog = await readPersistentMindRecipeCatalog(taskAccess);
+ const toolCapabilityPrompt = await buildPersistentMindToolPrompt(taskAccess, recipeCatalog, { turnId, isUserTurn, trace: true });
const callCapabilityPrompt = buildPersistentMindCallCapabilityPrompt({ enabled: taskAccess.callUser });
const screenshots = (Array.isArray(wake?.message?.images) ? wake.message.images : []).map((image) => {
const path = resolveScreenshot(image?.filename);
if (!path) throw new Error('A Persistent Mind image attachment no longer resolves under the screenshots directory');
return path;
});
- let basePrompt = buildPersistentMindTurnPrompt({
+ const turnPromptSections = {
context,
wake,
taskCapabilityPrompt,
issueCapabilityPrompt,
- toolCapabilityPrompt,
visibilityPrompt,
userActionsPrompt,
maintenancePrompt,
callCapabilityPrompt,
- });
- let providerPrompt = basePrompt;
+ };
+ // On a local window every round is fitted under the room the dispatch
+ // gate allows, instead of being refused mid-wake once tool results grow.
+ const promptBudget = await resolvePersistentMindPromptBudget({ provider, model });
+ // Set after the first tool round: what a continuation prompt carries.
+ let continuation = null;
+ const composeRoundPrompt = async (namePrompt) => {
+ // Rebuilds never age the lease or trace (isUserTurn/trace omitted).
+ const buildTools = (maxChars) => (continuation
+ ? buildPersistentMindToolPrompt(continuation.capabilities, continuation.recipes, {
+ turnId, maxChars, requiredToolNames: continuation.requiredToolNames,
+ })
+ : buildPersistentMindToolPrompt(taskAccess, recipeCatalog, { turnId, maxChars }));
+ const assemble = (toolPrompt, toolResults) => `${buildPersistentMindTurnPrompt({ ...turnPromptSections, toolCapabilityPrompt: toolPrompt })}${continuation
+ ? `\n\n# Completed tool results\n${JSON.stringify(toolResults)}\n\n${continuation.suffix}`
+ : ''}${namePrompt}`;
+ // A successful call proves only that its own schema was useful. Keep
+ // that schema (and the compact discovery index) for continuation; do
+ // not expand every sibling in the leased family.
+ let toolPrompt = continuation ? await buildTools(MAX_CONTINUATION_TOOL_PROMPT_CHARS) : toolCapabilityPrompt;
+ let toolResults = completedToolResults;
+ let prompt = assemble(toolPrompt, toolResults);
+ const limit = promptBudget?.maxPromptChars;
+ if (!limit || prompt.length <= limit) return prompt;
+ const untrimmedChars = prompt.length;
+ // 1. Narrow the tool catalog: schemas that already ran stay in full,
+ // the rest stay listed as budget-limited and can be re-requested.
+ const toolTarget = Math.max(Math.min(toolPrompt.length, MIN_LOCAL_TOOL_PROMPT_CHARS), toolPrompt.length - (prompt.length - limit));
+ if (toolTarget < toolPrompt.length) {
+ toolPrompt = await buildTools(toolTarget);
+ prompt = assemble(toolPrompt, toolResults);
+ }
+ // 2. Compact completed tool results (previews, then per-call stubs).
+ if (continuation && prompt.length > limit) {
+ const resultsChars = JSON.stringify(toolResults).length;
+ toolResults = compactToolResultsToFit(toolResults, Math.max(0, resultsChars - (prompt.length - limit)));
+ prompt = assemble(toolPrompt, toolResults);
+ }
+ console.log(`📏 Persistent mind prompt fitted to the ${promptBudget.contextWindow}-token local window: ${untrimmedChars} → ${prompt.length} chars (limit ${limit})`);
+ return prompt;
+ };
let result;
let parsed;
const toolBudget = { used: 0 };
@@ -492,7 +603,7 @@ export function createPersistentMindTurnAdapter() {
for (let round = 0; round < MAX_TOOL_PROVIDER_ROUNDS; round += 1) {
// Round 0 is the turn itself; every later round is a continuation the
// model earned by asking for tools. Each is admitted on its own.
- const prompt = `${providerPrompt}\n\n# Current naming identity\n${persistentMindNamePrompt(await readPersistentMindName(PERSISTENT_MIND_ID), { canChoose: taskAccess.manageMind })}`;
+ const prompt = await composeRoundPrompt(`\n\n# Current naming identity\n${persistentMindNamePrompt(await readPersistentMindName(PERSISTENT_MIND_ID), { canChoose: taskAccess.manageMind })}`);
result = await callBoundary(
{ purpose: round === 0 ? 'turn' : 'tool-round', round, promptChars: prompt.length, promptBytes: Buffer.byteLength(prompt) },
async ({ reportRunId }) => runPinnedPrompt({
@@ -623,17 +734,13 @@ export function createPersistentMindTurnAdapter() {
.filter((toolResult) => toolResult.state === 'completed')
.map((toolResult) => toolResult.name)
.filter(Boolean);
- basePrompt = buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, issueCapabilityPrompt, visibilityPrompt, userActionsPrompt, maintenancePrompt, callCapabilityPrompt,
- // A successful call proves only that its own schema was useful. Keep
- // that schema (and the compact discovery index) for continuation;
- // do not expand every sibling in the leased family. This bounds the
- // complete prompt while preserving explicit activation semantics.
- toolCapabilityPrompt: await buildPersistentMindToolPrompt(liveCapabilities, await readPersistentMindRecipeCatalog(liveCapabilities), {
- turnId, maxChars: MAX_CONTINUATION_TOOL_PROMPT_CHARS, requiredToolNames: completedToolNames,
- }),
- });
const budgetExhausted = toolBudget.used >= COS_TOOL_CALL_LIMITS.maxCallsPerTurn || round === MAX_TOOL_PROVIDER_ROUNDS - 2;
- providerPrompt = `${basePrompt}\n\n# Completed tool results\n${JSON.stringify(completedToolResults)}\n\n${parsed.taskRequests.length > 0 ? 'Task requests from this intermediate round were not queued. Include only the final desired taskRequests in a terminal response with toolCalls: [].\n' : ''}${budgetExhausted ? 'The tool-call budget is exhausted. Return a final response with toolCalls: [] and do not repeat completed actions.' : 'Use these results to continue. Do not repeat a completed requestId.'}`;
+ continuation = {
+ capabilities: liveCapabilities,
+ recipes: await readPersistentMindRecipeCatalog(liveCapabilities),
+ requiredToolNames: completedToolNames,
+ suffix: `${parsed.taskRequests.length > 0 ? 'Task requests from this intermediate round were not queued. Include only the final desired taskRequests in a terminal response with toolCalls: [].\n' : ''}${budgetExhausted ? 'The tool-call budget is exhausted. Return a final response with toolCalls: [] and do not repeat completed actions.' : 'Use these results to continue. Do not repeat a completed requestId.'}`,
+ };
}
// After the tool rounds, so a call is placed on the turn's final answer
// rather than on an intermediate round the model went on to revise.
diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.js
index 589e9ae3c1..4da7363865 100644
--- a/server/services/persistentMindAdapter.test.js
+++ b/server/services/persistentMindAdapter.test.js
@@ -15,6 +15,8 @@ const mock = vi.hoisted(() => ({
executeCallRequest: vi.fn(),
resolvePlaybookPhase: vi.fn(),
readMaintenance: vi.fn(),
+ resolveLocalPromptBudget: vi.fn(),
+ toolPromptPadding: '',
createPersistentMindMemoryFromCandidate: vi.fn(async ({ candidateId, ...candidate }) => ({
success: true,
duplicate: false,
@@ -35,6 +37,7 @@ vi.mock('./persistentMindContext.js', () => ({
vi.mock('./promptRunner.js', () => ({
runPromptThroughProvider: (...args) => mock.runPrompt(...args),
assertVisionRunUsedImages: (...args) => mock.assertVision(...args),
+ resolveLocalPromptBudget: (...args) => mock.resolveLocalPromptBudget(...args),
}));
vi.mock('./runner.js', () => ({ stopRun: (...args) => mock.stopRun(...args) }));
vi.mock('./persistentMindTaskCapability.js', () => ({
@@ -63,12 +66,16 @@ vi.mock('./persistentMindPlaybookSignals.js', () => ({
}));
vi.mock('./cosToolRegistry.js', () => ({
readPersistentMindRecipeCatalog: vi.fn(async () => []),
- buildPersistentMindToolPrompt: ({ readPortos, writePortos }) => `PortOS tools: read=${Boolean(readPortos)} write=${Boolean(writePortos)}`,
+ // Honors maxChars like the real builder, so local-window narrowing is visible.
+ buildPersistentMindToolPrompt: ({ readPortos, writePortos }, _recipes, { maxChars = Infinity } = {}) => {
+ const rendered = `PortOS tools: read=${Boolean(readPortos)} write=${Boolean(writePortos)}${mock.toolPromptPadding}`;
+ return rendered.length > maxChars ? rendered.slice(0, maxChars) : rendered;
+ },
executeCosToolCall: (...args) => mock.executeToolCall(...args),
isCosTaskToolName: (name) => name === 'cos.create-task' || name === 'cos_create_task',
}));
-const { createPersistentMindTurnAdapter, persistentMindHarnessInfo, persistentMindResponseSchema } = await import('./persistentMindAdapter.js');
+const { createPersistentMindTurnAdapter, persistentMindHarnessInfo, persistentMindResponseSchema, compactToolResultsToFit, resolvePersistentMindPromptBudget } = await import('./persistentMindAdapter.js');
const profile = { provider: { id: 'example-api', type: 'api' }, model: 'example-model', effort: 'high' };
@@ -87,6 +94,8 @@ beforeEach(() => {
mock.executeToolCall.mockResolvedValue({ state: 'completed', result: { ok: true, count: 1 } });
mock.resolvePlaybookPhase.mockResolvedValue({ phase: 'construct', reason: 'test default', signals: {} });
mock.assertVision.mockImplementation((result, provider) => result?.provider || provider);
+ mock.resolveLocalPromptBudget.mockResolvedValue(null);
+ mock.toolPromptPadding = '';
mock.runPrompt.mockResolvedValue({ text: JSON.stringify({
thinkingSummary: 'I connected the new request to the durable fact.',
message: 'Here is the answer.',
@@ -861,3 +870,101 @@ it('completes a self-directed turn with a public working note and null reply', a
expect(Date.parse(result.selfWake.notBefore) - Date.now()).toBeGreaterThan(59 * 60_000);
expect(Date.parse(result.selfWake.notBefore) - Date.now()).toBeLessThanOrEqual(60 * 60_000);
});
+
+// A 16K local window: the dispatch gate allows window − local reserve
+// (16,384 − 2,048) chars/4 tokens. On 2026-10-01 a qwen3:8b wake ran round 0
+// at 15,043 tokens and round 1 at 15,730, then round 2 was refused mid-wake at
+// a 16,967-token budget because tool results kept growing the prompt.
+describe('local-window prompt fitting', () => {
+ const LOCAL_16K = { contextWindow: 16_384, outputReserveTokens: 2_048, maxPromptTokens: 14_336 };
+ const LIMIT_16K = Math.floor(14_336 * 0.9) * 4;
+
+ it('sizes the prompt and recalled-context budgets from the local window', async () => {
+ mock.resolveLocalPromptBudget.mockResolvedValue(LOCAL_16K);
+ await expect(resolvePersistentMindPromptBudget(profile)).resolves.toEqual({
+ contextWindow: 16_384,
+ outputReserveTokens: 2_048,
+ maxPromptChars: LIMIT_16K,
+ contextMaxChars: Math.floor(LIMIT_16K * 0.25),
+ });
+ expect(mock.resolveLocalPromptBudget).toHaveBeenCalledWith(expect.objectContaining({ outputReserveTokens: 8192 }));
+ mock.resolveLocalPromptBudget.mockResolvedValue(null);
+ await expect(resolvePersistentMindPromptBudget(profile)).resolves.toBeNull();
+ });
+
+ it('bounds the recalled context only for a local window', async () => {
+ expect((await createPersistentMindTurnAdapter().prepare({ profile })).contextMaxChars).toBeUndefined();
+ mock.resolveLocalPromptBudget.mockResolvedValue(LOCAL_16K);
+ expect((await createPersistentMindTurnAdapter().prepare({ profile })).contextMaxChars).toBe(Math.floor(LIMIT_16K * 0.25));
+ });
+
+ it('keeps every round of a tool-heavy wake under the local limit instead of growing past it', async () => {
+ mock.resolveLocalPromptBudget.mockResolvedValue(LOCAL_16K);
+ mock.root.config.persistentMindCapabilities = { readPortos: true };
+ // A wide catalog and a long recalled context, plus ~4K-char results: the
+ // catalog narrows first, then the completed results compact.
+ mock.toolPromptPadding = 'T'.repeat(44_000);
+ mock.executeToolCall.mockImplementation(async ({ call }) => ({ state: 'completed', result: { call: call.requestId, blob: 'x'.repeat(3_800) } }));
+ const toolRound = (prefix) => ({ text: JSON.stringify({
+ thinkingSummary: 'Looking.',
+ toolCalls: [1, 2].map((n) => ({ requestId: `${prefix}-${n}`, name: 'catalog.search', arguments: { query: `${prefix}${n}` } })),
+ }) });
+ mock.runPrompt
+ .mockResolvedValueOnce(toolRound('a'))
+ .mockResolvedValueOnce(toolRound('b'))
+ .mockResolvedValueOnce({ text: JSON.stringify({ thinkingSummary: 'Done.', message: 'Finished.' }) });
+
+ await createPersistentMindTurnAdapter().run({ ...profile, turnId: 'local-fit', wake: { kind: 'self' }, context: { text: 'C'.repeat(30_000) }, recordCapabilityEvent: vi.fn(async () => true) });
+
+ const prompts = mock.runPrompt.mock.calls.map(([request]) => request.prompt);
+ expect(prompts).toHaveLength(3);
+ for (const prompt of prompts) expect(prompt.length).toBeLessThanOrEqual(LIMIT_16K);
+ // The last round still names every call that already ran, so the model
+ // cannot repeat one, even though their bodies were compacted.
+ for (const id of ['a-1', 'a-2', 'b-1', 'b-2']) expect(prompts[2]).toContain(`"requestId":"${id}"`);
+ expect(prompts[2]).toMatch(/"truncated":true|"compacted":true/);
+ expect(prompts[2]).toContain('# Current naming identity');
+ });
+
+ it('leaves cloud prompts untouched however large they are', async () => {
+ mock.root.config.persistentMindCapabilities = { readPortos: true };
+ mock.toolPromptPadding = 'T'.repeat(60_000);
+ mock.executeToolCall.mockResolvedValue({ state: 'completed', result: { blob: 'x'.repeat(3_800) } });
+ mock.runPrompt
+ .mockResolvedValueOnce({ text: JSON.stringify({ thinkingSummary: 'Looking.', toolCalls: [{ requestId: 'c-1', name: 'catalog.search', arguments: {} }] }) })
+ .mockResolvedValueOnce({ text: JSON.stringify({ thinkingSummary: 'Done.', message: 'Finished.' }) });
+
+ await createPersistentMindTurnAdapter().run({ ...profile, turnId: 'cloud', wake: { kind: 'self' }, context: { text: 'C'.repeat(8_000) }, recordCapabilityEvent: vi.fn(async () => true) });
+
+ const [first, second] = mock.runPrompt.mock.calls.map(([request]) => request.prompt);
+ expect(first).toContain('T'.repeat(60_000));
+ // Continuation keeps the pre-existing 24K catalog cap and verbatim results.
+ expect(second).toContain(`"blob":"${'x'.repeat(3_800)}"`);
+ expect(second).not.toContain('"compacted":true');
+ });
+});
+
+describe('compactToolResultsToFit', () => {
+ const results = [
+ { requestId: 'r1', name: 'catalog.search', state: 'completed', result: { blob: 'x'.repeat(3_000) } },
+ { requestId: 'r2', name: 'catalog.search', state: 'failed', error: 'e'.repeat(450) },
+ ];
+
+ it('returns results unchanged when they already fit', () => {
+ expect(compactToolResultsToFit(results, 10_000)).toBe(results);
+ });
+
+ it('shrinks result bodies to previews before dropping them', () => {
+ const compacted = compactToolResultsToFit(results, 2_000);
+ expect(JSON.stringify(compacted).length).toBeLessThanOrEqual(2_000);
+ expect(compacted[0]).toMatchObject({ requestId: 'r1', state: 'completed', result: { truncated: true } });
+ expect(compacted[1].requestId).toBe('r2');
+ });
+
+ it('falls back to per-call stubs that still name what ran', () => {
+ expect(compactToolResultsToFit(results, 150)).toEqual([
+ { requestId: 'r1', name: 'catalog.search', state: 'completed', compacted: true },
+ { requestId: 'r2', name: 'catalog.search', state: 'failed', compacted: true },
+ ]);
+ });
+});
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index 19ad88195e..2a272a7026 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -910,6 +910,9 @@ async function runClaimedPersistentMindTurn(turn, mind, globalSlot) {
identity: prepared.identity ?? turnAdapter.identity ?? 'One supervised persistent Chief of Staff mind.',
instructions: prepared.instructions || '',
memories: Array.isArray(prepared.memories) ? prepared.memories : [],
+ // A local window's adapter bounds the recalled context so the wake
+ // prompt leaves room for its tool rounds; absent means the default cap.
+ ...(Number.isInteger(prepared.contextMaxChars) && prepared.contextMaxChars > 0 ? { maxChars: prepared.contextMaxChars } : {}),
providerId: prepared.provider.id,
model: prepared.model || null,
summarize: typeof turnAdapter.summarize === 'function'
diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.js
index e639f7c553..2d9444bd66 100644
--- a/server/services/persistentMindSupervisor.test.js
+++ b/server/services/persistentMindSupervisor.test.js
@@ -255,6 +255,27 @@ describe('persistent mind supervisor', () => {
await running;
});
+ it('passes a local-window context bound from prepare through to context assembly', async () => {
+ const run = vi.fn(async () => ({}));
+ const prepare = vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' }, model: 'example-model', contextMaxChars: 12_000 }));
+ await supervisor.registerPersistentMindTurnAdapter({ prepare, run });
+ await supervisor.startPersistentMind();
+ await supervisor.wakePersistentMind();
+ await supervisor.drainPersistentMind();
+ await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1));
+ expect(mock.prepareContext).toHaveBeenCalledWith(expect.objectContaining({ maxChars: 12_000 }));
+ });
+
+ it('leaves the default context cap when prepare declares no bound', async () => {
+ const run = vi.fn(async () => ({}));
+ await supervisor.registerPersistentMindTurnAdapter({ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' }, model: 'example-model' })), run });
+ await supervisor.startPersistentMind();
+ await supervisor.wakePersistentMind();
+ await supervisor.drainPersistentMind();
+ await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1));
+ expect(mock.prepareContext.mock.calls.at(-1)[0]).not.toHaveProperty('maxChars');
+ });
+
it('starts and resumes for new messages without allowing retries to undo a later pause', async () => {
const run = vi.fn(async () => ({}));
await supervisor.registerPersistentMindTurnAdapter({ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' }, model: 'example-model', effort: 'high' })), run });
diff --git a/server/services/promptRunner.js b/server/services/promptRunner.js
index fc637c8701..e8a2ff22b3 100644
--- a/server/services/promptRunner.js
+++ b/server/services/promptRunner.js
@@ -1340,6 +1340,29 @@ async function resolveLocalOutputBudget(provider, model, { outputReserveTokens,
return reserve ? { outputReserveTokens: reserve, maxTokens: reserve } : unchanged;
}
+/**
+ * The prompt room a LOCAL provider leaves once its output reserve is planned,
+ * for callers that build their own prompt and want to fit it rather than be
+ * refused (the persistent mind's tool rounds). Uses the same window lookup and
+ * the same `localOutputReserveTokens` sizing as the dispatch gate, so a prompt
+ * kept under `maxPromptTokens` (chars/4) is one the gate admits.
+ *
+ * Returns `null` for a cloud / CLI provider, an undeclared reserve, or an
+ * unknown window — callers then build exactly as before.
+ *
+ * @param {{ provider: object, model?: string|null, outputReserveTokens: number }} args
+ * @returns {Promise<{ contextWindow: number, outputReserveTokens: number, maxPromptTokens: number }|null>}
+ */
+export async function resolveLocalPromptBudget({ provider, model = null, outputReserveTokens }) {
+ if (!isLocalInferenceProvider(provider)) return null;
+ const resolvedModel = model || provider?.defaultModel || null;
+ const observed = withOllamaRuntimeContextWindow(await withObservedContextWindowsLazy(provider));
+ const contextWindow = knownContextWindow(observed, resolvedModel);
+ const reserve = localOutputReserveTokens(outputReserveTokens, contextWindow);
+ if (!reserve) return null;
+ return { contextWindow, outputReserveTokens: reserve, maxPromptTokens: Math.max(0, contextWindow - reserve) };
+}
+
/**
* The budget a pre-dispatch REFUSAL is allowed to act on.
*
diff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.js
index 076d968a07..d237abbcbf 100644
--- a/server/services/promptRunner.test.js
+++ b/server/services/promptRunner.test.js
@@ -84,7 +84,7 @@ const observedWindows = await import('./observedContextWindows.js');
const { ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');
const { apiRunAbsoluteTimeoutMs } = await import('../lib/aiToolkit/internal/runTimeouts.js');
const { CREATIVE_LATITUDE_HEADING, withCreativeLatitude } = await import('../lib/creativeLatitude.js');
-const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel, pickConfigCorrectedModel, normalizeResponseSchema, coerceResponseToSchema, isSchemaTypeCategory, buildRequestCapabilities, assertVisionRunUsedImages } = await import('./promptRunner.js');
+const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel, pickConfigCorrectedModel, normalizeResponseSchema, coerceResponseToSchema, isSchemaTypeCategory, buildRequestCapabilities, assertVisionRunUsedImages, resolveLocalPromptBudget } = await import('./promptRunner.js');
const apiProvider = (extra = {}) => ({
id: 'mock-api', type: 'api', defaultModel: 'm-default', ...extra,
@@ -2699,6 +2699,19 @@ describe('promptRunner — context gate on the requested provider', () => {
expect(runner.executeApiRun.mock.calls[0][0].maxTokens).toBe(6_000);
});
+ it('reports the prompt room a local window leaves after its reserve', async () => {
+ observedWindows.withObservedContextWindows.mockImplementation(servingWindow(20_480));
+ await expect(resolveLocalPromptBudget({ provider: localOllama(), outputReserveTokens: 8_192 })).resolves.toEqual({
+ contextWindow: 20_480, outputReserveTokens: 2_560, maxPromptTokens: 17_920,
+ });
+ await expect(resolveLocalPromptBudget({
+ provider: apiProvider({ id: 'cloud-api', defaultModel: 'qwen3.8-27b', endpoint: 'https://api.example.com/v1' }),
+ outputReserveTokens: 8_192,
+ })).resolves.toBeNull();
+ observedWindows.withObservedContextWindows.mockImplementation(async (provider) => provider);
+ await expect(resolveLocalPromptBudget({ provider: localOllama(), outputReserveTokens: 8_192 })).resolves.toBeNull();
+ });
+
it('keeps the declared reserve for a cloud provider', async () => {
observedWindows.withObservedContextWindows.mockImplementation(servingWindow(16_384));