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
skip un-runnable providers when routing a fallback instead of ENOENT-ing at spawn (#4611)
[._.]/ Adam Eivy7f390925b05c
diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 5ac4219810..b8d5bed391 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. |-| `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 `providerCardState(provider, { runtime, status, orcaRouterKeySet })` + `PROVIDER_CARD_STATE` — is a provider ready to run, benched, blocked on a missing prerequisite (CLI not installed / API key absent), or simply switched off? Presentation-only (the server routes on `enabled && available` alone); `null` inputs 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. 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`, `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 `providerCardState(provider, { runtime, status, orcaRouterKeySet })` + `PROVIDER_CARD_STATE` — is a provider ready to run, benched, blocked on a missing prerequisite (CLI not installed / API key absent), 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 only what the browser alone can see — the local-app runtime shape; derives the credential checks itself only when an older server publishes nothing. `null` inputs 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. 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 7bdb1b4e2e..581c2a2b71 100644--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@ -989,13 +989,19 @@ export const PROVIDER_CARD_STATE = Object.freeze({* the right model. This decides the card's bucket from its toggle, its* credentials and the server's bench status; the two render side by side.*- * PRESENTATION state, not an exec gate: the server routes on- * `provider.enabled && isAvailable(id)` alone (`getFallbackProvider` in- * server/lib/aiToolkit/providerStatus.js) and discovers a missing binary at- * spawn time via ENOENT, so a `blocked` card here is still reachable by the- * runner. Publishing the prerequisite check server-side so routing can skip- * un-runnable providers is issue #4611; credentials carried in a secret env var- * (Bedrock, Ollama auth token) are not covered yet — issue #4612.+ * The prerequisite half is the SERVER's answer now (#4611): `GET+ * /api/providers` publishes `missingPrerequisites` per provider from+ * server/lib/providerPrerequisites.js, and `getFallbackProvider` skips a+ * provider whose CLI that same computation found missing — so a card blocked on+ * an uninstalled binary is no longer a routing candidate that dies at spawn+ * time on a raw ENOENT. (Routing acts only on that finding; a missing stored+ * key still shows here but stays presentation-only, because a provider can+ * authenticate through a secret env var — issue #4612, which also covers+ * DETECTING those env-var credentials so this stops over-reporting them.)+ *+ * This function consumes the published list and adds only what the browser+ * alone can see (the local-app runtime shape below). With an older server+ * publishing nothing, it falls back to deriving the credential checks itself.** Inputs are passed in rather than read from globals so this stays pure:* runtime — the provider's entry of the `runtimes` map (CLI binary)@@ -1024,22 +1030,42 @@ export const PROVIDER_CARD_STATE = Object.freeze({* @returns {{state: string, missing: {code: string, label: string}[]}}*/export const providerCardState = (provider, { runtime = null, status = null, orcaRouterKeySet = null } = {}) => {- const missing = [];+ // The server publishes its own verdict on `GET /api/providers`+ // (`missingPrerequisites`, from server/lib/providerPrerequisites.js) and+ // routes the fallback chain on exactly that computation. Where it has an+ // answer it WINS, so the card and the router cannot drift.+ //+ // An ARRAY is the sentinel for "published" — including the empty array, which+ // is a real answer ("nothing missing"). Anything else (an older server, a+ // payload fetched before the field existed) means not published, and the+ // local derivation below stands in.+ const published = Array.isArray(provider?.missingPrerequisites) ? provider.missingPrerequisites : null;+ const missing = published ? [...published] : [];+ const addMissing = (code, label) => {+ if (!missing.some((entry) => entry?.code === code)) missing.push({ code, label });+ };+ // Kept client-side even when the server has published: `runtime` here may be+ // the LOCAL-APP shape the page derives from the local-LLM status (an LM Studio+ // / Ollama app installed with no CLI shim on PATH), which the server's runtime+ // table does not cover. For a plain CLI provider this is the same row the+ // server probed, and `addMissing` de-dupes it by code.if (runtime && runtime.installed === false) {- missing.push({ code: 'runtime', label: `${runtime.label || 'Runtime'} is not installed` });- }- // API providers auth solely via the stored key — but only an endpoint outside- // the private network actually needs one. The server attaches `Authorization`- // only when a key is stored, so a keyless call to loopback, a LAN box, or a- // tailnet peer running LM Studio / Ollama works exactly as configured.- if (isApiProvider(provider) && provider?.hasApiKey !== true && !isPrivateNetworkEndpoint(provider?.endpoint)) {- missing.push({ code: 'apiKey', label: 'API key is not set' });+ addMissing('runtime', `${runtime.label || 'Runtime'} is not installed`);}- // The OpenCode OrcaRouter wrappers carry no key of their own — theirs lives- // on the sibling API provider, so that's the prerequisite to report.- if (isOrcaRouterBackedProvider(provider) && orcaRouterKeySet === false) {- missing.push({ code: 'inheritedApiKey', label: 'OrcaRouter API provider has no API key' });+ if (!published) {+ // API providers auth solely via the stored key — but only an endpoint outside+ // the private network actually needs one. The server attaches `Authorization`+ // only when a key is stored, so a keyless call to loopback, a LAN box, or a+ // tailnet peer running LM Studio / Ollama works exactly as configured.+ if (isApiProvider(provider) && provider?.hasApiKey !== true && !isPrivateNetworkEndpoint(provider?.endpoint)) {+ addMissing('apiKey', 'API key is not set');+ }+ // The OpenCode OrcaRouter wrappers carry no key of their own — theirs lives+ // on the sibling API provider, so that's the prerequisite to report.+ if (isOrcaRouterBackedProvider(provider) && orcaRouterKeySet === false) {+ addMissing('inheritedApiKey', 'OrcaRouter API provider has no API key');+ }}if (missing.length > 0) return { state: PROVIDER_CARD_STATE.BLOCKED, missing };diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex 7d41cbaac5..0947ecd278 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -1298,6 +1298,51 @@ describe('providerCardState', () => {);expect(readiness.missing.map(m => m.code)).toEqual(['runtime', 'apiKey']);});++ // The server publishes its own verdict on GET /api/providers and routes the+ // fallback chain on the same computation (#4611) — the card must read that+ // rather than re-deriving it, or the badge and the router can disagree.+ describe('server-published prerequisites', () => {+ it('paints a blocked card from the published findings', () => {+ const readiness = providerCardState(cli({+ missingPrerequisites: [{ code: 'runtime', label: 'OpenCode CLI is not installed' }],+ }));+ expect(readiness.state).toBe(PROVIDER_CARD_STATE.BLOCKED);+ expect(readiness.missing).toEqual([{ code: 'runtime', label: 'OpenCode CLI is not installed' }]);+ });++ // An EMPTY array is a real answer ("nothing missing"), not an absent one —+ // so it must SUPPRESS the local derivation, not fall back to it.+ it('trusts an empty published list over its own credential derivation', () => {+ expect(providerCardState(cloudApi({ hasApiKey: false, missingPrerequisites: [] })).state)+ .toBe(PROVIDER_CARD_STATE.READY);+ });++ it('falls back to deriving locally when the server published nothing', () => {+ expect(providerCardState(cloudApi({ hasApiKey: false })).state).toBe(PROVIDER_CARD_STATE.BLOCKED);+ expect(providerCardState(cloudApi({ hasApiKey: false, missingPrerequisites: null })).state)+ .toBe(PROVIDER_CARD_STATE.BLOCKED);+ });++ // The local-app runtime shape (an LM Studio / Ollama app installed with no+ // CLI shim on PATH) is derived from the local-LLM status, which the server's+ // runtime table does not cover — so it must still be added on top.+ it('adds a client-only local-app runtime finding to the published list', () => {+ const readiness = providerCardState(+ { id: 'lmstudio', type: 'api', endpoint: 'http://localhost:1234/v1', enabled: true, missingPrerequisites: [] },+ { runtime: { id: 'lmstudio', label: 'LM Studio', installed: false } },+ );+ expect(readiness.missing).toEqual([{ code: 'runtime', label: 'LM Studio is not installed' }]);+ });++ it('does not double-report a runtime both sides found missing', () => {+ const readiness = providerCardState(+ cli({ missingPrerequisites: [{ code: 'runtime', label: 'OpenCode CLI is not installed' }] }),+ { runtime: { label: 'OpenCode CLI', installed: false } },+ );+ expect(readiness.missing).toHaveLength(1);+ });+ });});describe('isPrivateNetworkEndpoint', () => {diff --git a/server/lib/README.md b/server/lib/README.mdindex ca8c7aeb5c..aa61dea365 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -109,6 +109,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), plus `providerRuntimeKey`, `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 — a credential finding stays presentation-only until #4612 teaches this module about env-var credentials, since a provider can authenticate through one. Pure. || `tuiPromptRunner.js` | One-shot TUI prompt runner (PTY-driven). || `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. || `tuiUsageScrape.js` | `scrapeTuiUsage({ command, slashCommand, … })` + `USAGE_SANDBOX_DIR` — drive an agy/grok TUI in a sandbox PTY, send a slash command, return the ANSI-stripped screen (for quota panels `--print` can't reach). |diff --git a/server/lib/aiToolkit/CLAUDE.md b/server/lib/aiToolkit/CLAUDE.mdindex eb3efaa517..46c3f37514 100644--- a/server/lib/aiToolkit/CLAUDE.md+++ b/server/lib/aiToolkit/CLAUDE.md@@ -15,6 +15,7 @@ The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previous- `setCliRunner(fn)` / `setTuiRunner(fn)` — register host CLI/TUI runners (pass `null` to revert). PortOS calls both in `server/index.js`: its CLI variant is stdin-based and knows the per-CLI argv conventions (Codex `exec -`, Antigravity `agy --print`, Claude Code `-p -`); the TUI runner has no toolkit built-in, and `setTuiRunner` attaches/detaches `executeTuiRun` so the runs router's `typeof runnerService.executeTuiRun === 'function'` gate stays honest.- `registerExternalRun(runId, killable)` / `unregisterExternalRun(runId)` / `hasExternalRun(runId)` — track host-spawned child processes / ptys. The toolkit's own `stopRun`, `isRunActive`, and `deleteRun` consult this registry *first*, so **a host runner that spawns its own process MUST register it here** (PortOS does this in `services/runner.js`) — otherwise the runs router reports live runs as inactive and refuses to stop them, and deleting a live run leaks a zombie process. `stopRun` also stamps a one-shot marker consumed through `consumeExternalRunStop(runId)` before unregistering, which lets the host classify the resulting signal as cancellation instead of a provider failure. That classification rides out to callers as `canceled: true` on the run metadata and `code: 'RUN_CANCELED'` on the rejection the prompt runner raises — **anything that turns an LLM failure into a verdict (a pause kind, a filed gap/investigation task, a provider bench, an `error` status) must call `isRunCanceledError` from `errorDetection.js` first**, or it files bug reports about a human pressing Stop. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.+- `createProviderStatusService({ prerequisitesMet })` — host gate for "can this provider run AT ALL?" (its CLI binary present). `getFallbackProvider` consults it on every candidate: task-level, configured, and system-priority alike. Injected rather than computed here because the answer needs host I/O (a PATH probe) and this directory stays self-contained; PortOS supplies `prerequisitesMetForRouting` from `services/providerPrerequisites.js` in `bootstrap.js`. It MUST be synchronous, and a missing / throwing / non-boolean answer deliberately reads as "yes" — an unknown answer has to route exactly as it did before, because emptying the fallback chain is a far worse failure than the late ENOENT the gate exists to prevent.- Time-based state transitions need read-side mirrors. `providerStatus.init()` clears expired `estimatedRecovery` entries; every reader (`getStatus`, `getAllStatuses`, `isAvailable`) must re-apply the same recovery check on read — otherwise providers stay "unavailable" past their recovery deadline until the next process restart.The worked example for "barrel + documented exports" (see root `CLAUDE.md` → Module Organization) is this directory's `index.js`.diff --git a/server/lib/aiToolkit/index.js b/server/lib/aiToolkit/index.jsindex be5b89ab14..93f7b3f399 100644--- a/server/lib/aiToolkit/index.js+++ b/server/lib/aiToolkit/index.js@@ -55,7 +55,10 @@ export function createAIToolkit(config = {}) {hooks = {},maxConcurrentRuns = 5,enableProviderStatus = true,- defaultFallbackPriority = ['claude-code', 'codex', 'nvidia-kimi', 'lmstudio', 'ollama', 'antigravity-cli', 'gemini-cli']+ defaultFallbackPriority = ['claude-code', 'codex', 'nvidia-kimi', 'lmstudio', 'ollama', 'antigravity-cli', 'gemini-cli'],+ // Host gate for "can this provider run at all?" — see providerStatus.js.+ // Unset standalone, so the toolkit routes on enabled + availability alone.+ prerequisitesMet = null} = config;const providerService = createProviderService({@@ -70,6 +73,7 @@ export function createAIToolkit(config = {}) {dataDir,statusFile,defaultFallbackPriority,+ prerequisitesMet,onStatusChange: (eventData) => {io?.emit('provider:status:changed', eventData);}diff --git a/server/lib/aiToolkit/providerStatus.js b/server/lib/aiToolkit/providerStatus.jsindex 1ec4c13349..64b344f6b4 100644--- a/server/lib/aiToolkit/providerStatus.js+++ b/server/lib/aiToolkit/providerStatus.js@@ -61,12 +61,41 @@ export function createProviderStatusService(config = {}) {defaultUsageLimitWait = 10 * 60 * 1000,maxUsageLimitWait = 5 * 60 * 60 * 1000,defaultRateLimitWait = 5 * 60 * 1000,- onStatusChange = null+ onStatusChange = null,+ // Host-supplied `(provider, providers) => boolean` answering "can this+ // provider run at all right now?" — its CLI binary present, its credential+ // stored. Enabled + not benched says nothing about either, so without this+ // the fallback chain happily hands a run to a provider whose binary was+ // never installed and the run dies at spawn time on a raw ENOENT (#4611).+ //+ // Injected rather than computed here because the answer needs host I/O (a+ // PATH probe) and this directory stays self-contained. It MUST be+ // synchronous and MUST default to "yes": an unknown answer has to route+ // exactly as it did before, never take a working provider out of the chain.+ prerequisitesMet = null} = config;const STATUS_PATH = join(dataDir, statusFile);const events = new EventEmitter();+ /**+ * Does the host vouch for this provider's prerequisites?+ *+ * A missing hook, a throwing hook, or a non-boolean answer all read as "yes".+ * The hook is a best-effort refinement of the routing decision; a broken one+ * must not silently empty the fallback chain, which is a far worse failure+ * than the late ENOENT it exists to prevent.+ */+ function meetsPrerequisites(provider, providers) {+ if (typeof prerequisitesMet !== 'function') return true;+ try {+ return prerequisitesMet(provider, providers) !== false;+ } catch (err) {+ console.error(`❌ Prerequisite check failed for ${provider?.id || 'provider'}: ${err.message}`);+ return true;+ }+ }+let statusCache = {providers: {},lastUpdated: null@@ -300,10 +329,16 @@ export function createProviderStatusService(config = {}) {// default"). It is NEVER the primary's model: a model id resolved against// the primary almost never exists on the fallback, and carrying it over is// exactly the leak that sent `codex-configured-default` to LM Studio.+ //+ // Every candidate must additionally clear `prerequisitesMet` (see the+ // config option): `enabled` + not benched says the user WANTS this provider+ // and it hasn't failed lately — neither says its CLI is installed or its+ // key is stored. Skipping an un-runnable candidate here is what turns a+ // late `spawn <binary> ENOENT` into "try the next provider instead".getFallbackProvider(primaryProviderId, providers, taskFallbackId = null, taskFallbackModelId = null) {if (taskFallbackId && taskFallbackId !== primaryProviderId) {const taskFallback = providers[taskFallbackId];- if (taskFallback?.enabled && this.isAvailable(taskFallback.id)) {+ if (taskFallback?.enabled && this.isAvailable(taskFallback.id) && meetsPrerequisites(taskFallback, providers)) {return { provider: taskFallback, source: 'task', model: usableFallbackModel(taskFallback, taskFallbackModelId) };}}@@ -315,7 +350,7 @@ export function createProviderStatusService(config = {}) {// primaryProviderId; the configured-fallback path needs its own check.if (primaryProvider?.fallbackProvider && primaryProvider.fallbackProvider !== primaryProviderId) {const configuredFallback = providers[primaryProvider.fallbackProvider];- if (configuredFallback?.enabled && this.isAvailable(configuredFallback.id)) {+ if (configuredFallback?.enabled && this.isAvailable(configuredFallback.id) && meetsPrerequisites(configuredFallback, providers)) {return { provider: configuredFallback, source: 'provider', model: usableFallbackModel(configuredFallback, primaryProvider.fallbackModel) };}}@@ -324,7 +359,7 @@ export function createProviderStatusService(config = {}) {if (providerId === primaryProviderId) continue;const provider = providers[providerId];- if (provider?.enabled && this.isAvailable(providerId)) {+ if (provider?.enabled && this.isAvailable(providerId) && meetsPrerequisites(provider, providers)) {return { provider, source: 'system', model: null };}}diff --git a/server/lib/aiToolkit/providerStatus.test.js b/server/lib/aiToolkit/providerStatus.test.jsindex 4931a5b440..950985d386 100644--- a/server/lib/aiToolkit/providerStatus.test.js+++ b/server/lib/aiToolkit/providerStatus.test.js@@ -359,6 +359,88 @@ describe('Provider Status Service', () => {});});+ describe('getFallbackProvider — host prerequisite gate', () => {+ const providers = {+ 'primary-provider': { id: 'primary-provider', enabled: true, fallbackProvider: 'configured-fallback' },+ 'configured-fallback': { id: 'configured-fallback', enabled: true },+ 'fallback-provider-1': { id: 'fallback-provider-1', enabled: true },+ 'fallback-provider-2': { id: 'fallback-provider-2', enabled: true },+ };++ const withGate = async (prerequisitesMet) => {+ const svc = createProviderStatusService({+ dataDir: TEST_DATA_DIR,+ statusFile: 'gated-status.json',+ defaultFallbackPriority: ['fallback-provider-1', 'fallback-provider-2'],+ prerequisitesMet,+ });+ await svc.init();+ return svc;+ };++ it('skips a CONFIGURED fallback whose prerequisites are unmet', async () => {+ const svc = await withGate((provider) => provider.id !== 'configured-fallback');++ const result = svc.getFallbackProvider('primary-provider', providers);++ expect(result.provider.id).toBe('fallback-provider-1');+ expect(result.source).toBe('system');+ });++ it('skips a TASK-level fallback whose prerequisites are unmet', async () => {+ const svc = await withGate((provider) => provider.id !== 'fallback-provider-2');++ const result = svc.getFallbackProvider('primary-provider', providers, 'fallback-provider-2');++ expect(result.provider.id).toBe('configured-fallback');+ expect(result.source).toBe('provider');+ });++ it('skips SYSTEM-priority candidates whose prerequisites are unmet', async () => {+ const svc = await withGate((provider) => provider.id === 'fallback-provider-2');++ const result = svc.getFallbackProvider('primary-provider', providers);++ expect(result.provider.id).toBe('fallback-provider-2');+ expect(result.source).toBe('system');+ });++ it('returns null when every candidate fails the gate', async () => {+ const svc = await withGate(() => false);++ expect(svc.getFallbackProvider('primary-provider', providers)).toBeNull();+ });++ it('passes the whole provider collection so an inherited-key check can see siblings', async () => {+ const seen = [];+ const svc = await withGate((provider, all) => { seen.push([provider.id, all]); return true; });++ svc.getFallbackProvider('primary-provider', providers);++ expect(seen[0][0]).toBe('configured-fallback');+ expect(seen[0][1]).toBe(providers);+ });++ it('routes exactly as before when the gate is absent or answers non-boolean', async () => {+ const noGate = await withGate(null);+ expect(noGate.getFallbackProvider('primary-provider', providers).provider.id).toBe('configured-fallback');++ // Only an explicit `false` may exclude a provider — "unknown" must never+ // empty the chain (see the sentinel discipline in providerPrerequisites).+ const vague = await withGate(() => undefined);+ expect(vague.getFallbackProvider('primary-provider', providers).provider.id).toBe('configured-fallback');+ });++ it('treats a THROWING gate as "yes" rather than emptying the chain', async () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const svc = await withGate(() => { throw new Error('probe exploded'); });++ expect(svc.getFallbackProvider('primary-provider', providers).provider.id).toBe('configured-fallback');+ expect(errorSpy).toHaveBeenCalled();+ errorSpy.mockRestore();+ });+ });+describe('getFallbackProvider — stale model pins', () => {// A `fallbackModel` is set on the PRIMARY but resolved against the// fallback, so a model bump on the fallback leaves the pin naming an iddiff --git a/server/lib/index.js b/server/lib/index.jsindex 53e0404e92..204bb90c4d 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -137,6 +137,7 @@ export * from './promptSystemStages.js';export * from './promptTemplate.js';export * from './providerCooldown.js';export * from './providerModels.js';+export * from './providerPrerequisites.js';// Namespaced: providerVendors.js re-exports `inferTuiCommand` /// `applyCommandDefaults` (from tuiHandshake.js) and `prepareCliPrompt` (from// cliProviderArgs.js), which would trip the barrel's duplicate-identifierdiff --git a/server/lib/providerPrerequisites.js b/server/lib/providerPrerequisites.jsnew file mode 100644index 0000000000..f9359177fb--- /dev/null+++ b/server/lib/providerPrerequisites.js@@ -0,0 +1,187 @@+/**+ * Provider PREREQUISITES — the things that must already be true on this host+ * before a provider can run at all: the CLI binary it shells out to is on+ * PortOS's PATH, and the credential it authenticates with is stored.+ *+ * Three different questions get asked about a provider, and this is the first+ * of them:+ *+ * 1. prerequisites (here) — can it run at all?+ * 2. readiness (`services/providerReadiness.js`) — is the local daemon it+ * points at up and serving the model it asks for?+ * 3. availability (`aiToolkit/providerStatus.js`) — is it benched after a+ * recent failure?+ *+ * Until #4611 this check existed only in the browser (`providerCardState` in+ * client/src/utils/providers.js), so it painted a `NEEDS SETUP` card while the+ * server happily routed a run at the very same provider and discovered the+ * missing binary at spawn time as a raw ENOENT. This module is the server-side+ * copy the routing layer and the API payload both read, and the client now+ * consumes the published result — one computation, two consumers, no drift.+ *+ * Pure: every input is passed in, nothing is probed here. The probing half is+ * `services/providerPrerequisites.js`.+ *+ * **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.+ *+ * Credentials carried in a secret env var (Bedrock, an Ollama auth token) are+ * deliberately NOT covered here yet — that is issue #4612.+ */++import { PROVIDER_TYPES } from './aiToolkit/constants.js';+import { isLocalInstanceHost } from './localProviderRuntime.js';+import { commandBasename } from './providerModels.js';++/**+ * Hosts inside the trust boundary, where an unauthenticated OpenAI-compatible+ * server is a normal setup rather than a misconfiguration: RFC1918 LAN ranges,+ * link-local, and the Tailscale CGNAT range 100.64.0.0/10 (PortOS is a+ * tailnet-first product — an API provider pointed at another machine's Ollama+ * is a first-class configuration, not an edge case).+ */+const PRIVATE_IP_RE = /^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/;++/**+ * IPv6 counterpart to {@link PRIVATE_IP_RE}: unique-local (`fc00::/7`) and+ * link-local (`fe80::/10`). Tailscale hands out a ULA address alongside the+ * CGNAT v4 one, so without this a tailnet peer reached over IPv6 reads as a+ * public host and its keyless provider is blocked on a missing API key.+ *+ * Gated on the host being an IPv6 literal (it contains a `:`) and compared+ * NUMERICALLY on the leading hextet — a bare `/^f[cd]/` prefix test would also+ * claim hostnames like `fdrive.example.com`, and `fd::1` expands to a leading+ * hextet of `0x00fd`, which is not in `fc00::/7` at all.+ */+const isPrivateIpv6 = (host) => {+ if (!host.includes(':')) return false;+ const first = host.split(':')[0];+ if (!/^[0-9a-f]{1,4}$/.test(first)) return false; // '' for `::1` — loopback, matched by isLocalInstanceHost+ const n = parseInt(first, 16);+ return (n >= 0xfc00 && n <= 0xfdff) || (n >= 0xfe80 && n <= 0xfebf);+};++/** The hostname of an endpoint (scheme optional), lowercased and de-bracketed; `null` when unparseable. */+const endpointHost = (endpoint) => {+ if (typeof endpoint !== 'string' || endpoint.trim() === '') return null;+ const trimmed = endpoint.trim();+ // A scheme-less endpoint ("192.0.2.10:1234/v1") is still a host — give the+ // parser one so it doesn't read the leading segment as a scheme.+ const candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;+ if (!URL.canParse(candidate)) return null;+ return new URL(candidate).hostname.toLowerCase().replace(/^\[|\]$/g, '');+};++/**+ * Is this endpoint inside the private network — loopback, a LAN/tailnet+ * address, a `.local`/`.ts.net`/`.internal` name, or a bare single-label host?+ *+ * Decides whether a missing API key is actually a missing prerequisite. The+ * server attaches an `Authorization` header only when a key is stored, so a+ * keyless call to a private OpenAI-compatible server (LM Studio on the desk+ * machine, Ollama on a tailnet peer) works exactly as configured — treating it+ * as un-runnable would take a supported deployment out of the fallback chain.+ * A public endpoint with no key stays flagged: that one really is misconfigured.+ *+ * MIRROR of `isPrivateNetworkEndpoint` in client/src/utils/providers.js — keep+ * in lockstep. A host that cannot be parsed reads as NOT private, keeping the+ * stricter of the two answers for input we don't understand.+ */+export const isPrivateNetworkEndpoint = (endpoint) => {+ const host = endpointHost(endpoint);+ if (host === null) return false;+ if (isLocalInstanceHost(host)) return true;+ if (PRIVATE_IP_RE.test(host)) return true;+ if (isPrivateIpv6(host)) return true;+ if (/\.(local|internal|lan|home\.arpa|ts\.net)$/.test(host)) return true;+ // A single-label host resolves only inside the local network (`http://nas:11434`).+ return !host.includes('.') && !host.includes(':');+};++/** True for a process-backed provider (cli/tui), which needs its binary on PATH. */+const isProcessProvider = (provider) =>+ provider?.type === PROVIDER_TYPES.CLI || provider?.type === PROVIDER_TYPES.TUI;++/**+ * The key a CLI/TUI provider's runtime is published under in the runtimes map+ * from `services/providerRuntimeInstaller.js` — the binary it spawns,+ * basename-normalized so a provider pinned to an absolute path still matches.+ * `null` for a provider with no spawned command (every API provider).+ */+export const providerRuntimeKey = (provider) =>+ (isProcessProvider(provider) && commandBasename(provider?.command)) || null;++/** Does this provider's record hold an API key? Accepts a raw OR a sanitized provider. */+const providerHasApiKey = (provider) =>+ provider?.hasApiKey === true || Boolean(provider?.apiKey);++/**+ * Which prerequisites `provider` is missing, and whether it is runnable at all.+ *+ * @param {object} provider — raw or sanitized provider record+ * @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".+ * @returns {{met: boolean, missing: {code: string, label: string}[]}}+ */+export const providerPrerequisites = (provider, { runtime = null, orcaRouterKeySet = null } = {}) => {+ const missing = [];++ if (runtime && runtime.installed === false) {+ missing.push({ code: 'runtime', label: `${runtime.label || 'Runtime'} is not installed` });+ }+ // API providers auth solely via the stored key — but only an endpoint outside+ // the private network actually needs one.+ if (provider?.type === PROVIDER_TYPES.API+ && !providerHasApiKey(provider)+ && !isPrivateNetworkEndpoint(provider?.endpoint)) {+ missing.push({ code: 'apiKey', label: 'API key is not set' });+ }+ // The OpenCode OrcaRouter wrappers carry no key of their own — theirs lives on+ // the sibling API provider, so that's the prerequisite to report.+ if (provider?.orcarouterBacked === true && orcaRouterKeySet === false) {+ missing.push({ code: 'inheritedApiKey', label: 'OrcaRouter API provider has no API key' });+ }++ return { met: missing.length === 0, missing };+};++/**+ * A one-line reason a provider was skipped, for the run log — "Codex CLI is not+ * installed; API key is not set". `null` when nothing is missing, so a caller+ * can use it as the whole gate.+ */+export const describeMissingPrerequisites = (missing) =>+ (Array.isArray(missing) && missing.length > 0)+ ? missing.map((entry) => entry?.label).filter(Boolean).join('; ') || null+ : null;++/**+ * The findings a ROUTING decision is allowed to act on — a deliberately+ * narrower set than what the card displays.+ *+ * A missing binary is unarguable: no credential, env var, or config file makes+ * `spawn codex` work when `codex` is not on PATH, so skipping that candidate+ * 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+ * key rather than the sibling's. Routing on those would take working providers+ * out of the chain, so they stay presentation-only until #4612 teaches this+ * module about env-var credentials; then they can move into this list.+ */+export const ROUTING_BLOCKING_CODES = Object.freeze(['runtime']);++/**+ * Is any of these findings severe enough to skip the provider when routing?+ * @param {{code: string}[]} missing+ */+export const blocksRouting = (missing) =>+ Array.isArray(missing) && missing.some((entry) => ROUTING_BLOCKING_CODES.includes(entry?.code));diff --git a/server/lib/providerPrerequisites.test.js b/server/lib/providerPrerequisites.test.jsnew file mode 100644index 0000000000..6b923ffa74--- /dev/null+++ b/server/lib/providerPrerequisites.test.js@@ -0,0 +1,137 @@+import { describe, it, expect } from 'vitest';+import {+ blocksRouting,+ describeMissingPrerequisites,+ isPrivateNetworkEndpoint,+ providerPrerequisites,+ providerRuntimeKey,+ ROUTING_BLOCKING_CODES,+} from './providerPrerequisites.js';++const cli = (over = {}) => ({ id: 'codex', type: 'cli', command: 'codex', ...over });+const api = (over = {}) => ({ id: 'openai', type: 'api', endpoint: 'https://api.example.com/v1', ...over });++describe('providerRuntimeKey', () => {+ it('normalizes a process provider command to its binary basename', () => {+ expect(providerRuntimeKey(cli({ command: '/opt/example/bin/Codex.exe' }))).toBe('codex');+ expect(providerRuntimeKey({ type: 'tui', command: 'agy' })).toBe('agy');+ });++ it('is null for a provider with no spawned command', () => {+ expect(providerRuntimeKey(api())).toBeNull();+ expect(providerRuntimeKey(cli({ command: '' }))).toBeNull();+ expect(providerRuntimeKey(null)).toBeNull();+ });+});++describe('isPrivateNetworkEndpoint', () => {+ it.each([+ 'http://localhost:1234/v1',+ 'http://127.0.0.2:11434',+ 'http://[::1]:1234',+ 'http://10.0.0.4:1234/v1',+ 'http://192.168.1.5:1234/v1',+ 'http://172.16.3.4:1234',+ 'http://100.100.0.9:11434', // Tailscale CGNAT+ 'http://[fd7a:115c:a1e0::1]:11434', // Tailscale ULA+ 'http://[fe80::1]:11434', // link-local+ 'http://desk.ts.net:11434',+ 'http://nas.local:1234',+ 'nas:11434', // single-label host, no scheme+ ])('treats %s as private', (endpoint) => {+ expect(isPrivateNetworkEndpoint(endpoint)).toBe(true);+ });++ it.each([+ 'https://api.example.com/v1',+ 'http://192.0.2.10:1234/v1', // TEST-NET-1 is routable, not private+ 'http://fdrive.example.com', // must not match the fc00::/7 hextet rule by prefix+ 'http://[fd::1]:11434', // leading hextet 0x00fd is NOT in fc00::/7+ '',+ 'not a url at all ::::',+ ])('treats %s as NOT private', (endpoint) => {+ expect(isPrivateNetworkEndpoint(endpoint)).toBe(false);+ });+});++describe('providerPrerequisites', () => {+ it('reports a CLI whose binary is absent', () => {+ const result = providerPrerequisites(cli(), { runtime: { installed: false, label: 'Codex CLI' } });+ expect(result.met).toBe(false);+ expect(result.missing).toEqual([{ code: 'runtime', label: 'Codex CLI is not installed' }]);+ });++ it('treats an UNPROBED runtime as met, never as missing', () => {+ expect(providerPrerequisites(cli(), { runtime: null }).met).toBe(true);+ expect(providerPrerequisites(cli()).met).toBe(true);+ expect(providerPrerequisites(cli(), { runtime: { installed: true, label: 'Codex CLI' } }).met).toBe(true);+ });++ it('reports a keyless API provider on a PUBLIC endpoint', () => {+ const result = providerPrerequisites(api());+ expect(result.met).toBe(false);+ expect(result.missing).toEqual([{ code: 'apiKey', label: 'API key is not set' }]);+ });++ it('does not demand a key for a private-network endpoint', () => {+ expect(providerPrerequisites(api({ endpoint: 'http://localhost:1234/v1' })).met).toBe(true);+ expect(providerPrerequisites(api({ endpoint: 'http://desk.ts.net:11434' })).met).toBe(true);+ });++ it('accepts a key from either a raw (apiKey) or a sanitized (hasApiKey) record', () => {+ expect(providerPrerequisites(api({ apiKey: 'sk-example' })).met).toBe(true);+ expect(providerPrerequisites(api({ hasApiKey: true })).met).toBe(true);+ expect(providerPrerequisites(api({ hasApiKey: false })).met).toBe(false);+ });++ 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)+ .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);+ });++ 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,+ });+ expect(result.missing.map((m) => m.code)).toEqual(['runtime', 'apiKey', 'inheritedApiKey']);+ });+});++describe('describeMissingPrerequisites', () => {+ it('joins the labels, and is null when nothing is missing', () => {+ expect(describeMissingPrerequisites([{ code: 'a', label: 'One' }, { code: 'b', label: 'Two' }]))+ .toBe('One; Two');+ expect(describeMissingPrerequisites([])).toBeNull();+ expect(describeMissingPrerequisites(undefined)).toBeNull();+ });+});++// Routing may act on strictly less than the card displays: a missing BINARY is+// unarguable, a missing stored key is not (a secret env var can supply it —+// issue #4612), so only the former may take a provider out of the chain.+describe('blocksRouting', () => {+ it('acts on a missing runtime', () => {+ expect(blocksRouting(providerPrerequisites(cli(), { runtime: { installed: false, label: 'Codex CLI' } }).missing)).toBe(true);+ });++ 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);+ });++ it('is false for nothing missing, and for a non-array', () => {+ expect(blocksRouting([])).toBe(false);+ expect(blocksRouting(undefined)).toBe(false);+ });++ it('pins the routing-blocking set so widening it is a deliberate edit', () => {+ expect([...ROUTING_BLOCKING_CODES]).toEqual(['runtime']);+ });+});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex effa363341..04767f4989 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -16,6 +16,7 @@ import {stopRuntimeInstaller,} from '../services/providerRuntimeInstaller.js';import { getProviderReadinessMap, resetProviderReadinessCache } from '../services/providerReadiness.js';+import { getProviderPrerequisiteMap } from '../services/providerPrerequisites.js';import { runLocalRuntimeSetup } from '../services/localRuntimeSetup.js';import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';@@ -99,11 +100,28 @@ export function createPortOSProviderRoutes(aiToolkit) {const providerStatusService = aiToolkit.services.providerStatus;// Sanitized GET routes — intercept toolkit GET endpoints to strip secrets+ /**+ * The provider list, each record decorated with the SERVER's verdict on its+ * prerequisites (#4611): `prerequisitesMet` plus the `missingPrerequisites`+ * findings behind it. The AI Providers page paints its `NEEDS SETUP` cards+ * from this instead of re-deriving the same rules in the browser, and the+ * fallback router gates on the same computation — so a card that says a+ * provider can't run and a router that hands it a run can no longer disagree.+ *+ * Computed on the RAW providers, before sanitization: the API-key check reads+ * `apiKey`, which `sanitizeProvider` replaces with a boolean, and the runtime+ * probe is TTL-cached so this costs a map lookup on the common path.+ */router.get('/', asyncHandler(async (req, res) => {const data = await providerService.getAllProviders();+ const prerequisites = await getProviderPrerequisiteMap(data.providers);res.json({activeProvider: data.activeProvider,- providers: data.providers.map(presentProvider),+ providers: data.providers.map((provider) => ({+ ...presentProvider(provider),+ prerequisitesMet: prerequisites[provider.id]?.met ?? true,+ missingPrerequisites: prerequisites[provider.id]?.missing ?? [],+ })),runnerAllowedCommands: RUNNER_ALLOWED_COMMANDS});}));diff --git a/server/routes/providers.prerequisites.test.js b/server/routes/providers.prerequisites.test.jsnew file mode 100644index 0000000000..e15c3de0ed--- /dev/null+++ b/server/routes/providers.prerequisites.test.js@@ -0,0 +1,70 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express, { Router } from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// The probe is the host's PATH; stub it so this suite asserts the PAYLOAD shape+// rather than which CLIs happen to be installed on the machine running it.+vi.mock('../services/providerRuntimeInstaller.js', async (importOriginal) => ({+ ...(await importOriginal()),+ getProviderRuntimeStatuses: vi.fn(async () => ({+ codex: { id: 'codex', label: 'Codex CLI', installed: false },+ claude: { id: 'claude', label: 'Claude Code CLI', installed: true },+ })),+}));++const { createPortOSProviderRoutes } = await import('./providers.js');++const CODEX = { id: 'codex', name: 'Codex CLI', type: 'cli', command: 'codex', envVars: {} };+const CLAUDE = { id: 'claude-code', name: 'Claude Code', type: 'cli', command: 'claude', envVars: {} };+const KEYLESS_CLOUD = { id: 'openai', name: 'OpenAI', type: 'api', endpoint: 'https://api.example.com/v1', envVars: {} };+const LOCAL_API = { id: 'lmstudio', name: 'LM Studio', type: 'api', endpoint: 'http://localhost:1234/v1', envVars: {} };++const appWith = (providers) => {+ const providerService = {+ getAllProviders: vi.fn().mockResolvedValue({ activeProvider: 'codex', providers }),+ };+ const toolkit = { services: { providers: providerService }, routes: { providers: Router() } };+ const app = express();+ app.use(express.json());+ app.use('/api/providers', createPortOSProviderRoutes(toolkit));+ app.use(errorMiddleware);+ return app;+};++const providersById = (res) => Object.fromEntries(res.body.providers.map((p) => [p.id, p]));++beforeEach(() => vi.clearAllMocks());++describe('#4611: GET /api/providers publishes each provider\'s prerequisites', () => {+ it('flags a CLI provider whose binary is absent, and names it', async () => {+ const byId = providersById(await request(appWith([CODEX, CLAUDE])).get('/api/providers'));++ expect(byId.codex.prerequisitesMet).toBe(false);+ expect(byId.codex.missingPrerequisites).toEqual([{ code: 'runtime', label: 'Codex CLI is not installed' }]);+ expect(byId['claude-code'].prerequisitesMet).toBe(true);+ expect(byId['claude-code'].missingPrerequisites).toEqual([]);+ });++ it('flags a keyless API provider on a public endpoint but not one on loopback', async () => {+ const byId = providersById(await request(appWith([KEYLESS_CLOUD, LOCAL_API])).get('/api/providers'));++ expect(byId.openai.missingPrerequisites).toEqual([{ code: 'apiKey', label: 'API key is not set' }]);+ expect(byId.lmstudio.prerequisitesMet).toBe(true);+ });++ it('derives the API-key check BEFORE sanitization, which replaces the key with a boolean', async () => {+ const byId = providersById(await request(appWith([{ ...KEYLESS_CLOUD, apiKey: 'sk-example' }])).get('/api/providers'));++ expect(byId.openai.prerequisitesMet).toBe(true);+ expect(byId.openai.apiKey).toBeUndefined();+ expect(byId.openai.hasApiKey).toBe(true);+ });++ it('still strips secrets and keeps the existing decorations', async () => {+ const byId = providersById(await request(appWith([CODEX])).get('/api/providers'));++ expect(byId.codex).toHaveProperty('canRefreshModels');+ expect(byId.codex).not.toHaveProperty('apiKey');+ });+});diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 5daeb9f58e..967225ec73 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -138,6 +138,7 @@ import { commissionStore, backfillAllCommissionFeedback } from './creativeCommisimport { backfillProjectCommissionIds } from './creativeCommissions/projectControl.js';import { outcomesStore as liOutcomesStore } from './layeredIntelligenceOutcomes.js';import * as gameStore from './games/store.js';+import { prerequisitesMetForRouting } from './providerPrerequisites.js';/*** Pre-route boot. Everything a route handler may depend on being ready the@@ -234,7 +235,12 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// Inject PortOS's ServerError so toolkit route errors normalize into the// canonical `{ error, code, timestamp, context? }` envelope (issue #1084).ServerError,- hooks: aiToolkitHooks+ hooks: aiToolkitHooks,+ // Keep the fallback chain off providers whose CLI is not installed on+ // this host (#4611), so a run falls through to the next candidate instead+ // of dying at spawn time. Sync by contract: it reads the runtime probe's+ // cache and never blocks.+ prerequisitesMet: prerequisitesMetForRouting}),// Compatibility shims for services that import from the old service files.diff --git a/server/services/providerPrerequisites.js b/server/services/providerPrerequisites.jsnew file mode 100644index 0000000000..c189fc1a3c--- /dev/null+++ b/server/services/providerPrerequisites.js@@ -0,0 +1,110 @@+/**+ * Provider prerequisites, probed.+ *+ * `lib/providerPrerequisites.js` decides what a provider is missing given the+ * facts; this module supplies the facts (the CLI-runtime probe) and exposes the+ * two shapes PortOS needs:+ *+ * - `getProviderPrerequisiteMap(providers)` — async, awaits the (TTL-cached)+ * runtime probe. Used to decorate `GET /api/providers` so the AI Providers+ * page reads the same answer the router uses instead of deriving its own.+ * - `prerequisitesMetForRouting(provider, providers)` — SYNC, for the+ * fallback-provider chain in `aiToolkit/providerStatus.js`, which is a+ * synchronous decision. Reads whatever the probe has already cached and+ * kicks a background refresh when that is cold.+ *+ * The sync path is deliberately permissive, twice over. An un-probed runtime+ * yields no finding, so the FIRST fallback pick after boot routes exactly as it+ * did before and the refresh it triggers makes every later pick accurate —+ * never the other way round, because a cold cache must not take every CLI+ * provider out of the chain. And it acts only on `ROUTING_BLOCKING_CODES` (the+ * missing binary), not on the credential findings the card also shows.+ *+ * No LLM call is made here. Probing a CLI is a `--version` spawn, so this is+ * safe under the no-cold-bootstrap policy in CLAUDE.md.+ */++import { blocksRouting, describeMissingPrerequisites, providerPrerequisites, providerRuntimeKey } from '../lib/providerPrerequisites.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?+ *+ * `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.+ */+const orcaRouterKeyState = (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);+};++const forProvider = (provider, runtimes, orcaRouterKeySet) => 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,+});++/**+ * `{ [providerId]: { met, missing } }` for a whole provider collection, one+ * runtime probe for the batch.+ * @param {Array<object>} providers — raw or sanitized provider records+ */+export async function getProviderPrerequisiteMap(providers) {+ const list = Array.isArray(providers) ? providers : [];+ if (list.length === 0) return {};+ const runtimes = await getProviderRuntimeStatuses();+ const orcaRouterKeySet = orcaRouterKeyState(list);+ return Object.fromEntries(list.map((provider) => [provider.id, forProvider(provider, runtimes, orcaRouterKeySet)]));+}++// Coalesced background refresh for the sync path — one probe in flight at a+// time, so a failure storm picking a fallback per failed run doesn't fan out a+// `--version` spawn per CLI per run.+let refreshInFlight = null;+const refreshRuntimesInBackground = () => {+ if (refreshInFlight) return;+ refreshInFlight = getProviderRuntimeStatuses()+ .catch((err) => console.error(`❌ Provider runtime probe failed: ${err.message}`))+ .finally(() => { refreshInFlight = null; });+};++/**+ * Can this provider run right now, as far as the already-probed facts say?+ *+ * The gate the fallback chain uses. Returns `true` for anything not KNOWN to be+ * un-runnable — see the sentinel note above, and `ROUTING_BLOCKING_CODES` for+ * why routing acts on a NARROWER set of findings than the card displays. Logs+ * the one line that explains a skip, which is the whole point of the change: a+ * run that used to die on `spawn codex ENOENT` now says which binary is absent+ * and moves on to the next candidate.+ *+ * @param {object} provider+ * @param {object|Array} providers — the sibling collection (for inherited keys)+ * @returns {boolean}+ */+export function prerequisitesMetForRouting(provider, providers) {+ const runtimes = peekProviderRuntimeStatuses();+ const key = providerRuntimeKey(provider);+ // Only for a binary PortOS's runtime table actually covers — a custom command+ // will never appear in the probe's answer, and re-requesting it per fallback+ // pick would be a refresh that can never succeed.+ if (key && !runtimes[key] && getProviderRuntime(key)) refreshRuntimesInBackground();+ const { missing } = forProvider(provider, runtimes, orcaRouterKeyState(providers));+ if (!blocksRouting(missing)) return true;+ console.log(`⛔ Skipping fallback ${provider?.id || 'provider'}: ${describeMissingPrerequisites(missing)}`);+ return false;+}++/** Test-only: drop the in-flight refresh handle so a suite starts clean. */+export function __resetPrerequisiteRefresh() {+ refreshInFlight = null;+}diff --git a/server/services/providerPrerequisites.test.js b/server/services/providerPrerequisites.test.jsnew file mode 100644index 0000000000..e415cd311d--- /dev/null+++ b/server/services/providerPrerequisites.test.js@@ -0,0 +1,137 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';++// Only the probe is stubbed — `getProviderRuntime` stays real so the "is this+// command even in the runtime table?" branch is exercised against the shipped+// table rather than a fixture that could drift from it.+vi.mock('./providerRuntimeInstaller.js', async (importOriginal) => ({+ ...(await importOriginal()),+ getProviderRuntimeStatuses: vi.fn(),+ peekProviderRuntimeStatuses: vi.fn(),+}));++const { getProviderRuntimeStatuses, peekProviderRuntimeStatuses } = await import('./providerRuntimeInstaller.js');+const { getProviderPrerequisiteMap, prerequisitesMetForRouting, __resetPrerequisiteRefresh } =+ await import('./providerPrerequisites.js');++const CODEX_ABSENT = { id: 'codex', label: 'Codex CLI', installed: false };+const CODEX_PRESENT = { id: 'codex', label: 'Codex CLI', installed: true };++const codex = (over = {}) => ({ id: 'codex', type: 'cli', command: 'codex', ...over });++beforeEach(() => {+ vi.clearAllMocks();+ __resetPrerequisiteRefresh();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+});++describe('getProviderPrerequisiteMap', () => {+ it('keys the verdict by provider id, from one runtime probe for the batch', async () => {+ getProviderRuntimeStatuses.mockResolvedValue({ codex: CODEX_ABSENT });++ const map = await getProviderPrerequisiteMap([+ codex(),+ { id: 'openai', type: 'api', endpoint: 'https://api.example.com/v1' },+ { id: 'lmstudio', type: 'api', endpoint: 'http://localhost:1234/v1' },+ ]);++ expect(getProviderRuntimeStatuses).toHaveBeenCalledTimes(1);+ expect(map.codex).toEqual({ met: false, missing: [{ code: 'runtime', label: 'Codex CLI is not installed' }] });+ expect(map.openai.met).toBe(false);+ expect(map.lmstudio.met).toBe(true);+ });++ it('probes nothing for an empty collection', async () => {+ expect(await getProviderPrerequisiteMap([])).toEqual({});+ expect(await getProviderPrerequisiteMap(null)).toEqual({});+ expect(getProviderRuntimeStatuses).not.toHaveBeenCalled();+ });++ it('reads the inherited OrcaRouter key off the sibling in the same collection', async () => {+ getProviderRuntimeStatuses.mockResolvedValue({});+ const wrapper = { id: 'opencode-orcarouter', type: 'cli', command: 'opencode', orcarouterBacked: true };++ const keyless = await getProviderPrerequisiteMap([wrapper, { id: 'orcarouter', type: 'api', hasApiKey: false, endpoint: 'https://api.example.com' }]);+ expect(keyless[wrapper.id].missing.map((m) => m.code)).toContain('inheritedApiKey');++ const keyed = await getProviderPrerequisiteMap([wrapper, { id: 'orcarouter', type: 'api', hasApiKey: true, endpoint: 'https://api.example.com' }]);+ expect(keyed[wrapper.id].met).toBe(true);+ });+});++describe('prerequisitesMetForRouting', () => {+ it('rejects a provider whose CLI the probe has already found absent', () => {+ peekProviderRuntimeStatuses.mockReturnValue({ codex: CODEX_ABSENT });++ expect(prerequisitesMetForRouting(codex(), {})).toBe(false);+ });++ it('accepts a provider whose CLI is installed', () => {+ peekProviderRuntimeStatuses.mockReturnValue({ codex: CODEX_PRESENT });++ expect(prerequisitesMetForRouting(codex(), {})).toBe(true);+ expect(getProviderRuntimeStatuses).not.toHaveBeenCalled();+ });++ it('accepts an UN-PROBED CLI and kicks a background refresh so the next pick is accurate', () => {+ peekProviderRuntimeStatuses.mockReturnValue({});+ getProviderRuntimeStatuses.mockResolvedValue({});++ expect(prerequisitesMetForRouting(codex(), {})).toBe(true);+ expect(getProviderRuntimeStatuses).toHaveBeenCalledTimes(1);+ });++ it('coalesces the background refresh while one is already in flight', () => {+ peekProviderRuntimeStatuses.mockReturnValue({});+ getProviderRuntimeStatuses.mockReturnValue(new Promise(() => {})); // never settles++ prerequisitesMetForRouting(codex(), {});+ prerequisitesMetForRouting(codex(), {});+ prerequisitesMetForRouting(codex(), {});++ expect(getProviderRuntimeStatuses).toHaveBeenCalledTimes(1);+ });++ it('never probes for a provider that spawns no command', () => {+ peekProviderRuntimeStatuses.mockReturnValue({});++ expect(prerequisitesMetForRouting({ id: 'lmstudio', type: 'api', endpoint: 'http://localhost:1234/v1' }, {})).toBe(true);+ expect(getProviderRuntimeStatuses).not.toHaveBeenCalled();+ });++ // Routing acts ONLY on the missing binary. A keyless-looking provider may+ // still authenticate through a secret env var (Bedrock, an Ollama auth token)+ // — the card says NEEDS SETUP, but skipping it here would take a working+ // provider out of the chain. See ROUTING_BLOCKING_CODES / issue #4612.+ it('does NOT reject a keyless API provider, however its card is painted', () => {+ peekProviderRuntimeStatuses.mockReturnValue({});++ expect(prerequisitesMetForRouting({ id: 'openai', type: 'api', endpoint: 'https://api.example.com/v1' }, {})).toBe(true);+ expect(prerequisitesMetForRouting({ id: 'peer', type: 'api', endpoint: 'http://desk.ts.net:11434' }, {})).toBe(true);+ });++ it('does NOT reject an OrcaRouter wrapper over its sibling key alone', () => {+ peekProviderRuntimeStatuses.mockReturnValue({ opencode: { id: 'opencode', label: 'OpenCode CLI', installed: true } });+ const wrapper = { id: 'opencode-orcarouter', type: 'cli', command: 'opencode', orcarouterBacked: true };++ expect(prerequisitesMetForRouting(wrapper, { orcarouter: { id: 'orcarouter' } })).toBe(true);+ // …but the missing BINARY still takes it out of the chain.+ peekProviderRuntimeStatuses.mockReturnValue({ opencode: { id: 'opencode', label: 'OpenCode CLI', installed: false } });+ expect(prerequisitesMetForRouting(wrapper, { orcarouter: { id: 'orcarouter' } })).toBe(false);+ });++ it('never probes for a command outside the runtime table', () => {+ peekProviderRuntimeStatuses.mockReturnValue({});++ expect(prerequisitesMetForRouting({ id: 'custom', type: 'cli', command: 'my-own-cli' }, {})).toBe(true);+ expect(getProviderRuntimeStatuses).not.toHaveBeenCalled();+ });++ it('logs one line naming what is missing when it skips a provider', () => {+ peekProviderRuntimeStatuses.mockReturnValue({ codex: CODEX_ABSENT });++ prerequisitesMetForRouting(codex(), {});++ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Codex CLI is not installed'));+ });+});diff --git a/server/services/providerRuntimeInstaller.js b/server/services/providerRuntimeInstaller.jsindex 9c8105f9ad..083b911c96 100644--- a/server/services/providerRuntimeInstaller.js+++ b/server/services/providerRuntimeInstaller.js@@ -254,6 +254,29 @@ export async function getProviderRuntimeStatuses(deps = {}) {}));}+/**+ * The runtime statuses ALREADY probed, read SYNCHRONOUSLY — no PATH scan, no+ * child process, no promise. For a caller that must answer "is this binary+ * here?" inside a synchronous decision (fallback-provider routing, via+ * `services/providerPrerequisites.js`) and cannot await the real probe.+ *+ * Returns `{}` when nothing has been probed yet, and a per-id status object+ * otherwise, aliases included — so a caller that finds NO entry for its runtime+ * reads "not probed", never "not installed". Deliberately ignores the TTL: a+ * minute-old answer about whether a CLI is installed is a far better routing+ * hint than none, and the async path re-probes on its own schedule.+ */+export function peekProviderRuntimeStatuses() {+ const byId = {};+ for (const runtime of PROVIDER_RUNTIMES) {+ const cached = statusCache.get(runtime.id);+ if (!cached) continue;+ byId[runtime.id] = cached.status;+ for (const alias of runtime.aliases) byId[alias] = cached.status;+ }+ return byId;+}+function memoizePerBatch(findCommand) {const seen = new Map();return (command) => {diff --git a/server/services/providerRuntimeInstaller.test.js b/server/services/providerRuntimeInstaller.test.jsindex 94b9a90b56..a762ea245a 100644--- a/server/services/providerRuntimeInstaller.test.js+++ b/server/services/providerRuntimeInstaller.test.js@@ -7,6 +7,7 @@ import {getProviderRuntimeStatuses,NPM_GLOBAL_INSTALL_FLAGS,PROVIDER_RUNTIMES,+ peekProviderRuntimeStatuses,spawnRuntimeInstaller,__resetRuntimeStatusCache,} from './providerRuntimeInstaller.js';@@ -173,6 +174,28 @@ describe('provider runtime installer', () => {expect(statuses.antigravity.id).toBe('agy');});+ // The sync read the fallback router depends on (#4611). It must answer+ // "not probed" — not "not installed" — for anything the async probe has not+ // reached yet, or a cold cache would take every CLI provider out of routing.+ describe('peekProviderRuntimeStatuses', () => {+ it('is empty before anything has been probed', () => {+ expect(peekProviderRuntimeStatuses()).toEqual({});+ });++ it('returns a probed runtime, under its aliases too, without probing again', async () => {+ const findCommand = vi.fn(async () => null);+ await getProviderRuntimeStatus('agy', { findCommand, probeCommand: async () => false });+ findCommand.mockClear();++ const peeked = peekProviderRuntimeStatuses();++ expect(peeked.agy.installed).toBe(false);+ expect(peeked.antigravity).toBe(peeked.agy);+ expect(peeked.codex).toBeUndefined(); // never probed → absent, not false+ expect(findCommand).not.toHaveBeenCalled();+ });+ });+// #3618's rule: a vendor is one row. A new coding-agent CLI must not land in// the runner allowlist and argv builders while silently having no way to be// installed from the Providers page.diff --git a/server/services/runner.js b/server/services/runner.jsindex 011c278618..06a4fabf9d 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -222,6 +222,24 @@ export async function patchRunMetadata(runId, patch) {});}+/**+ * A spawn failure phrased for the person reading the run log.+ *+ * Node reports a binary that isn't on PATH as `spawn codex ENOENT` — precise,+ * and meaningless to anyone who doesn't already know that ENOENT is "no such+ * file". Routing now skips a provider whose CLI is known to be absent (#4611),+ * so reaching this line means the probe hadn't caught up yet; name the binary+ * and where to install it rather than leaving the errno as the whole story.+ * Every other spawn failure keeps its raw message.+ *+ * @param {NodeJS.ErrnoException} spawnError+ * @param {string} command — the provider's configured command+ */+const describeSpawnFailure = (spawnError, command) =>+ spawnError?.code === 'ENOENT'+ ? `${command || 'The provider CLI'} is not installed on PortOS's PATH — install it from the AI Providers page, then re-run`+ : `Spawn failed: ${spawnError.message}`;+/*** Override executeCliRun.*@@ -408,7 +426,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, onmetadata.outputSize = Buffer.byteLength(output);if (spawnError) {- metadata.error = `Spawn failed: ${spawnError.message}`;+ metadata.error = describeSpawnFailure(spawnError, provider.command);metadata.errorCategory = 'spawn_error';} else if (canceled) {metadata.canceled = true;