Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
[issue-4854] add OpenRouter as an OpenCode-backed provider, collapsing the gateway axis into a registry
[._.]/ Adam Eivy4909254515c0
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsxindex c174bae7e4..2771100b74 100644--- a/client/src/components/providers/ProviderCard.jsx+++ b/client/src/components/providers/ProviderCard.jsx@@ -18,7 +18,7 @@ import {effectiveModelContextWindow,isApiProvider,isGrokBuildCli,- isOrcaRouterBackedProvider,+ gatewayForProvider,isPrivateNetworkEndpoint,isProcessProvider,isRunnerAllowedCommand,@@ -29,7 +29,7 @@ import {import { formatContextLength } from '../../utils/formatters';import ProviderRuntimeStatus from './ProviderRuntimeStatus';import ProviderReadiness from './ProviderReadiness';-import { GrokUploadWarning, OrcaRouterKeyHint } from './ProviderNotices';+import { GrokUploadWarning, GatewayKeyHint } from './ProviderNotices';// One phrasing for "this command isn't on the CoS Agent Runner's allowlist".// The editor states the same thing in its own inline banner, in prose.@@ -393,9 +393,10 @@ export default function ProviderCard({{isGrokBuildCli(provider) && <GrokUploadWarning className="max-w-3xl" />}- {isOrcaRouterBackedProvider(provider) && (- <OrcaRouterKeyHint- sibling={providersById.orcarouter}+ {gatewayForProvider(provider) && (+ <GatewayKeyHint+ gateway={gatewayForProvider(provider)}+ sibling={providersById[gatewayForProvider(provider).id]}onEdit={onEdit}className="max-w-3xl"/>diff --git a/client/src/components/providers/ProviderNotices.jsx b/client/src/components/providers/ProviderNotices.jsxindex 433bc5c0fb..6874950992 100644--- a/client/src/components/providers/ProviderNotices.jsx+++ b/client/src/components/providers/ProviderNotices.jsx@@ -1,6 +1,6 @@/*** The two credential/privacy notices a provider surface renders: the Grok Build- * CLI's repo-upload disclosure and the OpenCode OrcaRouter wrappers' "the key+ * CLI's repo-upload disclosure and a gateway-backed OpenCode wrapper's "the key* lives on the sibling API provider" hint.** Shared because both the provider CARD and the provider EDITOR show them — the@@ -24,27 +24,31 @@ disable_codebase_upload = true`}</pre>);}-// The OpenCode OrcaRouter wrappers (opencode-orcarouter / -tui) keep no key of-// their own — at spawn time the server copies the key from the sibling-// `orcarouter` API provider. This answers "where do I put the API key?" from the-// card/form: it's on the API provider, not here.-export function OrcaRouterKeyHint({ sibling, className = '', onEdit }) {+// A gateway-backed OpenCode wrapper (opencode-orcarouter / opencode-openrouter+// and their -tui twins) keeps no key of its own — at spawn time the server+// 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+// than hardcoding one.+export function GatewayKeyHint({ gateway, sibling, className = '', onEdit }) {+ if (!gateway) return null;const hasKey = Boolean(sibling?.hasApiKey);return (<div className={`text-xs rounded-md border border-port-border bg-port-bg/60 px-2.5 py-2 leading-relaxed ${className}`}><span className="text-gray-300">- API key is inherited from the <code className="font-mono">OrcaRouter</code> API provider+ API key is inherited from the <code className="font-mono">{gateway.label}</code> API provider{" "}at run time — this wrapper has no key field of its own.</span><p className="mt-1 text-gray-400">You do not need to add an environment variable. PortOS supplies{' '}- <code className="font-mono">ORCAROUTER_API_KEY</code> to OpenCode automatically.+ <code className="font-mono">{gateway.apiKeyEnv}</code> to OpenCode automatically.</p><div className="mt-2 flex flex-wrap items-center gap-2">{hasKey ? (- <span className="text-port-success">OrcaRouter key: set</span>+ <span className="text-port-success">{gateway.label} key: set</span>) : (- <span className="text-port-warning">OrcaRouter key: not set</span>+ <span className="text-port-warning">{gateway.label} key: not set</span>)}{sibling && onEdit && (<button@@ -52,7 +56,7 @@ export function OrcaRouterKeyHint({ sibling, className = '', onEdit }) {onClick={() => onEdit(sibling)}className="text-port-accent hover:text-port-accent/80 underline underline-offset-2">- Edit OrcaRouter API provider+ Edit {gateway.label} API provider</button>)}</div>diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex 23a374845a..a5edc1aec6 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -4,7 +4,7 @@ import { AlertTriangle, Gauge } from 'lucide-react';import toast from '../components/ui/Toast';import * as api from '../services/api';import socket from '../services/socket';-import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isGrokBuildCli, isLocalEndpoint, isLocalInstanceProvider, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, isOrcaRouterBackedProvider, isClaudeCommandProvider, generationControlsFor, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';+import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isGrokBuildCli, isLocalEndpoint, isLocalInstanceProvider, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';import useLocalModels from '../hooks/useLocalModels';import { useAutoRefetch } from '../hooks/useAutoRefetch';import BrailleSpinner from '../components/BrailleSpinner';@@ -25,7 +25,7 @@ import useDrawerTab from '../hooks/useDrawerTab';import { FormField } from '../components/ui/FormField';import RuntimeInstallModal from '../components/install/RuntimeInstallModal';import ProviderCard from '../components/providers/ProviderCard';-import { GrokUploadWarning, OrcaRouterKeyHint } from '../components/providers/ProviderNotices';+import { GrokUploadWarning, GatewayKeyHint } from '../components/providers/ProviderNotices';import CollapsibleSection from '../components/ui/CollapsibleSection';// The two local apps an API provider can front. Their installer lives on the@@ -944,7 +944,7 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders// and render blank — reading as "no model configured" when one is.const configuredDefault = configuredDefaultIn(mergedModels);// The markers that identify a backed provider (`ollamaBacked`, `llamaBacked`,- // `orcarouterBacked`) are NOT form fields, so a shape built from `formData`+ // `gatewayBacked`) are NOT form fields, so a shape built from `formData`// alone loses them — which hid the effort ladder on the OpenCode-Ollama// providers, whose ladder is keyed on `ollamaBacked`. Merge the live edits// over the stored record instead, so edits to command/endpoint/envVars count@@ -1333,7 +1333,7 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders<p className="text-xs text-gray-500 mt-1">This field is the only place API providers read a key from — it's stored on thisprovider and sent as an <code>Authorization: Bearer</code> header on every request.- No environment variable is involved. Hosted APIs (Cerebras, Grok, NVIDIA, OrcaRouter, …) require+ No environment variable is involved. Hosted APIs (Cerebras, Grok, NVIDIA, OrcaRouter, OpenRouter, …) requireone; local backends (Ollama, LM Studio) don't.</p></FormField>@@ -1369,9 +1369,10 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders{isGrokBuildCli({ type: formData.type, command: formData.command }) && <GrokUploadWarning />}- {isOrcaRouterBackedProvider(provider) && (- <OrcaRouterKeyHint- sibling={allProviders.find(p => p.id === 'orcarouter')}+ {gatewayForProvider(provider) && (+ <GatewayKeyHint+ gateway={gatewayForProvider(provider)}+ sibling={allProviders.find(p => p.id === gatewayForProvider(provider).id)}onEdit={onEditProvider}/>)}diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 63bb8cc256..f04d347a1a 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -41,7 +41,7 @@ grep -i "what you want to do" client/src/utils/README.md| `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), `isHttpUrl` (explicit http(s) only — safe-href check), 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`, `isAntigravityProvider`, `isOrcaRouterBackedProvider` (the OpenCode wrapper that inherits its API key from the sibling `orcarouter` API provider at spawn time), `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`). 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. 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. |+| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isAntigravityProvider`, `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`). 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. 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. || `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`). |## Module loading / resiliencediff --git a/client/src/utils/providers.js b/client/src/utils/providers.jsindex 4670b4a8d2..8e221ddaa6 100644--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@ -209,7 +209,8 @@ export const CURSOR_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhi/*** True when an OpenCode process provider runs against one of the local- * OpenAI-compatible backends (Ollama / MTPLX / llama.cpp / vLLM / OrcaRouter)+ * OpenAI-compatible backends (Ollama / 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@@ -224,7 +225,7 @@ export const isOpencodeLocalProvider = (provider) =>|| provider?.llamaBacked === true|| provider?.vllmBacked === true|| provider?.sglangBacked === true- || provider?.orcarouterBacked === true);+ || isGatewayBackedProvider(provider));/*** Antigravity base-model ↔ effort-suffix split — MIRROR of@@ -979,19 +980,42 @@ export const isOllamaBackedProvider = (provider) => {};/**-* True when a provider is an OpenCode wrapper that front-ends the OrcaRouter-* gateway (the shipped `opencode-orcarouter` / `opencode-orcarouter-tui`-* presets, or any renamed wrapper carrying the `orcarouterBacked` marker).-*-* These wrappers deliberately carry NO key of their own: at spawn time the-* server attaches the key from the sibling `orcarouter` API provider-* (`server/lib/aiToolkit/providers.js` `withOrcaRouterApiKey`), so the one place-* a user actually pastes the key is the `orcarouter` API provider, not this-* form. MIRROR of the `orcarouterBacked` marker the server keys on — keep in-* lockstep with `server/lib/providerModels.js#getOpencodeLocalProviderNamespace`.-* @param {{id?:string,orcarouterBacked?:boolean}} provider-*/-export const isOrcaRouterBackedProvider = (provider) => provider?.orcarouterBacked === true;+ * 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. `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;/*** True when a provider launches the Claude Code binary, whatever backend it is@@ -1012,13 +1036,13 @@ export const isClaudeCommandProvider = (provider) => commandBasename(provider?.c** 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 OrcaRouter- * gateway. A hosted cloud provider is deliberately excluded: PortOS sends it no+ * 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:- * OrcaRouter's upstream models own their own reasoning switch, so it has no+ * 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@@ -1030,7 +1054,7 @@ export const isClaudeCommandProvider = (provider) => commandBasename(provider?.c* @returns {{temperature:boolean, topP:boolean, thinking:boolean}|null}*/export const generationControlsFor = (provider) => {- const orcarouter = isOrcaRouterBackedProvider(provider);+ const gateway = isGatewayBackedProvider(provider);const local = isOllamaBackedProvider(provider)|| provider?.llamaBacked === true|| provider?.mtplxBacked === true@@ -1038,7 +1062,7 @@ export const generationControlsFor = (provider) => {// 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 && !orcarouter) return null;+ 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@@ -1052,7 +1076,7 @@ export const generationControlsFor = (provider) => {? { temperature: false, topP: false, thinking: true }: null;}- return { temperature: true, topP: true, thinking: !orcarouter };+ return { temperature: true, topP: true, thinking: !gateway };};// Environment variables whose names are conventionally credentials. The@@ -1084,10 +1108,10 @@ const credentialEnvVars = (provider) => {* 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 OrcaRouter marker because the server leaves a+ * 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,orcarouterBacked?:boolean,envVars?:Record<string,string>,secretEnvVars?:string[]}|null|undefined} provider+ * @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'|'none',ref:string|null}}*/export const credentialSource = (provider) => {@@ -1102,14 +1126,15 @@ export const credentialSource = (provider) => {if (isApiProvider(provider)) {return { kind: 'stored', ref: provider?.id || null };}- // An OrcaRouter wrapper with its own key is the one process-backed exception:- // withOrcaRouterApiKey leaves it untouched, so that key really is used.- if (isOrcaRouterBackedProvider(provider) && providerHasStoredKey(provider)) {+ // 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 };- if (isOrcaRouterBackedProvider(provider)) return { kind: 'inherited', ref: 'orcarouter' };+ const gateway = gatewayForProvider(provider);+ if (gateway) return { kind: 'inherited', ref: gateway.id };return { kind: 'none', ref: null };};@@ -1153,12 +1178,13 @@ const credentialEnvGroups = (provider) => {};const inheritedCredentialMissing = (provider, keySetFor) => {- if (!isOrcaRouterBackedProvider(provider) || providerHasStoredKey(provider)) return null;+ const gateway = gatewayForProvider(provider);+ if (!gateway || providerHasStoredKey(provider)) return null;const rawState = typeof keySetFor === 'function'- ? keySetFor('orcarouter')- : defaultKeySetFor(provider, 'orcarouter');+ ? keySetFor(gateway.id)+ : defaultKeySetFor(provider, gateway.id);return normalizeCredentialState(rawState) === false- ? { code: 'inheritedApiKey', label: 'OrcaRouter API provider has no API key' }+ ? { code: 'inheritedApiKey', label: `${gateway.label} API provider has no API key` }: null;};diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex 8df72e0cc2..7dad365568 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -38,7 +38,8 @@ import {isPrivateNetworkEndpoint,PROVIDER_CARD_STATE,isOllamaBackedProvider,- isOrcaRouterBackedProvider,+ gatewayForProvider,+ isGatewayBackedProvider,isGrokBuildCli,isKimiProvider,isCodexProvider,@@ -171,6 +172,8 @@ describe('generationControlsFor', () => {['native Ollama API', { id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1' }, { temperature: true, topP: true, thinking: true }],// OrcaRouter proxies cloud models that own their own reasoning switch.['OpenCode OrcaRouter', { id: 'opencode-orcarouter', command: 'opencode', orcarouterBacked: true }, { temperature: true, topP: true, thinking: false }],+ // Same posture for every gateway: upstream models own their reasoning switch.+ ['OpenCode OpenRouter', { id: 'opencode-openrouter', command: 'opencode', gatewayBacked: 'openrouter' }, { temperature: true, topP: true, thinking: false }],['cloud API provider', { id: 'anthropic', type: 'api', endpoint: 'https://api.anthropic.com/v1' }, null],['vendor CLI', { id: 'claude-code', command: 'claude' }, null],])('%s', (_label, provider, expected) => {@@ -479,17 +482,23 @@ describe('provider type predicates', () => {expect(isProcessProvider(api)).toBe(false);});- it('isOrcaRouterBackedProvider matches only the orcarouterBacked marker', () => {- expect(isOrcaRouterBackedProvider({ id: 'opencode-orcarouter', orcarouterBacked: true })).toBe(true);- expect(isOrcaRouterBackedProvider({ id: 'opencode-orcarouter-tui', orcarouterBacked: true })).toBe(true);+ it('gatewayForProvider matches the generic marker and the legacy boolean', () => {+ // The legacy per-gateway boolean, which stored records still carry.+ expect(gatewayForProvider({ id: 'opencode-orcarouter', orcarouterBacked: true }).id).toBe('orcarouter');+ expect(gatewayForProvider({ id: 'opencode-orcarouter-tui', orcarouterBacked: true }).id).toBe('orcarouter');+ // The generic marker every new gateway wrapper ships with.+ expect(gatewayForProvider({ id: 'opencode-openrouter', gatewayBacked: 'openrouter' }).id).toBe('openrouter');+ expect(gatewayForProvider({ id: 'opencode-openrouter-tui', gatewayBacked: 'openrouter' }).label).toBe('OpenRouter');// A renamed wrapper that keeps the marker still inherits the sibling key.- expect(isOrcaRouterBackedProvider({ id: 'my-orca', orcarouterBacked: true })).toBe(true);- // The sibling API provider itself is NOT orcarouter-backed (it owns the key).- expect(isOrcaRouterBackedProvider({ id: 'orcarouter', type: 'api' })).toBe(false);+ expect(isGatewayBackedProvider({ id: 'my-orca', orcarouterBacked: true })).toBe(true);+ // The sibling API provider itself is NOT gateway-backed (it owns the key).+ expect(isGatewayBackedProvider({ id: 'orcarouter', type: 'api' })).toBe(false);+ expect(isGatewayBackedProvider({ id: 'openrouter', type: 'api' })).toBe(false);// An ollama-backed OpenCode wrapper shares the form shape but not the marker.- expect(isOrcaRouterBackedProvider({ id: 'opencode-ollama', ollamaBacked: true })).toBe(false);- expect(isOrcaRouterBackedProvider(null)).toBe(false);- expect(isOrcaRouterBackedProvider(undefined)).toBe(false);+ expect(isGatewayBackedProvider({ id: 'opencode-ollama', ollamaBacked: true })).toBe(false);+ expect(isGatewayBackedProvider({ id: 'x', gatewayBacked: 'not-a-gateway' })).toBe(false);+ expect(isGatewayBackedProvider(null)).toBe(false);+ expect(isGatewayBackedProvider(undefined)).toBe(false);});it('isOllamaBackedProvider matches the marker or an Ollama base URL', () => {@@ -947,10 +956,11 @@ describe('supportsModelRefresh', () => {'cursor-tui', 'grok', 'lmstudio', 'mtplx', 'nvidia-kimi', 'ollama','opencode-llama-tui','opencode-mtplx', 'opencode-mtplx-tui', 'opencode-ollama',- 'opencode-ollama-tui', 'opencode-orcarouter', 'opencode-orcarouter-tui',+ 'opencode-ollama-tui', 'opencode-openrouter', 'opencode-openrouter-tui',+ 'opencode-orcarouter', 'opencode-orcarouter-tui','opencode-sglang', 'opencode-sglang-tui','opencode-vllm', 'opencode-vllm-tui',- 'orcarouter',+ 'openrouter', 'orcarouter',]);});});@@ -1269,9 +1279,11 @@ describe('credentialSource', () => {.toEqual({ kind: 'none', ref: null });});- it('identifies an inherited OrcaRouter key', () => {+ it('identifies an inherited gateway key, pointing at the sibling of that gateway', () => {expect(credentialSource({ id: 'opencode-orcarouter', type: 'cli', orcarouterBacked: true })).toEqual({ kind: 'inherited', ref: 'orcarouter' });+ expect(credentialSource({ id: 'opencode-openrouter', type: 'cli', gatewayBacked: 'openrouter' }))+ .toEqual({ kind: 'inherited', ref: 'openrouter' });});it('identifies env credentials from explicit metadata and conventional names', () => {@@ -1384,6 +1396,16 @@ describe('providerCardState', () => {expect(providerCardState(wrapper, { keySetFor: () => true }).state).toBe(PROVIDER_CARD_STATE.READY);});+ it('blocks an OpenRouter wrapper against its OWN sibling, naming that gateway', () => {+ const wrapper = cli({ id: 'opencode-openrouter', gatewayBacked: 'openrouter' });+ expect(providerCardState(wrapper, { keySetFor: id => id === 'openrouter' ? false : null }).missing)+ .toEqual([{ code: 'inheritedApiKey', label: 'OpenRouter API provider has no API key' }]);+ // An OrcaRouter key must never satisfy an OpenRouter wrapper.+ expect(providerCardState(wrapper, { keySetFor: id => id === 'orcarouter' }).missing)+ .toEqual([{ code: 'inheritedApiKey', label: 'OpenRouter API provider has no API key' }]);+ expect(providerCardState(wrapper, { keySetFor: () => true }).state).toBe(PROVIDER_CARD_STATE.READY);+ });+it('does not require the inherited key when a wrapper carries its own key', () => {const wrapper = cli({ id: 'opencode-orcarouter', apiKey: 'sk-example', orcarouterBacked: true });expect(providerCardState(wrapper, { keySetFor: id => id === wrapper.id })).toEqual({diff --git a/data.reference/providers.json b/data.reference/providers.jsonindex ed909b6dc9..e06a3ef661 100644--- a/data.reference/providers.json+++ b/data.reference/providers.json@@ -416,6 +416,59 @@"secretEnvVars": [],"headlessArgs": []},+ "openrouter": {+ "id": "openrouter",+ "name": "OpenRouter",+ "type": "api",+ "endpoint": "https://openrouter.ai/api/v1",+ "apiKey": "",+ "models": ["openrouter/auto"],+ "defaultModel": "openrouter/auto",+ "lightModel": "openrouter/auto",+ "mediumModel": "openrouter/auto",+ "heavyModel": "openrouter/auto",+ "timeout": 300000,+ "enabled": false,+ "envVars": {},+ "secretEnvVars": []+ },+ "opencode-openrouter": {+ "id": "opencode-openrouter",+ "name": "OpenCode OpenRouter",+ "type": "cli",+ "command": "opencode",+ "args": ["run"],+ "endpoint": "https://openrouter.ai/api/v1",+ "models": ["openrouter/auto"],+ "defaultModel": "openrouter/auto",+ "gatewayBacked": "openrouter",+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"openrouter\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"OpenRouter\",\"options\":{\"baseURL\":\"https://openrouter.ai/api/v1\"}}}}"+ },+ "secretEnvVars": [],+ "headlessArgs": []+ },+ "opencode-openrouter-tui": {+ "id": "opencode-openrouter-tui",+ "name": "OpenCode OpenRouter TUI",+ "type": "tui",+ "command": "opencode",+ "args": [],+ "endpoint": "https://openrouter.ai/api/v1",+ "models": ["openrouter/auto"],+ "defaultModel": "openrouter/auto",+ "gatewayBacked": "openrouter",+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"openrouter\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"OpenRouter\",\"options\":{\"baseURL\":\"https://openrouter.ai/api/v1\"}}}}"+ },+ "secretEnvVars": [],+ "tuiPromptDelayMs": 2500,+ "tuiIdleTimeoutMs": 180000+ },"opencode-orcarouter-tui": {"id": "opencode-orcarouter-tui","name": "OpenCode OrcaRouter TUI",diff --git a/scripts/migrations/293-openrouter-providers.js b/scripts/migrations/293-openrouter-providers.jsnew file mode 100644index 0000000000..c041fdad40--- /dev/null+++ b/scripts/migrations/293-openrouter-providers.js@@ -0,0 +1,85 @@+/**+ * Ship disabled OpenRouter API and OpenCode presets to existing installs.+ *+ * OpenRouter is an OpenAI-compatible gateway, the second row of+ * `server/lib/providerGateways.js` after OrcaRouter (migration 278). The API+ * provider owns the key; the OpenCode wrappers keep their static config keyless+ * and resolve the sibling API key only when spawning or refreshing models. This+ * migration is additive and never contacts the gateway or changes the active+ * provider.+ *+ * The wrappers carry the generic `gatewayBacked: 'openrouter'` marker rather+ * than a per-gateway boolean — the legacy `orcarouterBacked` shape stays+ * readable forever for records written before the registry existed, but nothing+ * new is written in it.+ *+ * Kept in lockstep with data.reference/providers.json and+ * server/lib/aiToolkit/defaults/providers.sample.json. Later default changes+ * require a new migration.+ */++import { makeProviderSeedMigration } from './_lib.js';++const OPENCODE_CONFIG_CONTENT = '{"permission":"allow","provider":{"openrouter":{"npm":"@ai-sdk/openai-compatible","name":"OpenRouter","options":{"baseURL":"https://openrouter.ai/api/v1"}}}}';++// OpenRouter's own auto-router. Namespaced for OpenCode it becomes+// `openrouter/openrouter/auto` — see `prefixOpencodeModel` on why the doubling+// is correct and why a single-prefix guard would break exactly this id.+const AUTO_MODEL = 'openrouter/auto';++const OPENROUTER_API = {+ id: 'openrouter',+ name: 'OpenRouter',+ type: 'api',+ endpoint: 'https://openrouter.ai/api/v1',+ apiKey: '',+ models: [AUTO_MODEL],+ defaultModel: AUTO_MODEL,+ lightModel: AUTO_MODEL,+ mediumModel: AUTO_MODEL,+ heavyModel: AUTO_MODEL,+ timeout: 300000,+ enabled: false,+ envVars: {},+ secretEnvVars: [],+};++const OPENCODE_OPENROUTER_CLI = {+ id: 'opencode-openrouter',+ name: 'OpenCode OpenRouter',+ type: 'cli',+ command: 'opencode',+ args: ['run'],+ endpoint: 'https://openrouter.ai/api/v1',+ models: [AUTO_MODEL],+ defaultModel: AUTO_MODEL,+ gatewayBacked: 'openrouter',+ timeout: 600000,+ enabled: false,+ envVars: { OPENCODE_CONFIG_CONTENT },+ secretEnvVars: [],+ headlessArgs: [],+};++const OPENCODE_OPENROUTER_TUI = {+ id: 'opencode-openrouter-tui',+ name: 'OpenCode OpenRouter TUI',+ type: 'tui',+ command: 'opencode',+ args: [],+ endpoint: 'https://openrouter.ai/api/v1',+ models: [AUTO_MODEL],+ defaultModel: AUTO_MODEL,+ gatewayBacked: 'openrouter',+ timeout: 600000,+ enabled: false,+ envVars: { OPENCODE_CONFIG_CONTENT },+ secretEnvVars: [],+ tuiPromptDelayMs: 2500,+ tuiIdleTimeoutMs: 180000,+};++export default makeProviderSeedMigration({+ label: 'OpenRouter',+ defs: [OPENROUTER_API, OPENCODE_OPENROUTER_CLI, OPENCODE_OPENROUTER_TUI],+});diff --git a/scripts/migrations/293-openrouter-providers.test.js b/scripts/migrations/293-openrouter-providers.test.jsnew file mode 100644index 0000000000..0c6eacadf1--- /dev/null+++ b/scripts/migrations/293-openrouter-providers.test.js@@ -0,0 +1,74 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './293-openrouter-providers.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 293 — OpenRouter providers', () => {+ let rootDir;+ let providersPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-293-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ providersPath = join(rootDir, 'data/providers.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('adds disabled presets without changing the active provider', async () => {+ writeJson(providersPath, {+ activeProvider: 'claude-code',+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },+ });++ await migration.up({ rootDir });+ const out = readJson(providersPath);+ const api = out.providers.openrouter;+ const cli = out.providers['opencode-openrouter'];+ const tui = out.providers['opencode-openrouter-tui'];++ expect(api).toMatchObject({+ endpoint: 'https://openrouter.ai/api/v1',+ apiKey: '',+ models: ['openrouter/auto'],+ enabled: false,+ });+ expect(cli).toMatchObject({ type: 'cli', gatewayBacked: 'openrouter', enabled: false });+ expect(tui).toMatchObject({ type: 'tui', gatewayBacked: 'openrouter', enabled: false, tuiIdleTimeoutMs: 180000 });+ // The wrappers stay keyless on disk — the key is attached to the+ // execution-time copy from the sibling API record (`withGatewayApiKey`).+ expect(JSON.parse(cli.envVars.OPENCODE_CONFIG_CONTENT).provider.openrouter.options.apiKey).toBeUndefined();+ expect(JSON.parse(tui.envVars.OPENCODE_CONFIG_CONTENT).provider.openrouter.options.apiKey).toBeUndefined();+ expect(out.activeProvider).toBe('claude-code');+ });++ it('preserves an existing OpenRouter API key and custom provider', async () => {+ const existing = { id: 'openrouter', name: 'My Router', type: 'api', apiKey: 'sk-or-example', enabled: true };+ writeJson(providersPath, { providers: { openrouter: existing } });++ await migration.up({ rootDir });+ expect(readJson(providersPath).providers.openrouter).toEqual(existing);+ });++ it('is a no-op on re-run', async () => {+ writeJson(providersPath, { activeProvider: 'claude-code', providers: {} });++ await migration.up({ rootDir });+ const first = readFileSync(providersPath, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(providersPath, 'utf-8')).toBe(first);+ });++ it('leaves the OrcaRouter presets untouched', async () => {+ const orca = { id: 'orcarouter', type: 'api', apiKey: 'sk-orca-example' };+ writeJson(providersPath, { providers: { orcarouter: orca } });++ await migration.up({ rootDir });+ expect(readJson(providersPath).providers.orcarouter).toEqual(orca);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex fb65bf8a26..8bd97529d7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -113,7 +113,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `aiProvider.js` | Shared AI provider utilities for LLM calls. || `promptRunner.js` | Shared LLM runner wrapper. || `providerCooldown.js` | Provider bench policy — `resolveProviderBench(analysis)` → `null` (don't bench) / a `usage-limit` marker / an `unavailable` marker with the per-category cooldown from `COOLDOWN_MS_BY_CATEGORY`. Declines to bench request/response-specific categories (`isRequestSpecificCategory` / `isSchemaTypeCategory`) so one bad model id or off-shape response can't take a healthy provider offline. Shared by `promptRunner.js` (prompt cascade) and `services/agentFinalization.js` (finished CoS agent run) so both bench a category for the same window. Pure. |-| `providerPrerequisites.js` | Can a provider run on this host AT ALL — `providerPrerequisites(provider, { runtime, orcaRouterKeySet })` → `{ met, missing: [{ code, label }] }` (CLI binary on PATH, API key stored for a public endpoint, the sibling key an OrcaRouter wrapper inherits unless it carries its own), plus `providerRuntimeKey` (`null` for an API provider, for a command carrying an explicit path, and for a provider with its own `PATH` in `envVars` — the runtime table only answers "does the BARE binary resolve on PortOS's PATH?", which is not those providers' question), `isPrivateNetworkEndpoint` (mirror of the client copy: loopback/RFC1918/tailnet CGNAT + ULA/`.ts.net`/single-label hosts need no key) and `describeMissingPrerequisites`. `runtime: null` = NOT PROBED and never counts as missing. Feeds BOTH `GET /api/providers` and the fallback chain in `aiToolkit/providerStatus.js` (via `services/providerPrerequisites.js`), so a `NEEDS SETUP` card and the router read one computation (#4611). `ROUTING_BLOCKING_CODES`/`blocksRouting(missing)` narrow what ROUTING may act on to the missing binary. Stored, inherited, and environment-backed credential findings stay presentation-only here because the server cannot assume the eventual process environment; the client card classifies sanitized env metadata through tri-state lookups (#4612). Pure. |+| `providerPrerequisites.js` | Can a provider run on this host AT ALL — `providerPrerequisites(provider, { runtime, gatewayKeySet })` → `{ met, missing: [{ code, label }] }` (CLI binary on PATH, API key stored for a public endpoint, the sibling key a gateway-backed wrapper inherits from the API record of its own gateway id unless it carries its own), plus `providerRuntimeKey` (`null` for an API provider, for a command carrying an explicit path, and for a provider with its own `PATH` in `envVars` — the runtime table only answers "does the BARE binary resolve on PortOS's PATH?", which is not those providers' question), `isPrivateNetworkEndpoint` (mirror of the client copy: loopback/RFC1918/tailnet CGNAT + ULA/`.ts.net`/single-label hosts need no key) and `describeMissingPrerequisites`. `runtime: null` = NOT PROBED and never counts as missing. Feeds BOTH `GET /api/providers` and the fallback chain in `aiToolkit/providerStatus.js` (via `services/providerPrerequisites.js`), so a `NEEDS SETUP` card and the router read one computation (#4611). `ROUTING_BLOCKING_CODES`/`blocksRouting(missing)` narrow what ROUTING may act on to the missing binary. Stored, inherited, and environment-backed credential findings stay presentation-only here because the server cannot assume the eventual process environment; the client card classifies sanitized env metadata through tri-state lookups (#4612). Pure. || `tuiPromptRunner.js` | One-shot TUI prompt runner (PTY-driven). || `tuiShellLaunch.js` | `buildTuiShellLaunch(provider)` → `{ commandLine, env }` for launching a TUI provider by hand in a Shell session (the AI Providers card's "Launch in Shell" button). Resolves the command via `tuiHandshake.js#buildTuiInvocation` (so the vendor posture flags and `--model`/`--effort` injection match a real TUI spawn) and the env via `cliChildEnv.js#composeProviderEnv`. **The env is why this is server-side and the deep link carries only a provider ID**: a TUI provider's backend lives in `envVars` (`ANTHROPIC_BASE_URL` for an Ollama-backed or Bedrock `claude`, `OPENCODE_CONFIG_CONTENT` for an OpenCode wrapper), so a shell handed only the command line would run the right binary against the vendor cloud instead of the local daemon the user configured — and those values are secret, so they can't ride a URL. Returns null for a non-TUI provider. Must be given a RAW provider, never a client-sanitized one (redacted `'***'` env reads truthy). || `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. Also owns `SUBMIT_KEY` — the single Enter byte every PTY writer sends, whether it's submitting a pasted TUI prompt or a command PortOS injected into a shell session. It is CR, never LF: a POSIX pty's ICRNL hides the difference, but cmd.exe under Windows ConPTY accepts only CR and leaves an LF-terminated line typed-but-unexecuted at the prompt. |@@ -138,6 +138,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). || `subscriptionSavings.js` | Subscription-vs-API savings math for the usage page — `resolveSavingsWindow` (clamps an open-ended report range to today / first activity day), `prorateMonthlyCost` (monthly plan price → this window's share, `DAYS_PER_MONTH`, capped by `MAX_MONTHLY_COST`), `savingsPercent` / `costMultiplier` (null, never 0, when the comparison is undefined), `attributeReportCostToFamilies` (groups report rows by their stamped `family`), `roundCents` (the one money rounder), and `buildSubscriptionSavings({ entries, range, unmatchedApiCost })` → per-family rows + totals. Pure. || `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. |+| `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. || `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. 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`. || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring bare model ids under the selected local provider (`ollama` or `mtplx`) for marked OpenCode providers. Fixes --model rejection. || `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project). |diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex 041f238429..47939d76e4 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -336,6 +336,59 @@"secretEnvVars": [],"headlessArgs": []},+ "openrouter": {+ "id": "openrouter",+ "name": "OpenRouter",+ "type": "api",+ "endpoint": "https://openrouter.ai/api/v1",+ "apiKey": "",+ "models": ["openrouter/auto"],+ "defaultModel": "openrouter/auto",+ "lightModel": "openrouter/auto",+ "mediumModel": "openrouter/auto",+ "heavyModel": "openrouter/auto",+ "timeout": 300000,+ "enabled": false,+ "envVars": {},+ "secretEnvVars": []+ },+ "opencode-openrouter": {+ "id": "opencode-openrouter",+ "name": "OpenCode OpenRouter",+ "type": "cli",+ "command": "opencode",+ "args": ["run"],+ "endpoint": "https://openrouter.ai/api/v1",+ "models": ["openrouter/auto"],+ "defaultModel": "openrouter/auto",+ "gatewayBacked": "openrouter",+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"openrouter\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"OpenRouter\",\"options\":{\"baseURL\":\"https://openrouter.ai/api/v1\"}}}}"+ },+ "secretEnvVars": [],+ "headlessArgs": []+ },+ "opencode-openrouter-tui": {+ "id": "opencode-openrouter-tui",+ "name": "OpenCode OpenRouter TUI",+ "type": "tui",+ "command": "opencode",+ "args": [],+ "endpoint": "https://openrouter.ai/api/v1",+ "models": ["openrouter/auto"],+ "defaultModel": "openrouter/auto",+ "gatewayBacked": "openrouter",+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"openrouter\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"OpenRouter\",\"options\":{\"baseURL\":\"https://openrouter.ai/api/v1\"}}}}"+ },+ "secretEnvVars": [],+ "tuiPromptDelayMs": 2500,+ "tuiIdleTimeoutMs": 180000+ },"opencode-orcarouter-tui": {"id": "opencode-orcarouter-tui","name": "OpenCode OrcaRouter TUI",diff --git a/server/lib/aiToolkit/internal/gateways.js b/server/lib/aiToolkit/internal/gateways.jsnew file mode 100644index 0000000000..ec534fe42c--- /dev/null+++ b/server/lib/aiToolkit/internal/gateways.js@@ -0,0 +1,61 @@+/**+ * Hosted OpenAI-compatible gateways an OpenCode CLI/TUI wrapper can front-end+ * (OrcaRouter, OpenRouter).+ *+ * A DELIBERATE MIRROR of `server/lib/providerGateways.js`. This directory is+ * vendored and stays self-contained — no imports out to other PortOS modules+ * (see `aiToolkit/CLAUDE.md`) — so the table is duplicated rather than imported.+ * `server/lib/providerGateways.parity.test.js` fails when the two drift.+ *+ * Lives in `internal/` for the same reason `ollamaBacked.js` does: the+ * model-fetcher table (`internal/modelFetchers.js`) keys a row on it, and an+ * import back into `providers.js` would form a module cycle. Re-exported from+ * `providers.js` so hosts classify a wrapper the same way the refresh dispatch+ * and the sibling-key attach do.+ *+ * What makes a gateway different from a local runtime (`ollamaBacked`,+ * `vllmBacked`, …): it is remote (nothing to probe), it always authenticates,+ * and the wrapper stores NO key — the sibling `api` record whose id equals the+ * gateway id owns it (`withGatewayApiKey` in `providers.js`).+ */++/** @type {readonly {id:string,label:string,baseURL:string,apiKeyEnv:string,legacyMarker?:string,legacyApiKeyField?:string}[]} */+export const PROVIDER_GATEWAYS = Object.freeze([+ Object.freeze({+ id: 'orcarouter',+ label: 'OrcaRouter',+ baseURL: 'https://api.orcarouter.ai/v1',+ apiKeyEnv: 'ORCAROUTER_API_KEY',+ legacyMarker: 'orcarouterBacked',+ legacyApiKeyField: 'orcarouterApiKey',+ }),+ Object.freeze({+ id: 'openrouter',+ label: 'OpenRouter',+ baseURL: 'https://openrouter.ai/api/v1',+ apiKeyEnv: 'OPENROUTER_API_KEY',+ }),+]);++/** Every gateway id. */+export const PROVIDER_GATEWAY_IDS = Object.freeze(PROVIDER_GATEWAYS.map((g) => g.id));++/** The registry row for a gateway id, or `null` for anything else. */+export const gatewayById = (id) => PROVIDER_GATEWAYS.find((g) => g.id === id) || null;++/**+ * The gateway a provider record opts into, or `null`.+ *+ * Reads the generic `gatewayBacked: '<id>'` marker first, then each row's+ * legacy per-gateway boolean (`orcarouterBacked`) — records predating the+ * registry keep resolving, forever, with no migration.+ */+export function gatewayForProvider(provider) {+ if (!provider || typeof provider !== 'object') return null;+ const declared = gatewayById(provider.gatewayBacked);+ if (declared) return declared;+ return PROVIDER_GATEWAYS.find((g) => g.legacyMarker && provider[g.legacyMarker] === true) || null;+}++/** True when this provider is an OpenCode wrapper front-ending any gateway. */+export const isGatewayBackedProvider = (provider) => gatewayForProvider(provider) !== null;diff --git a/server/lib/aiToolkit/internal/modelFetchers.js b/server/lib/aiToolkit/internal/modelFetchers.jsindex e5280d2c98..f168c58e38 100644--- a/server/lib/aiToolkit/internal/modelFetchers.js+++ b/server/lib/aiToolkit/internal/modelFetchers.js@@ -40,6 +40,7 @@import { ANTIGRAVITY_TUI_ID, isAntigravityCommand } from './antigravity.js';import { CURSOR_TUI_ID, isCursorCommand } from './cursor.js';import { isOllamaBackedProvider, ollamaBaseFromProvider } from './ollamaBacked.js';+import { isGatewayBackedProvider } from './gateways.js';const displayName = (provider) => String(provider?.name || '').toLowerCase();@@ -99,12 +100,14 @@ export const MODEL_FETCHERS = [fetch: '_fetchSglangModels',},{- key: 'orcarouter',- // OrcaRouter-backed OpenCode wrappers probe the sibling API provider's- // OpenAI-compatible `/models` endpoint, never `opencode models`.- cliMatch: (p) => p?.orcarouterBacked === true,- tuiMatch: (p) => p?.orcarouterBacked === true,- fetch: '_fetchOrcaRouterModels',+ key: 'gateway',+ // A gateway-backed OpenCode wrapper (OrcaRouter, OpenRouter — see+ // ./gateways.js) probes its sibling API provider's OpenAI-compatible+ // `/models` endpoint, never `opencode models`. ONE row for every gateway:+ // they differ only in base URL and key, which the provider record carries.+ cliMatch: isGatewayBackedProvider,+ tuiMatch: isGatewayBackedProvider,+ fetch: '_fetchGatewayModels',},{key: 'cursor',diff --git a/server/lib/aiToolkit/internal/modelFetchers.test.js b/server/lib/aiToolkit/internal/modelFetchers.test.jsindex 8c0bc20259..60a7fe7e26 100644--- a/server/lib/aiToolkit/internal/modelFetchers.test.js+++ b/server/lib/aiToolkit/internal/modelFetchers.test.js@@ -21,6 +21,9 @@ const SHIPPED_REFRESHABLE = ['opencode-llama-tui','opencode-mtplx', 'opencode-mtplx-tui', 'opencode-ollama', 'opencode-ollama-tui','opencode-orcarouter', 'opencode-orcarouter-tui', 'orcarouter',+ // Every hosted gateway refreshes through the same sibling `/models` probe —+ // one MODEL_FETCHERS row covers all of them (internal/gateways.js).+ 'opencode-openrouter', 'opencode-openrouter-tui', 'openrouter','opencode-vllm', 'opencode-vllm-tui',// SGLang publishes its served catalog through the same OpenAI-compatible// `/v1/models` contract as the vLLM pair, so its wrappers refresh too.diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex c8fce21f38..e0643671d0 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -21,11 +21,12 @@ import {parseCursorModelList,} from './internal/cursor.js';import { isOllamaBackedProvider, ollamaBaseFromProvider } from './internal/ollamaBacked.js';+import { gatewayForProvider, isGatewayBackedProvider } from './internal/gateways.js';import { canRefreshModels, ollamaRefreshGroupKey, resolveModelFetcher } from './internal/modelFetchers.js';// Re-exported (rather than defined here) so the model-fetcher table can key its// ollama row on the same predicate without importing back into this module.-export { isOllamaBackedProvider };+export { isOllamaBackedProvider, isGatewayBackedProvider };// Groups providers that share one daemon + one probe shape, so a host fanning a// refresh across them can fetch once instead of once per provider. The base-URL// normalizer it keys on stays internal — the group key IS the contract, and an@@ -39,13 +40,18 @@ export { canRefreshModels };const __dirname = dirname(fileURLToPath(import.meta.url));const DEFAULT_SAMPLE_PATH = join(__dirname, 'defaults/providers.sample.json');-// OpenCode OrcaRouter wrappers intentionally keep no key in their persisted+// Gateway-backed OpenCode wrappers intentionally keep no key in their persisted// record. Attach the sibling API key only to execution-time copies, and make// the property non-enumerable so provider responses and provider writes cannot// accidentally expose or persist it.-function withOrcaRouterApiKey(provider, providers) {- const siblingKey = providers?.orcarouter?.apiKey;- if (provider?.orcarouterBacked !== true || provider.apiKey || !siblingKey) return provider;+//+// The sibling is looked up by the wrapper's OWN gateway id (internal/gateways.js),+// never a hardcoded one — an OrcaRouter key must not leak into an OpenRouter+// wrapper, which would send a secret to the wrong host.+function withGatewayApiKey(provider, providers) {+ const gateway = gatewayForProvider(provider);+ const siblingKey = gateway ? providers?.[gateway.id]?.apiKey : null;+ if (!gateway || provider.apiKey || !siblingKey) return provider;const executionProvider = { ...provider };Object.defineProperty(executionProvider, 'apiKey', {value: siblingKey,@@ -548,14 +554,14 @@ export function createProviderService(config = {}) {async getProviderById(id) {const data = await loadProviders();const provider = data.providers[id];- return provider ? withOrcaRouterApiKey(provider, data.providers) : null;+ return provider ? withGatewayApiKey(provider, data.providers) : null;},async getActiveProvider() {const data = await loadProviders();if (!data.activeProvider) return null;const provider = data.providers[data.activeProvider];- return provider ? withOrcaRouterApiKey(provider, data.providers) : null;+ return provider ? withGatewayApiKey(provider, data.providers) : null;},async setActiveProvider(id) {@@ -615,6 +621,11 @@ export function createProviderService(config = {}) {// PortOS-owned launch line): preserve the marker so OpenCode receives the// `sglang/` namespace and model refresh probes the container....(providerData.sglangBacked === true ? { sglangBacked: true } : {}),+ // Hosted gateway markers: the generic one plus the legacy per-gateway+ // boolean, both preserved so a record written by any version keeps+ // resolving through internal/gateways.js.+ ...(typeof providerData.gatewayBacked === 'string' && providerData.gatewayBacked+ ? { gatewayBacked: providerData.gatewayBacked } : {}),...(providerData.orcarouterBacked === true ? { orcarouterBacked: true } : {}),// Explicit opt-in to send the API key to an arbitrary (non-local,// non-allowlisted) endpoint — see internal/endpointGuard.js. Only@@ -675,7 +686,7 @@ export function createProviderService(config = {}) {async testProvider(id) {const data = await loadProviders();- const provider = withOrcaRouterApiKey(data.providers[id], data.providers);+ const provider = withGatewayApiKey(data.providers[id], data.providers);if (!provider) {return { success: false, error: 'Provider not found' };@@ -809,7 +820,7 @@ export function createProviderService(config = {}) {*/async fetchProviderModels(id) {const data = await loadProviders();- const provider = withOrcaRouterApiKey(data.providers[id], data.providers);+ const provider = withGatewayApiKey(data.providers[id], data.providers);if (!provider) {return null;@@ -1127,8 +1138,8 @@ export function createProviderService(config = {}) {return this._refreshAPIProviderModels(provider);},- /** Fetch the OrcaRouter catalog for its OpenCode CLI/TUI wrappers. */- async _fetchOrcaRouterModels(provider) {+ /** Fetch a hosted gateway's catalog for its OpenCode CLI/TUI wrappers. */+ async _fetchGatewayModels(provider) {return this._refreshAPIProviderModels(provider);},diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex a4d53241ce..ae4b595538 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -124,9 +124,14 @@ export const providerSchema = z.object({// `vllmBacked`: a different engine, a different port, a different tool-call// parser, and an API key that is optional rather than required.sglangBacked: z.boolean().optional(),- // Marks an OpenCode CLI/TUI wrapper for the OrcaRouter OpenAI-compatible- // gateway. Its API key is read from the sibling `orcarouter` API record at- // spawn/refresh time and is never stored in this wrapper's config.+ // Marks an OpenCode CLI/TUI wrapper for a hosted OpenAI-compatible gateway+ // ('orcarouter', 'openrouter' — see internal/gateways.js). Its API key is read+ // from the sibling API record of the SAME id at spawn/refresh time and is+ // never stored in this wrapper's config.+ gatewayBacked: z.string().optional(),+ // Legacy per-gateway marker, superseded by `gatewayBacked` and still read+ // forever — stored records are never rewritten (installs upgrade on their own+ // schedule, so an older peer/version must keep resolving its own data).orcarouterBacked: z.boolean().optional(),// Explicit opt-in to attach the provider's API key to an arbitrary// (non-local, non-allowlisted) endpoint. Guards against SSRF / keydiff --git a/server/lib/cliChildEnv.js b/server/lib/cliChildEnv.jsindex 3e00d9d043..bed8593a26 100644--- a/server/lib/cliChildEnv.js+++ b/server/lib/cliChildEnv.js@@ -43,6 +43,7 @@import { withSpawnCwdEnv } from './spawnCwd.js';import { buildOpencodeEnvVars } from './opencodeConfig.js';import { getOpencodeLocalProviderNamespace, isClaudeCommand } from './providerModels.js';+import { isGatewayNamespace } from './providerGateways.js';import { agentGuardEnv } from './agentGuard/index.js';// Claude Code defaults to 32K output tokens. Thinking-capable local models can@@ -62,13 +63,13 @@ const CLAUDE_LOCAL_MAX_OUTPUT_TOKENS = '65536';* Anthropic-compatible `/v1/messages` endpoint, so a `claude` binary drives it* exactly the way it drives Ollama, and the 32K-output wedge above is a* property of "local thinking-capable model behind the Claude binary", not of- * Ollama specifically. `orcarouter` is excluded — it is a hosted gateway whose- * upstream models own their own budgets, the same carve-out `localRuntimeKind`- * makes.+ * Ollama specifically. Hosted gateways (`providerGateways.js`) are excluded —+ * their upstream models own their own budgets, the same carve-out+ * `localRuntimeKind` makes.*/function isLocalBackedClaude(provider) {const namespace = getOpencodeLocalProviderNamespace(provider);- return !!namespace && namespace !== 'orcarouter' && isClaudeCommand(provider?.command);+ return !!namespace && !isGatewayNamespace(namespace) && isClaudeCommand(provider?.command);}function claudeLocalEnvDefaults(provider) {@@ -102,7 +103,7 @@ function claudeLocalEnvDefaults(provider) {* @param {object} options* @param {object|null} [options.before] - layered first, so `provider.envVars`* overrides it (forgeTokenEnv, claudeSettingsEnv).- * @param {{command?:string, envVars?:object, models?:string[], defaultModel?:string|null, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean, orcarouterBacked?:boolean, thinking?:boolean}|null} [options.provider]+ * @param {{command?:string, envVars?:object, models?:string[], defaultModel?:string|null, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean, gatewayBacked?:string, orcarouterBacked?:boolean, thinking?:boolean}|null} [options.provider]* @param {string|null} [options.model] - the model being run this invocation,* unioned into the OpenCode declared-models map. Omit when the site has no* per-call model — `provider.defaultModel` is always declared regardless.diff --git a/server/lib/index.js b/server/lib/index.jsindex 8de3583fb2..5caeb739a9 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -318,6 +318,7 @@ export * from './navManifest.js';export * from './usageRange.js';export * from './subscriptionSavings.js';export * from './providerFamilies.js';+export * from './providerGateways.js';export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';export * from './postAdaptive.js';diff --git a/server/lib/localProviderRuntime.js b/server/lib/localProviderRuntime.jsindex ff5613a587..0c42884564 100644--- a/server/lib/localProviderRuntime.js+++ b/server/lib/localProviderRuntime.js@@ -30,6 +30,7 @@import { getOpencodeLocalProviderNamespace, isOpencodeCommand } from './providerModels.js';import { opencodeLocalBaseUrl } from './opencodeConfig.js';+import { isGatewayNamespace } from './providerGateways.js';// Default OpenAI-compatible ports for the two local backends PortOS manages. An// endpoint-only provider (no id/name) pointed at one of these on the local@@ -302,8 +303,9 @@ function opencodeConfiguredBaseUrl(provider, namespace) {* first and its endpoint/name only as a fallback.** The `*Backed` markers are authoritative — they are what the spawner itself- * keys on. `orcarouter` is deliberately excluded: it is an OpenCode local- * *namespace* but a remote hosted API, so there is no local daemon to check.+ * keys on. Hosted gateways (`providerGateways.js`) are deliberately excluded:+ * each is an OpenCode local *namespace* but a remote hosted API, so there is no+ * local daemon to check.** @param {object|null|undefined} provider* @returns {'llama'|'ollama'|'lmstudio'|'mtplx'|'vllm'|'sglang'|null}@@ -313,7 +315,7 @@ export function localRuntimeKind(provider) {// Marker-based, NOT command-based: this also resolves `claude-ollama`, which// carries `ollamaBacked` without being an OpenCode provider.const namespace = getOpencodeLocalProviderNamespace(provider);- if (namespace && namespace !== 'orcarouter') return namespace;+ if (namespace && !isGatewayNamespace(namespace)) return namespace;return localBackendForProvider(provider);}diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.jsindex b31e9f05b8..949095fc2b 100644--- a/server/lib/opencodeConfig.js+++ b/server/lib/opencodeConfig.js@@ -19,6 +19,7 @@*/import { getOpencodeLocalProviderNamespace, isOpencodeCommand } from './providerModels.js';+import { PROVIDER_GATEWAYS, PROVIDER_GATEWAY_IDS, gatewayById, isGatewayNamespace } from './providerGateways.js';import { PORTS } from './ports.js';const LLAMA_SERVER_BASE_URL = `http://127.0.0.1:${PORTS.LLAMA_SERVER}/v1`;@@ -56,11 +57,14 @@ const OPENCODE_LOCAL_BASE_PROVIDERS = {name: 'SGLang Qwen3.8-27B (local)',options: { baseURL: SGLANG_QWEN_BASE_URL },},- orcarouter: {+ // Every hosted gateway (`providerGateways.js`) declares the same+ // OpenAI-compatible shape, so the rows are generated rather than hand-listed —+ // a new gateway is one registry row, not an edit here.+ ...Object.fromEntries(PROVIDER_GATEWAYS.map((gateway) => [gateway.id, {npm: '@ai-sdk/openai-compatible',- name: 'OrcaRouter',- options: { baseURL: 'https://api.orcarouter.ai/v1' },- },+ name: gateway.label,+ options: { baseURL: gateway.baseURL },+ }])),};/**@@ -68,7 +72,7 @@ const OPENCODE_LOCAL_BASE_PROVIDERS = {* — what a spawned OpenCode talks to when the provider stores no config of its* own. Read by `lib/localProviderRuntime.js` so the readiness probe and the* spawn agree on the endpoint instead of keeping two copies of these ports.- * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'} providerKey+ * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|string} providerKey* @returns {string|null}*/export const opencodeLocalBaseUrl = (providerKey) =>@@ -79,7 +83,7 @@ export const opencodeLocalBaseUrl = (providerKey) =>* else here is an unauthenticated loopback daemon, and attaching a key to those* would put a secret into a config file that never needed one.*/-const KEY_BEARING_NAMESPACES = new Set(['orcarouter', 'vllm', 'sglang']);+const KEY_BEARING_NAMESPACES = new Set(['vllm', 'sglang', ...PROVIDER_GATEWAY_IDS]);const localProviderBase = (providerKey) => {if (!Object.hasOwn(OPENCODE_LOCAL_BASE_PROVIDERS, providerKey)) {@@ -91,8 +95,11 @@ const localProviderBase = (providerKey) => {// Strip the selected provider namespace so a model id can key that provider's// config `models` map. Idempotent for an already-bare id. A slash-bearing model// id (`hf.co/user/model:tag`) retains every slash after the leading namespace.+// A hosted gateway's model ids are already `vendor/model` and are NEVER+// namespace-prefixed in storage, so stripping would eat a real id segment+// (`anthropic/claude-sonnet-4` is the key, not `claude-sonnet-4`).const stripProviderPrefix = (id, providerKey) =>- providerKey === 'orcarouter' ? id :+ isGatewayNamespace(providerKey) ? id :typeof id === 'string' && id.startsWith(`${providerKey}/`)? id.slice(providerKey.length + 1): id;@@ -101,7 +108,7 @@ const stripProviderPrefix = (id, providerKey) =>* Normalize an id or list of ids to the unique, non-empty, prefix-stripped bare* model ids that key the OpenCode `models` map.* @param {string|string[]|null|undefined} models- * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'} [providerKey='ollama']+ * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|string} [providerKey='ollama']* @returns {string[]}*/export function toBareModelIds(models, providerKey = 'ollama') {@@ -122,9 +129,9 @@ export function toBareModelIds(models, providerKey = 'ollama') {* these entries speaks the OpenAI chat-completions shape, so they are emitted* for all of them. The thinking toggle is NOT: Ollama takes its own native* `think` boolean, while a llama.cpp / MTPLX / vLLM OpenAI endpoint routes it- * through the chat template (`chat_template_kwargs.enable_thinking`). OrcaRouter- * 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+ * 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.** A missing entry is not a missing checkbox — `buildAgentGeneration` bails on it@@ -132,7 +139,7 @@ export function toBareModelIds(models, providerKey = 'ollama') {* how vLLM shipped with no generation controls at all (#4765). Every local* runtime OpenCode can be pointed at needs a row here; `opencodeConfig.test.js`* walks `LOCAL_RUNTIMES` to make a missing one fail.- * @type {Record<'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter', 'think'|'chatTemplate'|null>}+ * @type {Record<string, 'think'|'chatTemplate'|null>}*/const THINKING_STYLE = {ollama: 'think',@@ -147,7 +154,10 @@ const THINKING_STYLE = {// tool-call format reliable), so the control has to exist for the operator to// set — but nothing here SEEDS `thinking: false`, per #4716.sglang: 'chatTemplate',- orcarouter: null,+ // 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).+ ...Object.fromEntries(PROVIDER_GATEWAY_IDS.map((id) => [id, null])),};const numberInRange = (value, min, max) => {@@ -174,7 +184,7 @@ const readBoolean = (value) =>* the provider.** @param {{temperature?:unknown, topP?:unknown, thinking?:unknown, effort?:unknown}|null|undefined} generation- * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'} providerKey+ * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|string} providerKey* @returns {object|null}*/export function buildAgentGeneration(generation, providerKey) {@@ -218,7 +228,7 @@ export function buildAgentGeneration(generation, providerKey) {** @param {string|string[]|null|undefined} models* @param {object|null} [base] - existing config to merge into (a fresh clone is made)- * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'} [providerKey='ollama']+ * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|string} [providerKey='ollama']* @returns {object} OpenCode config object*/export function buildOpencodeConfig(models, base = null, providerKey = 'ollama', generation = null) {@@ -257,7 +267,7 @@ export function buildOpencodeConfig(models, base = null, providerKey = 'ollama',** @param {string|string[]|null|undefined} models* @param {object|null} [base] - existing config to merge into- * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'} [providerKey='ollama']+ * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|string} [providerKey='ollama']* @returns {string} JSON string for OPENCODE_CONFIG_CONTENT*/export function buildOpencodeConfigContent(models, base = null, providerKey = 'ollama', generation = null) {@@ -277,7 +287,7 @@ export function buildOpencodeConfigContent(models, base = null, providerKey = 'o* model, and the model being run this invocation — so whichever namespaced* `--model` the spawner passes is always accepted.*- * @param {{command?:string, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean, orcarouterBacked?:boolean, models?:string[], defaultModel?:string|null, apiKey?:string, orcarouterApiKey?:string, envVars?:object}} provider+ * @param {{command?:string, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean, gatewayBacked?:string, orcarouterBacked?:boolean, models?:string[], defaultModel?:string|null, apiKey?:string, orcarouterApiKey?:string, envVars?:object}} provider* @param {string|null|undefined} model - the model being run (may differ from defaultModel)* @returns {{OPENCODE_CONFIG_CONTENT?: string}} env vars to merge*/@@ -304,13 +314,18 @@ export function buildOpencodeEnvVars(provider, model) {model,];const config = buildOpencodeConfig(ids, base, providerKey, provider);- // Both key-bearing namespaces read the SAME `provider.apiKey` field; the- // OrcaRouter alias is legacy. vLLM's compose stack is started with- // `VLLM_API_KEY`, so a wrapper pointed at it needs the key on- // `options.apiKey` exactly the way the hosted gateway does — the endpoint is- // loopback, but the server still 401s without it.+ // Every key-bearing namespace reads the SAME `provider.apiKey` field; a+ // gateway's `legacyApiKeyField` (`orcarouterApiKey`) is an older alias kept+ // readable forever. vLLM's compose stack is started with `VLLM_API_KEY`, so a+ // wrapper pointed at it needs the key on `options.apiKey` exactly the way a+ // hosted gateway does — the endpoint is loopback, but the server still 401s+ // without it.+ // Keyed off the RESOLVED namespace, not the record's marker: a malformed+ // record carrying both a local marker and a gateway marker resolves to the+ // local namespace above, and must not then export a gateway key env var.+ const gateway = gatewayById(providerKey);const apiKey = KEY_BEARING_NAMESPACES.has(providerKey)- ? (provider?.apiKey || (providerKey === 'orcarouter' ? provider?.orcarouterApiKey : null))+ ? (provider?.apiKey || (gateway?.legacyApiKeyField ? provider?.[gateway.legacyApiKeyField] : null)): null;if (apiKey) {config.provider[providerKey].options = {@@ -320,6 +335,6 @@ export function buildOpencodeEnvVars(provider, model) {}return {OPENCODE_CONFIG_CONTENT: JSON.stringify(config),- ...(apiKey && providerKey === 'orcarouter' ? { ORCAROUTER_API_KEY: apiKey } : {}),+ ...(apiKey && gateway ? { [gateway.apiKeyEnv]: apiKey } : {}),};}diff --git a/server/lib/providerGateways.js b/server/lib/providerGateways.jsnew file mode 100644index 0000000000..9198983c64--- /dev/null+++ b/server/lib/providerGateways.js@@ -0,0 +1,98 @@+/**+ * `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode+ * CLI/TUI wrapper can front-end (OrcaRouter, OpenRouter).+ *+ * Before this file, OrcaRouter wasn't *a* gateway — it was *the* gateway: the+ * boolean `orcarouterBacked` and the literal id `'orcarouter'` were 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 "this is NOT a local runtime" carve-outs).+ * Adding a second gateway that way would have doubled a copy-paste axis — the+ * same pressure `providerVendors.js` was created to relieve (#3618). Every+ * dispatch site now asks this registry instead.+ *+ * A gateway is distinct from a *local runtime* (`ollamaBacked`, `vllmBacked`,+ * `sglangBacked`, …) in three ways every consumer keys on:+ * - it is REMOTE, so there is no daemon to probe (`localRuntimeKind` and+ * `isLocalBackedClaude` both exclude it);+ * - it always AUTHENTICATES, and the wrapper deliberately stores no key — the+ * sibling API record with the same id as the gateway owns it;+ * - its upstream models own their own reasoning switch, so it exposes no+ * thinking toggle (`THINKING_STYLE[<gateway>] === null`).+ *+ * Dependency-light on purpose (mirrors `providerVendors.js` / `cliProviderArgs.js`):+ * it imports nothing, so it stays importable from `providerModels.js`, which the+ * standalone autofixer process pulls in.+ *+ * **Three copies of this table exist, by architecture, and must stay in lockstep:**+ * 1. this file — the PortOS server;+ * 2. `aiToolkit/internal/gateways.js` — the vendored toolkit, which may not+ * import out of its own directory (see `aiToolkit/CLAUDE.md`);+ * `providerGateways.parity.test.js` fails when the two drift;+ * 3. `client/src/utils/providers.js` — the browser, which cannot import server+ * code at all.+ */++/**+ * @typedef {object} ProviderGateway+ * @property {string} id — the OpenCode provider namespace, the `gatewayBacked`+ * marker value, AND the id of the sibling `api` record holding the key. One+ * string for all three on purpose: the sibling lookup is `providers[gateway.id]`.+ * @property {string} label — human name for UI copy and prerequisite labels.+ * @property {string} baseURL — the OpenAI-compatible endpoint.+ * @property {string} apiKeyEnv — the env var the spawner exports for OpenCode.+ * @property {string} [legacyMarker] — the pre-registry per-gateway boolean field+ * (`orcarouterBacked`). Records written before `gatewayBacked` existed still+ * carry it, and installs upgrade on their own schedule, so this is read+ * FOREVER — no migration rewrites stored records.+ * @property {string} [legacyApiKeyField] — a pre-registry alias for the wrapper's+ * own key field.+ */++/** @type {readonly ProviderGateway[]} */+export const PROVIDER_GATEWAYS = Object.freeze([+ Object.freeze({+ id: 'orcarouter',+ label: 'OrcaRouter',+ baseURL: 'https://api.orcarouter.ai/v1',+ apiKeyEnv: 'ORCAROUTER_API_KEY',+ legacyMarker: 'orcarouterBacked',+ legacyApiKeyField: 'orcarouterApiKey',+ }),+ Object.freeze({+ id: 'openrouter',+ label: 'OpenRouter',+ baseURL: 'https://openrouter.ai/api/v1',+ apiKeyEnv: 'OPENROUTER_API_KEY',+ }),+]);++/** Every gateway id — the namespace key space `opencodeConfig.js` extends. */+export const PROVIDER_GATEWAY_IDS = Object.freeze(PROVIDER_GATEWAYS.map((g) => g.id));++/** The registry row for a gateway id, or `null` for anything else. */+export const gatewayById = (id) => PROVIDER_GATEWAYS.find((g) => g.id === id) || null;++/** Is this OpenCode provider namespace a hosted gateway rather than a local runtime? */+export const isGatewayNamespace = (namespace) => PROVIDER_GATEWAY_IDS.includes(namespace);++/**+ * The gateway a provider record opts into, or `null`.+ *+ * Reads the generic `gatewayBacked: '<id>'` marker first, then each row's+ * `legacyMarker` boolean — so a record stored before this registry existed+ * resolves identically and needs no migration. Registry order breaks a tie on a+ * malformed record carrying two markers, preserving the legacy if-chain outcome.+ *+ * @param {{gatewayBacked?:string, [marker:string]:unknown}|null|undefined} provider+ * @returns {ProviderGateway|null}+ */+export function gatewayForProvider(provider) {+ if (!provider || typeof provider !== 'object') return null;+ const declared = gatewayById(provider.gatewayBacked);+ if (declared) return declared;+ return PROVIDER_GATEWAYS.find((g) => g.legacyMarker && provider[g.legacyMarker] === true) || null;+}++/** `gatewayForProvider`, reduced to the id (which is also the OpenCode namespace). */+export const gatewayIdForProvider = (provider) => gatewayForProvider(provider)?.id ?? null;diff --git a/server/lib/providerGateways.parity.test.js b/server/lib/providerGateways.parity.test.jsnew file mode 100644index 0000000000..d2c2a4d7f8--- /dev/null+++ b/server/lib/providerGateways.parity.test.js@@ -0,0 +1,37 @@+/**+ * The gateway registry exists in three places by architecture — the vendored+ * `aiToolkit/` may not import out of its own directory, and the browser cannot+ * import server code at all. This suite pins the two SERVER copies together so+ * a new gateway added to one is never silently missing from the other (which+ * would show up as a wrapper that spawns fine but can never refresh its models,+ * or vice versa).+ *+ * The client copy (`client/src/utils/providers.js`) is deliberately NOT imported+ * here: a server suite that imports a client module drags the client's deps into+ * the server CI job. It carries a "keep in lockstep" comment naming both server+ * copies instead.+ */+import { describe, it, expect } from 'vitest';+import { PROVIDER_GATEWAYS as SERVER_GATEWAYS } from './providerGateways.js';+import { PROVIDER_GATEWAYS as TOOLKIT_GATEWAYS, gatewayForProvider as toolkitGatewayFor } from './aiToolkit/internal/gateways.js';+import { gatewayForProvider as serverGatewayFor } from './providerGateways.js';++describe('providerGateways ↔ aiToolkit/internal/gateways parity', () => {+ it('declares the same rows, in the same order', () => {+ expect(TOOLKIT_GATEWAYS).toEqual(SERVER_GATEWAYS);+ });++ it('resolves the same provider records', () => {+ const records = [+ { gatewayBacked: 'openrouter' },+ { gatewayBacked: 'orcarouter' },+ { orcarouterBacked: true },+ { ollamaBacked: true },+ { gatewayBacked: 'not-a-gateway' },+ null,+ ];+ for (const record of records) {+ expect(toolkitGatewayFor(record)).toEqual(serverGatewayFor(record));+ }+ });+});diff --git a/server/lib/providerGateways.test.js b/server/lib/providerGateways.test.jsnew file mode 100644index 0000000000..a2ea558dd2--- /dev/null+++ b/server/lib/providerGateways.test.js@@ -0,0 +1,90 @@+import { describe, it, expect } from 'vitest';+import {+ PROVIDER_GATEWAYS,+ PROVIDER_GATEWAY_IDS,+ gatewayById,+ gatewayForProvider,+ gatewayIdForProvider,+ isGatewayNamespace,+} from './providerGateways.js';+import { getOpencodeLocalProviderNamespace, prefixOpencodeModel } from './providerModels.js';++describe('providerGateways', () => {+ it('ships both gateways with a complete row', () => {+ expect(PROVIDER_GATEWAY_IDS).toEqual(['orcarouter', 'openrouter']);+ for (const gateway of PROVIDER_GATEWAYS) {+ expect(gateway.label).toBeTruthy();+ expect(gateway.baseURL).toMatch(/^https:\/\//);+ expect(gateway.apiKeyEnv).toMatch(/^[A-Z0-9_]+$/);+ }+ });++ it('resolves the generic gatewayBacked marker', () => {+ expect(gatewayIdForProvider({ gatewayBacked: 'openrouter' })).toBe('openrouter');+ expect(gatewayIdForProvider({ gatewayBacked: 'orcarouter' })).toBe('orcarouter');+ });++ // Records written before the registry existed carry the per-gateway boolean.+ // Installs upgrade on their own schedule and nothing rewrites stored records,+ // so this must keep resolving forever.+ it('still resolves the legacy orcarouterBacked boolean', () => {+ expect(gatewayIdForProvider({ orcarouterBacked: true })).toBe('orcarouter');+ expect(getOpencodeLocalProviderNamespace({ orcarouterBacked: true })).toBe('orcarouter');+ });++ it('returns null for a non-gateway provider', () => {+ expect(gatewayForProvider({ ollamaBacked: true })).toBeNull();+ expect(gatewayForProvider({ gatewayBacked: 'not-a-gateway' })).toBeNull();+ expect(gatewayForProvider(null)).toBeNull();+ expect(gatewayForProvider('opencode')).toBeNull();+ expect(gatewayById('nope')).toBeNull();+ });++ // A malformed record carrying both a local marker and a gateway marker keeps+ // its legacy LOCAL outcome — the pre-registry if-chain checked local first.+ it('prefers a local runtime marker over a gateway marker', () => {+ expect(getOpencodeLocalProviderNamespace({ ollamaBacked: true, gatewayBacked: 'openrouter' })).toBe('ollama');+ });++ it('classifies namespaces', () => {+ expect(isGatewayNamespace('openrouter')).toBe(true);+ expect(isGatewayNamespace('orcarouter')).toBe(true);+ expect(isGatewayNamespace('ollama')).toBe(false);+ expect(isGatewayNamespace(null)).toBe(false);+ });+});++describe('prefixOpencodeModel — gateway namespacing', () => {+ const openrouter = { command: 'opencode', gatewayBacked: 'openrouter' };+ const orcarouter = { command: 'opencode', orcarouterBacked: true };++ // OpenRouter ids are ALREADY `vendor/model`, and OpenCode splits+ // provider/model on the first slash only, so the namespaced form is doubled.+ it('namespaces a vendor-qualified OpenRouter id', () => {+ expect(prefixOpencodeModel(openrouter, 'anthropic/claude-sonnet-4'))+ .toBe('openrouter/anthropic/claude-sonnet-4');+ });++ // The trap a single-prefix guard falls into: `openrouter/auto` is OpenRouter's+ // own auto-router MODEL id, not an already-namespaced id. Emitting it+ // unchanged would resolve to the model `auto`, which does not exist.+ it('namespaces OpenRouter\'s own auto-router id rather than treating it as prefixed', () => {+ expect(prefixOpencodeModel(openrouter, 'openrouter/auto')).toBe('openrouter/openrouter/auto');+ });++ it('is idempotent on an already-doubled id', () => {+ expect(prefixOpencodeModel(openrouter, 'openrouter/openrouter/auto')).toBe('openrouter/openrouter/auto');+ expect(prefixOpencodeModel(orcarouter, 'orcarouter/orcarouter/auto')).toBe('orcarouter/orcarouter/auto');+ });++ it('preserves the OrcaRouter behavior it generalized', () => {+ expect(prefixOpencodeModel(orcarouter, 'orcarouter/auto')).toBe('orcarouter/orcarouter/auto');+ });++ // A local runtime keeps the single-prefix rule — its stored ids are bare.+ it('leaves local-runtime namespacing single-prefixed', () => {+ const ollama = { command: 'opencode', ollamaBacked: true };+ expect(prefixOpencodeModel(ollama, 'qwen3:8b')).toBe('ollama/qwen3:8b');+ expect(prefixOpencodeModel(ollama, 'ollama/qwen3:8b')).toBe('ollama/qwen3:8b');+ });+});diff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex c4b50363c7..4e421105e5 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -3,6 +3,8 @@* Mirrors the constants in client/src/utils/providers.js — keep in sync.*/+import { gatewayIdForProvider, isGatewayNamespace } from './providerGateways.js';+export const CODEX_CONFIGURED_DEFAULT = 'codex-configured-default';export const ANTIGRAVITY_CONFIGURED_DEFAULT = 'antigravity-configured-default';// Grok Build CLI/TUI: PortOS does not select a model — the local `grok` binary@@ -564,8 +566,16 @@ export function prefixOpencodeModel(provider, model) {const namespace = getOpencodeLocalProviderNamespace(provider);if (!isOpencodeCommand(provider?.command) || !namespace || !model) return model;const id = String(model);- if (namespace === 'orcarouter') {- return id.startsWith('orcarouter/orcarouter/') ? id : `orcarouter/${id}`;+ if (isGatewayNamespace(namespace)) {+ // A gateway model id is ALREADY `vendor/model` (`anthropic/claude-sonnet-4`,+ // `orcarouter/auto`), and OpenCode splits provider/model on the FIRST slash+ // only — so the namespaced form is legitimately doubled+ // (`openrouter/anthropic/claude-sonnet-4`, `openrouter/openrouter/auto`).+ // Guard on the DOUBLED prefix, never the single one: a single-prefix check+ // would read OpenRouter's own auto-router id `openrouter/auto` as+ // already-namespaced and emit it unchanged, which OpenCode resolves to the+ // model `auto` — a model that does not exist.+ return id.startsWith(`${namespace}/${namespace}/`) ? id : `${namespace}/${id}`;}return id.startsWith(`${namespace}/`) ? id : `${namespace}/${id}`;}@@ -575,8 +585,8 @@ export function prefixOpencodeModel(provider, model) {* opted into one. Structural markers avoid deriving a backend from an editable* display name or endpoint and preserve the legacy Ollama outcome if a malformed* record carries both markers.- * @param {{ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean, orcarouterBacked?:boolean}|null|undefined} provider- * @returns {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'|null}+ * @param {{ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean, gatewayBacked?:string, orcarouterBacked?:boolean}|null|undefined} provider+ * @returns {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|string|null}*/export function getOpencodeLocalProviderNamespace(provider) {if (provider?.ollamaBacked === true) return 'ollama';@@ -584,8 +594,10 @@ export function getOpencodeLocalProviderNamespace(provider) {if (provider?.llamaBacked === true) return 'llama';if (provider?.vllmBacked === true) return 'vllm';if (provider?.sglangBacked === true) return 'sglang';- if (provider?.orcarouterBacked === true) return 'orcarouter';- return null;+ // Hosted gateways (`providerGateways.js`) come LAST so a malformed record+ // carrying both a local marker and a gateway marker keeps its legacy local+ // outcome, exactly as the old if-chain did with `orcarouterBacked`.+ return gatewayIdForProvider(provider);}/**diff --git a/server/lib/providerPrerequisites.js b/server/lib/providerPrerequisites.jsindex 69d605d99e..aa360283ee 100644--- a/server/lib/providerPrerequisites.js+++ b/server/lib/providerPrerequisites.js@@ -25,8 +25,9 @@* **SENTINEL DISCIPLINE.** `runtime` is `null` for NOT PROBED, which must never* read as "missing" — an unprobed CLI would otherwise take every perfectly* installed provider out of the fallback chain the first time a run failed.- * Same for `orcaRouterKeySet`: `false` is "the sibling holds no key", `null` is- * "the caller cannot tell". Only a definite negative produces a finding.+ * Same for each entry of `gatewayKeySet`: `false` is "that gateway's sibling API+ * record holds no key", `null`/absent is "the caller cannot tell". Only a+ * definite negative produces a finding.** Credentials carried in a secret env var (Bedrock, an Ollama auth token) stay* presentation-only here: the provider card resolves them from the sanitized@@ -37,6 +38,7 @@import { PROVIDER_TYPES } from './aiToolkit/constants.js';import { isLocalInstanceHost } from './localProviderRuntime.js';import { commandBasename } from './providerModels.js';+import { gatewayForProvider } from './providerGateways.js';/*** Hosts inside the trust boundary, where an unauthenticated OpenAI-compatible@@ -166,13 +168,13 @@ const providerHasApiKey = (provider) =>* @param {object} [options]* @param {object|null} [options.runtime] — the provider's entry of the runtimes* map. `null` = NOT PROBED (see the sentinel note at the top of this file).- * @param {boolean|null} [options.orcaRouterKeySet] — does the sibling- * `orcarouter` API provider hold the key an OpenCode OrcaRouter wrapper- * inherits at spawn time? `false` covers both "no key" and "sibling deleted";- * `null` is "cannot tell".+ * @param {Record<string, boolean|null>|null} [options.gatewayKeySet] — per gateway+ * id, does the sibling API provider of that id hold the key an OpenCode+ * wrapper inherits at spawn time? `false` covers both "no key" and "sibling+ * deleted"; `null`/absent is "cannot tell".* @returns {{met: boolean, missing: {code: string, label: string}[]}}*/-export const providerPrerequisites = (provider, { runtime = null, orcaRouterKeySet = null } = {}) => {+export const providerPrerequisites = (provider, { runtime = null, gatewayKeySet = null } = {}) => {const missing = [];if (runtime && runtime.installed === false) {@@ -185,10 +187,12 @@ export const providerPrerequisites = (provider, { runtime = null, orcaRouterKeyS&& !isPrivateNetworkEndpoint(provider?.endpoint)) {missing.push({ code: 'apiKey', label: 'API key is not set' });}- // OpenCode OrcaRouter wrappers normally inherit from the sibling API- // provider, but an explicitly stored wrapper key takes precedence at spawn.- if (provider?.orcarouterBacked === true && !providerHasApiKey(provider) && orcaRouterKeySet === false) {- missing.push({ code: 'inheritedApiKey', label: 'OrcaRouter API provider has no API key' });+ // A gateway-backed OpenCode wrapper normally inherits from the sibling API+ // provider of the same id, but an explicitly stored wrapper key takes+ // precedence at spawn.+ const gateway = gatewayForProvider(provider);+ if (gateway && !providerHasApiKey(provider) && gatewayKeySet?.[gateway.id] === false) {+ missing.push({ code: 'inheritedApiKey', label: `${gateway.label} API provider has no API key` });}return { met: missing.length === 0, missing };@@ -213,7 +217,7 @@ export const describeMissingPrerequisites = (missing) =>* can only ever save a doomed run. The credential findings are NOT in that* class. This module reads only the provider's own stored key, and a provider* can legitimately authenticate another way — a secret env var (Bedrock's AWS- * credentials, an Ollama auth token), or an OrcaRouter wrapper carrying its own+ * credentials, an Ollama auth token), or a gateway wrapper carrying its own* key rather than the sibling's. Routing on those would take working providers* out of the chain, so they stay presentation-only. The provider card may* report those credentials separately without changing the routing gate.diff --git a/server/lib/providerPrerequisites.test.js b/server/lib/providerPrerequisites.test.jsindex 1310821c9a..deb7ce69d9 100644--- a/server/lib/providerPrerequisites.test.js+++ b/server/lib/providerPrerequisites.test.js@@ -117,13 +117,28 @@ describe('providerPrerequisites', () => {expect(providerPrerequisites(api({ hasApiKey: false })).met).toBe(false);});+ // The legacy per-gateway boolean, which stored records still carry.it('reports an OrcaRouter wrapper whose sibling holds no key', () => {const wrapper = cli({ id: 'opencode-orcarouter', command: 'opencode', orcarouterBacked: true });- expect(providerPrerequisites(wrapper, { orcaRouterKeySet: false }).missing)+ expect(providerPrerequisites(wrapper, { gatewayKeySet: { orcarouter: false } }).missing).toEqual([{ code: 'inheritedApiKey', label: 'OrcaRouter API provider has no API key' }]);- expect(providerPrerequisites(wrapper, { orcaRouterKeySet: true }).met).toBe(true);- // null = cannot tell, which must never read as missing- expect(providerPrerequisites(wrapper, { orcaRouterKeySet: null }).met).toBe(true);+ expect(providerPrerequisites(wrapper, { gatewayKeySet: { orcarouter: true } }).met).toBe(true);+ // null = cannot tell, which must never read as missing — and so is an absent+ // entry (a collection that was never loaded).+ expect(providerPrerequisites(wrapper, { gatewayKeySet: { orcarouter: null } }).met).toBe(true);+ expect(providerPrerequisites(wrapper, { gatewayKeySet: null }).met).toBe(true);+ expect(providerPrerequisites(wrapper, {}).met).toBe(true);+ });++ it('reports an OpenRouter wrapper against its OWN sibling, naming that gateway', () => {+ const wrapper = cli({ id: 'opencode-openrouter', command: 'opencode', gatewayBacked: 'openrouter' });+ expect(providerPrerequisites(wrapper, { gatewayKeySet: { openrouter: false } }).missing)+ .toEqual([{ code: 'inheritedApiKey', label: 'OpenRouter API provider has no API key' }]);+ expect(providerPrerequisites(wrapper, { gatewayKeySet: { openrouter: true } }).met).toBe(true);+ // A DIFFERENT gateway's key must never satisfy this wrapper — that would be+ // a secret from the wrong host reading as the credential for this one.+ expect(providerPrerequisites(wrapper, { gatewayKeySet: { orcarouter: true, openrouter: false } }).missing)+ .toEqual([{ code: 'inheritedApiKey', label: 'OpenRouter API provider has no API key' }]);});it('does not demand the sibling key when the wrapper carries its own key', () => {@@ -133,14 +148,14 @@ describe('providerPrerequisites', () => {orcarouterBacked: true,apiKey: 'sk-example',});- expect(providerPrerequisites(wrapper, { orcaRouterKeySet: false }).met).toBe(true);+ expect(providerPrerequisites(wrapper, { gatewayKeySet: { orcarouter: false } }).met).toBe(true);});it('collects every finding rather than stopping at the first', () => {const wrapper = { id: 'x', type: 'api', endpoint: 'https://api.example.com', orcarouterBacked: true };const result = providerPrerequisites(wrapper, {runtime: { installed: false, label: 'OpenCode CLI' },- orcaRouterKeySet: false,+ gatewayKeySet: { orcarouter: false },});expect(result.missing.map((m) => m.code)).toEqual(['runtime', 'apiKey', 'inheritedApiKey']);});@@ -166,7 +181,7 @@ describe('blocksRouting', () => {it('does NOT act on the credential findings', () => {expect(blocksRouting(providerPrerequisites(api()).missing)).toBe(false);const wrapper = cli({ orcarouterBacked: true });- expect(blocksRouting(providerPrerequisites(wrapper, { orcaRouterKeySet: false }).missing)).toBe(false);+ expect(blocksRouting(providerPrerequisites(wrapper, { gatewayKeySet: { orcarouter: false } }).missing)).toBe(false);});it('is false for nothing missing, and for a non-array', () => {diff --git a/server/lib/validation.js b/server/lib/validation.jsindex ee0378e5f5..998284e05a 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -425,8 +425,14 @@ export const providerSchema = z.object({// Marks an OpenCode CLI/TUI wrapper for a separately started local SGLang// container (Qwen3.8-27B on a Hopper/Blackwell card).sglangBacked: z.boolean().optional(),- // Marks an OpenCode CLI/TUI wrapper for the OrcaRouter OpenAI-compatible- // gateway; the sibling API record owns its key.+ // Marks an OpenCode CLI/TUI wrapper for a hosted OpenAI-compatible gateway+ // ('orcarouter', 'openrouter' — see server/lib/providerGateways.js). The+ // sibling API record whose id equals this value owns the key.+ gatewayBacked: z.string().optional(),+ // Legacy per-gateway marker, superseded by `gatewayBacked`. Still accepted and+ // still READ (providerGateways.js resolves it), because records written before+ // the registry existed are never rewritten — installs upgrade on their own+ // schedule.orcarouterBacked: z.boolean().optional(),// Explicit opt-in to attach the API key to an arbitrary (non-local,// non-allowlisted) endpoint — mirrors the aiToolkit providerSchema. Guardsdiff --git a/server/services/providerPrerequisites.js b/server/services/providerPrerequisites.jsindex b92de66dd4..b251c51ce6 100644--- a/server/services/providerPrerequisites.js+++ b/server/services/providerPrerequisites.js@@ -34,25 +34,32 @@*/import { blocksRouting, describeMissingPrerequisites, providerPrerequisites, providerRuntimeKey } from '../lib/providerPrerequisites.js';+import { PROVIDER_GATEWAYS } from '../lib/providerGateways.js';import { getProviderRuntime, getProviderRuntimeStatuses, peekProviderRuntimeStatuses } from './providerRuntimeInstaller.js';/**- * Does the sibling `orcarouter` API provider hold the key an OpenCode- * OrcaRouter wrapper inherits at spawn time?+ * Per gateway id, does the sibling API provider of that id hold the key an+ * OpenCode wrapper inherits at spawn time?** `null` (cannot tell) when there is no provider collection to look in —* distinct from `false` ("looked, and the sibling has no key"), which is what a* present-but-keyless or deleted sibling gives. Accepts a raw map (keyed by id)* or a sanitized array.+ *+ * A map keyed by gateway id rather than one boolean, so a wrapper is only ever+ * judged against ITS OWN sibling — an OrcaRouter key must never satisfy an+ * OpenRouter wrapper.*/-const orcaRouterKeyState = (providers) => {+const gatewayKeyState = (providers) => {if (!providers || typeof providers !== 'object') return null;const entries = Array.isArray(providers) ? providers : Object.values(providers);// An EMPTY collection is "nothing loaded", not "the sibling is gone" — the// same `null`-vs-`false` distinction the whole module runs on.if (entries.length === 0) return null;- const sibling = entries.find((p) => p?.id === 'orcarouter');- return sibling?.hasApiKey === true || Boolean(sibling?.apiKey);+ return Object.fromEntries(PROVIDER_GATEWAYS.map((gateway) => {+ const sibling = entries.find((p) => p?.id === gateway.id);+ return [gateway.id, sibling?.hasApiKey === true || Boolean(sibling?.apiKey)];+ }));};// Coalesced background refresh — one probe in flight at a time, so a failure@@ -81,11 +88,11 @@ const runtimeSnapshotFor = (keys) => {return runtimes;};-const forProvider = (provider, runtimes, orcaRouterKeySet) => providerPrerequisites(provider, {+const forProvider = (provider, runtimes, gatewayKeySet) => providerPrerequisites(provider, {// `undefined` (no entry in the map) is NOT PROBED — normalize it to the// module's `null` sentinel rather than letting it fall through as a value.runtime: runtimes?.[providerRuntimeKey(provider) ?? ''] ?? null,- orcaRouterKeySet,+ gatewayKeySet,});/**@@ -96,8 +103,8 @@ export function getProviderPrerequisiteMap(providers) {const list = Array.isArray(providers) ? providers : [];if (list.length === 0) return {};const runtimes = runtimeSnapshotFor(list.map(providerRuntimeKey));- const orcaRouterKeySet = orcaRouterKeyState(list);- return Object.fromEntries(list.map((provider) => [provider.id, forProvider(provider, runtimes, orcaRouterKeySet)]));+ const gatewayKeySet = gatewayKeyState(list);+ return Object.fromEntries(list.map((provider) => [provider.id, forProvider(provider, runtimes, gatewayKeySet)]));}/**@@ -115,7 +122,7 @@ export function getProviderPrerequisiteMap(providers) {*/export function prerequisitesMetForRouting(provider, providers) {const runtimes = runtimeSnapshotFor([providerRuntimeKey(provider)]);- const { missing } = forProvider(provider, runtimes, orcaRouterKeyState(providers));+ const { missing } = forProvider(provider, runtimes, gatewayKeyState(providers));if (!blocksRouting(missing)) return true;console.log(`⛔ Skipping fallback ${provider?.id || 'provider'}: ${describeMissingPrerequisites(missing)}`);return false;diff --git a/server/services/providerPrerequisites.test.js b/server/services/providerPrerequisites.test.jsindex 2d804bd8a1..c867ee1e48 100644--- a/server/services/providerPrerequisites.test.js+++ b/server/services/providerPrerequisites.test.js@@ -65,6 +65,21 @@ describe('getProviderPrerequisiteMap', () => {.toContain('inheritedApiKey');expect(getProviderPrerequisiteMap([wrapper, sibling(true)])[wrapper.id].met).toBe(true);});++ // Each gateway wrapper is judged against ITS OWN sibling: a key on one gateway+ // must never satisfy another, or the card would report a wrapper as ready+ // while the spawn has no credential for the host it actually calls.+ it('keeps each gateway wrapper on its own sibling key', () => {+ const orcaWrapper = { id: 'opencode-orcarouter', type: 'cli', command: 'opencode', orcarouterBacked: true };+ const openWrapper = { id: 'opencode-openrouter', type: 'cli', command: 'opencode', gatewayBacked: 'openrouter' };+ const api = (id, hasApiKey) => ({ id, type: 'api', hasApiKey, endpoint: 'https://api.example.com' });++ const map = getProviderPrerequisiteMap([orcaWrapper, openWrapper, api('orcarouter', true), api('openrouter', false)]);+ expect(map[orcaWrapper.id].met).toBe(true);+ expect(map[openWrapper.id].missing).toEqual([+ { code: 'inheritedApiKey', label: 'OpenRouter API provider has no API key' },+ ]);+ });});describe('prerequisitesMetForRouting', () => {