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): size the output reserve to local model windows

atomanticagent511dc7461813
diff --git a/server/lib/README.md b/server/lib/README.md
index 996fa2f000..17c7e8de88 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -317,7 +317,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `codexUserConfig.js` | READ-ONLY probe of the user's own `~/.codex/config.toml` (honoring `CODEX_HOME`), so PortOS can SAY when a third-party bridge has re-pointed Codex model routing away from the account its cards report on. `parseCodexRoutingOverride` (pure) reports which of the top-level `openai_base_url` / `model_provider` / `model_catalog_json` keys are assigned and the base URL they name — top-level ONLY, since the same key inside a `[table]` is per-provider configuration and must not trip the badge. `readCodexRoutingOverride` adds a short TTL cache and the load-bearing sentinel: `null` = could not read (never paint that as "not overridden"), an ABSENT file = a definite `overridden: false`. PortOS never writes this file, and `baseUrl` is machine-local — render it, never log or federate it. |
| `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. |
| `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. |
-| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens`/`estimateTokensFromChars` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. |
+| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens`/`estimateTokensFromChars` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. `localOutputReserveTokens(declared, window)` shrinks a caller's output reserve for a local model with a known window (floor 2,048, ⅛ of the window, capped at ¼ of the window and at the declared reserve). |
| `localPromptBudget.js` | What a large prompt costs to PREFILL on a model server running on this machine (#6117). `planLocalPromptBudget({ prompt, endpoint, baseDurationMs })` → `{ promptTokens, prefillMs, expectedDurationMs, longPrefill, … }`, or `null` for a cloud endpoint / no prompt to measure — a sentinel a caller must read as "no estimate", never as a small one. `estimateLocalPrefillMs` and `describeLocalPromptBudget` are the token→ms and plan→sentence halves; `LOCAL_PREFILL_TOKENS_PER_SECOND` is a deliberately pessimistic constant, since over-estimating only widens the window a healthy run gets. Never refuses a dispatch: it raises the run's duration estimate so a ~100K-token public-review envelope reads as a long silent prefill instead of a wedged run. Pure. |
| `ansiStrip.js` | Streaming ANSI / control-byte stripper. |
| `hfErrors.js` | Parse huggingface_hub gated-access errors: `isGatedRepoError(text)` classifies a failure as gated (403/restricted), `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and MIDI transcription (LoRA trainer keeps its own regex to also match bare 401). Pure. |
diff --git a/server/lib/contextBudget.js b/server/lib/contextBudget.js
index b234121cd0..585e4de995 100644
--- a/server/lib/contextBudget.js
+++ b/server/lib/contextBudget.js
@@ -34,6 +34,36 @@ const CONTEXT_TRIM_MARKER = '\n…[context trimmed to fit the model window]…';
// Ollama's historical default so we never plan for more than we can be sure of.
export const FALLBACK_CONTEXT_WINDOW = 8_192;
+// Output reserve for a LOCAL model whose window is known. A caller's generic
+// reserve (8K) was sized for cloud windows; on a 16K local daemon it alone is
+// half the window, so a prompt that fits with ample room to answer was refused
+// before dispatch. The local reserve is the larger of a modest floor and an
+// eighth of the window, never more than a quarter of the window (so the floor
+// cannot swallow a tiny window) and never more than the caller declared.
+export const LOCAL_OUTPUT_RESERVE_FLOOR_TOKENS = 2_048;
+export const LOCAL_OUTPUT_RESERVE_WINDOW_DIVISOR = 8;
+export const LOCAL_OUTPUT_RESERVE_MAX_WINDOW_DIVISOR = 4;
+
+/**
+ * The output reserve to plan (and cap generation at) for a local model:
+ * `min(declared, floor(window / 4), max(LOCAL_OUTPUT_RESERVE_FLOOR_TOKENS, floor(window / 8)))`
+ * — 2,048 on a 16K window, 4,096 on 32K, 1,024 on 4K.
+ * Returns `null` when either input is missing or not a positive number — an
+ * unknown window or an undeclared reserve is not something to shrink.
+ *
+ * @param {number|null|undefined} declaredReserveTokens
+ * @param {number|null|undefined} contextWindow
+ * @returns {number|null}
+ */
+export function localOutputReserveTokens(declaredReserveTokens, contextWindow) {
+ const declared = Number(declaredReserveTokens);
+ const window = Number(contextWindow);
+ if (!Number.isFinite(declared) || declared <= 0 || !Number.isFinite(window) || window <= 0) return null;
+ const scaled = Math.max(LOCAL_OUTPUT_RESERVE_FLOOR_TOKENS, Math.floor(window / LOCAL_OUTPUT_RESERVE_WINDOW_DIVISOR));
+ const ceiling = Math.floor(window / LOCAL_OUTPUT_RESERVE_MAX_WINDOW_DIVISOR);
+ return Math.max(1, Math.floor(Math.min(declared, ceiling, scaled)));
+}
+
/** chars/4 token estimate. Conservative (real tokenizers pack denser). */
export const estimateTokens = (text) => Math.ceil(String(text ?? '').length / CHARS_PER_TOKEN);
diff --git a/server/lib/contextBudget.test.js b/server/lib/contextBudget.test.js
index b021cdb96d..b11587c4e0 100644
--- a/server/lib/contextBudget.test.js
+++ b/server/lib/contextBudget.test.js
@@ -10,6 +10,8 @@ import {
CHARS_PER_TOKEN,
FALLBACK_CONTEXT_WINDOW,
MANUSCRIPT_FLOOR_TOKENS,
+ localOutputReserveTokens,
+ LOCAL_OUTPUT_RESERVE_FLOOR_TOKENS,
} from './contextBudget.js';
const section = (n, chars) => ({ number: n, text: 'x'.repeat(chars) });
@@ -30,6 +32,30 @@ const paragraphs = (paras, chars) =>
Array.from({ length: paras }, (_, i) => `${String.fromCharCode(97 + (i % 26))}`.repeat(chars)).join('\n\n');
describe('contextBudget', () => {
+ describe('localOutputReserveTokens', () => {
+ it('shrinks a cloud-sized reserve to fit a 16K local window', () => {
+ // Helm: qwen3:8b at num_ctx 16384 with the mind's declared 8,192 reserve.
+ expect(localOutputReserveTokens(8_192, 16_384)).toBe(LOCAL_OUTPUT_RESERVE_FLOOR_TOKENS);
+ });
+
+ it('scales with the window but never above what the caller declared', () => {
+ expect(localOutputReserveTokens(8_192, 32_768)).toBe(4_096);
+ expect(localOutputReserveTokens(8_192, 131_072)).toBe(8_192);
+ expect(localOutputReserveTokens(1_000, 16_384)).toBe(1_000);
+ });
+
+ it('never lets the floor take more than a quarter of a tiny window', () => {
+ expect(localOutputReserveTokens(8_192, 4_096)).toBe(1_024);
+ });
+
+ it('returns null when the reserve or the window is unknown', () => {
+ expect(localOutputReserveTokens(undefined, 16_384)).toBeNull();
+ expect(localOutputReserveTokens(8_192, null)).toBeNull();
+ expect(localOutputReserveTokens(0, 16_384)).toBeNull();
+ expect(localOutputReserveTokens(8_192, -1)).toBeNull();
+ });
+ });
+
describe('estimateTokens', () => {
it('estimates chars/4, rounding up, and tolerates null', () => {
expect(estimateTokens('')).toBe(0);
diff --git a/server/services/promptRunner.js b/server/services/promptRunner.js
index 2aa94a4924..fc637c8701 100644
--- a/server/services/promptRunner.js
+++ b/server/services/promptRunner.js
@@ -40,14 +40,15 @@ import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { analyzeError, ERROR_CATEGORIES, isRunCanceledError, isRuntimeBudgetError } from '../lib/aiToolkit/errorDetection.js';
import { isSchemaTypeCategory, resolveProviderBench } from '../lib/providerCooldown.js';
import { isGenerationModel, isVisionCapableCliProvider } from '../lib/localModelHeuristics.js';
-import { contextWindowRejection } from '../lib/aiToolkit/providerStatus.js';
+import { contextWindowRejection, knownContextWindow } from '../lib/aiToolkit/providerStatus.js';
+import { isOllamaBackedProvider } from '../lib/aiToolkit/internal/ollamaBacked.js';
import { apiRunAbsoluteTimeoutMs } from '../lib/aiToolkit/internal/runTimeouts.js';
import { withOllamaRuntimeContextWindow } from '../lib/ollamaContext.js';
import { getAIToolkitInstance } from '../lib/aiToolkitState.js';
import { createSingleFlight } from '../lib/singleFlight.js';
import { extractJson } from '../lib/jsonExtract.js';
import { isCreativeRunSource, withCreativeLatitude } from '../lib/creativeLatitude.js';
-import { DEFAULT_OUTPUT_RESERVE_TOKENS, estimateTokens } from '../lib/contextBudget.js';
+import { DEFAULT_OUTPUT_RESERVE_TOKENS, estimateTokens, localOutputReserveTokens } from '../lib/contextBudget.js';
import { allowedModesFor, callerModeRejection } from '../lib/callerModePolicy.js';
import { attachGatewaySiblingKey } from '../lib/providerGateways.js';
@@ -1294,6 +1295,51 @@ function stripFallbackContext(err) {
return err;
}
+/**
+ * Whether `provider` generates on a local inference server — an API provider
+ * served by an Ollama daemon, flagged as llama.cpp / LM Studio / MTPLX / vLLM /
+ * SGLang, or pointed at a loopback endpoint. These are the windows a cloud-sized
+ * output reserve can swallow whole.
+ */
+function isLocalInferenceProvider(provider) {
+ if (provider?.type !== PROVIDER_TYPES.API) return false;
+ return isOllamaBackedProvider(provider)
+ || provider.llamaBacked === true
+ || provider.lmstudioBacked === true
+ || provider.mtplxBacked === true
+ || provider.vllmBacked === true
+ || provider.sglangBacked === true
+ || isLocalEndpoint(provider.endpoint);
+}
+
+/**
+ * The output reserve (and generation cap) for a run on a LOCAL model.
+ *
+ * A caller's declared `outputReserveTokens` is a cloud-sized number (the
+ * persistent mind declares 8,192). On a 16K local daemon that reserve alone is
+ * half the window, so since #9437 made the mind declare it on every wake, a
+ * ~13.5K-token prompt that fits was refused before dispatch ("known 16384-token
+ * context is below the 21744-token request budget"). For a local provider with
+ * a KNOWN window the reserve shrinks to `localOutputReserveTokens` (floor 2,048,
+ * ⅛ of the window, never above what was declared), and the request's
+ * `max_tokens` / `num_predict` is capped at the same number so generation
+ * cannot outgrow the room the gate planned for.
+ *
+ * Unchanged when the caller named its own `maxTokens` (it sized the answer
+ * deliberately), declared no reserve, the window is unknown, or the provider
+ * is not local.
+ *
+ * @returns {Promise<{ outputReserveTokens: number|undefined, maxTokens: number|undefined }>}
+ */
+async function resolveLocalOutputBudget(provider, model, { outputReserveTokens, maxTokens }) {
+ const unchanged = { outputReserveTokens, maxTokens };
+ if (Number.isInteger(maxTokens) && maxTokens > 0) return unchanged;
+ if (!Number.isFinite(Number(outputReserveTokens)) || !isLocalInferenceProvider(provider)) return unchanged;
+ const observed = withOllamaRuntimeContextWindow(await withObservedContextWindowsLazy(provider));
+ const reserve = localOutputReserveTokens(outputReserveTokens, knownContextWindow(observed, model));
+ return reserve ? { outputReserveTokens: reserve, maxTokens: reserve } : unchanged;
+}
+
/**
* The budget a pre-dispatch REFUSAL is allowed to act on.
*
@@ -1446,11 +1492,12 @@ async function executeProviderRunOnce({
// context gate needs it on EVERY attempt — a caller that supplies its own
// runId (stageRunner, the loops) skips that branch entirely and would
// otherwise dispatch ungated.
- const requestCapabilities = buildRequestCapabilities({ prompt, screenshots, outputReserveTokens, callerPolicy });
+ const localBudget = await resolveLocalOutputBudget(provider, effectiveModel, { outputReserveTokens, maxTokens });
+ const requestCapabilities = buildRequestCapabilities({ prompt, screenshots, outputReserveTokens: localBudget.outputReserveTokens, callerPolicy });
await assertRequestFitsContext(
effectiveProvider,
effectiveModel,
- refusalCapabilities({ requestCapabilities, prompt, outputReserveTokens }),
+ refusalCapabilities({ requestCapabilities, prompt, outputReserveTokens: localBudget.outputReserveTokens }),
{ runId: callerRunId, startTime: Date.now() },
);
@@ -1726,7 +1773,7 @@ async function executeProviderRunOnce({
// a per-call override (e.g. the importer's long stage timeout) governs the
// ceiling instead of the runner's provider/default fallback — same
// caller-override precedence CLI/TUI runs already get.
- executeApiRun({ runId, provider: effectiveProvider, model: effectiveModel, prompt, workspacePath: effectiveCwd, screenshots: Array.isArray(screenshots) ? screenshots : [], onData, onComplete, timeout: effectiveTimeout, absoluteTimeoutMs, maxTokens, ...(admitDispatch ? { beforeExecute: admitDispatch } : {}) }).catch(safeReject);
+ executeApiRun({ runId, provider: effectiveProvider, model: effectiveModel, prompt, workspacePath: effectiveCwd, screenshots: Array.isArray(screenshots) ? screenshots : [], onData, onComplete, timeout: effectiveTimeout, absoluteTimeoutMs, maxTokens: effectiveProvider === provider ? localBudget.maxTokens : maxTokens, ...(admitDispatch ? { beforeExecute: admitDispatch } : {}) }).catch(safeReject);
} else if (effectiveProvider.type === PROVIDER_TYPES.TUI) {
// `source` (e.g. 'pipeline-manuscript-completeness') labels the live,
// interactive view this TUI run surfaces in the Shell page.
diff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.js
index 8f59c9f436..076d968a07 100644
--- a/server/services/promptRunner.test.js
+++ b/server/services/promptRunner.test.js
@@ -2635,6 +2635,86 @@ describe('promptRunner — context gate on the requested provider', () => {
expect(status.markUnavailable).not.toHaveBeenCalled();
});
+ // #9437 made the persistent mind declare an 8,192-token reserve on every
+ // wake. On a 16K local daemon that refused a ~13.5K-token prompt that fits
+ // ("known 16384-token context is below the 21744-token request budget").
+ // A local provider plans a window-sized reserve instead, and caps generation
+ // at the same number so the answer cannot outgrow the room the gate planned.
+ describe('local output reserve', () => {
+ const localOllama = (extra = {}) => apiProvider({
+ id: 'ollama',
+ name: 'Ollama',
+ defaultModel: 'qwen3.8-27b',
+ models: ['qwen3.8-27b'],
+ endpoint: 'http://localhost:11434/v1',
+ ...extra,
+ });
+ // ~13,552 prompt tokens: fits 16K with a 2,048 reserve, not with 8,192.
+ const HELM_SIZED_PROMPT = 'x'.repeat(13_552 * 4);
+
+ it('dispatches a prompt that fits a 16K local window and caps max tokens at the local reserve', async () => {
+ observedWindows.withObservedContextWindows.mockImplementation(servingWindow(16_384));
+ runner.executeApiRun.mockImplementation(async ({ onComplete }) => onComplete({ success: true }));
+
+ await runPromptThroughProvider({
+ provider: localOllama(),
+ prompt: HELM_SIZED_PROMPT,
+ source: 'test',
+ outputReserveTokens: 8_192,
+ allowFallback: false,
+ });
+
+ expect(runner.executeApiRun).toHaveBeenCalledTimes(1);
+ expect(runner.executeApiRun.mock.calls[0][0].maxTokens).toBe(2_048);
+ });
+
+ it('still refuses a local prompt that cannot fit even with the smaller reserve', async () => {
+ observedWindows.withObservedContextWindows.mockImplementation(servingWindow(16_384));
+
+ const rejection = await runPromptThroughProvider({
+ provider: localOllama(),
+ prompt: 'x'.repeat(15_000 * 4),
+ source: 'test',
+ outputReserveTokens: 8_192,
+ allowFallback: false,
+ }).catch((err) => err);
+
+ expect(rejection.message).toMatch(/known 16384-token context is below the 17048-token request budget/);
+ expect(runner.executeApiRun).not.toHaveBeenCalled();
+ });
+
+ it('leaves an explicit caller maxTokens alone', async () => {
+ observedWindows.withObservedContextWindows.mockImplementation(servingWindow(32_768));
+ runner.executeApiRun.mockImplementation(async ({ onComplete }) => onComplete({ success: true }));
+
+ await runPromptThroughProvider({
+ provider: localOllama(),
+ prompt: 'short',
+ source: 'test',
+ outputReserveTokens: 8_192,
+ maxTokens: 6_000,
+ allowFallback: false,
+ });
+
+ expect(runner.executeApiRun.mock.calls[0][0].maxTokens).toBe(6_000);
+ });
+
+ it('keeps the declared reserve for a cloud provider', async () => {
+ observedWindows.withObservedContextWindows.mockImplementation(servingWindow(16_384));
+
+ const rejection = await runPromptThroughProvider({
+ provider: apiProvider({ id: 'cloud-api', name: 'Cloud API', defaultModel: 'qwen3.8-27b', endpoint: 'https://api.example.com/v1' }),
+ prompt: HELM_SIZED_PROMPT,
+ source: 'test',
+ outputReserveTokens: 8_192,
+ allowFallback: false,
+ }).catch((err) => err);
+
+ expect(rejection.message).toMatch(/known 16384-token context is below the 21744-token request budget/);
+ expect(runner.executeApiRun).not.toHaveBeenCalled();
+ });
+ });
+
it('dispatches unchanged when nothing declared a window', async () => {
// The default mock is the no-observation answer: a daemon that is down,
// silent about windows, or not daemon-backed at all. Unknown must keep