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
refuse a prompt that outgrew the local daemon's served context window (#7441)
[._.]/ Adam Eivy7befc015db14
diff --git a/server/lib/README.md b/server/lib/README.mdindex 95b3ada4d1..2e5f88712c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -249,7 +249,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `sglangQwenProject.js` | `resolveSglangProjectDir()` / `inspectSglangQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator's SGLang Qwen3.8-27B project, plus `sglangStartBlockedReason(project)` → the prose refusal (or `null`). Sibling of `vllmQwenProject.js` with the same tri-state `hasWeights` contract (`true` found / `false` caches read and empty / `null` no cache readable) and the same directory-reads-only rule — never docker, never a registry. Differs in that PortOS OWNS this launch line (SGLang publishes an image but no compose project), so the refusals point at the compose file in `docs/features/sglang-qwen38.md` rather than at a `git clone`. Also this stack's keyed view of `recordedProjectDir.js` — `readRecordedSglangProjectDir(envPath?)` / `recordSglangProjectDir(dir, envPath?)` / `sglangProjectDirIsSettled()` plus `SGLANG_PROJECT_LEAF` — so `resolveSglangProjectDir()` reads `SGLANG_QWEN_PROJECT_DIR` → the UNC path `services/sglangQwenManager.js` detected and recorded on Windows → `~/sglang-qwen38`. Overrides: `SGLANG_QWEN_PROJECT_DIR`, `SGLANG_QWEN_WEIGHTS_DIR`. || `sglangQwenRecipe.js` | The `sglang serve` launch line PortOS owns, per NVIDIA card class. `buildSglangQwenRecipe({hw, contextLength, ssmDtype, spec, radixStrategy, host, port})` → `{image, modelName, modelPath, cell, mambaRatio, stateSlots, flags, env}`, and `sglangComposeYaml(recipe)` renders the `docker-compose.yml` from it (one source of truth; a test pins the doc against it). `mambaFullMemoryRatio(...)` derives `--mamba-full-memory-ratio` from the cookbook formula `(S + D) × state_bytes / (L × kv_bytes_per_token)` — load-bearing, because the cookbook default `0.9` under-sizes the GDN state pool at CoS prompt lengths and silently clamps `max_running_requests`. Both Qwen parsers (`--reasoning-parser qwen3`, `--tool-call-parser qwen3_coder` — NOT vLLM's `qwen3_xml`) are baked into every cell: getting them wrong fails silently, with the model emitting raw markup and the agent never calling a tool. `sglangCellForGpu(gpu)` maps a `cudaCapability.js` compute-cap row to a cell (SM 9.x → `h200`, SM ≥10 → `rtx6000`/`rtx5090` by VRAM, Ampere → `null`, which is a refusal: 24 GB stays on vLLM), and `sglangUnsupportedReason({platform, status, gpus})` is the prose for every no — never collapsing a probe `'unknown'` into "no GPU". Pure: no filesystem, no docker, no network. || `opencodeStream.js` | OpenCode's `--format json` event stream — ONE parser, shared by `services/localModelAgentBenchmark.js` (which wants chars/tokens) and `services/modelCapabilityTests.js` (which wants a readable transcript). `eventPart` (accepts the flat `{part}` and nested `{properties.part}` envelopes OpenCode has both used), `isToolEvent` / `eventText`, `parseAgentLine` / `parseAgentEvents` (blank and unparsable lines yield nothing rather than throwing), `formatAgentEvent` (one frame → a transcript line a person can read, with the path or command the tool acted on), and `summarizeOpenCodeEvents` (assistant chars, tool calls, and output tokens — `null`, never 0, when OpenCode reported no usage; tool ARGUMENTS are deliberately not counted as answer text). Pure. The runner that produces the stream is `services/opencodeTask.js`. |-| `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs, apiKey })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. `apiKey` attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers `reachable: true` with `error: 'authentication required'` — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. |+| `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs, apiKey })` → `{ reachable, models, contextWindows, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/observedContextWindows.js` (and through it `services/providerReadiness.js`) and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`). `contextWindows` keys each served model to the window the listing declared (`max_model_len` / `n_ctx` / `loaded_context_length` / `context_length`, smallest wins), carrying an entry only where one was declared so `{}` reads as unknown — without it a prompt too large for the endpoint was dispatched anyway and stalled until the provider timeout (#7441). It also names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. `apiKey` attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers `reachable: true` with `error: 'authentication required'` — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. |+| `openAiModelsProbeCache.js` | `probeOpenAiModelsCached(endpoint, apiKey)` and `resetOpenAiModelsProbeCache()` — the shared 15s TTL cache in front of `openAiModelsProbe.js`, keyed `endpoint\napiKey` (two providers on one authenticated endpoint must not inherit each other’s 401) and storing the PROMISE so N providers sharing a daemon share one socket. It lives BELOW its two readers — `services/providerReadiness.js`’s checklist and `services/observedContextWindows.js`’s pre-dispatch context gate — so a page poll and a run starting in the same window cost one listing and can never disagree about a daemon that restarted between them. An unexpected throw drops the entry rather than poisoning it for the TTL; expired entries are swept on every miss. `services/providerReadiness.js#resetProviderReadinessCache` clears it for the llama-server lifecycle routes. || `openAiChatStream.js` | `iterateOpenAiChat(...)` → normalized async content/reasoning chunks and `streamOpenAiChat(...)` → the streamed text — one streaming `POST {base}/chat/completions` against any OpenAI-compatible endpoint; both own timeout/abort composition, retries, parsing, backpressure, and reader cleanup. `streamOllamaChat(...)` is the assessment-only native `/api/chat` transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports `buildMessages`, `parseStreamFrame`, `parseOllamaStreamFrame`, `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported), and `resolvePartialOutput`. Registering `onStats` on the OpenAI path asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint. Sibling of `openAiModelsProbe.js`. Shared by Ask (`services/askService.js`), `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record), and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. || `callerModePolicy.js` | The one caller EXECUTION-MODE policy: `CALLER_MODE_POLICIES` (`agent-harness`, `cli-harness`, `direct-api`, `any-text`) plus `resolveCallerModePolicy` / `allowedModesFor` / `callerModeRejection` / `isCallerModeEligible` / `filterCallerModeEligible`. Answers "may THIS caller run on THAT route mode?" for an explicit pin, `activeProvider` inheritance and every fallback candidate alike — `allowedModesFor()` is what rides on `requestCapabilities.allowedModes` into the toolkit's `getFallbackProvider`. Pure and dependency-light so the out-of-process autofixer can import it; `enabled`/benched state, prerequisites and text-transport consent stay with their existing owners. Unknown never becomes true: a record with no executable mode, and a required model capability with no positive evidence, are both refused. || `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: filters the inherited base to runtime essentials/provider auth, then layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.mdindex 32b3521b6d..dd307adc36 100644--- a/server/lib/aiToolkit/AGENTS.md+++ b/server/lib/aiToolkit/AGENTS.md@@ -3,7 +3,7 @@The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previously the `portos-ai-toolkit` npm package.) Keep the directory self-contained — no imports out to other PortOS modules — so future upstream syncs don't fight local edits.**Key points:**-- `index.js` exports `createAIToolkit`, `createProviderStatusService`, and the four Router factories (providers / runs / prompts / providerStatus)+- `index.js` exports `createAIToolkit`, `createProviderStatusService`, the four Router factories (providers / runs / prompts / providerStatus), and the context-fit pair `knownContextWindow` / `contextWindowRejection` — the host applies the same rule to the EXPLICITLY requested provider, which `getFallbackProvider` never sees. Both answer `null` for an unknown window, which every caller must keep reading as "no constraint"; nothing infers a window from a model id.- Provider configuration (models, tiers, fallbacks) lives in `providers.js`- `loadProviders()` auto-migrates legacy codex configs to the `codex-configured-default` sentinel; `server/index.js` warms it at startup so the rewrite happens before any request- PortOS extends toolkit routes in `server/routes/providers.js` for vision testing and provider status (status routes live in PortOS, not the toolkit, because they call PortOS-side socket helpers)diff --git a/server/lib/aiToolkit/index.js b/server/lib/aiToolkit/index.jsindex f2f4511760..b6cb7c1b1f 100644--- a/server/lib/aiToolkit/index.js+++ b/server/lib/aiToolkit/index.js@@ -14,7 +14,7 @@ import {} from './providers.js';import { createRunnerService } from './runner.js';import { createPromptsService } from './prompts.js';-import { createProviderStatusService } from './providerStatus.js';+import { contextWindowRejection, createProviderStatusService, knownContextWindow } from './providerStatus.js';import { createProvidersRoutes } from './routes/providers.js';import { createRunsRoutes } from './routes/runs.js';import { createPromptsRoutes } from './routes/prompts.js';@@ -31,6 +31,9 @@ export * from './errorDetection.js';export * from './endpointGuard.js';export * from './constants.js';export { createProviderService, createRunnerService, createPromptsService, createProviderStatusService };+// The context-fit rule, for the host's pre-dispatch gate on the EXPLICITLY+// requested provider — the one candidate `getFallbackProvider` never sees.+export { contextWindowRejection, knownContextWindow };export { isOllamaBackedProvider, canRefreshModels, ollamaRefreshGroupKey };export { createProvidersRoutes, createRunsRoutes, createPromptsRoutes, createProviderStatusRoutes };diff --git a/server/lib/aiToolkit/providerStatus.js b/server/lib/aiToolkit/providerStatus.jsindex c4b758ac2c..d8fad4f19e 100644--- a/server/lib/aiToolkit/providerStatus.js+++ b/server/lib/aiToolkit/providerStatus.js@@ -86,7 +86,20 @@ function resolvedFallbackModel(provider, correctedModel) {|| null;}-function knownContextWindow(provider, model) {+/**+ * The context window PortOS actually KNOWS this provider serves for this model,+ * or `null` for "no data".+ *+ * `null` is load-bearing and must never collapse into a number: every caller+ * reads it as "no constraint", so inventing a window here would refuse requests+ * that work today. Nothing infers a window from the model id — a name is not a+ * declaration, and the daemons that matter here rename freely+ * (`llama-server --alias`).+ *+ * Exported because the host applies the same rule to the EXPLICITLY REQUESTED+ * provider, which never passes through `getFallbackProvider` below.+ */+export function knownContextWindow(provider, model) {const explicit = Number(provider?.contextWindow);const catalog = Number(model && provider?.modelContextWindows?.[model]);const runtime = Number(provider?.numCtx);@@ -126,13 +139,21 @@ function modeRejection(provider, requestCapabilities) {return null;}-function capabilityRejection(provider, model, requestCapabilities) {- if (!requestCapabilities || typeof requestCapabilities !== 'object') return null;- if (requestCapabilities.hasImages === true && provider?.type !== 'api') {- return 'cannot transmit image input';- }-- const required = Number(requestCapabilities.requiredContextTokens);+/**+ * Why this prompt cannot fit this provider/model, or `null`.+ *+ * An UNKNOWN window is never a rejection — `knownContextWindow` returning+ * `null` means "no constraint", which is how every provider routed before any+ * window was recorded and how a provider whose daemon is down must keep+ * routing.+ *+ * Exported alongside `knownContextWindow` because the host applies this same+ * rule to the EXPLICITLY REQUESTED provider before dispatch. Until #7441 the+ * check ran only inside `getFallbackProvider` below, so the provider that+ * actually serves the happy path was never asked whether the prompt fit.+ */+export function contextWindowRejection(provider, model, requestCapabilities) {+ const required = Number(requestCapabilities?.requiredContextTokens);const available = knownContextWindow(provider, model);if (Number.isFinite(required) && required > 0 && available && required > available) {return `known ${available}-token context is below the ${required}-token request budget`;@@ -140,6 +161,13 @@ function capabilityRejection(provider, model, requestCapabilities) {return null;}+function capabilityRejection(provider, model, requestCapabilities) {+ if (requestCapabilities?.hasImages === true && provider?.type !== 'api') {+ return 'cannot transmit image input';+ }+ return contextWindowRejection(provider, model, requestCapabilities);+}+function noEligibleFallbackError(rejections) {const detail = rejections.map(({ provider, reason }) => `${provider}: ${reason}`).join('; ');const error = new Error(`No eligible fallback can satisfy this request (${detail})`);diff --git a/server/lib/index.js b/server/lib/index.jsindex d3db09598d..e787ea3e1b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -248,6 +248,7 @@ export * from './vllmQwenProvision.js';export * from './sglangQwenProject.js';export * from './sglangQwenRecipe.js';export * from './openAiModelsProbe.js';+export * from './openAiModelsProbeCache.js';export * from './openAiChatStream.js';// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live in// mediaModels.js — namespace it so the barrel surface is unambiguous.diff --git a/server/lib/openAiModelsProbe.js b/server/lib/openAiModelsProbe.jsindex c6a6e6cb78..1862a19ee9 100644--- a/server/lib/openAiModelsProbe.js+++ b/server/lib/openAiModelsProbe.js@@ -14,6 +14,13 @@* - `reachable: true, models: null`— it answered, but the listing was unreadable* - `reachable: true, models: []` — it is up and genuinely serving nothing*+ * The listing also carries each model's SERVED context window (vLLM spells it+ * `max_model_len`, llama-server `n_ctx`, LM Studio `loaded_context_length`), and+ * `contextWindows` keeps it. Dropping it was how a prompt that provably could+ * not fit still got dispatched: nothing upstream could tell a 50K-char prompt+ * from a 15K one against a 32K endpoint, so the only backstop was the+ * provider's wall-clock timeout (#7441).+ ** A daemon started behind an API key (vLLM's compose stack sets `VLLM_API_KEY`)* answers 401/403 to an unauthenticated probe. That is a REACHABLE server whose* listing we cannot read — reporting it as unreachable would tell the user to@@ -21,6 +28,13 @@* too.*/+// The toolkit's model refresh already reads a window off a listing row, and a+// second table here would let refresh-time and probe-time disagree about the+// same daemon. Reaching INTO `aiToolkit/internal/` is the established direction+// (`openAiChatStream.js`, `harnessOutput.js`, `providerGraphPreview.js` all do+// it) — the self-containment rule in its AGENTS.md forbids the toolkit+// importing OUT, not the host importing in.+import { catalogContextWindow } from './aiToolkit/internal/modelCatalog.js';import { fetchWithTimeout } from './fetchWithTimeout.js';import { describeFetchError } from './fetchErrorChain.js';import { readResponseJson } from './readResponseJson.js';@@ -44,7 +58,12 @@ function shortFailureReason(err) {/*** @param {string} baseUrl - an OpenAI-compatible base (…/v1); trailing slashes tolerated* @param {{timeoutMs?: number, apiKey?: string}} [opts]- * @returns {Promise<{reachable:boolean, models:string[]|null, error:string|null}>}+ * @returns {Promise<{reachable:boolean, models:string[]|null, contextWindows:Record<string,number>|null, error:string|null}>}+ * `contextWindows` carries an entry only for a model whose window the listing+ * actually declared, so `{}` means "nothing declared one" — never "these+ * models have no window". It is `null` exactly when `models` is. Per-row+ * parsing (which key, and smallest-wins when a row declares several) is+ * `catalogContextWindow`'s rule, shared with model refresh.*/export async function probeOpenAiModels(baseUrl, { timeoutMs = 2_000, apiKey = '' } = {}) {const url = `${String(baseUrl || '').replace(/\/+$/, '')}/models`;@@ -56,7 +75,7 @@ export async function probeOpenAiModels(baseUrl, { timeoutMs = 2_000, apiKey = '// cause chain..catch((err) => ({ transportError: shortFailureReason(err) }));- if (res.transportError) return { reachable: false, models: null, error: res.transportError };+ if (res.transportError) return { reachable: false, models: null, contextWindows: null, error: res.transportError };if (!res.ok) {// Undici holds the socket until an unread body is consumed; an endpoint// answering 404 on every poll would otherwise leak one each time.@@ -65,9 +84,9 @@ export async function probeOpenAiModels(baseUrl, { timeoutMs = 2_000, apiKey = '// read the request and refused it. Collapsing that into "nothing answered"// sends the user off to start a server that is already serving.if (res.status === 401 || res.status === 403) {- return { reachable: true, models: null, error: 'authentication required' };+ return { reachable: true, models: null, contextWindows: null, error: 'authentication required' };}- return { reachable: false, models: null, error: `HTTP ${res.status}` };+ return { reachable: false, models: null, contextWindows: null, error: `HTTP ${res.status}` };}// The body read is its own failure path: a daemon that accepts the connection@@ -78,12 +97,15 @@ export async function probeOpenAiModels(baseUrl, { timeoutMs = 2_000, apiKey = '// reachable-but-unreadable sentinel as a non-JSON body.const body = await readResponseJson(res, { fallback: null, emptyValue: null }).catch(() => null);const rows = Array.isArray(body?.data) ? body.data : Array.isArray(body?.models) ? body.models : null;- if (!rows) return { reachable: true, models: null, error: 'model listing was not readable' };- return {- reachable: true,- models: rows- .map((row) => (typeof row === 'string' ? row : row?.id || row?.name))- .filter((id) => typeof id === 'string' && id !== ''),- error: null,- };+ if (!rows) return { reachable: true, models: null, contextWindows: null, error: 'model listing was not readable' };+ const models = [];+ const contextWindows = {};+ for (const row of rows) {+ const id = typeof row === 'string' ? row : (row?.id || row?.name);+ if (typeof id !== 'string' || id === '') continue;+ models.push(id);+ const tokens = catalogContextWindow(row);+ if (tokens) contextWindows[id] = tokens;+ }+ return { reachable: true, models, contextWindows, error: null };}diff --git a/server/lib/openAiModelsProbe.test.js b/server/lib/openAiModelsProbe.test.jsindex ac609973b4..0a7d3b28c8 100644--- a/server/lib/openAiModelsProbe.test.js+++ b/server/lib/openAiModelsProbe.test.js@@ -34,6 +34,45 @@ describe('probeOpenAiModels', () => {await expect(probeOpenAiModels('http://x/v1')).resolves.toMatchObject({ reachable: true, models: ['a'] });});+ it('keeps each served model\'s declared context window, whatever the daemon calls it', async () => {+ // vLLM says `max_model_len`, llama-server `n_ctx`, LM Studio+ // `loaded_context_length`. Throwing these away is what let an oversized+ // prompt reach an endpoint that could never serve it (#7441).+ mockFetch(async () => jsonResponse({+ data: [+ { id: 'qwen3.8-27b', max_model_len: 32768 },+ { id: 'dflash', n_ctx: 8192 },+ { id: 'lmstudio-model', loaded_context_length: 16384 },+ { id: 'silent' },+ ],+ }));++ await expect(probeOpenAiModels('http://x/v1')).resolves.toMatchObject({+ reachable: true,+ models: ['qwen3.8-27b', 'dflash', 'lmstudio-model', 'silent'],+ // `silent` is ABSENT, not zero: a row that declares no window says+ // nothing about that model, and a caller must read it as unknown.+ contextWindows: { 'qwen3.8-27b': 32768, dflash: 8192, 'lmstudio-model': 16384 },+ });+ });++ it('takes the SMALLEST window a row declares', async () => {+ // A row that reports both a trained maximum and the narrower window the+ // process was actually loaded at means the loaded one. Budgeting to the+ // wider number builds a prompt the running server rejects.+ mockFetch(async () => jsonResponse({+ data: [+ { id: 'loaded-small', max_model_len: 131072, n_ctx: 8192 },+ { id: 'routed', context_length: 1_000_000, top_provider: { context_length: 128_000 } },+ { id: 'nonsense', max_model_len: 0, n_ctx: 'lots' },+ ],+ }));++ await expect(probeOpenAiModels('http://x/v1')).resolves.toMatchObject({+ contextWindows: { 'loaded-small': 8192, routed: 128_000 },+ });+ });+it('tells a server with nothing loaded from one whose listing is unreadable', async () => {mockFetch(async () => jsonResponse({ data: [] }));// Up and serving nothing — an actionable "load a model", not a connection problem.@@ -62,6 +101,7 @@ describe('probeOpenAiModels', () => {await expect(probeOpenAiModels('http://127.0.0.1:8080/v1')).resolves.toEqual({reachable: false,models: null,+ contextWindows: null,error: 'ECONNREFUSED',});});@@ -78,6 +118,7 @@ describe('probeOpenAiModels', () => {await expect(probeOpenAiModels('http://x/v1')).resolves.toEqual({reachable: false,models: null,+ contextWindows: null,error: 'HTTP 404',});// Undici holds the socket until an unread body is consumed; this path runs@@ -109,6 +150,7 @@ it('attaches a Bearer header only when a key is supplied', async () => {await expect(probeOpenAiModels('http://x/v1')).resolves.toEqual({reachable: true,models: null,+ contextWindows: null,error: 'authentication required',});expect(cancel).toHaveBeenCalled();diff --git a/server/lib/openAiModelsProbeCache.js b/server/lib/openAiModelsProbeCache.jsnew file mode 100644index 0000000000..4b8a9b6382--- /dev/null+++ b/server/lib/openAiModelsProbeCache.js@@ -0,0 +1,81 @@+/**+ * The shared TTL cache in front of `probeOpenAiModels`.+ *+ * Two independent readers ask the same local daemons the same question: the+ * Providers page's readiness checklist (`services/providerReadiness.js`) and the+ * pre-dispatch context gate (`services/observedContextWindows.js`). Giving each+ * its own cache would double the polling on every endpoint and let the two+ * disagree about a daemon that restarted between them, so the cache lives HERE —+ * beside the probe, below both services — and each clears it through the same+ * reset.+ *+ * `GET /v1/models` is a listing, never an LLM call, so this is safe to ask from+ * a settings-page poll and from the dispatch path alike under the+ * no-cold-bootstrap policy in AGENTS.md.+ */++import { probeOpenAiModels } from './openAiModelsProbe.js';++/**+ * Loopback daemons answer (or refuse the connection) in single-digit+ * milliseconds, so a short bound keeps a page poll snappy. A host that needs+ * longer than this to answer a model listing is not going to serve an agent run+ * either, and reporting it as unreachable points at the right fix.+ */+const PROBE_TIMEOUT_MS = 2_000;++/**+ * Sized just under the Providers page's 20s poll so consecutive polls each get+ * a fresh answer (a daemon the user just started must show up on the next tick,+ * not two ticks later) while a reload landing on top of a poll still reuses it.+ * Within ONE request the promise cache below is what collapses providers that+ * share an endpoint.+ */+const PROBE_TTL_MS = 15_000;++// endpoint + key → { at, promise } — the PROMISE, not the settled value, so N+// providers sharing one endpoint in the same batch share one socket instead of+// all missing a not-yet-written cache entry at once. The key is part of the+// cache key because two providers can point at one authenticated endpoint with+// different credentials, and one of them getting the other's 401 would be a+// false "not running".+const probeCache = new Map();++/**+ * TTL-cached `GET {endpoint}/models`.+ *+ * @returns {Promise<{reachable:boolean, models:string[]|null, contextWindows:Record<string,number>|null, error:string|null}>}+ * `models: null` means reachable but the listing could not be read — distinct+ * from `[]`, a server that is up with nothing loaded.+ */+export function probeOpenAiModelsCached(endpoint, apiKey = '') {+ const now = Date.now();+ const cacheKey = `${endpoint}\n${apiKey}`;+ const cached = probeCache.get(cacheKey);+ if (cached && now - cached.at < PROBE_TTL_MS) return cached.promise;+ // Sweep while we are here: entries are keyed by endpoint, and an edited or+ // deleted provider would otherwise leave its old endpoint behind forever.+ for (const [key, entry] of probeCache) {+ if (now - entry.at >= PROBE_TTL_MS) probeCache.delete(key);+ }+ // Written BEFORE the await so concurrent callers join this probe. A rejected+ // probe would poison the entry for its TTL, so drop it on failure —+ // `probeOpenAiModels` resolves for every expected failure, making this the+ // unexpected-throw path only.+ const promise = probeOpenAiModels(endpoint, { timeoutMs: PROBE_TIMEOUT_MS, apiKey }).catch((err) => {+ probeCache.delete(cacheKey);+ throw err;+ });+ probeCache.set(cacheKey, { at: now, promise });+ return promise;+}++/**+ * Drop every cached listing, so the next read reflects a daemon that was just+ * started, stopped, or relaunched at a different context size — the transitions+ * the llama-server lifecycle routes already announce through+ * `resetProviderReadinessCache()`.+ */+export function resetOpenAiModelsProbeCache() {+ probeCache.clear();+}diff --git a/server/lib/openAiModelsProbeCache.test.js b/server/lib/openAiModelsProbeCache.test.jsnew file mode 100644index 0000000000..6983e91ad9--- /dev/null+++ b/server/lib/openAiModelsProbeCache.test.js@@ -0,0 +1,51 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import * as probeModule from './openAiModelsProbe.js';+import { probeOpenAiModelsCached, resetOpenAiModelsProbeCache } from './openAiModelsProbeCache.js';++const listing = () => vi.spyOn(probeModule, 'probeOpenAiModels')+ .mockResolvedValue({ reachable: true, models: [], contextWindows: {}, error: null });++afterEach(() => {+ vi.restoreAllMocks();+ resetOpenAiModelsProbeCache();+});++describe('probeOpenAiModelsCached', () => {+ it('collapses concurrent callers onto one request and re-probes after a reset', async () => {+ // The Providers page poll and a run starting in the same window must cost+ // ONE listing; a daemon relaunched at a different `-c` must cost a fresh+ // one, which is what the lifecycle routes' reset buys.+ const spy = listing();++ await Promise.all([+ probeOpenAiModelsCached('http://127.0.0.1:18020/v1'),+ probeOpenAiModelsCached('http://127.0.0.1:18020/v1'),+ ]);+ expect(spy).toHaveBeenCalledTimes(1);++ resetOpenAiModelsProbeCache();+ await probeOpenAiModelsCached('http://127.0.0.1:18020/v1');+ expect(spy).toHaveBeenCalledTimes(2);+ });++ it('keys on the API key so one provider\'s 401 is not another\'s', async () => {+ const spy = listing();++ await probeOpenAiModelsCached('http://127.0.0.1:18020/v1', 'key-a');+ await probeOpenAiModelsCached('http://127.0.0.1:18020/v1', 'key-b');+ expect(spy).toHaveBeenCalledTimes(2);+ });++ it('does not poison the entry for its TTL when the probe throws', async () => {+ // `probeOpenAiModels` resolves for every expected failure, so a throw here+ // is unexpected — and caching the rejection would keep answering with it+ // for 15s after the daemon recovered.+ const spy = vi.spyOn(probeModule, 'probeOpenAiModels')+ .mockRejectedValueOnce(new Error('socket hang up'))+ .mockResolvedValue({ reachable: true, models: [], contextWindows: {}, error: null });++ await expect(probeOpenAiModelsCached('http://127.0.0.1:18020/v1')).rejects.toThrow('socket hang up');+ await expect(probeOpenAiModelsCached('http://127.0.0.1:18020/v1')).resolves.toMatchObject({ reachable: true });+ expect(spy).toHaveBeenCalledTimes(2);+ });+});diff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex 25b6952812..c49e99827b 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -803,6 +803,33 @@ export function prefixOpencodeModel(provider, model) {return id.startsWith(`${namespace}/`) ? id : `${namespace}/${id}`;}+/**+ * The inverse of {@link prefixOpencodeModel} for a KNOWN runtime kind: one model+ * id as the daemon's own listing spells it, with the `<kind>/` namespace+ * stripped. That namespace addresses the OpenCode provider entry and never+ * reaches the daemon, so a provider offering `llama/dflash` and a server serving+ * `dflash` are naming one model — and anything keyed on only one of the two+ * spellings answers "unknown" for half the providers.+ *+ * `null` for anything that does not name a model: blank, non-string, or a "use+ * the CLI's own default" sentinel. Callers that must keep the sentinel should+ * test it themselves before calling.+ *+ * Takes the kind rather than the provider because both callers+ * (`services/providerReadiness.js`'s checklist and+ * `services/observedContextWindows.js`'s dispatch gate) have already resolved+ * the runtime and would otherwise re-derive it per model id.+ *+ * @param {string|null|undefined} model+ * @param {string} kind - the local runtime kind (`llama`, `vllm`, `ollama`, …)+ * @returns {string|null}+ */+export function bareLocalModelId(model, kind) {+ if (typeof model !== 'string' || model.trim() === '' || isConfiguredDefaultModel(model)) return null;+ const trimmed = model.trim();+ return trimmed.startsWith(`${kind}/`) ? trimmed.slice(kind.length + 1) : trimmed;+}+/*** OpenCode's local OpenAI-compatible provider namespace, if this provider has* opted into one. Structural markers avoid deriving a backend from an editablediff --git a/server/services/observedContextWindows.js b/server/services/observedContextWindows.jsnew file mode 100644index 0000000000..95537d82d7--- /dev/null+++ b/server/services/observedContextWindows.js@@ -0,0 +1,97 @@+/**+ * What a local daemon is CURRENTLY serving, window included — observed from+ * `GET /v1/models`, never persisted.+ *+ * A provider seeded by migration (`opencode-vllm` and friends) stores no+ * `contextWindow` and no `modelContextWindows`, so every context-budget+ * question about it answered "unknown" and every prompt was dispatched+ * regardless of size. On one install that cost ten consecutive 600s timeouts:+ * the endpoint accepted a prompt larger than its window, emitted its banner,+ * and produced 36 bytes in ten minutes (#7441). The daemon knew the answer the+ * whole time — vLLM reports `max_model_len` on the same listing row+ * `providerReadiness.js` already polls.+ *+ * Two rules make this OBSERVED RUNTIME STATE rather than configuration:+ *+ * 1. Nothing here writes `providers.json`. The window is a property of the+ * process that is running right now — relaunch llama-server at a smaller+ * `-c` and the stored number would be a lie — and a user editing the+ * provider must never find a probe's value sitting in their record.+ * 2. An endpoint that is down, unreadable, or silent about its windows+ * contributes NOTHING. `null`/`{}` flows through as "unknown", which every+ * consumer already treats as "no constraint", so an install whose daemon+ * is off routes exactly as it did before this module existed.+ *+ * No LLM call is involved — a model listing is free — so this is safe to ask on+ * the dispatch path under the no-cold-bootstrap policy in AGENTS.md. The listing+ * itself is TTL-cached in `lib/openAiModelsProbeCache.js`, shared with the+ * Providers page's readiness poll.+ */++import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';+import { bareLocalModelId } from '../lib/providerModels.js';+import { probeOpenAiModelsCached } from '../lib/openAiModelsProbeCache.js';++/**+ * The windows this provider's daemon is serving right now, keyed by every+ * spelling the provider could dispatch under, or `null` when there is nothing+ * observed.+ *+ * Both spellings are emitted on purpose: the listing keys by the daemon's bare+ * id, while `resolveEffectiveModel` hands downstream code whatever the provider+ * record says — which for an OpenCode wrapper is the `<kind>/`-prefixed form. A+ * map keyed on only one of the two resolves for half the providers and silently+ * answers "unknown" for the rest.+ *+ * @param {object} provider — a RAW provider record (endpoint + envVars intact)+ * @param {{probe?: Function}} [deps]+ * @returns {Promise<Record<string, number>|null>}+ */+export async function observedContextWindows(provider, deps = {}) {+ const runtime = localRuntimeForProvider(provider);+ // Not daemon-backed: a cloud endpoint is somebody else's install to probe,+ // and its catalog windows already arrive through model refresh.+ if (!runtime) return null;++ const probe = deps.probe || probeOpenAiModelsCached;+ const result = await probe(runtime.endpoint, provider?.apiKey || '').catch(() => null);+ // The probe already rejects anything that is not a positive integer, so what+ // arrives is either usable or absent.+ const served = result?.contextWindows;+ if (!served || Object.keys(served).length === 0) return null;++ const windows = { ...served };+ // Alias each provider-listed spelling onto the window its bare form resolves.+ const offered = [provider?.defaultModel, ...(Array.isArray(provider?.models) ? provider.models : [])];+ for (const model of offered) {+ if (typeof model !== 'string' || windows[model]) continue;+ const bare = bareLocalModelId(model, runtime.kind);+ if (bare && windows[bare]) windows[model] = windows[bare];+ }+ return windows;+}++/**+ * `provider` with its daemon's live windows folded into `modelContextWindows`,+ * for a caller about to ask a context question about it.+ *+ * Returns the SAME object when there is nothing observed, so the no-daemon and+ * daemon-down paths allocate nothing and compare identically. The copy is+ * in-memory only — see this module's header for why it is never persisted.+ *+ * Observation WINS over a stored catalog entry for the same id: the stored+ * number is whatever a refresh recorded whenever the user last pressed it,+ * while the probe describes the process that will serve this very request. An+ * explicit `provider.contextWindow` still outranks both, because+ * `knownContextWindow` prefers it — a number the user typed is a deliberate+ * override, not a stale guess.+ *+ * @param {object} provider+ * @param {{probe?: Function}} [deps]+ * @returns {Promise<object>}+ */+export async function withObservedContextWindows(provider, deps = {}) {+ const observed = await observedContextWindows(provider, deps);+ if (!observed) return provider;+ return { ...provider, modelContextWindows: { ...provider?.modelContextWindows, ...observed } };+}diff --git a/server/services/observedContextWindows.test.js b/server/services/observedContextWindows.test.jsnew file mode 100644index 0000000000..23c0ecec0b--- /dev/null+++ b/server/services/observedContextWindows.test.js@@ -0,0 +1,158 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import * as fetchWithTimeoutModule from '../lib/fetchWithTimeout.js';+import { contextWindowRejection, knownContextWindow } from '../lib/aiToolkit/providerStatus.js';+import { resetOpenAiModelsProbeCache } from '../lib/openAiModelsProbeCache.js';+import { observedContextWindows, withObservedContextWindows } from './observedContextWindows.js';++// The shipped vLLM wrapper, which is exactly the record that carried no window+// at all: seeded by migration with no `contextWindow` and no+// `modelContextWindows`.+const vllmProvider = (overrides = {}) => ({+ id: 'opencode-vllm',+ name: 'OpenCode vLLM',+ type: 'cli',+ command: 'opencode',+ endpoint: 'http://127.0.0.1:18020/v1',+ defaultModel: 'qwen3.8-27b',+ models: ['qwen3.8-27b'],+ vllmBacked: true,+ ...overrides,+});++const listing = (contextWindows) => async () => ({+ reachable: true,+ models: Object.keys(contextWindows),+ contextWindows,+ error: null,+});++beforeEach(() => {+ resetOpenAiModelsProbeCache();+});++afterEach(() => {+ vi.restoreAllMocks();+ resetOpenAiModelsProbeCache();+});++describe('observedContextWindows', () => {+ it('reads the served window off a daemon-backed provider\'s /v1/models', async () => {+ const probe = vi.fn(listing({ 'qwen3.8-27b': 32768 }));++ await expect(observedContextWindows(vllmProvider(), { probe })).resolves.toEqual({ 'qwen3.8-27b': 32768 });+ expect(probe).toHaveBeenCalledWith('http://127.0.0.1:18020/v1', '');+ });++ it('aliases the provider\'s own spelling onto the daemon\'s bare id', async () => {+ // An OpenCode wrapper offers `llama/dflash`; the daemon lists `dflash`. A+ // map keyed on only one of the two answers "unknown" for every dispatch,+ // because `resolveEffectiveModel` hands downstream code the record's+ // spelling.+ const provider = {+ id: 'opencode-llama-tui',+ type: 'tui',+ command: 'opencode',+ endpoint: 'http://127.0.0.1:5568/v1',+ defaultModel: 'llama/dflash',+ models: ['llama/dflash'],+ llamaBacked: true,+ };++ await expect(observedContextWindows(provider, { probe: listing({ dflash: 8192 }) }))+ .resolves.toEqual({ dflash: 8192, 'llama/dflash': 8192 });+ });++ it('observes nothing for a provider that is not daemon-backed', async () => {+ const probe = vi.fn(listing({ 'claude-sonnet-5': 1_000_000 }));+ const remote = { id: 'anthropic', type: 'api', endpoint: 'https://api.anthropic.com/v1', models: [] };++ await expect(observedContextWindows(remote, { probe })).resolves.toBeNull();+ // An external endpoint is somebody else's install — PortOS must not poll it+ // from the dispatch path.+ expect(probe).not.toHaveBeenCalled();+ });++ it('observes nothing when the daemon is down, unreadable, or silent about windows', async () => {+ const unreachable = async () => ({ reachable: false, models: null, contextWindows: null, error: 'ECONNREFUSED' });+ await expect(observedContextWindows(vllmProvider(), { probe: unreachable })).resolves.toBeNull();++ const unlistable = async () => ({ reachable: true, models: null, contextWindows: null, error: 'authentication required' });+ await expect(observedContextWindows(vllmProvider(), { probe: unlistable })).resolves.toBeNull();++ // Up, listing fine, declaring no window — `{}` is "nothing declared one",+ // which must stay "unknown" rather than becoming a zero-token ceiling.+ await expect(observedContextWindows(vllmProvider(), { probe: listing({}) })).resolves.toBeNull();+ });++ it('observes nothing when the probe throws', async () => {+ const probe = async () => { throw new Error('socket hang up'); };+ await expect(observedContextWindows(vllmProvider(), { probe })).resolves.toBeNull();+ });+});++describe('withObservedContextWindows', () => {+ it('folds the live window into modelContextWindows without touching the record', async () => {+ const provider = vllmProvider();+ const decorated = await withObservedContextWindows(provider, { probe: listing({ 'qwen3.8-27b': 32768 }) });++ expect(decorated.modelContextWindows).toEqual({ 'qwen3.8-27b': 32768 });+ // The stored record is observed runtime state's source, never its target —+ // a user editing this provider must not find a probe's number in it.+ expect(provider.modelContextWindows).toBeUndefined();+ });++ it('lets the live window win over a stale stored one, and keeps the rest', async () => {+ // The stored number is whatever a refresh recorded whenever the user last+ // pressed it; the probe describes the process about to serve this request.+ const provider = vllmProvider({ modelContextWindows: { 'qwen3.8-27b': 131072, other: 4096 } });+ const decorated = await withObservedContextWindows(provider, { probe: listing({ 'qwen3.8-27b': 32768 }) });++ expect(decorated.modelContextWindows).toEqual({ 'qwen3.8-27b': 32768, other: 4096 });+ });++ it('returns the SAME provider when there is nothing observed', async () => {+ const provider = vllmProvider();+ const unreachable = async () => ({ reachable: false, models: null, contextWindows: null, error: 'ECONNREFUSED' });++ // Identity, not just equality: an install whose daemon is down must route+ // through exactly the record it always did.+ await expect(withObservedContextWindows(provider, { probe: unreachable })).resolves.toBe(provider);+ });+});++// The end-to-end contract #7441 asked for: a `/v1/models` body carrying+// `max_model_len` must reach `knownContextWindow` for a `vllmBacked` provider,+// through the real probe rather than a stubbed one.+describe('a vLLM listing resolves all the way through knownContextWindow', () => {+ const servedModels = (body) => vi.spyOn(fetchWithTimeoutModule, 'fetchWithTimeout')+ .mockResolvedValue({ ok: true, status: 200, text: async () => JSON.stringify(body) });++ it('turns max_model_len into a refusal for a prompt that cannot fit', async () => {+ servedModels({ data: [{ id: 'qwen3.8-27b', object: 'model', max_model_len: 32768 }] });++ const provider = await withObservedContextWindows(vllmProvider());++ expect(knownContextWindow(provider, 'qwen3.8-27b')).toBe(32768);+ expect(contextWindowRejection(provider, 'qwen3.8-27b', { requiredContextTokens: 21_000 })).toBeNull();+ expect(contextWindowRejection(provider, 'qwen3.8-27b', { requiredContextTokens: 60_000 }))+ .toMatch(/32768-token context is below the 60000-token request budget/);+ });++ it('leaves an explicit contextWindow the user set in charge', async () => {+ servedModels({ data: [{ id: 'qwen3.8-27b', max_model_len: 32768 }] });++ // A number the operator typed is a deliberate override, not a stale guess —+ // `knownContextWindow` prefers it, and observing must not change that.+ const provider = await withObservedContextWindows(vllmProvider({ contextWindow: 16_384 }));+ expect(knownContextWindow(provider, 'qwen3.8-27b')).toBe(16_384);+ });++ it('stays unknown when the daemon declares no window', async () => {+ servedModels({ data: [{ id: 'qwen3.8-27b', object: 'model' }] });++ const provider = await withObservedContextWindows(vllmProvider());+ expect(knownContextWindow(provider, 'qwen3.8-27b')).toBeNull();+ // Unknown is "no constraint" — a request of any size still routes.+ expect(contextWindowRejection(provider, 'qwen3.8-27b', { requiredContextTokens: 1_000_000 })).toBeNull();+ });+});diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex b35b753188..1c6c6cbcc6 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -39,6 +39,7 @@ import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { analyzeError, ERROR_CATEGORIES, isRunCanceledError } 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 { getAIToolkitInstance } from '../lib/aiToolkitState.js';import { createSingleFlight } from '../lib/singleFlight.js';import { extractJson } from '../lib/jsonExtract.js';@@ -65,6 +66,31 @@ function loadAutoFixer() {return autoFixerLoadPromise;}+// Deferred for the same reason as loadAutoFixer above: `observedContextWindows.js`+// reaches `lib/localProviderRuntime.js` and the endpoint probe, which+// promptRunner.js itself never needs, and ~160 suites only build or classify a+// run. A static edge instantiated that subtree in every one of them and pushed+// the server suite past its import budget (see "Import scoping" in+// server/AGENTS.md).+let observedContextWindowsLoadPromise;+function loadObservedContextWindows() {+ if (!observedContextWindowsLoadPromise) {+ observedContextWindowsLoadPromise = import('./observedContextWindows.js').catch((err) => {+ observedContextWindowsLoadPromise = null;+ throw err;+ });+ }+ return observedContextWindowsLoadPromise;+}++// The category an oversized prompt already carries everywhere else in PortOS —+// `agentErrorAnalysis.js` extracts it from a failed agent's output and+// `codexTurn.js` maps Codex's `contextWindowExceeded` tag to it. It is a plain+// string rather than an `ERROR_CATEGORIES` member on purpose: the toolkit's+// enum is for provider-health categories, and this one is REQUEST-specific+// (`providerCooldown.isSchemaTypeCategory` covers it, so it never benches).+const CONTEXT_LENGTH_CATEGORY = 'context-length';+export const DEFAULT_TIMEOUT_MS = 300000;// Grace window past the runner's own API timeout before promptRunner's backstop// timer fires. Lets executeApiRun's internal timeout win (aborting + finalizing@@ -1219,6 +1245,64 @@ function stripFallbackContext(err) {return err;}+/**+ * Refuse a prompt that provably cannot fit the provider about to run it.+ *+ * Before #7441 the context check ran ONLY inside `getFallbackProvider`, so it+ * judged the candidates a failure had already escalated to and never the+ * provider on the happy path — see `services/observedContextWindows.js` for the+ * stall that cost.+ *+ * Four rules, all deliberate:+ *+ * - An UNKNOWN window is not a rejection. `contextWindowRejection` answers+ * `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.+ * - 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+ * (`providerCooldown.isSchemaTypeCategory`), so it never benches a server+ * that is perfectly healthy for smaller prompts, and `autoFixer` already+ * knows its tier. It carries `effectiveProvider`, so the cascade in+ * `runPromptThroughProvider` routes it to a fallback with a wider window+ * (Tier 3, which applies this same rule to every candidate). A pinned+ * (`allowFallback: false`) caller gets the message in milliseconds instead+ * of the ten-minute stall — which is the whole point.+ * - It judges the REQUESTED provider, ahead of `createRun`'s proactive swap.+ * A provider that swap lands on was already asked the same question by+ * `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) {+ const required = Number(requestCapabilities?.requiredContextTokens);+ if (!Number.isFinite(required) || required <= 0) return;++ const { withObservedContextWindows } = await loadObservedContextWindows();+ const observed = await withObservedContextWindows(provider);+ // `reason` already names both numbers, which is what the operator needs to+ // decide between a smaller prompt and a wider provider — so it IS the+ // message rather than being re-worded beside it.+ const reason = contextWindowRejection(observed, model, requestCapabilities);+ if (!reason) return;++ const err = new Error(`${provider.name || provider.id}${model ? ` (${model})` : ''}: ${reason}`);+ // 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}`);+ throw err;+}+/*** Inner helper: execute one attempt against `rawArgs.provider`. Returns* { text, runId, model } on success. On failure, throws an Error with@@ -1275,6 +1359,13 @@ async function executeProviderRunOnce({// string-truthy gate so an empty override falls back to process.cwd().const effectiveCwd = (typeof cwdOverride === 'string' && cwdOverride) ? cwdOverride : process.cwd();+ // Built here rather than inside the createRun branch below because the+ // 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 });+ await assertRequestFitsContext(effectiveProvider, effectiveModel, requestCapabilities);+// Some call sites (stageRunner, loops) create the run themselves so// they can log the runId before the LLM call starts. When provided,// reuse it. Otherwise create one here so callers always get a runId@@ -1298,7 +1389,7 @@ async function executeProviderRunOnce({source,workspacePath: effectiveCwd,effort,- requestCapabilities: buildRequestCapabilities({ prompt, screenshots, outputReserveTokens, callerPolicy }),+ requestCapabilities,allowFallback,});runId = runResult.runId;diff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.jsindex 460e1c61a8..0a1e08abb5 100644--- a/server/services/promptRunner.test.js+++ b/server/services/promptRunner.test.js@@ -61,12 +61,22 @@ vi.mock('../lib/aiToolkitState.js', () => ({getAIToolkitInstance: vi.fn().mockReturnValue(null),}));+// The pre-dispatch context gate reads the daemon's live `/v1/models` through+// this module (lazily). Mocked so the suite can drive "the endpoint says 32K"+// without a daemon; the default is the no-observation answer, which is what+// every provider that is not daemon-backed (and every install whose daemon is+// down) gets — so the whole rest of the suite routes untouched.+vi.mock('./observedContextWindows.js', () => ({+ withObservedContextWindows: vi.fn(async (provider) => provider),+}));+const runner = await import('./runner.js');const tuiRunner = await import('./tuiPromptRunner.js');const executionReadiness = await import('./providerExecutionReadiness.js');const providers = await import('./providers.js');const autoFixer = await import('./autoFixer.js');const toolkitState = await import('../lib/aiToolkitState.js');+const observedWindows = await import('./observedContextWindows.js');const { ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.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');@@ -94,6 +104,7 @@ beforeEach(() => {// Defaults reset for fallback-path mocks too — same staleness concern.providers.getAllProviders.mockResolvedValue({ activeProvider: null, providers: [] });toolkitState.getAIToolkitInstance.mockReturnValue(null);+ observedWindows.withObservedContextWindows.mockImplementation(async (provider) => provider);});describe('promptRunner — happy paths', () => {@@ -2357,3 +2368,106 @@ describe('creative IP-latitude clause', () => {expect(runner.createRun.mock.calls[0][0].prompt).toContain(CREATIVE_LATITUDE_HEADING);});});++// ── Pre-dispatch context gate (#7441) ────────────────────────────────────────+// A local daemon accepts an oversized request, emits its banner, then produces+// nothing until the wall-clock timeout fires. Refusing up front is only correct+// if it fires ONLY on a known window, so both the refusal and the two+// unknown-window regressions live here.+describe('promptRunner — context gate on the requested provider', () => {+ // ~13 tokens of prompt + the 8000-token default output reserve, against a+ // daemon whose listing declared 4096 — a request that provably cannot fit.+ const vllmCli = () => cliProvider({+ id: 'opencode-vllm',+ name: 'OpenCode vLLM',+ defaultModel: 'qwen3.8-27b',+ models: ['qwen3.8-27b'],+ vllmBacked: true,+ endpoint: 'http://127.0.0.1:18020/v1',+ });+ const servingWindow = (tokens) => async (provider) => ({+ ...provider,+ modelContextWindows: { 'qwen3.8-27b': tokens },+ });++ // Tier-3 harness: a wider fallback the cascade can route to.+ function mockToolkitWithFallbackFor(primary) {+ const fallback = apiProvider({ id: 'fallback-api', name: 'Fallback API', defaultModel: 'fb-model' });+ const markUnavailable = vi.fn().mockResolvedValue(undefined);+ toolkitState.getAIToolkitInstance.mockReturnValue({+ services: {+ providerStatus: {+ isAvailable: vi.fn().mockReturnValue(true),+ markUnavailable,+ markUsageLimit: vi.fn().mockResolvedValue(undefined),+ getFallbackProvider: vi.fn().mockReturnValue({ provider: fallback, source: 'provider' }),+ },+ },+ });+ providers.getAllProviders.mockResolvedValue({ activeProvider: null, providers: [primary, fallback] });+ return { markUnavailable };+ }++ it('refuses before dispatch, naming both token counts, for a pinned caller', async () => {+ const status = mockToolkitWithFallbackFor(vllmCli());+ observedWindows.withObservedContextWindows.mockImplementation(servingWindow(4096));++ const rejection = await runPromptThroughProvider({+ provider: vllmCli(),+ prompt: 'a prompt that does not fit',+ source: 'test',+ allowFallback: false,+ }).catch((err) => err);++ // A pin opts out of ROUTING, not of health reporting — but this failure is+ // the REQUEST's, not the provider's, so the pinned path must not bench a+ // daemon that still serves smaller prompts perfectly well.+ expect(status.markUnavailable).not.toHaveBeenCalled();++ // 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).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();+ });++ it('routes an oversized request to a fallback instead of benching a healthy daemon', async () => {+ const status = mockToolkitWithFallbackFor(vllmCli());+ observedWindows.withObservedContextWindows.mockImplementation(async (provider) => (+ provider.id === 'opencode-vllm' ? (await servingWindow(4096)(provider)) : provider+ ));+ runner.executeApiRun.mockImplementation(async ({ onComplete }) => onComplete({ success: true }));++ const out = await runPromptThroughProvider({+ provider: vllmCli(),+ prompt: 'a prompt that does not fit',+ source: 'test',+ });++ expect(out.usedFallback).toBe(true);+ expect(out.provider.id).toBe('fallback-api');+ // The endpoint is healthy — a smaller prompt still works there — so this+ // must not take it offline for every other caller.+ expect(status.markUnavailable).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+ // meaning "no constraint", never "refuse".+ runner.executeCliRun.mockImplementation(async ({ onComplete }) => onComplete({ success: true }));++ await runPromptThroughProvider({ provider: vllmCli(), prompt: 'x'.repeat(200_000), source: 'test' });+ expect(runner.executeCliRun).toHaveBeenCalledTimes(1);+ });++ it('dispatches when the known window is wide enough', async () => {+ observedWindows.withObservedContextWindows.mockImplementation(servingWindow(131_072));+ runner.executeCliRun.mockImplementation(async ({ onComplete }) => onComplete({ success: true }));++ await runPromptThroughProvider({ provider: vllmCli(), prompt: 'small', source: 'test' });+ expect(runner.executeCliRun).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/services/providerReadiness.js b/server/services/providerReadiness.jsindex 9ae59d28a7..3b591962a2 100644--- a/server/services/providerReadiness.js+++ b/server/services/providerReadiness.js@@ -38,29 +38,12 @@import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';import { expandPageToken, getNavPageForPath } from '../lib/navManifest.js';-import { isConfiguredDefaultModel } from '../lib/providerModels.js';-import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';+import { bareLocalModelId } from '../lib/providerModels.js';+import { probeOpenAiModelsCached, resetOpenAiModelsProbeCache } from '../lib/openAiModelsProbeCache.js';import { findCommandOnPath } from '../lib/processEnv.js';import { actionCovers, describeRuntimeSetup, readRuntimeWeights, weightsBlockStart } from './localRuntimeSetup.js';import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';-/**- * Loopback daemons answer (or refuse the connection) in single-digit- * milliseconds, so a short bound keeps a page poll snappy. A host that needs- * longer than this to answer a model listing is not going to serve an agent run- * either, and reporting it as unreachable points at the right fix.- */-const PROBE_TIMEOUT_MS = 2_000;--/**- * Sized just under the Providers page's 20s poll so consecutive polls each get- * a fresh answer (a daemon the user just started must show up on the next tick,- * not two ticks later) while a reload landing on top of a poll still reuses it.- * Within ONE request the promise cache below is what collapses providers that- * share an endpoint.- */-const PROBE_TTL_MS = 15_000;-/*** Same 60s TTL and reasoning as `providerRuntimeInstaller.js`'s status cache:* availability changes only when someone installs or removes a binary, and@@ -77,53 +60,12 @@ const BINARY_TTL_MS = 60_000;*/const WEIGHTS_TTL_MS = 60_000;-// endpoint + key → { at, promise } — the PROMISE, not the settled value, so N-// providers sharing one endpoint in the same batch share one socket instead of-// all missing a not-yet-written cache entry at once. The key is part of the-// cache key because two providers can point at one authenticated endpoint with-// different credentials, and one of them getting the other's 401 would be a-// false "not running".-const probeCache = new Map();// command → { at, path }const binaryCache = new Map();// runtime kind → { at, promise } — the local model cache behind a daemon that// is NOT running, which is the only time PortOS cannot ask `/v1/models`.const weightsCache = new Map();-/**- * Ask an OpenAI-compatible endpoint what it serves. `llamaServerManager` runs the- * same probe against the same daemons, so the request shape lives in one lib.- * @returns {Promise<{reachable:boolean, models:string[]|null, error:string|null}>}- * `models: null` means reachable but the listing could not be read — distinct- * from `[]`, a server that is up with nothing loaded.- */-const probeEndpoint = (endpoint, apiKey = '') =>- probeOpenAiModels(endpoint, { timeoutMs: PROBE_TIMEOUT_MS, apiKey });--/** TTL-cached endpoint probe, shared across requests — see PROBE_TTL_MS. */-function probeEndpointCached(endpoint, apiKey = '') {- const now = Date.now();- const cacheKey = `${endpoint}-${apiKey}`;- const cached = probeCache.get(cacheKey);- if (cached && now - cached.at < PROBE_TTL_MS) return cached.promise;- // Sweep while we are here: entries are keyed by endpoint, and an edited or- // deleted provider would otherwise leave its old endpoint behind forever.- for (const [key, entry] of probeCache) {- if (now - entry.at >= PROBE_TTL_MS) probeCache.delete(key);- }- // Written BEFORE the await so concurrent callers join this probe. A rejected- // probe would poison the entry for its TTL, so drop it on failure —- // `probeEndpoint` resolves for every expected failure, making this the- // unexpected-throw path only.- const promise = probeEndpoint(endpoint, apiKey).catch((err) => {- probeCache.delete(cacheKey);- throw err;- });- probeCache.set(cacheKey, { at: now, promise });- return promise;-}-/*** What a runtime's own model cache holds, for the runtimes that have one PortOS* can read without starting them (today: MTPLX).@@ -167,25 +109,12 @@ function findCommandCached(command) {return path;}-/**- * One model id as the daemon's own listing spells it: trimmed, with any OpenCode- * `<namespace>/` prefix stripped, since that prefix addresses the OpenCode- * provider entry and never reaches the daemon's model list. `null` for anything- * that does not name a model (blank, non-string, or a "use the CLI's own- * default" sentinel).- */-function bareModelId(model, kind) {- if (typeof model !== 'string' || model.trim() === '' || isConfiguredDefaultModel(model)) return null;- const trimmed = model.trim();- return trimmed.startsWith(`${kind}/`) ? trimmed.slice(kind.length + 1) : trimmed;-}-/*** The model id the endpoint would be asked for — the provider's default.* Returns null when the provider selects no specific model.*/export function servedModelId(provider, kind) {- return bareModelId(provider?.defaultModel, kind);+ return bareLocalModelId(provider?.defaultModel, kind);}/**@@ -202,7 +131,7 @@ export function servedModelId(provider, kind) {function offeredModelIds(provider, kind) {const pinned = servedModelId(provider, kind);const ids = (Array.isArray(provider?.models) ? provider.models : [])- .map((model) => bareModelId(model, kind))+ .map((model) => bareLocalModelId(model, kind)).filter((id) => id !== null && id !== pinned);return [...new Set(ids)];}@@ -451,7 +380,7 @@ export async function getProviderReadiness(provider, deps = {}) {if (!runtime) return null;const findCommand = deps.findCommand || findCommandCached;- const probe = deps.probe || probeEndpointCached;+ const probe = deps.probe || probeOpenAiModelsCached;// The wrapper's own key: a vLLM container is started behind `VLLM_API_KEY`// and 401s an unauthenticated `/v1/models`, which would leave the model check@@ -489,7 +418,7 @@ export async function getProviderReadiness(provider, deps = {}) {serverCheck(runtime, { installed, result, setup, weights }),];const wanted = servedModelId(provider, runtime.kind);- // `probeEndpoint` returns `models: null` on every unreachable path, so this+ // The probe returns `models: null` on every unreachable path, so this// needs no second reachability test.if (wanted) checks.push(modelCheck(runtime, wanted, result.models, result.error, { weights, setup }));const offered = offeredModelIds(provider, runtime.kind);@@ -536,7 +465,7 @@ export async function getProviderReadinessMap(providers, deps = {}) {// the whole batch — including when the caller injects its own probe, which// would otherwise bypass the module-level caches that normally collapse them.const findCommand = memoize(deps.findCommand || findCommandCached);- const probe = memoize(deps.probe || probeEndpointCached);+ const probe = memoize(deps.probe || probeOpenAiModelsCached);// Same reasoning as the two above: one `mtplx models` subprocess per batch,// not one per provider pointed at the same runtime.const readWeights = memoize(deps.readWeights || readWeightsStateCached);@@ -572,7 +501,11 @@ function memoize(fn) {* which change exactly what these caches remember.*/export function resetProviderReadinessCache() {- probeCache.clear();+ // The endpoint listing cache lives in `lib/openAiModelsProbeCache.js` — the+ // dispatch path's context gate shares it, and a daemon relaunched at a+ // different context size must invalidate BOTH readers or a run is gated on+ // the old window.+ resetOpenAiModelsProbeCache();binaryCache.clear();weightsCache.clear();}