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
fix: clamp the prompt budget to the window an Ollama daemon was launched with (#7466)
[._.]/ Adam Eivyc18a19b13e5b
diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex a3c9864b94..c12b332495 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 — 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. |+| `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, and holds every resolved window down to an Ollama daemon's launch `num_ctx` through `clampToRuntimeContextWindow` (applied internally, from `server/lib/aiToolkit/internal/ollamaBacked.js` — the same module the server's budgeter and pre-dispatch gate use), so the meter can't promise a budget a run would be refused for (#7466). || `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.jsindex 6ca78c8dcb..afd360c369 100644--- a/client/src/utils/providerContextWindows.js+++ b/client/src/utils/providerContextWindows.js@@ -12,6 +12,9 @@* drift from the server (the walk order, and the client's own local-endpoint* test), so keep both beside their server twins in `stageRunner.js`.*+ * The Ollama `num_ctx` ceiling is shared with the SERVER's dispatch gate too,+ * so the meter cannot promise a window a run would then be refused for (#7466).+ ** Re-exported by `./providers.js` for existing `utils/providers` imports.*/@@ -24,6 +27,11 @@ import {knownModelContextWindow,knownProviderContextWindow,} from '../../../server/lib/providerContextWindows.js';+// The Ollama `num_ctx` ceiling, from the module the server's budgeter and its+// pre-dispatch gate resolve it through (#7466). Reached at the toolkit's+// dependency-free `internal/` leaf for the same reason `providerTypes.js`+// already takes `isOllamaBackedProvider` from there.+import { clampToRuntimeContextWindow } from '../../../server/lib/aiToolkit/internal/ollamaBacked.js';export {DEFAULT_LARGE_CONTEXT_WINDOW,@@ -65,20 +73,13 @@ export const CONTEXT_WINDOW_SOURCE = Object.freeze({});/**- * The planning context window for a provider/model AND where it came from.- * Walks the same rungs, in the same order, as `effectiveContextWindow` in+ * Which window this provider/model CLAIMS, before the runtime ceiling.+ * Walks the same rungs, in the same order, as `claimedContextWindow` in* server/services/stageRunner.js — the rungs are shared, so the order and the* local-endpoint test are what could drift, and the card would then promise a* budget the budgeter won't use.- *- * `{ tokens: null, source: null }` means nothing is known (an unrecognized model- * on a local backend); the budgeter applies its own conservative floor there.- *- * @param {object|null|undefined} provider- * @param {string|null|undefined} model- * @returns {{tokens: number|null, source: string|null}}*/-export const resolveModelContextWindow = (provider, model) => {+const claimedModelContextWindow = (provider, model) => {const explicit = Number(provider?.contextWindow);if (Number.isFinite(explicit) && explicit > 0) {return { tokens: explicit, source: CONTEXT_WINDOW_SOURCE.OVERRIDE };@@ -98,6 +99,29 @@ export const resolveModelContextWindow = (provider, model) => {: { tokens: null, source: null };};+/**+ * The planning context window for a provider/model AND where it came from —+ * the claimed window held to what an Ollama daemon was LAUNCHED with, exactly+ * as the server's budgeter and its pre-dispatch gate resolve it.+ *+ * `{ tokens: null, source: null }` means nothing is known (an unrecognized model+ * on a local backend); the budgeter applies its own conservative floor there.+ *+ * @param {object|null|undefined} provider+ * @param {string|null|undefined} model+ * @returns {{tokens: number|null, source: string|null}}+ */+export const resolveModelContextWindow = (provider, model) => {+ const claimed = claimedModelContextWindow(provider, model);+ const tokens = clampToRuntimeContextWindow(provider, claimed.tokens);+ // A clamped window is no longer whichever rung claimed it — what the card is+ // now printing is the daemon's own `num_ctx`, which is a REPORTED window even+ // when the number it replaced was a user override or a guess.+ return tokens === claimed.tokens+ ? claimed+ : { tokens, source: CONTEXT_WINDOW_SOURCE.REPORTED };+};+export const effectiveModelContextWindow = (provider, model) =>resolveModelContextWindow(provider, model).tokens;@@ -113,6 +137,11 @@ export const effectiveModelContextWindow = (provider, model) =>* purpose: they would stamp the same guessed number onto every option in the* list, which says nothing and reads as fact.*+ * The daemon's launch ceiling is NOT one of those guesses — it applies to every+ * option alike, and the picker is exactly where someone decides which model+ * "fits", so a `(40K ctx)` option beside a card promising 8K is two numbers+ * presented as fact in one form. Clamped for that reason (#7466).+ ** Take `provider` rather than a pre-merged map so every picker gets catalog* windows for free — merging at the call site is what left the fallback-model* and manuscript-override selects labelling a 1M model as if it were unknown.@@ -123,7 +152,10 @@ export const effectiveModelContextWindow = (provider, model) =>* @returns {string}*/export const modelOptionLabel = (id, ctxById, provider) => {- const ctx = ctxById?.[id] || catalogModelContextWindow(provider, id) || knownModelContextWindow(id);+ const ctx = clampToRuntimeContextWindow(+ provider,+ ctxById?.[id] || catalogModelContextWindow(provider, id) || knownModelContextWindow(id),+ );const label = formatContextLength(ctx);return label ? `${id} (${label})` : id;};diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex cbc9cbdca4..b694617dd6 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -1449,9 +1449,27 @@ describe('effectiveModelContextWindow', () => {expect(modelOptionLabel('stealth/ox-alpha', { 'stealth/ox-alpha': 32768 }, provider)).toBe('stealth/ox-alpha (32K ctx)');});- it('uses explicit contextWindow and numCtx with server precedence', () => {- expect(effectiveModelContextWindow({ type: 'api', endpoint: 'http://localhost:11434/v1', contextWindow: 64_000, numCtx: 32_768 }, 'unknown')).toBe(64_000);- expect(effectiveModelContextWindow({ type: 'api', endpoint: 'http://localhost:11434/v1', numCtx: 32_768 }, 'unknown')).toBe(32_768);+ it('bounds every wider rung by an Ollama daemon\'s launch numCtx', () => {+ // #7466: `numCtx` is the window the daemon was LAUNCHED with, so it bounds+ // every wider rung — a typed override included — exactly as the server's+ // budgeter and its pre-dispatch gate do. A card promising 64K against a 32K+ // daemon is a budget the run would then be refused for.+ const ollama = { type: 'api', endpoint: 'http://localhost:11434/v1' };+ expect(effectiveModelContextWindow({ ...ollama, contextWindow: 64_000, numCtx: 32_768 }, 'unknown')).toBe(32_768);+ expect(effectiveModelContextWindow({ ...ollama, numCtx: 32_768 }, 'unknown')).toBe(32_768);+ expect(effectiveModelContextWindow({ ...ollama, numCtx: 8_192, modelContextWindows: { 'qwen3:32b': 40_960 } }, 'qwen3:32b')).toBe(8_192);+ // A clamped window is the daemon's own report, not the override it replaced.+ expect(resolveModelContextWindow({ ...ollama, contextWindow: 64_000, numCtx: 32_768 }, 'unknown').source)+ .toBe(CONTEXT_WINDOW_SOURCE.REPORTED);+ // The picker has to agree with the meter beside it — one form must not+ // offer "(40K ctx)" under a card that says the budget is 8K.+ expect(modelOptionLabel('qwen3:32b', undefined, { ...ollama, numCtx: 8_192, modelContextWindows: { 'qwen3:32b': 40_960 } }))+ .toBe('qwen3:32b (8K ctx)');+ });++ it('leaves a non-Ollama endpoint alone, since nothing there honors num_ctx', () => {+ expect(effectiveModelContextWindow({ type: 'api', endpoint: 'http://localhost:1234/v1', contextWindow: 64_000, numCtx: 32_768 }, 'unknown')).toBe(64_000);+ expect(effectiveModelContextWindow({ type: 'api', endpoint: 'http://localhost:1234/v1', numCtx: 32_768 }, 'unknown')).toBe(32_768);});});diff --git a/server/lib/README.md b/server/lib/README.mdindex 4fb2f04d18..3e7113d4cd 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -174,7 +174,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|-| `aiToolkit/` | Vendored toolkit (providers + runner + prompts + status). See `aiToolkit/index.js`. `aiToolkit/endpointGuard.js` is the public SSRF / key-exfiltration guard for provider `endpoint` URLs (`evaluateSecretEndpoint` / `assertSecretEndpoint`) — import it from there, not from `internal/`. |+| `aiToolkit/` | Vendored toolkit (providers + runner + prompts + status). See `aiToolkit/index.js`. `aiToolkit/endpointGuard.js` is the public SSRF / key-exfiltration guard for provider `endpoint` URLs (`evaluateSecretEndpoint` / `assertSecretEndpoint`) — import it from there, not from `internal/`. `aiToolkit/internal/ollamaBacked.js` also declares `clampToRuntimeContextWindow(provider, planned)` — what an Ollama `num_ctx` means to a context window: an upper bound over every planning rung (a typed override included), and the answer when nothing else declared one. The budgeter (`services/stageRunner.js`), the pre-dispatch gate (`aiToolkit/providerStatus.js#knownContextWindow`) and the browser's provider-card meter all import it from there rather than restating it (#7466). || `aiToolkitState.js` | Module-level singleton for the toolkit instance shared by the `providers`/`runner`/`promptService` shims — `setAIToolkitInstance` / `requireToolkit` (throws `AI_TOOLKIT_NOT_INITIALIZED`) / `getAIToolkitInstance` (no-throw for cleanup paths). || `antigravity.js` | Antigravity (`agy`) CLI provider helpers — id/sentinel constants (`ANTIGRAVITY_CLI_ID`, `ANTIGRAVITY_CONFIGURED_DEFAULT`, `LEGACY_GEMINI_*`), `isAntigravityCommand`/`isAntigravityCliProvider` predicates, and `ensureAntigravityPrintArgs(args, {model, effort})`/`ensureAntigravityTuiArgs(args, {model, effort})`/`stripAntigravityUnsupportedArgs` argv normalizers. `parseAntigravityModelList(stdout)` parses `agy models` rows — accepts both the modern `<id>\t<Label>` shape and the older bare-id-per-line one, deduped, sentinel dropped (mirrored in the vendored toolkit's `internal/antigravity.js`; used by both the provider-catalog refresh and Image Gen's agy model picker). `isAntigravityModelId(id)` is the same id shape as a bare predicate, for spawn sites building an `agy --model` argv from a value no route schema bounded. The strip drops legacy Gemini `--yolo`/`-m`/`--output-format` but PRESERVES the long `--model` (agy accepts it as a per-session flag, so a user-baked pin is a real selection and suppresses the injected one); the two builders inject `--model`/`--effort` from the per-run overrides, always ahead of the trailing `--print` marker whose value is the prompt. || `llmText.js` | Pure LLM-output text helpers — `stripCodeFences` (unfence a model reply) and `parseLLMJSON` (unfence then JSON.parse with a descriptive throw). Below the provider layer, so lib can clean model output without importing provider orchestration. |@@ -226,7 +226,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) `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. |+| `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). The Ollama `num_ctx` ceiling is deliberately NOT here — see `aiToolkit/`. `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/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.mdindex dd307adc36..b87e542ec5 100644--- a/server/lib/aiToolkit/AGENTS.md+++ b/server/lib/aiToolkit/AGENTS.md@@ -4,6 +4,7 @@ The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previous**Key points:**- `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.+- **The Ollama `num_ctx` ceiling is declared ONCE, in `internal/ollamaBacked.js`** (`clampToRuntimeContextWindow`), beside the predicate that gates it. `knownContextWindow` applies it through that helper and must never restate the `Math.min` inline — the host's prompt budgeter (`server/services/stageRunner.js#effectiveContextWindow`) and the browser's provider-card meter call the same function, and when the rule was stated twice they drifted (#7466). It is an upper BOUND over every planning rung, a user's explicit `contextWindow` included, and the answer outright when nothing else declared one. Host callers import the `internal/` leaf directly: the public barrel reaches `fs` and `child_process`, and `stageRunner.js` sits inside the server suite's import budget.- 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/internal/ollamaBacked.js b/server/lib/aiToolkit/internal/ollamaBacked.jsindex 0a6216e767..0982ad89b9 100644--- a/server/lib/aiToolkit/internal/ollamaBacked.js+++ b/server/lib/aiToolkit/internal/ollamaBacked.js@@ -39,3 +39,50 @@ export function ollamaBaseFromProvider(provider) {const base = String(provider?.envVars?.ANTHROPIC_BASE_URL || provider?.endpoint || 'http://localhost:11434');return base.replace(/\/+$/, '').replace(/\/v1$/, '');}++/**+ * `planned` held to what an Ollama daemon will actually serve — the one place+ * PortOS decides what `numCtx` means to a context window.+ *+ * It is the window the daemon was launched with, so it is an upper BOUND over+ * whatever a planning ladder resolved, and the answer outright when nothing+ * else declared one. It is NOT a fallback rung under the declared windows: a+ * catalog entry of 40,960 on a daemon launched at 8,192 still gets 8,192. With+ * no ceiling `planned` passes through untouched, `null` included — unknown must+ * not become a new answer.+ *+ * Shared rather than restated because the two ends drifted (#7466): the+ * pre-dispatch gate (`providerStatus.js#knownContextWindow`) clamped while the+ * prompt budgeter (`server/services/stageRunner.js#effectiveContextWindow`)+ * ranked `numCtx` last, so a chunked stage was built against the model's+ * declared window and then refused before it dispatched. The gate, the budgeter+ * and the browser's provider-card meter now all call this.+ *+ * Two deliberate limits, both conservative (they can only under-plan):+ * - Only Ollama honors the runner's top-level `num_ctx`; every other+ * OpenAI-compatible endpoint ignores it, so there the field describes a+ * window nothing enforces and must never refuse a request. Hence the+ * `isOllamaBackedProvider` gate — and why this lives beside that predicate+ * rather than in its own module, which would add a module to the import+ * closure of every suite reaching either end of one rule.+ * - It reads `provider.numCtx` only. The ambient `OLLAMA_CONTEXT_LENGTH` rung+ * that `server/lib/ollamaContext.js#resolveOllamaContextLength` adds is not+ * visible here (the toolkit may not import out, and the browser cannot see+ * server env); and for an Ollama-backed CLI/TUI harness `numCtx` is the+ * window the daemon is reloaded UP TO, so a daemon already running wider+ * keeps its wider window.+ *+ * @param {object|null|undefined} provider+ * @param {number|null|undefined} planned — whatever the caller's ladder resolved+ * @returns {number|null}+ */+export function clampToRuntimeContextWindow(provider, planned) {+ const positive = (value) => {+ const n = Number(value);+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;+ };+ const ceiling = isOllamaBackedProvider(provider) ? positive(provider?.numCtx) : null;+ const usable = positive(planned);+ if (!ceiling) return usable;+ return usable ? Math.min(usable, ceiling) : ceiling;+}diff --git a/server/lib/aiToolkit/providerStatus.js b/server/lib/aiToolkit/providerStatus.jsindex d8fad4f19e..9eb6817318 100644--- a/server/lib/aiToolkit/providerStatus.js+++ b/server/lib/aiToolkit/providerStatus.js@@ -10,7 +10,7 @@ import { readFile } from 'fs/promises';import { existsSync } from 'fs';import { join, dirname } from 'path';import { atomicWrite } from './internal/atomicWrite.js';-import { isOllamaBackedProvider } from './internal/ollamaBacked.js';+import { clampToRuntimeContextWindow } from './internal/ollamaBacked.js';/*** Gate a *configured* fallback-model pin against the fallback provider's own@@ -102,17 +102,13 @@ function resolvedFallbackModel(provider, correctedModel) {export function knownContextWindow(provider, model) {const explicit = Number(provider?.contextWindow);const catalog = Number(model && provider?.modelContextWindows?.[model]);- const runtime = Number(provider?.numCtx);const planning = Number.isFinite(explicit) && explicit > 0? explicit: (Number.isFinite(catalog) && catalog > 0 ? catalog : null);- // Only Ollama honors the runner's top-level num_ctx option. When configured,- // it is the real runtime ceiling and therefore constrains any wider planning- // or catalog window; other OpenAI-compatible endpoints ignore the field.- if (isOllamaBackedProvider(provider) && Number.isFinite(runtime) && runtime > 0) {- return planning ? Math.min(planning, runtime) : runtime;- }- return planning;+ // The `num_ctx` ceiling goes through the shared clamp, never restated here:+ // the budgeter that decides how big a prompt to BUILD reads the same module,+ // so the two can no longer disagree about it (#7466).+ return clampToRuntimeContextWindow(provider, planning);}/**diff --git a/server/services/stageRunner.js b/server/services/stageRunner.jsindex 57b7941c32..0955ea1cfd 100644--- a/server/services/stageRunner.js+++ b/server/services/stageRunner.js@@ -29,6 +29,11 @@ import {knownProviderContextWindow,catalogModelContextWindow,} from '../lib/providerContextWindows.js';+// The Ollama `num_ctx` ceiling — the same module the pre-dispatch gate resolves+// it through, so the budgeter and the gate cannot disagree again (#7466). The+// dependency-free `internal/` leaf, not the toolkit barrel: that reaches `fs`+// and `child_process`, and this module is inside the server suite's import budget.+import { clampToRuntimeContextWindow } from '../lib/aiToolkit/internal/ollamaBacked.js';import { createRun, patchRunMetadata } from './runner.js';import { resolveProviderModelTier, MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from '../lib/aiToolkit/constants.js';@@ -197,15 +202,19 @@ const isLikelyLargeContextProvider = (provider) => {return false;};-// Planning-time context window for a provider/model: an explicit-// `contextWindow` wins, else the window the provider's own catalog reported for-// this model, else a known model window for the resolved model, else a known-// provider-level window for configured-default process providers, else the-// Ollama per-request `numCtx`, else a large default for frontier providers,-// else null (the budgeter applies a conservative floor for unknown local-// backends). The rungs themselves live in lib/providerContextWindows.js, the-// pure leaf the browser's provider-card meter shares.-export function effectiveContextWindow(provider, model) {+// Which window this provider/model CLAIMS, before the runtime ceiling: an+// explicit `contextWindow` wins, else the window the provider's own catalog+// reported for this model, else a known model window for the resolved model,+// else a known provider-level window for configured-default process providers,+// else `numCtx`, else a large default for frontier providers, else null (the+// budgeter applies a conservative floor for unknown local backends). The rungs+// themselves live in lib/providerContextWindows.js, the pure leaf the browser's+// provider-card meter shares.+//+// `numCtx` still ends the ladder, but it only DECIDES for a non-Ollama local+// endpoint, where it is a user's hint about a window the endpoint ignores. On+// an Ollama-backed provider the clamp has already bounded every rung above it.+function claimedContextWindow(provider, model) {if (Number(provider?.contextWindow) > 0) return Number(provider.contextWindow);const catalogWindow = catalogModelContextWindow(provider, model);if (catalogWindow) return catalogWindow;@@ -218,6 +227,17 @@ export function effectiveContextWindow(provider, model) {return null;}+/**+ * Planning-time context window for a provider/model — the number the prompt+ * budgeter chunks against: the claimed window held to what the daemon will+ * actually serve. The ceiling bounds every rung, an explicit override included+ * (a user preference the daemon cannot honor past its launch window). See+ * {@link clampToRuntimeContextWindow} for the rule and why it is shared.+ */+export function effectiveContextWindow(provider, model) {+ return clampToRuntimeContextWindow(provider, claimedContextWindow(provider, model));+}+/*** Resolve which provider/model a stage WOULD run against (without executing)* plus its planning context window — for callers that must budget the prompt@@ -257,7 +277,8 @@ export async function resolveStageContext(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.+ // result that is provably discarded. (The `numCtx` ceiling still applies: it+ // reads the provider RECORD, which an observation never touches.)if (Number(provider?.contextWindow) > 0) {return { provider, model, contextWindow: effectiveContextWindow(provider, model) };}diff --git a/server/services/stageRunner.test.js b/server/services/stageRunner.test.jsindex 7e203ca725..f93108e8b6 100644--- a/server/services/stageRunner.test.js+++ b/server/services/stageRunner.test.js@@ -49,6 +49,10 @@ const {} = await import('./stageRunner.js');const { withStagePinsIgnored, stagePinsIgnored } = await import('../lib/stagePinPolicy.js');const { CODEX_CONTEXT_WINDOW, DEFAULT_LARGE_CONTEXT_WINDOW } = await import('../lib/providerContextWindows.js');+// The pre-dispatch gate itself, imported from the toolkit leaf rather than its+// `fs`/`child_process`-reaching barrel: the contract test below asserts the+// budgeter and the gate agree, so it has to ask the real gate.+const { contextWindowRejection, knownContextWindow } = await import('../lib/aiToolkit/providerStatus.js');const apiProvider = (extra = {}) => ({id: 'mock-api', name: 'Mock', type: 'api', enabled: true, defaultModel: 'm-default', ...extra,@@ -57,6 +61,20 @@ const cliProvider = (extra = {}) => ({id: 'codex', name: 'Codex', type: 'cli', enabled: true, defaultModel: 'm-default', timeout: 5000, ...extra,});+// The live `/v1/models` listing `resolveStageContext` budgets against. Module+// scope so the shape of the probe's return value is spelled in ONE place —+// two describes stub it, and a change to the probe should break once.+const serving = (contextWindows) => probeCache.probeOpenAiModelsCached.mockResolvedValue({+ reachable: true,+ models: Object.keys(contextWindows),+ contextWindows,+ error: null,+});++// `vi.clearAllMocks()` clears calls but keeps implementations, so the probe stub+// has to be torn down explicitly or it leaks into later describes.+const resetProbe = () => probeCache.probeOpenAiModelsCached.mockReset();+beforeEach(() => {vi.clearAllMocks();runner.extractBakedModel.mockReturnValue(null);@@ -132,11 +150,31 @@ describe('stageRunner — context windows', () => {)).toBe(64_000);});- it('uses model and provider windows before provider numCtx', () => {+ it('holds every wider rung down to the Ollama numCtx the daemon was launched with', () => {+ // #7466: `numCtx` used to rank LAST, so a model whose declared window is+ // wider than the daemon's launch window was budgeted at the declared one and+ // then refused by the pre-dispatch gate, which had always clamped. It is an+ // upper BOUND, not a fallback rung — including over a typed override, which+ // is a preference the daemon has no way to honor past its launch window.expect(effectiveContextWindow({ type: 'api', endpoint: 'http://localhost:11434/v1', numCtx: 32_768 },'claude-sonnet-4-6'- )).toBe(1_000_000);+ )).toBe(32_768);+ expect(effectiveContextWindow(+ { type: 'api', endpoint: 'http://localhost:11434/v1', numCtx: 8_192, modelContextWindows: { 'qwen3:32b': 40_960 } },+ 'qwen3:32b'+ )).toBe(8_192);+ expect(effectiveContextWindow(+ { type: 'api', endpoint: 'http://localhost:11434/v1', numCtx: 8_192, contextWindow: 64_000 },+ 'unknown-local-model'+ )).toBe(8_192);+ // A ceiling never RAISES a narrower window.+ expect(effectiveContextWindow(+ { type: 'api', endpoint: 'http://localhost:11434/v1', numCtx: 131_072, modelContextWindows: { 'qwen3:32b': 40_960 } },+ 'qwen3:32b'+ )).toBe(40_960);+ // Only Ollama honors the runner's top-level num_ctx; for anything else the+ // field constrains nothing, so the ladder is untouched.expect(effectiveContextWindow({ id: 'codex', type: 'cli', command: 'codex', numCtx: 32_768 },'codex-configured-default'@@ -148,6 +186,12 @@ describe('stageRunner — context windows', () => {{ type: 'api', endpoint: 'http://localhost:11434/v1', numCtx: 32_768 },'unknown-local-model')).toBe(32_768);+ // A non-Ollama local endpoint ignores num_ctx, so it stays a last-resort+ // hint there rather than becoming a ceiling nothing enforces.+ expect(effectiveContextWindow(+ { type: 'api', endpoint: 'http://localhost:1234/v1', numCtx: 32_768 },+ 'unknown-local-model'+ )).toBe(32_768);expect(effectiveContextWindow({ type: 'cli' },'unknown-cli-model'@@ -194,18 +238,7 @@ describe('stageRunner — resolveStageContext reads the live daemon window', ()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,- });+ afterEach(resetProbe);it('budgets to the 32K the daemon is serving, not the 128K assumption', async () => {providers.getActiveProvider.mockResolvedValue(daemonProvider());@@ -277,6 +310,62 @@ describe('stageRunner — resolveStageContext reads the live daemon window', ()});});+// #7466 — the budgeter and the pre-dispatch gate must resolve ONE window. They+// are separate modules (the gate is in the vendored toolkit, which may not+// import out), so nothing but a contract test keeps them from drifting again.+describe('stageRunner — the budget never exceeds what the dispatch gate allows', () => {+ // The reported failure: Ollama launched at 8K, `qwen3:32b`'s own catalog entry+ // 40K. The chunker was told 40,960, built ~32,000 tokens, and the gate threw+ // `known 8192-token context is below the 32000-token request budget` — so the+ // stage never dispatched at all.+ const ollama = apiProvider({+ id: 'ollama',+ endpoint: 'http://localhost:11434/v1',+ defaultModel: 'qwen3:32b',+ models: ['qwen3:32b'],+ numCtx: 8_192,+ modelContextWindows: { 'qwen3:32b': 40_960 },+ });++ beforeEach(() => {+ prompts.getStage.mockReturnValue(null);+ });++ afterEach(resetProbe);++ it('budgets a chunked stage to the daemon\'s launch window instead of building a prompt the gate refuses', async () => {+ providers.getActiveProvider.mockResolvedValue(ollama);+ serving({ 'qwen3:32b': 40_960 });++ const { contextWindow, model } = await resolveStageContext('any-stage');+ expect(contextWindow).toBe(8_192);+ // …and a prompt built to that budget dispatches rather than being refused.+ expect(contextWindowRejection(ollama, model, { requiredContextTokens: contextWindow })).toBeNull();+ });++ it('never plans wider than the gate would admit', () => {+ // Only shapes where the gate DECLARES a window — an unknown one is "no+ // constraint" on both sides and proves nothing. The count assertion is the+ // point: without it a future ladder change that made every shape unknown+ // would leave this passing with zero comparisons.+ const shapes = [+ ollama,+ { ...ollama, modelContextWindows: undefined, contextWindow: 64_000 },+ { id: 'ollama', type: 'api', enabled: true, numCtx: 16_000, contextWindow: 128_000 },+ { type: 'tui', command: 'opencode', modelContextWindows: { 'qwen3:32b': 40_960 } },+ ];+ const compared = shapes.filter((provider) => {+ const admitted = knownContextWindow(provider, 'qwen3:32b');+ expect(admitted, `the gate declares no window for ${JSON.stringify(provider)}`).toBeGreaterThan(0);+ expect(effectiveContextWindow(provider, 'qwen3:32b'),+ `budgeted wider than the gate admits for ${JSON.stringify(provider)}`)+ .toBeLessThanOrEqual(admitted);+ return true;+ });+ expect(compared).toHaveLength(shapes.length);+ });+});+describe('stageRunner — extractJson', () => {it('parses JSON inside markdown code fences', () => {expect(extractJson('```json\n{"a":1}\n```')).toEqual({ a: 1 });