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

split the client provider helper hub into nine responsibility modules behind a facade

[._.]/ Adam Eivyb6429d476dc0
diff --git a/client/src/components/providers/ProviderNotices.jsx b/client/src/components/providers/ProviderNotices.jsx
index 698e6669d6..634f18bb70 100644
--- a/client/src/components/providers/ProviderNotices.jsx
+++ b/client/src/components/providers/ProviderNotices.jsx
@@ -12,7 +12,7 @@
// copies the key from the sibling API provider whose id equals the gateway id.
// This answers "where do I put the API key?" from the card/form: it's on the
// API provider, not here. `gateway` is a row of PROVIDER_GATEWAYS
-// (client/src/utils/providers.js), so the copy names the right gateway rather
+// (client/src/utils/providerGateways.js), so the copy names the right gateway rather
// than hardcoding one.
export function GatewayKeyHint({ gateway, sibling, className = '', onEdit }) {
if (!gateway) return null;
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 0d994be1c7..f90f4909c0 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -42,10 +42,28 @@ grep -i "what you want to do" client/src/utils/README.md
| `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), `isHttpUrl` / `isHttpsUrl` (safe-href checks), and `tiktokVideoId` / `tiktokEmbedSrc` (host-anchored TikTok video-id extraction + its Embed Player URL, so a reference embeds without loading TikTok's embed.js). |
| `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. |
| `navWorkingSet` | Recent/pinned nav persistence (`recordVisit`, `togglePin`, `isPinned`) plus `resolveRecentNavEntries` for mapping stored deep links back to their longest matching nav-manifest entry. Also `migrateLegacyNavPath(path, commands)` — maps a stored path onto the CURRENT path of the page that used to answer to it, driven by each command's own `previousPaths` (declared in `server/lib/navManifest.js` beside the page that moved, shipped whole in the palette manifest). A pin is a stored route path, so without it a moved page's pin stops matching the manifest and the sidebar row silently vanishes on update. |
-| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isCodexSubscriptionProvider` (subscription readiness is keyed on the `codex` command, never an editable id), `isAntigravityProvider`, `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 — `PROVIDER_GATEWAYS` / `gatewayForProvider` / `isGatewayBackedProvider` (an OpenCode wrapper front-ending a hosted OpenAI-compatible gateway — `orcarouter`, `openrouter` — which inherits 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; keep the three copies in lockstep), `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, `resolveEffectiveProvider` — the provider a record actually runs on (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 `seriesLlmOverride.js`: which provider/model a Pipeline **series** run resolves to — per-run override → `series.llm` → active provider) and `providerModelLabel` (the one "Provider / model" phrasing), configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). `TOOL_FREE_LOCAL_PROVIDER_IDS`, `TOOL_FREE_LOCAL_TEXT_CAPABILITIES`, `isToolFreeLocalProvider`, `isToolFreeLocalModel`, and `toolFreeLocalSelectionPolicy` share the fail-closed local/text/no-tools filter used by security-sensitive provider/model/effort pickers. `PUBLIC_REVIEW_NO_TOOL_POSTURE` / `PUBLIC_REVIEW_ACTIONS_POSTURE`, `supportsPublicReviewPosture`, `enforcesPublicReviewPosture`, and `publicReviewSelectionPolicy` are the pr-reviewer counterpart (mirror of server `agentExecutionProfiles.js`): a pipeline stage names a POSTURE, the server publishes each provider's `publicReviewPostures` (runnable) and `publicReviewEnforcedPostures` (backed by a vendor sandbox recipe) on `GET /api/providers`, and the picker offers exactly the providers this install can run the stage on — no vendor is named on either side. Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command? Mirrors only the *normalization* in `server/cos-runner/allowedCommands.js` (the list itself arrives as `runnerAllowedCommands` on `GET /api/providers`, because the allowlist is an exec boundary and stays hand-curated server-side); returns `null` for "list not fetched / field blank" so a failed fetch never renders a warning. Pinned by `server/cos-runner/allowedCommands.parity.test.js`. `isPrivateNetworkEndpoint(endpoint)` — loopback, RFC1918/tailnet address, or a `.local`/`.ts.net`/single-label host, i.e. somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key. `isLocalInstanceProvider(provider)` — the narrower question, mirroring server `localProviderRuntime.js#isLocalInstanceEndpoint`: does this provider talk to a daemon on THIS machine (loopback, or no endpoint at all)? Gate anything that explains a provider by inspecting the host PortOS runs on — install state, "start it from Settings → Local LLM" — since `localBackendForProvider` matches by NAME and would otherwise claim a peer's LM Studio. `codexRoutingAdvisory(provider)` reads the server-published `prerequisiteAdvisories` entry saying the install’s own `~/.codex/config.toml` re-points Codex model routing — a NON-blocking notice (never in `missingPrerequisites`, so it never buckets a card as NEEDS SETUP) whose `baseUrl` is machine-local and renders in the UI only. Server-only, with no client fallback: the browser cannot read that file. And `credentialSource(provider)` plus `providerCardState(provider, { runtime, status, keySetFor, envVarSet })` + `PROVIDER_CARD_STATE` — is a provider ready to run, benched, blocked on a missing prerequisite (CLI not installed / API key absent / empty credential environment variable), or simply switched off? Reads the SERVER's `missingPrerequisites` (published per provider on `GET /api/providers` from `server/lib/providerPrerequisites.js`, and the same computation `getFallbackProvider` routes on) and adds the local-app runtime shape plus tri-state checks for stored, inherited, and process environment credentials. Unknown lookup values mean "not probed", never "missing". Drives the AI Providers page card colors and grouping — distinct from `ProviderReadiness`/`GET /api/providers/readiness`, which probes the local daemon behind a provider. `resolvesOutsidePortosPath(provider)` — does this provider resolve its binary somewhere the runtime probe never looked (an explicit path in `command`, or its own `PATH` in `envVars`)? Mirror of the same two guards in the server's `providerRuntimeKey`, and what keeps the card's badge from accusing a working provider the router happily routes. And `providerRuntimeKey(provider)` — the key a provider's runtime is published under by `GET /api/providers/runtimes`, so a card can show its CLI install status (bare binary name for a cli/tui provider, provider id for an API provider fronted by a local app); the runtime table itself stays server-side. |
| `systemCapabilities` | Server-annotated hardware compatibility helpers: preserve model/provider choices when compatibility is unknown, and hide only entries whose `hardwareCompatibility.state` is definitively `unavailable`. |
| `layeredIntelligenceReasons` | Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens, shared by the on-demand toast and the durable "Last run" line (`formatLiReason`, `liReasonTone`, `LI_NEUTRAL_REASONS`). |
+## AI providers
+
+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.
+
+| 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`, `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. |
+| `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). |
+| `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. |
+| `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. |
+
## Module loading / resilience
| Module | Purpose |
diff --git a/client/src/utils/index.js b/client/src/utils/index.js
index 99d79b0dc3..0c6fe2eead 100644
--- a/client/src/utils/index.js
+++ b/client/src/utils/index.js
@@ -26,10 +26,24 @@ export * from './sleep.js';
export * from './urlNormalize.js';
export * from './platform.js';
export * from './navWorkingSet.js';
-export * from './providers.js';
export * from './systemCapabilities.js';
export * from './layeredIntelligenceReasons.js';
+// === AI providers ===
+// `providers.js` is the compatibility facade over the nine modules below (see
+// its header for the map); every file is listed so the drift test can hold each
+// one to its own README row.
+export * from './localModelHeuristics.js';
+export * from './providerAssignments.js';
+export * from './providerContextWindows.js';
+export * from './providerEndpoints.js';
+export * from './providerGateways.js';
+export * from './providerModels.js';
+export * from './providerReadiness.js';
+export * from './providerSelection.js';
+export * from './providerTypes.js';
+export * from './providers.js';
+
// === Module loading / resilience ===
export { lazyWithReload } from './lazyWithReload.js';
export * from './staleChunkReload.js';
diff --git a/client/src/utils/localModelHeuristics.js b/client/src/utils/localModelHeuristics.js
new file mode 100644
index 0000000000..393c1de652
--- /dev/null
+++ b/client/src/utils/localModelHeuristics.js
@@ -0,0 +1,281 @@
+/**
+ * What an untyped LOCAL model can do, judged from its id: the embedding /
+ * vision / tool-use family regexes, the picker annotations built on them, and
+ * 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.
+ *
+ * Re-exported by `./providers.js` for existing `utils/providers` imports.
+ */
+
+import { isLocalInstanceProvider, localBackendForProvider } from './providerEndpoints.js';
+import { filterSelectableModels } from './providerModels.js';
+import { commandBasename, isOllamaBackedProvider } from './providerTypes.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);
+
+/**
+ * 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.
+ * @param {{type?:string, command?:string}|null|undefined} provider
+ * @returns {boolean}
+ */
+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
+ * native tool calls — a local model that can't (e.g. Gemma) narrates a
+ * done-message instead of acting, silently wedging the task. This decides the
+ * per-option marker + the "pick a tool-capable model" warning in agent pickers.
+ *
+ * Tool-use is surfaced as an ANNOTATION + warning, never as a filter: the
+ * heuristic is a positive allowlist, so a non-match is "not a recognized
+ * tool-caller", not a proven negative, and hiding those options would make a
+ * newer tool-capable family unselectable (see {@link withToolUseOptionLabel}).
+ *
+ * Returns `null` for cloud / API providers: their model ids don't encode their
+ * family, so the name heuristic would mislabel them. LOCAL backends return
+ * `{ toolCapable }` — where "local" is BOTH a direct Ollama / LM Studio backend
+ * ({@link localBackendForProvider}) AND an Ollama-BACKED CLI/TUI wrapper
+ * ({@link isOllamaBackedProvider}): a renamed `claude-ollama-tui` / OpenCode
+ * wrapper keeps `ollamaBacked: true` but may lose the "ollama"
+ * name/endpoint/id that `localBackendForProvider` matches on, and that wrapper
+ * is exactly the incident's provider class — so it must still be flagged, not
+ * silently skipped.
+ *
+ * `toolUseIdsByProvider` is the AUTHORITATIVE map the server reports from each
+ * backend's own capability metadata (Ollama `/api/show` `tools`) keyed by the
+ * PROVIDER ID the server says serves each model — see `useToolUseModelIds`. It
+ * is UNIONED with, never substituted for, {@link isToolUseModel}: the regex is a
+ * positive allowlist that goes stale every time a new function-calling family
+ * ships (`phi4-mini`, newer Gemma builds got "⚠ no known tool use" while the
+ * Local LLMs tab's "Agents" badge, reading these same capabilities, said
+ * otherwise), while the map can't speak for a provider the server never
+ * enumerated. Pass `null` (the default) when it hasn't loaded — that degrades to
+ * regex-only, the behavior this picker has always had.
+ *
+ * Keyed by the ENUMERATED PROVIDER, not flattened and not keyed by backend,
+ * because a bare id is not a capability: a CUSTOM provider (or an Ollama-backed
+ * CLI wrapper) pointed at a *different* Ollama/LM Studio host resolves to the
+ * same backend, but the server never enumerated that host — so a local model's
+ * id must not vouch for a remote model that merely shares its name. Such a
+ * provider stays regex-only, which is the conservative direction: a false
+ * "tool-capable" sends an agent to a model that narrates instead of acting.
+ * @param {string} id
+ * @param {object} [provider]
+ * @param {Record<string, Set<string>>|null} [toolUseIdsByProvider]
+ * @returns {{toolCapable:boolean}|null}
+ */
+export const localToolUseHint = (id, provider, toolUseIdsByProvider = null) =>
+ (localBackendForProvider(provider) || isOllamaBackedProvider(provider) || provider?.lmstudioBacked === true || provider?.mtplxBacked === true || provider?.llamaBacked === true || provider?.vllmBacked === true || provider?.sglangBacked === true)
+ && typeof id === 'string' && id.length > 0
+ ? { toolCapable: toolUseIdsByProvider?.[provider?.id]?.has(id) === true || isToolUseModel(id) }
+ : null;
+
+/**
+ * Suffix a native `<option>` label with a tool-use marker for an agent picker.
+ * No-op (returns `label` unchanged) for cloud providers or a blank id, so it's
+ * safe to wrap every option. Pairs with {@link localToolUseHint} for the
+ * below-the-select warning. Emoji (not lucide icons) because native `<option>`
+ * elements can't render markup.
+ *
+ * The signal is asymmetric because {@link isToolUseModel} is a *positive
+ * allowlist* of families with dependable function-calling: a match is a reliable
+ * "tool-capable", but a NON-match only means "not a recognized tool-caller" —
+ * NOT a proven negative (a newer tool-capable family whose id isn't in the regex
+ * yet would fall here). So the negative marker is worded as unverified, not a
+ * false-certain "no tool use". Passing `toolUseIdsByProvider` (from
+ * `useToolUseModelIds`) shrinks that unverified band to the models the server
+ * couldn't speak for; see {@link localToolUseHint} for the union rule.
+ * @param {string} id - model id (drives the heuristic)
+ * @param {string} label - display label to annotate (often === id)
+ * @param {object} [provider] - the selected provider object
+ * @param {Record<string, Set<string>>|null} [toolUseIdsByProvider] - authoritative
+ * server-reported tool-capable ids, keyed by provider id; `null` = regex-only
+ * @returns {string}
+ */
+export const withToolUseOptionLabel = (id, label, provider, toolUseIdsByProvider = null) => {
+ const hint = localToolUseHint(id, provider, toolUseIdsByProvider);
+ if (!hint) return label;
+ return `${label}${hint.toolCapable ? ' · 🔧 tool use' : ' · ⚠ no known tool use'}`;
+};
+
+/**
+ * Selectable models for a generation/chat picker: drops internal sentinels AND
+ * embedding-only models. Use anywhere the user picks a model that will run a
+ * prompt (provider editor model lists, fallback model, manuscript review).
+ * @param {string[]} models
+ * @returns {string[]}
+ */
+export const filterGenerationModels = (models) =>
+ filterSelectableModels(models).filter((m) => !isEmbeddingModel(m));
+
+/**
+ * Per-model filter for a VISION picker: restrict LOCAL backends (Ollama /
+ * LM Studio) to vision-capable models by id, but leave cloud/API providers'
+ * lists untouched — `isVisionModel` is a local-name heuristic and would wrongly
+ * hide multimodal cloud models whose ids don't encode vision (`gpt-4o`,
+ * `claude-*`). Pass as `useProviderModels({ modelFilter: visionLocalModelFilter })`.
+ *
+ * `visionIdsByProvider` is the AUTHORITATIVE map the server reports from each
+ * backend's own capability metadata (Ollama `/api/show`, LM Studio
+ * `type: 'vlm'`), keyed by the PROVIDER ID the server says serves each model —
+ * see `useVisionModelIds`. It is unioned with, not substituted for, the id
+ * regex: the regex alone goes stale every time a new multimodal family ships
+ * (it knew `gemma-3` but not `gemma4`, so a user with only `gemma4:e4b` +
+ * `qwen3.6:35b` installed saw an EMPTY vision picker), while the map alone
+ * can't speak for a provider the server never enumerated. Pass `null` (the
+ * default) when it hasn't loaded — that degrades to regex-only.
+ *
+ * Keyed by the ENUMERATED PROVIDER, not flattened and not keyed by backend,
+ * because a bare id is not a capability:
+ * - The same id can be a VLM on one backend and text-only on another, and the
+ * server also reports `backend: 'cli'` rows asserting vision for EVERY model
+ * of a claude/codex CLI (that CLI reads an image file whatever model it
+ * fronts). Flattening let an ollama-backed Claude CLI's text-only ids — which
+ * collide with the real `ollama` provider's list — pass this filter.
+ * - Keying by backend alone still over-shares: a CUSTOM provider pointed at a
+ * *different* Ollama/LM Studio host (endpoint `:11434` on another machine)
+ * resolves to the same backend, but the server never enumerated that host,
+ * so a local VLM's id would vouch for a remote model that merely shares it.
+ * An unenumerated local provider therefore stays on the regex-only path. This
+ * matters because sceneEvaluator honors a pin's model verbatim — a wrong yes
+ * here sends frames to a model that cannot see them.
+ *
+ * @param {string} id
+ * @param {{id?:string,endpoint?:string,name?:string}} [provider]
+ * @param {Record<string, Set<string>>|null} [visionIdsByProvider]
+ * @returns {boolean}
+ */
+export const visionLocalModelFilter = (id, provider, visionIdsByProvider = null) => {
+ // Cloud/API providers are left intact — the regex is a local-name heuristic
+ // and would wrongly hide multimodal cloud ids like `gpt-4o`.
+ if (!localBackendForProvider(provider)) return true;
+ return visionIdsByProvider?.[provider?.id]?.has(id) === true || isVisionModel(id);
+};
+
+/**
+ * Resolve the capability badges for a selected model without over-sharing a
+ * local runtime's answer with another provider. The status endpoint is keyed
+ * by backend, but only the canonical `ollama` / `lmstudio` provider records
+ * are known to point at this install's daemon; custom or remote providers stay
+ * on conservative inference. This mirrors the provider-scoped boundary used
+ * by `useToolUseModelIds` and `useVisionModelIds`.
+ *
+ * `[]` is a valid runtime answer meaning no optional capabilities were
+ * reported. `null` means the capability set is unknown, and `source` tells the
+ * UI whether that is because the runtime is still loading, the runtime probe
+ * failed, the provider gave a harness-level fact, or no authoritative metadata
+ * exists.
+ *
+ * @param {{id?:string,type?:string,command?:string,endpoint?:string,name?:string,ollamaBacked?:boolean}|null|undefined} provider
+ * @param {string|null|undefined} model
+ * @param {{capabilitiesByBackend?: {ollama?: Record<string, string[]|null>, lmstudio?: Record<string, string[]|null>}, recommendations?: {ollama?: object|null, lmstudio?: object|null}, loading?: boolean}} [options]
+ * @returns {{capabilities: string[]|null, source: 'unselected'|'runtime'|'runtime-unknown'|'provider'|'inferred'|'loading'|'unknown', recommendation: object|null}}
+ */
+export const modelCapabilityInfo = (provider, model, {
+ capabilitiesByBackend = {},
+ recommendations = {},
+ loading = false,
+} = {}) => {
+ const modelId = typeof model === 'string' ? model.trim() : '';
+ if (!provider || !modelId) {
+ return { capabilities: null, source: 'unselected', recommendation: null };
+ }
+
+ const backend = localBackendForProvider(provider);
+ const canonicalLocalProvider = backend
+ && provider.id === backend
+ && isLocalInstanceProvider(provider);
+ const recommendation = canonicalLocalProvider ? recommendations?.[backend] : null;
+ const selectedRecommendation = recommendation?.id === modelId ? recommendation : null;
+
+ if (canonicalLocalProvider) {
+ const modelCapabilities = capabilitiesByBackend?.[backend];
+ if (modelCapabilities && Object.hasOwn(modelCapabilities, modelId)) {
+ const capabilities = modelCapabilities[modelId];
+ return {
+ capabilities: Array.isArray(capabilities) ? [...new Set(capabilities)] : null,
+ source: Array.isArray(capabilities) ? 'runtime' : 'runtime-unknown',
+ recommendation: selectedRecommendation,
+ };
+ }
+ if (loading) {
+ return { capabilities: null, source: 'loading', recommendation: selectedRecommendation };
+ }
+ }
+
+ // A Codex or Claude CLI can attach/read an image and invoke tools through its
+ // harness. That is deliberately labelled as provider-level below; it is not
+ // pretending that the provider published per-model metadata.
+ if (isVisionCapableCliProvider(provider)) {
+ return { capabilities: ['tools', 'vision'], source: 'provider', recommendation: null };
+ }
+
+ const inferred = [];
+ if (backend && isToolUseModel(modelId)) inferred.push('tools');
+ if (backend && isVisionModel(modelId)) inferred.push('vision');
+ return {
+ capabilities: inferred.length ? inferred : null,
+ source: inferred.length ? 'inferred' : 'unknown',
+ recommendation: selectedRecommendation,
+ };
+};
diff --git a/client/src/utils/providerAssignments.js b/client/src/utils/providerAssignments.js
new file mode 100644
index 0000000000..2e4a35c8d0
--- /dev/null
+++ b/client/src/utils/providerAssignments.js
@@ -0,0 +1,195 @@
+/**
+ * Which provider/model a RECORD resolves to, and the option helpers the
+ * assignment editors share: a record's pin else the active provider
+ * (`resolveEffectiveProvider`), a Pipeline series run's provider/model
+ * (`resolveSeriesRunLlm`), the one "Provider / model" phrasing, and the
+ * provider / model / default / tool-use-warning options for an AI Assignments
+ * entry — consumed by the global AI Assignments table and every per-record
+ * override drawer, so they cannot derive the rule differently.
+ *
+ * `resolveSeriesRunLlm` is a browser MIRROR of `server/lib/seriesLlmOverride.js`
+ * (the precedence rationale lives there).
+ *
+ * Re-exported by `./providers.js` for existing `utils/providers` imports.
+ */
+
+import { localToolUseHint, visionLocalModelFilter } from './localModelHeuristics.js';
+import { effectiveModelFor, mergeModelLists } from './providerModels.js';
+
+/**
+ * Resolve the provider whose timeout is the "fallback" for a stage — the
+ * stage's pinned provider when set, otherwise the active provider. Used to
+ * power the placeholder + hint on stage-timeout UIs in PromptManager and
+ * the Writers Room. Returns the timeout in ms (or `undefined` if neither
+ * provider is present, or its timeout isn't set).
+ */
+export const getProviderTimeout = (providers, stagePinnedId, activeProviderId) => {
+ const id = stagePinnedId || activeProviderId;
+ if (!id) return undefined;
+ return providers.find((p) => p.id === id)?.timeout;
+};
+
+/**
+ * The provider a record will ACTUALLY run on: its own pin when set, else the
+ * install's active provider. Every picker that offers a "use the default"
+ * option needs this — the model list, effort ladder, and "Default (active: X)"
+ * label all have to resolve against the fallback, or leaving a record unpinned
+ * silently means "no model or effort can be picked either".
+ *
+ * `usingActive` distinguishes the two so a caller can say which provider the
+ * blank option currently means rather than just showing "Default".
+ *
+ * @param {Array} providers
+ * @param {string|null|undefined} pinnedId - The record's own provider pin.
+ * @param {string|null|undefined} activeProviderId - The install's active provider.
+ * @returns {{provider: object|undefined, usingActive: boolean}}
+ */
+export const resolveEffectiveProvider = (providers, pinnedId, activeProviderId) => {
+ const id = pinnedId || activeProviderId || '';
+ const provider = id ? (providers || []).find((p) => p.id === id) : undefined;
+ return { provider, usingActive: !pinnedId && !!provider };
+};
+
+/**
+ * Effective provider/model for a run against a Pipeline series — CLIENT MIRROR
+ * of `resolveSeriesLlmOverride` (server/lib/seriesLlmOverride.js; the precedence
+ * rationale lives there), extended with the install's active provider as the
+ * final fallback so the UI can NAME what a run will call instead of a blank.
+ *
+ * Used by the Autopilot Options picker and the scheduled-run consent card so
+ * both name the same thing the server's `resolveAutopilotLlm` will resolve.
+ *
+ * @returns {{provider: string, model: string}}
+ */
+export const resolveSeriesRunLlm = (series, { overrideProvider, overrideModel, activeProviderId } = {}) => {
+ const seriesProvider = series?.llm?.provider || '';
+ // The series model belongs to the series provider — an override naming a
+ // different provider must resolve THAT provider's default instead.
+ const inheritsSeriesModel = !overrideProvider || overrideProvider === seriesProvider;
+ return {
+ provider: overrideProvider || seriesProvider || activeProviderId || '',
+ model: overrideModel || (inheritsSeriesModel ? series?.llm?.model || '' : ''),
+ };
+};
+
+/**
+ * "Claude Code / claude-opus-5" — or "Claude Code (provider default model)"
+ * when no model is pinned. The one phrasing for "which AI will this run call",
+ * so the Autopilot Options copy, its live-progress line and the scheduled-run
+ * consent card can't word the same fact three different ways.
+ */
+export const providerModelLabel = (providers, id, model) =>
+ `${providerDisplayName(providers, id, '—')}${model ? ` / ${model}` : ' (provider default model)'}`;
+
+/** Display name for a provider id, falling back to the id then `fallback`. */
+export const providerDisplayName = (providers, id, fallback = '') =>
+ providers.find((p) => p.id === id)?.name || id || fallback;
+
+/**
+ * Provider `{ id, name }` options eligible for an assignment entry — the entry's
+ * pre-baked `providerOptions` when present, else every provider whose `type` is
+ * in the entry's `providerTypes` (all providers when unfiltered), tagged with a
+ * "(disabled)" suffix on disabled providers.
+ */
+export const assignmentProviderOptions = (entry, providers) => {
+ if (Array.isArray(entry?.providerOptions)) return entry.providerOptions;
+ const types = Array.isArray(entry?.providerTypes) && entry.providerTypes.length
+ ? new Set(entry.providerTypes)
+ : null;
+ return providers
+ .filter((p) => !types || types.has(p.type))
+ .map((p) => ({ id: p.id, name: `${p.name}${p.enabled ? '' : ' (disabled)'}` }));
+};
+
+/**
+ * Model-id options for an assignment entry given the selected provider — the
+ * entry's pre-baked `modelOptions` when present, else the provider's own model
+ * list (empty when the provider is unknown or has none).
+ *
+ * When `entry.modelFilter === 'vision'`, LOCAL backends (Ollama / LM Studio)
+ * are reduced to vision-capable models via `visionLocalModelFilter` so the
+ * Scene Evaluation (and other vision) pickers can't offer text-only ids.
+ * Cloud/API providers are left intact by that filter. Pass `visionIdsByProvider`
+ * (from `useVisionModelIds`) so that reduction uses the backend's own capability
+ * metadata instead of the id regex alone.
+ *
+ * For a vision entry on an ENUMERATED local provider, the server's installed-VLM
+ * list is also UNIONED INTO the candidates rather than only filtering them: a
+ * provider's stored `models` is a snapshot that goes stale the moment the user
+ * pulls a model (`/local-llm/install` doesn't refresh it, and the shipped
+ * `ollama` provider starts out empty), so filtering that list alone still hides
+ * a VLM that is installed right now — the same staleness `useLocalModels` +
+ * `mergeModelLists` exists to solve for non-vision pickers. Only the provider
+ * the server actually enumerated gets this: an unenumerated one would otherwise
+ * be offered models from a host it doesn't serve.
+ */
+export const assignmentModelOptions = (entry, providers, providerId, visionIdsByProvider = null) => {
+ const provider = providers.find((p) => p.id === providerId);
+ const baked = Array.isArray(entry?.modelOptions);
+ const raw = baked ? entry.modelOptions : (provider?.models || []);
+ // Normalize object-shaped entries (`{ id }`) so both baked and live lists
+ // yield plain string options for the <select>.
+ const models = raw
+ .map((m) => (typeof m === 'string' ? m : m?.id))
+ .filter(Boolean);
+ if (entry?.modelFilter !== 'vision') return models;
+ // Pre-baked `modelOptions` is an explicit caller-supplied list — honor it as
+ // the full candidate set rather than widening it from the backend.
+ const installed = baked ? null : visionIdsByProvider?.[providerId];
+ const candidates = installed ? mergeModelLists(models, [...installed]) : models;
+ return candidates.filter((id) => visionLocalModelFilter(id, provider, visionIdsByProvider));
+};
+
+/**
+ * Tool-use annotation state for one AI-assignment row/stage, so every editor of
+ * the same pin (the AI Assignments table, the Creative Director Models drawer,
+ * any future one) derives it identically instead of re-deriving the rule and
+ * drifting — the drawer used to be the only editor that warned at all, because
+ * its stage list hard-coded `needsTools` client-side.
+ *
+ * `entry.needsTools` is the SERVER's marker for an assignment whose provider runs
+ * an agent harness (see `agentEntry` in server/services/aiAssignments.js). It
+ * mirrors `modelFilter: 'vision'`: one server flag, read uniformly.
+ *
+ * Three rules are baked in here so a caller can't forget one:
+ * - The EFFECTIVE model is judged, not the pin. A blank model isn't a no-op —
+ * the agent resolver then runs the provider's own `defaultModel`, which for a
+ * local backend can be the non-tool model that wedges the run.
+ * - Nothing is asserted until the capability scan SETTLES (`toolUseLoaded`,
+ * success or failure). Annotating mid-scan shows the false "no known tool
+ * use" the authoritative union exists to remove, only to retract it a beat
+ * later.
+ * - `incapable` is a strict `=== false` on the hint, so a non-agent entry, a
+ * cloud provider (`localToolUseHint` returns null — ids don't encode family)
+ * or an unpinned row all read as "no warning", never as "incapable".
+ *
+ * @param {{needsTools?:boolean}|null|undefined} entry - the assignment entry
+ * @param {object|undefined} provider - the currently selected provider object
+ * @param {string} model - the row's model pin ('' = provider default)
+ * @param {Record<string, Set<string>>|null} [toolUseIdsByProvider] - from `useToolUseModelIds`
+ * @param {boolean} [toolUseLoaded] - whether that scan has settled
+ * @returns {{annotate: boolean, effectiveModel: string, incapable: boolean}}
+ */
+export const assignmentToolUseState = (entry, provider, model, toolUseIdsByProvider = null, toolUseLoaded = false) => {
+ const effectiveModel = effectiveModelFor(provider, model);
+ const annotate = entry?.needsTools === true && toolUseLoaded;
+ const hint = annotate ? localToolUseHint(effectiveModel, provider, toolUseIdsByProvider) : null;
+ return { annotate, effectiveModel, incapable: hint?.toolCapable === false };
+};
+
+/**
+ * Default model to seed when the user picks a provider for an assignment.
+ * For vision-filtered entries, only returns a model that still appears in the
+ * filtered options — a local backend's text-only `defaultModel` must not be
+ * seeded into the Scene Evaluation picker.
+ */
+export const assignmentDefaultModel = (entry, providers, providerId, visionIdsByProvider = null) => {
+ if (!providerId) return '';
+ const provider = providers.find((p) => p.id === providerId);
+ if (!provider) return '';
+ const def = provider.defaultModel || '';
+ if (entry?.modelFilter !== 'vision') return def;
+ const models = assignmentModelOptions(entry, providers, providerId, visionIdsByProvider);
+ if (def && models.includes(def)) return def;
+ return models[0] || '';
+};
diff --git a/client/src/utils/providerContextWindows.js b/client/src/utils/providerContextWindows.js
new file mode 100644
index 0000000000..252b0949da
--- /dev/null
+++ b/client/src/utils/providerContextWindows.js
@@ -0,0 +1,160 @@
+/**
+ * How large a context window a provider/model gets for planning, and where that
+ * 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.
+ *
+ * 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';
+
+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 const isLikelyLargeContextProvider = (provider) => {
+ if (isProcessProvider(provider)) return true;
+ return isApiProvider(provider) && !isLocalEndpoint(provider.endpoint);
+};
+
+/**
+ * Where a resolved context window came from — three states, because that is
+ * what the UI actually distinguishes:
+ *
+ * - `REPORTED` — a real window for this model/provider (catalog, known-model
+ * table, vendor default, or Ollama's num_ctx). Which of those it was does not
+ * change what the card says, so they collapse into one state rather than
+ * growing an enum member per rung.
+ * - `OVERRIDE` — a number the user typed; worth labelling as theirs.
+ * - `ASSUMED` — nobody reported one, so the ladder GUESSED. This is the state
+ * that has to be visible: a card printing "128K ctx" for a model whose real
+ * window is 1M reads as a measured fact with nothing to say otherwise.
+ */
+export const CONTEXT_WINDOW_SOURCE = Object.freeze({
+ OVERRIDE: 'override',
+ REPORTED: 'reported',
+ 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.
+ *
+ * `{ tokens: null, source: null }` means nothing is known (an unrecognized model
+ * on a local backend); the budgeter applies its own conservative floor there.
+ *
+ * @param {object|null|undefined} provider
+ * @param {string|null|undefined} model
+ * @returns {{tokens: number|null, source: string|null}}
+ */
+export const resolveModelContextWindow = (provider, model) => {
+ const explicit = Number(provider?.contextWindow);
+ if (Number.isFinite(explicit) && explicit > 0) {
+ return { tokens: explicit, source: CONTEXT_WINDOW_SOURCE.OVERRIDE };
+ }
+ const catalog = catalogModelContextWindow(provider, model);
+ if (catalog) return { tokens: catalog, source: CONTEXT_WINDOW_SOURCE.REPORTED };
+ const known = knownModelContextWindow(model);
+ if (known) return { tokens: known, source: CONTEXT_WINDOW_SOURCE.REPORTED };
+ const providerKnown = knownProviderContextWindow(provider);
+ if (providerKnown) return { tokens: providerKnown, source: CONTEXT_WINDOW_SOURCE.REPORTED };
+ const numCtx = Number(provider?.numCtx);
+ if (Number.isFinite(numCtx) && numCtx > 0) {
+ return { tokens: numCtx, source: CONTEXT_WINDOW_SOURCE.REPORTED };
+ }
+ return isLikelyLargeContextProvider(provider)
+ ? { tokens: DEFAULT_LARGE_CONTEXT_WINDOW, source: CONTEXT_WINDOW_SOURCE.ASSUMED }
+ : { tokens: null, source: null };
+};
+
+export const effectiveModelContextWindow = (provider, model) =>
+ resolveModelContextWindow(provider, model).tokens;
+
+/**
+ * Display label for a model `<option>`: the id plus a "(32K ctx)" parenthetical
+ * when the model's context window is known. The option's `value` stays the raw
+ * id — only the label carries the annotation.
+ *
+ * Resolution is deliberately narrower than {@link resolveModelContextWindow}:
+ * only rungs that describe THIS model — the live local probe (`ctxById` from
+ * `useLocalModels`), the window `provider`'s catalog reported for it, then the
+ * known-model table. The provider-level and assumed rungs are excluded on
+ * purpose: they would stamp the same guessed number onto every option in the
+ * list, which says nothing and reads as fact.
+ *
+ * Take `provider` rather than a pre-merged map so every picker gets catalog
+ * windows for free — merging at the call site is what left the fallback-model
+ * and manuscript-override selects labelling a 1M model as if it were unknown.
+ *
+ * @param {string} id
+ * @param {Record<string, number>} [ctxById] — live windows for local models
+ * @param {object} [provider] — the provider whose catalog lists this model
+ * @returns {string}
+ */
+export const modelOptionLabel = (id, ctxById, provider) => {
+ const ctx = ctxById?.[id] || catalogModelContextWindow(provider, id) || knownModelContextWindow(id);
+ const label = formatContextLength(ctx);
+ return label ? `${id} (${label})` : id;
+};
diff --git a/client/src/utils/providerEndpoints.js b/client/src/utils/providerEndpoints.js
new file mode 100644
index 0000000000..75169f6d5b
--- /dev/null
+++ b/client/src/utils/providerEndpoints.js
@@ -0,0 +1,218 @@
+/**
+ * WHERE a provider's endpoint points: this machine (loopback), another host
+ * inside the private network (LAN / tailnet / `.local` — a "fleet" provider), or
+ * the public internet — and which local daemon (Ollama / LM Studio) a record
+ * names, so callers can fold in live-installed models or decide whether a
+ * missing API key is a real gap.
+ *
+ * Browser MIRROR of `localBackendForProvider` / `isLocalInstanceEndpoint` in
+ * `server/lib/localProviderRuntime.js` and `isPrivateNetworkEndpoint` in
+ * `server/lib/providerPrerequisites.js` — keep in lockstep. The server copies
+ * are authoritative and stricter (they gate actions); these only label UI.
+ *
+ * Re-exported by `./providers.js` for existing `utils/providers` imports.
+ */
+
+/**
+ * Classify a provider as a local-LLM backend by its id/endpoint/name, so callers
+ * can fold in live-installed models (Ollama/LM Studio) that aren't in the
+ * provider's stored `models` list. Ollama's native + OpenAI-compat ports are
+ * 11434; LM Studio defaults to 1234. The stable provider ids (`ollama` /
+ * `lmstudio`) are checked too — AI Assignments' curated provider payload
+ * omits `endpoint`, and a renamed display name would otherwise miss detection.
+ *
+ * Client mirror of `localBackendForProvider` in
+ * server/lib/localProviderRuntime.js — keep in lockstep. The SERVER copy is
+ * authoritative and stricter: it parses the endpoint as a URL and requires a
+ * loopback/bind-all host, so a peer machine's daemon on the same port is not
+ * claimed as local. This one only labels UI, so it stays a cheap regex; if it
+ * ever gates an action, take the server's rules with it.
+ *
+ * The pr-reviewer stage pickers (`PipelineStageConfig.jsx`) are downstream of
+ * this, the sandboxed actions stage included — but they only choose which model
+ * list to SHOW. The pin a stage saves is re-validated at spawn time by
+ * `modelPinIsOffered` (server/lib/localProviderRuntime.js), so a
+ * misclassification here degrades to a confusing dropdown, never to a model the
+ * provider was not allowed to run.
+ *
+ * @param {{id?:string,endpoint?:string,name?:string}} provider
+ * @returns {'ollama'|'lmstudio'|null}
+ */
+export const localBackendForProvider = (provider) => {
+ if (!provider) return null;
+ const id = String(provider.id || '').toLowerCase();
+ const endpoint = String(provider.endpoint || '');
+ const name = String(provider.name || '').toLowerCase();
+ if (id === 'ollama' || /:11434\b/.test(endpoint) || name.includes('ollama')) return 'ollama';
+ if (
+ id === 'lmstudio' ||
+ /:1234\b/.test(endpoint) ||
+ name.includes('lm studio') ||
+ name.includes('lmstudio') ||
+ /lm[\s-]?studio/i.test(name)
+ ) return 'lmstudio';
+ return null;
+};
+
+// The whole loopback block (`127.0.0.0/8`), not just `127.0.0.1` — a daemon on a
+// loopback alias (`127.0.0.2`) is as local as one on `.1`, and the server's
+// `isLocalInstanceHost` already accepts the full block. While they disagreed, a
+// provider on `http://127.0.0.2:11434` was badged NEEDS SETUP for an API key a
+// loopback endpoint never needs.
+const LOCAL_ENDPOINT_RE = /^(https?:\/\/)?(localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|0\.0\.0\.0|\[?::1\]?|\[?::\]?)(:|\/|$)/i;
+
+export const isLocalEndpoint = (endpoint) =>
+ typeof endpoint === 'string' && LOCAL_ENDPOINT_RE.test(endpoint.trim());
+
+// Hosts inside the trust boundary, where an unauthenticated OpenAI-compatible
+// server is a normal setup rather than a misconfiguration: RFC1918 LAN ranges,
+// link-local, and the Tailscale CGNAT range 100.64.0.0/10 (PortOS is a
+// tailnet-first product — an API provider pointed at another machine's Ollama
+// is a first-class configuration, not an edge case).
+const PRIVATE_IP_RE = /^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/;
+
+/**
+ * IPv6 counterpart to {@link PRIVATE_IP_RE}: unique-local (`fc00::/7`) and
+ * link-local (`fe80::/10`). Tailscale hands out a ULA address alongside the
+ * CGNAT v4 one, so without this a tailnet peer reached over IPv6 read as a
+ * public host and its keyless provider was blocked on a missing API key.
+ *
+ * Gated on the host being an IPv6 literal (it contains a `:`) and compared
+ * NUMERICALLY on the leading hextet — a bare `/^f[cd]/` prefix test would also
+ * claim hostnames like `fdrive.example.com`, and `fd::1` expands to a leading
+ * hextet of `0x00fd`, which is not in `fc00::/7` at all.
+ */
+/**
+ * Gate for {@link PRIVATE_IP_RE}: is this host an IPv4 literal at all?
+ *
+ * The range test above matches a PREFIX, which on its own also claims DNS names
+ * that merely start like one — `10.evil.example` — and would report a keyless
+ * PUBLIC endpoint as needing no key. Hosts arriving there have already been
+ * through `URL`, which canonicalizes any IPv4 spelling to a dotted quad.
+ * Mirror of the server helper in server/lib/providerPrerequisites.js.
+ */
+const isIpv4Literal = (host) => /^\d{1,3}(?:\.\d{1,3}){3}$/.test(host);
+
+const isPrivateIpv6 = (host) => {
+ if (!host.includes(':')) return false;
+ const first = host.split(':')[0];
+ if (!/^[0-9a-f]{1,4}$/.test(first)) return false; // '' for `::1` — loopback, already matched above
+ const n = parseInt(first, 16);
+ return (n >= 0xfc00 && n <= 0xfdff) || (n >= 0xfe80 && n <= 0xfebf);
+};
+
+/**
+ * Is this endpoint inside the private network — loopback, a LAN/tailnet address,
+ * a `.local`/`.ts.net`/`.internal` name, or a bare single-label host?
+ *
+ * Used to decide whether a missing API key is actually a missing prerequisite.
+ * The server only attaches an `Authorization` header when a key is stored, so a
+ * keyless call to a private OpenAI-compatible server (LM Studio on the desk
+ * machine, Ollama on a tailnet peer) works exactly as configured — reporting it
+ * as "needs setup" would be a false alarm on a supported deployment. A public
+ * endpoint with no key stays flagged: that one really is misconfigured.
+ *
+ * A host that cannot be parsed reads as NOT private, keeping the stricter of
+ * the two answers for input we don't understand.
+ */
+export const isPrivateNetworkEndpoint = (endpoint) => {
+ if (isLocalEndpoint(endpoint)) return true;
+ if (typeof endpoint !== 'string' || !endpoint.trim()) return false;
+ const trimmed = endpoint.trim();
+ // A scheme-less endpoint ("192.168.1.5:1234/v1") is still a host — give the
+ // parser one so it doesn't read the leading segment as a scheme.
+ const candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
+ if (!URL.canParse(candidate)) return false;
+ const host = new URL(candidate).hostname.toLowerCase().replace(/^\[|\]$/g, '');
+ if (isIpv4Literal(host) && PRIVATE_IP_RE.test(host)) return true;
+ if (isPrivateIpv6(host)) return true;
+ if (/\.(local|internal|lan|home\.arpa|ts\.net)$/.test(host)) return true;
+ // A single-label host resolves only inside the local network (`http://nas:11434`).
+ return !host.includes('.') && !host.includes(':');
+};
+
+/**
+ * Does this provider talk to a daemon on THIS machine?
+ *
+ * Client mirror of `isLocalInstanceEndpoint` in
+ * server/lib/localProviderRuntime.js, and the guard for anything that explains
+ * a provider by inspecting the machine PortOS runs on — "is `lms` installed
+ * here?", "start it from Models → LLMs". A provider named for LM Studio
+ * but pointed at another box on the tailnet matches
+ * {@link localBackendForProvider} by NAME, so without this it collected this
+ * machine's install state and offered to start a server it does not own.
+ *
+ * A blank endpoint reads as local, unlike the server's copy: the record simply
+ * hasn't named one, and every default it can fall back to is a loopback URL.
+ *
+ * @param {{endpoint?:string}} provider
+ * @returns {boolean}
+ */
+export const isLocalInstanceProvider = (provider) => {
+ const endpoint = provider?.endpoint;
+ if (typeof endpoint !== 'string' || endpoint.trim() === '') return true;
+ return isLocalEndpoint(endpoint);
+};
+
+/**
+ * Does this provider run on another machine inside the private network?
+ *
+ * This is presentation identity, not a trust escalation: prerequisite and key
+ * rules still come from {@link isPrivateNetworkEndpoint}. Public hosted APIs
+ * stay ordinary remote providers; loopback daemons stay local.
+ */
+export const isFleetProvider = (provider) =>
+ !isLocalInstanceProvider(provider) && isPrivateNetworkEndpoint(provider?.endpoint);
+
+/**
+ * Has this fleet host already been configured as a provider on this instance?
+ *
+ * @param {{endpoint?: string, peerHost?: string, peerAddress?: string}|null|undefined} host
+ * @param {Array<object>} providers
+ * @returns {boolean}
+ */
+export const isFleetHostConfigured = (host, providers = []) => {
+ if (!host || !Array.isArray(providers)) return false;
+ const hostEndpoint = typeof host.endpoint === 'string' ? host.endpoint.toLowerCase().replace(/\/+$/, '') : '';
+ const hostHostname = (host.peerHost || (host.endpoint && URL.canParse(host.endpoint) ? new URL(host.endpoint).hostname : ''))?.toLowerCase();
+ const hostAddress = (host.peerAddress || '')?.toLowerCase();
+
+ return providers.some((p) => {
+ // 1. Direct endpoint string equality
+ const pEndpoint = typeof p?.endpoint === 'string' ? p.endpoint.toLowerCase().replace(/\/+$/, '') : '';
+ if (hostEndpoint && pEndpoint === hostEndpoint) return true;
+
+ // 2. Parsed hostname/IP match
+ if (pEndpoint && URL.canParse(pEndpoint)) {
+ const pUrl = new URL(pEndpoint);
+ const pHost = pUrl.hostname.toLowerCase();
+ if ((hostHostname && pHost === hostHostname) || (hostAddress && pHost === hostAddress)) {
+ return true;
+ }
+ }
+
+ // 3. OpenCode TUI provider configuration check
+ if (p?.envVars?.OPENCODE_CONFIG_CONTENT) {
+ try {
+ const config = typeof p.envVars.OPENCODE_CONFIG_CONTENT === 'string'
+ ? JSON.parse(p.envVars.OPENCODE_CONFIG_CONTENT)
+ : p.envVars.OPENCODE_CONFIG_CONTENT;
+ const vllmBaseUrl = config?.provider?.vllm?.options?.baseURL;
+ if (typeof vllmBaseUrl === 'string') {
+ const normBase = vllmBaseUrl.toLowerCase().replace(/\/+$/, '');
+ if (hostEndpoint && normBase === hostEndpoint) return true;
+ if (URL.canParse(normBase)) {
+ const bHost = new URL(normBase).hostname.toLowerCase();
+ if ((hostHostname && bHost === hostHostname) || (hostAddress && bHost === hostAddress)) {
+ return true;
+ }
+ }
+ }
+ } catch {
+ // ignore parse error
+ }
+ }
+
+ return false;
+ });
+};
diff --git a/client/src/utils/providerGateways.js b/client/src/utils/providerGateways.js
new file mode 100644
index 0000000000..8ed005ff60
--- /dev/null
+++ b/client/src/utils/providerGateways.js
@@ -0,0 +1,50 @@
+/**
+ * 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.
+ *
+ * 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;
diff --git a/client/src/utils/providerModels.js b/client/src/utils/providerModels.js
new file mode 100644
index 0000000000..8caf73bb50
--- /dev/null
+++ b/client/src/utils/providerModels.js
@@ -0,0 +1,556 @@
+/**
+ * Which MODEL and EFFORT a provider actually runs, and what a picker may offer:
+ * the "use the CLI's own default" sentinels, the per-CLI reasoning-effort
+ * ladders and the clamp a stored effort resolves through, the Antigravity
+ * base-model ↔ effort-suffix split, the account-aware option list for a
+ * Codex-subscription provider, the model-list merge used when a refresh lands,
+ * 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.
+ *
+ * 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([
+ 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);
+
+/**
+ * The configured-default sentinel carried in a provider's model list, or null.
+ *
+ * `filterSelectableModels` strips sentinels from every picker, which is right
+ * for a *task's* model choice ("no override" is the empty option there). But a
+ * provider whose `defaultModel`/`lightModel`/… IS the sentinel while its
+ * `models` also holds real ids (Antigravity: `agy` has a real catalog AND its
+ * own configured default) would otherwise drive a `<select>` whose value
+ * matches no `<option>` — the field renders blank and reads as "unset" when the
+ * CLI's own default is in fact what's configured. The provider-edit form uses
+ * this to render an explicit option for it.
+ * @param {string[]|null|undefined} models
+ * @returns {string|null}
+ */
+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']);
+
+const codexEffortLevelsForModel = (model) => CODEX_ULTRA_MODELS.has(String(model || '').trim().toLowerCase())
+ ? 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
+ * only rewrites Antigravity (base models instead of one row per effort tier);
+ * every other provider's list passes through untouched. The single place the
+ * normalization lives, so `useProviderModels` and any caller that reads
+ * `provider.models` directly agree.
+ * @param {{id?:string, command?:string}|null|undefined} provider
+ * @param {unknown[]} models
+ * @returns {unknown[]}
+ */
+export const selectableModelsForProvider = (provider, models) =>
+ isAntigravityProvider(provider) ? antigravityBaseModels(models) : (models || []);
+
+/**
+ * Keeps a stored-but-no-longer-listed Antigravity id visible as its own option.
+ *
+ * A record saved before Antigravity split model from effort still holds
+ * `gemini-3.6-flash-high`, which matches no base-model option and would render
+ * the select BLANK (reading as "no model"). The server splits such an id back
+ * into base + `--effort`, so the pin still runs — it just has to stay selectable.
+ * Same posture as `EffortSelect`'s out-of-ladder option.
+ *
+ * Deliberately narrow: only an Antigravity id carrying an effort SUFFIX
+ * qualifies. A bare "not in the list" test would also re-surface the
+ * configured-default sentinel (the shipped agy `defaultModel`, which
+ * `filterSelectableModels` exists to hide) and any typo'd/stale pin.
+ *
+ * CLIENT-ONLY (no server mirror) — this is a rendering concern.
+ * @param {{id?:string, command?:string}|null|undefined} provider
+ * @param {unknown[]} models - the already-filtered option list
+ * @param {string|null|undefined} selectedModel
+ * @returns {unknown[]}
+ */
+export const withStaleAntigravityPin = (provider, models, selectedModel) => {
+ const list = models || [];
+ const stale = isAntigravityProvider(provider)
+ && !!splitAntigravityModel(selectedModel).effort
+ && !list.includes(selectedModel);
+ return stale ? [...list, selectedModel] : list;
+};
+
+/**
+ * The model ids in a signed-in ChatGPT account's catalog, or `null` when the
+ * catalog is not a SUCCESSFUL read.
+ *
+ * The server ships `{ models, fetchedAt, error }` on a Codex-subscription
+ * provider (`codexModelCatalog`), and all three states are distinct:
+ * `models: null` = never fetched, a set `error` = the last read failed (the
+ * list, if any, is only last-known-good), and `[]` = this account genuinely
+ * exposes no models. Only the last two of those are answers about the account,
+ * so a never-fetched or failed read collapses to `null` here and the caller
+ * keeps its shipped list — an offline or signed-out user must never be handed
+ * an empty dropdown.
+ *
+ * CLIENT-ONLY (no server mirror).
+ * @param {{codexModelCatalog?:{models?:unknown, error?:unknown}}|null|undefined} provider
+ * @returns {string[]|null}
+ */
+export const codexCatalogModelIds = (provider) => {
+ if (!isCodexSubscriptionProvider(provider)) return null;
+ const catalog = provider?.codexModelCatalog;
+ if (!catalog || catalog.error || !Array.isArray(catalog.models)) return null;
+ return catalog.models
+ .map((entry) => (typeof entry === 'string' ? entry : entry?.id))
+ .filter((id) => typeof id === 'string' && id !== '');
+};
+
+/**
+ * The RAW model list a picker should read for a provider, before any
+ * sentinel/effort/hardware filtering: the signed-in ChatGPT account's own
+ * catalog when one has been fetched, otherwise the provider's configured
+ * `models` — falling back to its `defaultModel` when that list is empty (a
+ * cloud/manual provider configured with only a default; `[]` is truthy, so a
+ * bare `||` would leave such a picker empty).
+ *
+ * This is the single place the account catalog enters a picker, so a caller
+ * that reads `provider.models` directly is the one bug this exists to prevent
+ * (#6306). A successfully-read EMPTY catalog is returned as `[]` and must not
+ * fall through to `defaultModel`: the account really has no models, and
+ * offering its default would put back the un-runnable option.
+ *
+ * CLIENT-ONLY (no server mirror).
+ * @param {{models?:unknown[], defaultModel?:string}|null|undefined} provider
+ * @returns {unknown[]}
+ */
+export const providerModelList = (provider) => {
+ const catalog = codexCatalogModelIds(provider);
+ if (catalog) return catalog;
+ return provider?.models?.length ? provider.models : [provider?.defaultModel];
+};
+
+/** Where a picker's option list came from. */
+export const MODEL_SOURCE = Object.freeze({
+ /** The provider's shipped/configured `models` array. */
+ shipped: 'shipped',
+ /** The signed-in ChatGPT account's own catalog. */
+ account: 'account',
+ /** The account was read successfully and exposes no models. */
+ accountEmpty: 'account-empty',
+});
+
+/**
+ * The option list for a picker, plus WHERE it came from.
+ *
+ * For a Codex-subscription provider whose account catalog has been fetched, the
+ * options are that account's real models — so a tier the plan cannot run is not
+ * selectable and cannot be queued against a worktree that would only fail later.
+ * Every other state (never fetched, failed read, non-Codex provider) falls back
+ * to the shipped list unchanged.
+ *
+ * ADDITIVE: a stored `selectedModel` the catalog no longer lists is retained as
+ * its own option and reported via `unlistedSelection`, so an existing task
+ * template renders what it actually holds instead of silently changing model.
+ *
+ * CLIENT-ONLY (no server mirror).
+ * @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider
+ * @param {string|null|undefined} selectedModel
+ * @returns {{models: unknown[], source: string, unlistedSelection: boolean}}
+ */
+export const resolveProviderModelOptions = (provider, selectedModel) => {
+ const shipped = withStaleAntigravityPin(
+ provider,
+ filterSelectableModels(selectableModelsForProvider(provider, provider?.models)),
+ selectedModel,
+ );
+ const catalog = codexCatalogModelIds(provider);
+ if (!catalog) return { models: shipped, source: MODEL_SOURCE.shipped, unlistedSelection: false };
+ const models = filterSelectableModels(catalog);
+ const unlistedSelection = !!selectedModel
+ && !isConfiguredDefaultModel(selectedModel)
+ && !models.includes(selectedModel);
+ return {
+ models: unlistedSelection ? [...models, selectedModel] : models,
+ source: models.length > 0 ? MODEL_SOURCE.account : MODEL_SOURCE.accountEmpty,
+ unlistedSelection,
+ };
+};
+
+/**
+ * The option list for a picker that renders an effort control but reads
+ * `provider.models` directly (no `useProviderModels`): base models, sentinels
+ * stripped, plus any legacy suffixed pin so the stored value stays visible.
+ * The hook's own list is assembled from the same two primitives, so the two
+ * paths can't drift. Codex-subscription providers resolve through
+ * `resolveProviderModelOptions`, so every picker offers the same account-aware
+ * answer without each one reimplementing the fallback.
+ *
+ * CLIENT-ONLY (no server mirror).
+ * @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider
+ * @param {string|null|undefined} selectedModel
+ * @returns {unknown[]}
+ */
+export const effortAwareModelOptions = (provider, selectedModel) =>
+ resolveProviderModelOptions(provider, selectedModel).models;
+
+/**
+ * The model a run will ACTUALLY use: the explicit pin, else the provider's own
+ * default. A blank model isn't a no-op — the resolver falls through to
+ * `defaultModel` — so anything keyed on the model (Antigravity's effort tiers,
+ * the local tool-use warning) has to evaluate this, not the raw selection.
+ *
+ * CLIENT-ONLY (no server mirror).
+ * @param {{defaultModel?:string}|null|undefined} provider
+ * @param {string|null|undefined} model
+ * @returns {string}
+ */
+export const effectiveModelFor = (provider, model) => model || provider?.defaultModel || '';
+
+/**
+ * Seeds a picker's two controls from a record that may predate the split.
+ * `{ model: 'gemini-3.6-flash-high', effort: '' }` reads back as
+ * `{ model: 'gemini-3.6-flash', effort: 'high' }`; a stored `effort` always
+ * wins over the suffix, and a non-Antigravity provider is left alone so a model
+ * that merely ends in `-high` isn't truncated.
+ *
+ * CLIENT-ONLY (no server mirror) — the server reads the suffixed id directly.
+ * @param {{id?:string, command?:string}|null|undefined} provider
+ * @param {string|null|undefined} model
+ * @param {string|null|undefined} effort
+ * @returns {{model: string, effort: string}}
+ */
+export const seedModelEffort = (provider, model, effort) => {
+ if (!isAntigravityProvider(provider)) return { model: model || '', effort: effort || '' };
+ const { base, effort: bakedEffort } = splitAntigravityModel(model || '');
+ return { model: base || '', effort: effort || bakedEffort || '' };
+};
+
+/**
+ * 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.
+ *
+ * `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.
+ * @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 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;
+ return null;
+};
+
+/**
+ * The effort a picker should keep after its MODEL changed under a fixed provider:
+ * the current one, or `''` when the new model has no effort control at all.
+ *
+ * Antigravity's tiers are per-model, and a model with NO tiers hides the select
+ * entirely (`effortLevelsForProvider` → null — `claude-sonnet-4-6` in the shipped
+ * agy catalog has no `-low|-medium|-high` siblings). Without this the previous
+ * effort stays in state with no UI left to clear it, and every submit path still
+ * sends it: an invocation agy rejects (`--model claude-sonnet-4-6 --effort high`)
+ * and, on the records that persist it, a stored level the run never used.
+ *
+ * A merely NARROWED ladder is deliberately left alone — `EffortSelect` renders an
+ * explicit `medium (runs as low)` option there, so the clamp stays visible rather
+ * than silently discarding the user's choice.
+ *
+ * CLIENT-ONLY (no server mirror) — the server clamps what it is sent; this keeps
+ * the UI from sending something it stopped showing.
+ * @param {{id?:string, command?:string, models?:unknown[], defaultModel?:string}|null|undefined} provider
+ * @param {string|null|undefined} model - the NEWLY selected model
+ * @param {string|null|undefined} effort - the currently selected effort
+ * @returns {string}
+ */
+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.
+ *
+ * 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
+ * (whose ladder stops at `high`) still runs, at `high`. Without this the select
+ * holds a value matching no option, renders blank — reading as "Default effort"
+ * — while the run silently uses the clamped level.
+ * @param {string|null|undefined} effort
+ * @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider
+ * @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]];
+};
+
+/**
+ * Union of one or more model-id lists, de-duplicated, order-preserving, falsy
+ * values dropped. Used to merge a provider's stored `models` with the live
+ * installed list for local backends.
+ * @param {...(string[]|undefined)} lists
+ * @returns {string[]}
+ */
+export const mergeModelLists = (...lists) => {
+ const seen = new Set();
+ const out = [];
+ for (const list of lists) {
+ for (const m of list || []) {
+ if (m && !seen.has(m)) { seen.add(m); out.push(m); }
+ }
+ }
+ return out;
+};
+
+/**
+ * Merge a partial-update payload onto an existing provider record in place, so
+ * repointing a provider at a new backend (e.g. a fleet host) doesn't clobber
+ * fields the payload didn't set out to change. A raw PATCH replaces whichever
+ * top-level keys it names wholesale — without this, pointing an OpenCode TUI
+ * provider at a new endpoint would silently drop its other env vars and reset
+ * its served-model history to just the one new model id.
+ *
+ * @param {object|null|undefined} target - the existing provider being updated
+ * @param {object} payload - field values about to be written; mutated in place
+ * @returns {object} payload
+ */
+export const mergeProviderUpdate = (target, payload) => {
+ if (!target) return payload;
+ if (payload.envVars) payload.envVars = { ...target.envVars, ...payload.envVars };
+ if (payload.secretEnvVars) {
+ payload.secretEnvVars = Array.from(new Set([...(target.secretEnvVars || []), ...payload.secretEnvVars]));
+ }
+ if (payload.models) payload.models = mergeModelLists(target.models, payload.models);
+ return payload;
+};
+
+/**
+ * Which default generation controls the provider editor should offer, or null
+ * when the provider has none.
+ *
+ * Only the local OpenAI-compatible backends qualify — Ollama, llama.cpp, MTPLX
+ * and vLLM (the first three reached directly as an `api` provider or through an
+ * OpenCode CLI/TUI wrapper; vLLM ships only the wrappers), plus the hosted
+ * gateways (OrcaRouter, OpenRouter). A hosted cloud provider is deliberately excluded: PortOS sends it no
+ * sampling fields at all, so offering a stored temperature there would be a
+ * control that silently does nothing.
+ *
+ * Each control is reported separately because the forwarding is uneven:
+ * A gateway's upstream models own their own reasoning switch, so it has no
+ * thinking toggle; and the Claude Code harness pointed at Ollama takes ONLY a
+ * thinking signal (`MAX_THINKING_TOKENS=0` in server/lib/cliChildEnv.js) — it
+ * owns its own sampling, so a temperature or top-p stored on one of those
+ * records would never reach the daemon. MIRROR of `THINKING_STYLE` /
+ * `buildAgentGeneration` in server/lib/opencodeConfig.js and
+ * `apiGenerationOptions` in server/lib/aiToolkit/internal/generationOptions.js;
+ * keep in lockstep.
+ * @param {object|null|undefined} provider
+ * @returns {{temperature:boolean, topP:boolean, thinking:boolean}|null}
+ */
+export const generationControlsFor = (provider) => {
+ const gateway = isGatewayBackedProvider(provider);
+ // LM Studio forwards temperature/top_p like any OpenAI-compatible endpoint,
+ // but reasoning there belongs to the LOADED model instance — see
+ // THINKING_STYLE.lmstudio on the server, which resolves to no toggle.
+ const lmstudio = provider?.lmstudioBacked === true;
+ const local = isOllamaBackedProvider(provider)
+ || lmstudio
+ || provider?.llamaBacked === true
+ || provider?.mtplxBacked === true
+ || provider?.vllmBacked === true
+ // SGLang takes the same `chat_template_kwargs.enable_thinking` as the other
+ // local OpenAI endpoints — see THINKING_STYLE.sglang on the server.
+ || provider?.sglangBacked === true;
+ if (!local && !gateway) return null;
+ if (isClaudeCommandProvider(provider)) {
+ // A Claude harness owns its own sampling, so only the thinking signal is
+ // ever forwardable — and only on Ollama, whose Anthropic endpoint maps an
+ // omitted `thinking` field to non-thinking mode (`MAX_THINKING_TOKENS=0`
+ // in server/lib/cliChildEnv.js). Every other local backend takes
+ // `chat_template_kwargs.enable_thinking`, which the Anthropic wire cannot
+ // carry — on SGLang the omitted field falls through to Qwen3.8's
+ // chat-template default (thinking ON), so offering the toggle there would
+ // pin a value nothing reads. No control at all is the honest answer.
+ return isOllamaBackedProvider(provider)
+ ? { temperature: false, topP: false, thinking: true }
+ : null;
+ }
+ // LM Studio joins the gateways in having no forwardable thinking signal.
+ return { temperature: true, topP: true, thinking: !gateway && !lmstudio };
+};
diff --git a/client/src/utils/providerReadiness.js b/client/src/utils/providerReadiness.js
new file mode 100644
index 0000000000..3e03d815be
--- /dev/null
+++ b/client/src/utils/providerReadiness.js
@@ -0,0 +1,443 @@
+/**
+ * Is a provider READY to run on this install, and if not, why: how it
+ * authenticates (`credentialSource`), which prerequisite it is missing, the
+ * CoS Agent Runner allowlist check for its command, the key its CLI runtime is
+ * published under, and the card state the AI Providers page groups by
+ * (`providerCardState`).
+ *
+ * Browser MIRROR of `server/lib/providerPrerequisites.js` (the same
+ * computation `getFallbackProvider` routes on — where the server has published
+ * `missingPrerequisites` it WINS) and of the normalization in
+ * `server/cos-runner/allowedCommands.js` (pinned by
+ * `server/cos-runner/allowedCommands.parity.test.js`). Unknown lookup values
+ * mean "not probed", never "missing".
+ *
+ * Re-exported by `./providers.js` for existing `utils/providers` imports.
+ */
+
+import { isPrivateNetworkEndpoint } from './providerEndpoints.js';
+import { gatewayForProvider, isGatewayBackedProvider } from './providerGateways.js';
+import { isApiProvider, isCodexSubscriptionProvider, isProcessProvider } from './providerTypes.js';
+
+/**
+ * The 'your own ~/.codex/config.toml is re-pointing this provider' advisory the
+ * server publishes on `GET /api/providers`, or `null`.
+ *
+ * Deliberately NOT part of `missingPrerequisites`: pointing Codex at a local
+ * bridge is a legitimate choice, so it must never bucket a card as NEEDS SETUP.
+ * What it fixes is PortOS reporting a ChatGPT account's readiness and quota for
+ * work that account never served. `advisory.baseUrl` is machine-local — render
+ * it here and nowhere else.
+ *
+ * SERVER-ONLY, with no client fallback: the browser cannot read the user's
+ * config file, so an older server publishing nothing correctly yields `null`.
+ * @returns {{code:string,label:string,keys:string[],baseUrl:string|null}|null}
+ */
+export const codexRoutingAdvisory = (provider) => (
+ Array.isArray(provider?.prerequisiteAdvisories)
+ ? provider.prerequisiteAdvisories.find((entry) => entry?.code === 'codexRoutingOverridden') || null
+ : null
+);
+
+/**
+ * Whether the AI Providers page should offer a "Refresh Models" button for this
+ * provider — i.e. whether the server has a model fetcher that can answer for it.
+ *
+ * Reads the server's own answer off the payload. `canRefreshModels` is derived
+ * on read from the per-vendor fetcher table
+ * (`server/lib/aiToolkit/internal/modelFetchers.js`) and decorated onto every
+ * provider-shaped response in `routes/providers.js`, so there is exactly one
+ * definition of "refreshable" and it lives next to the dispatch that has to
+ * honor it.
+ *
+ * This used to be a ~40-line hand-written mirror of both server dispatch arms,
+ * kept in lockstep by a comment. It drifted in both directions: too generous
+ * showed a button that 404'd, too stingy hid the feature with no error at all.
+ * Strict `=== true` so a legacy payload from an older server (no such field)
+ * hides the button rather than offering one that 404s.
+ * @param {{canRefreshModels?:boolean}|null|undefined} provider
+ * @returns {boolean}
+ */
+export const supportsModelRefresh = (provider) => provider?.canRefreshModels === true;
+
+/**
+ * Base name of a spawn command, normalized the way the CoS Agent Runner's
+ * allowlist check does before its membership test: strip any directory
+ * prefix, then a trailing Windows `.exe`. Mirror of `isAllowedCommand`'s
+ * normalization in `server/cos-runner/allowedCommands.js`, pinned by
+ * `server/cos-runner/allowedCommands.parity.test.js`.
+ *
+ * The server uses `path.basename`, which is platform-specific — on a POSIX
+ * host a backslash is NOT a separator. This mirror always treats both `/` and
+ * `\` as separators, so a Windows-style path typed into the editor on a POSIX
+ * install reads as "allowed" when the server would spawn-time reject it. That
+ * direction is deliberate: this drives an informational warning, and a false
+ * *warning* about a path the user's own platform handles fine is worse than a
+ * missing one for a path shape that platform can't run anyway.
+ */
+const runnerCommandBaseName = (command) => {
+ const base = String(command).replace(/[/\\]+$/, '').split(/[/\\]/).pop();
+ // Only `.exe` — a `.cmd`/`.bat` npm shim is deliberately NOT stripped,
+ // matching the server: the spawn path runs with `shell: false` and cannot
+ // execute a batch shim, so accepting it would only move the failure later.
+ return base.toLowerCase().endsWith('.exe') ? base.slice(0, -4) : base;
+};
+
+/**
+ * Would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command?
+ *
+ * `allowedCommands` is the server-published list (`runnerAllowedCommands` on
+ * `GET /api/providers`) — the client never carries its own copy, because the
+ * allowlist is the runner's exec boundary and must stay hand-curated
+ * server-side rather than derived from user-writable provider config.
+ *
+ * Returns `null` for "can't tell" — the list hasn't been fetched, or the field
+ * is still blank — which is distinct from `false` ("fetched, and this command
+ * is definitely off the list"). Only an explicit `false` should render a
+ * warning; a failed fetch must not accuse a perfectly good command.
+ *
+ * The command is matched UNTRIMMED (past the blank guard), because the editor
+ * persists it untrimmed too — `'claude '` really would fail the runner's check.
+ */
+export const isRunnerAllowedCommand = (command, allowedCommands) => {
+ if (!Array.isArray(allowedCommands) || allowedCommands.length === 0) return null;
+ if (typeof command !== 'string' || command.trim() === '') return null;
+ return allowedCommands.includes(runnerCommandBaseName(command));
+};
+
+/**
+ * The key a CLI/TUI provider's runtime is published under in the `runtimes` map
+ * from `GET /api/providers/runtimes` — the binary it spawns, basename-normalized
+ * so a provider pinned to an absolute path still matches.
+ *
+ * Deliberately NOT a client-side copy of the runtime table: the server owns
+ * which runtimes exist and how they install, and a key with no entry in the
+ * fetched map simply renders no install widget. That's the right default for a
+ * custom command PortOS has no installer for.
+ *
+ * API providers have no runtime here — the two fronted by a local app resolve
+ * through `localBackendForProvider` (which also matches a renamed provider by
+ * its endpoint) and get their install state from the local-LLM status.
+ */
+/**
+ * Does this provider resolve its binary somewhere PortOS's runtime probe never
+ * looked — an explicit path in `command`, or a `PATH` of its own in
+ * `envVars`?
+ *
+ * The runtime row answers one question, "does the bare binary resolve on
+ * PortOS's PATH?", and neither of these is that question: the runner spawns
+ * such a provider against its own resolution. MIRROR of the same two guards in
+ * `providerRuntimeKey` in server/lib/providerPrerequisites.js, which is what
+ * keeps the card's badge and the server's routing decision agreeing.
+ * @param {{type?:string,command?:string,envVars?:Record<string,string>}} provider
+ */
+export const resolvesOutsidePortosPath = (provider) => {
+ if (!isProcessProvider(provider)) return false;
+ if (/[\\/]/.test(String(provider?.command || '').trim())) return true;
+ return Object.keys(provider?.envVars || {}).some((key) => key.toUpperCase() === 'PATH');
+};
+
+export const providerRuntimeKey = (provider) => {
+ if (!isProcessProvider(provider)) return null;
+ const command = provider?.command;
+ if (typeof command !== 'string' || command.trim() === '') return null;
+ return runnerCommandBaseName(command.trim());
+};
+
+// Environment variables whose names are conventionally credentials. The
+// explicit secretEnvVars list remains the primary source, but it is a masking
+// list rather than a credential schema — providers may mark optional values
+// such as AWS_PROFILE secret too. Filter both sources so only actual credential
+// names participate in readiness. The explicit list can still name a custom
+// credential that does not follow this convention (for example MY_LLM_KEY).
+const CREDENTIAL_ENV_VAR_RE = /(?:^|_)(?:API_KEY|APIKEY|AUTH|ACCESS_KEY|ACCESS_TOKEN|BEARER|CLIENT_SECRET|CREDENTIALS?|KEY|PASSWORD|PRIVATE_KEY|SECRET|TOKEN)(?:_|$)/i;
+
+const NON_CREDENTIAL_ENV_VAR_RE = /(?:^|_)(?:BASE_URL|CONFIG|CONFIG_CONTENT|ENDPOINT|HOST|MODEL|MODE|PATH|PORT|PROFILE|REGION)(?:_|$)/i;
+
+const NON_CREDENTIAL_ENV_VAR_NAMES = new Set(['CLAUDE_CODE_USE_BEDROCK']);
+
+const providerHasStoredKey = (provider) =>
+ provider?.hasApiKey === true || Boolean(provider?.apiKey);
+
+const credentialEnvVars = (provider) => {
+ if (!isProcessProvider(provider)) return [];
+ const envVars = provider?.envVars && typeof provider.envVars === 'object' ? provider.envVars : {};
+ const secretEnvVars = Array.isArray(provider?.secretEnvVars) ? provider.secretEnvVars : [];
+ const explicit = new Set(secretEnvVars.filter((name) => typeof name === 'string' && name !== ''));
+ const names = [...secretEnvVars, ...Object.keys(envVars)];
+ return [...new Set(names.filter((name) => typeof name === 'string'
+ && !NON_CREDENTIAL_ENV_VAR_NAMES.has(name)
+ && !NON_CREDENTIAL_ENV_VAR_RE.test(name)
+ && (explicit.has(name) || CREDENTIAL_ENV_VAR_RE.test(name))))];
+};
+
+/**
+ * Identify how a provider authenticates, without deciding whether that
+ * credential is present. `null` is a deliberate ref for `none`, while a
+ * credential ref names the provider id, inherited sibling, or env var to look
+ * up. An own key wins over the gateway marker because the server leaves a
+ * provider carrying `provider.apiKey` untouched at spawn time.
+ *
+ * @param {{id?:string,type?:string,endpoint?:string,apiKey?:string,hasApiKey?:boolean,gatewayBacked?:string,orcarouterBacked?:boolean,envVars?:Record<string,string>,secretEnvVars?:string[]}|null|undefined} provider
+ * @returns {{kind:'stored'|'inherited'|'env'|'subscription'|'none',ref:string|null}}
+ */
+export const credentialSource = (provider) => {
+ // Codex CLI/TUI providers can use the ChatGPT subscription that Codex owns
+ // outside PortOS. It is neither a stored API key nor an environment
+ // credential, so the regular credential UI must not tell the user to paste a
+ // key. `providerCardState` receives the separate, bounded account verdict.
+ if (isCodexSubscriptionProvider(provider)) {
+ return { kind: 'subscription', ref: 'codex' };
+ }
+ // Local API endpoints need no credential, even if an old record happens to
+ // retain one from before the endpoint was changed.
+ if (isApiProvider(provider) && isPrivateNetworkEndpoint(provider?.endpoint)) {
+ return { kind: 'none', ref: null };
+ }
+ // API providers are the only ordinary providers whose stored key is read by
+ // PortOS itself. A legacy apiKey on a CLI/TUI record is not passed to the
+ // process and must not hide an empty process credential.
+ if (isApiProvider(provider)) {
+ return { kind: 'stored', ref: provider?.id || null };
+ }
+ // A gateway wrapper with its own key is the one process-backed exception:
+ // withGatewayApiKey leaves it untouched, so that key really is used.
+ if (isGatewayBackedProvider(provider) && providerHasStoredKey(provider)) {
+ return { kind: 'stored', ref: provider?.id || null };
+ }
+ const [envVar] = credentialEnvVars(provider);
+ if (envVar) return { kind: 'env', ref: envVar };
+ const gateway = gatewayForProvider(provider);
+ if (gateway) return { kind: 'inherited', ref: gateway.id };
+ return { kind: 'none', ref: null };
+};
+
+const normalizeCredentialState = (state) =>
+ state === true || state === false ? state : null;
+
+const defaultKeySetFor = (provider, id) =>
+ id && id === provider?.id ? providerHasStoredKey(provider) : null;
+
+const defaultEnvVarSet = (provider, name) => {
+ if (!name || !Object.hasOwn(provider?.envVars || {}, name)) return null;
+ const value = provider.envVars[name];
+ const isExplicitCredential = Array.isArray(provider?.secretEnvVars)
+ && provider.secretEnvVars.includes(name);
+ // `***` is the sanitized secret sentinel, not evidence that the value is
+ // present. A redacted value is unknown; an explicitly empty SECRET value is
+ // known missing. An unmarked empty value may deliberately clear an ambient
+ // host credential so the process can use another auth path, so it is unknown.
+ if (value === '***' || typeof value !== 'string') return null;
+ if (value === '' && !isExplicitCredential) return null;
+ return value !== '';
+};
+
+const credentialEnvGroups = (provider) => {
+ const names = credentialEnvVars(provider);
+ const groups = [];
+ const grouped = new Set();
+ const hasAwsAccessPair = names.includes('AWS_ACCESS_KEY_ID') && names.includes('AWS_SECRET_ACCESS_KEY');
+
+ for (const name of names) {
+ if (name === 'AWS_ACCESS_KEY_ID' && hasAwsAccessPair) {
+ groups.push(['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY']);
+ grouped.add('AWS_ACCESS_KEY_ID');
+ grouped.add('AWS_SECRET_ACCESS_KEY');
+ } else if (!grouped.has(name) && !(hasAwsAccessPair && name === 'AWS_SESSION_TOKEN')) {
+ groups.push([name]);
+ grouped.add(name);
+ }
+ }
+ return groups;
+};
+
+const inheritedCredentialMissing = (provider, keySetFor) => {
+ const gateway = gatewayForProvider(provider);
+ if (!gateway || providerHasStoredKey(provider)) return null;
+ const rawState = typeof keySetFor === 'function'
+ ? keySetFor(gateway.id)
+ : defaultKeySetFor(provider, gateway.id);
+ return normalizeCredentialState(rawState) === false
+ ? { code: 'inheritedApiKey', label: `${gateway.label} API provider has no API key` }
+ : null;
+};
+
+const credentialMissing = (provider, { keySetFor = null, envVarSet = null } = {}) => {
+ const source = credentialSource(provider);
+ if (source.kind === 'none' || source.kind === 'subscription' || !source.ref) return null;
+
+ if (source.kind === 'env') {
+ const groups = credentialEnvGroups(provider).map((group) => group.map((name) => {
+ const rawState = typeof envVarSet === 'function' ? envVarSet(name) : defaultEnvVarSet(provider, name);
+ return { name, state: normalizeCredentialState(rawState) };
+ }));
+ const inherited = inheritedCredentialMissing(provider, keySetFor);
+ // Providers can expose alternative credential schemes in one env map (for
+ // example Bedrock bearer auth or the AWS access-key pair). A complete known
+ // group satisfies the provider; a partial/unknown group keeps the result
+ // non-blocking rather than accusing a credential whose state is uncertain.
+ const satisfied = groups.some((group) => group.every(({ state }) => state === true));
+ const unknown = groups.some((group) => group.some(({ state }) => state === null));
+ if (satisfied || unknown) return inherited;
+ const missing = groups.flatMap((group) => group.filter(({ state }) => state === false).map(({ name }) => ({
+ code: 'envVar',
+ label: `${name} environment variable is not set`,
+ })));
+ if (inherited) missing.push(inherited);
+ return missing.length > 0 ? missing : null;
+ }
+
+ if (source.kind === 'inherited') {
+ return inheritedCredentialMissing(provider, keySetFor);
+ }
+ const rawState = typeof keySetFor === 'function'
+ ? keySetFor(source.ref)
+ : defaultKeySetFor(provider, source.ref);
+ return normalizeCredentialState(rawState) === false
+ ? { code: 'apiKey', label: 'API key is not set' }
+ : null;
+};
+
+/**
+ * The four states a provider card can be in on the AI Providers page, ordered
+ * the way the page groups them: usable now, temporarily benched, missing a
+ * prerequisite, or simply switched off.
+ */
+export const PROVIDER_CARD_STATE = Object.freeze({
+ READY: 'ready',
+ BENCHED: 'benched',
+ BLOCKED: 'blocked',
+ UNKNOWN: 'unknown',
+ DISABLED: 'disabled',
+});
+
+/**
+ * Which prerequisites a provider is missing, and the card state that follows
+ * from them — one place, so a card's border, its badge and the section the page
+ * files it under can never disagree with each other.
+ *
+ * NOT the same thing as `ProviderReadiness` /
+ * `GET /api/providers/readiness`, which probes whether the local DAEMON a
+ * provider points at (llama.cpp, Ollama, LM Studio, MTPLX, vLLM) is up and serving
+ * the right model. This decides the card's bucket from its toggle, its
+ * credentials and the server's bench status; the two render side by side.
+ *
+ * The prerequisite half is the SERVER's answer now (#4611): `GET
+ * /api/providers` publishes `missingPrerequisites` per provider from
+ * server/lib/providerPrerequisites.js, and `getFallbackProvider` skips a
+ * provider whose CLI that same computation found missing — so a card blocked on
+ * an uninstalled binary is no longer a routing candidate that dies at spawn
+ * time on a raw ENOENT. (Routing acts only on that finding; stored, inherited,
+ * and env-var credential findings stay presentation-only, and the browser now
+ * derives known env-var gaps without over-reporting redacted values.)
+ *
+ * This function consumes the published list and adds what the browser alone
+ * can see (the local-app runtime shape and sanitized env-credential state
+ * below). With an older server publishing nothing, it falls back to deriving
+ * the credential checks itself.
+ *
+ * Inputs are passed in rather than read from globals so this stays pure:
+ * runtime — the provider's entry of the `runtimes` map (CLI binary)
+ * or the local-app shape the page derives from the
+ * local-LLM status. `null` = NOT PROBED, which must never
+ * read as "missing" (an older server, or a card drawn
+ * before the probe lands, would otherwise accuse every
+ * perfectly-installed CLI).
+ * status — the runtime-availability entry from
+ * `GET /api/providers/status`; `available === false`
+ * means the provider is benched after a failure.
+ * keySetFor — tri-state lookup for a stored or inherited key. It must
+ * return `true`/`false` when known and `null` or another
+ * non-boolean when unknown.
+ * envVarSet — tri-state lookup for an environment credential. An
+ * explicitly empty configured value is `false`; a missing
+ * or redacted value is unknown and must not be reported.
+ *
+ * `disabled` outranks `blocked`: a provider the user switched off is not a gap
+ * in this install. PortOS ships dozens of provider records the user may never
+ * want, and calling every switched-off one "needs setup" makes an install with
+ * a perfectly good provider read as degraded or half-configured. What such a
+ * provider is missing is still returned in `missing` — a note for the user IF
+ * they decide to turn it on, not an outstanding task. `benched` only applies to
+ * an enabled provider that otherwise meets its prerequisites.
+ *
+ * @returns {{state: string, missing: {code: string, label: string}[]}}
+ */
+export const providerCardState = (provider, {
+ runtime = null,
+ status = null,
+ keySetFor = null,
+ envVarSet = null,
+ // `undefined` means an older server did not provide the account feature at
+ // all; `null` means this page tried to fetch it but could not determine a
+ // verdict. They must not collapse into "signed out" or "ready".
+ codexAccount = undefined,
+} = {}) => {
+ // The server publishes its own verdict on `GET /api/providers`
+ // (`missingPrerequisites`, from server/lib/providerPrerequisites.js) and
+ // routes the fallback chain on exactly that computation. Where it has an
+ // answer it WINS, so the card and the router cannot drift.
+ //
+ // An ARRAY is the sentinel for "published" — including the empty array, which
+ // is a real answer ("nothing missing"). Anything else (an older server, a
+ // payload fetched before the field existed) means not published, and the
+ // local derivation below stands in.
+ const published = Array.isArray(provider?.missingPrerequisites) ? provider.missingPrerequisites : null;
+ const missing = published ? [...published] : [];
+ const addMissing = (code, label) => {
+ if (!missing.some((entry) => entry?.code === code && (code !== 'envVar' || entry?.label === label))) {
+ missing.push({ code, label });
+ }
+ };
+
+ // Kept client-side even when the server has published: `runtime` here may be
+ // the LOCAL-APP shape the page derives from the local-LLM status (an LM Studio
+ // / Ollama app installed with no CLI shim on PATH), which the server's runtime
+ // table does not cover. For a plain CLI provider this is the same row the
+ // server probed, and `addMissing` de-dupes it by code.
+ //
+ // Except when the provider resolves its binary somewhere else. The runtime row
+ // answers "does the bare binary resolve on PortOS's PATH?", which says nothing
+ // about a provider configured as `/opt/tools/codex` or one that overrides
+ // `PATH` in its own env — the runner spawns those against their own
+ // resolution. Badging them NEEDS SETUP accuses a working provider, and the
+ // server (which owns the routing decision) already declines to. The install
+ // widget still renders from the same row: "PortOS can install this for you"
+ // remains true and useful either way.
+ if (runtime && runtime.installed === false && !resolvesOutsidePortosPath(provider)) {
+ addMissing('runtime', `${runtime.label || 'Runtime'} is not installed`);
+ }
+ // The server's published findings remain authoritative for stored/inherited
+ // credentials. Env credentials are also derived here because their values
+ // are intentionally redacted in the payload; the tri-state lookup lets an
+ // explicitly empty value be reported without treating a redacted/absent
+ // value as missing.
+ const source = credentialSource(provider);
+ if (!published || source.kind === 'env') {
+ const missingCredential = credentialMissing(provider, { keySetFor, envVarSet });
+ for (const entry of Array.isArray(missingCredential) ? missingCredential : [missingCredential]) {
+ if (entry) addMissing(entry.code, entry.label);
+ }
+ }
+
+ const codexSubscription = isCodexSubscriptionProvider(provider);
+ const accountStatus = codexAccount && typeof codexAccount === 'object'
+ ? codexAccount.status
+ : null;
+ if (codexSubscription && accountStatus === 'signed-out') {
+ addMissing('codexAccount', 'No ChatGPT account is signed in');
+ } else if (codexSubscription && accountStatus === 'reauth-required') {
+ addMissing('codexAccount', 'ChatGPT sign-in has expired');
+ } else if (codexSubscription && accountStatus === 'quota-exhausted') {
+ addMissing('codexQuota', 'ChatGPT usage limit reached');
+ }
+
+ // Switched off wins over every finding — see the precedence note above. The
+ // findings ride along so the card can still say what enabling it would take.
+ if (!provider?.enabled) return { state: PROVIDER_CARD_STATE.DISABLED, missing };
+ if (codexSubscription && codexAccount === null) return { state: PROVIDER_CARD_STATE.UNKNOWN, missing };
+ if (codexSubscription && accountStatus === 'unknown') return { state: PROVIDER_CARD_STATE.UNKNOWN, missing };
+ if (missing.length > 0) return { state: PROVIDER_CARD_STATE.BLOCKED, missing };
+ if (status?.available === false) return { state: PROVIDER_CARD_STATE.BENCHED, missing };
+ return { state: PROVIDER_CARD_STATE.READY, missing };
+};
diff --git a/client/src/utils/providerSelection.js b/client/src/utils/providerSelection.js
new file mode 100644
index 0000000000..02989ff6cd
--- /dev/null
+++ b/client/src/utils/providerSelection.js
@@ -0,0 +1,185 @@
+/**
+ * Which PROVIDERS and MODELS a picker may offer on this install: the
+ * hardware-compatibility filters (server-annotated, fail-open), the
+ * agent-harness runnability filter, and the fail-closed selection policies
+ * security-sensitive pickers apply — the tool-free local policy and the
+ * pr-reviewer public-review postures.
+ *
+ * The posture half is a browser MIRROR of `server/lib/agentExecutionProfiles.js`:
+ * a pipeline stage names a POSTURE, the server publishes each provider's
+ * `publicReviewPostures` / `publicReviewEnforcedPostures` on
+ * `GET /api/providers`, and the picker offers exactly the providers this
+ * install can run the stage on — no vendor is named on either side.
+ *
+ * Re-exported by `./providers.js` for existing `utils/providers` imports.
+ */
+
+import { isLocalInstanceProvider, localBackendForProvider } from './providerEndpoints.js';
+import { AGENT_HARNESS_PROVIDER_TYPES, isApiProvider } from './providerTypes.js';
+import { isHardwareCompatible } from './systemCapabilities.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,
+// but the harness still has filesystem/process authority, so they do not belong
+// in a tool-free security-review picker.
+export const TOOL_FREE_LOCAL_PROVIDER_IDS = Object.freeze(['ollama', 'lmstudio']);
+
+export const TOOL_FREE_LOCAL_TEXT_CAPABILITIES = Object.freeze(['chat', 'completion']);
+
+/**
+ * True only for PortOS's canonical local HTTP backends on this machine.
+ *
+ * The explicit ids keep a custom provider from inheriting a security-sensitive
+ * policy merely because its endpoint happens to mention Ollama or LM Studio.
+ * `isLocalInstanceProvider` keeps a renamed canonical record pointed at another
+ * machine out of the same policy.
+ */
+export const isToolFreeLocalProvider = (provider) =>
+ isApiProvider(provider)
+ && TOOL_FREE_LOCAL_PROVIDER_IDS.includes(String(provider?.id || '').toLowerCase())
+ && isLocalInstanceProvider(provider);
+
+/**
+ * Whether a local model has an authoritative, explicit text capability report
+ * that excludes native tool use. Embedding-only models cannot review a diff;
+ * unknown capability state is unsafe for a security scan and therefore returns
+ * false rather than falling back to model-name heuristics.
+ *
+ * `capabilitiesByBackend` is the shape returned by `useLocalModels`; object
+ * model entries are accepted too so callers with a richer model catalog can use
+ * the same predicate without rebuilding a map.
+ */
+const isToolFreeLocalModelForProvider = (model, provider, capabilitiesByBackend, providerPredicate) => {
+ if (!providerPredicate(provider)) return false;
+ const id = typeof model === 'string' ? model : model?.id || model?.name;
+ if (typeof id !== 'string' || !id.trim()) return false;
+ const reported = Array.isArray(model?.capabilities)
+ ? model.capabilities
+ : capabilitiesByBackend?.[localBackendForProvider(provider)]?.[id];
+ if (!Array.isArray(reported)) return false;
+ const normalized = reported.map((capability) => String(capability).toLowerCase());
+ return normalized.some((capability) => TOOL_FREE_LOCAL_TEXT_CAPABILITIES.includes(capability))
+ && !normalized.includes('tools');
+};
+
+export const isToolFreeLocalModel = (model, provider, capabilitiesByBackend = {}) =>
+ isToolFreeLocalModelForProvider(model, provider, capabilitiesByBackend, isToolFreeLocalProvider);
+
+/**
+ * Build the shared selection policy used by security-sensitive AI pickers.
+ * ProviderModelSelector owns applying all three predicates consistently; a
+ * caller supplies only the policy-specific capability source.
+ */
+export const toolFreeLocalSelectionPolicy = (
+ capabilitiesByBackend = {},
+ { providerPredicate = isToolFreeLocalProvider } = {},
+) => ({
+ provider: providerPredicate,
+ model: (model, provider) => isToolFreeLocalModelForProvider(
+ model,
+ provider,
+ capabilitiesByBackend,
+ providerPredicate,
+ ),
+});
+
+// The two enforceable public-review postures. MIRROR of
+// `server/lib/agentExecutionProfiles.js`; a pr-reviewer stage names a posture
+// and the server publishes each provider's `publicReviewPostures` on
+// `GET /api/providers`, so no vendor is ever named on either side.
+export const PUBLIC_REVIEW_NO_TOOL_POSTURE = 'no-tool';
+
+export const PUBLIC_REVIEW_ACTIONS_POSTURE = 'sandboxed-actions';
+
+/**
+ * Whether the SERVER says this provider can enforce `posture`. Falls back to
+ * the older per-posture booleans so a browser talking to a peer/older server
+ * still renders a correct picker instead of an empty one.
+ */
+export const supportsPublicReviewPosture = (provider, posture) => {
+ if (Array.isArray(provider?.publicReviewPostures)) return provider.publicReviewPostures.includes(posture);
+ return posture === PUBLIC_REVIEW_ACTIONS_POSTURE
+ ? provider?.publicReviewActionsSupported === true
+ : provider?.publicReviewSupported === true;
+};
+
+/**
+ * Whether the SERVER runs `posture` on this provider through a vendor-enforced
+ * recipe (an OS sandbox for the actions stage), as opposed to merely allowing
+ * it. `publicReviewEnforcedPostures` is the server's subset; an older server
+ * that does not publish it only ever offered enforced providers, so its
+ * eligible set is taken as enforced.
+ */
+export const enforcesPublicReviewPosture = (provider, posture) => {
+ if (Array.isArray(provider?.publicReviewEnforcedPostures)) return provider.publicReviewEnforcedPostures.includes(posture);
+ return supportsPublicReviewPosture(provider, posture);
+};
+
+/**
+ * Selection policy for a pr-reviewer stage.
+ *
+ * Provider eligibility is entirely server-derived. Model eligibility adds the
+ * authoritative no-tool capability check only where PortOS can actually probe
+ * it — a LOCAL runtime behind the provider. A cloud model is not probeable, so
+ * the vendor's enforced argv (`--restricted --tools ''`, `--sandbox read-only`,
+ * `--permission-mode plan`) is what denies it tools, and every model the
+ * provider lists stays selectable.
+ */
+export const publicReviewSelectionPolicy = (posture, capabilitiesByBackend = {}) => ({
+ provider: (provider) => supportsPublicReviewPosture(provider, posture),
+ model: (model, provider) => {
+ if (!supportsPublicReviewPosture(provider, posture)) return false;
+ if (posture !== PUBLIC_REVIEW_NO_TOOL_POSTURE || !localBackendForProvider(provider)) return true;
+ return isToolFreeLocalModelForProvider(
+ model,
+ provider,
+ capabilitiesByBackend,
+ () => true,
+ );
+ },
+});
+
+/**
+ * Retain an existing non-runnable pin so a saved job can still be edited and
+ * cleared, while limiting new agent-job selections to runnable providers.
+ */
+export const filterRunnableProviders = (providers, selectedProviderIds = []) => {
+ const preservedIds = new Set(
+ (Array.isArray(selectedProviderIds) ? selectedProviderIds : [selectedProviderIds]).filter(Boolean)
+ );
+ return (Array.isArray(providers) ? providers : []).filter(provider =>
+ AGENT_HARNESS_PROVIDER_TYPES.includes(provider?.type) || preservedIds.has(provider?.id)
+ );
+};
+
+/**
+ * Server-side hardware metadata is advisory for unknown probe results and
+ * definitive only when `state` is `unavailable`. Keep this helper fail-open so
+ * older servers and custom providers remain selectable.
+ */
+export const isProviderHardwareCompatible = (provider) =>
+ isHardwareCompatible(provider?.hardwareCompatibility);
+
+/**
+ * The providers a picker may offer: enabled, runnable on this hardware, and
+ * allowed by the caller's policy — plus the currently-selected id whatever its
+ * state, so a saved pin still renders instead of silently blanking. This is
+ * the single rule `ProviderModelSelector` renders from; a caller that lists
+ * "eligible" providers beside such a picker must derive the list from here so
+ * the note and the dropdown cannot disagree.
+ */
+export const selectableProviders = (providers, { selectedId = '', allowed = null } = {}) =>
+ (Array.isArray(providers) ? providers : []).filter((provider) => (
+ provider?.id === selectedId
+ || (provider?.enabled !== false && isProviderHardwareCompatible(provider) && (!allowed || allowed(provider)))
+ ));
+
+export const isProviderModelHardwareCompatible = (provider, model) =>
+ isProviderHardwareCompatible(provider)
+ && isHardwareCompatible(provider?.modelHardwareCompatibility?.[model]);
+
+export const filterHardwareCompatibleProviderModels = (models, provider) =>
+ (models || []).filter((model) => {
+ const modelId = typeof model === 'string' ? model : model?.id;
+ return isProviderModelHardwareCompatible(provider, modelId);
+ });
diff --git a/client/src/utils/providerTypes.js b/client/src/utils/providerTypes.js
new file mode 100644
index 0000000000..173490a612
--- /dev/null
+++ b/client/src/utils/providerTypes.js
@@ -0,0 +1,277 @@
+/**
+ * What KIND of provider a record is: the `cli`/`tui`/`api` type enum and its
+ * predicates, the vendor-harness predicates keyed on the shipped ids plus the
+ * launch command's basename (so a path-configured or renamed `codex`/`agy`/
+ * `kimi`/`cursor-agent`/`grok`/`claude` still qualifies), and the structural
+ * backend markers (`ollamaBacked`, `lmstudioBacked`, …) a wrapper record carries.
+ *
+ * Browser MIRROR of the predicates in `server/lib/providerModels.js` (the
+ * `isXProvider` family, `commandBasename`, `localRuntimeNamespace`),
+ * `server/lib/aiToolkit/constants.js#PROVIDER_TYPES` and
+ * `server/lib/aiToolkit/providers.js#isOllamaBackedProvider` — keep in lockstep.
+ * Every other provider helper module builds on these; this one imports only
+ * the gateway registry.
+ *
+ * Re-exported by `./providers.js` for existing `utils/providers` imports.
+ */
+
+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
+// 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) =>
+ typeof command === 'string' && command !== ''
+ ? command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '')
+ : '';
+
+/**
+ * True when a provider is codex-flavored — the shipped `codex`/`codex-tui` ids
+ * or any provider whose launch command basename is `codex` (path/exe tolerant).
+ * MIRROR of `isCodexProvider` in server/lib/providerModels.js — keep in lockstep.
+ * @param {{id?:string, command?:string}|null|undefined} provider
+ * @returns {boolean}
+ */
+export const isCodexProvider = (provider) => {
+ const id = String(provider?.id || '').toLowerCase();
+ return id === 'codex' || id === 'codex-tui' || commandBasename(provider?.command) === 'codex';
+};
+
+/**
+ * True when a provider is Grok-Build-flavored. MIRROR of `isGrokProvider` in
+ * server/lib/providerModels.js — the shipped `grok-cli`/`grok-tui` ids or a
+ * `grok` command basename. The bare `grok` id is the HTTP API provider, which
+ * has no CLI flag to carry an effort level, and is excluded.
+ * @param {{id?:string, command?:string}|null|undefined} provider
+ * @returns {boolean}
+ */
+export const isGrokProvider = (provider) => {
+ const id = String(provider?.id || '').toLowerCase();
+ return id === 'grok-cli' || id === 'grok-tui' || commandBasename(provider?.command) === 'grok';
+};
+
+/**
+ * True when a CLI/TUI record uses Codex's ChatGPT subscription. This mirrors
+ * server/lib/codexAccount.js: the command, not an editable provider id, owns
+ * the account contract.
+ * @param {{type?:string, command?:string}|null|undefined} provider
+ * @returns {boolean}
+ */
+export const isCodexSubscriptionProvider = (provider) =>
+ (provider?.type === 'cli' || provider?.type === 'tui')
+ && commandBasename(provider?.command) === 'codex'
+ // A local-runtime-backed codex record (`codex --oss --local-provider ollama`)
+ // generates its tokens on this machine and authenticates against nothing, so
+ // it must not be painted "No ChatGPT account is signed in" — or parked in
+ // UNKNOWN waiting on an account read that will never matter.
+ && localRuntimeNamespace(provider) === null;
+
+/**
+ * True when a provider is Kimi-Code-flavored — the shipped `kimi-cli`/`kimi-tui`
+ * ids or any provider whose launch command basename is `kimi` (path/exe tolerant).
+ * MIRROR of `isKimiProvider` in server/lib/providerModels.js — keep in lockstep.
+ * @param {{id?:string, command?:string}|null|undefined} provider
+ * @returns {boolean}
+ */
+export const isKimiProvider = (provider) => {
+ const id = String(provider?.id || '').toLowerCase();
+ return id === 'kimi-cli' || id === 'kimi-tui' || commandBasename(provider?.command) === 'kimi';
+};
+
+/**
+ * True when a provider is Antigravity-flavored — the shipped
+ * `antigravity-cli`/`antigravity-tui` ids or any provider whose launch command
+ * basename is `agy`/`antigravity` (path/exe tolerant). MIRROR of
+ * `isAntigravityProvider` in server/lib/providerModels.js — keep in lockstep.
+ * @param {{id?:string, command?:string}|null|undefined} provider
+ * @returns {boolean}
+ */
+export const isAntigravityProvider = (provider) => {
+ if (!provider) return false;
+ const id = String(provider.id || '').toLowerCase();
+ if (id === 'antigravity-cli' || id === 'antigravity-tui') return true;
+ const base = commandBasename(provider.command);
+ return base === 'agy' || base === 'antigravity';
+};
+
+/**
+ * True when a provider is Cursor-Agent-flavored — the shipped
+ * `cursor-cli`/`cursor-tui` ids or any provider whose launch command basename is
+ * `cursor-agent` (never a bare `cursor`, which is the GUI editor). MIRROR of
+ * `isCursorProvider` in server/lib/providerModels.js — keep in lockstep.
+ * @param {{id?:string, command?:string}|null|undefined} provider
+ * @returns {boolean}
+ */
+export const isCursorProvider = (provider) => {
+ if (!provider) return false;
+ const id = String(provider.id || '').toLowerCase();
+ return id === 'cursor-cli' || id === 'cursor-tui' || commandBasename(provider.command) === 'cursor-agent';
+};
+
+/**
+ * Provider-type enum mirrored from server/lib/aiToolkit/constants.js#PROVIDER_TYPES.
+ * The aiToolkit directory is kept self-contained (no imports out to other PortOS
+ * modules) so the client cannot import the server copy directly — keep these two
+ * in lockstep when adding a type. The provider type predicates below and the
+ * Tailwind chip helper read from this object, so a string literal only needs to
+ * appear once per side.
+ */
+export const PROVIDER_TYPES = Object.freeze({
+ CLI: 'cli',
+ TUI: 'tui',
+ API: 'api'
+});
+
+// Agent jobs need the CLI/TUI file-writing harnesses. Keep this allowlist in
+// lockstep with the api-provider rejection in server/services/agentProviderResolution.js.
+export const AGENT_HARNESS_PROVIDER_TYPES = Object.freeze([
+ PROVIDER_TYPES.CLI,
+ PROVIDER_TYPES.TUI
+]);
+
+/**
+ * True when an OpenCode process provider runs against one of the local
+ * OpenAI-compatible backends (Ollama / LM Studio / MTPLX / llama.cpp / vLLM) or
+ * a hosted gateway (OrcaRouter / OpenRouter)
+ * rather than a vendor cloud model. MIRROR of `isOpencodeProvider(p) &&
+ * getOpencodeLocalProviderNamespace(p)` in server/lib/providerModels.js, which
+ * is exactly what gates the effort ladder there — so a backend marker missing
+ * here hides the effort picker for a provider the server would happily forward
+ * `reasoningEffort` for (#4765).
+ */
+export const isOpencodeLocalProvider = (provider) =>
+ (['opencode', 'opencode-tui'].includes(String(provider?.id || '').toLowerCase())
+ || commandBasename(provider?.command) === 'opencode')
+ && (localRuntimeNamespace(provider) !== null || isGatewayBackedProvider(provider));
+
+/**
+ * Check if a provider is a TUI-backed agent provider. Mirror of
+ * `isTuiProvider` in server/services/agentCliSpawning.js.
+ */
+export const isTuiProvider = (provider) => provider?.type === PROVIDER_TYPES.TUI;
+
+/**
+ * Can a human launch this provider at a shell prompt?
+ *
+ * TUI is the only type that has an interactive form — a `cli` provider's args
+ * are headless (`--print`), and an `api` provider has no local binary at all.
+ * `tuiCommandLine` is the server's own resolution of what the launch will run
+ * (`server/lib/tuiShellLaunch.js`, published by `GET /api/providers`), so a
+ * provider it could not resolve a command for is not offered, and an older
+ * server that omits the field simply offers nothing.
+ *
+ * Shared so the AI Providers card's "Launch in Shell" button and the Shell
+ * page's launch menu can't disagree about which providers are launchable.
+ */
+export const isLaunchableTuiProvider = (provider) => isTuiProvider(provider) && Boolean(provider?.tuiCommandLine);
+
+/**
+ * Check if a provider is a one-shot CLI agent provider.
+ */
+export const isCliProvider = (provider) => provider?.type === PROVIDER_TYPES.CLI;
+
+/**
+ * Check if a provider is an HTTP-API provider (e.g. OpenAI, Anthropic, LM Studio),
+ * as opposed to a process-backed CLI/TUI agent. Use this anywhere you'd write
+ * `provider.type === PROVIDER_TYPES.API` against a saved provider.
+ */
+export const isApiProvider = (provider) => provider?.type === PROVIDER_TYPES.API;
+
+/**
+ * Stable, module-scoped filter for `useProviderModels({ filter })` and other
+ * call sites that need "enabled HTTP-API providers only". Hoisted so the
+ * identity is the same across renders (callers may pass it as a dependency).
+ */
+export const enabledApiProviderFilter = (provider) => Boolean(provider?.enabled) && isApiProvider(provider);
+
+/**
+ * Check if a provider is process-backed (cli or tui), as opposed to an
+ * HTTP-API provider. Use this for "shows a Command + args" config predicates.
+ */
+export const isProcessProvider = (provider) => isCliProvider(provider) || isTuiProvider(provider);
+
+/**
+ * Whether `provider` is served by an Ollama daemon rather than its nominal
+ * cloud/CLI backend: the built-in `ollama` API provider itself (id match), an
+ * `api`-type provider whose `endpoint` points at Ollama, or the Claude-Ollama
+ * CLI/TUI pattern — a `claude` process carrying the `ollamaBacked` marker or an
+ * `ANTHROPIC_BASE_URL` pointed at Ollama, which runs the Claude Code harness but
+ * generates tokens locally, so its model list is refreshed from Ollama
+ * (including the TUI variant, which the server refreshes via the
+ * `type==='tui' && ollamaBacked` branch). MIRROR of `isOllamaBackedProvider` in
+ * server/lib/aiToolkit/providers.js.
+ * @param {{id?:string,endpoint?:string,ollamaBacked?:boolean,envVars?:Record<string,string>}} provider
+ */
+export const isOllamaBackedProvider = (provider) => {
+ if (provider?.id === 'ollama') return true;
+ if (provider?.ollamaBacked === true) return true;
+ const base = String(provider?.envVars?.ANTHROPIC_BASE_URL || provider?.endpoint || '');
+ return /:11434\b/.test(base) || /ollama/i.test(base);
+};
+
+/**
+ * The LOCAL daemon namespace a provider is marked with, or null. Structural
+ * markers only — a hosted gateway is an OpenCode namespace and a remote API, so
+ * it is deliberately NOT one of these.
+ *
+ * MIRROR of `localRuntimeNamespace` in server/lib/providerModels.js — keep in
+ * lockstep. The order matters: a malformed record carrying two markers keeps its
+ * legacy Ollama outcome on both sides.
+ * @param {{ollamaBacked?:boolean,mtplxBacked?:boolean,llamaBacked?:boolean,vllmBacked?:boolean,sglangBacked?:boolean}|null|undefined} provider
+ * @returns {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|null}
+ */
+export const localRuntimeNamespace = (provider) => {
+ if (provider?.ollamaBacked === true) return 'ollama';
+ if (provider?.lmstudioBacked === true) return 'lmstudio';
+ if (provider?.mtplxBacked === true) return 'mtplx';
+ if (provider?.llamaBacked === true) return 'llama';
+ if (provider?.vllmBacked === true) return 'vllm';
+ if (provider?.sglangBacked === true) return 'sglang';
+ return null;
+};
+
+/**
+ * True when a provider launches the Claude Code binary, whatever backend it is
+ * pointed at (`claude-code`, `claude-ollama`, `claude-sglang`, or any renamed
+ * record whose command resolves to `claude`).
+ *
+ * The harness — not the backend — is what decides which knobs are forwardable:
+ * Claude Code owns its own sampling and speaks the Anthropic wire, so a control
+ * that reaches an OpenCode wrapper through `agent.build` has no route here.
+ * MIRROR of `isClaudeCommand` in server/lib/providerModels.js.
+ * @param {{command?:string}|null|undefined} provider
+ */
+export const isClaudeCommandProvider = (provider) => commandBasename(provider?.command) === 'claude';
+
+/**
+ * Check if a provider is the Grok Build CLI/TUI (the `grok` command harness).
+ * Matches the shipped `grok-cli` / `grok-tui` samples or any process provider
+ * whose command basename is `grok`; the plain Grok API provider is excluded.
+ * Reviewer-model discovery uses this for custom Grok process providers too.
+ */
+export const isGrokBuildCli = (provider) => {
+ if (!isProcessProvider(provider)) return false;
+ const id = String(provider?.id || '').toLowerCase();
+ return id === 'grok-cli' || id === 'grok-tui' || commandBasename(provider?.command) === 'grok';
+};
+
+/**
+ * Tailwind chip classes for the provider type badge ('cli' / 'tui' / 'api').
+ * Lifted out of AIProviders.jsx so other components can render the same
+ * color treatment without redefining it.
+ */
+export const providerTypeClass = (type) => {
+ if (type === PROVIDER_TYPES.CLI) return 'bg-blue-500/20 text-blue-400';
+ if (type === PROVIDER_TYPES.TUI) return 'bg-emerald-500/20 text-emerald-400';
+ return 'bg-purple-500/20 text-purple-400';
+};
+
+// ---------------------------------------------------------------------------
+// AI Assignments option helpers — shared by the global AI Assignments table
+// (settings/AiAssignmentsTab.jsx) and per-record override drawers (e.g. the
+// Creative Director Models drawer). All three consume the `getAiAssignments`
+// payload shape (`{ providers, assignments }`), where an assignment `entry` may
+// carry `providerTypes` (which provider kinds are eligible) and optional
+// pre-baked `providerOptions` / `modelOptions` overrides for runtime call sites.
+// ---------------------------------------------------------------------------
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 3bb3e5e29a..4ae973949c 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -1,2194 +1,31 @@
-import { formatContextLength } from './formatters.js';
-import { isHardwareCompatible } from './systemCapabilities.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([
- 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);
-
-/**
- * The configured-default sentinel carried in a provider's model list, or null.
- *
- * `filterSelectableModels` strips sentinels from every picker, which is right
- * for a *task's* model choice ("no override" is the empty option there). But a
- * provider whose `defaultModel`/`lightModel`/… IS the sentinel while its
- * `models` also holds real ids (Antigravity: `agy` has a real catalog AND its
- * own configured default) would otherwise drive a `<select>` whose value
- * matches no `<option>` — the field renders blank and reads as "unset" when the
- * CLI's own default is in fact what's configured. The provider-edit form uses
- * this to render an explicit option for it.
- * @param {string[]|null|undefined} models
- * @returns {string|null}
- */
-export const configuredDefaultIn = (models) =>
- (models || []).find(isConfiguredDefaultModel) || null;
-
-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;
-};
-
-// 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
-// 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) =>
- typeof command === 'string' && command !== ''
- ? command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '')
- : '';
-
-/**
- * True when a provider is codex-flavored — the shipped `codex`/`codex-tui` ids
- * or any provider whose launch command basename is `codex` (path/exe tolerant).
- * MIRROR of `isCodexProvider` in server/lib/providerModels.js — keep in lockstep.
- * @param {{id?:string, command?:string}|null|undefined} provider
- * @returns {boolean}
- */
-export const isCodexProvider = (provider) => {
- const id = String(provider?.id || '').toLowerCase();
- return id === 'codex' || id === 'codex-tui' || commandBasename(provider?.command) === 'codex';
-};
-
-/**
- * True when a provider is Grok-Build-flavored. MIRROR of `isGrokProvider` in
- * server/lib/providerModels.js — the shipped `grok-cli`/`grok-tui` ids or a
- * `grok` command basename. The bare `grok` id is the HTTP API provider, which
- * has no CLI flag to carry an effort level, and is excluded.
- * @param {{id?:string, command?:string}|null|undefined} provider
- * @returns {boolean}
- */
-export const isGrokProvider = (provider) => {
- const id = String(provider?.id || '').toLowerCase();
- return id === 'grok-cli' || id === 'grok-tui' || commandBasename(provider?.command) === 'grok';
-};
-
-/**
- * True when a CLI/TUI record uses Codex's ChatGPT subscription. This mirrors
- * server/lib/codexAccount.js: the command, not an editable provider id, owns
- * the account contract.
- * @param {{type?:string, command?:string}|null|undefined} provider
- * @returns {boolean}
- */
-export const isCodexSubscriptionProvider = (provider) =>
- (provider?.type === 'cli' || provider?.type === 'tui')
- && commandBasename(provider?.command) === 'codex'
- // A local-runtime-backed codex record (`codex --oss --local-provider ollama`)
- // generates its tokens on this machine and authenticates against nothing, so
- // it must not be painted "No ChatGPT account is signed in" — or parked in
- // UNKNOWN waiting on an account read that will never matter.
- && localRuntimeNamespace(provider) === null;
-
-/**
- * The 'your own ~/.codex/config.toml is re-pointing this provider' advisory the
- * server publishes on `GET /api/providers`, or `null`.
- *
- * Deliberately NOT part of `missingPrerequisites`: pointing Codex at a local
- * bridge is a legitimate choice, so it must never bucket a card as NEEDS SETUP.
- * What it fixes is PortOS reporting a ChatGPT account's readiness and quota for
- * work that account never served. `advisory.baseUrl` is machine-local — render
- * it here and nowhere else.
- *
- * SERVER-ONLY, with no client fallback: the browser cannot read the user's
- * config file, so an older server publishing nothing correctly yields `null`.
- * @returns {{code:string,label:string,keys:string[],baseUrl:string|null}|null}
- */
-export const codexRoutingAdvisory = (provider) => (
- Array.isArray(provider?.prerequisiteAdvisories)
- ? provider.prerequisiteAdvisories.find((entry) => entry?.code === 'codexRoutingOverridden') || null
- : null
-);
-
-/**
- * True when a provider is Kimi-Code-flavored — the shipped `kimi-cli`/`kimi-tui`
- * ids or any provider whose launch command basename is `kimi` (path/exe tolerant).
- * MIRROR of `isKimiProvider` in server/lib/providerModels.js — keep in lockstep.
- * @param {{id?:string, command?:string}|null|undefined} provider
- * @returns {boolean}
- */
-export const isKimiProvider = (provider) => {
- const id = String(provider?.id || '').toLowerCase();
- return id === 'kimi-cli' || id === 'kimi-tui' || commandBasename(provider?.command) === 'kimi';
-};
-
-/**
- * True when a provider is Antigravity-flavored — the shipped
- * `antigravity-cli`/`antigravity-tui` ids or any provider whose launch command
- * basename is `agy`/`antigravity` (path/exe tolerant). MIRROR of
- * `isAntigravityProvider` in server/lib/providerModels.js — keep in lockstep.
- * @param {{id?:string, command?:string}|null|undefined} provider
- * @returns {boolean}
- */
-export const isAntigravityProvider = (provider) => {
- if (!provider) return false;
- const id = String(provider.id || '').toLowerCase();
- if (id === 'antigravity-cli' || id === 'antigravity-tui') return true;
- const base = commandBasename(provider.command);
- return base === 'agy' || base === 'antigravity';
-};
-
-/**
- * True when a provider is Cursor-Agent-flavored — the shipped
- * `cursor-cli`/`cursor-tui` ids or any provider whose launch command basename is
- * `cursor-agent` (never a bare `cursor`, which is the GUI editor). MIRROR of
- * `isCursorProvider` in server/lib/providerModels.js — keep in lockstep.
- * @param {{id?:string, command?:string}|null|undefined} provider
- * @returns {boolean}
- */
-export const isCursorProvider = (provider) => {
- if (!provider) return false;
- const id = String(provider.id || '').toLowerCase();
- return id === 'cursor-cli' || id === 'cursor-tui' || commandBasename(provider.command) === 'cursor-agent';
-};
-
-/**
- * Whether the AI Providers page should offer a "Refresh Models" button for this
- * provider — i.e. whether the server has a model fetcher that can answer for it.
- *
- * Reads the server's own answer off the payload. `canRefreshModels` is derived
- * on read from the per-vendor fetcher table
- * (`server/lib/aiToolkit/internal/modelFetchers.js`) and decorated onto every
- * provider-shaped response in `routes/providers.js`, so there is exactly one
- * definition of "refreshable" and it lives next to the dispatch that has to
- * honor it.
- *
- * This used to be a ~40-line hand-written mirror of both server dispatch arms,
- * kept in lockstep by a comment. It drifted in both directions: too generous
- * showed a button that 404'd, too stingy hid the feature with no error at all.
- * Strict `=== true` so a legacy payload from an older server (no such field)
- * hides the button rather than offering one that 404s.
- * @param {{canRefreshModels?:boolean}|null|undefined} provider
- * @returns {boolean}
- */
-export const supportsModelRefresh = (provider) => provider?.canRefreshModels === true;
-
-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;
-};
-
-/**
- * Provider-type enum mirrored from server/lib/aiToolkit/constants.js#PROVIDER_TYPES.
- * The aiToolkit directory is kept self-contained (no imports out to other PortOS
- * modules) so the client cannot import the server copy directly — keep these two
- * in lockstep when adding a type. The provider type predicates below and the
- * Tailwind chip helper read from this object, so a string literal only needs to
- * appear once per side.
- */
-export const PROVIDER_TYPES = Object.freeze({
- CLI: 'cli',
- TUI: 'tui',
- API: 'api'
-});
-
-// Agent jobs need the CLI/TUI file-writing harnesses. Keep this allowlist in
-// lockstep with the api-provider rejection in server/services/agentProviderResolution.js.
-export const AGENT_HARNESS_PROVIDER_TYPES = Object.freeze([
- PROVIDER_TYPES.CLI,
- PROVIDER_TYPES.TUI
-]);
-
-// 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,
-// but the harness still has filesystem/process authority, so they do not belong
-// in a tool-free security-review picker.
-export const TOOL_FREE_LOCAL_PROVIDER_IDS = Object.freeze(['ollama', 'lmstudio']);
-export const TOOL_FREE_LOCAL_TEXT_CAPABILITIES = Object.freeze(['chat', 'completion']);
-
-/**
- * True only for PortOS's canonical local HTTP backends on this machine.
- *
- * The explicit ids keep a custom provider from inheriting a security-sensitive
- * policy merely because its endpoint happens to mention Ollama or LM Studio.
- * `isLocalInstanceProvider` keeps a renamed canonical record pointed at another
- * machine out of the same policy.
- */
-export const isToolFreeLocalProvider = (provider) =>
- isApiProvider(provider)
- && TOOL_FREE_LOCAL_PROVIDER_IDS.includes(String(provider?.id || '').toLowerCase())
- && isLocalInstanceProvider(provider);
-
-/**
- * Whether a local model has an authoritative, explicit text capability report
- * that excludes native tool use. Embedding-only models cannot review a diff;
- * unknown capability state is unsafe for a security scan and therefore returns
- * false rather than falling back to model-name heuristics.
- *
- * `capabilitiesByBackend` is the shape returned by `useLocalModels`; object
- * model entries are accepted too so callers with a richer model catalog can use
- * the same predicate without rebuilding a map.
- */
-const isToolFreeLocalModelForProvider = (model, provider, capabilitiesByBackend, providerPredicate) => {
- if (!providerPredicate(provider)) return false;
- const id = typeof model === 'string' ? model : model?.id || model?.name;
- if (typeof id !== 'string' || !id.trim()) return false;
- const reported = Array.isArray(model?.capabilities)
- ? model.capabilities
- : capabilitiesByBackend?.[localBackendForProvider(provider)]?.[id];
- if (!Array.isArray(reported)) return false;
- const normalized = reported.map((capability) => String(capability).toLowerCase());
- return normalized.some((capability) => TOOL_FREE_LOCAL_TEXT_CAPABILITIES.includes(capability))
- && !normalized.includes('tools');
-};
-
-export const isToolFreeLocalModel = (model, provider, capabilitiesByBackend = {}) =>
- isToolFreeLocalModelForProvider(model, provider, capabilitiesByBackend, isToolFreeLocalProvider);
-
-/**
- * Build the shared selection policy used by security-sensitive AI pickers.
- * ProviderModelSelector owns applying all three predicates consistently; a
- * caller supplies only the policy-specific capability source.
- */
-export const toolFreeLocalSelectionPolicy = (
- capabilitiesByBackend = {},
- { providerPredicate = isToolFreeLocalProvider } = {},
-) => ({
- provider: providerPredicate,
- model: (model, provider) => isToolFreeLocalModelForProvider(
- model,
- provider,
- capabilitiesByBackend,
- providerPredicate,
- ),
-});
-
-// The two enforceable public-review postures. MIRROR of
-// `server/lib/agentExecutionProfiles.js`; a pr-reviewer stage names a posture
-// and the server publishes each provider's `publicReviewPostures` on
-// `GET /api/providers`, so no vendor is ever named on either side.
-export const PUBLIC_REVIEW_NO_TOOL_POSTURE = 'no-tool';
-export const PUBLIC_REVIEW_ACTIONS_POSTURE = 'sandboxed-actions';
-
-/**
- * Whether the SERVER says this provider can enforce `posture`. Falls back to
- * the older per-posture booleans so a browser talking to a peer/older server
- * still renders a correct picker instead of an empty one.
- */
-export const supportsPublicReviewPosture = (provider, posture) => {
- if (Array.isArray(provider?.publicReviewPostures)) return provider.publicReviewPostures.includes(posture);
- return posture === PUBLIC_REVIEW_ACTIONS_POSTURE
- ? provider?.publicReviewActionsSupported === true
- : provider?.publicReviewSupported === true;
-};
-
-/**
- * Whether the SERVER runs `posture` on this provider through a vendor-enforced
- * recipe (an OS sandbox for the actions stage), as opposed to merely allowing
- * it. `publicReviewEnforcedPostures` is the server's subset; an older server
- * that does not publish it only ever offered enforced providers, so its
- * eligible set is taken as enforced.
- */
-export const enforcesPublicReviewPosture = (provider, posture) => {
- if (Array.isArray(provider?.publicReviewEnforcedPostures)) return provider.publicReviewEnforcedPostures.includes(posture);
- return supportsPublicReviewPosture(provider, posture);
-};
-
-/**
- * Selection policy for a pr-reviewer stage.
- *
- * Provider eligibility is entirely server-derived. Model eligibility adds the
- * authoritative no-tool capability check only where PortOS can actually probe
- * it — a LOCAL runtime behind the provider. A cloud model is not probeable, so
- * the vendor's enforced argv (`--restricted --tools ''`, `--sandbox read-only`,
- * `--permission-mode plan`) is what denies it tools, and every model the
- * provider lists stays selectable.
- */
-export const publicReviewSelectionPolicy = (posture, capabilitiesByBackend = {}) => ({
- provider: (provider) => supportsPublicReviewPosture(provider, posture),
- model: (model, provider) => {
- if (!supportsPublicReviewPosture(provider, posture)) return false;
- if (posture !== PUBLIC_REVIEW_NO_TOOL_POSTURE || !localBackendForProvider(provider)) return true;
- return isToolFreeLocalModelForProvider(
- model,
- provider,
- capabilitiesByBackend,
- () => true,
- );
- },
-});
-
-/**
- * Retain an existing non-runnable pin so a saved job can still be edited and
- * cleared, while limiting new agent-job selections to runnable providers.
- */
-export const filterRunnableProviders = (providers, selectedProviderIds = []) => {
- const preservedIds = new Set(
- (Array.isArray(selectedProviderIds) ? selectedProviderIds : [selectedProviderIds]).filter(Boolean)
- );
- return (Array.isArray(providers) ? providers : []).filter(provider =>
- AGENT_HARNESS_PROVIDER_TYPES.includes(provider?.type) || preservedIds.has(provider?.id)
- );
-};
-
-/**
- * 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));
-
-/**
- * Server-side hardware metadata is advisory for unknown probe results and
- * definitive only when `state` is `unavailable`. Keep this helper fail-open so
- * older servers and custom providers remain selectable.
- */
-export const isProviderHardwareCompatible = (provider) =>
- isHardwareCompatible(provider?.hardwareCompatibility);
-
-/**
- * The providers a picker may offer: enabled, runnable on this hardware, and
- * allowed by the caller's policy — plus the currently-selected id whatever its
- * state, so a saved pin still renders instead of silently blanking. This is
- * the single rule `ProviderModelSelector` renders from; a caller that lists
- * "eligible" providers beside such a picker must derive the list from here so
- * the note and the dropdown cannot disagree.
- */
-export const selectableProviders = (providers, { selectedId = '', allowed = null } = {}) =>
- (Array.isArray(providers) ? providers : []).filter((provider) => (
- provider?.id === selectedId
- || (provider?.enabled !== false && isProviderHardwareCompatible(provider) && (!allowed || allowed(provider)))
- ));
-
-export const isProviderModelHardwareCompatible = (provider, model) =>
- isProviderHardwareCompatible(provider)
- && isHardwareCompatible(provider?.modelHardwareCompatibility?.[model]);
-
-export const filterHardwareCompatibleProviderModels = (models, provider) =>
- (models || []).filter((model) => {
- const modelId = typeof model === 'string' ? model : model?.id;
- return isProviderModelHardwareCompatible(provider, modelId);
- });
-
-/**
- * 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']);
-
-const codexEffortLevelsForModel = (model) => CODEX_ULTRA_MODELS.has(String(model || '').trim().toLowerCase())
- ? CODEX_ULTRA_EFFORT_LEVELS
- : CODEX_EFFORT_LEVELS;
-
-/**
- * True when an OpenCode process provider runs against one of the local
- * OpenAI-compatible backends (Ollama / LM Studio / MTPLX / llama.cpp / vLLM) or
- * a hosted gateway (OrcaRouter / OpenRouter)
- * rather than a vendor cloud model. MIRROR of `isOpencodeProvider(p) &&
- * getOpencodeLocalProviderNamespace(p)` in server/lib/providerModels.js, which
- * is exactly what gates the effort ladder there — so a backend marker missing
- * here hides the effort picker for a provider the server would happily forward
- * `reasoningEffort` for (#4765).
- */
-export const isOpencodeLocalProvider = (provider) =>
- (['opencode', 'opencode-tui'].includes(String(provider?.id || '').toLowerCase())
- || commandBasename(provider?.command) === 'opencode')
- && (localRuntimeNamespace(provider) !== null || isGatewayBackedProvider(provider));
-
-/**
- * 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
- * only rewrites Antigravity (base models instead of one row per effort tier);
- * every other provider's list passes through untouched. The single place the
- * normalization lives, so `useProviderModels` and any caller that reads
- * `provider.models` directly agree.
- * @param {{id?:string, command?:string}|null|undefined} provider
- * @param {unknown[]} models
- * @returns {unknown[]}
- */
-export const selectableModelsForProvider = (provider, models) =>
- isAntigravityProvider(provider) ? antigravityBaseModels(models) : (models || []);
-
-/**
- * Keeps a stored-but-no-longer-listed Antigravity id visible as its own option.
- *
- * A record saved before Antigravity split model from effort still holds
- * `gemini-3.6-flash-high`, which matches no base-model option and would render
- * the select BLANK (reading as "no model"). The server splits such an id back
- * into base + `--effort`, so the pin still runs — it just has to stay selectable.
- * Same posture as `EffortSelect`'s out-of-ladder option.
- *
- * Deliberately narrow: only an Antigravity id carrying an effort SUFFIX
- * qualifies. A bare "not in the list" test would also re-surface the
- * configured-default sentinel (the shipped agy `defaultModel`, which
- * `filterSelectableModels` exists to hide) and any typo'd/stale pin.
- *
- * CLIENT-ONLY (no server mirror) — this is a rendering concern.
- * @param {{id?:string, command?:string}|null|undefined} provider
- * @param {unknown[]} models - the already-filtered option list
- * @param {string|null|undefined} selectedModel
- * @returns {unknown[]}
- */
-export const withStaleAntigravityPin = (provider, models, selectedModel) => {
- const list = models || [];
- const stale = isAntigravityProvider(provider)
- && !!splitAntigravityModel(selectedModel).effort
- && !list.includes(selectedModel);
- return stale ? [...list, selectedModel] : list;
-};
-
-/**
- * The model ids in a signed-in ChatGPT account's catalog, or `null` when the
- * catalog is not a SUCCESSFUL read.
- *
- * The server ships `{ models, fetchedAt, error }` on a Codex-subscription
- * provider (`codexModelCatalog`), and all three states are distinct:
- * `models: null` = never fetched, a set `error` = the last read failed (the
- * list, if any, is only last-known-good), and `[]` = this account genuinely
- * exposes no models. Only the last two of those are answers about the account,
- * so a never-fetched or failed read collapses to `null` here and the caller
- * keeps its shipped list — an offline or signed-out user must never be handed
- * an empty dropdown.
- *
- * CLIENT-ONLY (no server mirror).
- * @param {{codexModelCatalog?:{models?:unknown, error?:unknown}}|null|undefined} provider
- * @returns {string[]|null}
- */
-export const codexCatalogModelIds = (provider) => {
- if (!isCodexSubscriptionProvider(provider)) return null;
- const catalog = provider?.codexModelCatalog;
- if (!catalog || catalog.error || !Array.isArray(catalog.models)) return null;
- return catalog.models
- .map((entry) => (typeof entry === 'string' ? entry : entry?.id))
- .filter((id) => typeof id === 'string' && id !== '');
-};
-
-/**
- * The RAW model list a picker should read for a provider, before any
- * sentinel/effort/hardware filtering: the signed-in ChatGPT account's own
- * catalog when one has been fetched, otherwise the provider's configured
- * `models` — falling back to its `defaultModel` when that list is empty (a
- * cloud/manual provider configured with only a default; `[]` is truthy, so a
- * bare `||` would leave such a picker empty).
- *
- * This is the single place the account catalog enters a picker, so a caller
- * that reads `provider.models` directly is the one bug this exists to prevent
- * (#6306). A successfully-read EMPTY catalog is returned as `[]` and must not
- * fall through to `defaultModel`: the account really has no models, and
- * offering its default would put back the un-runnable option.
- *
- * CLIENT-ONLY (no server mirror).
- * @param {{models?:unknown[], defaultModel?:string}|null|undefined} provider
- * @returns {unknown[]}
- */
-export const providerModelList = (provider) => {
- const catalog = codexCatalogModelIds(provider);
- if (catalog) return catalog;
- return provider?.models?.length ? provider.models : [provider?.defaultModel];
-};
-
-/** Where a picker's option list came from. */
-export const MODEL_SOURCE = Object.freeze({
- /** The provider's shipped/configured `models` array. */
- shipped: 'shipped',
- /** The signed-in ChatGPT account's own catalog. */
- account: 'account',
- /** The account was read successfully and exposes no models. */
- accountEmpty: 'account-empty',
-});
-
-/**
- * The option list for a picker, plus WHERE it came from.
- *
- * For a Codex-subscription provider whose account catalog has been fetched, the
- * options are that account's real models — so a tier the plan cannot run is not
- * selectable and cannot be queued against a worktree that would only fail later.
- * Every other state (never fetched, failed read, non-Codex provider) falls back
- * to the shipped list unchanged.
- *
- * ADDITIVE: a stored `selectedModel` the catalog no longer lists is retained as
- * its own option and reported via `unlistedSelection`, so an existing task
- * template renders what it actually holds instead of silently changing model.
- *
- * CLIENT-ONLY (no server mirror).
- * @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider
- * @param {string|null|undefined} selectedModel
- * @returns {{models: unknown[], source: string, unlistedSelection: boolean}}
- */
-export const resolveProviderModelOptions = (provider, selectedModel) => {
- const shipped = withStaleAntigravityPin(
- provider,
- filterSelectableModels(selectableModelsForProvider(provider, provider?.models)),
- selectedModel,
- );
- const catalog = codexCatalogModelIds(provider);
- if (!catalog) return { models: shipped, source: MODEL_SOURCE.shipped, unlistedSelection: false };
- const models = filterSelectableModels(catalog);
- const unlistedSelection = !!selectedModel
- && !isConfiguredDefaultModel(selectedModel)
- && !models.includes(selectedModel);
- return {
- models: unlistedSelection ? [...models, selectedModel] : models,
- source: models.length > 0 ? MODEL_SOURCE.account : MODEL_SOURCE.accountEmpty,
- unlistedSelection,
- };
-};
-
-/**
- * The option list for a picker that renders an effort control but reads
- * `provider.models` directly (no `useProviderModels`): base models, sentinels
- * stripped, plus any legacy suffixed pin so the stored value stays visible.
- * The hook's own list is assembled from the same two primitives, so the two
- * paths can't drift. Codex-subscription providers resolve through
- * `resolveProviderModelOptions`, so every picker offers the same account-aware
- * answer without each one reimplementing the fallback.
- *
- * CLIENT-ONLY (no server mirror).
- * @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider
- * @param {string|null|undefined} selectedModel
- * @returns {unknown[]}
- */
-export const effortAwareModelOptions = (provider, selectedModel) =>
- resolveProviderModelOptions(provider, selectedModel).models;
-
-/**
- * The model a run will ACTUALLY use: the explicit pin, else the provider's own
- * default. A blank model isn't a no-op — the resolver falls through to
- * `defaultModel` — so anything keyed on the model (Antigravity's effort tiers,
- * the local tool-use warning) has to evaluate this, not the raw selection.
- *
- * CLIENT-ONLY (no server mirror).
- * @param {{defaultModel?:string}|null|undefined} provider
- * @param {string|null|undefined} model
- * @returns {string}
- */
-export const effectiveModelFor = (provider, model) => model || provider?.defaultModel || '';
-
-/**
- * Seeds a picker's two controls from a record that may predate the split.
- * `{ model: 'gemini-3.6-flash-high', effort: '' }` reads back as
- * `{ model: 'gemini-3.6-flash', effort: 'high' }`; a stored `effort` always
- * wins over the suffix, and a non-Antigravity provider is left alone so a model
- * that merely ends in `-high` isn't truncated.
- *
- * CLIENT-ONLY (no server mirror) — the server reads the suffixed id directly.
- * @param {{id?:string, command?:string}|null|undefined} provider
- * @param {string|null|undefined} model
- * @param {string|null|undefined} effort
- * @returns {{model: string, effort: string}}
- */
-export const seedModelEffort = (provider, model, effort) => {
- if (!isAntigravityProvider(provider)) return { model: model || '', effort: effort || '' };
- const { base, effort: bakedEffort } = splitAntigravityModel(model || '');
- return { model: base || '', effort: effort || bakedEffort || '' };
-};
-
-/**
- * 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.
- *
- * `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.
- * @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 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;
- return null;
-};
-
-/**
- * The effort a picker should keep after its MODEL changed under a fixed provider:
- * the current one, or `''` when the new model has no effort control at all.
- *
- * Antigravity's tiers are per-model, and a model with NO tiers hides the select
- * entirely (`effortLevelsForProvider` → null — `claude-sonnet-4-6` in the shipped
- * agy catalog has no `-low|-medium|-high` siblings). Without this the previous
- * effort stays in state with no UI left to clear it, and every submit path still
- * sends it: an invocation agy rejects (`--model claude-sonnet-4-6 --effort high`)
- * and, on the records that persist it, a stored level the run never used.
- *
- * A merely NARROWED ladder is deliberately left alone — `EffortSelect` renders an
- * explicit `medium (runs as low)` option there, so the clamp stays visible rather
- * than silently discarding the user's choice.
- *
- * CLIENT-ONLY (no server mirror) — the server clamps what it is sent; this keeps
- * the UI from sending something it stopped showing.
- * @param {{id?:string, command?:string, models?:unknown[], defaultModel?:string}|null|undefined} provider
- * @param {string|null|undefined} model - the NEWLY selected model
- * @param {string|null|undefined} effort - the currently selected effort
- * @returns {string}
- */
-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.
- *
- * 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
- * (whose ladder stops at `high`) still runs, at `high`. Without this the select
- * holds a value matching no option, renders blank — reading as "Default effort"
- * — while the run silently uses the clamped level.
- * @param {string|null|undefined} effort
- * @param {{id?:string, command?:string, models?:unknown[]}|null|undefined} provider
- * @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]];
-};
-
-/**
- * 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);
-
-/**
- * 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.
- * @param {{type?:string, command?:string}|null|undefined} provider
- * @returns {boolean}
- */
-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
- * native tool calls — a local model that can't (e.g. Gemma) narrates a
- * done-message instead of acting, silently wedging the task. This decides the
- * per-option marker + the "pick a tool-capable model" warning in agent pickers.
- *
- * Tool-use is surfaced as an ANNOTATION + warning, never as a filter: the
- * heuristic is a positive allowlist, so a non-match is "not a recognized
- * tool-caller", not a proven negative, and hiding those options would make a
- * newer tool-capable family unselectable (see {@link withToolUseOptionLabel}).
- *
- * Returns `null` for cloud / API providers: their model ids don't encode their
- * family, so the name heuristic would mislabel them. LOCAL backends return
- * `{ toolCapable }` — where "local" is BOTH a direct Ollama / LM Studio backend
- * ({@link localBackendForProvider}) AND an Ollama-BACKED CLI/TUI wrapper
- * ({@link isOllamaBackedProvider}): a renamed `claude-ollama-tui` / OpenCode
- * wrapper keeps `ollamaBacked: true` but may lose the "ollama"
- * name/endpoint/id that `localBackendForProvider` matches on, and that wrapper
- * is exactly the incident's provider class — so it must still be flagged, not
- * silently skipped.
- *
- * `toolUseIdsByProvider` is the AUTHORITATIVE map the server reports from each
- * backend's own capability metadata (Ollama `/api/show` `tools`) keyed by the
- * PROVIDER ID the server says serves each model — see `useToolUseModelIds`. It
- * is UNIONED with, never substituted for, {@link isToolUseModel}: the regex is a
- * positive allowlist that goes stale every time a new function-calling family
- * ships (`phi4-mini`, newer Gemma builds got "⚠ no known tool use" while the
- * Local LLMs tab's "Agents" badge, reading these same capabilities, said
- * otherwise), while the map can't speak for a provider the server never
- * enumerated. Pass `null` (the default) when it hasn't loaded — that degrades to
- * regex-only, the behavior this picker has always had.
- *
- * Keyed by the ENUMERATED PROVIDER, not flattened and not keyed by backend,
- * because a bare id is not a capability: a CUSTOM provider (or an Ollama-backed
- * CLI wrapper) pointed at a *different* Ollama/LM Studio host resolves to the
- * same backend, but the server never enumerated that host — so a local model's
- * id must not vouch for a remote model that merely shares its name. Such a
- * provider stays regex-only, which is the conservative direction: a false
- * "tool-capable" sends an agent to a model that narrates instead of acting.
- * @param {string} id
- * @param {object} [provider]
- * @param {Record<string, Set<string>>|null} [toolUseIdsByProvider]
- * @returns {{toolCapable:boolean}|null}
- */
-export const localToolUseHint = (id, provider, toolUseIdsByProvider = null) =>
- (localBackendForProvider(provider) || isOllamaBackedProvider(provider) || provider?.lmstudioBacked === true || provider?.mtplxBacked === true || provider?.llamaBacked === true || provider?.vllmBacked === true || provider?.sglangBacked === true)
- && typeof id === 'string' && id.length > 0
- ? { toolCapable: toolUseIdsByProvider?.[provider?.id]?.has(id) === true || isToolUseModel(id) }
- : null;
-
-/**
- * Suffix a native `<option>` label with a tool-use marker for an agent picker.
- * No-op (returns `label` unchanged) for cloud providers or a blank id, so it's
- * safe to wrap every option. Pairs with {@link localToolUseHint} for the
- * below-the-select warning. Emoji (not lucide icons) because native `<option>`
- * elements can't render markup.
- *
- * The signal is asymmetric because {@link isToolUseModel} is a *positive
- * allowlist* of families with dependable function-calling: a match is a reliable
- * "tool-capable", but a NON-match only means "not a recognized tool-caller" —
- * NOT a proven negative (a newer tool-capable family whose id isn't in the regex
- * yet would fall here). So the negative marker is worded as unverified, not a
- * false-certain "no tool use". Passing `toolUseIdsByProvider` (from
- * `useToolUseModelIds`) shrinks that unverified band to the models the server
- * couldn't speak for; see {@link localToolUseHint} for the union rule.
- * @param {string} id - model id (drives the heuristic)
- * @param {string} label - display label to annotate (often === id)
- * @param {object} [provider] - the selected provider object
- * @param {Record<string, Set<string>>|null} [toolUseIdsByProvider] - authoritative
- * server-reported tool-capable ids, keyed by provider id; `null` = regex-only
- * @returns {string}
- */
-export const withToolUseOptionLabel = (id, label, provider, toolUseIdsByProvider = null) => {
- const hint = localToolUseHint(id, provider, toolUseIdsByProvider);
- if (!hint) return label;
- return `${label}${hint.toolCapable ? ' · 🔧 tool use' : ' · ⚠ no known tool use'}`;
-};
-
-/**
- * Selectable models for a generation/chat picker: drops internal sentinels AND
- * embedding-only models. Use anywhere the user picks a model that will run a
- * prompt (provider editor model lists, fallback model, manuscript review).
- * @param {string[]} models
- * @returns {string[]}
- */
-export const filterGenerationModels = (models) =>
- filterSelectableModels(models).filter((m) => !isEmbeddingModel(m));
-
-/**
- * Per-model filter for a VISION picker: restrict LOCAL backends (Ollama /
- * LM Studio) to vision-capable models by id, but leave cloud/API providers'
- * lists untouched — `isVisionModel` is a local-name heuristic and would wrongly
- * hide multimodal cloud models whose ids don't encode vision (`gpt-4o`,
- * `claude-*`). Pass as `useProviderModels({ modelFilter: visionLocalModelFilter })`.
- *
- * `visionIdsByProvider` is the AUTHORITATIVE map the server reports from each
- * backend's own capability metadata (Ollama `/api/show`, LM Studio
- * `type: 'vlm'`), keyed by the PROVIDER ID the server says serves each model —
- * see `useVisionModelIds`. It is unioned with, not substituted for, the id
- * regex: the regex alone goes stale every time a new multimodal family ships
- * (it knew `gemma-3` but not `gemma4`, so a user with only `gemma4:e4b` +
- * `qwen3.6:35b` installed saw an EMPTY vision picker), while the map alone
- * can't speak for a provider the server never enumerated. Pass `null` (the
- * default) when it hasn't loaded — that degrades to regex-only.
- *
- * Keyed by the ENUMERATED PROVIDER, not flattened and not keyed by backend,
- * because a bare id is not a capability:
- * - The same id can be a VLM on one backend and text-only on another, and the
- * server also reports `backend: 'cli'` rows asserting vision for EVERY model
- * of a claude/codex CLI (that CLI reads an image file whatever model it
- * fronts). Flattening let an ollama-backed Claude CLI's text-only ids — which
- * collide with the real `ollama` provider's list — pass this filter.
- * - Keying by backend alone still over-shares: a CUSTOM provider pointed at a
- * *different* Ollama/LM Studio host (endpoint `:11434` on another machine)
- * resolves to the same backend, but the server never enumerated that host,
- * so a local VLM's id would vouch for a remote model that merely shares it.
- * An unenumerated local provider therefore stays on the regex-only path. This
- * matters because sceneEvaluator honors a pin's model verbatim — a wrong yes
- * here sends frames to a model that cannot see them.
- *
- * @param {string} id
- * @param {{id?:string,endpoint?:string,name?:string}} [provider]
- * @param {Record<string, Set<string>>|null} [visionIdsByProvider]
- * @returns {boolean}
- */
-export const visionLocalModelFilter = (id, provider, visionIdsByProvider = null) => {
- // Cloud/API providers are left intact — the regex is a local-name heuristic
- // and would wrongly hide multimodal cloud ids like `gpt-4o`.
- if (!localBackendForProvider(provider)) return true;
- return visionIdsByProvider?.[provider?.id]?.has(id) === true || isVisionModel(id);
-};
-
-/**
- * Classify a provider as a local-LLM backend by its id/endpoint/name, so callers
- * can fold in live-installed models (Ollama/LM Studio) that aren't in the
- * provider's stored `models` list. Ollama's native + OpenAI-compat ports are
- * 11434; LM Studio defaults to 1234. The stable provider ids (`ollama` /
- * `lmstudio`) are checked too — AI Assignments' curated provider payload
- * omits `endpoint`, and a renamed display name would otherwise miss detection.
- *
- * Client mirror of `localBackendForProvider` in
- * server/lib/localProviderRuntime.js — keep in lockstep. The SERVER copy is
- * authoritative and stricter: it parses the endpoint as a URL and requires a
- * loopback/bind-all host, so a peer machine's daemon on the same port is not
- * claimed as local. This one only labels UI, so it stays a cheap regex; if it
- * ever gates an action, take the server's rules with it.
- *
- * The pr-reviewer stage pickers (`PipelineStageConfig.jsx`) are downstream of
- * this, the sandboxed actions stage included — but they only choose which model
- * list to SHOW. The pin a stage saves is re-validated at spawn time by
- * `modelPinIsOffered` (server/lib/localProviderRuntime.js), so a
- * misclassification here degrades to a confusing dropdown, never to a model the
- * provider was not allowed to run.
- *
- * @param {{id?:string,endpoint?:string,name?:string}} provider
- * @returns {'ollama'|'lmstudio'|null}
- */
-export const localBackendForProvider = (provider) => {
- if (!provider) return null;
- const id = String(provider.id || '').toLowerCase();
- const endpoint = String(provider.endpoint || '');
- const name = String(provider.name || '').toLowerCase();
- if (id === 'ollama' || /:11434\b/.test(endpoint) || name.includes('ollama')) return 'ollama';
- if (
- id === 'lmstudio' ||
- /:1234\b/.test(endpoint) ||
- name.includes('lm studio') ||
- name.includes('lmstudio') ||
- /lm[\s-]?studio/i.test(name)
- ) return 'lmstudio';
- return null;
-};
-
-// The whole loopback block (`127.0.0.0/8`), not just `127.0.0.1` — a daemon on a
-// loopback alias (`127.0.0.2`) is as local as one on `.1`, and the server's
-// `isLocalInstanceHost` already accepts the full block. While they disagreed, a
-// provider on `http://127.0.0.2:11434` was badged NEEDS SETUP for an API key a
-// loopback endpoint never needs.
-const LOCAL_ENDPOINT_RE = /^(https?:\/\/)?(localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|0\.0\.0\.0|\[?::1\]?|\[?::\]?)(:|\/|$)/i;
-export const isLocalEndpoint = (endpoint) =>
- typeof endpoint === 'string' && LOCAL_ENDPOINT_RE.test(endpoint.trim());
-
-// Hosts inside the trust boundary, where an unauthenticated OpenAI-compatible
-// server is a normal setup rather than a misconfiguration: RFC1918 LAN ranges,
-// link-local, and the Tailscale CGNAT range 100.64.0.0/10 (PortOS is a
-// tailnet-first product — an API provider pointed at another machine's Ollama
-// is a first-class configuration, not an edge case).
-const PRIVATE_IP_RE = /^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/;
-
/**
- * IPv6 counterpart to {@link PRIVATE_IP_RE}: unique-local (`fc00::/7`) and
- * link-local (`fe80::/10`). Tailscale hands out a ULA address alongside the
- * CGNAT v4 one, so without this a tailnet peer reached over IPv6 read as a
- * public host and its keyless provider was blocked on a missing API key.
- *
- * Gated on the host being an IPv6 literal (it contains a `:`) and compared
- * NUMERICALLY on the leading hextet — a bare `/^f[cd]/` prefix test would also
- * claim hostnames like `fdrive.example.com`, and `fd::1` expands to a leading
- * hextet of `0x00fd`, which is not in `fc00::/7` at all.
- */
-/**
- * Gate for {@link PRIVATE_IP_RE}: is this host an IPv4 literal at all?
- *
- * The range test above matches a PREFIX, which on its own also claims DNS names
- * that merely start like one — `10.evil.example` — and would report a keyless
- * PUBLIC endpoint as needing no key. Hosts arriving there have already been
- * through `URL`, which canonicalizes any IPv4 spelling to a dotted quad.
- * Mirror of the server helper in server/lib/providerPrerequisites.js.
- */
-const isIpv4Literal = (host) => /^\d{1,3}(?:\.\d{1,3}){3}$/.test(host);
-
-const isPrivateIpv6 = (host) => {
- if (!host.includes(':')) return false;
- const first = host.split(':')[0];
- if (!/^[0-9a-f]{1,4}$/.test(first)) return false; // '' for `::1` — loopback, already matched above
- const n = parseInt(first, 16);
- return (n >= 0xfc00 && n <= 0xfdff) || (n >= 0xfe80 && n <= 0xfebf);
-};
-
-/**
- * Is this endpoint inside the private network — loopback, a LAN/tailnet address,
- * a `.local`/`.ts.net`/`.internal` name, or a bare single-label host?
- *
- * Used to decide whether a missing API key is actually a missing prerequisite.
- * The server only attaches an `Authorization` header when a key is stored, so a
- * keyless call to a private OpenAI-compatible server (LM Studio on the desk
- * machine, Ollama on a tailnet peer) works exactly as configured — reporting it
- * as "needs setup" would be a false alarm on a supported deployment. A public
- * endpoint with no key stays flagged: that one really is misconfigured.
- *
- * A host that cannot be parsed reads as NOT private, keeping the stricter of
- * the two answers for input we don't understand.
- */
-export const isPrivateNetworkEndpoint = (endpoint) => {
- if (isLocalEndpoint(endpoint)) return true;
- if (typeof endpoint !== 'string' || !endpoint.trim()) return false;
- const trimmed = endpoint.trim();
- // A scheme-less endpoint ("192.168.1.5:1234/v1") is still a host — give the
- // parser one so it doesn't read the leading segment as a scheme.
- const candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
- if (!URL.canParse(candidate)) return false;
- const host = new URL(candidate).hostname.toLowerCase().replace(/^\[|\]$/g, '');
- if (isIpv4Literal(host) && PRIVATE_IP_RE.test(host)) return true;
- if (isPrivateIpv6(host)) return true;
- if (/\.(local|internal|lan|home\.arpa|ts\.net)$/.test(host)) return true;
- // A single-label host resolves only inside the local network (`http://nas:11434`).
- return !host.includes('.') && !host.includes(':');
-};
-
-/**
- * Does this provider talk to a daemon on THIS machine?
- *
- * Client mirror of `isLocalInstanceEndpoint` in
- * server/lib/localProviderRuntime.js, and the guard for anything that explains
- * a provider by inspecting the machine PortOS runs on — "is `lms` installed
- * here?", "start it from Models → LLMs". A provider named for LM Studio
- * but pointed at another box on the tailnet matches
- * {@link localBackendForProvider} by NAME, so without this it collected this
- * machine's install state and offered to start a server it does not own.
- *
- * A blank endpoint reads as local, unlike the server's copy: the record simply
- * hasn't named one, and every default it can fall back to is a loopback URL.
- *
- * @param {{endpoint?:string}} provider
- * @returns {boolean}
- */
-export const isLocalInstanceProvider = (provider) => {
- const endpoint = provider?.endpoint;
- if (typeof endpoint !== 'string' || endpoint.trim() === '') return true;
- return isLocalEndpoint(endpoint);
-};
-
-/**
- * Does this provider run on another machine inside the private network?
- *
- * This is presentation identity, not a trust escalation: prerequisite and key
- * rules still come from {@link isPrivateNetworkEndpoint}. Public hosted APIs
- * stay ordinary remote providers; loopback daemons stay local.
- */
-export const isFleetProvider = (provider) =>
- !isLocalInstanceProvider(provider) && isPrivateNetworkEndpoint(provider?.endpoint);
-
-/**
- * Has this fleet host already been configured as a provider on this instance?
- *
- * @param {{endpoint?: string, peerHost?: string, peerAddress?: string}|null|undefined} host
- * @param {Array<object>} providers
- * @returns {boolean}
- */
-export const isFleetHostConfigured = (host, providers = []) => {
- if (!host || !Array.isArray(providers)) return false;
- const hostEndpoint = typeof host.endpoint === 'string' ? host.endpoint.toLowerCase().replace(/\/+$/, '') : '';
- const hostHostname = (host.peerHost || (host.endpoint && URL.canParse(host.endpoint) ? new URL(host.endpoint).hostname : ''))?.toLowerCase();
- const hostAddress = (host.peerAddress || '')?.toLowerCase();
-
- return providers.some((p) => {
- // 1. Direct endpoint string equality
- const pEndpoint = typeof p?.endpoint === 'string' ? p.endpoint.toLowerCase().replace(/\/+$/, '') : '';
- if (hostEndpoint && pEndpoint === hostEndpoint) return true;
-
- // 2. Parsed hostname/IP match
- if (pEndpoint && URL.canParse(pEndpoint)) {
- const pUrl = new URL(pEndpoint);
- const pHost = pUrl.hostname.toLowerCase();
- if ((hostHostname && pHost === hostHostname) || (hostAddress && pHost === hostAddress)) {
- return true;
- }
- }
-
- // 3. OpenCode TUI provider configuration check
- if (p?.envVars?.OPENCODE_CONFIG_CONTENT) {
- try {
- const config = typeof p.envVars.OPENCODE_CONFIG_CONTENT === 'string'
- ? JSON.parse(p.envVars.OPENCODE_CONFIG_CONTENT)
- : p.envVars.OPENCODE_CONFIG_CONTENT;
- const vllmBaseUrl = config?.provider?.vllm?.options?.baseURL;
- if (typeof vllmBaseUrl === 'string') {
- const normBase = vllmBaseUrl.toLowerCase().replace(/\/+$/, '');
- if (hostEndpoint && normBase === hostEndpoint) return true;
- if (URL.canParse(normBase)) {
- const bHost = new URL(normBase).hostname.toLowerCase();
- if ((hostHostname && bHost === hostHostname) || (hostAddress && bHost === hostAddress)) {
- return true;
- }
- }
- }
- } catch {
- // ignore parse error
- }
- }
-
- return false;
- });
-};
-
-export const isLikelyLargeContextProvider = (provider) => {
- if (isProcessProvider(provider)) return true;
- return isApiProvider(provider) && !isLocalEndpoint(provider.endpoint);
-};
-
-/**
- * Where a resolved context window came from — three states, because that is
- * what the UI actually distinguishes:
- *
- * - `REPORTED` — a real window for this model/provider (catalog, known-model
- * table, vendor default, or Ollama's num_ctx). Which of those it was does not
- * change what the card says, so they collapse into one state rather than
- * growing an enum member per rung.
- * - `OVERRIDE` — a number the user typed; worth labelling as theirs.
- * - `ASSUMED` — nobody reported one, so the ladder GUESSED. This is the state
- * that has to be visible: a card printing "128K ctx" for a model whose real
- * window is 1M reads as a measured fact with nothing to say otherwise.
- */
-export const CONTEXT_WINDOW_SOURCE = Object.freeze({
- OVERRIDE: 'override',
- REPORTED: 'reported',
- 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.
- *
- * `{ tokens: null, source: null }` means nothing is known (an unrecognized model
- * on a local backend); the budgeter applies its own conservative floor there.
- *
- * @param {object|null|undefined} provider
- * @param {string|null|undefined} model
- * @returns {{tokens: number|null, source: string|null}}
- */
-export const resolveModelContextWindow = (provider, model) => {
- const explicit = Number(provider?.contextWindow);
- if (Number.isFinite(explicit) && explicit > 0) {
- return { tokens: explicit, source: CONTEXT_WINDOW_SOURCE.OVERRIDE };
- }
- const catalog = catalogModelContextWindow(provider, model);
- if (catalog) return { tokens: catalog, source: CONTEXT_WINDOW_SOURCE.REPORTED };
- const known = knownModelContextWindow(model);
- if (known) return { tokens: known, source: CONTEXT_WINDOW_SOURCE.REPORTED };
- const providerKnown = knownProviderContextWindow(provider);
- if (providerKnown) return { tokens: providerKnown, source: CONTEXT_WINDOW_SOURCE.REPORTED };
- const numCtx = Number(provider?.numCtx);
- if (Number.isFinite(numCtx) && numCtx > 0) {
- return { tokens: numCtx, source: CONTEXT_WINDOW_SOURCE.REPORTED };
- }
- return isLikelyLargeContextProvider(provider)
- ? { tokens: DEFAULT_LARGE_CONTEXT_WINDOW, source: CONTEXT_WINDOW_SOURCE.ASSUMED }
- : { tokens: null, source: null };
-};
-
-export const effectiveModelContextWindow = (provider, model) =>
- resolveModelContextWindow(provider, model).tokens;
-
-/**
- * Union of one or more model-id lists, de-duplicated, order-preserving, falsy
- * values dropped. Used to merge a provider's stored `models` with the live
- * installed list for local backends.
- * @param {...(string[]|undefined)} lists
- * @returns {string[]}
- */
-export const mergeModelLists = (...lists) => {
- const seen = new Set();
- const out = [];
- for (const list of lists) {
- for (const m of list || []) {
- if (m && !seen.has(m)) { seen.add(m); out.push(m); }
- }
- }
- return out;
-};
-
-/**
- * Merge a partial-update payload onto an existing provider record in place, so
- * repointing a provider at a new backend (e.g. a fleet host) doesn't clobber
- * fields the payload didn't set out to change. A raw PATCH replaces whichever
- * top-level keys it names wholesale — without this, pointing an OpenCode TUI
- * provider at a new endpoint would silently drop its other env vars and reset
- * its served-model history to just the one new model id.
- *
- * @param {object|null|undefined} target - the existing provider being updated
- * @param {object} payload - field values about to be written; mutated in place
- * @returns {object} payload
- */
-export const mergeProviderUpdate = (target, payload) => {
- if (!target) return payload;
- if (payload.envVars) payload.envVars = { ...target.envVars, ...payload.envVars };
- if (payload.secretEnvVars) {
- payload.secretEnvVars = Array.from(new Set([...(target.secretEnvVars || []), ...payload.secretEnvVars]));
- }
- if (payload.models) payload.models = mergeModelLists(target.models, payload.models);
- return payload;
-};
-
-/**
- * Display label for a model `<option>`: the id plus a "(32K ctx)" parenthetical
- * when the model's context window is known. The option's `value` stays the raw
- * id — only the label carries the annotation.
- *
- * Resolution is deliberately narrower than {@link resolveModelContextWindow}:
- * only rungs that describe THIS model — the live local probe (`ctxById` from
- * `useLocalModels`), the window `provider`'s catalog reported for it, then the
- * known-model table. The provider-level and assumed rungs are excluded on
- * purpose: they would stamp the same guessed number onto every option in the
- * list, which says nothing and reads as fact.
- *
- * Take `provider` rather than a pre-merged map so every picker gets catalog
- * windows for free — merging at the call site is what left the fallback-model
- * and manuscript-override selects labelling a 1M model as if it were unknown.
- *
- * @param {string} id
- * @param {Record<string, number>} [ctxById] — live windows for local models
- * @param {object} [provider] — the provider whose catalog lists this model
- * @returns {string}
- */
-export const modelOptionLabel = (id, ctxById, provider) => {
- const ctx = ctxById?.[id] || catalogModelContextWindow(provider, id) || knownModelContextWindow(id);
- const label = formatContextLength(ctx);
- return label ? `${id} (${label})` : id;
-};
-
-/**
- * Check if a provider is a TUI-backed agent provider. Mirror of
- * `isTuiProvider` in server/services/agentCliSpawning.js.
- */
-export const isTuiProvider = (provider) => provider?.type === PROVIDER_TYPES.TUI;
-
-/**
- * Can a human launch this provider at a shell prompt?
- *
- * TUI is the only type that has an interactive form — a `cli` provider's args
- * are headless (`--print`), and an `api` provider has no local binary at all.
- * `tuiCommandLine` is the server's own resolution of what the launch will run
- * (`server/lib/tuiShellLaunch.js`, published by `GET /api/providers`), so a
- * provider it could not resolve a command for is not offered, and an older
- * server that omits the field simply offers nothing.
- *
- * Shared so the AI Providers card's "Launch in Shell" button and the Shell
- * page's launch menu can't disagree about which providers are launchable.
- */
-export const isLaunchableTuiProvider = (provider) => isTuiProvider(provider) && Boolean(provider?.tuiCommandLine);
-
-/**
- * Check if a provider is a one-shot CLI agent provider.
- */
-export const isCliProvider = (provider) => provider?.type === PROVIDER_TYPES.CLI;
-
-/**
- * Check if a provider is an HTTP-API provider (e.g. OpenAI, Anthropic, LM Studio),
- * as opposed to a process-backed CLI/TUI agent. Use this anywhere you'd write
- * `provider.type === PROVIDER_TYPES.API` against a saved provider.
- */
-export const isApiProvider = (provider) => provider?.type === PROVIDER_TYPES.API;
-
-/**
- * Stable, module-scoped filter for `useProviderModels({ filter })` and other
- * call sites that need "enabled HTTP-API providers only". Hoisted so the
- * identity is the same across renders (callers may pass it as a dependency).
- */
-export const enabledApiProviderFilter = (provider) => Boolean(provider?.enabled) && isApiProvider(provider);
-
-/**
- * Check if a provider is process-backed (cli or tui), as opposed to an
- * HTTP-API provider. Use this for "shows a Command + args" config predicates.
- */
-export const isProcessProvider = (provider) => isCliProvider(provider) || isTuiProvider(provider);
-
-/**
- * Base name of a spawn command, normalized the way the CoS Agent Runner's
- * allowlist check does before its membership test: strip any directory
- * prefix, then a trailing Windows `.exe`. Mirror of `isAllowedCommand`'s
- * normalization in `server/cos-runner/allowedCommands.js`, pinned by
- * `server/cos-runner/allowedCommands.parity.test.js`.
- *
- * The server uses `path.basename`, which is platform-specific — on a POSIX
- * host a backslash is NOT a separator. This mirror always treats both `/` and
- * `\` as separators, so a Windows-style path typed into the editor on a POSIX
- * install reads as "allowed" when the server would spawn-time reject it. That
- * direction is deliberate: this drives an informational warning, and a false
- * *warning* about a path the user's own platform handles fine is worse than a
- * missing one for a path shape that platform can't run anyway.
- */
-const runnerCommandBaseName = (command) => {
- const base = String(command).replace(/[/\\]+$/, '').split(/[/\\]/).pop();
- // Only `.exe` — a `.cmd`/`.bat` npm shim is deliberately NOT stripped,
- // matching the server: the spawn path runs with `shell: false` and cannot
- // execute a batch shim, so accepting it would only move the failure later.
- return base.toLowerCase().endsWith('.exe') ? base.slice(0, -4) : base;
-};
-
-/**
- * Would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command?
- *
- * `allowedCommands` is the server-published list (`runnerAllowedCommands` on
- * `GET /api/providers`) — the client never carries its own copy, because the
- * allowlist is the runner's exec boundary and must stay hand-curated
- * server-side rather than derived from user-writable provider config.
- *
- * Returns `null` for "can't tell" — the list hasn't been fetched, or the field
- * is still blank — which is distinct from `false` ("fetched, and this command
- * is definitely off the list"). Only an explicit `false` should render a
- * warning; a failed fetch must not accuse a perfectly good command.
- *
- * The command is matched UNTRIMMED (past the blank guard), because the editor
- * persists it untrimmed too — `'claude '` really would fail the runner's check.
- */
-export const isRunnerAllowedCommand = (command, allowedCommands) => {
- if (!Array.isArray(allowedCommands) || allowedCommands.length === 0) return null;
- if (typeof command !== 'string' || command.trim() === '') return null;
- return allowedCommands.includes(runnerCommandBaseName(command));
-};
-
-/**
- * The key a CLI/TUI provider's runtime is published under in the `runtimes` map
- * from `GET /api/providers/runtimes` — the binary it spawns, basename-normalized
- * so a provider pinned to an absolute path still matches.
- *
- * Deliberately NOT a client-side copy of the runtime table: the server owns
- * which runtimes exist and how they install, and a key with no entry in the
- * fetched map simply renders no install widget. That's the right default for a
- * custom command PortOS has no installer for.
- *
- * API providers have no runtime here — the two fronted by a local app resolve
- * through `localBackendForProvider` (which also matches a renamed provider by
- * its endpoint) and get their install state from the local-LLM status.
- */
-/**
- * Does this provider resolve its binary somewhere PortOS's runtime probe never
- * looked — an explicit path in `command`, or a `PATH` of its own in
- * `envVars`?
- *
- * The runtime row answers one question, "does the bare binary resolve on
- * PortOS's PATH?", and neither of these is that question: the runner spawns
- * such a provider against its own resolution. MIRROR of the same two guards in
- * `providerRuntimeKey` in server/lib/providerPrerequisites.js, which is what
- * keeps the card's badge and the server's routing decision agreeing.
- * @param {{type?:string,command?:string,envVars?:Record<string,string>}} provider
- */
-export const resolvesOutsidePortosPath = (provider) => {
- if (!isProcessProvider(provider)) return false;
- if (/[\\/]/.test(String(provider?.command || '').trim())) return true;
- return Object.keys(provider?.envVars || {}).some((key) => key.toUpperCase() === 'PATH');
-};
-
-export const providerRuntimeKey = (provider) => {
- if (!isProcessProvider(provider)) return null;
- const command = provider?.command;
- if (typeof command !== 'string' || command.trim() === '') return null;
- return runnerCommandBaseName(command.trim());
-};
-
-/**
- * Whether `provider` is served by an Ollama daemon rather than its nominal
- * cloud/CLI backend: the built-in `ollama` API provider itself (id match), an
- * `api`-type provider whose `endpoint` points at Ollama, or the Claude-Ollama
- * CLI/TUI pattern — a `claude` process carrying the `ollamaBacked` marker or an
- * `ANTHROPIC_BASE_URL` pointed at Ollama, which runs the Claude Code harness but
- * generates tokens locally, so its model list is refreshed from Ollama
- * (including the TUI variant, which the server refreshes via the
- * `type==='tui' && ollamaBacked` branch). MIRROR of `isOllamaBackedProvider` in
- * server/lib/aiToolkit/providers.js.
- * @param {{id?:string,endpoint?:string,ollamaBacked?:boolean,envVars?:Record<string,string>}} provider
- */
-export const isOllamaBackedProvider = (provider) => {
- if (provider?.id === 'ollama') return true;
- if (provider?.ollamaBacked === true) return true;
- const base = String(provider?.envVars?.ANTHROPIC_BASE_URL || provider?.endpoint || '');
- return /:11434\b/.test(base) || /ollama/i.test(base);
-};
-
-/**
- * Resolve the capability badges for a selected model without over-sharing a
- * local runtime's answer with another provider. The status endpoint is keyed
- * by backend, but only the canonical `ollama` / `lmstudio` provider records
- * are known to point at this install's daemon; custom or remote providers stay
- * on conservative inference. This mirrors the provider-scoped boundary used
- * by `useToolUseModelIds` and `useVisionModelIds`.
- *
- * `[]` is a valid runtime answer meaning no optional capabilities were
- * reported. `null` means the capability set is unknown, and `source` tells the
- * UI whether that is because the runtime is still loading, the runtime probe
- * failed, the provider gave a harness-level fact, or no authoritative metadata
- * exists.
- *
- * @param {{id?:string,type?:string,command?:string,endpoint?:string,name?:string,ollamaBacked?:boolean}|null|undefined} provider
- * @param {string|null|undefined} model
- * @param {{capabilitiesByBackend?: {ollama?: Record<string, string[]|null>, lmstudio?: Record<string, string[]|null>}, recommendations?: {ollama?: object|null, lmstudio?: object|null}, loading?: boolean}} [options]
- * @returns {{capabilities: string[]|null, source: 'unselected'|'runtime'|'runtime-unknown'|'provider'|'inferred'|'loading'|'unknown', recommendation: object|null}}
- */
-export const modelCapabilityInfo = (provider, model, {
- capabilitiesByBackend = {},
- recommendations = {},
- loading = false,
-} = {}) => {
- const modelId = typeof model === 'string' ? model.trim() : '';
- if (!provider || !modelId) {
- return { capabilities: null, source: 'unselected', recommendation: null };
- }
-
- const backend = localBackendForProvider(provider);
- const canonicalLocalProvider = backend
- && provider.id === backend
- && isLocalInstanceProvider(provider);
- const recommendation = canonicalLocalProvider ? recommendations?.[backend] : null;
- const selectedRecommendation = recommendation?.id === modelId ? recommendation : null;
-
- if (canonicalLocalProvider) {
- const modelCapabilities = capabilitiesByBackend?.[backend];
- if (modelCapabilities && Object.hasOwn(modelCapabilities, modelId)) {
- const capabilities = modelCapabilities[modelId];
- return {
- capabilities: Array.isArray(capabilities) ? [...new Set(capabilities)] : null,
- source: Array.isArray(capabilities) ? 'runtime' : 'runtime-unknown',
- recommendation: selectedRecommendation,
- };
- }
- if (loading) {
- return { capabilities: null, source: 'loading', recommendation: selectedRecommendation };
- }
- }
-
- // A Codex or Claude CLI can attach/read an image and invoke tools through its
- // harness. That is deliberately labelled as provider-level below; it is not
- // pretending that the provider published per-model metadata.
- if (isVisionCapableCliProvider(provider)) {
- return { capabilities: ['tools', 'vision'], source: 'provider', recommendation: null };
- }
-
- const inferred = [];
- if (backend && isToolUseModel(modelId)) inferred.push('tools');
- if (backend && isVisionModel(modelId)) inferred.push('vision');
- return {
- capabilities: inferred.length ? inferred : null,
- source: inferred.length ? 'inferred' : 'unknown',
- recommendation: selectedRecommendation,
- };
-};
-
-/**
- * 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;
-
-/**
- * The LOCAL daemon namespace a provider is marked with, or null. Structural
- * markers only — a hosted gateway is an OpenCode namespace and a remote API, so
- * it is deliberately NOT one of these.
- *
- * MIRROR of `localRuntimeNamespace` in server/lib/providerModels.js — keep in
- * lockstep. The order matters: a malformed record carrying two markers keeps its
- * legacy Ollama outcome on both sides.
- * @param {{ollamaBacked?:boolean,mtplxBacked?:boolean,llamaBacked?:boolean,vllmBacked?:boolean,sglangBacked?:boolean}|null|undefined} provider
- * @returns {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|null}
- */
-export const localRuntimeNamespace = (provider) => {
- if (provider?.ollamaBacked === true) return 'ollama';
- if (provider?.lmstudioBacked === true) return 'lmstudio';
- if (provider?.mtplxBacked === true) return 'mtplx';
- if (provider?.llamaBacked === true) return 'llama';
- if (provider?.vllmBacked === true) return 'vllm';
- if (provider?.sglangBacked === true) return 'sglang';
- return null;
-};
-
-/**
- * True when a provider launches the Claude Code binary, whatever backend it is
- * pointed at (`claude-code`, `claude-ollama`, `claude-sglang`, or any renamed
- * record whose command resolves to `claude`).
- *
- * The harness — not the backend — is what decides which knobs are forwardable:
- * Claude Code owns its own sampling and speaks the Anthropic wire, so a control
- * that reaches an OpenCode wrapper through `agent.build` has no route here.
- * MIRROR of `isClaudeCommand` in server/lib/providerModels.js.
- * @param {{command?:string}|null|undefined} provider
- */
-export const isClaudeCommandProvider = (provider) => commandBasename(provider?.command) === 'claude';
-
-/**
- * Which default generation controls the provider editor should offer, or null
- * when the provider has none.
- *
- * Only the local OpenAI-compatible backends qualify — Ollama, llama.cpp, MTPLX
- * and vLLM (the first three reached directly as an `api` provider or through an
- * OpenCode CLI/TUI wrapper; vLLM ships only the wrappers), plus the hosted
- * gateways (OrcaRouter, OpenRouter). A hosted cloud provider is deliberately excluded: PortOS sends it no
- * sampling fields at all, so offering a stored temperature there would be a
- * control that silently does nothing.
- *
- * Each control is reported separately because the forwarding is uneven:
- * A gateway's upstream models own their own reasoning switch, so it has no
- * thinking toggle; and the Claude Code harness pointed at Ollama takes ONLY a
- * thinking signal (`MAX_THINKING_TOKENS=0` in server/lib/cliChildEnv.js) — it
- * owns its own sampling, so a temperature or top-p stored on one of those
- * records would never reach the daemon. MIRROR of `THINKING_STYLE` /
- * `buildAgentGeneration` in server/lib/opencodeConfig.js and
- * `apiGenerationOptions` in server/lib/aiToolkit/internal/generationOptions.js;
- * keep in lockstep.
- * @param {object|null|undefined} provider
- * @returns {{temperature:boolean, topP:boolean, thinking:boolean}|null}
- */
-export const generationControlsFor = (provider) => {
- const gateway = isGatewayBackedProvider(provider);
- // LM Studio forwards temperature/top_p like any OpenAI-compatible endpoint,
- // but reasoning there belongs to the LOADED model instance — see
- // THINKING_STYLE.lmstudio on the server, which resolves to no toggle.
- const lmstudio = provider?.lmstudioBacked === true;
- const local = isOllamaBackedProvider(provider)
- || lmstudio
- || provider?.llamaBacked === true
- || provider?.mtplxBacked === true
- || provider?.vllmBacked === true
- // SGLang takes the same `chat_template_kwargs.enable_thinking` as the other
- // local OpenAI endpoints — see THINKING_STYLE.sglang on the server.
- || provider?.sglangBacked === true;
- if (!local && !gateway) return null;
- if (isClaudeCommandProvider(provider)) {
- // A Claude harness owns its own sampling, so only the thinking signal is
- // ever forwardable — and only on Ollama, whose Anthropic endpoint maps an
- // omitted `thinking` field to non-thinking mode (`MAX_THINKING_TOKENS=0`
- // in server/lib/cliChildEnv.js). Every other local backend takes
- // `chat_template_kwargs.enable_thinking`, which the Anthropic wire cannot
- // carry — on SGLang the omitted field falls through to Qwen3.8's
- // chat-template default (thinking ON), so offering the toggle there would
- // pin a value nothing reads. No control at all is the honest answer.
- return isOllamaBackedProvider(provider)
- ? { temperature: false, topP: false, thinking: true }
- : null;
- }
- // LM Studio joins the gateways in having no forwardable thinking signal.
- return { temperature: true, topP: true, thinking: !gateway && !lmstudio };
-};
-
-// Environment variables whose names are conventionally credentials. The
-// explicit secretEnvVars list remains the primary source, but it is a masking
-// list rather than a credential schema — providers may mark optional values
-// such as AWS_PROFILE secret too. Filter both sources so only actual credential
-// names participate in readiness. The explicit list can still name a custom
-// credential that does not follow this convention (for example MY_LLM_KEY).
-const CREDENTIAL_ENV_VAR_RE = /(?:^|_)(?:API_KEY|APIKEY|AUTH|ACCESS_KEY|ACCESS_TOKEN|BEARER|CLIENT_SECRET|CREDENTIALS?|KEY|PASSWORD|PRIVATE_KEY|SECRET|TOKEN)(?:_|$)/i;
-const NON_CREDENTIAL_ENV_VAR_RE = /(?:^|_)(?:BASE_URL|CONFIG|CONFIG_CONTENT|ENDPOINT|HOST|MODEL|MODE|PATH|PORT|PROFILE|REGION)(?:_|$)/i;
-const NON_CREDENTIAL_ENV_VAR_NAMES = new Set(['CLAUDE_CODE_USE_BEDROCK']);
-
-const providerHasStoredKey = (provider) =>
- provider?.hasApiKey === true || Boolean(provider?.apiKey);
-
-const credentialEnvVars = (provider) => {
- if (!isProcessProvider(provider)) return [];
- const envVars = provider?.envVars && typeof provider.envVars === 'object' ? provider.envVars : {};
- const secretEnvVars = Array.isArray(provider?.secretEnvVars) ? provider.secretEnvVars : [];
- const explicit = new Set(secretEnvVars.filter((name) => typeof name === 'string' && name !== ''));
- const names = [...secretEnvVars, ...Object.keys(envVars)];
- return [...new Set(names.filter((name) => typeof name === 'string'
- && !NON_CREDENTIAL_ENV_VAR_NAMES.has(name)
- && !NON_CREDENTIAL_ENV_VAR_RE.test(name)
- && (explicit.has(name) || CREDENTIAL_ENV_VAR_RE.test(name))))];
-};
-
-/**
- * Identify how a provider authenticates, without deciding whether that
- * credential is present. `null` is a deliberate ref for `none`, while a
- * credential ref names the provider id, inherited sibling, or env var to look
- * up. An own key wins over the gateway marker because the server leaves a
- * provider carrying `provider.apiKey` untouched at spawn time.
- *
- * @param {{id?:string,type?:string,endpoint?:string,apiKey?:string,hasApiKey?:boolean,gatewayBacked?:string,orcarouterBacked?:boolean,envVars?:Record<string,string>,secretEnvVars?:string[]}|null|undefined} provider
- * @returns {{kind:'stored'|'inherited'|'env'|'subscription'|'none',ref:string|null}}
- */
-export const credentialSource = (provider) => {
- // Codex CLI/TUI providers can use the ChatGPT subscription that Codex owns
- // outside PortOS. It is neither a stored API key nor an environment
- // credential, so the regular credential UI must not tell the user to paste a
- // key. `providerCardState` receives the separate, bounded account verdict.
- if (isCodexSubscriptionProvider(provider)) {
- return { kind: 'subscription', ref: 'codex' };
- }
- // Local API endpoints need no credential, even if an old record happens to
- // retain one from before the endpoint was changed.
- if (isApiProvider(provider) && isPrivateNetworkEndpoint(provider?.endpoint)) {
- return { kind: 'none', ref: null };
- }
- // API providers are the only ordinary providers whose stored key is read by
- // PortOS itself. A legacy apiKey on a CLI/TUI record is not passed to the
- // process and must not hide an empty process credential.
- if (isApiProvider(provider)) {
- return { kind: 'stored', ref: provider?.id || null };
- }
- // A gateway wrapper with its own key is the one process-backed exception:
- // withGatewayApiKey leaves it untouched, so that key really is used.
- if (isGatewayBackedProvider(provider) && providerHasStoredKey(provider)) {
- return { kind: 'stored', ref: provider?.id || null };
- }
- const [envVar] = credentialEnvVars(provider);
- if (envVar) return { kind: 'env', ref: envVar };
- const gateway = gatewayForProvider(provider);
- if (gateway) return { kind: 'inherited', ref: gateway.id };
- return { kind: 'none', ref: null };
-};
-
-const normalizeCredentialState = (state) =>
- state === true || state === false ? state : null;
-
-const defaultKeySetFor = (provider, id) =>
- id && id === provider?.id ? providerHasStoredKey(provider) : null;
-
-const defaultEnvVarSet = (provider, name) => {
- if (!name || !Object.hasOwn(provider?.envVars || {}, name)) return null;
- const value = provider.envVars[name];
- const isExplicitCredential = Array.isArray(provider?.secretEnvVars)
- && provider.secretEnvVars.includes(name);
- // `***` is the sanitized secret sentinel, not evidence that the value is
- // present. A redacted value is unknown; an explicitly empty SECRET value is
- // known missing. An unmarked empty value may deliberately clear an ambient
- // host credential so the process can use another auth path, so it is unknown.
- if (value === '***' || typeof value !== 'string') return null;
- if (value === '' && !isExplicitCredential) return null;
- return value !== '';
-};
-
-const credentialEnvGroups = (provider) => {
- const names = credentialEnvVars(provider);
- const groups = [];
- const grouped = new Set();
- const hasAwsAccessPair = names.includes('AWS_ACCESS_KEY_ID') && names.includes('AWS_SECRET_ACCESS_KEY');
-
- for (const name of names) {
- if (name === 'AWS_ACCESS_KEY_ID' && hasAwsAccessPair) {
- groups.push(['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY']);
- grouped.add('AWS_ACCESS_KEY_ID');
- grouped.add('AWS_SECRET_ACCESS_KEY');
- } else if (!grouped.has(name) && !(hasAwsAccessPair && name === 'AWS_SESSION_TOKEN')) {
- groups.push([name]);
- grouped.add(name);
- }
- }
- return groups;
-};
-
-const inheritedCredentialMissing = (provider, keySetFor) => {
- const gateway = gatewayForProvider(provider);
- if (!gateway || providerHasStoredKey(provider)) return null;
- const rawState = typeof keySetFor === 'function'
- ? keySetFor(gateway.id)
- : defaultKeySetFor(provider, gateway.id);
- return normalizeCredentialState(rawState) === false
- ? { code: 'inheritedApiKey', label: `${gateway.label} API provider has no API key` }
- : null;
-};
-
-const credentialMissing = (provider, { keySetFor = null, envVarSet = null } = {}) => {
- const source = credentialSource(provider);
- if (source.kind === 'none' || source.kind === 'subscription' || !source.ref) return null;
-
- if (source.kind === 'env') {
- const groups = credentialEnvGroups(provider).map((group) => group.map((name) => {
- const rawState = typeof envVarSet === 'function' ? envVarSet(name) : defaultEnvVarSet(provider, name);
- return { name, state: normalizeCredentialState(rawState) };
- }));
- const inherited = inheritedCredentialMissing(provider, keySetFor);
- // Providers can expose alternative credential schemes in one env map (for
- // example Bedrock bearer auth or the AWS access-key pair). A complete known
- // group satisfies the provider; a partial/unknown group keeps the result
- // non-blocking rather than accusing a credential whose state is uncertain.
- const satisfied = groups.some((group) => group.every(({ state }) => state === true));
- const unknown = groups.some((group) => group.some(({ state }) => state === null));
- if (satisfied || unknown) return inherited;
- const missing = groups.flatMap((group) => group.filter(({ state }) => state === false).map(({ name }) => ({
- code: 'envVar',
- label: `${name} environment variable is not set`,
- })));
- if (inherited) missing.push(inherited);
- return missing.length > 0 ? missing : null;
- }
-
- if (source.kind === 'inherited') {
- return inheritedCredentialMissing(provider, keySetFor);
- }
- const rawState = typeof keySetFor === 'function'
- ? keySetFor(source.ref)
- : defaultKeySetFor(provider, source.ref);
- return normalizeCredentialState(rawState) === false
- ? { code: 'apiKey', label: 'API key is not set' }
- : null;
-};
-
-/**
- * Check if a provider is the Grok Build CLI/TUI (the `grok` command harness).
- * Matches the shipped `grok-cli` / `grok-tui` samples or any process provider
- * whose command basename is `grok`; the plain Grok API provider is excluded.
- * Reviewer-model discovery uses this for custom Grok process providers too.
- */
-export const isGrokBuildCli = (provider) => {
- if (!isProcessProvider(provider)) return false;
- const id = String(provider?.id || '').toLowerCase();
- return id === 'grok-cli' || id === 'grok-tui' || commandBasename(provider?.command) === 'grok';
-};
-
-/**
- * The four states a provider card can be in on the AI Providers page, ordered
- * the way the page groups them: usable now, temporarily benched, missing a
- * prerequisite, or simply switched off.
- */
-export const PROVIDER_CARD_STATE = Object.freeze({
- READY: 'ready',
- BENCHED: 'benched',
- BLOCKED: 'blocked',
- UNKNOWN: 'unknown',
- DISABLED: 'disabled',
-});
-
-/**
- * Which prerequisites a provider is missing, and the card state that follows
- * from them — one place, so a card's border, its badge and the section the page
- * files it under can never disagree with each other.
- *
- * NOT the same thing as `ProviderReadiness` /
- * `GET /api/providers/readiness`, which probes whether the local DAEMON a
- * provider points at (llama.cpp, Ollama, LM Studio, MTPLX, vLLM) is up and serving
- * the right model. This decides the card's bucket from its toggle, its
- * credentials and the server's bench status; the two render side by side.
- *
- * The prerequisite half is the SERVER's answer now (#4611): `GET
- * /api/providers` publishes `missingPrerequisites` per provider from
- * server/lib/providerPrerequisites.js, and `getFallbackProvider` skips a
- * provider whose CLI that same computation found missing — so a card blocked on
- * an uninstalled binary is no longer a routing candidate that dies at spawn
- * time on a raw ENOENT. (Routing acts only on that finding; stored, inherited,
- * and env-var credential findings stay presentation-only, and the browser now
- * derives known env-var gaps without over-reporting redacted values.)
- *
- * This function consumes the published list and adds what the browser alone
- * can see (the local-app runtime shape and sanitized env-credential state
- * below). With an older server publishing nothing, it falls back to deriving
- * the credential checks itself.
- *
- * Inputs are passed in rather than read from globals so this stays pure:
- * runtime — the provider's entry of the `runtimes` map (CLI binary)
- * or the local-app shape the page derives from the
- * local-LLM status. `null` = NOT PROBED, which must never
- * read as "missing" (an older server, or a card drawn
- * before the probe lands, would otherwise accuse every
- * perfectly-installed CLI).
- * status — the runtime-availability entry from
- * `GET /api/providers/status`; `available === false`
- * means the provider is benched after a failure.
- * keySetFor — tri-state lookup for a stored or inherited key. It must
- * return `true`/`false` when known and `null` or another
- * non-boolean when unknown.
- * envVarSet — tri-state lookup for an environment credential. An
- * explicitly empty configured value is `false`; a missing
- * or redacted value is unknown and must not be reported.
- *
- * `disabled` outranks `blocked`: a provider the user switched off is not a gap
- * in this install. PortOS ships dozens of provider records the user may never
- * want, and calling every switched-off one "needs setup" makes an install with
- * a perfectly good provider read as degraded or half-configured. What such a
- * provider is missing is still returned in `missing` — a note for the user IF
- * they decide to turn it on, not an outstanding task. `benched` only applies to
- * an enabled provider that otherwise meets its prerequisites.
- *
- * @returns {{state: string, missing: {code: string, label: string}[]}}
- */
-export const providerCardState = (provider, {
- runtime = null,
- status = null,
- keySetFor = null,
- envVarSet = null,
- // `undefined` means an older server did not provide the account feature at
- // all; `null` means this page tried to fetch it but could not determine a
- // verdict. They must not collapse into "signed out" or "ready".
- codexAccount = undefined,
-} = {}) => {
- // The server publishes its own verdict on `GET /api/providers`
- // (`missingPrerequisites`, from server/lib/providerPrerequisites.js) and
- // routes the fallback chain on exactly that computation. Where it has an
- // answer it WINS, so the card and the router cannot drift.
- //
- // An ARRAY is the sentinel for "published" — including the empty array, which
- // is a real answer ("nothing missing"). Anything else (an older server, a
- // payload fetched before the field existed) means not published, and the
- // local derivation below stands in.
- const published = Array.isArray(provider?.missingPrerequisites) ? provider.missingPrerequisites : null;
- const missing = published ? [...published] : [];
- const addMissing = (code, label) => {
- if (!missing.some((entry) => entry?.code === code && (code !== 'envVar' || entry?.label === label))) {
- missing.push({ code, label });
- }
- };
-
- // Kept client-side even when the server has published: `runtime` here may be
- // the LOCAL-APP shape the page derives from the local-LLM status (an LM Studio
- // / Ollama app installed with no CLI shim on PATH), which the server's runtime
- // table does not cover. For a plain CLI provider this is the same row the
- // server probed, and `addMissing` de-dupes it by code.
- //
- // Except when the provider resolves its binary somewhere else. The runtime row
- // answers "does the bare binary resolve on PortOS's PATH?", which says nothing
- // about a provider configured as `/opt/tools/codex` or one that overrides
- // `PATH` in its own env — the runner spawns those against their own
- // resolution. Badging them NEEDS SETUP accuses a working provider, and the
- // server (which owns the routing decision) already declines to. The install
- // widget still renders from the same row: "PortOS can install this for you"
- // remains true and useful either way.
- if (runtime && runtime.installed === false && !resolvesOutsidePortosPath(provider)) {
- addMissing('runtime', `${runtime.label || 'Runtime'} is not installed`);
- }
- // The server's published findings remain authoritative for stored/inherited
- // credentials. Env credentials are also derived here because their values
- // are intentionally redacted in the payload; the tri-state lookup lets an
- // explicitly empty value be reported without treating a redacted/absent
- // value as missing.
- const source = credentialSource(provider);
- if (!published || source.kind === 'env') {
- const missingCredential = credentialMissing(provider, { keySetFor, envVarSet });
- for (const entry of Array.isArray(missingCredential) ? missingCredential : [missingCredential]) {
- if (entry) addMissing(entry.code, entry.label);
- }
- }
-
- const codexSubscription = isCodexSubscriptionProvider(provider);
- const accountStatus = codexAccount && typeof codexAccount === 'object'
- ? codexAccount.status
- : null;
- if (codexSubscription && accountStatus === 'signed-out') {
- addMissing('codexAccount', 'No ChatGPT account is signed in');
- } else if (codexSubscription && accountStatus === 'reauth-required') {
- addMissing('codexAccount', 'ChatGPT sign-in has expired');
- } else if (codexSubscription && accountStatus === 'quota-exhausted') {
- addMissing('codexQuota', 'ChatGPT usage limit reached');
- }
-
- // Switched off wins over every finding — see the precedence note above. The
- // findings ride along so the card can still say what enabling it would take.
- if (!provider?.enabled) return { state: PROVIDER_CARD_STATE.DISABLED, missing };
- if (codexSubscription && codexAccount === null) return { state: PROVIDER_CARD_STATE.UNKNOWN, missing };
- if (codexSubscription && accountStatus === 'unknown') return { state: PROVIDER_CARD_STATE.UNKNOWN, missing };
- if (missing.length > 0) return { state: PROVIDER_CARD_STATE.BLOCKED, missing };
- if (status?.available === false) return { state: PROVIDER_CARD_STATE.BENCHED, missing };
- return { state: PROVIDER_CARD_STATE.READY, missing };
-};
-
-/**
- * Resolve the provider whose timeout is the "fallback" for a stage — the
- * stage's pinned provider when set, otherwise the active provider. Used to
- * power the placeholder + hint on stage-timeout UIs in PromptManager and
- * the Writers Room. Returns the timeout in ms (or `undefined` if neither
- * provider is present, or its timeout isn't set).
- */
-export const getProviderTimeout = (providers, stagePinnedId, activeProviderId) => {
- const id = stagePinnedId || activeProviderId;
- if (!id) return undefined;
- return providers.find((p) => p.id === id)?.timeout;
-};
-
-/**
- * The provider a record will ACTUALLY run on: its own pin when set, else the
- * install's active provider. Every picker that offers a "use the default"
- * option needs this — the model list, effort ladder, and "Default (active: X)"
- * label all have to resolve against the fallback, or leaving a record unpinned
- * silently means "no model or effort can be picked either".
- *
- * `usingActive` distinguishes the two so a caller can say which provider the
- * blank option currently means rather than just showing "Default".
- *
- * @param {Array} providers
- * @param {string|null|undefined} pinnedId - The record's own provider pin.
- * @param {string|null|undefined} activeProviderId - The install's active provider.
- * @returns {{provider: object|undefined, usingActive: boolean}}
- */
-export const resolveEffectiveProvider = (providers, pinnedId, activeProviderId) => {
- const id = pinnedId || activeProviderId || '';
- const provider = id ? (providers || []).find((p) => p.id === id) : undefined;
- return { provider, usingActive: !pinnedId && !!provider };
-};
-
-/**
- * Effective provider/model for a run against a Pipeline series — CLIENT MIRROR
- * of `resolveSeriesLlmOverride` (server/lib/seriesLlmOverride.js; the precedence
- * rationale lives there), extended with the install's active provider as the
- * final fallback so the UI can NAME what a run will call instead of a blank.
- *
- * Used by the Autopilot Options picker and the scheduled-run consent card so
- * both name the same thing the server's `resolveAutopilotLlm` will resolve.
- *
- * @returns {{provider: string, model: string}}
- */
-export const resolveSeriesRunLlm = (series, { overrideProvider, overrideModel, activeProviderId } = {}) => {
- const seriesProvider = series?.llm?.provider || '';
- // The series model belongs to the series provider — an override naming a
- // different provider must resolve THAT provider's default instead.
- const inheritsSeriesModel = !overrideProvider || overrideProvider === seriesProvider;
- return {
- provider: overrideProvider || seriesProvider || activeProviderId || '',
- model: overrideModel || (inheritsSeriesModel ? series?.llm?.model || '' : ''),
- };
-};
-
-/**
- * "Claude Code / claude-opus-5" — or "Claude Code (provider default model)"
- * when no model is pinned. The one phrasing for "which AI will this run call",
- * so the Autopilot Options copy, its live-progress line and the scheduled-run
- * consent card can't word the same fact three different ways.
- */
-export const providerModelLabel = (providers, id, model) =>
- `${providerDisplayName(providers, id, '—')}${model ? ` / ${model}` : ' (provider default model)'}`;
-
-/**
- * Tailwind chip classes for the provider type badge ('cli' / 'tui' / 'api').
- * Lifted out of AIProviders.jsx so other components can render the same
- * color treatment without redefining it.
- */
-export const providerTypeClass = (type) => {
- if (type === PROVIDER_TYPES.CLI) return 'bg-blue-500/20 text-blue-400';
- if (type === PROVIDER_TYPES.TUI) return 'bg-emerald-500/20 text-emerald-400';
- return 'bg-purple-500/20 text-purple-400';
-};
-
-// ---------------------------------------------------------------------------
-// AI Assignments option helpers — shared by the global AI Assignments table
-// (settings/AiAssignmentsTab.jsx) and per-record override drawers (e.g. the
-// Creative Director Models drawer). All three consume the `getAiAssignments`
-// payload shape (`{ providers, assignments }`), where an assignment `entry` may
-// carry `providerTypes` (which provider kinds are eligible) and optional
-// pre-baked `providerOptions` / `modelOptions` overrides for runtime call sites.
-// ---------------------------------------------------------------------------
-
-/** Display name for a provider id, falling back to the id then `fallback`. */
-export const providerDisplayName = (providers, id, fallback = '') =>
- providers.find((p) => p.id === id)?.name || id || fallback;
-
-/**
- * Provider `{ id, name }` options eligible for an assignment entry — the entry's
- * pre-baked `providerOptions` when present, else every provider whose `type` is
- * in the entry's `providerTypes` (all providers when unfiltered), tagged with a
- * "(disabled)" suffix on disabled providers.
- */
-export const assignmentProviderOptions = (entry, providers) => {
- if (Array.isArray(entry?.providerOptions)) return entry.providerOptions;
- const types = Array.isArray(entry?.providerTypes) && entry.providerTypes.length
- ? new Set(entry.providerTypes)
- : null;
- return providers
- .filter((p) => !types || types.has(p.type))
- .map((p) => ({ id: p.id, name: `${p.name}${p.enabled ? '' : ' (disabled)'}` }));
-};
-
-/**
- * Model-id options for an assignment entry given the selected provider — the
- * entry's pre-baked `modelOptions` when present, else the provider's own model
- * list (empty when the provider is unknown or has none).
- *
- * When `entry.modelFilter === 'vision'`, LOCAL backends (Ollama / LM Studio)
- * are reduced to vision-capable models via `visionLocalModelFilter` so the
- * Scene Evaluation (and other vision) pickers can't offer text-only ids.
- * Cloud/API providers are left intact by that filter. Pass `visionIdsByProvider`
- * (from `useVisionModelIds`) so that reduction uses the backend's own capability
- * metadata instead of the id regex alone.
- *
- * For a vision entry on an ENUMERATED local provider, the server's installed-VLM
- * list is also UNIONED INTO the candidates rather than only filtering them: a
- * provider's stored `models` is a snapshot that goes stale the moment the user
- * pulls a model (`/local-llm/install` doesn't refresh it, and the shipped
- * `ollama` provider starts out empty), so filtering that list alone still hides
- * a VLM that is installed right now — the same staleness `useLocalModels` +
- * `mergeModelLists` exists to solve for non-vision pickers. Only the provider
- * the server actually enumerated gets this: an unenumerated one would otherwise
- * be offered models from a host it doesn't serve.
- */
-export const assignmentModelOptions = (entry, providers, providerId, visionIdsByProvider = null) => {
- const provider = providers.find((p) => p.id === providerId);
- const baked = Array.isArray(entry?.modelOptions);
- const raw = baked ? entry.modelOptions : (provider?.models || []);
- // Normalize object-shaped entries (`{ id }`) so both baked and live lists
- // yield plain string options for the <select>.
- const models = raw
- .map((m) => (typeof m === 'string' ? m : m?.id))
- .filter(Boolean);
- if (entry?.modelFilter !== 'vision') return models;
- // Pre-baked `modelOptions` is an explicit caller-supplied list — honor it as
- // the full candidate set rather than widening it from the backend.
- const installed = baked ? null : visionIdsByProvider?.[providerId];
- const candidates = installed ? mergeModelLists(models, [...installed]) : models;
- return candidates.filter((id) => visionLocalModelFilter(id, provider, visionIdsByProvider));
-};
-
-/**
- * Tool-use annotation state for one AI-assignment row/stage, so every editor of
- * the same pin (the AI Assignments table, the Creative Director Models drawer,
- * any future one) derives it identically instead of re-deriving the rule and
- * drifting — the drawer used to be the only editor that warned at all, because
- * its stage list hard-coded `needsTools` client-side.
- *
- * `entry.needsTools` is the SERVER's marker for an assignment whose provider runs
- * an agent harness (see `agentEntry` in server/services/aiAssignments.js). It
- * mirrors `modelFilter: 'vision'`: one server flag, read uniformly.
- *
- * Three rules are baked in here so a caller can't forget one:
- * - The EFFECTIVE model is judged, not the pin. A blank model isn't a no-op —
- * the agent resolver then runs the provider's own `defaultModel`, which for a
- * local backend can be the non-tool model that wedges the run.
- * - Nothing is asserted until the capability scan SETTLES (`toolUseLoaded`,
- * success or failure). Annotating mid-scan shows the false "no known tool
- * use" the authoritative union exists to remove, only to retract it a beat
- * later.
- * - `incapable` is a strict `=== false` on the hint, so a non-agent entry, a
- * cloud provider (`localToolUseHint` returns null — ids don't encode family)
- * or an unpinned row all read as "no warning", never as "incapable".
- *
- * @param {{needsTools?:boolean}|null|undefined} entry - the assignment entry
- * @param {object|undefined} provider - the currently selected provider object
- * @param {string} model - the row's model pin ('' = provider default)
- * @param {Record<string, Set<string>>|null} [toolUseIdsByProvider] - from `useToolUseModelIds`
- * @param {boolean} [toolUseLoaded] - whether that scan has settled
- * @returns {{annotate: boolean, effectiveModel: string, incapable: boolean}}
- */
-export const assignmentToolUseState = (entry, provider, model, toolUseIdsByProvider = null, toolUseLoaded = false) => {
- const effectiveModel = effectiveModelFor(provider, model);
- const annotate = entry?.needsTools === true && toolUseLoaded;
- const hint = annotate ? localToolUseHint(effectiveModel, provider, toolUseIdsByProvider) : null;
- return { annotate, effectiveModel, incapable: hint?.toolCapable === false };
-};
-
-/**
- * Default model to seed when the user picks a provider for an assignment.
- * For vision-filtered entries, only returns a model that still appears in the
- * filtered options — a local backend's text-only `defaultModel` must not be
- * seeded into the Scene Evaluation picker.
- */
-export const assignmentDefaultModel = (entry, providers, providerId, visionIdsByProvider = null) => {
- if (!providerId) return '';
- const provider = providers.find((p) => p.id === providerId);
- if (!provider) return '';
- const def = provider.defaultModel || '';
- if (entry?.modelFilter !== 'vision') return def;
- const models = assignmentModelOptions(entry, providers, providerId, visionIdsByProvider);
- if (def && models.includes(def)) return def;
- return models[0] || '';
-};
+ * Compatibility facade for the AI-provider helpers.
+ *
+ * The helpers used to live here as one 2,200-line module. They now live in
+ * nine responsibility-scoped siblings, each named for the question it answers
+ * (and, where one exists, for the server module it mirrors):
+ *
+ * providerTypes.js — what KIND of provider a record is
+ * providerGateways.js — the hosted-gateway registry a wrapper fronts
+ * providerEndpoints.js — WHERE its endpoint points (local / fleet / public)
+ * providerModels.js — which MODEL and EFFORT a run resolves to
+ * providerSelection.js — which providers/models a picker may OFFER
+ * localModelHeuristics.js — what an untyped local model can DO
+ * providerContextWindows.js — how large a CONTEXT WINDOW it gets
+ * providerReadiness.js — is it READY to run, and why not
+ * 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.
+ */
+
+export * from './localModelHeuristics.js';
+export * from './providerAssignments.js';
+export * from './providerContextWindows.js';
+export * from './providerEndpoints.js';
+export * from './providerGateways.js';
+export * from './providerModels.js';
+export * from './providerReadiness.js';
+export * from './providerSelection.js';
+export * from './providerTypes.js';
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 389ddacdbd..859d96154f 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -1,3 +1,8 @@
+// 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.
import { describe, it, expect } from 'vitest';
import {
ANTIGRAVITY_CONFIGURED_DEFAULT,
diff --git a/server/cos-runner/allowedCommands.parity.test.js b/server/cos-runner/allowedCommands.parity.test.js
index 36b67450e1..d1f64d9473 100644
--- a/server/cos-runner/allowedCommands.parity.test.js
+++ b/server/cos-runner/allowedCommands.parity.test.js
@@ -10,7 +10,7 @@
import { describe, it, expect } from 'vitest';
import { ALLOWED_COMMANDS, isAllowedCommand } from './allowedCommands.js';
-import { isRunnerAllowedCommand } from '../../client/src/utils/providers.js';
+import { isRunnerAllowedCommand } from '../../client/src/utils/providerReadiness.js';
const allowlist = [...ALLOWED_COMMANDS].sort();
const sampleAllowed = allowlist[0];
diff --git a/server/lib/README.md b/server/lib/README.md
index cc4539e364..52ebf906a4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -184,7 +184,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)` → 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/providers.js` (the browser cannot import server code) — `providerGateways.parity.test.js` fails when the first two drift. Dependency-light: imports nothing. |
+| `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. |
| `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
| `opencodeCatalogCache.js` | Primes the on-disk catalog `opencode models` prints from — `primeOpencodeCatalogCache()` fetches OpenCode's `api.json` with Node's fetch and atomically writes `$XDG_CACHE_HOME/opencode/models.json` (`~/.cache` when unset). OpenCode refreshes that file from a forked task whose failures it swallows (`opencode models --refresh` still prints `Models cache refreshed`) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when `OPENCODE_MODELS_PATH` / a custom `OPENCODE_MODELS_URL` / `OPENCODE_DISABLE_MODELS_FETCH` means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way. |
| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. Under a `no-tool` public-review profile it also applies `hardenOpencodeConfigForNoTool` — root `permission: deny`, an emptied tool map on every agent, `tool_call: false` on every declared model, and no MCP/plugins/share/autoupdate — which IS OpenCode's enforced tool-free recipe, since it ships no read-only argv flag (`providerVendors.js` pairs it with `run --agent` + `OPENCODE_PUBLIC_REVIEW_AGENT`). The harden step also copies `agent.build`'s generation settings onto that agent, so the stage's configured thinking effort reaches the model that actually runs. |
@@ -407,7 +407,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/providers.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`. |
| `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. |
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index ebf3136215..2abd04c142 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -144,7 +144,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/providers.js — keep all three in lockstep
+// client/src/utils/localModelHeuristics.js — keep all three in lockstep
// (server/lib/localModelHeuristics.mirror.test.js fails when they drift).
const TOOL_USE_RE = new RegExp([
'qwen',
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index c6132330cb..236b1ba8eb 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -10,7 +10,7 @@ const ALLOWED_SCREENSHOT_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif',
// Reasoning-effort values accepted by the effort-capable CLI providers. Keep
// this local because the vendored toolkit must remain self-contained; the
// runtime mirror lives in server/lib/providerModels.js and the UI mirror lives
-// in client/src/utils/providers.js.
+// in client/src/utils/providerModels.js.
const PROVIDER_EFFORT_LEVELS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
const providerEffort = z.preprocess(
diff --git a/server/lib/cliChildEnv.js b/server/lib/cliChildEnv.js
index ec3f2384b9..1000fb34ba 100644
--- a/server/lib/cliChildEnv.js
+++ b/server/lib/cliChildEnv.js
@@ -147,7 +147,7 @@ function claudeLocalEnvDefaults(provider) {
// to Qwen3.8's chat-template default, which is thinking ON. Emitting the
// var there would look like an off switch while changing nothing, so the
// provider card does not offer the toggle for those records either (see
- // `generationControlsFor` in client/src/utils/providers.js).
+ // `generationControlsFor` in client/src/utils/providerModels.js).
...(provider.ollamaBacked === true && provider.thinking === false
? { MAX_THINKING_TOKENS: '0' }
: {}),
diff --git a/server/lib/codexAccount.js b/server/lib/codexAccount.js
index 3264126a4a..cada7fec94 100644
--- a/server/lib/codexAccount.js
+++ b/server/lib/codexAccount.js
@@ -111,7 +111,7 @@ export const isCodexSubscriptionProvider = (provider) => {
// paint "No ChatGPT account is signed in" on a provider that needs no account
// — and the card would sit in UNKNOWN until an account read that will never
// matter answers. MIRROR of `isCodexSubscriptionProvider` in
- // client/src/utils/providers.js.
+ // client/src/utils/providerTypes.js.
return localRuntimeNamespace(provider) === null;
};
diff --git a/server/lib/localModelHeuristics.js b/server/lib/localModelHeuristics.js
index be7acd47e8..90a7380941 100644
--- a/server/lib/localModelHeuristics.js
+++ b/server/lib/localModelHeuristics.js
@@ -10,7 +10,7 @@
* - localLlm.getStatus (recommend a best-fit editorial model)
*
* The client mirrors `isEmbeddingModel` + `isVisionModel` + `isToolUseModel`
- * in client/src/utils/providers.js — keep the regexes in lockstep (the
+ * 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.
*/
@@ -171,7 +171,7 @@ 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/providers.js (isToolUseModel) and inlined in
+// 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.
const TOOL_USE_RE = new RegExp([
diff --git a/server/lib/localModelHeuristics.mirror.test.js b/server/lib/localModelHeuristics.mirror.test.js
index 91d8c106a5..aa184be57d 100644
--- a/server/lib/localModelHeuristics.mirror.test.js
+++ b/server/lib/localModelHeuristics.mirror.test.js
@@ -2,7 +2,7 @@
* Mirror parity test for the local-model capability regexes, which exist in
* three copies by architecture:
* 1. server/lib/localModelHeuristics.js — authoritative;
- * 2. client/src/utils/providers.js — the browser cannot import server code;
+ * 2. client/src/utils/localModelHeuristics.js — the browser cannot import server code;
* 3. 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.
@@ -33,7 +33,7 @@ import { compareDeclaration, compareRegexDeclaration } 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/providers.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]
@@ -58,14 +58,14 @@ describe('localModelHeuristics↔client providers capability-regex mirror parity
compareRegexDeclaration(serverSrc, clientSrc, serverName, clientName);
expect(serverDecl, `server/lib/localModelHeuristics.js is missing: ${serverName}`).not.toBeNull();
- expect(clientDecl, `client/src/utils/providers.js is missing: ${clientName}`).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/providers.js#${clientName} no longer inlines a /…/i literal`,
+ `client/src/utils/localModelHeuristics.js#${clientName} no longer inlines a /…/i literal`,
).not.toBeNull();
expect(
clientSource,
diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.js
index 41571f2d9e..cd2d76be16 100644
--- a/server/lib/opencodeConfig.js
+++ b/server/lib/opencodeConfig.js
@@ -163,7 +163,7 @@ export function toBareModelIds(models, providerKey = 'ollama') {
* through the chat template (`chat_template_kwargs.enable_thinking`). A hosted
* gateway fronts cloud models that own their reasoning switch upstream, so it
* gets no toggle at all and the editor hides the checkbox for it. MIRROR of
- * `generationControlsFor` in `client/src/utils/providers.js`; keep in lockstep.
+ * `generationControlsFor` in `client/src/utils/providerModels.js`; keep in lockstep.
*
* A missing entry is not a missing checkbox — `buildAgentGeneration` bails on it
* and drops temperature / topP / reasoningEffort along with the toggle, which is
@@ -194,7 +194,7 @@ const THINKING_STYLE = {
sglang: 'chatTemplate',
// Every hosted gateway fronts cloud models that own their reasoning switch
// upstream, so none of them gets a toggle — the editor hides the checkbox for
- // them (`generationControlsFor` in client/src/utils/providers.js).
+ // them (`generationControlsFor` in client/src/utils/providerModels.js).
...Object.fromEntries(PROVIDER_GATEWAY_IDS.map((id) => [id, null])),
};
diff --git a/server/lib/providerGateways.js b/server/lib/providerGateways.js
index 9a7e740c08..8094c499c5 100644
--- a/server/lib/providerGateways.js
+++ b/server/lib/providerGateways.js
@@ -29,7 +29,7 @@
* 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/providers.js` — the browser, which cannot import server
+ * 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.
*/
diff --git a/server/lib/providerGateways.parity.test.js b/server/lib/providerGateways.parity.test.js
index 82f8c0aa44..219f21c157 100644
--- a/server/lib/providerGateways.parity.test.js
+++ b/server/lib/providerGateways.parity.test.js
@@ -9,7 +9,7 @@
* The two SERVER copies are compared as VALUES — the toolkit module imports
* cleanly here, so `toEqual` pins every field including `baseURL`.
*
- * The client copy (`client/src/utils/providers.js`) is compared as TEXT: it is
+ * 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`
@@ -30,7 +30,7 @@ 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/providers.js');
+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'];
@@ -119,13 +119,13 @@ describe('providerGateways ↔ aiToolkit/internal/gateways parity', () => {
});
});
-describe('providerGateways ↔ client/src/utils/providers.js 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/providers.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',
+ '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);
});
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.js
index 77eee37617..1a3cf3885f 100644
--- a/server/lib/providerModels.js
+++ b/server/lib/providerModels.js
@@ -1,6 +1,6 @@
/**
* Shared sentinel and helpers for provider model resolution.
- * Mirrors the constants in client/src/utils/providers.js — keep in sync.
+ * Mirrored in client/src/utils/providerModels.js (sentinels, ladders) and client/src/utils/providerTypes.js (predicates) — keep in sync.
*/
import { gatewayIdForProvider, isGatewayNamespace } from './providerGateways.js';
@@ -79,7 +79,7 @@ export const resolveCliModel = (model) => isConfiguredDefaultModel(model) ? null
// 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/providers.js — keep in sync
+// client/src/utils/providerModels.js — keep in sync
// (`providerModels.mirror.test.js` fails when the two copies drift).
//
// Codex Ultra adds automatic task delegation on the models that advertise it.
@@ -141,7 +141,7 @@ const codexEffortLevelsForModel = (model) => CODEX_ULTRA_MODELS.has(String(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/providers.js — keep in lockstep.
+// Mirrored in client/src/utils/providerModels.js — keep in lockstep.
// ---------------------------------------------------------------------------
const ANTIGRAVITY_EFFORT_SUFFIX_RE = new RegExp(`-(${ANTIGRAVITY_EFFORT_LEVELS.join('|')})$`);
@@ -276,7 +276,7 @@ export function isOpencodeProvider(provider) {
* True when a provider is Kimi-Code-flavored — the shipped `kimi-cli`/`kimi-tui`
* ids or any provider whose launch command basename is `kimi` (path/exe tolerant).
* The single home for the kimi signature, same posture as `isCodexProvider`.
- * Mirrored in client/src/utils/providers.js — keep in lockstep.
+ * Mirrored in client/src/utils/providerTypes.js — keep in lockstep.
* @param {{id?:string, command?:string}|null|undefined} provider
* @returns {boolean}
*/
@@ -292,7 +292,7 @@ export function isKimiProvider(provider) {
* companion to `isAntigravityCommand` in antigravity.js; lives here (rather
* than there) so `effortLevelsForProvider` can key on it without this
* dependency-light module importing a sibling. Mirrored in
- * client/src/utils/providers.js — keep in lockstep.
+ * client/src/utils/providerTypes.js — keep in lockstep.
* @param {{id?:string, command?:string}|null|undefined} provider
* @returns {boolean}
*/
@@ -315,7 +315,7 @@ export function isAntigravityProvider(provider) {
*
* Deliberately never matches a bare `cursor` command: that is Cursor's GUI
* editor launcher, not the agent binary (see cursor.js).
- * Mirrored in client/src/utils/providers.js — keep in lockstep.
+ * Mirrored in client/src/utils/providerTypes.js — keep in lockstep.
* @param {{id?:string, command?:string}|null|undefined} provider
* @returns {boolean}
*/
diff --git a/server/lib/providerModels.mirror.test.js b/server/lib/providerModels.mirror.test.js
index f848ca53b4..5c83c8c6b9 100644
--- a/server/lib/providerModels.mirror.test.js
+++ b/server/lib/providerModels.mirror.test.js
@@ -1,6 +1,6 @@
/**
* Mirror parity test for the effort ladders and model sentinels shared by
- * server/lib/providerModels.js and client/src/utils/providers.js (the browser
+ * 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).
*
@@ -29,7 +29,7 @@ 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/providers.js');
+const CLIENT_PATH = resolve(__dirname, '../../client/src/utils/providerModels.js');
const MIRRORED_NAMES = [
'CLAUDE_EFFORT_LEVELS',
@@ -67,7 +67,7 @@ describe('providerModels↔client providers effort-ladder mirror parity', () =>
compareDeclaration(serverSrc, clientSrc, name);
expect(serverDecl, `server/lib/providerModels.js is missing: ${name}`).not.toBeNull();
- expect(clientDecl, `client/src/utils/providers.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`,
diff --git a/server/lib/providerPrerequisites.js b/server/lib/providerPrerequisites.js
index 8d88064be3..cb1f7b6324 100644
--- a/server/lib/providerPrerequisites.js
+++ b/server/lib/providerPrerequisites.js
@@ -13,7 +13,7 @@
* recent failure?
*
* Until #4611 this check existed only in the browser (`providerCardState` in
- * client/src/utils/providers.js), so it painted a `NEEDS SETUP` card while the
+ * client/src/utils/providerReadiness.js), so it painted a `NEEDS SETUP` card while the
* server happily routed a run at the very same provider and discovered the
* missing binary at spawn time as a raw ENOENT. This module is the server-side
* copy the routing layer and the API payload both read, and the client now
@@ -109,7 +109,7 @@ const endpointHost = (endpoint) => {
* as un-runnable would take a supported deployment out of the fallback chain.
* A public endpoint with no key stays flagged: that one really is misconfigured.
*
- * MIRROR of `isPrivateNetworkEndpoint` in client/src/utils/providers.js — keep
+ * MIRROR of `isPrivateNetworkEndpoint` in client/src/utils/providerEndpoints.js — keep
* in lockstep. A host that cannot be parsed reads as NOT private, keeping the
* stricter of the two answers for input we don't understand.
*
diff --git a/server/services/stageRunner.js b/server/services/stageRunner.js
index 7700acd8e5..8d68e1a834 100644
--- a/server/services/stageRunner.js
+++ b/server/services/stageRunner.js
@@ -181,7 +181,7 @@ 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/providers.js.
+// 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],
@@ -243,7 +243,7 @@ const isLikelyLargeContextProvider = (provider) => {
* 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/providers.js.
+ * client/src/utils/providerContextWindows.js.
*/
export function catalogModelContextWindow(provider, model) {
const windows = provider?.modelContextWindows;
diff --git a/server/services/stageRunner.mirror.test.js b/server/services/stageRunner.mirror.test.js
index 7e56f36c97..fa6b09f991 100644
--- a/server/services/stageRunner.mirror.test.js
+++ b/server/services/stageRunner.mirror.test.js
@@ -1,6 +1,6 @@
/**
* Mirror parity test for the `KNOWN_MODEL_CONTEXT_WINDOWS` table, which lives
- * in both server/services/stageRunner.js and client/src/utils/providers.js (the
+ * 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).
*
@@ -26,7 +26,7 @@ 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/providers.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
@@ -61,7 +61,7 @@ describe('stageRunner↔client providers context-window mirror parity', () => {
compareDeclaration(serverSrc, clientSrc, name);
expect(serverDecl, `server/services/stageRunner.js is missing: ${name}`).not.toBeNull();
- expect(clientDecl, `client/src/utils/providers.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`,
diff --git a/server/services/stageRunner.test.js b/server/services/stageRunner.test.js
index 140394014f..258a87f93a 100644
--- a/server/services/stageRunner.test.js
+++ b/server/services/stageRunner.test.js
@@ -114,7 +114,7 @@ describe('stageRunner — context 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);
- // Mirrors client/src/utils/providers.js — a custom grok CLI/TUI without an
+ // 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);