Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review: settle a caller-owned run record on refusal, and never refuse on a reserve nobody asked for
[._.]/ Adam Eivy5af42a7e0463
diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex 1c6c6cbcc6..845251ae3b 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -1245,6 +1245,28 @@ function stripFallbackContext(err) {return err;}+/**+ * The budget a pre-dispatch REFUSAL is allowed to act on.+ *+ * `requiredContextTokens` is the prompt plus an output reserve, and when the+ * caller named no reserve that is `DEFAULT_OUTPUT_RESERVE_TOKENS` — 8,000+ * tokens nobody asked for. Ranking fallback candidates on that optimistic+ * budget is fine (it prefers a provider with room to answer), but REFUSING on+ * it turns "provably cannot fit" into "probably cannot fit": a pinned caller+ * sending a 26K-token prompt to a 32K endpoint and expecting three sentences+ * back would be refused, though it succeeds today — these daemons size the+ * answer from what the window has left.+ *+ * So a refusal uses the provable floor — the prompt alone — unless the caller+ * declared its own `outputReserveTokens`, which is it telling us how much room+ * the answer genuinely needs. Candidate ranking in `getFallbackProvider` keeps+ * using the full budget, exactly as it did before this gate existed.+ */+function refusalCapabilities({ requestCapabilities, prompt, outputReserveTokens }) {+ if (Number.isFinite(Number(outputReserveTokens))) return requestCapabilities;+ return { ...requestCapabilities, requiredContextTokens: estimateTokens(prompt) };+}+/*** Refuse a prompt that provably cannot fit the provider about to run it.*@@ -1259,12 +1281,8 @@ function stripFallbackContext(err) {* `null` whenever nothing declared a window, and nothing infers one from a* model id — so a provider PortOS has no data about dispatches exactly as* it does today.- * - The budget compared is `requiredContextTokens` — the prompt PLUS the- * caller's output reserve — because these daemons spend one window on input- * and output together. Comparing the prompt alone would have let the- * reported stall through: its ~14K-token prompt fit the window on its own,- * and only the reserve on top of it did not. A caller that knows its answer- * is short says so with `outputReserveTokens` rather than being guessed at.+ * - What it compares is `refusalCapabilities`, not the raw routing budget:+ * a reserve the caller never asked for must not manufacture a refusal.* - The refusal is an ORDINARY failure, not a new category or exception class.* `context-length` is what `agentErrorAnalysis.js` and `codexTurn.js`* already tag an oversized prompt, and it is request-specific@@ -1280,7 +1298,7 @@ function stripFallbackContext(err) {* `capabilityRejection`, so the only cost is a cached listing spent on a* primary that turns out to be benched.*/-async function assertRequestFitsContext(provider, model, requestCapabilities) {+async function assertRequestFitsContext(provider, model, requestCapabilities, { runId = null, startTime = null } = {}) {const required = Number(requestCapabilities?.requiredContextTokens);if (!Number.isFinite(required) || required <= 0) return;@@ -1292,14 +1310,23 @@ async function assertRequestFitsContext(provider, model, requestCapabilities) {const reason = contextWindowRejection(observed, model, requestCapabilities);if (!reason) return;- const err = new Error(`${provider.name || provider.id}${model ? ` (${model})` : ''}: ${reason}`);+ const message = `${provider.name || provider.id}${model ? ` (${model})` : ''}: ${reason}`;+ // A caller that created its own run record (stageRunner, the loops) has one+ // sitting at `success: null, endTime: null`. Throwing past it leaves the Runs+ // page showing an attempt that never ends and every `success === null`+ // reconciler seeing a phantom active run, so settle it here — the same thing+ // the TUI readiness check below does for its own pre-execution refusal.+ if (runId) {+ await finalizeRunRecord({ runId, output: '', exitCode: 1, success: false, error: message, startTime });+ }+ const err = new Error(message);// The cascade only retries a failure annotated with the provider that ran// (see runPromptThroughProvider) — without these the refusal would be// rethrown straight to the caller and a wider fallback would never be tried.err.effectiveProvider = provider;err.effectiveModel = model;- err.errorAnalysis = { category: CONTEXT_LENGTH_CATEGORY, message: err.message };- console.log(`📏 Refused before dispatch: ${err.message}`);+ err.errorAnalysis = { category: CONTEXT_LENGTH_CATEGORY, message };+ console.log(`📏 Refused before dispatch: ${message}`);throw err;}@@ -1364,7 +1391,12 @@ async function executeProviderRunOnce({// runId (stageRunner, the loops) skips that branch entirely and would// otherwise dispatch ungated.const requestCapabilities = buildRequestCapabilities({ prompt, screenshots, outputReserveTokens, callerPolicy });- await assertRequestFitsContext(effectiveProvider, effectiveModel, requestCapabilities);+ await assertRequestFitsContext(+ effectiveProvider,+ effectiveModel,+ refusalCapabilities({ requestCapabilities, prompt, outputReserveTokens }),+ { runId: callerRunId, startTime: Date.now() },+ );// Some call sites (stageRunner, loops) create the run themselves so// they can log the runId before the LLM call starts. When provided,diff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.jsindex 0a1e08abb5..ab860235df 100644--- a/server/services/promptRunner.test.js+++ b/server/services/promptRunner.test.js@@ -15,6 +15,10 @@ vi.mock('./runner.js', () => ({// run record's providerId/model so /runs attribution matches what// actually ran. Mocked as a no-op resolve.patchRunMetadata: vi.fn().mockResolvedValue(undefined),+ // Settles a run record a pre-execution refusal throws past (the TUI readiness+ // check and the context gate), so the Runs page never shows an attempt that+ // never ends.+ finalizeRunRecord: vi.fn().mockResolvedValue(undefined),}));// TUI runner is in lib (different module from services/runner.js) — mock it@@ -2385,6 +2389,9 @@ describe('promptRunner — context gate on the requested provider', () => {vllmBacked: true,endpoint: 'http://127.0.0.1:18020/v1',});+ // ~5,000 prompt tokens on its own — over a 4096-token window with no+ // reserve arithmetic needed.+ const OVERSIZED_PROMPT = 'x'.repeat(20_000);const servingWindow = (tokens) => async (provider) => ({...provider,modelContextWindows: { 'qwen3.8-27b': tokens },@@ -2414,7 +2421,7 @@ describe('promptRunner — context gate on the requested provider', () => {const rejection = await runPromptThroughProvider({provider: vllmCli(),- prompt: 'a prompt that does not fit',+ prompt: OVERSIZED_PROMPT,source: 'test',allowFallback: false,}).catch((err) => err);@@ -2426,13 +2433,66 @@ describe('promptRunner — context gate on the requested provider', () => {// Both numbers, because the operator's next move depends on the gap:// a smaller prompt, or a provider with a wider window.- expect(rejection.message).toMatch(/known 4096-token context is below the 8\d{3}-token request budget/);+ expect(rejection.message).toMatch(/known 4096-token context is below the \d+-token request budget/);expect(rejection.message).toContain('OpenCode vLLM (qwen3.8-27b)');// The whole point: no run record, no spawn, no ten-minute stall.expect(runner.createRun).not.toHaveBeenCalled();expect(runner.executeCliRun).not.toHaveBeenCalled();});+ // The refusal must act on what is PROVABLE. `requiredContextTokens` adds an+ // 8,000-token output reserve that most callers never asked for; refusing on+ // it would kill a 26K-token prompt to a 32K endpoint that expects three+ // sentences back and succeeds today.+ it('does not refuse on an output reserve the caller never asked for', async () => {+ observedWindows.withObservedContextWindows.mockImplementation(servingWindow(4096));+ runner.executeCliRun.mockImplementation(async ({ onComplete }) => onComplete({ success: true }));++ // ~2,000 prompt tokens: under the 4096 window on its own, over it once the+ // default 8,000-token reserve is added.+ await runPromptThroughProvider({ provider: vllmCli(), prompt: 'x'.repeat(8_000), source: 'test' });+ expect(runner.executeCliRun).toHaveBeenCalledTimes(1);+ });++ it('honors a reserve the caller DID declare', async () => {+ observedWindows.withObservedContextWindows.mockImplementation(servingWindow(4096));++ // Same prompt, but now the caller says it needs 4,000 tokens of answer —+ // that genuinely does not fit, and it said so itself.+ const rejection = await runPromptThroughProvider({+ provider: vllmCli(),+ prompt: 'x'.repeat(8_000),+ source: 'test',+ outputReserveTokens: 4_000,+ allowFallback: false,+ }).catch((err) => err);++ expect(rejection.message).toContain('known 4096-token context is below');+ expect(runner.executeCliRun).not.toHaveBeenCalled();+ });++ // stageRunner and the loops create the run record themselves. Throwing past+ // one leaves the Runs page showing an attempt that never ends, and every+ // `success === null` reconciler seeing a phantom active run.+ it('settles a caller-supplied run record instead of stranding it open', async () => {+ observedWindows.withObservedContextWindows.mockImplementation(servingWindow(4096));++ await runPromptThroughProvider({+ provider: vllmCli(),+ prompt: OVERSIZED_PROMPT,+ source: 'test',+ runId: 'caller-owned-run',+ allowFallback: false,+ }).catch(() => {});++ expect(runner.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'caller-owned-run',+ success: false,+ exitCode: 1,+ error: expect.stringContaining('4096-token context'),+ }));+ });+it('routes an oversized request to a fallback instead of benching a healthy daemon', async () => {const status = mockToolkitWithFallbackFor(vllmCli());observedWindows.withObservedContextWindows.mockImplementation(async (provider) => (@@ -2442,7 +2502,7 @@ describe('promptRunner — context gate on the requested provider', () => {const out = await runPromptThroughProvider({provider: vllmCli(),- prompt: 'a prompt that does not fit',+ prompt: OVERSIZED_PROMPT,source: 'test',});