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
never let a stale or path-shaped runtime probe drop a working provider from routing (#4611)
[._.]/ Adam Eivydfe350389f54
diff --git a/server/lib/README.md b/server/lib/README.mdindex aa61dea365..192a1b55f7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -109,7 +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. |+| `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` (`null` for an API provider AND for a command carrying an explicit path — the runtime table only answers "does the BARE binary resolve on PATH?"), `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/providerPrerequisites.js b/server/lib/providerPrerequisites.jsindex f9359177fb..fac62acf38 100644--- a/server/lib/providerPrerequisites.js+++ b/server/lib/providerPrerequisites.js@@ -89,6 +89,11 @@ const endpointHost = (endpoint) => {* 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.+ *+ * The two disagree only on compact loopback spellings (`http://127.1`), which+ * `URL` expands and the client's cheap regex does not. That no longer reaches+ * the card: the client consumes THIS answer when the server publishes one, and+ * falls back to its own regex only against a server too old to publish.*/export const isPrivateNetworkEndpoint = (endpoint) => {const host = endpointHost(endpoint);@@ -107,12 +112,25 @@ const isProcessProvider = (provider) =>/*** 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).+ * from `services/providerRuntimeInstaller.js`, or `null` when that map has+ * nothing to say about this provider.+ *+ * `null` for an API provider (nothing is spawned) and — unlike the client's+ * same-named helper, which uses the key to offer an INSTALL button — `null` for+ * a command carrying an explicit path. The runtime table answers exactly one+ * question: "does the bare binary resolve on PortOS's PATH?" A provider+ * configured as `/opt/tools/codex` is not that question: the runner spawns the+ * configured path against the provider's own env (`buildCliChildEnv`), so+ * basename-matching it would report a perfectly working CLI as missing and drop+ * it from the fallback chain. No key means NOT PROBED, which is the honest+ * answer here.*/-export const providerRuntimeKey = (provider) =>- (isProcessProvider(provider) && commandBasename(provider?.command)) || null;+export const providerRuntimeKey = (provider) => {+ if (!isProcessProvider(provider)) return null;+ const command = typeof provider?.command === 'string' ? provider.command.trim() : '';+ if (command === '' || /[\\/]/.test(command)) return null;+ return commandBasename(command) || null;+};/** Does this provider's record hold an API key? Accepts a raw OR a sanitized provider. */const providerHasApiKey = (provider) =>diff --git a/server/lib/providerPrerequisites.test.js b/server/lib/providerPrerequisites.test.jsindex 6b923ffa74..2ce79097ef 100644--- a/server/lib/providerPrerequisites.test.js+++ b/server/lib/providerPrerequisites.test.js@@ -12,14 +12,25 @@ const cli = (over = {}) => ({ id: 'codex', type: 'cli', command: 'codex', ...oveconst 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('normalizes a bare process-provider command to its binary name', () => {+ expect(providerRuntimeKey(cli({ command: 'Codex.exe' }))).toBe('codex');+ expect(providerRuntimeKey({ type: 'tui', command: ' agy ' })).toBe('agy');+ });++ // The runtime table only ever answered "does the BARE binary resolve on+ // PortOS's PATH?". The runner spawns an explicitly-pathed command against the+ // provider's own env, so lending it the bare binary's verdict would report a+ // working CLI as missing.+ it('is null for a command carrying an explicit path', () => {+ expect(providerRuntimeKey(cli({ command: '/opt/example/bin/codex' }))).toBeNull();+ expect(providerRuntimeKey(cli({ command: './codex' }))).toBeNull();+ expect(providerRuntimeKey(cli({ command: 'C:\\tools\\codex.exe' }))).toBeNull();});it('is null for a provider with no spawned command', () => {expect(providerRuntimeKey(api())).toBeNull();expect(providerRuntimeKey(cli({ command: '' }))).toBeNull();+ expect(providerRuntimeKey(cli({ command: ' ' }))).toBeNull();expect(providerRuntimeKey(null)).toBeNull();});});@@ -32,7 +43,7 @@ describe('isPrivateNetworkEndpoint', () => {'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://100.64.0.5:11434', // Tailscale CGNAT'http://[fd7a:115c:a1e0::1]:11434', // Tailscale ULA'http://[fe80::1]:11434', // link-local'http://desk.ts.net:11434',diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 04767f4989..aa675abf96 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -109,12 +109,17 @@ export function createPortOSProviderRoutes(aiToolkit) {* 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.+ * `apiKey`, which `sanitizeProvider` replaces with a boolean.+ *+ * Synchronous by design — this endpoint is fetched by half the app, so it+ * reads the runtime probe's cache and lets a cold one refresh in the+ * background rather than putting a `--version` sweep of every CLI on that+ * critical path. An unprobed runtime simply publishes no finding, and the+ * page's own `/runtimes` fetch fills that gap on the card.*/router.get('/', asyncHandler(async (req, res) => {const data = await providerService.getAllProviders();- const prerequisites = await getProviderPrerequisiteMap(data.providers);+ const prerequisites = getProviderPrerequisiteMap(data.providers);res.json({activeProvider: data.activeProvider,providers: data.providers.map((provider) => ({diff --git a/server/routes/providers.prerequisites.test.js b/server/routes/providers.prerequisites.test.jsindex e15c3de0ed..63573618be 100644--- a/server/routes/providers.prerequisites.test.js+++ b/server/routes/providers.prerequisites.test.js@@ -7,7 +7,7 @@ import { errorMiddleware } from '../lib/errorHandler.js';// 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 () => ({+ peekProviderRuntimeStatuses: vi.fn(() => ({codex: { id: 'codex', label: 'Codex CLI', installed: false },claude: { id: 'claude', label: 'Claude Code CLI', installed: true },})),diff --git a/server/services/providerPrerequisites.js b/server/services/providerPrerequisites.jsindex c189fc1a3c..b92de66dd4 100644--- a/server/services/providerPrerequisites.js+++ b/server/services/providerPrerequisites.js@@ -2,23 +2,32 @@* 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:+ * facts; this module supplies the facts 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.+ * - `getProviderPrerequisiteMap(providers)` — the whole collection's verdict,+ * for decorating `GET /api/providers` so the AI Providers page reads the+ * same answer the router uses instead of deriving its own.+ * - `prerequisitesMetForRouting(provider, providers)` — the gate the+ * fallback-provider chain in `aiToolkit/providerStatus.js` consults.*- * 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.+ * BOTH are synchronous and read only what the runtime probe has already cached,+ * kicking a coalesced background refresh when it has nothing current. Routing+ * has no choice — `getFallbackProvider` is a synchronous decision — and the+ * route must not await either: `GET /api/providers` is fetched by half the app,+ * and a cold cache would put a multi-second `--version` sweep of every CLI on+ * that critical path. The credential checks need no probe at all, so they are+ * always exact; only the runtime finding waits on the cache.+ *+ * The result is permissive in three deliberate ways. An un-probed runtime+ * yields no finding, so the first pick after boot behaves exactly as it did+ * before and the refresh it triggers makes later picks accurate. An EXPIRED+ * probe is likewise no answer, so a CLI installed by hand stops being skipped+ * within the TTL rather than until the next restart. And routing acts only on+ * `ROUTING_BLOCKING_CODES` (the missing binary), never on the credential+ * findings the card also shows. Never the other way round: taking a working+ * provider out of the fallback chain is worse than the late ENOENT this+ * prevents.** 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.@@ -46,6 +55,32 @@ const orcaRouterKeyState = (providers) => {return sibling?.hasApiKey === true || Boolean(sibling?.apiKey);};+// Coalesced background refresh — 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. Errors are logged and swallowed: this runs outside the+// request lifecycle, where an unhandled rejection kills the process.+let refreshInFlight = null;+const refreshRuntimesInBackground = () => {+ if (refreshInFlight) return;+ refreshInFlight = getProviderRuntimeStatuses()+ .catch((err) => console.error(`❌ Provider runtime probe failed: ${err.message}`))+ .finally(() => { refreshInFlight = null; });+};++/**+ * The cached runtime statuses, plus a background refresh for any runtime this+ * batch wanted and the cache had nothing current for.+ *+ * Scoped to runtimes the table actually covers: a custom command will never+ * appear in the probe's answer, so re-requesting it per call would be a refresh+ * that can never succeed.+ */+const runtimeSnapshotFor = (keys) => {+ const runtimes = peekProviderRuntimeStatuses();+ if (keys.some((key) => key && !runtimes[key] && getProviderRuntime(key))) refreshRuntimesInBackground();+ return runtimes;+};+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.@@ -54,50 +89,32 @@ const forProvider = (provider, runtimes, orcaRouterKeySet) => providerPrerequisi});/**- * `{ [providerId]: { met, missing } }` for a whole provider collection, one- * runtime probe for the batch.+ * `{ [providerId]: { met, missing } }` for a whole provider collection.* @param {Array<object>} providers — raw or sanitized provider records*/-export async function getProviderPrerequisiteMap(providers) {+export function getProviderPrerequisiteMap(providers) {const list = Array.isArray(providers) ? providers : [];if (list.length === 0) return {};- const runtimes = await getProviderRuntimeStatuses();+ const runtimes = runtimeSnapshotFor(list.map(providerRuntimeKey));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.+ * un-runnable — see the module note above — and 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 runtimes = runtimeSnapshotFor([providerRuntimeKey(provider)]);const { missing } = forProvider(provider, runtimes, orcaRouterKeyState(providers));if (!blocksRouting(missing)) return true;console.log(`⛔ Skipping fallback ${provider?.id || 'provider'}: ${describeMissingPrerequisites(missing)}`);diff --git a/server/services/providerPrerequisites.test.js b/server/services/providerPrerequisites.test.jsindex e415cd311d..2d804bd8a1 100644--- a/server/services/providerPrerequisites.test.js+++ b/server/services/providerPrerequisites.test.js@@ -21,41 +21,49 @@ const codex = (over = {}) => ({ id: 'codex', type: 'cli', command: 'codex', ...obeforeEach(() => {vi.clearAllMocks();__resetPrerequisiteRefresh();+ peekProviderRuntimeStatuses.mockReturnValue({});+ getProviderRuntimeStatuses.mockResolvedValue({});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 });+ it('keys the verdict by provider id, from the cached runtime statuses', () => {+ peekProviderRuntimeStatuses.mockReturnValue({ codex: CODEX_ABSENT });- const map = await getProviderPrerequisiteMap([+ const map = 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({});+ // Fetched by half the app — a cold cache must not put a multi-second sweep of+ // every CLI on that request.+ it('never awaits the probe; a cold cache publishes no runtime finding and refreshes behind the request', () => {+ const map = getProviderPrerequisiteMap([codex()]);++ expect(map.codex).toEqual({ met: true, missing: [] });+ expect(getProviderRuntimeStatuses).toHaveBeenCalledTimes(1);+ });++ it('probes nothing for an empty collection', () => {+ expect(getProviderPrerequisiteMap([])).toEqual({});+ expect(getProviderPrerequisiteMap(null)).toEqual({});expect(getProviderRuntimeStatuses).not.toHaveBeenCalled();});- it('reads the inherited OrcaRouter key off the sibling in the same collection', async () => {- getProviderRuntimeStatuses.mockResolvedValue({});+ it('reads the inherited OrcaRouter key off the sibling in the same collection', () => {const wrapper = { id: 'opencode-orcarouter', type: 'cli', command: 'opencode', orcarouterBacked: true };+ const sibling = (hasApiKey) => ({ id: 'orcarouter', type: 'api', hasApiKey, endpoint: 'https://api.example.com' });- 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);+ expect(getProviderPrerequisiteMap([wrapper, sibling(false)])[wrapper.id].missing.map((m) => m.code))+ .toContain('inheritedApiKey');+ expect(getProviderPrerequisiteMap([wrapper, sibling(true)])[wrapper.id].met).toBe(true);});});@@ -66,7 +74,7 @@ describe('prerequisitesMetForRouting', () => {expect(prerequisitesMetForRouting(codex(), {})).toBe(false);});- it('accepts a provider whose CLI is installed', () => {+ it('accepts a provider whose CLI is installed, without re-probing', () => {peekProviderRuntimeStatuses.mockReturnValue({ codex: CODEX_PRESENT });expect(prerequisitesMetForRouting(codex(), {})).toBe(true);@@ -74,15 +82,22 @@ describe('prerequisitesMetForRouting', () => {});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);+ });++ // `peekProviderRuntimeStatuses` drops a status once its TTL is up, so an+ // expired "not installed" arrives here as an absent entry. That must route+ // normally — otherwise a CLI installed by hand stays skipped until something+ // else happens to re-probe.+ it('accepts a provider whose cached negative has aged out of the snapshot', () => {+ peekProviderRuntimeStatuses.mockReturnValue({}); // codex probed, then expiredexpect(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 settlesprerequisitesMetForRouting(codex(), {});@@ -92,20 +107,43 @@ describe('prerequisitesMetForRouting', () => {expect(getProviderRuntimeStatuses).toHaveBeenCalledTimes(1);});- it('never probes for a provider that spawns no command', () => {- peekProviderRuntimeStatuses.mockReturnValue({});+ it('logs and clears a FAILED refresh so the next call can try again', async () => {+ getProviderRuntimeStatuses.mockRejectedValueOnce(new Error('PATH scan exploded'));++ expect(prerequisitesMetForRouting(codex(), {})).toBe(true);+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('PATH scan exploded'));+ prerequisitesMetForRouting(codex(), {});+ expect(getProviderRuntimeStatuses).toHaveBeenCalledTimes(2);+ });++ it('never probes for a provider that spawns no command', () => {expect(prerequisitesMetForRouting({ id: 'lmstudio', type: 'api', endpoint: 'http://localhost:1234/v1' }, {})).toBe(true);expect(getProviderRuntimeStatuses).not.toHaveBeenCalled();});+ it('never probes for a command outside the runtime table', () => {+ expect(prerequisitesMetForRouting({ id: 'custom', type: 'cli', command: 'my-own-cli' }, {})).toBe(true);+ expect(getProviderRuntimeStatuses).not.toHaveBeenCalled();+ });++ // The runtime table answers "does the bare binary resolve on PortOS's PATH?".+ // A provider pinned to an explicit path is a different question — the runner+ // spawns that path against the provider's own env — so borrowing the bare+ // binary's answer would drop a perfectly working CLI from the chain.+ it('does not borrow a bare binary\'s verdict for a provider pinned to an explicit path', () => {+ peekProviderRuntimeStatuses.mockReturnValue({ codex: CODEX_ABSENT });++ expect(prerequisitesMetForRouting(codex({ command: '/opt/example/bin/codex' }), {})).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);});@@ -120,13 +158,6 @@ describe('prerequisitesMetForRouting', () => {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 });diff --git a/server/services/providerRuntimeInstaller.js b/server/services/providerRuntimeInstaller.jsindex 083b911c96..5517129dae 100644--- a/server/services/providerRuntimeInstaller.js+++ b/server/services/providerRuntimeInstaller.js@@ -255,22 +255,28 @@ export async function getProviderRuntimeStatuses(deps = {}) {}/**- * The runtime statuses ALREADY probed, read SYNCHRONOUSLY — no PATH scan, no+ * The runtime statuses currently cached, 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.+ * Returns `{}` when nothing is cached, 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".+ *+ * Honors the same TTL as the async path, which matters in one direction+ * specifically: a cached `installed: false` that has aged out must stop being+ * an answer. Otherwise a user who installs the CLI from a terminal stays+ * skipped by routing until something else happens to re-probe — an expiry is+ * "we no longer know", and the caller's response to not-knowing is to route+ * normally and kick a refresh.*/export function peekProviderRuntimeStatuses() {+ const now = Date.now();const byId = {};for (const runtime of PROVIDER_RUNTIMES) {const cached = statusCache.get(runtime.id);- if (!cached) continue;+ if (!cached || now - cached.at >= STATUS_TTL_MS) continue;byId[runtime.id] = cached.status;for (const alias of runtime.aliases) byId[alias] = cached.status;}diff --git a/server/services/providerRuntimeInstaller.test.js b/server/services/providerRuntimeInstaller.test.jsindex a762ea245a..9de2586db4 100644--- a/server/services/providerRuntimeInstaller.test.js+++ b/server/services/providerRuntimeInstaller.test.js@@ -194,6 +194,18 @@ describe('provider runtime installer', () => {expect(peeked.codex).toBeUndefined(); // never probed → absent, not falseexpect(findCommand).not.toHaveBeenCalled();});++ // A cached "not installed" that has aged out must stop being an answer, or+ // a CLI the user installed from a terminal stays skipped by routing until+ // something else happens to re-probe.+ it('drops a status once its TTL is up, so an expired negative reads as unprobed', async () => {+ await getProviderRuntimeStatus('codex', { findCommand: async () => null, probeCommand: async () => false });+ expect(peekProviderRuntimeStatuses().codex.installed).toBe(false);++ vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 61_000);+ expect(peekProviderRuntimeStatuses().codex).toBeUndefined();+ vi.restoreAllMocks();+ });});// #3618's rule: a vendor is one row. A new coding-agent CLI must not land in