Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: give Codex a harness model lister, skip derived presets in harness refresh (#8497)

[._.]/ Adam Eivyf18e5999efc4
diff --git a/server/lib/aiToolkit/internal/codexModelListProbe.js b/server/lib/aiToolkit/internal/codexModelListProbe.js
new file mode 100644
index 0000000000..f8854c1aa8
--- /dev/null
+++ b/server/lib/aiToolkit/internal/codexModelListProbe.js
@@ -0,0 +1,97 @@
+/**
+ * Codex publishes no plain `models` subcommand — its catalog lives behind the
+ * `app-server` JSON-RPC handshake (`initialize` → `initialized` →
+ * `model/list`), so listing it means driving that long-lived process
+ * directly rather than treating it as a single `commandOutput` stdout capture
+ * the way every other harness's `<cli> models` answer is read.
+ *
+ * A LEAF module (no imports out of this directory) so a host caller — the
+ * Harnesses page refresh in `services/harnesses.js`, which has no Codex
+ * `provider` record to resolve a spawn from — can drive the same probe
+ * `_fetchCodexModels` in `providerCatalogService.js` uses, with an
+ * already-resolved `command`/`args`/`env` rather than a toolkit provider
+ * shape (#8497).
+ */
+import { spawn } from 'child_process';
+
+const DEFAULT_TIMEOUT_MS = 15000;
+
+/**
+ * @param {string} command - the resolved (Windows-safe) executable.
+ * @param {string[]} args - argv, expected to end in `app-server`.
+ * @param {{ envVars?: NodeJS.ProcessEnv }|null} provider - only `envVars` is
+ * read (a toolkit provider record, or `null` for a bare harness probe with
+ * no per-record overrides — `services/providerRuntimeInstaller.js`).
+ * @param {{ timeoutMs?: number, label?: string }} [options]
+ * @returns {Promise<string[]>} de-duplicated, non-hidden model ids.
+ */
+export function probeCodexModelsViaAppServer(command, args, provider, options = {}) {
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const label = options.label ?? `'${command} ${args.join(' ')}'`;
+ const childEnv = { ...process.env, ...provider?.envVars };
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ let child;
+ const settle = (err, result) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ try { child?.kill('SIGTERM'); } catch { /* already exited */ }
+ if (err) reject(err);
+ else resolve(result);
+ };
+ const timer = setTimeout(() => {
+ settle(new Error(`${label} timed out waiting for model catalog`));
+ }, timeoutMs);
+ timer.unref?.();
+ try {
+ child = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'], env: childEnv, windowsHide: true });
+ } catch (err) {
+ settle(new Error(`${label} failed to spawn: ${err?.message || err}`));
+ return;
+ }
+ child.on('error', (err) => settle(new Error(`${label} failed: ${err?.message || err}`)));
+ child.stdin?.on('error', () => {});
+ child.on('exit', (code, signal) => settle(new Error(`${label} exited prematurely with code ${code ?? signal}`)));
+
+ let buffer = '';
+ child.stdout?.on('data', (chunk) => {
+ buffer += chunk.toString();
+ const lines = buffer.split('\n');
+ buffer = lines.pop() ?? '';
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ try {
+ const msg = JSON.parse(trimmed);
+ if (msg.id === 1) {
+ child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', method: 'initialized', params: {} }) + '\n');
+ child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'model/list', params: {} }) + '\n');
+ } else if (msg.id === 2) {
+ if (msg.error) {
+ settle(new Error(`${label} model/list error: ${msg.error.message || JSON.stringify(msg.error)}`));
+ return;
+ }
+ const rawModels = msg.result?.data || msg.result?.models || [];
+ const ids = rawModels
+ .filter((m) => !m.hidden)
+ .map((m) => (typeof m === 'string' ? m : m?.id || m?.model))
+ .filter(Boolean);
+ if (ids.length === 0) {
+ settle(new Error(`${label} returned no model ids`));
+ return;
+ }
+ settle(null, [...new Set(ids)]);
+ return;
+ }
+ } catch { /* not JSON, or not a message we're waiting on — ignore */ }
+ }
+ });
+ child.stdin?.write(JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: { clientInfo: { name: 'portos', version: '1.0.0' } },
+ }) + '\n');
+ });
+}
diff --git a/server/lib/aiToolkit/internal/codexModelListProbe.test.js b/server/lib/aiToolkit/internal/codexModelListProbe.test.js
new file mode 100644
index 0000000000..b2235e80ac
--- /dev/null
+++ b/server/lib/aiToolkit/internal/codexModelListProbe.test.js
@@ -0,0 +1,112 @@
+import { describe, it, expect, vi } from 'vitest';
+import { EventEmitter } from 'events';
+
+// A fake child speaks the JSON-RPC handshake back, so this pins the PROTOCOL
+// (initialize → initialized + model/list, hidden filtering, error/timeout/exit
+// handling) rather than whether `codex` happens to be installed.
+vi.mock('child_process', () => ({ spawn: vi.fn() }));
+const { spawn } = await import('child_process');
+const { probeCodexModelsViaAppServer } = await import('./codexModelListProbe.js');
+
+function fakeChild() {
+ const child = new EventEmitter();
+ child.stdin = { write: vi.fn(), end: vi.fn(), on: vi.fn() };
+ child.stdout = new EventEmitter();
+ child.kill = vi.fn();
+ return child;
+}
+
+describe('probeCodexModelsViaAppServer', () => {
+ it('merges a provider record\'s envVars over process.env for the spawned child', async () => {
+ const child = fakeChild();
+ spawn.mockReturnValue(child);
+
+ probeCodexModelsViaAppServer('codex', ['app-server'], { envVars: { OPENAI_API_KEY: 'example-key' } });
+
+ const [, , spawnOptions] = spawn.mock.calls[0];
+ expect(spawnOptions.env).toMatchObject({ ...process.env, OPENAI_API_KEY: 'example-key' });
+ });
+
+ it('runs under plain process.env when there is no provider record (a bare harness probe)', async () => {
+ const child = fakeChild();
+ spawn.mockReturnValue(child);
+
+ probeCodexModelsViaAppServer('codex', ['app-server'], null);
+
+ const [, , spawnOptions] = spawn.mock.calls[0];
+ expect(spawnOptions.env).toEqual(process.env);
+ });
+
+ it('drives initialize → initialized + model/list, filters hidden entries, and de-dupes', async () => {
+ const child = fakeChild();
+ spawn.mockReturnValue(child);
+
+ const promise = probeCodexModelsViaAppServer('codex', ['app-server'], null);
+ // Handshake starts with `initialize`.
+ expect(JSON.parse(child.stdin.write.mock.calls[0][0])).toMatchObject({ id: 1, method: 'initialize' });
+
+ child.stdout.emit('data', `${JSON.stringify({ jsonrpc: '2.0', id: 1, result: {} })}\n`);
+ // `initialized` (a notification) then the `model/list` request follow.
+ expect(JSON.parse(child.stdin.write.mock.calls[1][0])).toMatchObject({ method: 'initialized' });
+ expect(JSON.parse(child.stdin.write.mock.calls[2][0])).toMatchObject({ id: 2, method: 'model/list' });
+
+ child.stdout.emit('data', `${JSON.stringify({
+ jsonrpc: '2.0',
+ id: 2,
+ result: { data: [{ id: 'gpt-6-astra' }, { id: 'gpt-6-hidden', hidden: true }, 'gpt-6-sol', 'gpt-6-sol'] },
+ })}\n`);
+
+ await expect(promise).resolves.toEqual(['gpt-6-astra', 'gpt-6-sol']);
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ });
+
+ it('rejects with the RPC error message when model/list answers one', async () => {
+ const child = fakeChild();
+ spawn.mockReturnValue(child);
+
+ const promise = probeCodexModelsViaAppServer('codex', ['app-server'], null);
+ child.stdout.emit('data', `${JSON.stringify({ jsonrpc: '2.0', id: 1, result: {} })}\n`);
+ child.stdout.emit('data', `${JSON.stringify({ jsonrpc: '2.0', id: 2, error: { message: 'not signed in' } })}\n`);
+
+ await expect(promise).rejects.toThrow(/not signed in/);
+ });
+
+ it('rejects when the catalog answers with no usable ids', async () => {
+ const child = fakeChild();
+ spawn.mockReturnValue(child);
+
+ const promise = probeCodexModelsViaAppServer('codex', ['app-server'], null);
+ child.stdout.emit('data', `${JSON.stringify({ jsonrpc: '2.0', id: 1, result: {} })}\n`);
+ child.stdout.emit('data', `${JSON.stringify({ jsonrpc: '2.0', id: 2, result: { data: [] } })}\n`);
+
+ await expect(promise).rejects.toThrow(/returned no model ids/);
+ });
+
+ it('rejects when the process exits before answering', async () => {
+ const child = fakeChild();
+ spawn.mockReturnValue(child);
+
+ const promise = probeCodexModelsViaAppServer('codex', ['app-server'], null);
+ child.emit('exit', 1, null);
+
+ await expect(promise).rejects.toThrow(/exited prematurely with code 1/);
+ });
+
+ it('rejects when the child cannot be spawned at all', async () => {
+ spawn.mockImplementation(() => { throw new Error('ENOENT'); });
+
+ await expect(probeCodexModelsViaAppServer('codex', ['app-server'], null)).rejects.toThrow(/failed to spawn/);
+ });
+
+ it('settles only once even if exit and a late message both arrive', async () => {
+ const child = fakeChild();
+ spawn.mockReturnValue(child);
+
+ const promise = probeCodexModelsViaAppServer('codex', ['app-server'], null);
+ child.stdout.emit('data', `${JSON.stringify({ jsonrpc: '2.0', id: 1, result: {} })}\n`);
+ child.stdout.emit('data', `${JSON.stringify({ jsonrpc: '2.0', id: 2, result: { data: ['gpt-6-astra'] } })}\n`);
+ child.emit('exit', 0, null); // must not flip an already-settled resolution to a rejection
+
+ await expect(promise).resolves.toEqual(['gpt-6-astra']);
+ });
+});
diff --git a/server/lib/aiToolkit/internal/providerCatalogService.js b/server/lib/aiToolkit/internal/providerCatalogService.js
index 9202fe3d5f..8b2d7c801b 100644
--- a/server/lib/aiToolkit/internal/providerCatalogService.js
+++ b/server/lib/aiToolkit/internal/providerCatalogService.js
@@ -1,8 +1,8 @@
import { readFile, readdir } from 'fs/promises';
import { existsSync } from 'fs';
import { homedir } from 'os';
-import { join, isAbsolute, delimiter } from 'path';
-import { execFile, spawn } from 'child_process';
+import { join } from 'path';
+import { execFile } from 'child_process';
import { promisify } from 'util';
import { assertSecretEndpoint, evaluateSecretEndpoint } from '../endpointGuard.js';
import { composeBootstrapSpawn } from './credentialBootstrap.js';
@@ -13,40 +13,8 @@ import { providerModeGroups } from './providerModes.js';
import { ollamaRefreshGroupKey, resolveModelFetcher } from './modelFetchers.js';
import { modelCatalogUpdate, parseModelCatalog, toModelCatalog } from './modelCatalog.js';
import { CLAUDE_CATALOG_SUBPATH, catalogAge, claudeConfigDir, selectCatalogModels } from './claudeCodeCatalog.js';
-
-const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];
-
-function resolveWindowsExecutable(command, isWin32 = process.platform === 'win32', searchEnv = process.env) {
- if (!isWin32 || !command || isAbsolute(command) || /[\\/]/.test(command)) return null;
- const pathDirs = (searchEnv.PATH || searchEnv.Path || '').split(delimiter).filter(Boolean);
- for (const dir of pathDirs) {
- for (const ext of WIN_EXECUTABLE_EXTS) {
- const candidate = join(dir, `${command}${ext}`);
- if (existsSync(candidate)) return candidate;
- }
- }
- return null;
-}
-
-const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;
-const CMD_METACHAR_RE = /[&|<>^()]/g;
-const NEEDS_NODE_QUOTING_RE = /[\s"]/;
-
-function prepareWindowsSafeSpawn(command, args, isWin32 = process.platform === 'win32') {
- if (isWin32 && WIN_BATCH_EXT_RE.test(command)) {
- return {
- command: 'cmd.exe',
- args: ['/c', escapeCmdMetacharsIfUnquoted(command), ...args.map(escapeCmdMetacharsIfUnquoted)],
- };
- }
- return { command, args };
-}
-
-function escapeCmdMetacharsIfUnquoted(value) {
- const str = String(value);
- if (NEEDS_NODE_QUOTING_RE.test(str)) return str;
- return str.replace(CMD_METACHAR_RE, '^$&');
-}
+import { prepareWindowsSafeSpawn, resolveWindowsExecutable } from './windowsSafeSpawn.js';
+import { probeCodexModelsViaAppServer } from './codexModelListProbe.js';
function resolveProbeSpawn(provider, defaultBin, args) {
const spawned = composeBootstrapSpawn(provider, provider?.command || defaultBin, args);
@@ -390,79 +358,15 @@ export function createProviderCatalogService({
async _fetchCodexModels(provider) {
const spawned = resolveProbeSpawn(provider, 'codex', ['app-server']);
- const probe = spawned.label;
+ // Only needed here for the Windows shim search — `probeCodexModelsViaAppServer`
+ // rebuilds the same merge itself from `provider.envVars` before spawning.
const childEnv = { ...process.env, ...provider?.envVars };
const resolvedBin = resolveWindowsExecutable(spawned.command, process.platform === 'win32', childEnv) || spawned.command;
const { command, args } = prepareWindowsSafeSpawn(resolvedBin, spawned.args);
- return new Promise((resolve, reject) => {
- let settled = false;
- let child;
- const settle = (err, result) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- try { child?.kill('SIGTERM'); } catch {}
- if (err) reject(err);
- else resolve(result);
- };
- const timer = setTimeout(() => {
- settle(new Error(`${probe} timed out waiting for model catalog`));
- }, 15000);
- timer.unref?.();
- try {
- child = spawn(command, args, {
- stdio: ['pipe', 'pipe', 'pipe'],
- env: childEnv,
- windowsHide: true,
- });
- } catch (err) {
- settle(new Error(`${probe} failed to spawn: ${err?.message || err}`));
- return;
- }
- child.on('error', (err) => settle(new Error(`${probe} failed: ${err?.message || err}`)));
- child.stdin?.on('error', () => {});
- child.on('exit', (code, signal) => settle(new Error(`${probe} exited prematurely with code ${code ?? signal}`)));
-
- let buffer = '';
- child.stdout?.on('data', (chunk) => {
- buffer += chunk.toString();
- const lines = buffer.split('\n');
- buffer = lines.pop() ?? '';
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- try {
- const msg = JSON.parse(trimmed);
- if (msg.id === 1) {
- child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', method: 'initialized', params: {} }) + '\n');
- child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'model/list', params: {} }) + '\n');
- } else if (msg.id === 2) {
- if (msg.error) {
- settle(new Error(`${probe} model/list error: ${msg.error.message || JSON.stringify(msg.error)}`));
- return;
- }
- const rawModels = msg.result?.data || msg.result?.models || [];
- const ids = rawModels
- .filter(m => !m.hidden)
- .map(m => (typeof m === 'string' ? m : m?.id || m?.model))
- .filter(Boolean);
- if (ids.length === 0) {
- settle(new Error(`${probe} returned no model ids`));
- return;
- }
- settle(null, [...new Set(ids)]);
- return;
- }
- } catch {}
- }
- });
- child.stdin?.write(JSON.stringify({
- jsonrpc: '2.0',
- id: 1,
- method: 'initialize',
- params: { clientInfo: { name: 'portos', version: '1.0.0' } },
- }) + '\n');
- });
+ // `probeCodexModelsViaAppServer` is the shared leaf (`codexModelListProbe.js`)
+ // — the Harnesses page refresh (`services/harnesses.js`) drives the same
+ // probe from a resolved command/args with no toolkit `provider` shape (#8497).
+ return probeCodexModelsViaAppServer(command, args, provider, { label: spawned.label });
},
async _fetchOllamaToolCapableModels(provider) {
diff --git a/server/lib/aiToolkit/internal/windowsSafeSpawn.js b/server/lib/aiToolkit/internal/windowsSafeSpawn.js
new file mode 100644
index 0000000000..ce32a5d32f
--- /dev/null
+++ b/server/lib/aiToolkit/internal/windowsSafeSpawn.js
@@ -0,0 +1,57 @@
+/**
+ * Windows-safe spawn helpers shared by every CLI probe that resolves a bare
+ * command name into an executable path before handing it to `spawn`/`execFile`.
+ *
+ * Lives here (its own leaf) rather than inline in `providerCatalogService.js`
+ * because `internal/codexAppServer.js` needs the same resolution and this
+ * directory stays self-contained — no imports out, so a second copy of these
+ * rules is the alternative to importing this file.
+ */
+import { existsSync } from 'fs';
+import { join, isAbsolute, delimiter } from 'path';
+
+const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];
+
+/**
+ * The absolute path of a bare command's Windows shim (`.exe`/`.cmd`/`.bat`/`.com`),
+ * or `null` off-Windows, for an already-absolute/pathed command, or when no
+ * shim is on `PATH`. `execFile` under `shell: false` refuses a bare `.cmd`
+ * name outright, so a caller that only has the vendor's bare command must
+ * resolve it first or the probe silently answers nothing.
+ */
+export function resolveWindowsExecutable(command, isWin32 = process.platform === 'win32', searchEnv = process.env) {
+ if (!isWin32 || !command || isAbsolute(command) || /[\\/]/.test(command)) return null;
+ const pathDirs = (searchEnv.PATH || searchEnv.Path || '').split(delimiter).filter(Boolean);
+ for (const dir of pathDirs) {
+ for (const ext of WIN_EXECUTABLE_EXTS) {
+ const candidate = join(dir, `${command}${ext}`);
+ if (existsSync(candidate)) return candidate;
+ }
+ }
+ return null;
+}
+
+const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;
+const CMD_METACHAR_RE = /[&|<>^()]/g;
+const NEEDS_NODE_QUOTING_RE = /[\s"]/;
+
+function escapeCmdMetacharsIfUnquoted(value) {
+ const str = String(value);
+ if (NEEDS_NODE_QUOTING_RE.test(str)) return str;
+ return str.replace(CMD_METACHAR_RE, '^$&');
+}
+
+/**
+ * A `.cmd`/`.bat` target must run through `cmd.exe /c`, or `spawn` under
+ * `shell: false` cannot execute it at all. Every other command/argv pair
+ * passes through unchanged.
+ */
+export function prepareWindowsSafeSpawn(command, args, isWin32 = process.platform === 'win32') {
+ if (isWin32 && WIN_BATCH_EXT_RE.test(command)) {
+ return {
+ command: 'cmd.exe',
+ args: ['/c', escapeCmdMetacharsIfUnquoted(command), ...args.map(escapeCmdMetacharsIfUnquoted)],
+ };
+ }
+ return { command, args };
+}
diff --git a/server/lib/cliChildEnv.test.js b/server/lib/cliChildEnv.test.js
index db92101207..f9ca0ae070 100644
--- a/server/lib/cliChildEnv.test.js
+++ b/server/lib/cliChildEnv.test.js
@@ -683,7 +683,12 @@ describe('no spawn site rebuilds the CLI child env by hand', () => {
// composer, and the dormancy is why its missing CLAUDECODE strip / OpenCode
// map is not a live PortOS gap someone needs to chase.
['lib/aiToolkit/runner.js', 'vendored toolkit — must not import out to other PortOS modules, and its spawn is dormant under PortOS\'s setCliRunner override'],
- ['lib/aiToolkit/internal/providerCatalogService.js', 'vendored toolkit catalog probes — must not import out to other PortOS modules'],
+ // `providerCatalogService.js`'s Codex probe moved its spawn into this leaf
+ // (#8497) so a host caller with no toolkit `provider` record — the
+ // Harnesses page refresh in `services/harnesses.js` — can drive the same
+ // JSON-RPC handshake; the file that now spreads `provider.envVars` next to
+ // a `spawn(` call is this one, not `providerCatalogService.js`.
+ ['lib/aiToolkit/internal/codexModelListProbe.js', 'vendored toolkit catalog probe — must not import out to other PortOS modules'],
]);
// Two independent markers, because either one alone has a blind spot: a new
diff --git a/server/routes/providers.services.test.js b/server/routes/providers.services.test.js
index cc5845a226..6f00e3827a 100644
--- a/server/routes/providers.services.test.js
+++ b/server/routes/providers.services.test.js
@@ -305,17 +305,23 @@ describe('POST /api/providers/services/:slug/refresh-catalog', () => {
expect(ok.body.service.catalog).toMatchObject({ state: 'known', models: ['claude-a', 'claude-b'] });
});
- it('falls back to a bound route\'s own lister when the harness has no models command', async () => {
+ // Codex's row now has its own lister (`listModels`, driving `codex
+ // app-server` — services/harnesses.js #8497), so `listByHarness` no longer
+ // falls back to a bound route's toolkit lister for a harness that refuses
+ // with `noLister`. A harness with no lister at all just fails, as any other
+ // refusal does.
+ it('does not fall back to a bound route\'s own lister when the harness has no models command', async () => {
const withRoute = graphFixture();
withRoute.bindings.push({ id: '99999999-9999-4999-8999-999999999999', revision: 1, connectionId: CLAUDE_SUB, harnessId: 'claude', variantKey: 'default', label: 'Claude', enabled: true, selectedModels: [] });
withRoute.routes.push({ providerId: 'example-claude-tui', bindingId: '99999999-9999-4999-8999-999999999999' });
store.readGraph.mockResolvedValue(withRoute);
harnessModels.mockResolvedValue({ ok: false, reason: 'Claude Code has no command for listing its models.', noLister: true, models: [], updated: [] });
- providerService.fetchProviderModels.mockResolvedValue(['claude-new', 'claude-example']);
const res = await request(app()).post('/api/providers/services/claude-subscription/refresh-catalog');
- expect(providerService.fetchProviderModels).toHaveBeenCalledWith('example-claude-tui');
- expect(res.body.service.catalog).toMatchObject({ state: 'known', models: ['claude-new', 'claude-example'] });
+ expect(providerService.fetchProviderModels).not.toHaveBeenCalled();
+ expect(res.body.service.catalog).toMatchObject({
+ state: 'failed', models: ['claude-example'], error: 'Claude Code has no command for listing its models.',
+ });
});
it('refreshes a derived preset through its service catalog, never onto the record alone', async () => {
diff --git a/server/services/harnesses.js b/server/services/harnesses.js
index de3a309a74..bc00c40d83 100644
--- a/server/services/harnesses.js
+++ b/server/services/harnesses.js
@@ -35,12 +35,14 @@ import { prepareCliSpawn } from '../lib/bufferedSpawn.js';
import { hasCredentialBootstrap, resolveCliSpawn } from '../lib/credentialBootstrap.js';
import { commandOutput } from '../lib/commandExists.js';
import { compareHarnessVersions, parseHarnessModels, parseNpmLatestVersion } from '../lib/harnessOutput.js';
+import { isDerivedPreset } from '../lib/providerGraphRecords.js';
import { findCommandOnPath } from '../lib/processEnv.js';
import { primeOpencodeCatalogCache } from '../lib/opencodeCatalogCache.js';
import { getOpencodeLocalProviderNamespace, isConfiguredDefaultModel } from '../lib/providerModels.js';
import { providerRuntimeKey } from '../lib/providerPrerequisites.js';
import { createStaleWhileRevalidate } from '../lib/staleWhileRevalidate.js';
import * as providerService from './providers.js';
+import { providerGraphEnabled } from './providerGraph.js';
import {
PROVIDER_RUNTIMES,
getProviderRuntime,
@@ -136,10 +138,10 @@ export const usesHarnessCatalog = (provider) =>
*
* The full precondition for {@link refreshHarnessModels} in one place: the
* binary this record launches must know how to enumerate its models
- * (`modelsArgs`), and the record must be a plain wrapper rather than one
- * pointed at a local daemon or a hosted gateway ({@link usesHarnessCatalog}).
- * A custom binary resolves to no runtime row at all and answers `null` on the
- * first question.
+ * (`modelsArgs` or `listModels`), and the record must be a plain wrapper
+ * rather than one pointed at a local daemon or a hosted gateway
+ * ({@link usesHarnessCatalog}). A custom binary resolves to no runtime row at
+ * all and answers `null` on the first question.
*
* Lives here rather than beside its caller because the answer is exactly the
* set this refresh may rewrite, and TWO places ask it: the provider card's
@@ -151,7 +153,7 @@ export const usesHarnessCatalog = (provider) =>
*/
export const harnessCatalogRuntime = (provider) => {
const runtime = getProviderRuntime(providerRuntimeKey(provider));
- return runtime?.modelsArgs && usesHarnessCatalog(provider) ? runtime : null;
+ return (runtime?.modelsArgs || runtime?.listModels) && usesHarnessCatalog(provider) ? runtime : null;
};
/**
@@ -304,10 +306,28 @@ const credentialProbeGroups = (targets) => {
/**
* Write one probe's catalog to the records that probe answers for, and return
* the ids actually rewritten.
+ *
+ * A DERIVED preset (#7565) never receives this write directly: its `models`
+ * IS its service's catalog narrowed, so the next re-derivation would discard
+ * whatever landed here and the underlying catalog would stay stale forever —
+ * exactly the bug the Harnesses page's bulk refresh shipped with, because it
+ * (unlike the provider card's own button, `POST /:id/refresh-models`) has no
+ * single record to special-case. Refresh the SERVICE instead, once per
+ * `serviceId` even when several of its presets target this harness, and reuse
+ * the catalog this call already fetched — passing it back through as an
+ * injected `harnessModels` answers `refreshServiceCatalog`'s harness strategy
+ * with no second probe and no re-entry into `refreshHarnessModels` (#8497).
*/
async function applyHarnessCatalog(runtime, models, targets) {
const updated = [];
+ const derivedProviderIdsByService = new Map();
for (const provider of targets) {
+ if (isDerivedPreset(provider) && providerGraphEnabled()) {
+ const ids = derivedProviderIdsByService.get(provider.serviceId) || [];
+ ids.push(provider.id);
+ derivedProviderIdsByService.set(provider.serviceId, ids);
+ continue;
+ }
// Hold the record's namespace scope (see `storedNamespaces`). A filter that
// matched nothing means the harness no longer lists anything this record is
// for — skip it rather than blanking a working list on that evidence.
@@ -336,6 +356,20 @@ async function applyHarnessCatalog(runtime, models, targets) {
await providerService.updateProvider(provider.id, { models: next, defaultModel });
updated.push(provider.id);
}
+ if (derivedProviderIdsByService.size > 0) {
+ // Deferred: a bulk-refresh path that most calls never touch should not
+ // drag the whole provider-graph module into every caller of this file
+ // (server/AGENTS.md "Import scoping").
+ const { refreshServiceCatalog } = await import('./providerServices.js');
+ const alreadyListed = async () => ({ ok: true, models });
+ for (const [serviceId, providerIds] of derivedProviderIdsByService) {
+ const outcome = await refreshServiceCatalog(serviceId, { harnessModels: alreadyListed }).catch((err) => {
+ console.error(`❌ ${runtime.label}: could not refresh service "${serviceId}"'s catalog: ${err?.message || err}`);
+ return null;
+ });
+ if (outcome?.service?.catalog?.state !== 'failed') updated.push(...providerIds);
+ }
+ }
return updated;
}
@@ -364,10 +398,16 @@ async function applyHarnessCatalog(runtime, models, targets) {
*
* @returns {Promise<{ok:boolean, reason?:string, models:string[], updated:string[]}>}
*/
-export async function refreshHarnessModels(id, { run = commandOutput, providerId = null, ...probeDeps } = {}) {
+export async function refreshHarnessModels(id, { run = commandOutput, providerId = null, listModels, ...probeDeps } = {}) {
const runtime = getProviderRuntime(id);
if (!runtime) return { ok: false, reason: 'Unknown harness.', models: [], updated: [] };
- if (!runtime.modelsArgs) {
+ // `listModels` is the alternative to `modelsArgs` for a harness whose
+ // catalog cannot be read from a single argv + stdout capture (Codex's lives
+ // behind an `app-server` JSON-RPC handshake — `providerRuntimeInstaller.js`).
+ // The caller may override it (tests do, to skip the real spawn), but never
+ // supplies one for a harness whose row declares its own.
+ const listModelsImpl = listModels || runtime.listModels;
+ if (!runtime.modelsArgs && !listModelsImpl) {
return {
ok: false,
reason: `${runtime.label} has no command for listing its models, so PortOS cannot refresh them from here.`,
@@ -431,6 +471,21 @@ export async function refreshHarnessModels(id, { run = commandOutput, providerId
// (its harness need not be there); `resolveCliSpawn` resolves the bootstrap
// binary's own shim instead.
const resolved = group.probeAs ? null : await findCommand(runtime.command);
+ if (listModelsImpl) {
+ // A harness-specific lister owns its own spawn shape (Codex drives a
+ // JSON-RPC handshake, not a single argv + stdout capture) — hand it the
+ // same resolved credential/command context `resolveCliSpawn` would use.
+ // Per-bucket, same as the generic path below: one credential's failure
+ // must not fail buckets probed under a different one.
+ const listed = await listModelsImpl({
+ probeAs: group.probeAs,
+ resolvedCommand: resolved || runtime.command,
+ env: process.env,
+ timeoutMs: MODELS_PROBE_TIMEOUT_MS,
+ }).catch((err) => ({ error: err?.message || `${runtime.label} failed to list its models.` }));
+ if (Array.isArray(listed) && listed.length > 0) return { group, listed };
+ return { group, failure: Array.isArray(listed) ? `${runtime.label} returned no models.` : listed.error };
+ }
const probe = resolveCliSpawn(group.probeAs, resolved || runtime.command, [...runtime.modelsArgs], process.env);
const listed = parseHarnessModels(runtime.id, await run(probe.command, probe.args, { timeoutMs: MODELS_PROBE_TIMEOUT_MS }));
if (listed.length > 0) return { group, listed };
diff --git a/server/services/harnesses.test.js b/server/services/harnesses.test.js
index 4d0d37cc15..1ba1b382d6 100644
--- a/server/services/harnesses.test.js
+++ b/server/services/harnesses.test.js
@@ -22,6 +22,18 @@ const providerService = vi.hoisted(() => ({
}));
vi.mock('./providers.js', () => providerService);
+// Defaults to `false` so every existing test (none of which seeds a
+// structurally-derived-preset record) keeps exercising the plain write path.
+const providerGraph = vi.hoisted(() => ({ providerGraphEnabled: vi.fn(() => false) }));
+vi.mock('./providerGraph.js', () => providerGraph);
+
+// Dynamically imported only on the derived-preset path (`applyHarnessCatalog`)
+// — see `services/providerGraph.js` "Import scoping" precedent.
+const providerServices = vi.hoisted(() => ({
+ refreshServiceCatalog: vi.fn(async () => ({ service: { catalog: { state: 'known', models: [] } } })),
+}));
+vi.mock('./providerServices.js', () => providerServices);
+
import { prepareCliSpawn } from '../lib/bufferedSpawn.js';
import {
__resetLatestVersionCache,
@@ -55,6 +67,9 @@ beforeEach(() => {
providerService.listProviders.mockResolvedValue(Object.values(providers));
providerService.updateProvider.mockClear();
opencodeCatalog.primeOpencodeCatalogCache.mockClear();
+ providerGraph.providerGraphEnabled.mockReturnValue(false);
+ providerServices.refreshServiceCatalog.mockClear();
+ providerServices.refreshServiceCatalog.mockResolvedValue({ service: { catalog: { state: 'known', models: [] } } });
});
// `usesHarnessCatalog` keys on the ABSENCE of a backend marker, so the class it
@@ -85,6 +100,11 @@ describe('the shipped records a harness refresh may rewrite', () => {
// `openchamber-cli`, whose `models` subcommand prints its runtime's
// SETTINGS rather than a catalog, so its row declares no `modelsArgs`.
'antigravity-cli', 'antigravity-tui',
+ // Codex has no `modelsArgs` — its lister is the `listModels` hook that
+ // drives `codex app-server`'s JSON-RPC handshake instead (#8497). Its
+ // `-ollama`/`-lmstudio` siblings carry a local-runtime marker and stay
+ // correctly absent.
+ 'codex', 'codex-tui',
'cursor-cli', 'cursor-tui',
'grok-cli', 'grok-tui',
// Kilo serves whatever the user's own `/connect` credentials reach, which
@@ -480,4 +500,125 @@ describe('refreshHarnessModels', () => {
expect((await refreshHarnessModels('not-a-harness')).ok).toBe(false);
});
+
+ // Codex has no `models` subcommand — its row declares `listModels` instead,
+ // which drives `codex app-server`'s JSON-RPC handshake (#8497). Injected here
+ // so the suite never spawns a real process.
+ describe('a harness whose row declares listModels (Codex)', () => {
+ it('lists through the injected hook instead of modelsArgs, with bare ids and no namespace filter', async () => {
+ providerService.listProviders.mockResolvedValue([
+ { id: 'codex', type: 'cli', command: 'codex', models: ['gpt-5.6-terra'], defaultModel: 'gpt-5.6-terra' },
+ ]);
+ const listModels = vi.fn(async ({ probeAs, resolvedCommand, timeoutMs }) => {
+ expect(probeAs).toBe(null);
+ expect(resolvedCommand).toBe('/example/codex');
+ expect(timeoutMs).toBeGreaterThan(0);
+ return ['gpt-6-astra', 'gpt-6-sol'];
+ });
+
+ const result = await refreshHarnessModels('codex', { run: vi.fn(async () => '0.50.0'), listModels, ...found });
+
+ expect(result.ok).toBe(true);
+ expect(result.models).toEqual(['gpt-6-astra', 'gpt-6-sol']);
+ expect(result.updated).toEqual(['codex']);
+ expect(listModels).toHaveBeenCalledTimes(1);
+ const [, patch] = providerService.updateProvider.mock.calls[0];
+ expect(patch.models).toEqual(['gpt-6-astra', 'gpt-6-sol']);
+ });
+
+ it('surfaces the hook’s own failure as this bucket’s reason', async () => {
+ providerService.listProviders.mockResolvedValue([
+ { id: 'codex', type: 'cli', command: 'codex', models: [], defaultModel: null },
+ ]);
+ const listModels = vi.fn(async () => {
+ throw new Error("'codex app-server' exited prematurely with code 1");
+ });
+
+ const result = await refreshHarnessModels('codex', { run: vi.fn(async () => '0.50.0'), listModels, ...found });
+
+ expect(result.ok).toBe(false);
+ expect(result.reason).toContain('exited prematurely');
+ expect(providerService.updateProvider).not.toHaveBeenCalled();
+ });
+
+ it('still refuses with no lister when neither modelsArgs nor listModels is supplied', async () => {
+ // Claude Code's row declares neither — unaffected by adding Codex's hook.
+ const result = await refreshHarnessModels('claude', { run: vi.fn(async () => '2.1.259'), ...found });
+ expect(result.ok).toBe(false);
+ expect(result.noLister).toBe(true);
+ });
+ });
+});
+
+// A DERIVED preset's `models` IS its service's catalog narrowed (#7565): the
+// Harnesses page's bulk refresh has no single record to special-case the way
+// the provider card's own button does, so `applyHarnessCatalog` must skip the
+// raw write itself and refresh the service instead (#8497).
+describe('applyHarnessCatalog — derived presets', () => {
+ const derivedPreset = (overrides) => ({
+ type: 'cli', command: 'opencode', models: [], harnessId: 'opencode', method: 'cli', serviceId: 'opencode-zen', ...overrides,
+ });
+
+ it('never PATCHes a derived preset directly — refreshes its service catalog with the already-fetched models', async () => {
+ providerGraph.providerGraphEnabled.mockReturnValue(true);
+ const run = vi.fn(async (command, args) => (args[0] === 'models' ? OPENCODE_MODELS : '1.18.27'));
+ providerService.listProviders.mockResolvedValue([derivedPreset({ id: 'opencode-zen-derived' })]);
+
+ const result = await refreshHarnessModels('opencode', { run, ...found });
+
+ expect(result.ok).toBe(true);
+ expect(providerService.updateProvider).not.toHaveBeenCalled();
+ expect(providerServices.refreshServiceCatalog).toHaveBeenCalledTimes(1);
+ const [serviceId, deps] = providerServices.refreshServiceCatalog.mock.calls[0];
+ expect(serviceId).toBe('opencode-zen');
+ // The injected `harnessModels` answers with the catalog THIS call already
+ // fetched — the service refresh must not re-spawn the CLI (which would
+ // also recurse straight back into `refreshHarnessModels`).
+ await expect(deps.harnessModels()).resolves.toEqual({
+ ok: true, models: ['opencode/big-pickle', 'opencode/mimo-v2.5-free'],
+ });
+ expect(result.updated).toEqual(['opencode-zen-derived']);
+ });
+
+ it('refreshes one service once even when several of its presets share it', async () => {
+ providerGraph.providerGraphEnabled.mockReturnValue(true);
+ const run = vi.fn(async (command, args) => (args[0] === 'models' ? OPENCODE_MODELS : '1.18.27'));
+ providerService.listProviders.mockResolvedValue([
+ derivedPreset({ id: 'preset-a', method: 'cli' }),
+ derivedPreset({ id: 'preset-b', type: 'tui', method: 'tui' }),
+ ]);
+
+ const result = await refreshHarnessModels('opencode', { run, ...found });
+
+ expect(providerServices.refreshServiceCatalog).toHaveBeenCalledTimes(1);
+ expect(result.updated.sort()).toEqual(['preset-a', 'preset-b']);
+ });
+
+ it('does not report a service as updated when its catalog refresh failed', async () => {
+ providerGraph.providerGraphEnabled.mockReturnValue(true);
+ providerServices.refreshServiceCatalog.mockResolvedValue({ service: { catalog: { state: 'failed', error: 'boom' } } });
+ const run = vi.fn(async (command, args) => (args[0] === 'models' ? OPENCODE_MODELS : '1.18.27'));
+ providerService.listProviders.mockResolvedValue([derivedPreset({ id: 'preset-a' })]);
+
+ const result = await refreshHarnessModels('opencode', { run, ...found });
+
+ expect(result.updated).toEqual([]);
+ });
+
+ it('falls back to the plain write when the provider graph is disabled', async () => {
+ // No live graph means no service behind the record to refresh — the shape
+ // alone is not enough; write it directly, same as before this change.
+ providerGraph.providerGraphEnabled.mockReturnValue(false);
+ const run = vi.fn(async (command, args) => (args[0] === 'models' ? OPENCODE_MODELS : '1.18.27'));
+ providerService.listProviders.mockResolvedValue([
+ derivedPreset({ id: 'preset-a', models: ['opencode/stale'], defaultModel: 'opencode/stale' }),
+ ]);
+
+ await refreshHarnessModels('opencode', { run, ...found });
+
+ expect(providerServices.refreshServiceCatalog).not.toHaveBeenCalled();
+ expect(providerService.updateProvider).toHaveBeenCalledWith('preset-a', expect.objectContaining({
+ models: ['opencode/big-pickle', 'opencode/mimo-v2.5-free'],
+ }));
+ });
});
diff --git a/server/services/providerRuntimeInstaller.js b/server/services/providerRuntimeInstaller.js
index 48cfd599f3..447f16af89 100644
--- a/server/services/providerRuntimeInstaller.js
+++ b/server/services/providerRuntimeInstaller.js
@@ -111,6 +111,27 @@ const RUNTIME_ROWS = [
install: { kind: 'npm', package: '@openai/codex@latest' },
selfUpdate: ['update'],
docsUrl: 'https://developers.openai.com/codex/cli',
+ // Codex has no `models` subcommand — its catalog lives behind the
+ // `codex app-server` JSON-RPC handshake, which the toolkit already speaks
+ // for a provider's own "Refresh models" button
+ // (`_fetchCodexModels`/`internal/codexModelListProbe.js`). `listModels` is
+ // the harness-table alternative to `modelsArgs` for exactly this shape: a
+ // lister that cannot be driven by a bare argv + stdout capture (#8497).
+ listModels: async ({ probeAs, resolvedCommand, env, timeoutMs }) => {
+ const [{ resolveCliSpawn }, { probeCodexModelsViaAppServer }, { prepareWindowsSafeSpawn, resolveWindowsExecutable }] = await Promise.all([
+ import('../lib/credentialBootstrap.js'),
+ import('../lib/aiToolkit/internal/codexModelListProbe.js'),
+ import('../lib/aiToolkit/internal/windowsSafeSpawn.js'),
+ ]);
+ const spawned = resolveCliSpawn(probeAs, resolvedCommand, ['app-server'], env);
+ const isWin32 = process.platform === 'win32';
+ const resolvedBin = resolveWindowsExecutable(spawned.command, isWin32, env) || spawned.command;
+ const { command, args } = prepareWindowsSafeSpawn(resolvedBin, spawned.args, isWin32);
+ // No toolkit `provider` record at this layer — the harness probe runs
+ // under the ambient/bootstrap `env` already resolved above, with no
+ // per-record `envVars` overlay to merge.
+ return probeCodexModelsViaAppServer(command, args, null, { timeoutMs, label: `'${spawned.command} ${spawned.args.join(' ')}'` });
+ },
},
{
vendor: 'opencode',
@@ -197,10 +218,18 @@ const vendorRow = (vendorId) => {
* an install goes stale with no visible way to refresh it. `npmPackage` is
* present only for `npm`-kind rows, and it is what makes a row REMOVABLE: a
* script-installed binary has no vendor-published uninstall PortOS can run.
+ *
+ * `listModels` is the alternative to `modelsArgs` for a harness whose catalog
+ * cannot be read from a single argv + stdout capture (Codex's lives behind an
+ * `app-server` JSON-RPC handshake). `refreshHarnessModels` calls it with the
+ * resolved probe context (`{ probeAs, resolvedCommand, env, timeoutMs }`)
+ * instead of spawning `[...modelsArgs]` through the generic `run` probe; a row
+ * declares at most one of the two.
*/
export const PROVIDER_RUNTIMES = Object.freeze(RUNTIME_ROWS.map((row) => Object.freeze({
selfUpdate: null,
modelsArgs: null,
+ listModels: null,
...row,
// The accepted binary spellings come from the VENDOR row, the same list
// `matchCommand` and the runner's allowlist read — a card looks its runtime up
@@ -287,7 +316,7 @@ async function probeRuntimeStatus(runtime, findCommand, probeCommand) {
// button per row instead of keeping its own copy of this table.
updatable: Boolean(runtime.selfUpdate) || (kind === 'npm' && Boolean(toolPath)),
removable: Boolean(runtime.npmPackage) && Boolean(toolPath),
- listsModels: Boolean(runtime.modelsArgs),
+ listsModels: Boolean(runtime.modelsArgs || runtime.listModels),
};
}
diff --git a/server/services/providerServices.js b/server/services/providerServices.js
index 42345a294b..acf46ac961 100644
--- a/server/services/providerServices.js
+++ b/server/services/providerServices.js
@@ -12,11 +12,9 @@ import {
takenServiceSlugs,
toServiceDto,
} from '../lib/providerServiceInstances.js';
-import { requireToolkit } from '../lib/aiToolkitState.js';
import { isNonBlankStr } from '../lib/textUtils.js';
import { resolveServiceInstance, serviceDefinitionById } from '../lib/serviceDefinitions.js';
import {
- connectionFanout,
findConnectionByRef,
rematerializeDerivedPresets,
requireProviderGraph,
@@ -82,21 +80,19 @@ async function listByProbe(connection, definition, { env, probe }) {
/**
* Ask the program that signs in. `ok: false` — an uninstalled binary, a
- * signed-out CLI, a refused probe — is a failure with its reason, never an
- * empty catalog: `refreshHarnessModels` already refuses to report a blank
- * listing as "zero models", and this keeps that refusal.
+ * signed-out CLI, a refused probe, a harness with no lister — is a failure
+ * with its reason, never an empty catalog: `refreshHarnessModels` already
+ * refuses to report a blank listing as "zero models", and this keeps that
+ * refusal.
*
- * A harness with no `models` verb (Codex lists through `codex app-server`)
- * falls back to a bound route's toolkit lister, so its derived presets can
- * still pick up new models. Any other refusal stays a refusal.
+ * Every `catalog.strategy: 'harness'` definition now names a harness that can
+ * actually enumerate its own models (`modelsArgs` or the JSON-RPC `listModels`
+ * hook Codex uses — `services/harnesses.js`, #8497); there is no longer a
+ * bound-route fallback to a toolkit lister for one that cannot.
*/
-async function listByHarness(connection, definition, graph, { harnessModels, routeModels }) {
+async function listByHarness(definition, { harnessModels }) {
const result = await harnessModels(definition.harnessOnly);
if (result?.ok) return { refreshed: true, models: result.models || [] };
- for (const route of result?.noLister ? connectionFanout(graph, connection.id).routes : []) {
- const models = await routeModels(route.providerId).catch(() => null);
- if (Array.isArray(models) && models.length > 0) return { refreshed: true, models };
- }
return { refreshed: false, error: result?.reason || `${definition.label} could not list its models` };
}
@@ -105,13 +101,13 @@ async function listByHarness(connection, definition, graph, { harnessModels, rou
* has nothing to ask: the instance's declared list IS the catalog, re-stamped
* as known.
*/
-async function listByStrategy(connection, definition, graph, deps) {
+async function listByStrategy(connection, definition, deps) {
switch (definition.catalog.strategy) {
case 'probe':
case 'daemon':
return listByProbe(connection, definition, deps);
case 'harness':
- return listByHarness(connection, definition, graph, deps);
+ return listByHarness(definition, deps);
case 'static':
return { refreshed: true, models: connection.catalog?.models || [] };
default:
@@ -131,8 +127,6 @@ const defaultDeps = () => ({
const runtime = PROVIDER_RUNTIMES.find((row) => row.vendor === harnessId || row.id === harnessId)?.id ?? harnessId;
return refreshHarnessModels(runtime);
},
- // Probe-only: the answer lands in the instance catalog, never on the record.
- routeModels: (providerId) => requireToolkit().services.providers.fetchProviderModels(providerId),
now: () => new Date().toISOString(),
});
@@ -245,7 +239,7 @@ export async function updateService(ref, input) {
* route model list is touched.
*/
export function refreshServiceCatalog(ref, deps = {}) {
- const { env, probe, harnessModels, routeModels, now } = { ...defaultDeps(), ...deps };
+ const { env, probe, harnessModels, now } = { ...defaultDeps(), ...deps };
return serializeProviderGraph(async () => {
requireProviderGraph();
const [graph, envFile] = await Promise.all([readGraph(), loadInstallEnvFile()]);
@@ -256,7 +250,7 @@ export function refreshServiceCatalog(ref, deps = {}) {
{ status: 409, code: 'SERVICE_DEFINITION_UNKNOWN' });
}
- const outcome = await listByStrategy(connection, definition, graph, { env, probe, harnessModels, routeModels })
+ const outcome = await listByStrategy(connection, definition, { env, probe, harnessModels })
.catch((err) => ({ refreshed: false, error: err }));
const catalog = nextConnectionCatalog(connection.catalog, {
...outcome,