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

import the provider registries from server/lib instead of copying them into client/src/utils

[._.]/ Adam Eivyc82dcdf3a723
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e357bf6ce6..af5105970c 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -14,8 +14,8 @@ direction: nothing under `server/` may import from `client/`, because a client-o
dependency added to such a file breaks the server CI job. A server module the client
imports must reach no Node built-in and nothing outside `server/lib`; when the natural
home does (`storyBible.js` pulls `crypto`), split the pure part into its own leaf.
-`server/lib/importGraphPurity.test.js` and `server/serverImportsNoClient.test.js` enforce
-both halves.
+`scripts/client-server-import-purity.test.js` and `scripts/server-imports-no-client.test.js`
+enforce both halves.
## Discovery rule
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 1bb0ee30d4..7b65094038 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -49,19 +49,19 @@ grep -i "what you want to do" client/src/utils/README.md
Provider helpers are split by the question each answers; `providers.js` is the compatibility
facade over all of them. Grep here for the question, then import the declaring module — that
-is where the server parity tests pin each browser mirror.
+is where each shared table is re-exported from its `server/lib` leaf.
| Module | Purpose |
|---|---|
| `providers` | Compatibility facade re-exporting every helper from the nine modules below, so existing `../utils/providers` imports keep working. New code imports the declaring module. |
| `providerTypes` | What KIND of provider a record is: `PROVIDER_TYPES` (mirror of `server/lib/aiToolkit/constants.js`) with `isCliProvider` / `isTuiProvider` / `isApiProvider` / `isProcessProvider`, `isLaunchableTuiProvider` (a TUI provider carrying the server-resolved `tuiCommandLine`, i.e. one a human can start at a shell prompt — shared by the Providers card's "Launch in Shell" button and the Shell page's launch menu so the two can't disagree), `enabledApiProviderFilter`, `enabledProcessProviderFilter` (the coding/CLI-TUI-only counterpart, for a manual Claim/Replan/Resolve/Review "Run with" picker), `providerTypeClass`; the vendor-harness predicates keyed on the shipped ids plus `commandBasename` so a path-configured or renamed binary still qualifies (`isCodexProvider`, `isCodexSubscriptionProvider` — subscription readiness is keyed on the `codex` command, never an editable id — `isAntigravityProvider`, `isCursorProvider`, `isKimiProvider`, `isGrokProvider`, `isGrokBuildCli`, `isClaudeCommandProvider`, `isOpencodeLocalProvider`); and the structural backend markers a wrapper carries (`localRuntimeNamespace`, `isOllamaBackedProvider`). Mirror of the same predicates in `server/lib/providerModels.js`. |
-| `providerGateways` | `PROVIDER_GATEWAYS` / `gatewayForProvider` / `isGatewayBackedProvider` — the hosted OpenAI-compatible gateways (`orcarouter`, `openrouter`) an OpenCode CLI/TUI wrapper can front-end, inheriting its API key at spawn time from the sibling API provider whose id equals the gateway id. Reads the generic `gatewayBacked` marker and, forever, the legacy per-gateway boolean. MIRROR of `server/lib/providerGateways.js`, which the browser cannot import; `server/lib/providerGateways.parity.test.js` reads this file as text and fails when the copies drift. |
-| `providerHarnesses` | `PROVIDER_HARNESS_LABELS` / `harnessLabel(harnessId)` — display names for the agent programs PortOS drives (Claude Code, OpenCode, Codex, …), used by the connection-management UI, where `null` means Direct API and an unknown id renders verbatim rather than disappearing. MIRROR of `PROVIDER_HARNESSES` in `server/lib/providerHarnesses.js`, which the browser cannot import; `server/lib/providerHarnesses.parity.test.js` reads this file as text and fails when the copies drift. |
+| `providerGateways` | `PROVIDER_GATEWAYS` / `gatewayForProvider` / `isGatewayBackedProvider` — the hosted OpenAI-compatible gateways (`orcarouter`, `openrouter`) an OpenCode CLI/TUI wrapper can front-end, inheriting its API key at spawn time from the sibling API provider whose id equals the gateway id. Reads the generic `gatewayBacked` marker and, forever, the legacy per-gateway boolean. All three are re-exported from the pure leaf `server/lib/providerGateways.js`. |
+| `providerHarnesses` | `harnessLabel(harnessId)` — the display name for an agent program PortOS drives (Claude Code, OpenCode, Codex, …), used by the connection-management UI, where `null` means Direct API and an unknown id renders verbatim rather than disappearing. Read through `harnessById` from the pure leaf `server/lib/providerHarnesses.js`, so a harness added to the registry is named here without a second edit. |
| `providerEndpoints` | WHERE a provider's endpoint points. `isLocalEndpoint` (loopback), `isPrivateNetworkEndpoint` (RFC1918 / tailnet address, or a `.local` / `.ts.net` / single-label host — somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key), `isLocalInstanceProvider` (talks to a daemon on THIS machine; mirror of `server/lib/localProviderRuntime.js#isLocalInstanceEndpoint` — gate anything that explains a provider by inspecting the host PortOS runs on), `isFleetProvider` / `isFleetHostConfigured` (another machine inside the private network), and `localBackendForProvider` (`'ollama'` / `'lmstudio'` / `null` by id, endpoint or name — it matches by NAME, so pair it with `isLocalInstanceProvider` before claiming this machine's install state). |
-| `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). Mirror of `server/lib/providerModels.js` (and `server/lib/opencodeConfig.js` for the controls); `server/lib/providerModels.mirror.test.js` reads this file as text and fails when a mirrored declaration drifts. |
-| `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 mirror (`CALLER_MODE_POLICY_MODES`, `callerModeList`, `providerModeSelectionPolicy`) of `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 (parity: `providerModePolicy.parity.test.js`). |
-| `localModelHeuristics` | What an untyped LOCAL model can do, judged from its id: `isEmbeddingModel` / `isVisionModel` / `isToolUseModel` (regexes mirrored from `server/lib/localModelHeuristics.js`; `server/lib/localModelHeuristics.mirror.test.js` reads this file as text and fails when a pattern stops matching the same ids), `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)"). Mirror of the ladder in `server/services/stageRunner.js`; `server/services/stageRunner.mirror.test.js` reads this file as text and fails when the two resolve differently. |
+| `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. |
| `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/localModelHeuristics.js b/client/src/utils/localModelHeuristics.js
index 393c1de652..ca46ef0b5d 100644
--- a/client/src/utils/localModelHeuristics.js
+++ b/client/src/utils/localModelHeuristics.js
@@ -4,10 +4,11 @@
* the union with the backend's own capability report where the server could
* probe one (`useToolUseModelIds` / `useVisionModelIds`).
*
- * Browser MIRROR of `server/lib/localModelHeuristics.js` — the regexes are
- * inlined here because the browser cannot import server code, and
- * `server/lib/localModelHeuristics.mirror.test.js` reads this file as TEXT and
- * fails when a pattern stops matching the same ids as the server's.
+ * The family predicates (`isEmbeddingModel` / `isVisionModel` /
+ * `isToolUseModel`) are re-exported from the pure leaf
+ * `server/lib/localModelHeuristics.js`. They take a bare id string (the case
+ * every caller here has) or a model card, whose explicit capability metadata
+ * outranks the id regex.
*
* Re-exported by `./providers.js` for existing `utils/providers` imports.
*/
@@ -15,46 +16,17 @@
import { isLocalInstanceProvider, localBackendForProvider } from './providerEndpoints.js';
import { filterSelectableModels } from './providerModels.js';
import { commandBasename, isOllamaBackedProvider } from './providerTypes.js';
+import { isEmbeddingModel, isToolUseModel, isVisionModel } from '../../../server/lib/localModelHeuristics.js';
-/**
- * Embedding-only model detector — mirror of `isEmbeddingModel` in
- * server/lib/localModelHeuristics.js. Keep the two regexes in lockstep (the
- * server lib can't be imported here). Used to keep embedding models (e.g.
- * `nomic-embed-text`) out of generation/chat model pickers.
- * @param {string} id
- * @returns {boolean}
- */
-export const isEmbeddingModel = (id) =>
- typeof id === 'string' && id.length > 0 &&
- // Mirror of EMBEDDING_RE in server/lib/localModelHeuristics.js — keep in lockstep.
- // `embeddinggemma` needs its own alternative: the anchored `embedding` marker
- // requires a separator after it, and that id glues the family straight on.
- // `minilm` / `paraphrase-multilingual` carry no `embed` marker at all —
- // `all-minilm` and `paraphrase-multilingual` are Ollama embedding models that
- // would otherwise be offered in a chat/generation picker.
- /(?:^|[-_/:])(?:embed|embedding|bge|nomic|mxbai|gte|e5|snowflake-arctic-embed)(?:[-_/:]|$)|text-embedding|embeddinggemma|minilm|paraphrase-multilingual/i.test(id);
-
-/**
- * Vision-capable (multimodal) model detector — mirror of `isVisionModel` in
- * server/lib/localModelHeuristics.js (id-regex branch only). Keep the regex in
- * lockstep with the server. Used to flag/select vision models in the LoRA
- * caption picker. The server prefers explicit backend capability metadata
- * (`vision: true` on the model card); use that field when you have it and fall
- * back to this for bare id strings.
- * @param {string} id
- * @returns {boolean}
- */
-export const isVisionModel = (id) =>
- typeof id === 'string' && id.length > 0 &&
- // Mirror of VISION_RE in server/lib/localModelHeuristics.js — keep in lockstep.
- /(?:^|[-_/:])vision(?:[-_/:.]|$)|(?:^|[-_/:])vl(?:\d|[-_/:.]|$)|qwen[\d.]*-?vl|(?:^|[-_/:])gemma-?[34]|llava|bakllava|moondream|minicpm-?v|pixtral|smolvlm|internvl|cogvlm|glm-?4v|phi-?3\.5?-vision|phi-?4-multimodal|got-ocr|idefics|fuyu|paligemma|kosmos|nanollava/i.test(id);
+export { isEmbeddingModel, isToolUseModel, isVisionModel } from '../../../server/lib/localModelHeuristics.js';
/**
* Whether a CLI-type provider can read an image file (its CLI accepts a
- * vision attachment). Mirror of `isVisionCapableCliProvider` in
- * server/lib/localModelHeuristics.js — keyed on command basename so a
- * renamed/path-configured Claude or Codex still qualifies. API providers
- * return false here; use `visionLocalModelFilter` for their model lists.
+ * vision attachment). The client's own take on `isVisionCapableCliProvider`
+ * in server/lib/localModelHeuristics.js: keyed on the command basename so a
+ * path-configured Claude or Codex still qualifies here, where the server
+ * matches the bare command exactly. API providers return false; use
+ * `visionLocalModelFilter` for their model lists.
* @param {{type?:string, command?:string}|null|undefined} provider
* @returns {boolean}
*/
@@ -62,23 +34,6 @@ export const isVisionCapableCliProvider = (provider) =>
provider?.type === 'cli'
&& (commandBasename(provider.command) === 'codex' || commandBasename(provider.command) === 'claude');
-/**
- * Tool-use (function-calling) capable model detector — mirror of `isToolUseModel`
- * in server/lib/localModelHeuristics.js (and the TOOL_USE_RE inlined in
- * server/lib/aiToolkit/providers.js). Keep all three in lockstep (the server libs
- * can't be imported here) — server/lib/localModelHeuristics.mirror.test.js reads
- * this file as text and fails when the patterns stop matching the same ids. Ollama's /api/show `tools` capability is authoritative
- * when known; this id regex is the fallback for bare model-id strings. The CoS
- * agent harness depends on reliable tool-calling, so only these families should
- * be selectable for a local-model-backed coding provider.
- * @param {string} id
- * @returns {boolean}
- */
-export const isToolUseModel = (id) =>
- typeof id === 'string' && id.length > 0 &&
- // Mirror of TOOL_USE_RE in server/lib/localModelHeuristics.js — keep in lockstep.
- /qwen|llama-?3\.[1-9]|llama-?4|mistral|mixtral|ministral|codestral|devstral|magistral|command-?r|command-?a|north-mini-code|firefunction|functionary|watt-tool|hermes|functiongemma|glm-?4|granite-?[34]|(?:^|[-_/:])gemma-?4|gpt-oss|nemotron|olmo-?3|lfm2|ornith|muse-glimmer|nex-n2|smollm2|dflash|deepseek-v3|deepseek-r1|deepseek-v4/i.test(id);
-
/**
* Agent-picker tool-use annotation for a model id. Agent / CoS tasks (the CD
* treatment + plan stages, coding agents) only work with a model that can emit
diff --git a/client/src/utils/providerContextWindows.js b/client/src/utils/providerContextWindows.js
index 252b0949da..6a5c297ad6 100644
--- a/client/src/utils/providerContextWindows.js
+++ b/client/src/utils/providerContextWindows.js
@@ -3,61 +3,38 @@
* number came from (a user override, a reported window, or a ladder guess the
* card must label as assumed) — plus the "(32K ctx)" option label built on it.
*
- * Browser MIRROR of the context-window ladder in `server/services/stageRunner.js`
- * (`KNOWN_MODEL_CONTEXT_WINDOWS`, the vendor constants, `catalogModelContextWindow`,
- * `effectiveContextWindow`) — the two must resolve identically or the card
- * promises a budget the budgeter won't use. `server/services/stageRunner.mirror.test.js`
- * reads this file as TEXT and fails when they drift.
+ * The rungs — the vendor constants, the known-model table, the per-provider
+ * fallback and the catalog read — 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
+ * number came from; it and `isLikelyLargeContextProvider` are what can still
+ * 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`.
*
* Re-exported by `./providers.js` for existing `utils/providers` imports.
*/
import { formatContextLength } from './formatters.js';
import { isLocalEndpoint } from './providerEndpoints.js';
-import { commandBasename, isApiProvider, isCodexProvider, isProcessProvider } from './providerTypes.js';
+import { isApiProvider, isProcessProvider } from './providerTypes.js';
+import {
+ DEFAULT_LARGE_CONTEXT_WINDOW,
+ catalogModelContextWindow,
+ knownModelContextWindow,
+ knownProviderContextWindow,
+} from '../../../server/lib/providerContextWindows.js';
-export const DEFAULT_LARGE_CONTEXT_WINDOW = 128_000;
-
-export const CODEX_CONTEXT_WINDOW = 1_000_000;
-
-export const GEMINI_CONTEXT_WINDOW = 1_048_576;
-
-export const GROK_CONTEXT_WINDOW = 256_000;
-
-export const KIMI_CONTEXT_WINDOW = 256_000;
-
-// Keep in sync with server/services/stageRunner.js.
-const KNOWN_MODEL_CONTEXT_WINDOWS = Object.freeze([
- [/gpt[-_.:/]?5\.5(?:[-_.:/]|\b)/i, CODEX_CONTEXT_WINDOW],
- [/gpt[-_.:/]?5\.4[-_.:/]?mini(?:[-_.:/]|\b)/i, 400_000],
- [/gpt[-_.:/]?5\.4(?![-_.:/]?(?:mini|nano))(?:[-_.:/]|\b)/i, CODEX_CONTEXT_WINDOW],
- [/claude[-_.:/]?fable[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
- [/claude[-_.:/]?mythos[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
- [/claude[-_.:/]?opus[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
- [/claude[-_.:/]?opus[-_.:/]?4[-_.:/]?8/i, 1_000_000],
- [/claude[-_.:/]?sonnet[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
- [/claude[-_.:/]?sonnet[-_.:/]?4[-_.:/]?6(?:[-_.:/]|\b)/i, 1_000_000],
- [/claude[-_.:/]?sonnet[-_.:/]?4(?:[-_.:/]|\b)/i, 200_000],
- [/claude[-_.:/]?haiku[-_.:/]?4(?:[-_.:/]|\b)/i, 200_000],
- [/gemini[-_.:/]?2\.5[-_.:/]?pro(?:[-_.:/]|\b)/i, GEMINI_CONTEXT_WINDOW],
-]);
-
-export const knownModelContextWindow = (model) => {
- if (typeof model !== 'string' || !model.trim()) return null;
- const found = KNOWN_MODEL_CONTEXT_WINDOWS.find(([pattern]) => pattern.test(model));
- return found ? found[1] : null;
-};
-
-export const knownProviderContextWindow = (provider) => {
- if (!isProcessProvider(provider)) return null;
- const id = String(provider?.id || '').toLowerCase();
- const command = commandBasename(provider?.command);
- if (isCodexProvider(provider)) return CODEX_CONTEXT_WINDOW;
- if (id === 'antigravity-cli' || id === 'antigravity-tui' || command === 'agy') return GEMINI_CONTEXT_WINDOW;
- if (id === 'grok-cli' || id === 'grok-tui' || command === 'grok') return GROK_CONTEXT_WINDOW;
- if (id === 'kimi-cli' || id === 'kimi-tui' || command === 'kimi') return KIMI_CONTEXT_WINDOW;
- return null;
-};
+export {
+ DEFAULT_LARGE_CONTEXT_WINDOW,
+ CODEX_CONTEXT_WINDOW,
+ GEMINI_CONTEXT_WINDOW,
+ GROK_CONTEXT_WINDOW,
+ KIMI_CONTEXT_WINDOW,
+ knownModelContextWindow,
+ knownProviderContextWindow,
+ catalogModelContextWindow,
+} from '../../../server/lib/providerContextWindows.js';
export const isLikelyLargeContextProvider = (provider) => {
if (isProcessProvider(provider)) return true;
@@ -83,24 +60,12 @@ export const CONTEXT_WINDOW_SOURCE = Object.freeze({
ASSUMED: 'assumed',
});
-/**
- * The window this provider's own `/models` catalog reported for this model, or
- * `null` when it never mentioned it. Recorded by model refresh — the serving
- * side's own declaration, so it outranks the hand-maintained regex table.
- * Mirror of `catalogModelContextWindow` in server/services/stageRunner.js.
- */
-export function catalogModelContextWindow(provider, model) {
- const windows = provider?.modelContextWindows;
- if (!windows || typeof windows !== 'object') return null;
- if (typeof model !== 'string' || !model) return null;
- const tokens = Number(windows[model]);
- return Number.isFinite(tokens) && tokens > 0 ? tokens : null;
-}
-
/**
* The planning context window for a provider/model AND where it came from.
- * Mirror of `effectiveContextWindow` in server/services/stageRunner.js — the two
- * must resolve identically, or the card promises a budget the budgeter won't use.
+ * Walks the same rungs, in the same order, as `effectiveContextWindow` 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.
diff --git a/client/src/utils/providerGateways.js b/client/src/utils/providerGateways.js
index 8ed005ff60..1696b2c0c8 100644
--- a/client/src/utils/providerGateways.js
+++ b/client/src/utils/providerGateways.js
@@ -2,49 +2,15 @@
* The hosted OpenAI-compatible gateways an OpenCode CLI/TUI wrapper can front-end,
* and which one a given provider record is marked as fronting.
*
- * Browser MIRROR of `server/lib/providerGateways.js` (and its vendored twin
- * `server/lib/aiToolkit/internal/gateways.js`) — the browser cannot import server
- * code, so the registry is duplicated and `server/lib/providerGateways.parity.test.js`
- * reads this file as TEXT to pin the copies together.
+ * The registry and its predicates are re-exported from the pure leaf
+ * `server/lib/providerGateways.js`. Each row's `id` is simultaneously the
+ * OpenCode namespace, the `gatewayBacked` marker value, and the id of the
+ * sibling `api` record that owns the key; the wrappers themselves deliberately
+ * carry NO key (`server/lib/aiToolkit/providers.js` `withGatewayApiKey`
+ * attaches the sibling's at spawn time), so the one place a user pastes it is
+ * that API provider, not the wrapper form.
*
* Re-exported by `./providers.js` for existing `utils/providers` imports.
*/
-/**
- * The hosted OpenAI-compatible gateways an OpenCode CLI/TUI wrapper can
- * front-end. MIRROR of `PROVIDER_GATEWAYS` in `server/lib/providerGateways.js`
- * (and its vendored twin `server/lib/aiToolkit/internal/gateways.js`) — the
- * browser cannot import server code, so the table is duplicated; keep the three
- * in lockstep (server/lib/providerGateways.parity.test.js pins this copy's
- * `id`/`label`/`apiKeyEnv`/`legacyMarker` rows against the server registry). `id` is simultaneously the OpenCode namespace, the
- * `gatewayBacked` marker value, and the id of the sibling `api` record that
- * owns the key.
- */
-export const PROVIDER_GATEWAYS = Object.freeze([
- Object.freeze({ id: 'orcarouter', label: 'OrcaRouter', apiKeyEnv: 'ORCAROUTER_API_KEY', legacyMarker: 'orcarouterBacked' }),
- Object.freeze({ id: 'openrouter', label: 'OpenRouter', apiKeyEnv: 'OPENROUTER_API_KEY' }),
-]);
-
-/**
- * The gateway an OpenCode wrapper front-ends, or null (the shipped
- * `opencode-<gateway>` / `-tui` presets, or any renamed wrapper carrying the
- * marker).
- *
- * These wrappers deliberately carry NO key of their own: at spawn time the
- * server attaches the key from the sibling API provider whose id equals the
- * gateway id (`server/lib/aiToolkit/providers.js` `withGatewayApiKey`), so the
- * one place a user actually pastes the key is that API provider, not this form.
- * Reads the generic `gatewayBacked` marker first, then the legacy per-gateway
- * boolean — MIRROR of `gatewayForProvider` on the server; keep in lockstep with
- * `server/lib/providerModels.js#getOpencodeLocalProviderNamespace`.
- * @param {{id?:string,gatewayBacked?:string,orcarouterBacked?:boolean}|null|undefined} provider
- */
-export const gatewayForProvider = (provider) => {
- if (!provider || typeof provider !== 'object') return null;
- const declared = PROVIDER_GATEWAYS.find((g) => g.id === provider.gatewayBacked);
- if (declared) return declared;
- return PROVIDER_GATEWAYS.find((g) => g.legacyMarker && provider[g.legacyMarker] === true) || null;
-};
-
-/** True when a provider is an OpenCode wrapper front-ending any hosted gateway. */
-export const isGatewayBackedProvider = (provider) => gatewayForProvider(provider) !== null;
+export { PROVIDER_GATEWAYS, gatewayForProvider, isGatewayBackedProvider } from '../../../server/lib/providerGateways.js';
diff --git a/client/src/utils/providerHarnesses.js b/client/src/utils/providerHarnesses.js
index 2f6fc138d8..a4a98b96eb 100644
--- a/client/src/utils/providerHarnesses.js
+++ b/client/src/utils/providerHarnesses.js
@@ -1,30 +1,16 @@
/**
* The agent programs PortOS drives, as the browser needs to name them.
*
- * Browser MIRROR of `PROVIDER_HARNESSES` in `server/lib/providerHarnesses.js`
- * — the browser cannot import server code, so the id→label table is duplicated
- * and `server/lib/providerHarnesses.parity.test.js` reads this file as TEXT to
- * pin the two together.
- *
- * Only `id → label` is mirrored, and deliberately so. The server registry's
- * other columns are all decided server-side and arrive on the wire already
- * resolved: `matches` classifies a provider RECORD (the browser is handed a
- * `harnessId`), `modes` is already reflected by the routes a binding actually
- * owns, and `protocol` is a transport decision no picker makes. Mirroring them
- * would create three more things to drift for no rendered difference.
+ * Read straight off `PROVIDER_HARNESSES` in `server/lib/providerHarnesses.js`
+ * through `harnessById`, so a harness added to the registry is named here
+ * without a second edit. Only the label is read: the registry's other columns
+ * are decided server-side and arrive on the wire already resolved — `matches`
+ * classifies a provider RECORD (the browser is handed a `harnessId`), `modes`
+ * is already reflected by the routes a binding actually owns, and `protocol`
+ * is a transport decision no picker makes.
*/
-/** id → display label. MIRROR of the server registry; keep in lockstep. */
-export const PROVIDER_HARNESS_LABELS = Object.freeze({
- claude: 'Claude Code',
- opencode: 'OpenCode',
- codex: 'Codex',
- antigravity: 'Antigravity',
- cursor: 'Cursor Agent',
- grok: 'Grok',
- kimi: 'Kimi Code',
- pi: 'Pi',
-});
+import { harnessById } from '../../../server/lib/providerHarnesses.js';
/**
* What to call a binding's harness.
@@ -36,5 +22,5 @@ export const PROVIDER_HARNESS_LABELS = Object.freeze({
*/
export const harnessLabel = (harnessId) => {
if (harnessId === null || harnessId === undefined) return 'Direct API';
- return PROVIDER_HARNESS_LABELS[harnessId] || harnessId;
+ return harnessById(harnessId)?.label || harnessId;
};
diff --git a/client/src/utils/providerModePolicy.parity.test.js b/client/src/utils/providerModePolicy.test.js
similarity index 53%
rename from client/src/utils/providerModePolicy.parity.test.js
rename to client/src/utils/providerModePolicy.test.js
index 97d8a4ae93..5b88e57ced 100644
--- a/client/src/utils/providerModePolicy.parity.test.js
+++ b/client/src/utils/providerModePolicy.test.js
@@ -1,20 +1,14 @@
import { describe, it, expect } from 'vitest';
-import { CALLER_MODE_POLICIES } from '../../../server/lib/callerModePolicy.js';
-import { CALLER_MODE_POLICY_MODES, callerModeList, providerModeSelectionPolicy } from './providerSelection.js';
+import { callerModeList, providerModeSelectionPolicy } from './providerSelection.js';
/**
- * The browser mirror only decides what a PICKER offers; the server decides what
- * actually runs. They must agree, or a user saves a route the server refuses at
- * spawn time (or, worse, the picker hides a route the server would happily run).
+ * The picker-side policy only decides what a PICKER offers; the server decides
+ * what actually runs. The mode table is derived from the server's
+ * `CALLER_MODE_POLICIES` directly, so what remains to pin is the picker's own
+ * behaviour on top of it: an unknown policy fails closed, and a known one offers
+ * exactly its modes.
*/
-describe('caller execution-mode policy — client/server parity', () => {
- it('mirrors every server policy, name for name and mode for mode', () => {
- expect(Object.keys(CALLER_MODE_POLICY_MODES).sort()).toEqual(Object.keys(CALLER_MODE_POLICIES).sort());
- for (const [id, { allowedModes }] of Object.entries(CALLER_MODE_POLICIES)) {
- expect(CALLER_MODE_POLICY_MODES[id]).toEqual([...allowedModes]);
- }
- });
-
+describe('caller execution-mode policy — picker selection', () => {
it('permits nothing for an unknown policy name rather than everything', () => {
// Fail-closed in the same direction as the server, which throws: a typo has
// to be visible, never a silently permissive picker.
diff --git a/client/src/utils/providerModels.js b/client/src/utils/providerModels.js
index 23dd8b7a14..768dbca600 100644
--- a/client/src/utils/providerModels.js
+++ b/client/src/utils/providerModels.js
@@ -7,42 +7,46 @@
* and which generation controls (temperature / top-p / thinking) a provider
* forwards at all.
*
- * Browser MIRROR of `server/lib/providerModels.js` (sentinels, effort ladders,
- * `EFFORT_RANK`, the Antigravity split, `resolveCliEffort`) and of the
- * generation-control tables in `server/lib/opencodeConfig.js` /
- * `server/lib/aiToolkit/internal/generationOptions.js`.
- * `server/lib/providerModels.mirror.test.js` reads this file as TEXT and fails
- * when a mirrored declaration drifts. Helpers marked CLIENT-ONLY are rendering
- * concerns with no server twin.
+ * 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 one rung the browser
+ * needs — the ladder the server publishes on a sanitized provider inventory.
+ * The generation-control tables still mirror `server/lib/opencodeConfig.js` /
+ * `server/lib/aiToolkit/internal/generationOptions.js`. Helpers marked
+ * CLIENT-ONLY are rendering concerns with no server twin.
*
* Re-exported by `./providers.js` for existing `utils/providers` imports.
*/
import { isGatewayBackedProvider } from './providerGateways.js';
-import { commandBasename, isAntigravityProvider, isClaudeCommandProvider, isCodexProvider, isCodexSubscriptionProvider, isCursorProvider, isGrokProvider, isOllamaBackedProvider, isOpencodeLocalProvider } from './providerTypes.js';
-
-/**
- * Sentinel value used by the Codex provider to indicate the model is configured
- * via ~/.codex/config.toml rather than PortOS. Filter this out of selectable
- * model lists so the UI shows the explanatory note instead of a token dropdown.
- */
-export const CODEX_CONFIGURED_DEFAULT = 'codex-configured-default';
-
-export const ANTIGRAVITY_CONFIGURED_DEFAULT = 'antigravity-configured-default';
-
-export const GROK_CONFIGURED_DEFAULT = 'grok-configured-default';
-
-export const KIMI_CONFIGURED_DEFAULT = 'kimi-configured-default';
-
-const CONFIGURED_DEFAULT_SENTINELS = new Set([
+import { isAntigravityProvider, isClaudeCommandProvider, isCodexSubscriptionProvider, isOllamaBackedProvider } from './providerTypes.js';
+import {
+ antigravityBaseModels,
+ clampEffortToLadder,
+ effortLevelsForProvider as serverEffortLevelsForProvider,
+ filterSelectableModels,
+ isConfiguredDefaultModel,
+ splitAntigravityModel,
+} from '../../../server/lib/providerModels.js';
+
+export {
CODEX_CONFIGURED_DEFAULT,
ANTIGRAVITY_CONFIGURED_DEFAULT,
GROK_CONFIGURED_DEFAULT,
KIMI_CONFIGURED_DEFAULT,
-]);
-
-/** True for any provider "use CLI's own default" sentinel. Mirror of server `isConfiguredDefaultModel`. */
-export const isConfiguredDefaultModel = (model) => CONFIGURED_DEFAULT_SENTINELS.has(model);
+ isConfiguredDefaultModel,
+ filterSelectableModels,
+ CLAUDE_EFFORT_LEVELS,
+ CODEX_EFFORT_LEVELS,
+ CODEX_ULTRA_EFFORT_LEVELS,
+ ANTIGRAVITY_EFFORT_LEVELS,
+ OPENCODE_LOCAL_EFFORT_LEVELS,
+ CURSOR_EFFORT_LEVELS,
+ GROK_EFFORT_LEVELS,
+ splitAntigravityModel,
+ antigravityBaseModels,
+ antigravityModelEffortLevels,
+} from '../../../server/lib/providerModels.js';
/**
* The configured-default sentinel carried in a provider's model list, or null.
@@ -61,138 +65,6 @@ export const isConfiguredDefaultModel = (model) => CONFIGURED_DEFAULT_SENTINELS.
export const configuredDefaultIn = (models) =>
(models || []).find(isConfiguredDefaultModel) || null;
-/**
- * Returns the provider's model list with internal sentinel values removed.
- * Use this anywhere a list of user-selectable models is needed.
- * @param {string[]} models
- * @returns {string[]}
- */
-export const filterSelectableModels = (models) =>
- (models || []).filter(m => !isConfiguredDefaultModel(m));
-
-/**
- * Reasoning-effort levels per effort-capable CLI — MIRROR of
- * `CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` /
- * `effortLevelsForProvider` in server/lib/providerModels.js; keep in lockstep.
- * Claude Code and agy take `--effort <level>`, Codex takes
- * `-c model_reasoning_effort=<level>`.
- *
- * Codex's config enum includes `max` alongside
- * `none|minimal|low|medium|high|xhigh`. Sol and Terra additionally advertise
- * `ultra`, which adds automatic task delegation; older models and Luna top out
- * at `max`.
- */
-export const CLAUDE_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
-
-export const CODEX_EFFORT_LEVELS = Object.freeze(['minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
-
-export const CODEX_ULTRA_EFFORT_LEVELS = Object.freeze([...CODEX_EFFORT_LEVELS, 'ultra']);
-
-export const ANTIGRAVITY_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high']);
-
-// OpenCode passes this through as `reasoningEffort` to its configured local
-// provider. The OpenAI-compatible local backends accept this narrow ladder for
-// thinking models; the broader vendor-CLI ladders are not portable here.
-export const OPENCODE_LOCAL_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high']);
-
-// Cursor Agent. MIRROR of `CURSOR_EFFORT_LEVELS`. Cursor takes NO `--effort`
-// flag — the server folds the level into the model id as Cursor's own variant
-// syntax (`gpt-5[effort=max]`) — but the level is still user-pickable, so this
-// ladder drives the same selects as every other CLI's.
-export const CURSOR_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
-
-// Grok Build CLI. MIRROR of `GROK_EFFORT_LEVELS` in server/lib/providerModels.js.
-// Grok's own ladder, read off its rejection message rather than guessed
-// (`use one of: xhigh, high, medium, low`) — no `max`/`minimal`, so a stored
-// `max` clamps to `xhigh` here exactly as it does on the server.
-export const GROK_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhigh']);
-
-const CODEX_ULTRA_MODELS = new Set(['gpt-5.6', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-6-astra']);
-
-// MIRROR of `CODEX_NO_MINIMAL_MODEL_RE` in server/lib/providerModels.js. The
-// gpt-6 family dropped the `minimal` rung and answers HTTP 400
-// `unsupported_value` when it is sent, so the picker must not offer it. Matched
-// as a family prefix so a new gpt-6/7 model doesn't reintroduce the 400.
-const CODEX_NO_MINIMAL_MODEL_RE = /^gpt-[6-9]([.-]|$)/;
-
-const withoutMinimal = (levels) => Object.freeze(levels.filter((l) => l !== 'minimal'));
-const CODEX_EFFORT_LEVELS_NO_MINIMAL = withoutMinimal(CODEX_EFFORT_LEVELS);
-const CODEX_ULTRA_EFFORT_LEVELS_NO_MINIMAL = withoutMinimal(CODEX_ULTRA_EFFORT_LEVELS);
-
-const codexEffortLevelsForModel = (model) => {
- const id = String(model || '').trim().toLowerCase();
- const ultra = CODEX_ULTRA_MODELS.has(id);
- if (CODEX_NO_MINIMAL_MODEL_RE.test(id)) {
- return ultra ? CODEX_ULTRA_EFFORT_LEVELS_NO_MINIMAL : CODEX_EFFORT_LEVELS_NO_MINIMAL;
- }
- return ultra ? CODEX_ULTRA_EFFORT_LEVELS : CODEX_EFFORT_LEVELS;
-};
-
-/**
- * Antigravity base-model ↔ effort-suffix split — MIRROR of
- * `splitAntigravityModel` / `antigravityBaseModels` / `antigravityModelEffortLevels`
- * in server/lib/providerModels.js; keep in lockstep.
- *
- * `agy models` enumerates the effort tiers as separate model ids
- * (`gemini-3.6-flash-low|-medium|-high`), which forces the effort choice into
- * the model dropdown. agy also accepts the BASE id with a separate `--effort`
- * flag, so PortOS lists base models and carries effort as its own control. agy
- * validates the PAIR, though (`gemini-3.1-pro` has no `medium`), so the tiers a
- * base model offers come from the provider's own catalog.
- */
-const ANTIGRAVITY_EFFORT_SUFFIX_RE = new RegExp(`-(${ANTIGRAVITY_EFFORT_LEVELS.join('|')})$`);
-
-/**
- * `gemini-3.6-flash-high` → `{ base: 'gemini-3.6-flash', effort: 'high' }`.
- * Unsuffixed ids, sentinels and non-strings → `{ base: <input>, effort: null }`.
- * @param {string|null|undefined} id
- * @returns {{base: string|null|undefined, effort: string|null}}
- */
-export const splitAntigravityModel = (id) => {
- if (typeof id !== 'string' || id === '' || isConfiguredDefaultModel(id)) return { base: id, effort: null };
- const match = ANTIGRAVITY_EFFORT_SUFFIX_RE.exec(id);
- return match ? { base: id.slice(0, -match[0].length), effort: match[1] } : { base: id, effort: null };
-};
-
-/**
- * The user-selectable view of an Antigravity model list: effort suffixes
- * stripped, duplicates collapsed, order preserved. Sentinels and non-string
- * (`{ id, name }`) entries ride through untouched.
- * @param {unknown[]} models
- * @returns {unknown[]}
- */
-export const antigravityBaseModels = (models) => {
- const out = [];
- const seen = new Set();
- for (const entry of Array.isArray(models) ? models : []) {
- if (typeof entry !== 'string') { out.push(entry); continue; }
- const { base } = splitAntigravityModel(entry);
- if (seen.has(base)) continue;
- seen.add(base);
- out.push(base);
- }
- return out;
-};
-
-/**
- * The effort tiers an Antigravity base model offers per the provider's catalog:
- * the present suffixes, `[]` when the model has none, or `null` when the MODEL
- * is unknown — blank, the configured-default sentinel, or an empty catalog — so
- * the caller falls back to the full ladder. The sentinel case matters: it is the
- * shipped agy `defaultModel`, and reporting `[]` for it would hide the effort
- * control on every freshly-opened picker.
- * @param {string|null|undefined} model
- * @param {unknown[]} models
- * @returns {readonly string[]|null}
- */
-export const antigravityModelEffortLevels = (model, models) => {
- const list = (Array.isArray(models) ? models : []).filter(m => typeof m === 'string');
- if (list.length === 0) return null;
- if (isConfiguredDefaultModel(model)) return null;
- const { base } = splitAntigravityModel(model);
- if (typeof base !== 'string' || base === '') return null;
- return Object.freeze(ANTIGRAVITY_EFFORT_LEVELS.filter(level => list.includes(`${base}-${level}`)));
-};
/**
* The provider's selectable model list as the pickers should show it. Today that
@@ -383,35 +255,24 @@ export const seedModelEffort = (provider, model, effort) => {
/**
* The effort levels a provider's CLI accepts, or null when the provider has no
- * effort control (opencode, grok, kimi, HTTP API providers). Keyed on the launch
- * command basename plus the shipped provider ids, so path-configured or renamed
- * claude/codex/agy providers still qualify. Drives the "Effort (optional)"
- * select in task/schedule forms.
+ * effort control. The server's `effortLevelsForProvider` answers for every
+ * provider it can positively identify; a sanitized provider inventory — which
+ * omits command/path/env so a renamed custom CLI leaks no machine detail — is
+ * answered from the ladder the server published on it instead. Drives the
+ * "Effort (optional)" select in task/schedule forms.
*
* `model` narrows the Antigravity ladder to the tiers that base model actually
- * offers (see above). Omit it — or leave `provider.models` empty — for the full
- * low/medium/high ladder. MIRROR of the server helper; keep in lockstep.
+ * offers (see above). The server's null is FINAL for Antigravity: it means the
+ * catalog names no tier for this model, and the published provider-level ladder
+ * must not resurrect an effort agy would reject.
* @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider
* @param {string|null} [model]
* @returns {readonly string[]|null}
*/
export const effortLevelsForProvider = (provider, model = null) => {
if (!provider) return null;
- if (isOpencodeLocalProvider(provider)) return OPENCODE_LOCAL_EFFORT_LEVELS;
- if (isCodexProvider(provider)) return codexEffortLevelsForModel(model);
- if (isAntigravityProvider(provider)) {
- const perModel = model ? antigravityModelEffortLevels(model, provider.models) : null;
- if (perModel === null) return ANTIGRAVITY_EFFORT_LEVELS;
- return perModel.length ? perModel : null;
- }
- if (isCursorProvider(provider)) return CURSOR_EFFORT_LEVELS;
- if (commandBasename(provider.command) === 'pi') return ['low', 'medium', 'high', 'xhigh', 'max'];
- if (isGrokProvider(provider)) return GROK_EFFORT_LEVELS;
- const id = String(provider.id || '').toLowerCase();
- if (id.startsWith('claude-code') || commandBasename(provider.command) === 'claude') return CLAUDE_EFFORT_LEVELS;
- // Sanitized provider inventories intentionally omit command/path/env details.
- // The server publishes the derived ladder so renamed custom CLIs still expose
- // the same effort control without leaking machine-specific configuration.
+ const known = serverEffortLevelsForProvider(provider, model);
+ if (known || isAntigravityProvider(provider)) return known;
const modelLevels = model ? provider.effortLevelsByModel?.[model] : null;
if (Array.isArray(modelLevels)) return modelLevels.length ? modelLevels : null;
if (Array.isArray(provider.effortLevels)) return provider.effortLevels.length ? provider.effortLevels : null;
@@ -443,14 +304,10 @@ export const effortLevelsForProvider = (provider, model = null) => {
export const effortSurvivingModel = (provider, model, effort) =>
(effortLevelsForProvider(provider, effectiveModelFor(provider, model)) ? (effort || '') : '');
-// Every effort value any CLI accepts, weakest→strongest. MIRROR of EFFORT_RANK
-// in server/lib/providerModels.js — keep in lockstep.
-const EFFORT_RANK = Object.freeze(['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']);
-
/**
* The level a stored effort will ACTUALLY run at on this provider, or null when
- * no flag is emitted. MIRROR of `resolveCliEffort` in
- * server/lib/providerModels.js — keep in lockstep.
+ * no flag is emitted: the server's clamp, over the ladder resolved here (which
+ * can come from the server-published fields).
*
* The UI needs this because the server clamps an out-of-ladder effort rather
* than dropping it: a stage pinned to claude `max` and switched to Antigravity
@@ -462,18 +319,8 @@ const EFFORT_RANK = Object.freeze(['minimal', 'low', 'medium', 'high', 'xhigh',
* @param {string|null} [model] - narrows the Antigravity ladder (see effortLevelsForProvider)
* @returns {string|null}
*/
-export const resolveCliEffort = (effort, provider, model = null) => {
- if (!effort) return null;
- const levels = effortLevelsForProvider(provider, model);
- if (!levels) return null;
- if (levels.includes(effort)) return effort;
- const requested = EFFORT_RANK.indexOf(effort);
- if (requested === -1) return null;
- const supported = levels.map(l => EFFORT_RANK.indexOf(l)).filter(i => i !== -1).sort((a, b) => a - b);
- if (supported.length === 0) return null;
- const below = supported.filter(i => i < requested);
- return EFFORT_RANK[below.length ? below[below.length - 1] : supported[0]];
-};
+export const resolveCliEffort = (effort, provider, model = null) =>
+ clampEffortToLadder(effort, effortLevelsForProvider(provider, model));
/**
* Union of one or more model-id lists, de-duplicated, order-preserving, falsy
diff --git a/client/src/utils/providerSelection.js b/client/src/utils/providerSelection.js
index e376281ab3..e93cefce83 100644
--- a/client/src/utils/providerSelection.js
+++ b/client/src/utils/providerSelection.js
@@ -17,6 +17,7 @@
import { isLocalInstanceProvider, localBackendForProvider } from './providerEndpoints.js';
import { AGENT_HARNESS_PROVIDER_TYPES, isApiProvider } from './providerTypes.js';
import { isHardwareCompatible } from './systemCapabilities.js';
+import { CALLER_MODE_POLICIES } from '../../../server/lib/callerModePolicy.js';
// Direct local HTTP providers are the only provider class that can be made
// tool-free by construction. CLI/TUI providers may be pointed at a local model,
@@ -185,27 +186,22 @@ export const filterHardwareCompatibleProviderModels = (models, provider) =>
});
/**
- * Caller EXECUTION-MODE policies, mirrored from
- * `server/lib/callerModePolicy.js#CALLER_MODE_POLICIES`.
+ * The allowed execution modes for a caller policy name, or the array itself
+ * when given one — read off the server's `CALLER_MODE_POLICIES` (the pure leaf
+ * `server/lib/callerModePolicy.js`), so the picker can never offer a mode the
+ * server refuses, nor hide one it would run. An unknown name yields `[]`
+ * (permits nothing) where the server's own `allowedModesFor` throws.
*
* The server is the authority — it enforces the same policy on the explicit
* pin, on `activeProvider` inheritance and on every fallback candidate. This
- * mirror exists only so a picker can SHOW the rule rather than let a user save
- * a route the server will refuse at run time. `providerModeSelectionPolicy`
+ * exists only so a picker can SHOW the rule rather than let a user save a
+ * route the server will refuse at run time. `providerModeSelectionPolicy`
* feeds `ProviderModelSelector`'s `selectionPolicy`, which keeps an ineligible
* saved value visible-but-disabled with a reason instead of hiding or silently
- * replacing it. Pinned by `providerModePolicy.parity.test.js`.
+ * replacing it.
*/
-export const CALLER_MODE_POLICY_MODES = Object.freeze({
- 'agent-harness': Object.freeze(['cli', 'tui']),
- 'cli-harness': Object.freeze(['cli']),
- 'direct-api': Object.freeze(['api']),
- 'any-text': Object.freeze(['cli', 'tui', 'api']),
-});
-
-/** The allowed-mode list for a policy name, or the array itself when given one. */
export const callerModeList = (policy) =>
- (Array.isArray(policy) ? policy : CALLER_MODE_POLICY_MODES[policy]) || [];
+ (Array.isArray(policy) ? policy : CALLER_MODE_POLICIES[policy]?.allowedModes) || [];
/**
* A `selectionPolicy` restricting the provider select to one caller's allowed
diff --git a/client/src/utils/providerTypes.js b/client/src/utils/providerTypes.js
index f1c3c11466..56aea9d99e 100644
--- a/client/src/utils/providerTypes.js
+++ b/client/src/utils/providerTypes.js
@@ -17,8 +17,9 @@
import { isGatewayBackedProvider } from './providerGateways.js';
-// Inline mirror of server/lib/providerModels.js#commandBasename — the client can't
-// import server-side modules. Strip the directory + a Windows `.exe` suffix so a
+// Copy of server/lib/providerModels.js#commandBasename (the predicates in this
+// file are the one provider table still copied rather than re-exported — see
+// the header). Strip the directory + a Windows `.exe` suffix so a
// path-configured command (/opt/homebrew/bin/grok) matches the bare vendor name.
// Keep in lockstep with the server helper (only `.exe` is stripped, not `.cmd`).
export const commandBasename = (command) =>
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 4ae973949c..e5ebf9c916 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -16,8 +16,9 @@
* providerAssignments.js — which provider a RECORD resolves to; assignment options
*
* Every existing `import { … } from '../utils/providers'` keeps working through
- * this file. New code should import the declaring module — that is where the
- * server parity tests pin the mirrored declarations, and where a change belongs.
+ * this file. New code should import the declaring module — that is where a
+ * change belongs, and where each shared table is re-exported from its
+ * `server/lib` leaf rather than copied.
*/
export * from './localModelHeuristics.js';
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 417c57826f..e6f918bfe7 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -1,8 +1,9 @@
// Exercised THROUGH the `providers.js` facade on purpose: the helpers under test
// are declared across the nine `provider*` / `localModelHeuristics` modules it
// re-exports, so a helper that drops out of the facade fails here before any of
-// the 69 `utils/providers` importers notices. The server-mirror parity suites
-// (`server/lib/*.mirror.test.js`) pin the declaring modules directly.
+// the 69 `utils/providers` importers notices. The declaring modules re-export
+// their shared tables from `server/lib`, so what is pinned here is the
+// client-side behaviour built on top of them.
import { describe, it, expect } from 'vitest';
import {
ANTIGRAVITY_CONFIGURED_DEFAULT,
@@ -103,15 +104,13 @@ import {
effortLevelsForProvider as serverEffortLevelsForProvider,
isAntigravityProvider as serverIsAntigravityProvider,
resolveCliEffort as serverResolveCliEffort,
- splitAntigravityModel as serverSplitAntigravityModel,
- antigravityBaseModels as serverAntigravityBaseModels,
- antigravityModelEffortLevels as serverAntigravityModelEffortLevels,
} from '../../../server/lib/providerModels.js';
-// The client copy drives what EffortSelect DISPLAYS; the server copy decides
-// what the CLI actually receives. Any drift means the UI names a level the run
-// won't use, so every case is asserted against both implementations.
-describe('resolveCliEffort (server mirror)', () => {
+// The client resolves its own ladder and clamps through the server's
+// clampEffortToLadder; the server's resolveCliEffort decides what the CLI
+// actually receives. On a full provider record the two must agree, or the UI
+// names a level the run won't use — so every case is asserted against both.
+describe('resolveCliEffort', () => {
const AGY = { id: 'antigravity-cli', command: 'agy' };
const CLAUDE = { id: 'claude-code', command: 'claude' };
const CODEX = { id: 'codex', command: 'codex' };
@@ -155,9 +154,9 @@ describe('resolveCliEffort (server mirror)', () => {
});
// These drive the Effort/model pickers in the CoS task + schedule forms. The
-// client copy is a hand-mirror of server/lib/providerModels.js (the client can't
-// import server modules at runtime), so pin both sides together here.
-describe('effortLevelsForProvider (server mirror)', () => {
+// client helper delegates to server/lib/providerModels.js and adds the
+// published-field fallback, so pin both sides together here.
+describe('effortLevelsForProvider', () => {
const CASES = [
['antigravity CLI', { id: 'antigravity-cli', command: 'agy' }, ANTIGRAVITY_EFFORT_LEVELS],
['antigravity TUI', { id: 'antigravity-tui' }, ANTIGRAVITY_EFFORT_LEVELS],
@@ -248,11 +247,38 @@ describe('generationControlsFor', () => {
});
});
+describe('effortLevelsForProvider on a sanitized inventory', () => {
+ // The safe settings payload (server/services/aiAssignments.js) omits command/
+ // path/env and publishes the derived ladder instead. The server's own answer
+ // for such a record is null, so the published fields are the only rung —
+ // except for Antigravity, whose server null is final: the catalog names no
+ // tier for that model, and the provider-level ladder must not resurrect one.
+ const CATALOG = ['gemini-3.6-flash-high', 'gemini-3.6-flash-medium', 'gemini-3.6-flash-low', 'claude-sonnet-4-6'];
+
+ it('reads the published ladder, but never lets it resurrect an Antigravity tier', () => {
+ const agy = {
+ id: 'antigravity-cli',
+ models: CATALOG,
+ effortLevels: ['low', 'medium', 'high'],
+ effortLevelsByModel: { 'gemini-3.6-flash': ['low', 'medium', 'high'] },
+ };
+ expect(effortLevelsForProvider(agy, 'gemini-3.6-flash')).toEqual(['low', 'medium', 'high']);
+ expect(effortLevelsForProvider(agy, 'claude-sonnet-4-6')).toBeNull();
+ expect(effortLevelsForProvider(agy, 'not-in-catalog')).toBeNull();
+
+ const custom = { id: 'custom-agent', effortLevels: ['low', 'medium', 'high'], effortLevelsByModel: { m: ['low', 'high'] } };
+ expect(effortLevelsForProvider(custom, 'm')).toEqual(['low', 'high']);
+ expect(effortLevelsForProvider(custom)).toEqual(['low', 'medium', 'high']);
+ expect(resolveCliEffort('max', custom)).toBe('high');
+ });
+});
+
// Antigravity lists one model id per effort tier (`gemini-3.6-flash-high`), but
// agy also takes the BASE id with a separate `--effort` flag — so the pickers
-// show base models and carry effort as its own control. Both sides must agree on
-// the split, or a client-side base id won't match what the server rebuilds.
-describe('Antigravity base-model split (server mirror)', () => {
+// show base models and carry effort as its own control. The split is the
+// server's (re-exported), so a client-side base id always matches what the
+// server rebuilds.
+describe('Antigravity base-model split', () => {
// The catalog `agy models` prints — the shipped provider list mirrors it.
const CATALOG = [
ANTIGRAVITY_CONFIGURED_DEFAULT,
@@ -274,12 +300,10 @@ describe('Antigravity base-model split (server mirror)', () => {
['', { base: '', effort: null }],
])('splitAntigravityModel(%s)', (id, expected) => {
expect(splitAntigravityModel(id)).toEqual(expected);
- expect(serverSplitAntigravityModel(id)).toEqual(expected);
});
- it('strips + dedupes the catalog into base models on both sides', () => {
+ it('strips + dedupes the catalog into base models', () => {
expect(antigravityBaseModels(CATALOG)).toEqual(BASES);
- expect(serverAntigravityBaseModels(CATALOG)).toEqual(BASES);
});
it.each([
@@ -293,7 +317,6 @@ describe('Antigravity base-model split (server mirror)', () => {
[ANTIGRAVITY_CONFIGURED_DEFAULT, null],
])('antigravityModelEffortLevels(%s)', (model, expected) => {
expect(antigravityModelEffortLevels(model, CATALOG)).toEqual(expected);
- expect(serverAntigravityModelEffortLevels(model, CATALOG)).toEqual(expected);
});
it('narrows the picker ladder per selected model, and hides it for a tier-less model', () => {
@@ -846,7 +869,7 @@ describe('isEmbeddingModel / filterGenerationModels', () => {
});
});
-describe('isVisionModel (mirror of server localModelHeuristics)', () => {
+describe('isVisionModel', () => {
it('flags known vision model ids', () => {
for (const id of [
'qwen2.5-vl:7b', 'qwen2.5vl', 'qwen2.5vl:32b', 'llava:latest', 'moondream:latest', 'minicpm-v:8b',
@@ -879,7 +902,7 @@ describe('isVisionCapableCliProvider', () => {
});
});
-describe('isToolUseModel (mirror of server localModelHeuristics)', () => {
+describe('isToolUseModel', () => {
it('flags known tool-use-capable model ids', () => {
for (const id of [
'qwen2.5:7b', 'qwen3:32b', 'llama3.1:8b', 'llama3.3:70b',
@@ -1135,7 +1158,7 @@ describe('modelCapabilityInfo', () => {
});
});
-describe('knownProviderContextWindow (mirror of server stageRunner)', () => {
+describe('knownProviderContextWindow', () => {
it('resolves vendor windows for bare commands', () => {
expect(knownProviderContextWindow({ id: 'codex-tui', type: 'tui', command: 'codex' })).toBe(CODEX_CONTEXT_WINDOW);
expect(knownProviderContextWindow({ id: 'antigravity-cli', type: 'cli', command: 'agy' })).toBe(GEMINI_CONTEXT_WINDOW);
@@ -1261,10 +1284,6 @@ describe('cursor providers', () => {
expect(effortLevelsForProvider({ id: 'custom', command: 'cursor' })).toBeNull();
});
- it('keeps the cursor ladder in lockstep with the server', () => {
- expect(CURSOR_EFFORT_LEVELS).toEqual(serverEffortLevelsForProvider({ id: 'cursor-cli', command: 'cursor-agent' }));
- });
-
it('is not mistaken for a claude/codex/antigravity provider by its model ids', () => {
const cursor = { id: 'cursor-cli', command: 'cursor-agent', models: ['claude-opus-5-thinking-high'] };
expect(isCodexProvider(cursor)).toBe(false);
@@ -1303,9 +1322,9 @@ describe('effectiveModelContextWindow', () => {
});
it('prefers the window the provider catalog reported for that model', () => {
- // Mirrors the server ladder in stageRunner.js: catalog beats the regex
- // table, and both beat the blanket 128K assumption that made a 1M-context
- // model look capped.
+ // The same rungs as the server's effectiveContextWindow: catalog beats the
+ // regex table, and both beat the blanket 128K assumption that made a
+ // 1M-context model look capped.
const wrapper = { id: 'opencode-openrouter-tui', type: 'tui', command: 'opencode', modelContextWindows: { 'stealth/ox-alpha': 1_000_000 } };
expect(effectiveModelContextWindow(wrapper, 'stealth/ox-alpha')).toBe(1_000_000);
expect(effectiveModelContextWindow(wrapper, 'openrouter/auto')).toBe(128_000);
diff --git a/server/lib/README.md b/server/lib/README.md
index 0750610b80..e16263ee36 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -185,7 +185,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `videoReferenceModes.js` | The i2v reference-mode contract (#4874) — what a supplied conditioning image PROMISES. `I2V_REFERENCE_MODES` (`anchor` \| `inspire`) + `I2V_REFERENCE_MODE_OPTIONS` (the label + the promise sentence the UI prints), `I2V_REFERENCE_MODE_RUNTIMES` (only `ltx25` can honor `inspire` — it needs per-image conditioning strength), `INSPIRE_DEFAULT_IMAGE_STRENGTH`, plus `normalizeI2vReferenceMode` / `isDefaultI2vReferenceMode` / `isKnownI2vReferenceMode` / `runtimeSupportsI2vReferenceMode` / `i2vReferenceModeLabel` / `resolveI2vReferenceStrength` and the one rule `i2vReferenceModeViolation({ model, mode, referenceMode, hasFirstImage })` → `{ code, message }` or null. Pure (no `ServerError`) because it is MIRRORED to `client/src/lib/videoReferenceModes.js`; `videoGen/modeContract.js#videoReferenceModeError` wraps it for the route + render boundaries. |
| `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path, and `videoTextEncoderRuntimes()` enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written. |
| `pi.js` | Pi command identity, headless/TUI arguments, and positional prompt delivery. |
-| `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, `localRuntimeNamespace(provider)` — the OpenCode namespace only when it names a LOCAL daemon, i.e. the composed "namespace and not a hosted gateway" test that `cliChildEnv.js`, `localProviderRuntime.js` and `providerVendors.js` all key on, `CODEX_OSS_LOCAL_PROVIDERS` / `CODEX_OSS_MIN_VERSION` / `codexOssLocalProvider` / `codexUnsupportedLocalRuntime` — the codex half of that same axis: which local runtimes Codex's `--local-provider` can serve, and which marked runtime it cannot, kept here beside the namespace they wrap so `providerPrerequisites.js` classifies a codex record without importing `codex.js` (the argv emitter, `buildCodexOssArgs`, stays there), `OPENCODE_PUBLIC_REVIEW_AGENT` — the read-only OpenCode agent a no-tool public-review stage runs as, kept in this leaf because `providerVendors.js` must not import `opencodeConfig.js`, `parseOpencodeConfigContent` — the shared "is this stored OPENCODE_CONFIG_CONTENT usable?" read — plus `opencodeConfigIsLocalOnly` / `opencodeProviderIsLocalOnly`, the ONE locality rule `providerVendors.js` (gate eligibility) and `cliChildEnv.js` (public-review env allowlist) must not disagree about: if eligibility says yes where the allowlist strips the config, the stage spawns against the user's own ~/.config/opencode with tools intact while still reporting an enforced tool-free gate, `normalizeClaudeModelId` / `resolveClaudeCliModel` — the Claude-argv chokepoint that rewrites a dotted first-party version (`claude-fable-5.1`) to the dashed id Claude Code actually serves before the Bedrock mapping runs, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file. |
+| `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, `localRuntimeNamespace(provider)` — the OpenCode namespace only when it names a LOCAL daemon, i.e. the composed "namespace and not a hosted gateway" test that `cliChildEnv.js`, `localProviderRuntime.js` and `providerVendors.js` all key on, `CODEX_OSS_LOCAL_PROVIDERS` / `CODEX_OSS_MIN_VERSION` / `codexOssLocalProvider` / `codexUnsupportedLocalRuntime` — the codex half of that same axis: which local runtimes Codex's `--local-provider` can serve, and which marked runtime it cannot, kept here beside the namespace they wrap so `providerPrerequisites.js` classifies a codex record without importing `codex.js` (the argv emitter, `buildCodexOssArgs`, stays there), `OPENCODE_PUBLIC_REVIEW_AGENT` — the read-only OpenCode agent a no-tool public-review stage runs as, kept in this leaf because `providerVendors.js` must not import `opencodeConfig.js`, `parseOpencodeConfigContent` — the shared "is this stored OPENCODE_CONFIG_CONTENT usable?" read — plus `opencodeConfigIsLocalOnly` / `opencodeProviderIsLocalOnly`, the ONE locality rule `providerVendors.js` (gate eligibility) and `cliChildEnv.js` (public-review env allowlist) must not disagree about: if eligibility says yes where the allowlist strips the config, the stage spawns against the user's own ~/.config/opencode with tools intact while still reporting an enforced tool-free gate, `normalizeClaudeModelId` / `resolveClaudeCliModel` — the Claude-argv chokepoint that rewrites a dotted first-party version (`claude-fable-5.1`) to the dashed id Claude Code actually serves before the Bedrock mapping runs, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `clampEffortToLadder` (that clamp over an explicit ladder; the client's own `resolveCliEffort` runs its published-field ladder through it), `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file. |
| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. |
| `modelCapabilityTests.js` | Catalog + scoring for the CAPABILITY tests on `/models/performance` (run by `services/modelCapabilityTests.js`): `CAPABILITY_TESTS` (sandbox repair / image analysis / story outline / fiction scene / rhetoric evaluator, each gated on the capability badges the install catalog already shows), `applicabilityFor` + `applicableTests` (`applicable` / `not-applicable` / `unknown` — an UNCLAIMED capability is never a failure, and `null` capabilities mean the runtime reported none, which is distinct from `[]`), `scoreKeywords` + `VISION_FIXTURE_KEYWORDS` (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), `scoreStoryBeats` + `HEROS_JOURNEY_BEATS` (coverage AND ordering, judged only over the beats present), `scoreSandboxRepair` (verdict from observed disk facts — editing the test instead of the module fails outright), `formatAgentEvent` (one agent stream frame → a transcript line), `rollUpVerdict`, and the verbatim `CAPABILITY_TEST_PROMPTS` / `SANDBOX_TASK_PROMPT` the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call. |
| `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. |
@@ -196,8 +196,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, idPattern, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)`, `familyForProviderId(id)` (the weaker id-only classifier a Zod schema can use, null when the id names no family) → family id or null (local-runtime wrappers and API-only providers belong to none). The pure half of the registry `services/providerUsage.js` attaches quota `fetch`ers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from `providerVendors.js`, which is argv-shaped and includes vendors with no subscription quota. |
| `fleetQuotas.js` | Unifies subscription-quota readings across federated instances — one plan, several machines, each able to read only its own local CLI. `sanitizeQuotaCards` bounds a peer-supplied payload to the wire shape; `mergeFleetQuotaCards(localCards, peerEntries)` folds every peer's reading into this install's cards, taking the FRESHEST reading per limit key (the meters are account-wide, so summing them would multiply one allowance) and SUMMING activity counts (those are per-machine, which is why the provider captions them "does not include other devices"); `fleetNote` writes the caption naming what was combined. `metrics[]` is left local — its values are prose, not addends. Fed by `services/providerQuotaShare.js` (this machine's readings, persisted) and `services/peerUsage.js` (the `usage` sync category that carries them). |
| `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`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)` and `gatewayForProvider(config)` → row or null. 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) and `client/src/utils/providerGateways.js` (the browser cannot import server code) — `providerGateways.parity.test.js` fails when the first two drift. 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). |
+| `providerGateways.js` | `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (`orcarouter`, `openrouter`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)`, `gatewayForProvider(config)` → row or null, and `isGatewayBackedProvider(config)`. 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. |
| `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). `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. |
@@ -432,7 +433,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `specDecodePresets.js` | Curated llama-server speculative-decoding presets (target + drafter GGUF paths, `--spec-type`, and the Hugging Face repo/quant each file comes from) plus `findSpecDecodePreset` / `specDecodeSource` / `hfSearchUrl`. Also owns the `--spec-type` vocabulary: `SPEC_TYPE_SUGGESTIONS` (published to the launcher card), `parseSpecTypes` (the flag is a comma-separated list) and `isDraftSpecType` (the `draft-` prefix is what needs a drafter GGUF — every `ngram-*` type runs without one). Server-owned so the launcher card can offer a Download button per file. Pure. |
| `llamaCppInstall.js` | Where a llama.cpp install comes from on this host, for `services/llamaServerManager.js`. `llamaCppInstallPlan(platform)` → the frozen descriptor for that platform's package manager — Homebrew on macOS/Linux (`brew install llama.cpp`), winget on Windows (`winget install ggml.llamacpp`) — carrying `manager`, `managerLabel`, `packageId`, `installCommand`, the install/upgrade (and, for winget, list/upgrade-check) argv, and the three refusal strings a caller would otherwise hardcode: `missingManagerError`, `notInstalledError`, `pathRepairHint`. The LLMs page renders `installCommand` out of the llama-server status payload, which is what stopped a Windows install prompt from telling the user to run Homebrew. Also the winget-side readers Homebrew needs no equivalent for: `parseWingetPackageFields(stdout, id)` (winget has NO machine-readable output mode and LOCALIZED table headers, so fields are read positionally from the tokens after the id token — `Version [Available] [Source]`; `null` = not installed), `wingetLinkDirs(env)` (the portable-shim directories winget adds to the USER PATH, which an already-running server has not inherited) and `isWingetManagedPath` (counterpart of the manager's `isHomebrewLlamaServer`: a source build earlier on PATH must not be offered a `winget upgrade`). Every WinGet path is reasoned about with `path.win32` regardless of host, so both branches are coverable from a macOS/Linux checkout. Pure. |
| `ollamaContext.js` | Ollama runtime context-window reasoning. `resolveOllamaContextLength(provider, env)` → the window PortOS should hold the daemon at (`provider.numCtx`, then `OLLAMA_CONTEXT_LENGTH`, then `null` = leave Ollama's VRAM-based auto-pick alone); `withOllamaContextEnv(env, n)` builds the `ollama serve` child env; `parseOllamaContextOverflow(text)` recognizes the `exceed_context_size_error` rejection and pulls `{ promptTokens, contextLength }` out of either the JSON body or the human message; `describeOllamaContextOverflow` / `describeOllamaContextTooSmall` render the actionable one-liners; `isSameOllamaDaemon(providerBase, managedBase)` compares host+port so a provider pointed at a *remote* Ollama never triggers a local-daemon reload; `OLLAMA_AGENT_MIN_CONTEXT` is the window below which an agent harness is warned. Pure — the daemon side lives in `services/ollamaManager.js` (`ensureContextWindow`), the pre-spawn enforcement in `services/ollamaAgentContext.js`. |
-| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models, { measured })` ranks installed models for editorial review/editing, dropping any a fresh measurement proved cannot run here. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/localModelHeuristics.js`. |
+| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models, { measured })` ranks installed models for editorial review/editing, dropping any a fresh measurement proved cannot run here. Pure — `client/src/utils/localModelHeuristics.js` re-exports `isEmbeddingModel`/`isVisionModel`/`isToolUseModel` from here. |
| `localModelAssessment.js` | Scoring for MEASURED local-model assessments (recorded by `services/localModelAssessments.js`): `classifyFitVerdict` (`fits`/`does-not-fit`/`incompatible`/`unknown`), `summarizePerformance` (mean/peak chars-per-second AND tokens-per-second, prefill rate, TTFT, max working context, cross-context degradation), `scoreAssessment` + `scoreForIntent` + `rankByIntent` for the balanced/smartest/fastest/lightweight pickers, `explainAssessment`, `compareEnvironments`/`describeStaleness` (is a stored reading still valid for THIS machine?), `buildThroughputReport` (every measurement as one tokens/s table, fastest first, per-context readings intact), `selectSweepTargets`/`summarizeSweepScopes`/`SWEEP_SCOPES` (which measurements a "measure everything" run covers, and how many), and `measuredFitVerdict`/`reconcileFit` (fold a measurement into the catalog's size-estimate fit badge, keeping the disagreement). Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |
| `localModelTuning.js` | Launch/runtime tuning knobs for the measurable local runtimes — ONLY knobs PortOS can actually apply. A knob is defined by its transport, and `applies` + the user-facing `note` are DERIVED from it: `config` (llama.cpp's `-b`/`-ub`/`-t`/`--parallel`/`--flash-attn`/`--cache-type-k\|v`/`--spec-draft-n-max`, via `launchConfig`), `env` (Ollama's `OLLAMA_CONTEXT_LENGTH`/`_FLASH_ATTENTION`/`_KV_CACHE_TYPE`/`_NUM_PARALLEL`, via `launchEnv`), `cli` (a flag on the launch line of a daemon PortOS re-runs — LM Studio's `lms load --context-length`/`--gpu`/`--parallel`, and MTPLX's `mtplx serve --context-window`/`--depth`/`--generation-mode`/`--kv-quant`/`--batching-preset`/`--profile` — via `launchArgs`), or `wire` (a request-body field, via `requestBody` — currently no members). vLLM declares none: PortOS does not start it, so there is no launch line to put a flag on. Read the MTPLX verification note in the module before adding an `mtplx serve` flag — it exits before it binds on one it does not recognize. Also `normalizeTuning` (coerce + clamp + drop unknown keys), `tuningSignature` (stable identity — `''` for backend defaults, so pre-tuning store keys keep resolving), `describeTuning`, `launchTuning`, and `compareTunings` (which tuning won per model using exact tokens/s when all variants have tokenizer counts and chars/s otherwise, labelled from each record's persisted `tuningLabel`, with a `deltaPercent` against the winner), and `tuningGridFor` (the candidate grid a tuning sweep runs — backend defaults plus one variant per knob declaring a `sweep` value, capped by `maxVariants`; `sweepWith` carries a knob's documented prerequisite). Pure. || `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
| `loraTriggers.js` | Pure trigger-word weaving for renders that load a LoRA (#4665): `weaveLoraTriggers(prompt, triggerWordLists)` → `{ prompt, added }` appends each selected LoRA's FIRST activation token to the prompt when it is not already there, in selection order, as a trailing comma clause so the user's own phrasing keeps its position and weight. `promptHasTriggerWord` is the whole-token, case-insensitive presence test (`aria_tok` does not match inside `aria_token`); `firstTriggerWord` picks the canonical token out of a Civitai `trainedWords` list. Idempotent, so a re-render of an already-woven prompt is a no-op. Consumed by `services/imageGen/local.js` and `services/videoGen/local.js` (paired with `services/loras.js#readTriggerWordsByFilename` for the sidecar reads). The comic pipeline shares it rather than opting out — its own "<Name> (<trigger>)" clause uses the same token, so the weave adds nothing there except for the characters that clause drops. |
@@ -571,7 +572,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
|---|---|
| `dbTestGate.js` | `requireDbOrSkip(label, dbReady, reason)` keeps a missing local test database as a visible skipped suite, but throws when `PORTOS_REQUIRE_DB` is set so CI cannot pass after DB-backed suites disappear. |
| `gitTestRepo.js` | Shared real-git sandbox for integration tests (#4394): one initialized template (working tree + bare origin) per worker, then `fs.cp` into a fresh temp dir. `makeGitSandbox({ origin })`, `attachBareOrigin(scratch, repo)`, `materializeGitRepo(dest)`, `destroyGitSandbox`, plus `SKIP_HEAVY_INTEGRATION` (`VITEST_FAST=1`). `resetGitSandbox({ scratch, repo, initialHead })` / `resetGitWorktreeSandbox(repo, initialHead)` restore a sandbox in place (branches, worktrees, remote) so a `describe` can build one sandbox in `beforeAll` and reset between tests instead of paying the fs.cp/rm cycle per test (#5902). Every entry point runs `assertTempPath` first, so a path outside `os.tmpdir()` throws instead of `git init`-ing or `rm -rf`-ing a real checkout (#4554). Still real git — just not rebuilt from `init`+`commit`+`push` in every `beforeEach`. |
-| `mirrorParity.js` | Source-comparison primitives for the remaining `*.mirror.test.js` parity tests — the copies that are NOT pure `server/lib` leaves (component constants, service tables), since a shared pure module is imported rather than mirrored: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), `compareDeclaration(serverSrc, clientSrc, name)`, and `compareRegexDeclaration(serverSrc, clientSrc, serverName, clientName?)` / `regexAlternationSource(declText)` (for a regex spelled as a `new RegExp([…].join('|'), 'i')` array on one side and an inline `/…/i` literal on the other — compares what it matches, not how it is typeset, and returns `null` rather than a partial read on any shape it can't decode). Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. |
+| `mirrorParity.js` | Source-comparison primitives for the remaining `*.mirror.test.js` parity tests — the copies that are NOT pure `server/lib` leaves (component constants, service tables), since a shared pure module is imported rather than mirrored: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), and `compareDeclaration(serverSrc, clientSrc, name)`. Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. |
| `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir` and no-peer record creation guards. |
| `settingsTestUtil.js` | `bindSettingsFile(dataRoot)` → `writeSettingsFile`/`mergeSettingsFile`: direct settings.json disk writes that also drop the `getSettings()` read cache (dynamic-import reset) so a stale cache can't survive a bypass-`save()` write. |
| `runtimeEnv.js` | `isTestRunner()` — NODE_ENV=test **or** the VITEST env var, so a run that dropped NODE_ENV is still armed. Dependency-free and deliberately apart from `db.js`, which used to own it: the lowest-level file primitives need the same answer and must not pull in `pg`, and the many suites spelling `vi.mock('../lib/db.js', () => ({ query }))` used to strip it out of the graph for every other consumer. |
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 79d7aee0d2..81cdfe0566 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -143,8 +143,7 @@ const execFileAsync = (file, args, options) =>
// Tool-use (function-calling) capable model families. Inlined here because the
// aiToolkit is self-contained (no imports out to server/lib). MIRROR of
-// TOOL_USE_RE in server/lib/localModelHeuristics.js and isToolUseModel in
-// client/src/utils/localModelHeuristics.js — keep all three in lockstep
+// TOOL_USE_RE in server/lib/localModelHeuristics.js — keep the two in lockstep
// (server/lib/localModelHeuristics.mirror.test.js fails when they drift).
const TOOL_USE_RE = new RegExp([
'qwen',
diff --git a/server/lib/callerModePolicy.js b/server/lib/callerModePolicy.js
index e739153e58..bb05600416 100644
--- a/server/lib/callerModePolicy.js
+++ b/server/lib/callerModePolicy.js
@@ -42,7 +42,9 @@
* constants: this module is reached by the agent resolver, promptRunner and the
* out-of-process autofixer, and a widely-reached module must not drag a subtree
* it needs one three-string constant from (see "Import scoping" in
- * server/AGENTS.md). `callerModePolicy.parity.test.js` pins it to both mirrors.
+ * server/AGENTS.md). The browser derives its picker table from
+ * `CALLER_MODE_POLICIES` directly (client/src/utils/providerSelection.js), so
+ * there is no client copy to pin.
*/
export const EXECUTION_MODES = Object.freeze(['cli', 'tui', 'api']);
diff --git a/server/lib/index.js b/server/lib/index.js
index 40344072e1..94f19f9f7e 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -424,6 +424,7 @@ export * from './fleetQuotas.js';
export * from './harnessOutput.js';
export * from './providerGateways.js';
export * from './providerHarnesses.js';
+export * from './providerContextWindows.js';
export * from './providerConnections.js';
export * from './providerGraphPreview.js';
export * from './providerGraphRecords.js';
diff --git a/server/lib/localModelHeuristics.js b/server/lib/localModelHeuristics.js
index 90a7380941..911d790ca7 100644
--- a/server/lib/localModelHeuristics.js
+++ b/server/lib/localModelHeuristics.js
@@ -9,10 +9,12 @@
* generation/fallback run — the cause of the nomic-embed-text fallback bug)
* - localLlm.getStatus (recommend a best-fit editorial model)
*
- * The client mirrors `isEmbeddingModel` + `isVisionModel` + `isToolUseModel`
- * in client/src/utils/localModelHeuristics.js — keep the regexes in lockstep (the
- * aiToolkit/lib dirs can't be imported there). `localModelHeuristics.mirror.test.js`
- * enforces that, by what each pattern matches rather than by its text.
+ * Pure and dependency-free, so the browser imports it too:
+ * client/src/utils/localModelHeuristics.js re-exports `isEmbeddingModel` +
+ * `isVisionModel` + `isToolUseModel` from here rather than inlining the regexes.
+ * The one remaining copy is `TOOL_USE_RE` in server/lib/aiToolkit/providers.js
+ * (the vendored toolkit may not import out of its own directory);
+ * `localModelHeuristics.mirror.test.js` fails when that copy drifts.
*/
// Embedding-only models — never valid for chat/generation. The bge/nomic/e5/gte
@@ -171,9 +173,9 @@ export function isVisionModel(model) {
// NOT matched (tool use landed in 3.1); neither is Gemma 3 (tools landed in
// Gemma 4), so the gemma rule is anchored to the family AND the version.
//
-// MIRRORED in client/src/utils/localModelHeuristics.js (isToolUseModel) and inlined in
-// server/lib/aiToolkit/providers.js (TOOL_USE_RE) — keep all three in lockstep;
-// `localModelHeuristics.mirror.test.js` fails when any of them drifts.
+// Inlined in server/lib/aiToolkit/providers.js (TOOL_USE_RE) — keep the two in
+// lockstep; `localModelHeuristics.mirror.test.js` fails when they drift. The
+// client re-exports `isToolUseModel` from this file, so it needs no copy.
const TOOL_USE_RE = new RegExp([
'qwen',
'llama-?3\\.[1-9]', 'llama-?4',
diff --git a/server/lib/localModelHeuristics.mirror.test.js b/server/lib/localModelHeuristics.mirror.test.js
index aa184be57d..c449218eab 100644
--- a/server/lib/localModelHeuristics.mirror.test.js
+++ b/server/lib/localModelHeuristics.mirror.test.js
@@ -1,80 +1,27 @@
/**
- * Mirror parity test for the local-model capability regexes, which exist in
- * three copies by architecture:
+ * Mirror parity test for the tool-use capability regex, which exists in two
+ * copies by architecture:
* 1. server/lib/localModelHeuristics.js — authoritative;
- * 2. client/src/utils/localModelHeuristics.js — the browser cannot import server code;
- * 3. server/lib/aiToolkit/providers.js — the vendored toolkit may not import
+ * 2. server/lib/aiToolkit/providers.js — the vendored toolkit may not import
* out of its own directory (see aiToolkit/AGENTS.md), so TOOL_USE_RE is
* inlined there too.
*
- * All three were pinned by a "keep all three in lockstep" comment and by
- * per-side hardcoded id lists (`providers.test.js`'s
- * `describe('isToolUseModel (mirror of server localModelHeuristics)')` never
- * reads the server file), so a family added to one copy alone left every suite
- * green. The consequence is user-visible in both directions: a model the server
- * accepts for tool use gets a "no known tool use" warning in the agent picker,
- * and an embedding model the client hasn't learned to recognise is offered in a
- * generation picker, where the daemon answers `400 … does not support chat`.
- *
- * The server spells VISION_RE / TOOL_USE_RE as a multi-line array of
- * alternatives so each one can carry its own comment; the client inlines the
- * same pattern as a single literal. Declaration TEXT therefore cannot be
- * compared — `compareRegexDeclaration` compares what the two patterns match
- * instead. Typesetting is irrelevant; the accepted id set is not. The toolkit
- * copy is the array form on both sides, so it is compared as text.
+ * A family added to one copy alone would leave every suite green while a model
+ * the server accepts for tool use gets a "no known tool use" warning in the
+ * agent picker. Both copies are the array form, so they are compared as text
+ * (comments stripped, whitespace normalized). The browser re-exports the server
+ * predicates, so it needs no pin.
*/
-
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
-import { compareDeclaration, compareRegexDeclaration } from './mirrorParity.js';
+import { compareDeclaration } from './mirrorParity.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
-
const SERVER_PATH = resolve(__dirname, 'localModelHeuristics.js');
-const CLIENT_PATH = resolve(__dirname, '../../client/src/utils/localModelHeuristics.js');
const TOOLKIT_PATH = resolve(__dirname, 'aiToolkit/providers.js');
-// [server declaration, the client predicate that inlines it]
-const MIRRORED_REGEXES = [
- ['EMBEDDING_RE', 'isEmbeddingModel'],
- ['VISION_RE', 'isVisionModel'],
- ['TOOL_USE_RE', 'isToolUseModel'],
-];
-
-describe('localModelHeuristics↔client providers capability-regex mirror parity', () => {
- const serverSrc = readFileSync(SERVER_PATH, 'utf8');
- const clientSrc = readFileSync(CLIENT_PATH, 'utf8');
-
- it('both files are non-empty', () => {
- expect(serverSrc.length).toBeGreaterThan(100);
- expect(clientSrc.length).toBeGreaterThan(100);
- });
-
- for (const [serverName, clientName] of MIRRORED_REGEXES) {
- it(`${serverName} accepts the same ids as the client's ${clientName}`, () => {
- const { serverDecl, clientDecl, serverSource, clientSource } =
- compareRegexDeclaration(serverSrc, clientSrc, serverName, clientName);
-
- expect(serverDecl, `server/lib/localModelHeuristics.js is missing: ${serverName}`).not.toBeNull();
- expect(clientDecl, `client/src/utils/localModelHeuristics.js is missing: ${clientName}`).not.toBeNull();
- expect(
- serverSource,
- `server/lib/localModelHeuristics.js#${serverName} is neither a /…/i literal nor the new RegExp([…].join('|'), 'i') form`,
- ).not.toBeNull();
- expect(
- clientSource,
- `client/src/utils/localModelHeuristics.js#${clientName} no longer inlines a /…/i literal`,
- ).not.toBeNull();
- expect(
- clientSource,
- `"${serverName}" diverged from the client's ${clientName} — the server copy is authoritative; port the alternatives verbatim`,
- ).toBe(serverSource);
- });
- }
-});
-
describe('localModelHeuristics↔aiToolkit TOOL_USE_RE mirror parity', () => {
const serverSrc = readFileSync(SERVER_PATH, 'utf8');
const toolkitSrc = readFileSync(TOOLKIT_PATH, 'utf8');
diff --git a/server/lib/mirrorParity.js b/server/lib/mirrorParity.js
index 4c128ad4ee..bce98c30f6 100644
--- a/server/lib/mirrorParity.js
+++ b/server/lib/mirrorParity.js
@@ -123,126 +123,3 @@ export function compareDeclaration(serverSrc, clientSrc, name) {
match: serverNorm != null && serverNorm === clientNorm,
};
}
-
-// One single-quoted JS string literal at the head of the remaining array body,
-// plus its trailing separator.
-const NEXT_STRING_LITERAL_RE = /^'((?:[^'\\]|\\.)*)'\s*(?:,\s*)?/;
-// Each accepted spelling of a mirrored capability regex, anchored to the WHOLE
-// normalized declaration. Anchoring is what makes an unrecognized shape fail
-// closed: a search-anywhere pattern would happily read a decoy array out of a
-// declaration that assigns something else entirely, and report the mirror as
-// intact. Group 1 is the alternation body in every one of them.
-//
-// 1. `const NAME = new RegExp([ 'a', 'b' ].join('|'), 'i');` — the server's
-// array form, so each alternative can carry its own comment;
-// 2. `const NAME = /…/i;` — a plain literal;
-// 3. `export const isX = (id) => <guards> && /…/i.test(id);` — the browser's
-// predicate form, where the literal is inlined at the end of a guard chain.
-const DECLARATION_FORMS = [
- /^(?:export\s+)?const\s+\w+\s*=\s*new RegExp\(\s*\[(.*)\]\s*\.join\('\|'\)\s*,\s*'i'\s*\)\s*;$/,
- // Greedy on purpose: `[-_/:]` puts an unescaped `/` mid-pattern, so a lazy
- // walk would end the literal inside a character class.
- /^(?:export\s+)?const\s+\w+\s*=\s*\/(.*)\/i\s*;$/,
- /^(?:export\s+)?const\s+\w+\s*=\s*\(\w+\)\s*=>\s*(?:[^/]*&&\s*)?\/(.*)\/i\.test\(\w+\)\s*;$/,
-];
-// Only the first form's body is a list of alternatives; the other two capture
-// the finished pattern.
-const [ARRAY_FORM_RE] = DECLARATION_FORMS;
-
-/**
- * The regex fragment a single-quoted source literal denotes, or null when it
- * uses an escape this reader cannot decode by inspection.
- *
- * Only `\\` (a backslash the regex engine will actually see, which is how every
- * alternative spells `\d` / `\.`) and `\'` are decodable here. `\x2e`, `\u002e`
- * and `\n` all denote something OTHER than their own text — `'\x2e'` is `.`,
- * which matches ANY character — so copying them through verbatim would let a
- * client literal that means something different compare equal. These guards
- * exist to catch drift, so an unreadable literal fails CLOSED rather than
- * being guessed at.
- */
-function decodeRegexFragmentLiteral(body) {
- let out = '';
- for (let i = 0; i < body.length; i++) {
- const ch = body[i];
- if (ch !== '\\') {
- out += ch;
- continue;
- }
- const escaped = body[i + 1];
- if (escaped !== '\\' && escaped !== "'") return null;
- out += escaped;
- i++;
- }
- return out;
-}
-
-/**
- * Every alternative in an array body, or null when the body holds anything
- * other than a comma-separated run of decodable string literals.
- *
- * Failing closed on the leftovers is the point: a `[...SHARED, 'extra']` or a
- * `[NAMED_FRAGMENT]` element read by a scan-for-literals pass would silently
- * vanish from the comparison, and the mirror it is supposed to pin would drift
- * green.
- */
-function parseAlternativeList(body) {
- const alternatives = [];
- let rest = body.trim();
- while (rest.length > 0) {
- const match = NEXT_STRING_LITERAL_RE.exec(rest);
- if (!match) return null;
- const decoded = decodeRegexFragmentLiteral(match[1]);
- if (decoded === null) return null;
- alternatives.push(decoded);
- rest = rest.slice(match[0].length);
- }
- return alternatives;
-}
-
-/**
- * The alternation source of a capability regex, whichever of the accepted
- * spellings above the declaration is typeset in.
- *
- * `/` is normalized (an escaped `\/` and a bare `/` mean the same thing to the
- * engine, and only one of them is legal inside a literal outside a character
- * class), so the two sides may differ in slash escaping but not in what they
- * accept. Returns null for any shape not in `DECLARATION_FORMS` — a mirror the
- * reader cannot fully account for must fail its guard, not skip past it.
- */
-export function regexAlternationSource(declText) {
- if (declText == null) return null;
- const norm = stripCommentsAndNormalize(declText);
- const form = DECLARATION_FORMS.find((re) => re.test(norm));
- if (!form) return null;
- const [, body] = form.exec(norm);
- const source = form === ARRAY_FORM_RE ? parseAlternativeList(body)?.join('|') ?? null : body;
- return source == null ? null : source.replace(/\\\//g, '/');
-}
-
-/**
- * Compare a case-insensitive regex mirrored across two files that spell it
- * differently — an array of per-alternative strings on one side, a single
- * inline literal on the other — by what it MATCHES rather than by its text.
- *
- * `compareDeclaration` can't be used there: the two typesettings never compare
- * equal even when they accept exactly the same ids, and forcing one side to
- * adopt the other's form is churn for no behavioural gain.
- *
- * `clientName` defaults to `serverName`; pass it when the client inlines the
- * pattern inside a differently-named predicate (`isToolUseModel` wrapping what
- * the server declares as `TOOL_USE_RE`).
- */
-export function compareRegexDeclaration(serverSrc, clientSrc, serverName, clientName = serverName) {
- const serverDecl = extractDeclaration(serverSrc, serverName);
- const clientDecl = extractDeclaration(clientSrc, clientName);
- const serverSource = regexAlternationSource(serverDecl);
- const clientSource = regexAlternationSource(clientDecl);
- return {
- serverDecl,
- clientDecl,
- serverSource,
- clientSource,
- match: serverSource != null && serverSource === clientSource,
- };
-}
diff --git a/server/lib/mirrorParity.test.js b/server/lib/mirrorParity.test.js
index 8a8199c32a..9faae1bb44 100644
--- a/server/lib/mirrorParity.test.js
+++ b/server/lib/mirrorParity.test.js
@@ -3,8 +3,6 @@ import {
stripCommentsAndNormalize,
extractDeclaration,
compareDeclaration,
- compareRegexDeclaration,
- regexAlternationSource,
} from './mirrorParity.js';
describe('stripCommentsAndNormalize', () => {
@@ -99,69 +97,3 @@ describe('compareDeclaration', () => {
expect(match).toBe(false);
});
});
-
-describe('compareRegexDeclaration', () => {
- // The shape this exists for: the server spells a capability regex as an array
- // of per-alternative strings (so each alternative can carry its own comment)
- // while the browser copy inlines the same pattern as one literal.
- const server = "const TOOL_USE_RE = new RegExp([\n 'qwen',\n 'llama-?3\\\\.[1-9]',\n].join('|'), 'i');\n";
- const client = "export const isToolUseModel = (id) =>\n /qwen|llama-?3\\.[1-9]/i.test(id);\n";
-
- it('matches the array form against the inline literal it compiles to', () => {
- const { serverSource, match } = compareRegexDeclaration(server, client, 'TOOL_USE_RE', 'isToolUseModel');
- expect(serverSource).toBe('qwen|llama-?3\\.[1-9]');
- expect(match).toBe(true);
- });
-
- it('reports a mismatch when one side gains an alternative', () => {
- const drifted = "export const isToolUseModel = (id) =>\n /qwen|llama-?3\\.[1-9]|newfamily/i.test(id);\n";
- expect(compareRegexDeclaration(server, drifted, 'TOOL_USE_RE', 'isToolUseModel').match).toBe(false);
- });
-
- it('treats an escaped and a bare slash as the same pattern', () => {
- // `[-_/:]` is legal bare inside a character class and must be escaped
- // outside one; that typesetting difference is not a divergence.
- const bare = 'const RE = /a[-_/:]b/i;\n';
- const escaped = 'const RE = /a[-_\\/:]b/i;\n';
- expect(compareRegexDeclaration(bare, escaped, 'RE').match).toBe(true);
- });
-
- it('does not report a match when a side is missing or is not a regex', () => {
- expect(compareRegexDeclaration(server, 'const other = 1;', 'TOOL_USE_RE').match).toBe(false);
- expect(compareRegexDeclaration(server, 'const TOOL_USE_RE = 42;', 'TOOL_USE_RE').match).toBe(false);
- });
-});
-
-describe('regexAlternationSource fails closed', () => {
- // A scan-for-literals pass would silently DROP the non-literal element and
- // report the surviving alternatives as the whole pattern — a mirror that has
- // genuinely diverged then compares equal. Refuse the array instead.
- it('refuses an array holding anything but string literals', () => {
- expect(regexAlternationSource("const RE = new RegExp(['a', 'b'].join('|'), 'i');")).toBe('a|b');
- expect(regexAlternationSource("const RE = new RegExp(['a', SHARED].join('|'), 'i');")).toBeNull();
- expect(regexAlternationSource("const RE = new RegExp([...SHARED, 'b'].join('|'), 'i');")).toBeNull();
- });
-
- // `'\\x2e'` is the single character `.`, which matches ANYTHING — copying the
- // escape through as the text `x2e` would compare equal to a client `/x2e/i`
- // that means something entirely different.
- it('refuses an escape it cannot decode by inspection', () => {
- expect(regexAlternationSource("const RE = new RegExp(['a\\\\.b'].join('|'), 'i');")).toBe('a\\.b');
- expect(regexAlternationSource("const RE = new RegExp(['\\x2e'].join('|'), 'i');")).toBeNull();
- expect(regexAlternationSource("const RE = new RegExp(['\\n'].join('|'), 'i');")).toBeNull();
- });
-
- // A search-anywhere read would find the array and report the mirror intact
- // while the declaration assigns something else entirely.
- it('refuses a declaration that merely CONTAINS a recognizable form', () => {
- const array = "new RegExp(['a', 'b'].join('|'), 'i')";
- expect(regexAlternationSource(`const RE = ${array};`)).toBe('a|b');
- expect(regexAlternationSource(`const RE = FLAG ? ${array} : OTHER_RE;`)).toBeNull();
- expect(regexAlternationSource(`const RE = widen(${array});`)).toBeNull();
- });
-
- it('returns null for a declaration that is neither supported form', () => {
- expect(regexAlternationSource(null)).toBeNull();
- expect(regexAlternationSource('const RE = buildPattern();')).toBeNull();
- });
-});
diff --git a/server/lib/providerContextWindows.js b/server/lib/providerContextWindows.js
new file mode 100644
index 0000000000..200f5e2dab
--- /dev/null
+++ b/server/lib/providerContextWindows.js
@@ -0,0 +1,80 @@
+/**
+ * Context-window ladder for provider/model planning: the vendor constants, the
+ * known-model regex table, and the per-provider fallback.
+ *
+ * Split out of `services/stageRunner.js` so the browser can import it: the
+ * budget meter on a provider card and the manuscript chunker on the server
+ * must resolve the same window, or the card promises a budget the budgeter
+ * won't use (silent, and ~8x off when the two disagree). Pure: no Node
+ * built-ins, nothing outside `server/lib`.
+ *
+ * `effectiveContextWindow` — the full planning walk, which also needs the
+ * local-endpoint test from `promptRunner.js` — stays in `stageRunner.js`.
+ */
+
+import { 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
+// ceiling (Claude/GPT/Gemini are ≥128K, often ~1M), so it means "a typical
+// whole manuscript fits in one call" without over-promising. It is a floor to
+// escape, not a cap to honor: refreshing the provider's models records each
+// model's real window (`modelContextWindows`), and an explicit `contextWindow`
+// overrides both.
+export const DEFAULT_LARGE_CONTEXT_WINDOW = 128_000;
+export const CODEX_CONTEXT_WINDOW = 1_000_000;
+export const GEMINI_CONTEXT_WINDOW = 1_048_576;
+export const GROK_CONTEXT_WINDOW = 256_000;
+export const KIMI_CONTEXT_WINDOW = 256_000;
+
+const KNOWN_MODEL_CONTEXT_WINDOWS = Object.freeze([
+ [/gpt[-_.:/]?5\.5(?:[-_.:/]|\b)/i, CODEX_CONTEXT_WINDOW],
+ [/gpt[-_.:/]?5\.4[-_.:/]?mini(?:[-_.:/]|\b)/i, 400_000],
+ [/gpt[-_.:/]?5\.4(?![-_.:/]?(?:mini|nano))(?:[-_.:/]|\b)/i, CODEX_CONTEXT_WINDOW],
+ [/claude[-_.:/]?fable[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
+ [/claude[-_.:/]?mythos[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
+ [/claude[-_.:/]?opus[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
+ [/claude[-_.:/]?opus[-_.:/]?4[-_.:/]?8/i, 1_000_000],
+ [/claude[-_.:/]?sonnet[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
+ [/claude[-_.:/]?sonnet[-_.:/]?4[-_.:/]?6(?:[-_.:/]|\b)/i, 1_000_000],
+ [/claude[-_.:/]?sonnet[-_.:/]?4(?:[-_.:/]|\b)/i, 200_000],
+ [/claude[-_.:/]?haiku[-_.:/]?4(?:[-_.:/]|\b)/i, 200_000],
+ [/gemini[-_.:/]?2\.5[-_.:/]?pro(?:[-_.:/]|\b)/i, GEMINI_CONTEXT_WINDOW],
+]);
+
+/** The known window for a model id, or `null` when the table has no row for it. */
+export function knownModelContextWindow(model) {
+ if (typeof model !== 'string' || !model.trim()) return null;
+ const found = KNOWN_MODEL_CONTEXT_WINDOWS.find(([pattern]) => pattern.test(model));
+ return found ? found[1] : null;
+}
+
+/**
+ * The vendor window for a configured-default CLI/TUI provider, or `null`.
+ * Keyed on the shared vendor predicates, which match the shipped ids and the
+ * command basename — so a path-configured `/opt/homebrew/bin/grok` resolves
+ * the same window as a bare `grok` on PATH, exactly as the effort ladders do.
+ */
+export function knownProviderContextWindow(provider) {
+ if (provider?.type !== 'cli' && provider?.type !== 'tui') return null;
+ if (isCodexProvider(provider)) return CODEX_CONTEXT_WINDOW;
+ if (isAntigravityProvider(provider)) return GEMINI_CONTEXT_WINDOW;
+ if (isGrokProvider(provider)) return GROK_CONTEXT_WINDOW;
+ if (isKimiProvider(provider)) return KIMI_CONTEXT_WINDOW;
+ return null;
+}
+
+/**
+ * The window this provider's own `/models` catalog reported for this model, or
+ * `null` when the catalog never mentioned it. Populated by model refresh (see
+ * aiToolkit/internal/modelCatalog.js), so it is the serving side's declaration
+ * rather than a guess — which is why it outranks the hand-maintained regex
+ * table above.
+ */
+export function catalogModelContextWindow(provider, model) {
+ const windows = provider?.modelContextWindows;
+ if (!windows || typeof windows !== 'object') return null;
+ if (typeof model !== 'string' || !model) return null;
+ const tokens = Number(windows[model]);
+ return Number.isFinite(tokens) && tokens > 0 ? tokens : null;
+}
diff --git a/server/lib/providerContextWindows.test.js b/server/lib/providerContextWindows.test.js
new file mode 100644
index 0000000000..79d75996f7
--- /dev/null
+++ b/server/lib/providerContextWindows.test.js
@@ -0,0 +1,77 @@
+import { describe, it, expect } from 'vitest';
+import {
+ CODEX_CONTEXT_WINDOW,
+ GEMINI_CONTEXT_WINDOW,
+ GROK_CONTEXT_WINDOW,
+ KIMI_CONTEXT_WINDOW,
+ catalogModelContextWindow,
+ knownModelContextWindow,
+ knownProviderContextWindow,
+} from './providerContextWindows.js';
+
+describe('providerContextWindows — known model windows', () => {
+ it('resolves known model windows from the selected model id', () => {
+ expect(knownModelContextWindow('gpt-5.5')).toBe(CODEX_CONTEXT_WINDOW);
+ expect(knownModelContextWindow('gpt-5.4')).toBe(CODEX_CONTEXT_WINDOW);
+ expect(knownModelContextWindow('gpt-5.4-mini')).toBe(400_000);
+ expect(knownModelContextWindow('gpt-5.4-nano')).toBeNull();
+ expect(knownModelContextWindow('claude-opus-5')).toBe(1_000_000);
+ expect(knownModelContextWindow('global.anthropic.claude-opus-5')).toBe(1_000_000);
+ expect(knownModelContextWindow('claude-opus-4-8')).toBe(1_000_000);
+ expect(knownModelContextWindow('claude-sonnet-5')).toBe(1_000_000);
+ expect(knownModelContextWindow('claude-sonnet-4-6')).toBe(1_000_000);
+ expect(knownModelContextWindow('us.anthropic.claude-sonnet-4-5-20250929-v1:0')).toBe(200_000);
+ expect(knownModelContextWindow('gemini-2.5-pro')).toBe(GEMINI_CONTEXT_WINDOW);
+ expect(knownModelContextWindow('unknown-model')).toBeNull();
+ });
+});
+
+describe('providerContextWindows — known provider windows', () => {
+ it('resolves configured-default provider windows by provider identity', () => {
+ expect(knownProviderContextWindow({ id: 'codex-tui', type: 'tui', command: 'codex' })).toBe(CODEX_CONTEXT_WINDOW);
+ expect(knownProviderContextWindow({ id: 'antigravity-cli', type: 'cli', command: 'agy' })).toBe(GEMINI_CONTEXT_WINDOW);
+ // A custom grok CLI/TUI without an explicit contextWindow resolves the
+ // vendor's 256K — the browser's provider-card meter reads this same leaf.
+ expect(knownProviderContextWindow({ id: 'grok-cli', type: 'cli', command: 'grok' })).toBe(GROK_CONTEXT_WINDOW);
+ expect(knownProviderContextWindow({ id: 'grok-tui', type: 'tui', command: 'grok' })).toBe(GROK_CONTEXT_WINDOW);
+ // Kimi Code (K2's 256K window).
+ expect(knownProviderContextWindow({ id: 'kimi-cli', type: 'cli', command: 'kimi' })).toBe(KIMI_CONTEXT_WINDOW);
+ expect(knownProviderContextWindow({ id: 'kimi-tui', type: 'tui', command: 'kimi' })).toBe(KIMI_CONTEXT_WINDOW);
+ });
+
+ it('answers only for a CLI/TUI provider', () => {
+ expect(knownProviderContextWindow({ id: 'codex', type: 'api', command: 'codex' })).toBeNull();
+ expect(knownProviderContextWindow(null)).toBeNull();
+ });
+
+ it('normalizes command paths to the basename for vendor windows (#2337)', () => {
+ // Absolute path to the binary (common when the service PATH can't resolve the CLI).
+ expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: '/opt/homebrew/bin/grok' })).toBe(GROK_CONTEXT_WINDOW);
+ expect(knownProviderContextWindow({ id: 'custom', type: 'tui', command: '/usr/local/bin/codex' })).toBe(CODEX_CONTEXT_WINDOW);
+ expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: '/opt/homebrew/bin/agy' })).toBe(GEMINI_CONTEXT_WINDOW);
+ // The shared vendor predicate also accepts the `antigravity` basename, so
+ // the window agrees with the effort ladder for that spelling too.
+ expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: '/usr/local/bin/antigravity' })).toBe(GEMINI_CONTEXT_WINDOW);
+ // Relative path.
+ expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: './bin/codex' })).toBe(CODEX_CONTEXT_WINDOW);
+ // Windows .exe suffix + backslash separators.
+ expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: 'C:\\tools\\grok.exe' })).toBe(GROK_CONTEXT_WINDOW);
+ expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: '/opt/homebrew/bin/kimi' })).toBe(KIMI_CONTEXT_WINDOW);
+ // Unrelated custom command still falls through to null.
+ expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: '/opt/homebrew/bin/mycli' })).toBeNull();
+ });
+});
+
+describe('providerContextWindows — catalog windows', () => {
+ it('reads the window a model refresh recorded for this model', () => {
+ expect(catalogModelContextWindow({ modelContextWindows: { m: 1_000_000 } }, 'm')).toBe(1_000_000);
+ });
+
+ it('ignores a malformed or unrelated catalog entry instead of budgeting from it', () => {
+ expect(catalogModelContextWindow({ modelContextWindows: { m: 0 } }, 'm')).toBeNull();
+ expect(catalogModelContextWindow({ modelContextWindows: { m: 'lots' } }, 'm')).toBeNull();
+ expect(catalogModelContextWindow({ modelContextWindows: { other: 1_000 } }, 'm')).toBeNull();
+ expect(catalogModelContextWindow({ modelContextWindows: null }, 'm')).toBeNull();
+ expect(catalogModelContextWindow({ modelContextWindows: { m: 1_000 } }, null)).toBeNull();
+ });
+});
diff --git a/server/lib/providerGateways.js b/server/lib/providerGateways.js
index 8094c499c5..cae22d5b88 100644
--- a/server/lib/providerGateways.js
+++ b/server/lib/providerGateways.js
@@ -24,14 +24,13 @@
* it imports nothing, so it stays importable from `providerModels.js`, which the
* standalone autofixer process pulls in.
*
- * **Three copies of this table exist, by architecture, and must stay in lockstep:**
+ * **Two copies of this table exist, by architecture, and must stay in lockstep:**
* 1. this file — the PortOS server;
* 2. `aiToolkit/internal/gateways.js` — the vendored toolkit, which may not
* import out of its own directory (see `aiToolkit/AGENTS.md`);
- * `providerGateways.parity.test.js` fails when the two drift;
- * 3. `client/src/utils/providerGateways.js` — the browser, which cannot import server
- * code at all; `providerGateways.parity.test.js` reads it as TEXT (never
- * imports it) and pins the fields it carries.
+ * `providerGateways.parity.test.js` fails when the two drift.
+ * The browser is not a third: this leaf is pure, so
+ * `client/src/utils/providerGateways.js` re-exports it.
*/
/**
@@ -97,3 +96,6 @@ export function gatewayForProvider(provider) {
/** `gatewayForProvider`, reduced to the id (which is also the OpenCode namespace). */
export const gatewayIdForProvider = (provider) => gatewayForProvider(provider)?.id ?? null;
+
+/** True when a provider is an OpenCode wrapper front-ending any hosted gateway. */
+export const isGatewayBackedProvider = (provider) => gatewayForProvider(provider) !== null;
diff --git a/server/lib/providerGateways.parity.test.js b/server/lib/providerGateways.parity.test.js
index 219f21c157..c416c6ccea 100644
--- a/server/lib/providerGateways.parity.test.js
+++ b/server/lib/providerGateways.parity.test.js
@@ -1,103 +1,19 @@
/**
- * The gateway registry exists in three places by architecture — the vendored
- * `aiToolkit/` may not import out of its own directory, and the browser cannot
- * import server code at all. This suite pins all three together so a new
- * gateway added to one is never silently missing from another (which would show
- * up as a wrapper that spawns fine but can never refresh its models, or a
- * gateway the server supports that no picker ever offers).
+ * The gateway registry exists in two places by architecture — the vendored
+ * `aiToolkit/` may not import out of its own directory, so it carries its own
+ * copy. This suite pins the two together so a new gateway added to one is never
+ * silently missing from the other (which would show up as a wrapper that spawns
+ * fine but can never refresh its models).
*
- * The two SERVER copies are compared as VALUES — the toolkit module imports
- * cleanly here, so `toEqual` pins every field including `baseURL`.
+ * The browser needs no pin: `client/src/utils/providerGateways.js` re-exports
+ * this leaf rather than copying it.
*
- * The client copy (`client/src/utils/providerGateways.js`) is compared as TEXT: it is
- * read with `readFileSync` and its rows are parsed out of the source, never
- * imported, so the client's dependency tree stays out of the server CI job.
- * That comparison is deliberately field-scoped — the browser omits `baseURL`
- * and `legacyApiKeyField` (it never dials the gateway, and it never handles the
- * key), so `toEqual` against the server rows cannot be used. The fields it does
- * carry are all user-visible or dispatch-critical: `id` is the OpenCode
- * namespace AND the sibling-key lookup, `label` and `apiKeyEnv` are rendered in
- * the provider form, and `legacyMarker` is how a pre-registry stored record
- * still resolves.
+ * The two copies are compared as VALUES — the toolkit module imports cleanly
+ * here, so `toEqual` pins every field including `baseURL`.
*/
import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'fs';
-import { resolve, dirname } from 'path';
-import { fileURLToPath } from 'url';
-import { PROVIDER_GATEWAYS as SERVER_GATEWAYS } from './providerGateways.js';
+import { PROVIDER_GATEWAYS as SERVER_GATEWAYS, gatewayForProvider as serverGatewayFor } from './providerGateways.js';
import { PROVIDER_GATEWAYS as TOOLKIT_GATEWAYS, gatewayForProvider as toolkitGatewayFor } from './aiToolkit/internal/gateways.js';
-import { gatewayForProvider as serverGatewayFor } from './providerGateways.js';
-import { extractDeclaration, stripCommentsAndNormalize } from './mirrorParity.js';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const CLIENT_PATH = resolve(__dirname, '../../client/src/utils/providerGateways.js');
-
-// The fields the browser copy carries, and the only ones it can be held to.
-const CLIENT_FIELDS = ['id', 'label', 'apiKeyEnv', 'legacyMarker'];
-
-const pickClientFields = (row) => Object.fromEntries(
- CLIENT_FIELDS.filter((field) => row[field] !== undefined).map((field) => [field, row[field]]),
-);
-
-// The whole normalized declaration, anchored: `export const PROVIDER_GATEWAYS =
-// Object.freeze([ … ]);`. Anchoring is what makes an unrecognized shape fail
-// closed — a scan for `{…}` anywhere in the declaration would keep reading the
-// old row literals out of a table that had been wrapped in a transform, and
-// report a registry that no longer exists as intact.
-const TABLE_RE = /^(?:export\s+)?const\s+PROVIDER_GATEWAYS\s*=\s*Object\.freeze\(\s*\[(.*)\]\s*\)\s*;$/;
-// One `Object.freeze({ … })` row at the head of the remaining array body, plus
-// its trailing separator.
-const NEXT_ROW_RE = /^Object\.freeze\(\s*\{([^{}]*)\}\s*\)\s*(?:,\s*)?/;
-// One `key: 'value'` property at the head of the remaining row body, plus its
-// trailing separator. Escapes are rejected outright — no gateway field has one,
-// and decoding them by inspection is how a parser starts guessing.
-const NEXT_ROW_FIELD_RE = /^(\w+)\s*:\s*'([^'\\]*)'\s*(?:,\s*)?/;
-
-/**
- * Consume `text` with `nextRe` until nothing is left, collecting what each
- * match yields — or null the moment a leftover doesn't match.
- *
- * Failing closed on the leftover is the whole point: a `{ id: 'x', ...overrides }`
- * row, or a table wrapped in a helper, read by a scan-for-what-I-recognize pass
- * would compare equal to the static shape it stopped being, and the drift this
- * guard exists to catch would pass green.
- */
-function consumeAll(text, nextRe, valueOf) {
- const collected = [];
- let rest = text.trim();
- while (rest.length > 0) {
- const match = nextRe.exec(rest);
- if (!match) return null;
- const value = valueOf(match, collected);
- if (value === null) return null;
- collected.push(value);
- rest = rest.slice(match[0].length);
- }
- return collected;
-}
-
-/** One registry row as a plain object, or null when it is not a static table. */
-function parseGatewayRow(body) {
- const fields = consumeAll(body, NEXT_ROW_FIELD_RE, ([, key, value], seen) =>
- (seen.some(([existing]) => existing === key) ? null : [key, value]));
- return fields && Object.fromEntries(fields);
-}
-
-/**
- * A registry declaration's rows, or null when it — or any row in it — is no
- * longer a flat run of static literals. Anything more structural would mean
- * importing the module, which is the thing this file exists to avoid.
- */
-function parseGatewayTable(declaration) {
- const table = TABLE_RE.exec(stripCommentsAndNormalize(declaration));
- return table && consumeAll(table[1], NEXT_ROW_RE, ([, body]) => parseGatewayRow(body));
-}
-
-/** `parseGatewayTable` over the browser copy's `PROVIDER_GATEWAYS`. */
-function parseClientGatewayRows() {
- const declaration = extractDeclaration(readFileSync(CLIENT_PATH, 'utf8'), 'PROVIDER_GATEWAYS');
- return declaration == null ? null : parseGatewayTable(declaration);
-}
describe('providerGateways ↔ aiToolkit/internal/gateways parity', () => {
it('declares the same rows, in the same order', () => {
@@ -118,42 +34,3 @@ describe('providerGateways ↔ aiToolkit/internal/gateways parity', () => {
}
});
});
-
-describe('providerGateways ↔ client/src/utils/providerGateways.js parity', () => {
- const clientRows = parseClientGatewayRows();
-
- it('the client declares a parseable PROVIDER_GATEWAYS table', () => {
- expect(
- clientRows,
- 'client/src/utils/providerGateways.js#PROVIDER_GATEWAYS is missing, or a row is no longer a flat table of static `key: \'value\'` properties — this guard cannot read it, so re-shape the row or teach the parser',
- ).not.toBeNull();
- expect(clientRows.length).toBeGreaterThan(0);
- });
-
- // The parser must refuse what it cannot see through, not skip it: a row that
- // pulls fields in at runtime would otherwise compare equal to the static row
- // it stopped being.
- it('refuses a row carrying anything but static single-quoted properties', () => {
- expect(parseGatewayRow("id: 'openrouter', label: 'OpenRouter'")).toEqual({ id: 'openrouter', label: 'OpenRouter' });
- expect(parseGatewayRow("id: 'openrouter', ...overrides")).toBeNull();
- expect(parseGatewayRow("id: 'openrouter', label: LABELS.openrouter")).toBeNull();
- expect(parseGatewayRow("id: 'openrouter', id: 'orcarouter'")).toBeNull();
- });
-
- // …and the table reader must refuse a declaration whose rows it can still
- // see but whose exported value they no longer are.
- it('refuses a table that is not a plain frozen array of frozen rows', () => {
- const rows = "Object.freeze({ id: 'openrouter', label: 'OpenRouter' })";
- expect(parseGatewayTable(`export const PROVIDER_GATEWAYS = Object.freeze([${rows}]);`))
- .toEqual([{ id: 'openrouter', label: 'OpenRouter' }]);
- expect(parseGatewayTable(`export const PROVIDER_GATEWAYS = Object.freeze([${rows}].map(withBaseURL));`)).toBeNull();
- expect(parseGatewayTable(`export const PROVIDER_GATEWAYS = Object.freeze([${rows}, ...EXTRA]);`)).toBeNull();
- });
-
- it('declares the same rows, in the same order (browser-visible fields)', () => {
- expect(
- clientRows,
- 'the gateway registry diverged — server/lib/providerGateways.js is authoritative; port the row verbatim (minus baseURL / legacyApiKeyField, which the browser omits)',
- ).toEqual(SERVER_GATEWAYS.map(pickClientFields));
- });
-});
diff --git a/server/lib/providerHarnesses.parity.test.js b/server/lib/providerHarnesses.parity.test.js
deleted file mode 100644
index 9518942470..0000000000
--- a/server/lib/providerHarnesses.parity.test.js
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * The harness registry lives in two places by architecture: the browser cannot
- * import server code, so `client/src/utils/providerHarnesses.js` carries its own
- * id→label table. This suite pins the two together, so a harness added to the
- * server registry can never render as a bare id in the connection management UI
- * — and a harness REMOVED from the server can never linger as a label the
- * browser still offers.
- *
- * The client copy is read with `readFileSync` and parsed out of the source,
- * never imported, so the client's dependency tree stays out of the server CI
- * job (`server/vitest.config.js` globs this directory).
- */
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'fs';
-import { resolve, dirname } from 'path';
-import { fileURLToPath } from 'url';
-import { PROVIDER_HARNESSES } from './providerHarnesses.js';
-import { stripCommentsAndNormalize } from './mirrorParity.js';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const CLIENT_PATH = resolve(__dirname, '../../client/src/utils/providerHarnesses.js');
-
-// The whole normalized declaration, ANCHORED: a scan for `key: 'value'` pairs
-// anywhere in the file would keep reading row literals out of a table that had
-// been wrapped in a transform and report a registry that no longer exists as
-// intact. Anchoring makes an unrecognized shape fail closed instead.
-const TABLE_RE = /^(?:export\s+)?const\s+PROVIDER_HARNESS_LABELS\s*=\s*Object\.freeze\(\s*\{(.*)\}\s*\)\s*;$/;
-// One `id: 'Label'` entry at the head of the remaining body, plus its separator.
-// Escapes are rejected outright — no harness label has one, and decoding them by
-// inspection is how a parser starts guessing.
-const NEXT_ENTRY_RE = /^(\w+)\s*:\s*'([^'\\]*)'\s*(?:,\s*)?/;
-
-/** The client's mirrored table as a plain object, or null when it isn't a static one. */
-function parseClientLabels(source) {
- const declaration = stripCommentsAndNormalize(source)
- .split(';')
- .map((statement) => `${statement.trim()};`)
- .find((statement) => TABLE_RE.test(statement));
- if (!declaration) return null;
-
- const labels = {};
- let rest = TABLE_RE.exec(declaration)[1].trim();
- while (rest.length > 0) {
- const match = NEXT_ENTRY_RE.exec(rest);
- if (!match) return null;
- labels[match[1]] = match[2];
- rest = rest.slice(match[0].length);
- }
- return labels;
-}
-
-describe('provider harness registry parity', () => {
- const clientLabels = parseClientLabels(readFileSync(CLIENT_PATH, 'utf8'));
-
- it('parses the browser mirror as a static table', () => {
- expect(clientLabels).not.toBeNull();
- });
-
- it('mirrors every server harness id and label, and adds none', () => {
- expect(clientLabels).toEqual(
- Object.fromEntries(PROVIDER_HARNESSES.map((harness) => [harness.id, harness.label])),
- );
- });
-
- // A guard that cannot fail is not a guard. These pin the parser itself:
- // real drift has to be DETECTED, and an unparseable table has to fail closed
- // rather than silently compare an empty registry against an empty one.
- it('detects a drifted label', () => {
- const drifted = parseClientLabels(
- readFileSync(CLIENT_PATH, 'utf8').replace("claude: 'Claude Code'", "claude: 'Claude'"),
- );
- expect(drifted).not.toEqual(
- Object.fromEntries(PROVIDER_HARNESSES.map((harness) => [harness.id, harness.label])),
- );
- });
-
- it('fails closed on a table it cannot read statically', () => {
- expect(parseClientLabels(
- "export const PROVIDER_HARNESS_LABELS = Object.freeze({ ...someOtherTable });",
- )).toBeNull();
- });
-});
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.js
index a10f531cf3..90a1bc9f1d 100644
--- a/server/lib/providerModels.js
+++ b/server/lib/providerModels.js
@@ -1,6 +1,14 @@
/**
* Shared sentinel and helpers for provider model resolution.
- * Mirrored in client/src/utils/providerModels.js (sentinels, ladders) and client/src/utils/providerTypes.js (predicates) — keep in sync.
+ *
+ * Pure leaf (no Node built-ins, nothing outside server/lib), so the browser
+ * imports it: client/src/utils/providerModels.js re-exports the sentinels,
+ * effort ladders and the Antigravity split, and delegates its own ladder
+ * resolution to `effortLevelsForProvider` / `clampEffortToLadder`. The
+ * `isXProvider` predicates are still copied in client/src/utils/providerTypes.js
+ * — keep those in sync. One caveat the purity guard cannot see: the Bedrock /
+ * Claude-argv resolvers below default to `process.env`, so they are server-only
+ * — never call them from the browser (they tree-shake out unless something does).
*/
import { gatewayIdForProvider, isGatewayNamespace } from './providerGateways.js';
@@ -78,9 +86,10 @@ export const resolveCliModel = (model) => isConfiguredDefaultModel(model) ? null
// verified against claude CLI v2.1.x (`--help`), current Codex CLI config
// values (`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, plus
// model-gated `ultra`) and agy
-// (`--help`: "Reasoning effort for the current CLI session (low|medium|high)"). Mirrored in
-// client/src/utils/providerModels.js — keep in sync
-// (`providerModels.mirror.test.js` fails when the two copies drift).
+// (`--help`: "Reasoning effort for the current CLI session (low|medium|high)").
+// Re-exported by client/src/utils/providerModels.js, whose own
+// `effortLevelsForProvider` layers the server-published `effortLevels` /
+// `effortLevelsByModel` fields on top of these ladders.
//
// Codex Ultra adds automatic task delegation on the models that advertise it.
// Keep it model-gated: older Codex models and Luna top out at `max`.
@@ -165,7 +174,7 @@ const codexEffortLevelsForModel = (model) => {
// errors with `gemini-3.1-pro has no "medium" effort (available: low, high)`.
// So the tiers a base model offers are derived from the provider's own model
// catalog rather than assumed to be the full low/medium/high ladder.
-// Mirrored in client/src/utils/providerModels.js — keep in lockstep.
+// Re-exported by client/src/utils/providerModels.js.
// ---------------------------------------------------------------------------
const ANTIGRAVITY_EFFORT_SUFFIX_RE = new RegExp(`-(${ANTIGRAVITY_EFFORT_LEVELS.join('|')})$`);
@@ -438,9 +447,22 @@ const EFFORT_RANK = Object.freeze(['minimal', 'low', 'medium', 'high', 'xhigh',
* @returns {string|null}
*/
export function resolveCliEffort(effort, provider, model = null) {
- if (!effort) return null;
- const levels = effortLevelsForProvider(provider, model);
- if (!levels) return null;
+ return clampEffortToLadder(effort, effortLevelsForProvider(provider, model));
+}
+
+/**
+ * The clamp behind `resolveCliEffort`, over an explicit ladder: the effort
+ * itself when `levels` has it, else the nearest supported level below it, else
+ * the ladder's weakest — or null when there is no effort, no ladder, or the
+ * value is not an effort at all. The client's `resolveCliEffort` clamps its own
+ * ladder (which can come from the server-published fields) through this, so
+ * the two ends can't rank the rungs differently.
+ * @param {string|null|undefined} effort
+ * @param {readonly string[]|null|undefined} levels
+ * @returns {string|null}
+ */
+export function clampEffortToLadder(effort, levels) {
+ if (!effort || !levels) return null;
if (levels.includes(effort)) return effort;
const requested = EFFORT_RANK.indexOf(effort);
if (requested === -1) return null; // not an effort value at all
diff --git a/server/lib/providerModels.mirror.test.js b/server/lib/providerModels.mirror.test.js
deleted file mode 100644
index 06f51320e3..0000000000
--- a/server/lib/providerModels.mirror.test.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * Mirror parity test for the effort ladders and model sentinels shared by
- * server/lib/providerModels.js and client/src/utils/providerModels.js (the browser
- * cannot import server code, so the tables are duplicated on each side behind a
- * "keep in sync" comment).
- *
- * Until now that comment was the only pin: each side had its own hardcoded
- * expectations (`providerModels.test.js` / `providers.test.js`), so an effort
- * level or Codex Ultra model added to one copy alone left BOTH suites green.
- * The two ends then disagree about what the user may select — an effort the
- * picker offers and the server's ladder rejects is clamped to something else or
- * dropped, and an ultra-capable model the client hasn't heard of loses its
- * `ultra` rung entirely.
- *
- * Only the DATA is mirrored. `effortLevelsForProvider` / `resolveCliEffort` are
- * legitimately `function` server-side and arrow consts client-side (and the
- * client's ladder resolution falls back to the server-published
- * `effortLevels`/`effortLevelsByModel` fields, which have no server-side
- * counterpart), so they are not compared. Comparison strips comments, so
- * per-side commentary may diverge — logic can't.
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'fs';
-import { resolve, dirname } from 'path';
-import { fileURLToPath } from 'url';
-import { compareDeclaration } from './mirrorParity.js';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-const SERVER_PATH = resolve(__dirname, 'providerModels.js');
-const CLIENT_PATH = resolve(__dirname, '../../client/src/utils/providerModels.js');
-
-const MIRRORED_NAMES = [
- 'CLAUDE_EFFORT_LEVELS',
- 'CODEX_EFFORT_LEVELS',
- 'CODEX_ULTRA_EFFORT_LEVELS',
- 'ANTIGRAVITY_EFFORT_LEVELS',
- 'OPENCODE_LOCAL_EFFORT_LEVELS',
- 'CURSOR_EFFORT_LEVELS',
- // The ladder a Codex model gets is model-gated, so the gate's membership is
- // as load-bearing as the ladders themselves: a new Ultra model added
- // server-side only tops the client picker out at `max`.
- 'CODEX_ULTRA_MODELS',
- // The other model gate: which Codex models REJECT `minimal`. Divergence here
- // is worse than a missing rung — a client that still offers `minimal` for a
- // gpt-6 model lets the user pick a level whose run dies on an HTTP 400.
- 'CODEX_NO_MINIMAL_MODEL_RE',
- // The clamp order. Divergence here is silent — every value stays "known", it
- // just resolves to a different rung than the run will actually use.
- 'EFFORT_RANK',
- 'CONFIGURED_DEFAULT_SENTINELS',
- // Derived FROM ANTIGRAVITY_EFFORT_LEVELS on both sides, and pinned anyway:
- // the suffix split is what turns `gemini-3.6-flash-high` into a base model
- // plus an effort, so a divergence strands a stored model id.
- 'ANTIGRAVITY_EFFORT_SUFFIX_RE',
-];
-
-describe('providerModels↔client providers effort-ladder mirror parity', () => {
- const serverSrc = readFileSync(SERVER_PATH, 'utf8');
- const clientSrc = readFileSync(CLIENT_PATH, 'utf8');
-
- it('both files are non-empty', () => {
- expect(serverSrc.length).toBeGreaterThan(100);
- expect(clientSrc.length).toBeGreaterThan(100);
- });
-
- for (const name of MIRRORED_NAMES) {
- it(`${name} is present and identical on both sides (code only)`, () => {
- const { serverDecl, clientDecl, serverNorm, clientNorm } =
- compareDeclaration(serverSrc, clientSrc, name);
-
- expect(serverDecl, `server/lib/providerModels.js is missing: ${name}`).not.toBeNull();
- expect(clientDecl, `client/src/utils/providerModels.js is missing: ${name}`).not.toBeNull();
- expect(
- clientNorm,
- `"${name}" diverged — the server copy is authoritative; port the change verbatim`,
- ).toBe(serverNorm);
- });
- }
-});
diff --git a/server/services/stageRunner.js b/server/services/stageRunner.js
index b94a34b247..f39a4747ba 100644
--- a/server/services/stageRunner.js
+++ b/server/services/stageRunner.js
@@ -20,9 +20,14 @@ import { resolveEffectiveModel, runPromptThroughProvider, DEFAULT_TIMEOUT_MS, is
import { stripCodeFences } from '../lib/llmText.js';
import { extractCodexAssistant } from '../lib/codexAssistantExtract.js';
import { getActiveProvider, getProviderById } from './providers.js';
-import { commandBasename, isCodexProvider } from '../lib/providerModels.js';
import { buildPrompt, getStage } from './promptService.js';
import { stagePinsIgnored } from '../lib/stagePinPolicy.js';
+import {
+ DEFAULT_LARGE_CONTEXT_WINDOW,
+ knownModelContextWindow,
+ knownProviderContextWindow,
+ catalogModelContextWindow,
+} from '../lib/providerContextWindows.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';
@@ -171,55 +176,6 @@ export function resolveEffortHint(stage, options = {}) {
return options.effortOverride || stage?.effort || options.effortDefault || null;
}
-// 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
-// ceiling (Claude/GPT/Gemini are ≥128K, often ~1M), so it means "a typical
-// whole manuscript fits in one call" without over-promising. It is a floor to
-// escape, not a cap to honor: refreshing the provider's models records each
-// model's real window (`modelContextWindows`), and an explicit `contextWindow`
-// overrides both.
-export const DEFAULT_LARGE_CONTEXT_WINDOW = 128_000;
-export const CODEX_CONTEXT_WINDOW = 1_000_000;
-export const GEMINI_CONTEXT_WINDOW = 1_048_576;
-export const GROK_CONTEXT_WINDOW = 256_000;
-export const KIMI_CONTEXT_WINDOW = 256_000;
-
-// Keep in sync with client/src/utils/providerContextWindows.js.
-const KNOWN_MODEL_CONTEXT_WINDOWS = Object.freeze([
- [/gpt[-_.:/]?5\.5(?:[-_.:/]|\b)/i, CODEX_CONTEXT_WINDOW],
- [/gpt[-_.:/]?5\.4[-_.:/]?mini(?:[-_.:/]|\b)/i, 400_000],
- [/gpt[-_.:/]?5\.4(?![-_.:/]?(?:mini|nano))(?:[-_.:/]|\b)/i, CODEX_CONTEXT_WINDOW],
- [/claude[-_.:/]?fable[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
- [/claude[-_.:/]?mythos[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
- [/claude[-_.:/]?opus[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
- [/claude[-_.:/]?opus[-_.:/]?4[-_.:/]?8/i, 1_000_000],
- [/claude[-_.:/]?sonnet[-_.:/]?5(?:[-_.:/]|\b)/i, 1_000_000],
- [/claude[-_.:/]?sonnet[-_.:/]?4[-_.:/]?6(?:[-_.:/]|\b)/i, 1_000_000],
- [/claude[-_.:/]?sonnet[-_.:/]?4(?:[-_.:/]|\b)/i, 200_000],
- [/claude[-_.:/]?haiku[-_.:/]?4(?:[-_.:/]|\b)/i, 200_000],
- [/gemini[-_.:/]?2\.5[-_.:/]?pro(?:[-_.:/]|\b)/i, GEMINI_CONTEXT_WINDOW],
-]);
-
-export function knownModelContextWindow(model) {
- if (typeof model !== 'string' || !model.trim()) return null;
- const found = KNOWN_MODEL_CONTEXT_WINDOWS.find(([pattern]) => pattern.test(model));
- return found ? found[1] : null;
-}
-
-export function knownProviderContextWindow(provider) {
- if (provider?.type !== 'cli' && provider?.type !== 'tui') return null;
- const id = String(provider?.id || '').toLowerCase();
- // Normalize to the basename so a path-configured command (/opt/homebrew/bin/grok)
- // resolves the same vendor window as a bare `grok` on PATH — matching how the
- // arg-builder predicates (isOpencodeCommand/isGrokCommand) key on commandBasename.
- const command = commandBasename(provider?.command);
- if (isCodexProvider(provider)) return CODEX_CONTEXT_WINDOW;
- if (id === 'antigravity-cli' || id === 'antigravity-tui' || command === 'agy') return GEMINI_CONTEXT_WINDOW;
- if (id === 'grok-cli' || id === 'grok-tui' || command === 'grok') return GROK_CONTEXT_WINDOW;
- if (id === 'kimi-cli' || id === 'kimi-tui' || command === 'kimi') return KIMI_CONTEXT_WINDOW;
- return null;
-}
-
// The local-backend concurrency gate (cap concurrent in-flight calls per local
// endpoint so N parallel stage calls don't thrash one GPU's VRAM) lives in
// promptRunner.js — the actual execution layer — so it covers the initially
@@ -240,29 +196,14 @@ const isLikelyLargeContextProvider = (provider) => {
return false;
};
-/**
- * The window this provider's own `/models` catalog reported for this model, or
- * `null` when the catalog never mentioned it. Populated by model refresh (see
- * aiToolkit/internal/modelCatalog.js), so it is the serving side's declaration
- * rather than a guess — which is why it outranks the hand-maintained regex
- * table below. Mirror of `catalogModelContextWindow` in
- * client/src/utils/providerContextWindows.js.
- */
-export function catalogModelContextWindow(provider, model) {
- const windows = provider?.modelContextWindows;
- if (!windows || typeof windows !== 'object') return null;
- if (typeof model !== 'string' || !model) return null;
- const tokens = Number(windows[model]);
- return Number.isFinite(tokens) && tokens > 0 ? tokens : null;
-}
-
// 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).
+// backends). The rungs themselves live in lib/providerContextWindows.js, the
+// pure leaf the browser's provider-card meter shares.
export function effectiveContextWindow(provider, model) {
if (Number(provider?.contextWindow) > 0) return Number(provider.contextWindow);
const catalogWindow = catalogModelContextWindow(provider, model);
diff --git a/server/services/stageRunner.mirror.test.js b/server/services/stageRunner.mirror.test.js
deleted file mode 100644
index fa6b09f991..0000000000
--- a/server/services/stageRunner.mirror.test.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * Mirror parity test for the `KNOWN_MODEL_CONTEXT_WINDOWS` table, which lives
- * in both server/services/stageRunner.js and client/src/utils/providerContextWindows.js (the
- * client can't import server modules, so the table is duplicated behind a
- * "Keep in sync" comment on each side).
- *
- * Until now the mirror was pinned by that comment alone: each side had its own
- * hardcoded expectations (`stageRunner.test.js` / `providers.test.js`), so a
- * model bump that added a row to only one copy left BOTH suites green. The two
- * ends would then disagree about whether a given manuscript fits in one call —
- * the server chunking against the real window while the client's "context used"
- * meter falls through to the conservative DEFAULT_LARGE_CONTEXT_WINDOW, or vice
- * versa. Silent, and ~8x off.
- *
- * Only the table is mirrored: `knownModelContextWindow` is legitimately a
- * `function` server-side and an arrow const client-side, so it is not compared.
- * Comparison strips comments, so per-side commentary may diverge — logic can't.
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'fs';
-import { resolve, dirname } from 'path';
-import { fileURLToPath } from 'url';
-import { compareDeclaration } from '../lib/mirrorParity.js';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-const SERVER_PATH = resolve(__dirname, 'stageRunner.js');
-const CLIENT_PATH = resolve(__dirname, '../../client/src/utils/providerContextWindows.js');
-
-// The table's rows are `[/regex/i, SOME_CONTEXT_WINDOW]` — the *values* are
-// symbols defined separately in each file, so pinning the table text alone
-// leaves the exact hole this test exists to close: edit `CODEX_CONTEXT_WINDOW`
-// on one side only and the table still matches byte-for-byte while the two
-// ends silently disagree about the window. Pin the constants too.
-const MIRRORED_NAMES = [
- 'DEFAULT_LARGE_CONTEXT_WINDOW',
- 'CODEX_CONTEXT_WINDOW',
- 'GEMINI_CONTEXT_WINDOW',
- 'GROK_CONTEXT_WINDOW',
- 'KIMI_CONTEXT_WINDOW',
- 'KNOWN_MODEL_CONTEXT_WINDOWS',
- // The catalog rung sits ABOVE the table in both ladders, so a divergence here
- // is the same silent ~8x disagreement the table's parity closes. Both copies
- // are declared `function` precisely so this comparison can be made.
- 'catalogModelContextWindow',
-];
-
-describe('stageRunner↔client providers context-window mirror parity', () => {
- const serverSrc = readFileSync(SERVER_PATH, 'utf8');
- const clientSrc = readFileSync(CLIENT_PATH, 'utf8');
-
- it('both files are non-empty', () => {
- expect(serverSrc.length).toBeGreaterThan(100);
- expect(clientSrc.length).toBeGreaterThan(100);
- });
-
- for (const name of MIRRORED_NAMES) {
- it(`${name} is present and identical on both sides (code only)`, () => {
- const { serverDecl, clientDecl, serverNorm, clientNorm } =
- compareDeclaration(serverSrc, clientSrc, name);
-
- expect(serverDecl, `server/services/stageRunner.js is missing: ${name}`).not.toBeNull();
- expect(clientDecl, `client/src/utils/providerContextWindows.js is missing: ${name}`).not.toBeNull();
- expect(
- clientNorm,
- `"${name}" diverged — the server copy is authoritative; port the change verbatim`,
- ).toBe(serverNorm);
- });
- }
-});
diff --git a/server/services/stageRunner.test.js b/server/services/stageRunner.test.js
index affe212efb..48daa67f2e 100644
--- a/server/services/stageRunner.test.js
+++ b/server/services/stageRunner.test.js
@@ -29,15 +29,7 @@ const {
runInlineLLM,
resolveModel,
extractJson,
- DEFAULT_LARGE_CONTEXT_WINDOW,
- CODEX_CONTEXT_WINDOW,
- GEMINI_CONTEXT_WINDOW,
- GROK_CONTEXT_WINDOW,
- KIMI_CONTEXT_WINDOW,
- catalogModelContextWindow,
effectiveContextWindow,
- knownModelContextWindow,
- knownProviderContextWindow,
resolveStageContext,
resolveJudgeForStage,
resolveEffortHint,
@@ -46,6 +38,7 @@ const {
LOCAL_LLM_MAX_CONCURRENCY,
} = 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');
const apiProvider = (extra = {}) => ({
id: 'mock-api', name: 'Mock', type: 'api', enabled: true, defaultModel: 'm-default', ...extra,
@@ -96,47 +89,6 @@ describe('stageRunner — resolveModel', () => {
});
describe('stageRunner — context windows', () => {
- it('resolves known model windows from the selected model id', () => {
- expect(knownModelContextWindow('gpt-5.5')).toBe(CODEX_CONTEXT_WINDOW);
- expect(knownModelContextWindow('gpt-5.4')).toBe(CODEX_CONTEXT_WINDOW);
- expect(knownModelContextWindow('gpt-5.4-mini')).toBe(400_000);
- expect(knownModelContextWindow('gpt-5.4-nano')).toBeNull();
- expect(knownModelContextWindow('claude-opus-5')).toBe(1_000_000);
- expect(knownModelContextWindow('global.anthropic.claude-opus-5')).toBe(1_000_000);
- expect(knownModelContextWindow('claude-opus-4-8')).toBe(1_000_000);
- expect(knownModelContextWindow('claude-sonnet-5')).toBe(1_000_000);
- expect(knownModelContextWindow('claude-sonnet-4-6')).toBe(1_000_000);
- expect(knownModelContextWindow('us.anthropic.claude-sonnet-4-5-20250929-v1:0')).toBe(200_000);
- expect(knownModelContextWindow('gemini-2.5-pro')).toBe(GEMINI_CONTEXT_WINDOW);
- expect(knownModelContextWindow('unknown-model')).toBeNull();
- });
-
- it('resolves configured-default provider windows by provider identity', () => {
- expect(knownProviderContextWindow({ id: 'codex-tui', type: 'tui', command: 'codex' })).toBe(CODEX_CONTEXT_WINDOW);
- expect(knownProviderContextWindow({ id: 'antigravity-cli', type: 'cli', command: 'agy' })).toBe(GEMINI_CONTEXT_WINDOW);
- // Mirrors client/src/utils/providerContextWindows.js — a custom grok CLI/TUI without an
- // explicit contextWindow must resolve the same 256K on both sides.
- expect(knownProviderContextWindow({ id: 'grok-cli', type: 'cli', command: 'grok' })).toBe(GROK_CONTEXT_WINDOW);
- expect(knownProviderContextWindow({ id: 'grok-tui', type: 'tui', command: 'grok' })).toBe(GROK_CONTEXT_WINDOW);
- // Kimi Code (K2's 256K window) — same on both server + client mirrors.
- expect(knownProviderContextWindow({ id: 'kimi-cli', type: 'cli', command: 'kimi' })).toBe(KIMI_CONTEXT_WINDOW);
- expect(knownProviderContextWindow({ id: 'kimi-tui', type: 'tui', command: 'kimi' })).toBe(KIMI_CONTEXT_WINDOW);
- });
-
- it('normalizes command paths to the basename for vendor windows (#2337)', () => {
- // Absolute path to the binary (common when the service PATH can't resolve the CLI).
- expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: '/opt/homebrew/bin/grok' })).toBe(GROK_CONTEXT_WINDOW);
- expect(knownProviderContextWindow({ id: 'custom', type: 'tui', command: '/usr/local/bin/codex' })).toBe(CODEX_CONTEXT_WINDOW);
- expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: '/opt/homebrew/bin/agy' })).toBe(GEMINI_CONTEXT_WINDOW);
- // Relative path.
- expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: './bin/codex' })).toBe(CODEX_CONTEXT_WINDOW);
- // Windows .exe suffix + backslash separators.
- expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: 'C:\\tools\\grok.exe' })).toBe(GROK_CONTEXT_WINDOW);
- expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: '/opt/homebrew/bin/kimi' })).toBe(KIMI_CONTEXT_WINDOW);
- // Unrelated custom command still falls through to null.
- expect(knownProviderContextWindow({ id: 'custom', type: 'cli', command: '/opt/homebrew/bin/mycli' })).toBeNull();
- });
-
it('keeps an explicit provider contextWindow above model defaults', () => {
expect(effectiveContextWindow(
{ type: 'tui', contextWindow: 64_000 },
@@ -170,14 +122,6 @@ describe('stageRunner — context windows', () => {
)).toBe(64_000);
});
- it('ignores a malformed or unrelated catalog entry instead of budgeting from it', () => {
- expect(catalogModelContextWindow({ modelContextWindows: { m: 0 } }, 'm')).toBeNull();
- expect(catalogModelContextWindow({ modelContextWindows: { m: 'lots' } }, 'm')).toBeNull();
- expect(catalogModelContextWindow({ modelContextWindows: { other: 1_000 } }, 'm')).toBeNull();
- expect(catalogModelContextWindow({ modelContextWindows: null }, 'm')).toBeNull();
- expect(catalogModelContextWindow({ modelContextWindows: { m: 1_000 } }, null)).toBeNull();
- });
-
it('uses model and provider windows before provider numCtx', () => {
expect(effectiveContextWindow(
{ type: 'api', endpoint: 'http://localhost:11434/v1', numCtx: 32_768 },