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

budget prompts against the window a local daemon is serving, not a stale catalog entry (#7447)

[._.]/ Adam Eivy058c385882a0
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsx
index 67b7b821aa..84fec0e9f6 100644
--- a/client/src/components/providers/ProviderCard.jsx
+++ b/client/src/components/providers/ProviderCard.jsx
@@ -30,6 +30,7 @@ import {
isProviderHardwareCompatible,
isTuiProvider,
isLaunchableTuiProvider,
+ mergeObservedContextWindows,
providerTypeClass,
resolveModelContextWindow,
supportsModelRefresh,
@@ -507,7 +508,16 @@ export default function ProviderCard({
// a blanket 128K guess, and printing that bare made a 1M-context
// model look like PortOS had capped it. A reported window prints
// plain; a guess says so and names the way to replace it.
- const { tokens, source } = resolveModelContextWindow(provider, provider.defaultModel);
+ //
+ // A local daemon's LIVE window (off the readiness poll) is folded in
+ // first, so the meter agrees with what the dispatch gate enforces —
+ // a card reading 128K beside an endpoint serving 32K promised a
+ // budget no run could ever spend. Down or silent → `null`, and the
+ // ladder resolves exactly as it did before.
+ const { tokens, source } = resolveModelContextWindow(
+ mergeObservedContextWindows(provider, daemonReadiness?.contextWindows),
+ provider.defaultModel
+ );
const windowLabel = formatContextLength(tokens);
if (!windowLabel) return null;
// Only offer Refresh Models when this card HAS that button —
diff --git a/client/src/components/providers/ProviderCard.test.jsx b/client/src/components/providers/ProviderCard.test.jsx
index 39fe612bbf..10a2d14d11 100644
--- a/client/src/components/providers/ProviderCard.test.jsx
+++ b/client/src/components/providers/ProviderCard.test.jsx
@@ -16,10 +16,11 @@ const wrapper = (overrides = {}) => ({
...overrides,
});
-const renderCard = (provider) => render(
+const renderCard = (provider, daemonReadiness = null) => render(
<MemoryRouter>
<ProviderCard
provider={provider}
+ daemonReadiness={daemonReadiness}
// `providerCardState` returns `missing` on every path, so the fixture
// carries it too — the card reads it without a defensive guard.
cardState={{ state: PROVIDER_CARD_STATE.READY, missing: [] }}
@@ -63,6 +64,36 @@ describe('ProviderCard context window', () => {
expect(screen.getByText('override')).toBeTruthy();
expect(screen.queryByText(/assumed/)).toBeNull();
});
+
+ // #7447: the meter must show the number the DISPATCH GATE would enforce. A
+ // card reading 128K beside an endpoint serving 32K promised a budget no run
+ // could ever spend — the chunker built the oversized prompt and the gate
+ // refused it.
+ it('shows the window the daemon is serving right now, over a stale catalog entry', () => {
+ renderCard(
+ wrapper({ modelContextWindows: { 'stealth/ox-alpha': 128_000 } }),
+ { contextWindows: { 'stealth/ox-alpha': 32_768 } },
+ );
+ expect(screen.getByText('32K ctx')).toBeTruthy();
+ expect(screen.queryByText('128K ctx')).toBeNull();
+ expect(screen.queryByText(/assumed/)).toBeNull();
+ });
+
+ it('still lets a hand-entered window beat the live observation', () => {
+ renderCard(
+ wrapper({ contextWindow: 250_000 }),
+ { contextWindows: { 'stealth/ox-alpha': 32_768 } },
+ );
+ expect(screen.getByText('250K ctx')).toBeTruthy();
+ expect(screen.getByText('override')).toBeTruthy();
+ });
+
+ it('renders exactly as before when the daemon reported no window', () => {
+ // Down, silent, or not daemon-backed at all — unknown stays unknown.
+ renderCard(wrapper({ canRefreshModels: true }), { contextWindows: null });
+ expect(screen.getByText('128K ctx')).toBeTruthy();
+ expect(screen.getByText(/assumed — Refresh Models to read the real one/)).toBeTruthy();
+ });
});
describe('ProviderCard fleet identity', () => {
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsx
index b943015265..5e16c0cce6 100644
--- a/client/src/components/providers/ProviderForm.jsx
+++ b/client/src/components/providers/ProviderForm.jsx
@@ -3,7 +3,7 @@ import { useState } from 'react';
import { AlertTriangle, Braces, Cpu, Plug, SlidersHorizontal } from 'lucide-react';
import toast from '../ui/Toast';
import * as api from '../../services/api';
-import { filterHardwareCompatibleProviderModels, filterGenerationModels, isEmbeddingModel, isProviderHardwareCompatible, isProviderModelHardwareCompatible, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, isProcessProvider, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor, isCodexProvider } from '../../utils/providers';
+import { filterHardwareCompatibleProviderModels, filterGenerationModels, isEmbeddingModel, isProviderHardwareCompatible, isProviderModelHardwareCompatible, mergeModelLists, configuredDefaultIn, localBackendForProvider, mergeObservedContextWindows, modelOptionLabel, isProcessProvider, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor, isCodexProvider } from '../../utils/providers';
import Banner from '../ui/Banner';
import {
formatDurationMs,
@@ -48,7 +48,7 @@ const PROVIDER_FIELD_RANGES = {
const rangeMessage = (label, { min, max }, unit = '') =>
`${label} must be between ${formatCount(min)} and ${formatCount(max)}${unit ? ` ${unit}` : ''}`;
-export default function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders = [], localModels = { ollama: [], lmstudio: [], ctxById: {}, hardwareCompatibilityByBackend: {} }, runnerAllowedCommands = null }) {
+export default function ProviderForm({ provider, daemonReadiness = null, onClose, onSave, onEditProvider, allProviders = [], localModels = { ollama: [], lmstudio: [], ctxById: {}, hardwareCompatibilityByBackend: {} }, runnerAllowedCommands = null }) {
const [formData, setFormData] = useState({
name: provider?.name || '',
type: provider?.type || 'cli',
@@ -115,7 +115,12 @@ export default function ProviderForm({ provider, onClose, onSave, onEditProvider
// The server publishes compatibility for both the provider runtime and any
// explicitly annotated model. Unknown probe results stay in the list; only a
// definitive mismatch is hidden.
- const capabilityProvider = {
+ // The live windows a local daemon is SERVING (off the readiness poll) fold in
+ // here rather than onto `provider`, because this object is derived and shown,
+ // never saved — `modelContextWindows` is not a form field, so an observation
+ // can reach "Budgeter uses …" and the model-option labels without any risk of
+ // a Save writing a running process's window into the record (#7441).
+ const capabilityProvider = mergeObservedContextWindows({
...provider,
...formData,
id: provider?.id,
@@ -124,7 +129,7 @@ export default function ProviderForm({ provider, onClose, onSave, onEditProvider
...provider?.modelHardwareCompatibility,
...liveHardwareFor(formData),
},
- };
+ }, daemonReadiness?.contextWindows);
const availableModels = filterHardwareCompatibleProviderModels(
filterGenerationModels(mergedModels),
capabilityProvider,
diff --git a/client/src/components/providers/ProviderForm.test.jsx b/client/src/components/providers/ProviderForm.test.jsx
index 6669933678..ca87592675 100644
--- a/client/src/components/providers/ProviderForm.test.jsx
+++ b/client/src/components/providers/ProviderForm.test.jsx
@@ -99,3 +99,39 @@ describe('ProviderForm', () => {
});
});
+
+// #7447: this editor is the surface that literally names the budgeter
+// ("Budgeter uses N"), so it must not contradict the card beside it — or the
+// server that will enforce the number.
+describe('ProviderForm planned context window', () => {
+ const daemonProvider = {
+ id: 'opencode-vllm',
+ name: 'OpenCode vLLM',
+ type: 'cli',
+ command: 'opencode',
+ endpoint: 'http://127.0.0.1:18020/v1',
+ models: ['qwen3.8-27b'],
+ defaultModel: 'qwen3.8-27b',
+ // What a model refresh recorded whenever the user last pressed it.
+ modelContextWindows: { 'qwen3.8-27b': 128000 },
+ enabled: true,
+ };
+
+ const plannedContext = () => {
+ switchTab('Generation');
+ return screen.getByText(/Budgeter uses/).textContent;
+ };
+
+ it('names the window the daemon is serving now, not the stale catalog one', () => {
+ renderForm({
+ provider: daemonProvider,
+ daemonReadiness: { contextWindows: { 'qwen3.8-27b': 32768 } },
+ });
+ expect(plannedContext()).toBe('Budgeter uses 32K ctx');
+ });
+
+ it('falls back to the recorded catalog window when the daemon says nothing', () => {
+ renderForm({ provider: daemonProvider, daemonReadiness: { contextWindows: null } });
+ expect(plannedContext()).toBe('Budgeter uses 128K ctx');
+ });
+});
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 1b5ef5556e..5ca8a12b65 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -1117,6 +1117,7 @@ export default function AIProviders() {
<ProviderForm
key={editingProvider?.id || 'new'}
provider={editingProvider}
+ daemonReadiness={editingProvider?.id ? readiness[editingProvider.id] : null}
allProviders={providers}
localModels={localModels}
runnerAllowedCommands={runnerAllowedCommands}
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 8b5dfa2244..a3c9864b94 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -61,7 +61,7 @@ is where each shared table is re-exported from its `server/lib` leaf.
| `providerModels` | Which MODEL and EFFORT a run resolves to, and what a picker may list. The configured-default sentinels (`CODEX_CONFIGURED_DEFAULT` …, `isConfiguredDefaultModel`, `configuredDefaultIn` — so a picker can render an option matching a sentinel-valued tier instead of a blank select) and `filterSelectableModels`; the per-CLI effort ladders, `effortLevelsForProvider`, `resolveCliEffort` (what a stored effort actually runs as, so the picker can name a clamped level), `effortSurvivingModel` and `seedModelEffort`; the Antigravity base-model ↔ effort-suffix split (`splitAntigravityModel`, `antigravityBaseModels`, `antigravityModelEffortLevels`, `withStaleAntigravityPin`); the account-aware option list (`providerModelList`, `resolveProviderModelOptions`, `effortAwareModelOptions`, `MODEL_SOURCE` — the one place a Codex-subscription account catalog enters a picker); `effectiveModelFor`; `mergeModelLists` / `mergeProviderUpdate`; and `generationControlsFor` (which temperature / top-p / thinking controls a provider forwards at all). The sentinels, effort ladders and the Antigravity split are re-exported from the pure leaf `server/lib/providerModels.js`; `effortLevelsForProvider` / `resolveCliEffort` delegate to the server's and add the ladder a sanitized provider inventory publishes, clamped through the server's `clampEffortToLadder`. The generation-control tables still mirror `server/lib/opencodeConfig.js`. |
| `providerSelection` | Which providers and models a picker may OFFER on this install: `isProviderHardwareCompatible` / `isProviderModelHardwareCompatible` / `filterHardwareCompatibleProviderModels` (server-annotated, fail-open), `selectableProviders` (the single rule `ProviderModelSelector` renders from), `filterRunnableProviders` (agent jobs need a CLI/TUI harness), the fail-closed tool-free local policy (`TOOL_FREE_LOCAL_PROVIDER_IDS`, `TOOL_FREE_LOCAL_TEXT_CAPABILITIES`, `isToolFreeLocalProvider`, `isToolFreeLocalModel`, `toolFreeLocalSelectionPolicy`) used by security-sensitive pickers, and the pr-reviewer postures (`PUBLIC_REVIEW_NO_TOOL_POSTURE` / `PUBLIC_REVIEW_ACTIONS_POSTURE`, `supportsPublicReviewPosture`, `enforcesPublicReviewPosture`, `publicReviewSelectionPolicy` — mirror of `server/lib/agentExecutionProfiles.js`: a pipeline stage names a POSTURE, the server publishes each provider's `publicReviewPostures` and `publicReviewEnforcedPostures` on `GET /api/providers`, and the picker offers exactly the providers this install can run the stage on, so no vendor is named on either side). Also the caller EXECUTION-MODE picker rule (`callerModeList`, `providerModeSelectionPolicy`) over `server/lib/callerModePolicy.js` — the server enforces the policy on the pin, on `activeProvider` inheritance and on every fallback candidate; this only lets a picker SHOW the rule, keeping an ineligible saved value visible-but-disabled instead of hidden or silently replaced — read off `CALLER_MODE_POLICIES` in that pure leaf, so it cannot drift). |
| `localModelHeuristics` | What an untyped LOCAL model can do, judged from its id: `isEmbeddingModel` / `isVisionModel` / `isToolUseModel` (re-exported from the pure leaf `server/lib/localModelHeuristics.js` — one regex per family; a model card's explicit capability metadata outranks the id regex), `isVisionCapableCliProvider`, `filterGenerationModels` (sentinels and embedding-only models dropped), `visionLocalModelFilter` and `localToolUseHint` / `withToolUseOptionLabel` (unioned with the server's authoritative per-provider capability maps from `useVisionModelIds` / `useToolUseModelIds`; tool-use is an annotation plus warning, never a filter), and `modelCapabilityInfo` (capability badges for a selected model without over-sharing a local runtime's answer with another provider). |
-| `providerContextWindows` | How large a context window a provider/model gets for planning and where the number came from: the vendor constants and the `KNOWN_MODEL_CONTEXT_WINDOWS` ladder (`knownModelContextWindow`, `knownProviderContextWindow`), `catalogModelContextWindow` (the window the provider's own `/models` catalog reported), `resolveModelContextWindow` → `{ tokens, source }` with `CONTEXT_WINDOW_SOURCE` (`override` / `reported` / `assumed` — the state a card has to label rather than print as fact), `effectiveModelContextWindow`, and `modelOptionLabel` ("id (32K ctx)"). The constants and the known-model / known-provider / catalog rungs are re-exported from the pure leaf `server/lib/providerContextWindows.js`, the same rungs the server's `effectiveContextWindow` budgets with. |
+| `providerContextWindows` | How large a context window a provider/model gets for planning and where the number came from: the vendor constants and the `KNOWN_MODEL_CONTEXT_WINDOWS` ladder (`knownModelContextWindow`, `knownProviderContextWindow`), `catalogModelContextWindow` (the window the provider's own `/models` catalog reported), `resolveModelContextWindow` → `{ tokens, source }` with `CONTEXT_WINDOW_SOURCE` (`override` / `reported` / `assumed` — the state a card has to label rather than print as fact), `effectiveModelContextWindow`, and `modelOptionLabel` ("id (32K ctx)"). The constants and the known-model / known-provider / catalog rungs are re-exported from the pure leaf `server/lib/providerContextWindows.js`, the same rungs the server's `effectiveContextWindow` budgets with — including `mergeObservedContextWindows`, which folds a local daemon's live window (off the readiness payload) onto the catalog rung so the card shows what the dispatch gate enforces. |
| `providerReadiness` | Is a provider READY to run on this install, and why not. `credentialSource` (stored / inherited / env / subscription / none) and `providerCardState(provider, { runtime, status, keySetFor, envVarSet, codexAccount })` + `PROVIDER_CARD_STATE` — ready, benched, blocked on a missing prerequisite (CLI not installed / API key absent / empty credential env var / signed-out ChatGPT account), unknown, or simply switched off. Reads the SERVER's `missingPrerequisites` (published per provider on `GET /api/providers` from `server/lib/providerPrerequisites.js`, the same computation `getFallbackProvider` routes on) and adds only what the browser can see; unknown lookup values mean "not probed", never "missing". Distinct from `ProviderReadiness` / `GET /api/providers/readiness`, which probes the local daemon behind a provider. Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner accept this command? Mirrors only the normalization in `server/cos-runner/allowedCommands.js` (the list arrives as `runnerAllowedCommands` on `GET /api/providers`); returns `null` for "list not fetched" so a failed fetch never renders a warning; pinned by `server/cos-runner/allowedCommands.parity.test.js`. `resolvesOutsidePortosPath` / `providerRuntimeKey` (the key a CLI runtime is published under by `GET /api/providers/runtimes`), `supportsModelRefresh` (`canRefreshModels === true`, the server's own answer) and `codexRoutingAdvisory` (the non-blocking "your `~/.codex/config.toml` re-points Codex" notice — server-only and machine-local, rendered in the UI and nowhere else). |
| `providerAssignments` | Which provider/model a RECORD resolves to, and the option helpers the assignment editors share: `resolveEffectiveProvider` (its pin, else the active provider, plus whether it fell back so a "Default" option can name what it resolves to), `resolveSeriesRunLlm` (mirror of `server/lib/seriesLlmOverride.js`: per-run override → `series.llm` → active provider), `getProviderTimeout`, `providerDisplayName` and `providerModelLabel` (the one "Provider / model" phrasing), and `assignmentProviderOptions` / `assignmentModelOptions` / `assignmentDefaultModel` / `assignmentToolUseState` over the `getAiAssignments` payload shape — shared by the global AI Assignments table and every per-record override drawer so none of them derives the rule differently. |
diff --git a/client/src/utils/providerContextWindows.js b/client/src/utils/providerContextWindows.js
index 6a5c297ad6..6ca78c8dcb 100644
--- a/client/src/utils/providerContextWindows.js
+++ b/client/src/utils/providerContextWindows.js
@@ -4,7 +4,7 @@
* card must label as assumed) — plus the "(32K ctx)" option label built on it.
*
* The rungs — the vendor constants, the known-model table, the per-provider
- * fallback and the catalog read — are re-exported from the pure leaf
+ * fallback, the catalog read and the live-daemon merge — are re-exported from the pure leaf
* `server/lib/providerContextWindows.js`, the same ones the server's
* `effectiveContextWindow` budgets with. `resolveModelContextWindow` is the
* client's own walk over them, because the UI also needs to know WHERE the
@@ -34,6 +34,10 @@ export {
knownModelContextWindow,
knownProviderContextWindow,
catalogModelContextWindow,
+ // Folds a daemon's live `/v1/models` windows (off the readiness payload) onto
+ // the catalog rung, exactly as the server's budgeter does — shared rather than
+ // re-walked so the card cannot rank the observation differently.
+ mergeObservedContextWindows,
} from '../../../server/lib/providerContextWindows.js';
export const isLikelyLargeContextProvider = (provider) => {
diff --git a/docs/API.md b/docs/API.md
index f9c3d743c7..f216221ac3 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -122,7 +122,7 @@ legacy list for local Apps/Dashboard views.
| PUT | `/providers/active` | Set active provider |
| GET | `/providers/runtimes` | Per-runtime install status (`claude`, `codex`, `opencode`, `grok`, `kimi`, `agy`, `cursor-agent`): is the binary runnable here, and can PortOS install it? Booleans and labels only — never resolved filesystem paths. 60s TTL cache. Ollama / LM Studio are absent on purpose — Models → LLMs owns their install. |
| POST | `/providers/runtimes/install?runtime=<id>` | Install one runtime from the installer's fixed table, streaming installer output as SSE. Rejects any id not in the table. |
-| GET | `/providers/readiness` | Requirements checklist per provider backed by a LOCAL daemon (llama.cpp / Ollama / LM Studio / MTPLX), keyed by provider id: is the daemon installed, is it answering at the endpoint THIS provider points at, and is it serving the provider's default model. Each entry also carries `setup` — what the one-click fix below can do about the unmet checks (`null` when nothing is auto-fixable here). Providers with no local dependency are absent from the map. Complements `/providers/runtimes` (which answers "can PortOS run this CLI?"). Booleans, labels, and the provider's own endpoint only — never a resolved binary path. Skips disabled providers; 15s endpoint-probe cache (one probe per distinct endpoint), 60s binary-PATH cache, both dropped by the llama-server start/stop/install routes. |
+| GET | `/providers/readiness` | Requirements checklist per provider backed by a LOCAL daemon (llama.cpp / Ollama / LM Studio / MTPLX), keyed by provider id: is the daemon installed, is it answering at the endpoint THIS provider points at, and is it serving the provider's default model. Each entry also carries `setup` — what the one-click fix below can do about the unmet checks (`null` when nothing is auto-fixable here). Each entry also carries `contextWindows` — what the daemon is SERVING right now, keyed by every spelling the provider could dispatch under, or `null` when it is down or silent about them; the provider card budgets its meter with it so the number matches what the pre-dispatch gate enforces, and it is never written back to the stored provider record. Providers with no local dependency are absent from the map. Complements `/providers/runtimes` (which answers "can PortOS run this CLI?"). Booleans, labels, and the provider's own endpoint only — never a resolved binary path. Skips disabled providers; 15s endpoint-probe cache (one probe per distinct endpoint), 60s binary-PATH cache, both dropped by the llama-server start/stop/install routes. |
| POST | `/providers/readiness/setup?provider=<id>` | Install and/or start the LOCAL DAEMON that provider points at (llama.cpp / Ollama / LM Studio / MTPLX), streaming progress as SSE — the "do it for me" half of `/providers/readiness`, so an unmet requirement is fixed from the card instead of from a vendor setup doc. The request names a PROVIDER only: the runtime kind and endpoint are re-derived server-side from the stored record, so no query value reaches a spawn argument (an optional `runtime=` is cross-checked and 409s on a mismatch). Every command comes from a fixed per-runtime table. Never downloads model weights, never starts llama-server (it needs a checkpoint you choose), and never runs MTPLX's privileged fan-control helper. Single-flight. |
| POST | `/providers/readiness/serve-model?provider=<id>` | Relaunch the local daemon so it answers under the model id THIS provider sends — the other half of the readiness model mismatch. `llama-server` serves one model per process under the `--alias` on its launch line, so the fix keeps the loaded weights and changes only the name; the whole launch line is carried forward and the previous one restored if the relaunch is rejected or never answers. The model id is re-derived server-side from the stored record. 400s for a runtime that has no such label (Ollama / LM Studio / MTPLX name a model after its weights), 409s when PortOS did not start the daemon. |
| GET | `/providers/model-pins` | Stored model pins naming a model their provider no longer lists. A vendor retires an id, the install's catalog refresh picks that up, and every pin still naming it rots silently until a render or a scheduled run dies with a raw vendor error. Answers `{ pins, providers }` — each pin carries where it lives and a deep link, and `providers` carries only the catalogs a stale pin actually names. Covers the Image Gen and render-default settings pins, global and per-app scheduled-task pins, per-record render pins, the Code Review Defaults reviewer pins (the `<reviewer>Model` scalars, the `provider:<id>` entries in `providerModels`, and `goalFidelity.model`), and user-saved CoS task-template pins. A reviewer pin names a BINARY that several provider records front, so it carries `providerIds` and is reported only when EVERY one of them stops listing the model — judging it against one record would call a tier retired that the other still serves. Derived on read, never persisted, so a pin cleared a moment ago is already gone from the answer and one that rotted before this shipped is reported on the first read. Every UNKNOWN case (no pin, empty catalog, unresolved provider) reads as "still listed" — a false "your pin is gone" tells the user to change a setting that works. |
diff --git a/server/lib/README.md b/server/lib/README.md
index 2e5f88712c..d47afcd332 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -225,7 +225,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `harnessOutput.js` | Parsers for what a coding-agent HARNESS prints about itself: `parseHarnessVersion(stdout)` (the one semver run in a `--version` banner, `null` when unparseable), `compareHarnessVersions(a, b)` (the null-guarding wrapper around `versionUtils.js#compareSemver` — `null` when either side is unparseable, so a version that did not parse never reads as "out of date"), `parseHarnessModels(harnessId, stdout)` + `HARNESS_MODEL_PARSER_IDS` (OpenCode's `provider/model` lines and Grok's bulleted list are parsed here; Antigravity and Cursor DELEGATE to `antigravity.js#parseAntigravityModelList` / `aiToolkit/internal/cursor.js#parseCursorModelList`, which the provider-card refresh has used for far longer), `MAX_MODELS`, and `parseNpmLatestVersion`. Pure: the service layer runs the child and hands the captured stdout here, so the vendor output shapes are pinned by table-driven tests instead of by running six real binaries in CI. Model ids come back in the exact spelling `--model` takes — namespaces kept where the vendor keeps them. Consumed by `services/providerRuntimeInstaller.js` and `services/harnesses.js`. |
| `providerGateways.js` | `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (`orcarouter`, `openrouter`, `nvidia-nim`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)`, `gatewayForProvider(config)` → row or null, `isGatewayBackedProvider(config)`, and `attachGatewaySiblingKey(provider, providers)` — the synchronous twin of the toolkit's `withGatewayApiKey` for callers holding an already-loaded (RAW, keyless) collection: a fallback pick armed from such a map executes with its sibling's key instead of going out with no Authorization header. Each row's `id` is simultaneously the OpenCode provider namespace, the `gatewayBacked` marker value, and the id of the sibling `api` record that owns the key — so the sibling lookup is `providers[gateway.id]` and an OrcaRouter key can never satisfy an OpenRouter wrapper. Replaces the `orcarouterBacked` boolean + literal `'orcarouter'` that had been hand-copied across ~15 server and client files (namespace resolution, the OpenCode config builder, both zod schemas, the model-fetcher table, the sibling-key attach, the prerequisite check, and the two "not a local runtime" carve-outs in `cliChildEnv.js`/`localProviderRuntime.js`). Reads the legacy per-gateway boolean FOREVER, so stored records are never rewritten. Distinct from a local runtime (`ollamaBacked`, `vllmBacked`, …): remote, always authenticating, and no thinking toggle. Deliberately mirrored in `aiToolkit/internal/gateways.js` (the vendored toolkit may not import out) — `providerGateways.parity.test.js` fails when the two drift; `client/src/utils/providerGateways.js` re-exports this leaf rather than copying it. Dependency-light: imports nothing. |
| `providerHarnesses.js` | Provider HARNESS identity for the connection graph (#6366) — `PROVIDER_HARNESSES` (one row per agent program PortOS drives: claude/opencode/codex/antigravity/cursor/grok/kimi/pi, each with its supported `modes`, wire `protocol` and the existing `is*Provider` predicate as its matcher), `PROVIDER_HARNESS_IDS`, `harnessById`, `harnessForProvider` (null for an `api` record AND for an unknown harness — use `providerRouteMode` to tell them apart), `harnessSupportsMode`, `ROUTE_MODES`, plus the model-name adapters `toExecutableModelName` / `toCanonicalModelName` (the verified inverse of `prefixOpencodeModel`: a stored alias is canonicalized only when it maps back to the exact stored string, so import never rewrites a saved model by heuristically stripping a prefix). Distinct from `providerVendors.js` (argv-shaped), `providerFamilies.js` (subscription quota) and `providerGateways.js` (hosted backend). Pure leaf — `client/src/utils/providerHarnesses.js` names a binding's harness through `harnessById`. |
-| `providerContextWindows.js` | The context-window ladder for provider/model planning, split out of `services/stageRunner.js` so the browser shares it: the vendor constants (`DEFAULT_LARGE_CONTEXT_WINDOW` / `CODEX_CONTEXT_WINDOW` / `GEMINI_CONTEXT_WINDOW` / `GROK_CONTEXT_WINDOW` / `KIMI_CONTEXT_WINDOW`), `knownModelContextWindow(model)` (the known-model regex table), `knownProviderContextWindow(provider)` (the vendor window for a configured-default CLI/TUI provider) and `catalogModelContextWindow(provider, model)` (the window the provider's own `/models` catalog reported, which outranks the table). `stageRunner.js` builds `effectiveContextWindow` on them; `client/src/utils/providerContextWindows.js` re-exports them for the provider-card budget meter, so the two ends can't resolve a different window. Pure. |
+| `providerContextWindows.js` | The context-window ladder for provider/model planning, split out of `services/stageRunner.js` so the browser shares it: the vendor constants (`DEFAULT_LARGE_CONTEXT_WINDOW` / `CODEX_CONTEXT_WINDOW` / `GEMINI_CONTEXT_WINDOW` / `GROK_CONTEXT_WINDOW` / `KIMI_CONTEXT_WINDOW`), `knownModelContextWindow(model)` (the known-model regex table), `knownProviderContextWindow(provider)` (the vendor window for a configured-default CLI/TUI provider) `catalogModelContextWindow(provider, model)` (the window the provider's own `/models` catalog reported, which outranks the table) and `mergeObservedContextWindows(provider, observed)` (folds a local daemon's LIVE `/v1/models` windows onto that catalog rung, so they outrank a stale refresh while an explicit `contextWindow` still wins; never persisted) and `aliasServedContextWindows(provider, runtime, served)` (re-keys a daemon's served windows by every spelling the provider could dispatch under, for a caller that already holds the listing). `stageRunner.js` builds `effectiveContextWindow` on them; `client/src/utils/providerContextWindows.js` re-exports them for the provider-card budget meter, so the two ends can't resolve a different window. Pure. |
| `providerConnections.js` | Provider CONNECTION identity for the connection graph (#6366) — `providerConnectionProfile(provider)` reads one record as the backend it describes (`kind`, `protocol`, `transports`, RAW server-only `credentials`, the `owned` field/env split, and `reasons` from `CONNECTION_ISOLATION_REASONS` when the config is dynamic, external, unparsable or endpoint-less). `sameConnectionIdentity` compares real credential values and refuses once any is the `REDACTED_CREDENTIAL` sentinel, so a sanitized record can never merge two connections; `compareBackendEndpoints` is the looser same-daemon test that only ever produces a link SUGGESTION, applying the recognized OpenAI-compatible `/v1` conversion (never DNS resolution, loopback/remote equivalence or arbitrary path trimming). `projectConnectionOwnedFields(provider, connection)` projects a stored backend through the reader's protocol and env-ownership rules for the graph service; `withoutConnectionOwnedFields` / `withConnectionOwnedFields` are the lossless split/materialize pair that keeps a downgraded install runnable from `data/providers.json` alone. Pure: no I/O. |
| `providerGraphPreview.js` | READ-ONLY import preview for the provider connection graph (#6366) — `buildProviderGraphPreview({providers, activeProvider})` projects the records an install already runs into proposed connections, harness bindings and executable routes, grouping ONLY the proven same-harness CLI/TUI siblings from `providerModeGroups` and surfacing a cross-harness daemon match as a `suggestedLinks` entry requiring an explicit link. `toManagementPreviewDto` sanitizes and validates the version-1 DTOs (`managementPreviewSchema`, `PROVIDER_GRAPH_SCHEMA_VERSION`) that `GET /api/providers/management/preview` returns; `projectPreviewToProviders` re-materializes every original record (pins, secrets, consent flags and unknown custom fields included) as the import-fidelity and downgrade proof; `providerGraphUniquenessViolations` checks the UNIQUE constraints #6367 will enforce; `routeModeEligibility` is the pure declarative half of mode eligibility (harness support + enabled + caller-allowed mode + text-transport consent), with the prerequisite/fallback policy left to #6368. Persists nothing and makes no generation call or runtime launch. |
| `providerGraphRecords.js` | The DURABLE half of the provider connection graph (#6367) — the pure record layer over `ai_connections` / `ai_harness_bindings` / `ai_route_bindings`. `graphFromPreview` / `importGraphFromProviders` mint UUID-keyed rows from a #6366 preview while every executable `providerId` stays untouched; `toManagementGraphDto` (`managementGraphSchema`) sanitizes them for `GET /api/providers/management` (credential PRESENCE only, no projection snapshots); `connectionOwnedSnapshot` / `applyProjections` materialize connection-owned values back into providers.json so a downgraded install still runs; `routeBelongsOnConnection` answers whether a stored connection still CONTAINS the backend one route describes (the create-time and reconcile-time test, looser than `sameConnectionIdentity`); and `planGraphReconciliation` / `reconciliationIsNoop` are the reconciliation contract shared by boot, legacy provider writes and downgrade-edit-reupgrade — acknowledging a landed projection, retrying an interrupted one, REFUSING a third externally changed value, dropping deleted records without resurrecting them, and detaching or splitting a binding whose backend moved. Pure: no DB handle, no file I/O, no provider call. |
diff --git a/server/lib/providerContextWindows.js b/server/lib/providerContextWindows.js
index 200f5e2dab..3e392ecf4d 100644
--- a/server/lib/providerContextWindows.js
+++ b/server/lib/providerContextWindows.js
@@ -12,7 +12,7 @@
* local-endpoint test from `promptRunner.js` — stays in `stageRunner.js`.
*/
-import { isAntigravityProvider, isCodexProvider, isGrokProvider, isKimiProvider } from './providerModels.js';
+import { bareLocalModelId, isAntigravityProvider, isCodexProvider, isGrokProvider, isKimiProvider } from './providerModels.js';
// A conservative-large window ASSUMED for frontier CLI / cloud-API providers
// that haven't declared one. 128K is below every current frontier model's real
@@ -78,3 +78,66 @@ export function catalogModelContextWindow(provider, model) {
const tokens = Number(windows[model]);
return Number.isFinite(tokens) && tokens > 0 ? tokens : null;
}
+
+/**
+ * `provider` with a daemon's OBSERVED windows folded onto the catalog rung, or
+ * the SAME object when there is nothing observed.
+ *
+ * Pure and shared on purpose: the server budgets with it
+ * (`services/observedContextWindows.js`, which supplies the observation) and
+ * the provider card's meter merges the same map off the readiness payload, so
+ * the number on the card is the number the dispatch gate enforces.
+ *
+ * Observation lands on `modelContextWindows` rather than on `contextWindow`
+ * because that is exactly its rank: it outranks whatever a model refresh last
+ * recorded and the regex table below it, while an explicit `provider.contextWindow`
+ * the user typed still wins — a deliberate override is not a stale guess.
+ *
+ * Nothing here is persisted. See `services/observedContextWindows.js` for why.
+ *
+ * @param {object|null|undefined} provider
+ * @param {Record<string, number>|null|undefined} observed
+ */
+export function mergeObservedContextWindows(provider, observed) {
+ // `{}` is normalized away by both producers, but this is a shared pure leaf
+ // reached from the browser over HTTP — an older or newer server on the other
+ // end of `/providers/readiness` may spell "nothing observed" either way, and
+ // the identity-stability promise above must hold for both.
+ if (!observed || Object.keys(observed).length === 0) return provider;
+ return { ...provider, modelContextWindows: { ...provider?.modelContextWindows, ...observed } };
+}
+
+/**
+ * A local daemon's served window map, re-keyed by every spelling `provider`
+ * could dispatch under, or `null` when the listing said nothing about windows.
+ *
+ * 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.
+ *
+ * Lives beside {@link mergeObservedContextWindows} — its own consumer — rather
+ * than in `services/observedContextWindows.js`, so a caller that ALREADY holds
+ * the listing (`services/providerReadiness.js`, which polls the same cached
+ * `/v1/models` for its checklist) reuses the one aliasing rule without a static
+ * edge onto the probing service that `promptRunner.js` deliberately defers.
+ *
+ * @param {object} provider — a RAW provider record
+ * @param {{kind: string}} runtime — its local runtime, already resolved
+ * @param {Record<string, number>|null|undefined} served — the probe's `contextWindows`
+ * @returns {Record<string, number>|null}
+ */
+export function aliasServedContextWindows(provider, runtime, served) {
+ // The probe already rejects anything that is not a positive integer, so what
+ // arrives is either usable or absent.
+ if (!served || Object.keys(served).length === 0) return null;
+ const windows = { ...served };
+ 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;
+}
diff --git a/server/routes/universeBuilder/castIntegrity.test.js b/server/routes/universeBuilder/castIntegrity.test.js
index d3c345c7b5..dd885d0bdc 100644
--- a/server/routes/universeBuilder/castIntegrity.test.js
+++ b/server/routes/universeBuilder/castIntegrity.test.js
@@ -2,7 +2,7 @@
* Route → Zod → service → store round trip for the cast-integrity endpoints (#6415).
*
* Only the PROVIDER boundary is stubbed (`runPromptRefineRaw` /
- * `resolveStageContext`) — everything else is the real router, the real
+ * `resolveStageRoute`) — everything else is the real router, the real
* schemas, the real merge and the real contract. `updateUniverse` is a faithful
* stand-in that actually applies the mutator against a mutable universe, so the
* inside-the-write-queue lock / staleness re-checks are genuinely exercised
@@ -37,14 +37,13 @@ vi.mock('../../services/pipeline/refineHelpers.js', async (importOriginal) => ({
runPromptRefineRaw: (...args) => refineRawMock(...args),
}));
-const resolveStageContextMock = vi.fn(async () => ({
+const resolveStageRouteMock = vi.fn(async () => ({
provider: { id: 'prov-1', name: 'Local Llama' },
model: 'llama-3.3',
- contextWindow: 32000,
}));
vi.mock('../../services/stageRunner.js', async (importOriginal) => ({
...(await importOriginal()),
- resolveStageContext: (...args) => resolveStageContextMock(...args),
+ resolveStageRoute: (...args) => resolveStageRouteMock(...args),
}));
const { default: universeBuilderRoutes } = await import('./index.js');
@@ -86,8 +85,8 @@ const lead = () => ({
beforeEach(() => {
vi.clearAllMocks();
- resolveStageContextMock.mockResolvedValue({
- provider: { id: 'prov-1', name: 'Local Llama' }, model: 'llama-3.3', contextWindow: 32000,
+ resolveStageRouteMock.mockResolvedValue({
+ provider: { id: 'prov-1', name: 'Local Llama' }, model: 'llama-3.3',
});
universe = {
id: 'u-1',
@@ -116,7 +115,7 @@ describe('GET /:id/characters/integrity — the deterministic pass', () => {
});
it('still renders the report when no provider can be resolved', async () => {
- resolveStageContextMock.mockRejectedValue(new Error('no provider configured'));
+ resolveStageRouteMock.mockRejectedValue(new Error('no provider configured'));
const res = await request(makeApp()).get('/api/universe-builder/u-1/characters/integrity');
expect(res.status).toBe(200);
expect(res.body.reviewScope.providerId).toBeNull();
diff --git a/server/services/observedContextWindows.js b/server/services/observedContextWindows.js
index 95537d82d7..77065a07d8 100644
--- a/server/services/observedContextWindows.js
+++ b/server/services/observedContextWindows.js
@@ -29,7 +29,7 @@
*/
import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
-import { bareLocalModelId } from '../lib/providerModels.js';
+import { aliasServedContextWindows, mergeObservedContextWindows } from '../lib/providerContextWindows.js';
import { probeOpenAiModelsCached } from '../lib/openAiModelsProbeCache.js';
/**
@@ -55,20 +55,7 @@ export async function observedContextWindows(provider, deps = {}) {
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;
+ return aliasServedContextWindows(provider, runtime, result?.contextWindows);
}
/**
@@ -79,19 +66,15 @@ export async function observedContextWindows(provider, deps = {}) {
* 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.
+ * Where the observation RANKS is stated once, with the merge itself in
+ * `lib/providerContextWindows.js` — the provider card folds the same map in off
+ * the readiness payload, so the card and this gate cannot rank it differently.
+ * What this wrapper adds is the probe that supplies it.
*
* @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 } };
+ return mergeObservedContextWindows(provider, await observedContextWindows(provider, deps));
}
diff --git a/server/services/promptRunner.js b/server/services/promptRunner.js
index 845251ae3b..29e0841ab3 100644
--- a/server/services/promptRunner.js
+++ b/server/services/promptRunner.js
@@ -83,6 +83,22 @@ function loadObservedContextWindows() {
return observedContextWindowsLoadPromise;
}
+/**
+ * `withObservedContextWindows(provider)` behind that deferred load — the ONE
+ * operation both readers of the module want (the dispatch gate below, and
+ * `stageRunner.resolveStageContext` for the budgeter). Exported as the operation
+ * rather than the loader so neither caller hard-codes which named export to
+ * destructure, and both share one dynamic import and one settled promise.
+ *
+ * Rejects on a load or probe failure; error policy is the caller's, because the
+ * two differ deliberately — the gate lets it surface, the budgeter degrades to
+ * the provider as stored rather than turning planning into a new failure mode.
+ */
+export async function withObservedContextWindowsLazy(provider) {
+ const { withObservedContextWindows } = await loadObservedContextWindows();
+ return withObservedContextWindows(provider);
+}
+
// 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
@@ -1302,8 +1318,7 @@ 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);
+ const observed = await withObservedContextWindowsLazy(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.
diff --git a/server/services/providerReadiness.js b/server/services/providerReadiness.js
index 3b591962a2..f6a84ed334 100644
--- a/server/services/providerReadiness.js
+++ b/server/services/providerReadiness.js
@@ -40,6 +40,7 @@ import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
import { expandPageToken, getNavPageForPath } from '../lib/navManifest.js';
import { bareLocalModelId } from '../lib/providerModels.js';
import { probeOpenAiModelsCached, resetOpenAiModelsProbeCache } from '../lib/openAiModelsProbeCache.js';
+import { aliasServedContextWindows } from '../lib/providerContextWindows.js';
import { findCommandOnPath } from '../lib/processEnv.js';
import { actionCovers, describeRuntimeSetup, readRuntimeWeights, weightsBlockStart } from './localRuntimeSetup.js';
import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';
@@ -438,6 +439,11 @@ export async function getProviderReadiness(provider, deps = {}) {
standby,
standbyDetail: standby ? expandPageToken(runtime.standbyDetail, runtime) : null,
checks,
+ // What this daemon is SERVING right now. It rides the readiness payload
+ // BECAUSE it is observed runtime state and must never reach `providers.json`
+ // (#7441) — this is the channel the provider card budgets its meter from, so
+ // the card shows the window the dispatch gate would actually enforce.
+ contextWindows: aliasServedContextWindows(provider, runtime, result.contextWindows),
// What a one-click "set this up for me" button can do about the unmet
// checks, or `null` when nothing here is auto-fixable (see
// `localRuntimeSetup.js`). Carried on the readiness payload so the card
diff --git a/server/services/providerReadiness.test.js b/server/services/providerReadiness.test.js
index ce5d2404a5..d11c4a4778 100644
--- a/server/services/providerReadiness.test.js
+++ b/server/services/providerReadiness.test.js
@@ -14,7 +14,7 @@ const llamaProvider = (overrides = {}) => ({
...overrides,
});
-const reachable = (models) => async () => ({ reachable: true, models, error: null });
+const reachable = (models, contextWindows = null) => async () => ({ reachable: true, models, contextWindows, error: null });
const unreachable = (error = 'connection refused') => async () => ({ reachable: false, models: null, error });
const checkById = (readiness, id) => readiness.checks.find((check) => check.id === id);
@@ -555,3 +555,33 @@ describe('getProviderReadinessMap batching', () => {
expect(probes).toBe(1);
});
});
+
+// #7447: the readiness payload is how the LIVE window reaches the provider
+// card, because observed runtime state must never touch `providers.json`.
+describe('getProviderReadiness — observed context windows', () => {
+ it('carries the served windows, keyed by every spelling the provider dispatches under', async () => {
+ // The daemon lists the bare id; the OpenCode wrapper offers `llama/dflash`.
+ // A map keyed on only one of the two answers "unknown" for every dispatch.
+ const readiness = await getProviderReadiness(
+ llamaProvider({ models: ['llama/dflash'], defaultModel: 'llama/dflash' }),
+ { findCommand: () => '/opt/homebrew/bin/llama-server', probe: reachable(['dflash'], { dflash: 32768 }) },
+ );
+ expect(readiness.contextWindows).toEqual({ dflash: 32768, 'llama/dflash': 32768 });
+ });
+
+ it('reports null when the daemon is down or silent about windows', async () => {
+ const down = await getProviderReadiness(
+ llamaProvider(),
+ { findCommand: () => '/opt/homebrew/bin/llama-server', probe: unreachable() },
+ );
+ expect(down.contextWindows).toBeNull();
+
+ // Reachable, listing readable, but no window declared: still unknown, never
+ // a zero or an invented number.
+ const silent = await getProviderReadiness(
+ llamaProvider(),
+ { findCommand: () => '/opt/homebrew/bin/llama-server', probe: reachable(['dflash']) },
+ );
+ expect(silent.contextWindows).toBeNull();
+ });
+});
diff --git a/server/services/stageRunner.js b/server/services/stageRunner.js
index d5754a1e5a..57b7941c32 100644
--- a/server/services/stageRunner.js
+++ b/server/services/stageRunner.js
@@ -17,7 +17,7 @@
import { isProcessProvider } from '../lib/providerTypes.js';
import { ServerError } from '../lib/errorHandler.js';
import { findBalancedBlocks, tryParseWithRepair } from '../lib/jsonExtract.js';
-import { resolveEffectiveModel, runPromptThroughProvider, DEFAULT_TIMEOUT_MS, isLocalEndpoint } from './promptRunner.js';
+import { resolveEffectiveModel, runPromptThroughProvider, DEFAULT_TIMEOUT_MS, isLocalEndpoint, withObservedContextWindowsLazy } from './promptRunner.js';
import { stripCodeFences } from '../lib/llmText.js';
import { extractCodexAssistant } from '../lib/codexAssistantExtract.js';
import { getActiveProvider, getProviderById } from './providers.js';
@@ -225,13 +225,46 @@ export function effectiveContextWindow(provider, model) {
*
* Best-effort planning: this resolves the PRIMARY provider; a runtime fallback
* to a different (possibly smaller-window) provider is not reflected here.
+ *
+ * WHICH provider/model a stage would use is {@link resolveStageRoute}, and it
+ * makes no network call. Use that when the window is not what you came for.
*/
-export async function resolveStageContext(stageName, options = {}) {
+export async function resolveStageRoute(stageName, options = {}) {
const stage = effectiveStage(getStage(stageName));
const provider = await resolveProviderForStage(stage, options);
const requestedModel = resolveModel(provider, resolveModelHint(stage, options));
- const model = resolveEffectiveModel(provider, requestedModel);
- return { provider, model, contextWindow: effectiveContextWindow(provider, model) };
+ return { provider, model: resolveEffectiveModel(provider, requestedModel) };
+}
+
+/**
+ * {@link resolveStageRoute} plus the window to budget the prompt against.
+ *
+ * That window is measured against what a local daemon is SERVING right now, not
+ * only against what the provider record remembers. Without it the chunker
+ * planned to the blanket 128K assumption for a seeded local wrapper, built the
+ * oversized prompt, and the pre-dispatch gate (#7441, which already reads the
+ * live listing) refused it — a run lost to a limit the budgeter could have
+ * respected. The listing is TTL-cached and shared with that gate, so a chunked
+ * run spends at most one `/v1/models` per endpoint per 15s rather than one per
+ * stage; a daemon that is down or silent contributes nothing, and the ladder
+ * resolves exactly as it did before.
+ *
+ * `provider` is returned UNMERGED — callers read it for the record's identity,
+ * and observed runtime state has no business riding a provider record around.
+ */
+export async function resolveStageContext(stageName, options = {}) {
+ const { provider, model } = await resolveStageRoute(stageName, options);
+ // An explicit `contextWindow` already short-circuits the ladder's first rung,
+ // so observing one could not change the answer — skip the probe rather than
+ // spend a round trip (up to the probe timeout on a black-holed endpoint) on a
+ // result that is provably discarded.
+ if (Number(provider?.contextWindow) > 0) {
+ return { provider, model, contextWindow: effectiveContextWindow(provider, model) };
+ }
+ // Budget-only enrichment, so a probe or module-load failure must never turn
+ // planning into a new failure mode — fall back to the provider as stored.
+ const observed = await withObservedContextWindowsLazy(provider).catch(() => provider);
+ return { provider, model, contextWindow: effectiveContextWindow(observed, model) };
}
// Provider resolution precedence, strongest first:
diff --git a/server/services/stageRunner.test.js b/server/services/stageRunner.test.js
index 48daa67f2e..7e203ca725 100644
--- a/server/services/stageRunner.test.js
+++ b/server/services/stageRunner.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
vi.mock('./providers.js', () => ({
getActiveProvider: vi.fn(),
@@ -10,6 +10,14 @@ vi.mock('./promptService.js', () => ({
getStage: vi.fn(),
}));
+// The live `/v1/models` listing `resolveStageContext` budgets against (#7447).
+// Mocked rather than spied so no test in this file can reach a real socket; the
+// registry covers the dynamic import `resolveStageContext` reaches it through.
+vi.mock('../lib/openAiModelsProbeCache.js', () => ({
+ probeOpenAiModelsCached: vi.fn(),
+ resetOpenAiModelsProbeCache: vi.fn(),
+}));
+
vi.mock('./runner.js', () => ({
createRun: vi.fn(async () => ({ runId: 'run-abc12345' })),
executeApiRun: vi.fn(),
@@ -22,6 +30,7 @@ vi.mock('./runner.js', () => ({
const providers = await import('./providers.js');
const prompts = await import('./promptService.js');
const runner = await import('./runner.js');
+const probeCache = await import('../lib/openAiModelsProbeCache.js');
const { buildEffortArgs } = await import('../lib/providerModels.js');
const { CREATIVE_LATITUDE_HEADING } = await import('../lib/creativeLatitude.js');
const {
@@ -31,6 +40,7 @@ const {
extractJson,
effectiveContextWindow,
resolveStageContext,
+ resolveStageRoute,
resolveJudgeForStage,
resolveEffortHint,
effectiveStage,
@@ -163,6 +173,110 @@ describe('stageRunner — context windows', () => {
});
});
+// #7447 — see `resolveStageContext`'s docblock for why the live window matters.
+describe('stageRunner — resolveStageContext reads the live daemon window', () => {
+ // The shipped vLLM wrapper: seeded with no `contextWindow` and no
+ // `modelContextWindows`, so every rung below it used to answer 128K.
+ const daemonProvider = (extra = {}) => ({
+ id: 'opencode-vllm',
+ name: 'OpenCode vLLM',
+ type: 'cli',
+ enabled: true,
+ command: 'opencode',
+ endpoint: 'http://127.0.0.1:18020/v1',
+ defaultModel: 'qwen3.8-27b',
+ models: ['qwen3.8-27b'],
+ vllmBacked: true,
+ ...extra,
+ });
+
+ beforeEach(() => {
+ prompts.getStage.mockReturnValue(null);
+ });
+
+ // `vi.clearAllMocks()` clears calls but keeps implementations, so the probe
+ // stub has to be torn down explicitly or it leaks into later describes.
+ afterEach(() => {
+ probeCache.probeOpenAiModelsCached.mockReset();
+ });
+
+ const serving = (contextWindows) => probeCache.probeOpenAiModelsCached.mockResolvedValue({
+ reachable: true,
+ models: Object.keys(contextWindows),
+ contextWindows,
+ error: null,
+ });
+
+ it('budgets to the 32K the daemon is serving, not the 128K assumption', async () => {
+ providers.getActiveProvider.mockResolvedValue(daemonProvider());
+ serving({ 'qwen3.8-27b': 32_768 });
+
+ const context = await resolveStageContext('any-stage');
+ expect(context.contextWindow).toBe(32_768);
+ });
+
+ it('lets the observation outrank a stale catalog entry, but not a typed override', async () => {
+ // Both rungs at once: the record remembers 128K from whenever the user last
+ // pressed Refresh Models, and the daemon has since been relaunched at 32K.
+ providers.getActiveProvider.mockResolvedValue(daemonProvider({
+ modelContextWindows: { 'qwen3.8-27b': 128_000 },
+ }));
+ serving({ 'qwen3.8-27b': 32_768 });
+ await expect(resolveStageContext('any-stage')).resolves.toMatchObject({ contextWindow: 32_768 });
+
+ // A number the user typed is a deliberate override, not a stale guess.
+ providers.getActiveProvider.mockResolvedValue(daemonProvider({ contextWindow: 8_192 }));
+ await expect(resolveStageContext('any-stage')).resolves.toMatchObject({ contextWindow: 8_192 });
+ });
+
+ it('spends no probe at all when an explicit window already decides the answer', async () => {
+ // The override short-circuits the ladder's first rung, so observing could
+ // not change the result — and a chunked run would otherwise pay a round trip
+ // per stage (up to the probe timeout on a black-holed endpoint) for it.
+ providers.getActiveProvider.mockResolvedValue(daemonProvider({ contextWindow: 8_192 }));
+ serving({ 'qwen3.8-27b': 32_768 });
+
+ await expect(resolveStageContext('any-stage')).resolves.toMatchObject({ contextWindow: 8_192 });
+ expect(probeCache.probeOpenAiModelsCached).not.toHaveBeenCalled();
+ });
+
+ it('resolveStageRoute answers provider/model without touching the network', async () => {
+ // `universeCastIntegrity` renders a deterministic report and reads only the
+ // provider's identity; budgeting enrichment must not put a daemon probe on
+ // that read path.
+ providers.getActiveProvider.mockResolvedValue(daemonProvider());
+ serving({ 'qwen3.8-27b': 32_768 });
+
+ const route = await resolveStageRoute('any-stage');
+ expect(route).toEqual({ provider: expect.objectContaining({ id: 'opencode-vllm' }), model: 'qwen3.8-27b' });
+ expect(route.contextWindow).toBeUndefined();
+ expect(probeCache.probeOpenAiModelsCached).not.toHaveBeenCalled();
+ });
+
+ it('budgets exactly as before when the daemon is unreachable or silent about windows', async () => {
+ // The regression guard for "unknown stays unknown": a down daemon must not
+ // become a NEW answer, and must not become a new failure mode either.
+ providers.getActiveProvider.mockResolvedValue(daemonProvider());
+ probeCache.probeOpenAiModelsCached.mockRejectedValue(new Error('ECONNREFUSED'));
+ await expect(resolveStageContext('any-stage')).resolves.toMatchObject({
+ contextWindow: DEFAULT_LARGE_CONTEXT_WINDOW,
+ });
+
+ serving({});
+ await expect(resolveStageContext('any-stage')).resolves.toMatchObject({
+ contextWindow: DEFAULT_LARGE_CONTEXT_WINDOW,
+ });
+ });
+
+ it('returns the provider record UNMERGED, so observed runtime state rides nothing persistable', async () => {
+ providers.getActiveProvider.mockResolvedValue(daemonProvider());
+ serving({ 'qwen3.8-27b': 32_768 });
+
+ const context = await resolveStageContext('any-stage');
+ expect(context.provider.modelContextWindows).toBeUndefined();
+ });
+});
+
describe('stageRunner — extractJson', () => {
it('parses JSON inside markdown code fences', () => {
expect(extractJson('```json\n{"a":1}\n```')).toEqual({ a: 1 });
diff --git a/server/services/universeCastIntegrity.js b/server/services/universeCastIntegrity.js
index f31fe8dba5..49c69b80c1 100644
--- a/server/services/universeCastIntegrity.js
+++ b/server/services/universeCastIntegrity.js
@@ -27,7 +27,7 @@
import { getUniverse, updateUniverse } from './universeBuilder.js';
import { runPromptRefineRaw } from './pipeline/refineHelpers.js';
-import { resolveStageContext } from './stageRunner.js';
+import { resolveStageRoute } from './stageRunner.js';
import { ServerError } from '../lib/errorHandler.js';
import { shortId } from '../lib/fileUtils.js';
import {
@@ -75,7 +75,7 @@ const resolveScopeIds = (cast, characterIds) => {
/**
* The deterministic report plus the cost of the semantic review that would
- * follow. Makes NO provider call: `resolveStageContext` only resolves which
+ * follow. Makes NO provider call and no network call: `resolveStageRoute` only resolves which
* provider/model the stage would use.
*/
export async function getUniverseCastIntegrity(universeId, { characterIds = null } = {}) {
@@ -87,7 +87,7 @@ export async function getUniverseCastIntegrity(universeId, { characterIds = null
// Best-effort: a universe with no provider configured yet must still be able
// to render its deterministic report, so a resolution failure degrades to an
// unnamed scope rather than failing the whole request.
- const resolved = await resolveStageContext(REVIEW_STAGE).catch(() => null);
+ const resolved = await resolveStageRoute(REVIEW_STAGE).catch(() => null);
return {
...report,