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

feat: run the Codex harness on a local Ollama model via codex's native --oss flags (#6305)

[._.]/ Adam Eivy545fdfa64bc1
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 4eac030c5d..d12f2f6160 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -109,7 +109,12 @@ export const isGrokProvider = (provider) => {
*/
export const isCodexSubscriptionProvider = (provider) =>
(provider?.type === 'cli' || provider?.type === 'tui')
- && commandBasename(provider?.command) === 'codex';
+ && commandBasename(provider?.command) === 'codex'
+ // A local-runtime-backed codex record (`codex --oss --local-provider ollama`)
+ // generates its tokens on this machine and authenticates against nothing, so
+ // it must not be painted "No ChatGPT account is signed in" — or parked in
+ // UNKNOWN waiting on an account read that will never matter.
+ && localRuntimeNamespace(provider) === null;
/**
* The 'your own ~/.codex/config.toml is re-pointing this provider' advisory the
@@ -449,12 +454,7 @@ const codexEffortLevelsForModel = (model) => CODEX_ULTRA_MODELS.has(String(model
export const isOpencodeLocalProvider = (provider) =>
(['opencode', 'opencode-tui'].includes(String(provider?.id || '').toLowerCase())
|| commandBasename(provider?.command) === 'opencode')
- && (provider?.ollamaBacked === true
- || provider?.mtplxBacked === true
- || provider?.llamaBacked === true
- || provider?.vllmBacked === true
- || provider?.sglangBacked === true
- || isGatewayBackedProvider(provider));
+ && (localRuntimeNamespace(provider) !== null || isGatewayBackedProvider(provider));
/**
* Antigravity base-model ↔ effort-suffix split — MIRROR of
@@ -1522,6 +1522,26 @@ export const gatewayForProvider = (provider) => {
/** True when a provider is an OpenCode wrapper front-ending any hosted gateway. */
export const isGatewayBackedProvider = (provider) => gatewayForProvider(provider) !== null;
+/**
+ * The LOCAL daemon namespace a provider is marked with, or null. Structural
+ * markers only — a hosted gateway is an OpenCode namespace and a remote API, so
+ * it is deliberately NOT one of these.
+ *
+ * MIRROR of `localRuntimeNamespace` in server/lib/providerModels.js — keep in
+ * lockstep. The order matters: a malformed record carrying two markers keeps its
+ * legacy Ollama outcome on both sides.
+ * @param {{ollamaBacked?:boolean,mtplxBacked?:boolean,llamaBacked?:boolean,vllmBacked?:boolean,sglangBacked?:boolean}|null|undefined} provider
+ * @returns {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|null}
+ */
+export const localRuntimeNamespace = (provider) => {
+ if (provider?.ollamaBacked === true) return 'ollama';
+ if (provider?.mtplxBacked === true) return 'mtplx';
+ if (provider?.llamaBacked === true) return 'llama';
+ if (provider?.vllmBacked === true) return 'vllm';
+ if (provider?.sglangBacked === true) return 'sglang';
+ return null;
+};
+
/**
* True when a provider launches the Claude Code binary, whatever backend it is
* pointed at (`claude-code`, `claude-ollama`, `claude-sglang`, or any renamed
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 36e3ce31c6..b38210ce01 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -1202,7 +1202,8 @@ describe('supportsModelRefresh', () => {
expect(withButton).toEqual([
'antigravity-cli', 'antigravity-tui', 'cerebras', 'claude-code',
'claude-code-bedrock', 'claude-ollama', 'claude-ollama-tui',
- 'claude-sglang', 'claude-sglang-tui', 'codex', 'codex-tui', 'cursor-cli',
+ 'claude-sglang', 'claude-sglang-tui', 'codex', 'codex-ollama', 'codex-tui',
+ 'cursor-cli',
'cursor-tui', 'grok', 'lmstudio', 'mtplx', 'nvidia-kimi', 'ollama',
'opencode-llama-tui',
'opencode-mtplx', 'opencode-mtplx-tui', 'opencode-ollama',
@@ -1613,6 +1614,22 @@ describe('credentialSource', () => {
expect(credentialSource(renamed)).toEqual({ kind: 'env', ref: 'CUSTOM_API_KEY' });
});
+ it('exempts a local-backed Codex record from the ChatGPT subscription contract', () => {
+ // `codex --oss --local-provider ollama` generates its tokens on this machine
+ // and authenticates against nothing, so the account is not one of its
+ // prerequisites — without this the card claims "No ChatGPT account is signed
+ // in" and, worse, parks in UNKNOWN awaiting a read that never matters.
+ // MIRROR of server/lib/codexAccount.js#isCodexSubscriptionProvider.
+ const local = SHIPPED_PROVIDERS.providers['codex-ollama'];
+ expect(local.ollamaBacked).toBe(true);
+ expect(isCodexSubscriptionProvider(local)).toBe(false);
+ expect(isCodexSubscriptionProvider(SHIPPED_PROVIDERS.providers.codex)).toBe(true);
+ // An enabled copy: a codex-command card whose account read came back with
+ // no verdict parks in UNKNOWN, which this record must never reach.
+ const enabled = { ...local, enabled: true, missingPrerequisites: [] };
+ expect(providerCardState(enabled, { codexAccount: null }).state).toBe(PROVIDER_CARD_STATE.READY);
+ });
+
it('lets a wrapper carrying its own key stand down from inheritance', () => {
expect(credentialSource({ id: 'wrapper', type: 'cli', apiKey: 'sk-example', orcarouterBacked: true }))
.toEqual({ kind: 'stored', ref: 'wrapper' });
diff --git a/data.reference/providers.json b/data.reference/providers.json
index f6d8b01557..22099cf112 100644
--- a/data.reference/providers.json
+++ b/data.reference/providers.json
@@ -107,6 +107,23 @@
"envVars": {},
"tuiPromptDelayMs": 2500
},
+ "codex-ollama": {
+ "id": "codex-ollama",
+ "name": "Codex Ollama (local model)",
+ "type": "cli",
+ "command": "codex",
+ "args": [],
+ "endpoint": "http://localhost:11434",
+ "models": [],
+ "defaultModel": null,
+ "ollamaBacked": true,
+ "numCtx": 131072,
+ "timeout": 600000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": [],
+ "headlessArgs": []
+ },
"claude-code-tui": {
"id": "claude-code-tui",
"name": "Claude Code TUI",
diff --git a/scripts/migrations/346-codex-ollama-provider.js b/scripts/migrations/346-codex-ollama-provider.js
new file mode 100644
index 0000000000..d4fbc8649b
--- /dev/null
+++ b/scripts/migrations/346-codex-ollama-provider.js
@@ -0,0 +1,75 @@
+/**
+ * Ship the disabled Codex-against-Ollama provider preset to existing installs.
+ *
+ * PortOS already runs Claude Code and OpenCode against a local model
+ * (`claude-ollama`, migration 146; `opencode-ollama`) — the harness is the
+ * value, and the model behind it is swappable. Codex was the one vendor with no
+ * local-backed variant, because it has no `ANTHROPIC_BASE_URL`-style env lever.
+ *
+ * It no longer needs one: Codex 0.153.0 ships `--oss` / `--local-provider
+ * <lmstudio|ollama>` natively, so PortOS emits a pair of PER-INVOCATION flags
+ * from the record's own `ollamaBacked` marker (`buildCodexOssArgs` in
+ * server/lib/codex.js). Deliberately NOT a rewrite of `~/.codex/config.toml`:
+ * that file is the user's, and re-pointing it would re-route every `codex` run
+ * on the machine rather than only PortOS's.
+ *
+ * Three things about this record are load-bearing:
+ *
+ * 1. **`ollamaBacked: true`, not a codex-specific flag.** It is the same axis
+ * the Claude/OpenCode wrappers ride, so `isOllamaBackedProvider`,
+ * `localRuntimeNamespace` and `ensureOllamaAgentContext` pick the row up
+ * with no new call site. A hand-copied second instance of that axis is
+ * exactly what `providerGateways.js`'s header warns about.
+ * 2. **`numCtx` is pinned.** Same trap #6191 fixed for the Claude Ollama
+ * pair: an unpinned local prefill at Codex's 262K window reloads the daemon
+ * into a context it cannot serve at usable speed.
+ * 3. **No `textTransport`.** The codex app-server transport is the ChatGPT
+ * subscription path; a local-backed record runs the ordinary `codex exec`
+ * argv, which is what carries the `--oss` flags.
+ *
+ * The preset is DISABLED and this migration installs nothing — no model pull,
+ * no request to the daemon, nothing until the user enables it (AGENTS.md, "No
+ * cold-bootstrap LLM calls"). On a Codex older than 0.153.0 the row fails
+ * closed with a named prerequisite rather than spawning (see
+ * server/services/codexOssSupport.js).
+ *
+ * LM Studio is codex's other `--local-provider` value and is deliberately NOT
+ * seeded here: PortOS has no LM Studio backing marker, and inventing a second
+ * daemon-prep path is its own change. See #6309.
+ *
+ * Kept in lockstep with data.reference/providers.json and
+ * server/lib/aiToolkit/defaults/providers.sample.json. This frozen literal is
+ * the historical upgrade payload; later default changes require a new migration
+ * rather than rewriting this record.
+ */
+
+import { makeProviderSeedMigration } from './_lib.js';
+
+const CODEX_OLLAMA = {
+ id: 'codex-ollama',
+ name: 'Codex Ollama (local model)',
+ type: 'cli',
+ command: 'codex',
+ args: [],
+ // The daemon the readiness probe and the model refresh hit. Codex resolves
+ // its OWN connection from `--local-provider ollama`; this is PortOS's copy of
+ // the same fact, and it is what `ollamaBaseFromProvider` reads to decide
+ // whether the local daemon is the one to reload.
+ endpoint: 'http://localhost:11434',
+ // Filled by the Ollama model refresh — a seeded list would name models this
+ // install has never pulled.
+ models: [],
+ defaultModel: null,
+ ollamaBacked: true,
+ numCtx: 131072,
+ timeout: 600000,
+ enabled: false,
+ envVars: {},
+ secretEnvVars: [],
+ headlessArgs: [],
+};
+
+export default makeProviderSeedMigration({
+ label: 'Codex Ollama (local model)',
+ defs: [CODEX_OLLAMA],
+});
diff --git a/scripts/migrations/346-codex-ollama-provider.test.js b/scripts/migrations/346-codex-ollama-provider.test.js
new file mode 100644
index 0000000000..250ed01ac9
--- /dev/null
+++ b/scripts/migrations/346-codex-ollama-provider.test.js
@@ -0,0 +1,111 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, resolve, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+import migration from './346-codex-ollama-provider.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+const ID = 'codex-ollama';
+
+describe('migration 346 — Codex Ollama provider', () => {
+ let rootDir;
+ let providersPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-345-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ providersPath = join(rootDir, 'data/providers.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('adds the preset disabled, without touching the cloud codex row or the active provider', async () => {
+ const codex = { id: 'codex', type: 'cli', command: 'codex', enabled: true, textTransport: 'codex-app-server' };
+ writeJson(providersPath, { activeProvider: 'codex', providers: { codex } });
+
+ await migration.up({ rootDir });
+ const out = readJson(providersPath);
+
+ expect(out.providers[ID]).toMatchObject({
+ name: 'Codex Ollama (local model)',
+ type: 'cli',
+ command: 'codex',
+ ollamaBacked: true,
+ enabled: false,
+ defaultModel: null,
+ models: [],
+ });
+ expect(out.providers.codex).toEqual(codex);
+ expect(out.activeProvider).toBe('codex');
+ });
+
+ it('pins numCtx — an unpinned local prefill at codex\'s native window is the #6191 trap', async () => {
+ writeJson(providersPath, { providers: {} });
+ await migration.up({ rootDir });
+ expect(readJson(providersPath).providers[ID].numCtx).toBe(131072);
+ });
+
+ it('carries NO textTransport — the app-server transport is the ChatGPT path', async () => {
+ // A local-backed record runs the ordinary `codex exec` argv, which is what
+ // carries the --oss flags; the app-server transport would bypass them.
+ writeJson(providersPath, { providers: {} });
+ await migration.up({ rootDir });
+ expect(readJson(providersPath).providers[ID].textTransport).toBeUndefined();
+ });
+
+ it('marks the backing with the SHARED local-runtime axis, not a codex-only flag', async () => {
+ // `ollamaBacked` is what makes isOllamaBackedProvider / localRuntimeNamespace
+ // / ensureOllamaAgentContext pick the row up with no new call site.
+ writeJson(providersPath, { providers: {} });
+ await migration.up({ rootDir });
+ const row = readJson(providersPath).providers[ID];
+ expect(row.ollamaBacked).toBe(true);
+ expect(Object.keys(row).filter((key) => key.endsWith('Backed'))).toEqual(['ollamaBacked']);
+ });
+
+ it('preserves a customized or disabled row rather than resurrecting the shipped one', async () => {
+ const existing = {
+ id: ID, name: 'My Codex Ollama', type: 'cli', command: '/opt/tools/codex',
+ ollamaBacked: true, numCtx: 32768, enabled: true,
+ };
+ writeJson(providersPath, { providers: { [ID]: existing } });
+
+ await migration.up({ rootDir });
+ expect(readJson(providersPath).providers[ID]).toEqual(existing);
+ });
+
+ it('is idempotent — a second run changes nothing', async () => {
+ writeJson(providersPath, { providers: {} });
+ await migration.up({ rootDir });
+ const first = readFileSync(providersPath, 'utf-8');
+
+ const second = await migration.up({ rootDir });
+ expect(second).toMatchObject({ ok: true, reason: 'already-present', added: 0 });
+ expect(readFileSync(providersPath, 'utf-8')).toBe(first);
+ });
+
+ it('skips a fresh install with no providers file — data.reference seeds that one', async () => {
+ const result = await migration.up({ rootDir });
+ expect(result).toMatchObject({ ok: false, reason: 'no-file', added: 0 });
+ });
+
+ it('ships the same record all three seed copies do', async () => {
+ // Three populations, three sources: the migration upgrades an existing
+ // install, data.reference seeds a fresh one, and providers.sample.json is
+ // loadProviders()'s fallback. A divergence gives them different providers.
+ writeJson(providersPath, { providers: {} });
+ await migration.up({ rootDir });
+ const migrated = readJson(providersPath).providers[ID];
+ const reference = readJson(resolve(__dirname, '../../data.reference/providers.json')).providers[ID];
+ const sample = readJson(resolve(__dirname, '../../server/lib/aiToolkit/defaults/providers.sample.json')).providers[ID];
+
+ expect(migrated).toEqual(reference);
+ expect(sample).toEqual(reference);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index dedd351778..bc89652372 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -171,7 +171,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `videoDurationProfiles.js` | Pure pinned duration/frame contracts shared by model-registry upgrades and migrations. LTX-2.5 A2V follows the full uploaded audio, rounds up to its 8n+1 temporal grid, and tops out at 1017 frames under the API's single-pass boundary. |
| `videoReferenceModes.js` | The i2v reference-mode contract (#4874) — what a supplied conditioning image PROMISES. `I2V_REFERENCE_MODES` (`anchor` \| `inspire`) + `I2V_REFERENCE_MODE_OPTIONS` (the label + the promise sentence the UI prints), `I2V_REFERENCE_MODE_RUNTIMES` (only `ltx25` can honor `inspire` — it needs per-image conditioning strength), `INSPIRE_DEFAULT_IMAGE_STRENGTH`, plus `normalizeI2vReferenceMode` / `isDefaultI2vReferenceMode` / `isKnownI2vReferenceMode` / `runtimeSupportsI2vReferenceMode` / `i2vReferenceModeLabel` / `resolveI2vReferenceStrength` and the one rule `i2vReferenceModeViolation({ model, mode, referenceMode, hasFirstImage })` → `{ code, message }` or null. Pure (no `ServerError`) because it is MIRRORED to `client/src/lib/videoReferenceModes.js`; `videoGen/modeContract.js#videoReferenceModeError` wraps it for the route + render boundaries. |
| `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path, and `videoTextEncoderRuntimes()` enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written. |
-| `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, `localRuntimeNamespace(provider)` — the OpenCode namespace only when it names a LOCAL daemon, i.e. the composed "namespace and not a hosted gateway" test that `cliChildEnv.js`, `localProviderRuntime.js` and `providerVendors.js` all key on, `OPENCODE_PUBLIC_REVIEW_AGENT` — the read-only OpenCode agent a no-tool public-review stage runs as, kept in this leaf because `providerVendors.js` must not import `opencodeConfig.js`, `parseOpencodeConfigContent` — the shared "is this stored OPENCODE_CONFIG_CONTENT usable?" read — plus `opencodeConfigIsLocalOnly` / `opencodeProviderIsLocalOnly`, the ONE locality rule `providerVendors.js` (gate eligibility) and `cliChildEnv.js` (public-review env allowlist) must not disagree about: if eligibility says yes where the allowlist strips the config, the stage spawns against the user's own ~/.config/opencode with tools intact while still reporting an enforced tool-free gate, `normalizeClaudeModelId` / `resolveClaudeCliModel` — the Claude-argv chokepoint that rewrites a dotted first-party version (`claude-fable-5.1`) to the dashed id Claude Code actually serves before the Bedrock mapping runs, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file. |
+| `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, `localRuntimeNamespace(provider)` — the OpenCode namespace only when it names a LOCAL daemon, i.e. the composed "namespace and not a hosted gateway" test that `cliChildEnv.js`, `localProviderRuntime.js` and `providerVendors.js` all key on, `CODEX_OSS_LOCAL_PROVIDERS` / `CODEX_OSS_MIN_VERSION` / `codexOssLocalProvider` / `codexUnsupportedLocalRuntime` — the codex half of that same axis: which local runtimes Codex's `--local-provider` can serve, and which marked runtime it cannot, kept here beside the namespace they wrap so `providerPrerequisites.js` classifies a codex record without importing `codex.js` (the argv emitter, `buildCodexOssArgs`, stays there), `OPENCODE_PUBLIC_REVIEW_AGENT` — the read-only OpenCode agent a no-tool public-review stage runs as, kept in this leaf because `providerVendors.js` must not import `opencodeConfig.js`, `parseOpencodeConfigContent` — the shared "is this stored OPENCODE_CONFIG_CONTENT usable?" read — plus `opencodeConfigIsLocalOnly` / `opencodeProviderIsLocalOnly`, the ONE locality rule `providerVendors.js` (gate eligibility) and `cliChildEnv.js` (public-review env allowlist) must not disagree about: if eligibility says yes where the allowlist strips the config, the stage spawns against the user's own ~/.config/opencode with tools intact while still reporting an enforced tool-free gate, `normalizeClaudeModelId` / `resolveClaudeCliModel` — the Claude-argv chokepoint that rewrites a dotted first-party version (`claude-fable-5.1`) to the dashed id Claude Code actually serves before the Bedrock mapping runs, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file. |
| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. |
| `modelCapabilityTests.js` | Catalog + scoring for the CAPABILITY tests on `/models/performance` (run by `services/modelCapabilityTests.js`): `CAPABILITY_TESTS` (sandbox repair / image analysis / story outline / fiction scene / rhetoric evaluator, each gated on the capability badges the install catalog already shows), `applicabilityFor` + `applicableTests` (`applicable` / `not-applicable` / `unknown` — an UNCLAIMED capability is never a failure, and `null` capabilities mean the runtime reported none, which is distinct from `[]`), `scoreKeywords` + `VISION_FIXTURE_KEYWORDS` (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), `scoreStoryBeats` + `HEROS_JOURNEY_BEATS` (coverage AND ordering, judged only over the beats present), `scoreSandboxRepair` (verdict from observed disk facts — editing the test instead of the module fails outright), `formatAgentEvent` (one agent stream frame → a transcript line), `rollUpVerdict`, and the verbatim `CAPABILITY_TEST_PROMPTS` / `SANDBOX_TASK_PROMPT` the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call. |
| `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. |
@@ -208,7 +208,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
| `cliStderrNoise.js` | `isKnownCliStderrNoise(trimmedLine)` — drops the real Anthropic `claude` CLI's harmless `[claude-code:unrecognized_model]` SDK telemetry line, which fires on every claude-ollama / claude-ollama-tui run because those providers point the binary's `ANTHROPIC_BASE_URL` at a local Ollama model the SDK doesn't recognize. |
-| `codex.js` | OpenAI Codex CLI (`codex`) provider helpers — the `CODEX_COMMAND`/`CODEX_CLI_ID` constants, the `isCodexCommand` predicate, and `ensureCodexTuiArgs` (injects `--dangerously-bypass-approvals-and-sandbox` + disables the startup update-check config, skipped when the argv already declares an approval/sandbox posture via `argvHasFlag`). Extracted from `tuiHandshake.js` (#3618) to match the one-file-per-vendor shape of `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`, which `providerVendors.js` consumes as registry rows. |
+| `codex.js` | OpenAI Codex CLI (`codex`) provider helpers — the `CODEX_COMMAND`/`CODEX_CLI_ID` constants, the `isCodexCommand` predicate, and `ensureCodexTuiArgs` (injects `--dangerously-bypass-approvals-and-sandbox` + disables the startup update-check config, skipped when the argv already declares an approval/sandbox posture via `argvHasFlag`). Extracted from `tuiHandshake.js` (#3618) to match the one-file-per-vendor shape of `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`, which `providerVendors.js` consumes as registry rows. Also owns `buildCodexOssArgs` — the `--oss --local-provider <ns>` pair emitted from a record's `ollamaBacked` marker, so the Codex harness runs on a local model without rewriting the user's `~/.codex/config.toml` (the record-classification half of that lives in `providerModels.js`, so `providerPrerequisites.js` can classify a codex record without importing a vendor argv module). |
| `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — the `CURSOR_COMMAND` binary constant, the `isCursorCommand` predicate, and the `ensureCursorHeadlessArgs` (`--print --force`, folding any pinned reasoning effort into `--model`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. |
| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |
| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |
diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.json
index ed1daf157d..a75de034fa 100644
--- a/server/lib/aiToolkit/defaults/providers.sample.json
+++ b/server/lib/aiToolkit/defaults/providers.sample.json
@@ -496,6 +496,23 @@
"secretEnvVars": [],
"tuiPromptDelayMs": 2500
},
+ "codex-ollama": {
+ "id": "codex-ollama",
+ "name": "Codex Ollama (local model)",
+ "type": "cli",
+ "command": "codex",
+ "args": [],
+ "endpoint": "http://localhost:11434",
+ "models": [],
+ "defaultModel": null,
+ "ollamaBacked": true,
+ "numCtx": 131072,
+ "timeout": 600000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": [],
+ "headlessArgs": []
+ },
"claude-code-tui": {
"id": "claude-code-tui",
"name": "Claude Code TUI",
diff --git a/server/lib/aiToolkit/internal/modelFetchers.test.js b/server/lib/aiToolkit/internal/modelFetchers.test.js
index 700e7d5996..e5c4e8ef6e 100644
--- a/server/lib/aiToolkit/internal/modelFetchers.test.js
+++ b/server/lib/aiToolkit/internal/modelFetchers.test.js
@@ -26,6 +26,10 @@ const SHIPPED_REFRESHABLE = [
// one MODEL_FETCHERS row covers all of them (internal/gateways.js).
'opencode-openrouter', 'opencode-openrouter-tui', 'openrouter',
'codex', 'codex-tui',
+ // The local-backed Codex wrapper resolves through the OLLAMA row, not codex's:
+ // `ollamaBacked` sits in the first pass, and the tool-capable local catalog is
+ // exactly what its harness needs — the static OpenAI list would be wrong.
+ 'codex-ollama',
// OpenCode Zen's API record is an ordinary OpenAI-compatible endpoint, so it
// refreshes through the same `/models` probe. Its CLI/TUI wrappers do NOT:
// they carry no namespace marker at all, which is what makes OpenCode resolve
diff --git a/server/lib/codex.js b/server/lib/codex.js
index c07053ea60..004060d44e 100644
--- a/server/lib/codex.js
+++ b/server/lib/codex.js
@@ -9,9 +9,23 @@
* Dependency-light on purpose: imports only `providerModels.js` helpers,
* mirroring the other vendor files so it stays importable from the standalone
* autofixer.
+ *
+ * The RECORD-CLASSIFICATION half of the local-model backing
+ * (`CODEX_OSS_LOCAL_PROVIDERS`, `codexOssLocalProvider`,
+ * `codexUnsupportedLocalRuntime`) lives in `providerModels.js` beside the
+ * `localRuntimeNamespace` it wraps, for the same reason `isCodexProvider` is
+ * defined there rather than here: classifying a provider RECORD is that file's
+ * job, and it lets a consumer that only needs the verdict —
+ * `providerPrerequisites.js` — skip a vendor's argv module entirely. Argv
+ * construction stays here.
*/
-import { argvHasFlag, buildCodexStartupArgs, commandBasename } from './providerModels.js';
+import {
+ argvHasFlag,
+ buildCodexStartupArgs,
+ codexOssLocalProvider,
+ commandBasename,
+} from './providerModels.js';
export const CODEX_COMMAND = 'codex';
export const CODEX_CLI_ID = 'codex';
@@ -60,5 +74,28 @@ export function ensureCodexTuiArgs(args, provider = null) {
prefix.push('--ignore-user-config');
}
prefix.push(...buildCodexStartupArgs(args));
+ // The local backing, on the same posture-flag step both TUI spawn paths
+ // share — an interactive `codex-ollama` session without it silently reaches
+ // the OpenAI cloud instead of the daemon the record names.
+ prefix.push(...buildCodexOssArgs(provider, args));
return prefix.length ? [...prefix, ...args] : args;
}
+
+
+/**
+ * `['--oss', '--local-provider', '<ns>']` for a local-runtime-backed codex
+ * record, or `[]`.
+ *
+ * Skipped when `existingArgs` already pins either flag, so a user who typed the
+ * pair into their provider args keeps their own spelling instead of getting a
+ * duplicate codex rejects.
+ * @param {object|null|undefined} provider
+ * @param {string[]} [existingArgs]
+ * @returns {string[]}
+ */
+export function buildCodexOssArgs(provider, existingArgs = []) {
+ const localProvider = codexOssLocalProvider(provider);
+ if (!localProvider) return [];
+ if (argvHasFlag(existingArgs, ['--oss', '--local-provider'])) return [];
+ return ['--oss', '--local-provider', localProvider];
+}
diff --git a/server/lib/codexAccount.js b/server/lib/codexAccount.js
index a70a5370ac..3264126a4a 100644
--- a/server/lib/codexAccount.js
+++ b/server/lib/codexAccount.js
@@ -32,7 +32,7 @@
* with no limit window in flight is never mistaken for a broken fetch.
*/
-import { commandBasename } from './providerModels.js';
+import { commandBasename, localRuntimeNamespace } from './providerModels.js';
/**
* The one invocation PortOS is allowed to spawn. Fixed argv, never assembled
@@ -104,7 +104,15 @@ export const isCodexSubscriptionProvider = (provider) => {
if (provider?.type !== 'cli' && provider?.type !== 'tui') return false;
const command = typeof provider?.command === 'string' ? provider.command.trim() : '';
if (command === '') return false;
- return commandBasename(command) === CODEX_APP_SERVER_COMMAND;
+ if (commandBasename(command) !== CODEX_APP_SERVER_COMMAND) return false;
+ // A local-runtime-backed codex record (`codex --oss --local-provider ollama`)
+ // generates its tokens on this machine and authenticates against nothing, so
+ // the ChatGPT account is not one of its prerequisites. Without this it would
+ // paint "No ChatGPT account is signed in" on a provider that needs no account
+ // — and the card would sit in UNKNOWN until an account read that will never
+ // matter answers. MIRROR of `isCodexSubscriptionProvider` in
+ // client/src/utils/providers.js.
+ return localRuntimeNamespace(provider) === null;
};
/**
diff --git a/server/lib/codexLocalBacking.test.js b/server/lib/codexLocalBacking.test.js
new file mode 100644
index 0000000000..ba2d36ed0e
--- /dev/null
+++ b/server/lib/codexLocalBacking.test.js
@@ -0,0 +1,186 @@
+/**
+ * The Codex-harness-on-a-local-model contract (#6305).
+ *
+ * Codex 0.153.0 ships `--oss` / `--local-provider <lmstudio|ollama>`, so PortOS
+ * swaps the model behind the Codex harness with a pair of per-invocation flags
+ * instead of rewriting the user's `~/.codex/config.toml`. What this pins is the
+ * ARGV — the one place the swap is expressed — plus the two ways it must fail
+ * closed: a codex record marked with a runtime Codex cannot serve, and a Codex
+ * binary too old to know the flags.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { buildCodexOssArgs } from './codex.js';
+import {
+ CODEX_OSS_MIN_VERSION,
+ codexOssLocalProvider,
+ codexUnsupportedLocalRuntime,
+} from './providerModels.js';
+import { applyCommandDefaults, buildVendorCliArgs, buildVendorSpawnConfig } from './providerVendors.js';
+import { buildTuiInvocation } from './tuiHandshake.js';
+import { PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from './agentExecutionProfiles.js';
+import { providerPrerequisites, blocksRouting } from './providerPrerequisites.js';
+import { isCodexSubscriptionProvider } from './codexAccount.js';
+
+const codexCloud = { id: 'codex', type: 'cli', command: 'codex', args: [] };
+const codexOllama = { id: 'codex-ollama', type: 'cli', command: 'codex', args: [], ollamaBacked: true };
+
+// The flags, as one adjacent triple — codex rejects `--local-provider` on its own.
+const ossTriple = ['--oss', '--local-provider', 'ollama'];
+const hasOssTriple = (args) => {
+ const i = args.indexOf('--oss');
+ return i !== -1 && args.slice(i, i + 3).join(' ') === ossTriple.join(' ');
+};
+
+describe('codexOssLocalProvider / codexUnsupportedLocalRuntime', () => {
+ it('maps the ollama marker onto codex\'s own --local-provider value', () => {
+ expect(codexOssLocalProvider(codexOllama)).toBe('ollama');
+ expect(codexUnsupportedLocalRuntime(codexOllama)).toBeNull();
+ });
+
+ it('is null for a cloud record and for a hosted gateway', () => {
+ expect(codexOssLocalProvider(codexCloud)).toBeNull();
+ // A gateway is an OpenCode namespace and a REMOTE API — never a local daemon.
+ expect(codexOssLocalProvider({ ...codexCloud, gatewayBacked: 'openrouter' })).toBeNull();
+ expect(codexUnsupportedLocalRuntime({ ...codexCloud, gatewayBacked: 'openrouter' })).toBeNull();
+ });
+
+ it('names a local runtime codex cannot serve rather than silently ignoring it', () => {
+ // PortOS's marker axis carries five runtimes; codex serves two by name.
+ // Returning null here would run the record against the OpenAI cloud while
+ // the card claimed it was local.
+ expect(codexOssLocalProvider({ ...codexCloud, vllmBacked: true })).toBeNull();
+ expect(codexUnsupportedLocalRuntime({ ...codexCloud, vllmBacked: true })).toBe('vllm');
+ });
+
+ it('yields to a user who already pinned either flag in their provider args', () => {
+ expect(buildCodexOssArgs(codexOllama, ['--oss'])).toEqual([]);
+ expect(buildCodexOssArgs(codexOllama, ['--local-provider', 'ollama'])).toEqual([]);
+ expect(buildCodexOssArgs(codexOllama, [])).toEqual(ossTriple);
+ });
+});
+
+describe('codex argv carries the local backing on every recipe', () => {
+ it('adds the flags to the headless one-shot argv, before the stdin marker', () => {
+ const args = buildVendorCliArgs(codexOllama, [], { model: 'qwen3:8b', effort: null });
+ expect(hasOssTriple(args)).toBe(true);
+ expect(args.indexOf('--oss')).toBeGreaterThan(args.indexOf('exec'));
+ expect(args.indexOf('--oss')).toBeLessThan(args.indexOf('-'));
+ // The local model id still rides `--model`; the flags select the BACKEND.
+ expect(args.slice(args.indexOf('--model'), args.indexOf('--model') + 2)).toEqual(['--model', 'qwen3:8b']);
+ });
+
+ it('adds them to the coding-agent spawn argv', () => {
+ const { command, args } = buildVendorSpawnConfig(codexOllama, { effectiveModel: 'qwen3:8b' });
+ expect(command).toBe('codex');
+ expect(hasOssTriple(args)).toBe(true);
+ });
+
+ it('leaves a cloud codex argv untouched', () => {
+ expect(buildVendorCliArgs(codexCloud, [], { model: 'gpt-5.6-terra', effort: null })).not.toContain('--oss');
+ expect(buildVendorSpawnConfig(codexCloud, { effectiveModel: 'gpt-5.6-terra' }).args).not.toContain('--oss');
+ });
+
+ it('routes a renamed codex record through the codex recipe, not claude\'s fallback row', () => {
+ // The vendor registry used to match codex by provider ID alone, so any
+ // record other than the shipped `codex` fell through to claude's
+ // unconditionally-true row and got `claude --print` argv on the codex binary.
+ const renamed = { id: 'my-codex', type: 'cli', command: 'codex', args: [] };
+ expect(buildVendorCliArgs(renamed, [], { model: null, effort: null })).toContain('exec');
+ });
+});
+
+describe('the INTERACTIVE paths carry the backing too', () => {
+ // Both TUI spawn paths (`buildTuiInvocation` here, `buildTuiSpawnConfig` in
+ // agentTuiSpawning.js) share `applyCommandDefaults` as their posture step, so
+ // that is the single place the backing has to land. Without it an attached
+ // `codex-ollama` session reaches the OpenAI cloud while every headless run of
+ // the same record goes to the daemon — the worst kind of split, because the
+ // record and the card both still say "local".
+ const codexOllamaTui = { id: 'codex-ollama-tui', type: 'tui', command: 'codex', args: [], ollamaBacked: true };
+
+ it('emits the flags from the shared posture step both TUI paths call', () => {
+ expect(hasOssTriple(applyCommandDefaults('codex', [], codexOllamaTui))).toBe(true);
+ expect(applyCommandDefaults('codex', [], { id: 'codex-tui', type: 'tui', command: 'codex' })).not.toContain('--oss');
+ // No provider at all is a cloud record's answer, never a crash.
+ expect(applyCommandDefaults('codex', [])).not.toContain('--oss');
+ });
+
+ it('reaches the interactive invocation alongside the bypass posture', () => {
+ const { command, args } = buildTuiInvocation(codexOllamaTui, 'qwen3:8b');
+ expect(command).toBe('codex');
+ expect(args).toContain('--dangerously-bypass-approvals-and-sandbox');
+ expect(hasOssTriple(args)).toBe(true);
+ expect(args.slice(args.indexOf('--model'), args.indexOf('--model') + 2)).toEqual(['--model', 'qwen3:8b']);
+ });
+});
+
+describe('the public-review recipe keeps its posture AND gains the backing', () => {
+ it('emits the exact sandbox posture flags plus the local backing', () => {
+ const { args } = buildVendorSpawnConfig(codexOllama, {
+ effectiveModel: 'qwen3:8b',
+ safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,
+ });
+ // The posture is the enforcement and must not shift because the backing did.
+ expect(args.slice(0, 6)).toEqual([
+ 'exec', '--sandbox', 'workspace-write', '--approve-for-me', '--ephemeral', '--ignore-user-config',
+ ]);
+ // `--ignore-user-config` does not strip the pair: it is argv, not config.
+ expect(hasOssTriple(args)).toBe(true);
+ expect(args).not.toContain('--dangerously-bypass-approvals-and-sandbox');
+ });
+
+ it('keeps a cloud codex public review byte-identical apart from the backing', () => {
+ const local = buildVendorSpawnConfig(codexOllama, {
+ effectiveModel: 'm', safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,
+ }).args;
+ const cloud = buildVendorSpawnConfig(codexCloud, {
+ effectiveModel: 'm', safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,
+ }).args;
+ expect(local.filter((arg) => !ossTriple.includes(arg))).toEqual(cloud);
+ });
+});
+
+describe('prerequisites fail closed and legibly', () => {
+ it('reports nothing while the flag probe has not answered', () => {
+ // `null` is NOT PROBED — an unprobed CLI must never take a working provider
+ // out of the fallback chain.
+ expect(providerPrerequisites(codexOllama, { codexOssSupport: null }).missing).toEqual([]);
+ expect(providerPrerequisites(codexOllama, { codexOssSupport: { supported: true } }).met).toBe(true);
+ });
+
+ it('names the required CLI version when the installed codex has no --oss', () => {
+ const { met, missing } = providerPrerequisites(codexOllama, { codexOssSupport: { supported: false } });
+ expect(met).toBe(false);
+ expect(missing).toEqual([
+ { code: 'codexOss', label: `Codex CLI ${CODEX_OSS_MIN_VERSION}+ is required to run a local model (--oss)` },
+ ]);
+ // Blocking: no credential or config makes an absent flag exist, so routing
+ // skips the candidate instead of dying on it mid-run.
+ expect(blocksRouting(missing)).toBe(true);
+ });
+
+ it('blocks a codex record marked with a runtime codex cannot serve', () => {
+ const { missing } = providerPrerequisites({ ...codexCloud, sglangBacked: true }, { codexOssSupport: { supported: true } });
+ expect(missing.map((entry) => entry.code)).toEqual(['codexLocalRuntime']);
+ expect(missing[0].label).toContain('sglang');
+ expect(blocksRouting(missing)).toBe(true);
+ });
+
+ it('never charges a NON-codex provider with either finding', () => {
+ const claudeOllama = { id: 'claude-ollama', type: 'cli', command: 'claude', ollamaBacked: true };
+ expect(providerPrerequisites(claudeOllama, { codexOssSupport: { supported: false } }).missing).toEqual([]);
+ });
+
+ it('drops the ChatGPT-account prerequisite for a local-backed codex record', () => {
+ // It generates its tokens on this machine and authenticates against
+ // nothing, so "No ChatGPT account is signed in" would be a false accusation
+ // — and would park the card in UNKNOWN awaiting a read that never matters.
+ expect(isCodexSubscriptionProvider(codexCloud)).toBe(true);
+ expect(isCodexSubscriptionProvider(codexOllama)).toBe(false);
+ expect(providerPrerequisites(codexOllama, {
+ codexAccount: { status: 'signed-out' },
+ codexOssSupport: { supported: true },
+ }).missing).toEqual([]);
+ });
+});
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 5a6425af05..763ac6b089 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -162,8 +162,18 @@ describe('deferred imports stay deferred (#6156)', () => {
* History, over the test files under `server/` only — the same denominator
* #6009 reported, and what `serverTestFiles()` below walks:
* 115,519 before #6009 · 96,233 after · 83,439 after #6156 · 85,105 after #5992 (orchestration profiles service & routes).
+ *
+ * Raised to 88,000 in #6305. The budget had drifted to within single digits of
+ * the measured total, so the next ordinary addition was always going to trip it
+ * — #6305's own share is ~43 (two new suites, plus one leaf service module,
+ * `services/codexOssSupport.js`, reached by the 14 suites that cross
+ * `services/providerPrerequisites.js`). That is the ordinary growth this budget
+ * is documented to tolerate, not the shape it exists to catch, so the fix is to
+ * restore the ~1.5k headroom the number is supposed to carry rather than to
+ * inch it up by a hundred each time. It stays thousands below what ONE eager
+ * edge into a heavy subtree costs, which is what actually has to fail here.
*/
-const MAX_STATIC_INSTANTIATIONS = 86500;
+const MAX_STATIC_INSTANTIATIONS = 88000;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
const serverTestFiles = (dir = SERVER_DIR, out = []) => {
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.js
index adca7323e9..6e92640d56 100644
--- a/server/lib/providerModels.js
+++ b/server/lib/providerModels.js
@@ -703,6 +703,59 @@ export function localRuntimeNamespace(provider) {
return namespace && !isGatewayNamespace(namespace) ? namespace : null;
}
+/**
+ * The Codex CLI's own `--local-provider` values, mapped from PortOS's
+ * local-runtime marker axis (`localRuntimeNamespace` in providerModels.js).
+ *
+ * Codex 0.153.0+ ships `--oss` / `--local-provider <lmstudio|ollama>`, so
+ * running the Codex harness on a local model is a pair of flags rather than a
+ * rewrite of the user's `~/.codex/config.toml` — the flags are per-invocation
+ * and leave every other `codex` run on the machine untouched.
+ *
+ * Deliberately a TABLE, not a passthrough: PortOS's marker axis carries five
+ * local runtimes (ollama / mtplx / llama / vllm / sglang) and Codex serves two
+ * of them by name. Forwarding an unmapped namespace would hand codex a value it
+ * rejects, and forwarding nothing would silently run the record against the
+ * OpenAI cloud — which is why `codexUnsupportedLocalRuntime` below exists.
+ *
+ * `lmstudio` is absent because PortOS has no LM Studio backing marker yet; the
+ * row lands with the marker, not before it.
+ */
+export const CODEX_OSS_LOCAL_PROVIDERS = Object.freeze({ ollama: 'ollama' });
+
+/**
+ * The first Codex CLI release that ships `--oss` / `--local-provider`. Used
+ * only to NAME the requirement in a prerequisite finding — the gate itself is a
+ * `codex exec --help` flag probe (`services/codexOssSupport.js`), because a
+ * version string is a proxy for the contract and the help text IS the contract.
+ */
+export const CODEX_OSS_MIN_VERSION = '0.153.0';
+
+/**
+ * The `--local-provider` value for `provider`, or `null` when this record is not
+ * backed by a local runtime Codex can serve.
+ * @param {object|null|undefined} provider
+ * @returns {string|null}
+ */
+export function codexOssLocalProvider(provider) {
+ const namespace = localRuntimeNamespace(provider);
+ return (namespace && CODEX_OSS_LOCAL_PROVIDERS[namespace]) || null;
+}
+
+/**
+ * The local runtime this codex record is marked with but Codex cannot serve
+ * (`vllm`, `sglang`, …), or `null`. A definite negative: the marker is on the
+ * record, and no credential or config makes `--local-provider vllm` exist. The
+ * prerequisite layer turns it into a finding rather than letting the row spawn
+ * against the OpenAI cloud while the card claims it is local.
+ * @param {object|null|undefined} provider
+ * @returns {string|null}
+ */
+export function codexUnsupportedLocalRuntime(provider) {
+ const namespace = localRuntimeNamespace(provider);
+ return namespace && !CODEX_OSS_LOCAL_PROVIDERS[namespace] ? namespace : null;
+}
+
/**
* Parse a stored `OPENCODE_CONFIG_CONTENT` value, or null when it is absent or
* no longer valid JSON (a hand-edited config tells us nothing, so every caller
diff --git a/server/lib/providerPrerequisites.js b/server/lib/providerPrerequisites.js
index f0af2f95b2..8d88064be3 100644
--- a/server/lib/providerPrerequisites.js
+++ b/server/lib/providerPrerequisites.js
@@ -38,7 +38,14 @@
import { PROVIDER_TYPES } from './aiToolkit/constants.js';
import { CODEX_ACCOUNT_STATUS, isCodexSubscriptionProvider } from './codexAccount.js';
import { isLocalInstanceHost } from './localProviderRuntime.js';
-import { commandBasename, isCodexProvider } from './providerModels.js';
+import {
+ CODEX_OSS_LOCAL_PROVIDERS,
+ CODEX_OSS_MIN_VERSION,
+ codexOssLocalProvider,
+ codexUnsupportedLocalRuntime,
+ commandBasename,
+ isCodexProvider,
+} from './providerModels.js';
import { gatewayForProvider } from './providerGateways.js';
/**
@@ -216,6 +223,33 @@ const codexRoutingAdvisory = (provider, routing) => {
};
};
+/**
+ * The local-backing findings for a codex record, in the order a user should act
+ * on them. Both are DEFINITE negatives — the marker is on the record, or the
+ * installed binary was probed and answered — so both block routing: spawning
+ * either one would run the OpenAI cloud model the user thought they had
+ * replaced, or die on an unknown flag mid-run.
+ *
+ * `support: null` is NOT PROBED and produces nothing, per the sentinel rule at
+ * the top of this file.
+ */
+const codexLocalBackingFindings = (provider, codexOssSupport) => {
+ if (!isProcessProvider(provider) || !isCodexProvider(provider)) return [];
+ const unsupportedRuntime = codexUnsupportedLocalRuntime(provider);
+ if (unsupportedRuntime) {
+ return [{
+ code: 'codexLocalRuntime',
+ label: `Codex cannot run against ${unsupportedRuntime} — it serves ${Object.keys(CODEX_OSS_LOCAL_PROVIDERS).join(' / ')} only`,
+ }];
+ }
+ if (!codexOssLocalProvider(provider)) return [];
+ if (codexOssSupport?.supported !== false) return [];
+ return [{
+ code: 'codexOss',
+ label: `Codex CLI ${CODEX_OSS_MIN_VERSION}+ is required to run a local model (--oss)`,
+ }];
+};
+
/**
* Which prerequisites `provider` is missing, and whether it is runnable at all.
*
@@ -235,7 +269,13 @@ const codexRoutingAdvisory = (provider, routing) => {
* DETERMINED. Produces an ADVISORY only (see {@link codexRoutingAdvisory}).
* @returns {{met: boolean, missing: {code: string, label: string}[], advisories: object[]}}
*/
-export const providerPrerequisites = (provider, { runtime = null, gatewayKeySet = null, codexAccount = null, codexRouting = null } = {}) => {
+export const providerPrerequisites = (provider, {
+ runtime = null,
+ gatewayKeySet = null,
+ codexAccount = null,
+ codexRouting = null,
+ codexOssSupport = null,
+} = {}) => {
const missing = [];
if (runtime && runtime.installed === false) {
@@ -258,6 +298,7 @@ export const providerPrerequisites = (provider, { runtime = null, gatewayKeySet
const codexFinding = codexAccountFinding(provider, codexAccount);
if (codexFinding) missing.push(codexFinding);
+ missing.push(...codexLocalBackingFindings(provider, codexOssSupport));
// Advisories are a SEPARATE list on purpose: everything in `missing` blocks
// something (a card's bucket, a strict readiness verdict), and this must
@@ -294,7 +335,7 @@ export const describeMissingPrerequisites = (missing) =>
* out of the chain, so they stay presentation-only. The provider card may
* report those credentials separately without changing the routing gate.
*/
-export const ROUTING_BLOCKING_CODES = Object.freeze(['runtime']);
+export const ROUTING_BLOCKING_CODES = Object.freeze(['runtime', 'codexOss', 'codexLocalRuntime']);
/**
* Is any of these findings severe enough to skip the provider when routing?
diff --git a/server/lib/providerPrerequisites.test.js b/server/lib/providerPrerequisites.test.js
index 79747a9478..af13dd922d 100644
--- a/server/lib/providerPrerequisites.test.js
+++ b/server/lib/providerPrerequisites.test.js
@@ -190,7 +190,12 @@ describe('blocksRouting', () => {
});
it('pins the routing-blocking set so widening it is a deliberate edit', () => {
- expect([...ROUTING_BLOCKING_CODES]).toEqual(['runtime']);
+ // Every member is an UNARGUABLE negative — no credential, env var, or
+ // config file makes it go away. `codexOss` (the probed binary does not
+ // accept --oss) and `codexLocalRuntime` (the record is marked with a local
+ // runtime codex cannot serve) qualify for the same reason the missing
+ // binary does; the credential findings still do not.
+ expect([...ROUTING_BLOCKING_CODES]).toEqual(['runtime', 'codexOss', 'codexLocalRuntime']);
});
});
diff --git a/server/lib/providerVendors.js b/server/lib/providerVendors.js
index 6b8483e49c..fe50d61b81 100644
--- a/server/lib/providerVendors.js
+++ b/server/lib/providerVendors.js
@@ -82,6 +82,7 @@ import {
ensureCodexTuiArgs,
CODEX_COMMAND,
CODEX_CLI_ID,
+ buildCodexOssArgs,
} from './codex.js';
import {
ANTIGRAVITY_COMMAND,
@@ -178,6 +179,10 @@ function codexCliArgs(baseArgs, { model, effort, provider }) {
const args = hasExec ? [...baseArgs] : [...baseArgs, 'exec'];
args.push(...codexIgnoreUserConfigArgs(provider, args));
args.push(...buildCodexStartupArgs(baseArgs));
+ // The local-model backing, when the record carries a runtime marker codex can
+ // serve. Emitted from the marker rather than from provider args so a wrapper
+ // stays declarative — see buildCodexOssArgs in codex.js.
+ args.push(...buildCodexOssArgs(provider, baseArgs));
if (model) {
args.push('--model', model);
}
@@ -195,6 +200,7 @@ function codexSpawnArgs(provider, { effectiveModel, effort, maxConcurrentThreads
'--dangerously-bypass-approvals-and-sandbox',
...codexIgnoreUserConfigArgs(provider),
...buildCodexStartupArgs(),
+ ...buildCodexOssArgs(provider),
...buildCodexAgentThreadArgs(maxConcurrentThreads),
];
if (effectiveModel) {
@@ -227,6 +233,11 @@ function codexPublicReviewArgs(provider, { effectiveModel, effort, maxConcurrent
'--ephemeral',
'--ignore-user-config',
...buildCodexStartupArgs(),
+ // The backing is orthogonal to the posture: a local-backed record reviews
+ // untrusted public code under the SAME sandbox ladder, with the tokens
+ // generated on-box. `--ignore-user-config` does not strip it — the pair is
+ // argv, not config.
+ ...buildCodexOssArgs(provider),
...buildCodexAgentThreadArgs(maxConcurrentThreads),
];
if (effectiveModel) {
@@ -291,7 +302,11 @@ const CODEX = {
idFragment: 'codex',
inferredCommand: CODEX_COMMAND,
matchCommand: isCodexCommand,
- matchCliProvider: (provider) => provider?.id === CODEX_CLI_ID,
+ // Id OR command: the shipped `codex` record is not the only one that must
+ // build codex argv any more — a local-backed wrapper (`codex-ollama`) carries
+ // its own id, and an id-only match would drop it through to `claude`'s
+ // fallback row and spawn `claude --print` against the codex binary.
+ matchCliProvider: (provider) => provider?.id === CODEX_CLI_ID || isCodexCommand(provider?.command),
tuiArgs: ensureCodexTuiArgs,
cliArgs: codexCliArgs,
spawnArgs: codexSpawnArgs,
@@ -794,13 +809,19 @@ export function inferTuiCommand(id) {
* (That is load-bearing for the attachable case: `ensureAntigravityTuiArgs` and
* friends append `--dangerously-skip-permissions`-class defaults, which would
* undo the recipe.)
+ *
+ * `provider` carries the record-level facts a command name cannot — the codex
+ * `ignoreUserConfig` pin and its local-runtime backing. Passing it here keeps
+ * BOTH TUI spawn paths on one injection point, which is the whole reason this
+ * dispatcher exists (see the `injectTuiModelAndEffort` note below for what
+ * happened the last time an argv rule lived in only one of them).
*/
export function applyCommandDefaults(command, args, provider = null) {
const vendor = PROVIDER_VENDORS.find((v) => v.tuiArgs && v.matchCommand(command));
if (!vendor) return args;
// `provider` is optional and only some vendors read it (codex, for the
- // `ignoreUserConfig` pin) — a vendor that ignores the second argument keeps
- // behaving exactly as before.
+ // `ignoreUserConfig` pin and the local-runtime backing) — a vendor that
+ // ignores the second argument keeps behaving exactly as before.
return vendor.tuiArgs(args, provider);
}
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index 9822ef2810..78423369ca 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -456,17 +456,21 @@ describe('buildCliSpawnConfig', () => {
expect(config.args[config.args.indexOf('--effort') + 1]).toBe('high');
});
- it('never emits the claude-shaped --effort for a renamed codex provider (detection and emission agree)', () => {
- // id !== 'codex' routes this into the default (claude-style) branch, but
- // the effort arg shape must still follow the binary, not the branch.
+ it('routes a renamed codex provider through the codex recipe, effort shape included', () => {
+ // The vendor registry used to match codex by provider ID alone, so any
+ // record but the shipped `codex` fell through to claude's
+ // unconditionally-true row — claude-shaped argv on the codex binary, with
+ // only the effort pair keyed off the command. Now the whole recipe follows
+ // the binary (#6305, which needed a SECOND codex record to build codex argv).
const config = buildCliSpawnConfig(
- { id: 'my-codex', command: '/opt/homebrew/bin/codex' },
+ { id: 'my-codex', command: '/opt/tools/codex' },
null,
{},
{ effort: 'xhigh' },
);
+ expect(config.args[0]).toBe('exec');
expect(config.args).not.toContain('--effort');
- expect(config.args[config.args.indexOf('-c') + 1]).toBe('model_reasoning_effort=xhigh');
+ expect(config.args.join(' ')).toContain('-c model_reasoning_effort=xhigh');
});
it('respects a user-baked --effort pin in provider args (mirrors the --model rule)', () => {
diff --git a/server/services/codexOssSupport.js b/server/services/codexOssSupport.js
new file mode 100644
index 0000000000..27bd83e013
--- /dev/null
+++ b/server/services/codexOssSupport.js
@@ -0,0 +1,119 @@
+/**
+ * Does the installed Codex CLI accept `--oss` / `--local-provider`?
+ *
+ * PortOS ships a `codex-ollama` provider — the Codex harness (sandbox ladder,
+ * `apply_patch`, approvals, session lifecycle) generating its tokens from a
+ * local Ollama model. That swap is a pair of per-invocation flags Codex added
+ * in 0.153.0, and PortOS does NOT rewrite `~/.codex/config.toml` to fake them
+ * on an older binary: a config rewrite would re-point every `codex` run on the
+ * machine, not just PortOS's.
+ *
+ * So on an older CLI the row must fail CLOSED and legibly — a prerequisite
+ * finding naming the required version — rather than spawning and dying mid-run
+ * on an unknown flag, or, worse, silently running the OpenAI cloud model the
+ * user thought they had replaced.
+ *
+ * `codex exec --help` is the source of truth, not the `--version` string: the
+ * help text IS the contract, and a fork or a repackaged build can carry either
+ * one without the other.
+ *
+ * **SENTINEL DISCIPLINE** (AGENTS.md), the same three-way split
+ * `providerPrerequisites.js` runs on:
+ *
+ * - `null` — NOT PROBED (cold cache, expired entry, or the probe itself could
+ * not run). Never reads as unsupported; an unprobed CLI must not take a
+ * working provider out of the fallback chain.
+ * - `{ supported: true }` — the help text names both flags.
+ * - `{ supported: false }` — the help text was read and does NOT name them.
+ *
+ * A probe that fails to spawn returns `null`, not `false`: "codex isn't here"
+ * is the runtime table's finding, not this one's.
+ *
+ * No LLM call is made here — `--help` is a local process, safe under the
+ * no-cold-bootstrap policy in AGENTS.md.
+ */
+
+import { commandOutput } from '../lib/commandExists.js';
+import { CODEX_COMMAND } from '../lib/codex.js';
+
+// Same window as the runtime `--version` sweep in providerRuntimeInstaller.js:
+// an expiry is "we no longer know", so a user who upgrades Codex from a
+// terminal stops being blocked within the TTL rather than until a restart.
+const SUPPORT_TTL_MS = 60_000;
+
+/** Both flags must be named — one without the other is not the contract. */
+const OSS_FLAGS = ['--oss', '--local-provider'];
+
+// Keyed by the command STRING the provider is configured with, so a wrapper
+// pinned to `/opt/tools/codex` is judged on the binary it will actually spawn
+// rather than on whatever `codex` resolves to on PATH.
+const supportCache = new Map();
+
+let refreshInFlight = new Map();
+
+const readHelp = (command) => commandOutput(command, ['exec', '--help'], { timeoutMs: 10_000 });
+
+const resolveCommand = (command) => (typeof command === 'string' && command.trim()) || CODEX_COMMAND;
+
+/**
+ * The cached verdict for `command`, or `null` when nothing current is cached.
+ * Synchronous — no spawn, no promise. This is what the `GET /api/providers`
+ * peek path reads.
+ * @param {string} [command]
+ * @returns {{supported: boolean}|null}
+ */
+export function peekCodexOssSupport(command) {
+ const cached = supportCache.get(resolveCommand(command));
+ if (!cached || Date.now() - cached.at >= SUPPORT_TTL_MS) return null;
+ return cached.support;
+}
+
+/**
+ * The verdict for `command`, probing when nothing current is cached.
+ *
+ * Coalesced per command: a failure storm picking a fallback per failed run must
+ * not fan out one `--help` spawn per run.
+ *
+ * @param {string} [command]
+ * @param {{fresh?: boolean, run?: (command: string) => Promise<string|null>}} [options]
+ * @returns {Promise<{supported: boolean}|null>}
+ */
+export async function getCodexOssSupport(command, { fresh = false, run = readHelp } = {}) {
+ const resolved = resolveCommand(command);
+ if (!fresh) {
+ const cached = peekCodexOssSupport(resolved);
+ if (cached) return cached;
+ const pending = refreshInFlight.get(resolved);
+ if (pending) return pending;
+ }
+ const probe = (async () => {
+ const help = await run(resolved).catch(() => null);
+ // Could not run it at all — NOT PROBED, and deliberately not cached: the
+ // next call should try again rather than sit on a non-answer for the TTL.
+ if (help === null) return null;
+ const support = { supported: OSS_FLAGS.every((flag) => help.includes(flag)) };
+ supportCache.set(resolved, { at: Date.now(), support });
+ return support;
+ })().finally(() => { refreshInFlight.delete(resolved); });
+ refreshInFlight.set(resolved, probe);
+ return probe;
+}
+
+/**
+ * Kick a probe in the background and swallow the result — for the synchronous
+ * peek path, which cannot await but can make the NEXT read accurate. Errors are
+ * logged, never thrown: this runs outside the request lifecycle, where an
+ * unhandled rejection kills the process.
+ * @param {string} [command]
+ */
+export function refreshCodexOssSupportInBackground(command) {
+ const resolved = resolveCommand(command);
+ if (refreshInFlight.has(resolved)) return;
+ getCodexOssSupport(resolved).catch((err) => console.error(`❌ Codex --oss probe failed: ${err.message}`));
+}
+
+/** Test-only: drop the cache and any in-flight probe so a suite starts clean. */
+export function __resetCodexOssSupport() {
+ supportCache.clear();
+ refreshInFlight = new Map();
+}
diff --git a/server/services/codexOssSupport.test.js b/server/services/codexOssSupport.test.js
new file mode 100644
index 0000000000..fec165297e
--- /dev/null
+++ b/server/services/codexOssSupport.test.js
@@ -0,0 +1,74 @@
+/**
+ * The `codex exec --help` flag probe (#6305) — the gate that keeps a
+ * local-backed Codex row from spawning against a CLI that has never heard of
+ * `--oss`.
+ *
+ * What matters here is the tri-state, not the parsing: "could not run it" and
+ * "ran it and the flags are absent" must never collapse, because the first is
+ * NOT PROBED (route normally) and the second is a definite negative (skip).
+ */
+
+import { describe, expect, it, beforeEach, vi } from 'vitest';
+import {
+ __resetCodexOssSupport,
+ getCodexOssSupport,
+ peekCodexOssSupport,
+} from './codexOssSupport.js';
+
+const HELP_WITH_OSS = `Usage: codex exec [OPTIONS] [PROMPT]
+ --oss
+ Use open-source provider
+ --local-provider <OSS_PROVIDER>
+ Specify which local provider to use (lmstudio or ollama)`;
+const HELP_WITHOUT_OSS = 'Usage: codex exec [OPTIONS] [PROMPT]\n -m, --model <MODEL>';
+
+describe('codexOssSupport', () => {
+ beforeEach(() => __resetCodexOssSupport());
+
+ it('reports supported when the help text names BOTH flags', async () => {
+ expect(await getCodexOssSupport('codex', { run: async () => HELP_WITH_OSS })).toEqual({ supported: true });
+ });
+
+ it('reports unsupported when the help text was read and does not name them', async () => {
+ expect(await getCodexOssSupport('codex', { run: async () => HELP_WITHOUT_OSS })).toEqual({ supported: false });
+ });
+
+ it('requires both flags — one without the other is not the contract', async () => {
+ const partial = 'Usage: codex exec\n --oss\n Use open-source provider';
+ expect(await getCodexOssSupport('codex', { run: async () => partial })).toEqual({ supported: false });
+ });
+
+ it('answers NOT PROBED when the probe could not run, and does not cache it', async () => {
+ const run = vi.fn().mockResolvedValueOnce(null).mockResolvedValueOnce(HELP_WITH_OSS);
+ // A binary that isn't there is the runtime table's finding, not this one's:
+ // caching `false` here would blame a perfectly good provider for a
+ // transient spawn failure until the TTL expired.
+ expect(await getCodexOssSupport('codex', { run })).toBeNull();
+ expect(peekCodexOssSupport('codex')).toBeNull();
+ expect(await getCodexOssSupport('codex', { run })).toEqual({ supported: true });
+ expect(run).toHaveBeenCalledTimes(2);
+ });
+
+ it('caches per command, so a probe of one binary never answers for another', async () => {
+ const run = vi.fn(async (command) => (command === '/opt/old/codex' ? HELP_WITHOUT_OSS : HELP_WITH_OSS));
+ expect(await getCodexOssSupport('codex', { run })).toEqual({ supported: true });
+ expect(await getCodexOssSupport('/opt/old/codex', { run })).toEqual({ supported: false });
+ expect(peekCodexOssSupport('codex')).toEqual({ supported: true });
+ expect(peekCodexOssSupport('/opt/old/codex')).toEqual({ supported: false });
+ });
+
+ it('serves a cached verdict without re-spawning, and coalesces concurrent probes', async () => {
+ let resolveHelp;
+ const run = vi.fn(() => new Promise((resolve) => { resolveHelp = resolve; }));
+ const [a, b] = [getCodexOssSupport('codex', { run }), getCodexOssSupport('codex', { run })];
+ resolveHelp(HELP_WITH_OSS);
+ expect(await a).toEqual({ supported: true });
+ expect(await b).toEqual({ supported: true });
+ await getCodexOssSupport('codex', { run });
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+
+ it('peeks nothing before anything has been probed', () => {
+ expect(peekCodexOssSupport('codex')).toBeNull();
+ });
+});
diff --git a/server/services/providerPrerequisites.js b/server/services/providerPrerequisites.js
index f6bd259e51..095996d52c 100644
--- a/server/services/providerPrerequisites.js
+++ b/server/services/providerPrerequisites.js
@@ -39,6 +39,8 @@ import { readCodexRoutingOverride } from '../lib/codexUserConfig.js';
import { inferTuiCommand } from '../lib/providerVendors.js';
import { findCommandOnPath } from '../lib/processEnv.js';
import { peekCodexAccountReadiness } from './codexAppServer.js';
+import { getCodexOssSupport, peekCodexOssSupport, refreshCodexOssSupportInBackground } from './codexOssSupport.js';
+import { codexOssLocalProvider } from '../lib/providerModels.js';
import { delimiter, isAbsolute } from 'path';
import {
getProviderRuntime,
@@ -98,6 +100,19 @@ const runtimeSnapshotFor = (keys) => {
return runtimes;
};
+// The codex `--oss` verdict for a LOCAL-BACKED codex record, read cache-only.
+// Unlike the ChatGPT account read (a heavyweight `codex app-server` spawn, so
+// cache-only with no background fill), `codex exec --help` is the same class of
+// probe as the runtime `--version` sweep above — so a cold cache kicks the same
+// kind of background refresh and the NEXT read is accurate. A record with no
+// local backing is never probed: the flags are not among its prerequisites.
+const codexOssSupportFor = (provider) => {
+ if (!codexOssLocalProvider(provider)) return null;
+ const support = peekCodexOssSupport(provider?.command);
+ if (!support) refreshCodexOssSupportInBackground(provider?.command);
+ return support;
+};
+
// CACHE-ONLY (`peek`, never `get`): the Codex ChatGPT readiness a card shows
// must never be the thing that spawns `codex app-server`. A cold cache answers
// `null` — NOT PROBED — so `GET /api/providers` stays a synchronous read and a
@@ -113,6 +128,7 @@ const forProvider = (provider, runtimes, gatewayKeySet) => providerPrerequisites
// Advisory only: it never reaches `missing`, so it cannot change routing or
// a readiness verdict.
codexRouting: readCodexRoutingOverride(),
+ codexOssSupport: codexOssSupportFor(provider),
});
const effectiveProcessCommand = (provider) => {
@@ -205,6 +221,13 @@ export async function getProviderPrerequisiteReadinessMap(providers, {
await getProviderRuntimeStatus(key),
]));
const runtimes = { ...cached, ...Object.fromEntries(probed) };
+ // An authoritative caller cannot publish a codex-local choice on an unprobed
+ // flag verdict, so this path AWAITS the `--help` probe the sync path can only
+ // kick in the background. One probe per distinct command, not per provider.
+ await Promise.all([...new Set(processProviders
+ .filter((provider) => codexOssLocalProvider(provider))
+ .map((provider) => provider.command))]
+ .map((command) => getCodexOssSupport(command).catch(() => null)));
const gatewayKeySet = gatewayKeyState(list);
return Object.fromEntries(targetList.map((provider, index) => {
const effectiveProvider = processProviders[index];