The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
cli: a Codex agent leaving a grid names the provider it comes back to
bitcoinbuilder76d5fa69edd9
diff --git a/cli/src/engines/codex/ownLoginProvider.spec.ts b/cli/src/engines/codex/ownLoginProvider.spec.tsnew file mode 100644index 000000000..817a42f39--- /dev/null+++ b/cli/src/engines/codex/ownLoginProvider.spec.ts@@ -0,0 +1,102 @@+/**+ * Reading a Codex `config.toml` for the provider an agent goes back to.+ *+ * The parsing is deliberately small — one key, top level only — so what is worth pinning is where+ * it must NOT find that key, and what it hands back when it finds nothing.+ */+import { describe, expect, it } from 'vitest'+import {+ CODEX_DEFAULT_PROVIDER,+ codexConfigPath,+ ownLoginProviderArgs,+ parseCodexModelProvider,+} from './ownLoginProvider.js'++describe('parseCodexModelProvider', () => {+ it('reads a top-level key, with either kind of quote and any spacing', () => {+ expect(parseCodexModelProvider('model_provider = "azure"')).toBe('azure')+ expect(parseCodexModelProvider("model_provider='azure'")).toBe('azure')+ expect(parseCodexModelProvider(' model_provider = "azure" \n')).toBe('azure')+ })++ it('finds it among the other top-level keys a real config carries', () => {+ expect(parseCodexModelProvider([+ 'model = "gpt-6-astra"',+ 'model_reasoning_effort = "max"',+ 'model_provider = "azure"',+ 'service_tier = "default"',+ ].join('\n'))).toBe('azure')+ })++ it('STOPS at the first table header', () => {+ // In TOML every key after a header belongs to that table. `model_provider` under+ // `[profiles.work]` is that profile's choice, and handing it back as the file's would move the+ // agent onto a provider the user selected for something else entirely.+ expect(parseCodexModelProvider([+ 'model = "gpt-6"',+ '',+ '[profiles.work]',+ 'model_provider = "azure"',+ ].join('\n'))).toBeNull()+ expect(parseCodexModelProvider('[projects."/x"]\nmodel_provider = "azure"')).toBeNull()+ })++ it('ignores a commented-out key, and keeps a comment that follows a real one', () => {+ expect(parseCodexModelProvider('# model_provider = "azure"')).toBeNull()+ expect(parseCodexModelProvider('model_provider = "azure" # the work tenant')).toBe('azure')+ })++ it('does not mistake a `#` inside the value for a comment', () => {+ expect(parseCodexModelProvider('model_provider = "az#ure"')).toBe('az#ure')+ })++ it('is not fooled by a key that merely ends in model_provider', () => {+ expect(parseCodexModelProvider('default_model_provider = "azure"')).toBeNull()+ })++ it('answers null for an empty value, a missing key, and an empty file', () => {+ expect(parseCodexModelProvider('model_provider = ""')).toBeNull()+ expect(parseCodexModelProvider('model = "gpt-6"')).toBeNull()+ expect(parseCodexModelProvider('')).toBeNull()+ })+})++describe('codexConfigPath', () => {+ it('prefers the agent’s own profile over the environment', () => {+ expect(codexConfigPath('/profiles/work', { CODEX_HOME: '/elsewhere' })).toBe('/profiles/work/config.toml')+ })++ it('falls back to CODEX_HOME when the agent names no profile', () => {+ expect(codexConfigPath(null, { CODEX_HOME: '/elsewhere' })).toBe('/elsewhere/config.toml')+ })+})++describe('ownLoginProviderArgs', () => {+ const read = (toml: string | null) => () => toml++ it('names the configured provider when there is one', () => {+ expect(ownLoginProviderArgs('codex', null, { read: read('model_provider = "azure"'), env: {} }))+ .toEqual(['-c', 'model_provider="azure"'])+ })++ it('falls back to Codex’s own default, which is what Codex would have picked', () => {+ expect(ownLoginProviderArgs('codex', null, { read: read(null), env: {} }))+ .toEqual(['-c', `model_provider="${CODEX_DEFAULT_PROVIDER}"`])+ })++ it('says nothing for every engine that does not persist a provider', () => {+ // Claude Code and Hermes resolve theirs fresh each launch; OpenCode's lives in a file this+ // daemon writes and can stop writing. Only Codex keeps one in state of its own.+ for (const engine of ['claude', 'hermes', 'opencode', 'cursor', 'grok'] as const) {+ expect(ownLoginProviderArgs(engine, '/profiles/work', { read: read('model_provider = "azure"'), env: {} })).toEqual([])+ }+ })++ it('treats an unreadable config as "nothing configured" rather than as a failure', () => {+ // A relaunch must not be blocked by a config.toml that is absent, or that this daemon cannot+ // read. The default is a correct answer in both cases.+ const throws = () => { throw new Error('EACCES') }+ expect(ownLoginProviderArgs('codex', null, { read: () => { try { return throws() } catch { return null } }, env: {} }))+ .toEqual(['-c', `model_provider="${CODEX_DEFAULT_PROVIDER}"`])+ })+})diff --git a/cli/src/engines/codex/ownLoginProvider.ts b/cli/src/engines/codex/ownLoginProvider.tsnew file mode 100644index 000000000..2010d29aa--- /dev/null+++ b/cli/src/engines/codex/ownLoginProvider.ts@@ -0,0 +1,102 @@+/**+ * Undoing the provider a grid launch left behind in Codex's own state.+ *+ * Codex does not resolve its provider from argv alone. From 0.155 it records one PER THREAD in+ * `<CODEX_HOME>/state_5.sqlite` (`threads.model_provider`), written at launch from whatever+ * `-c model_provider=` said. The grid contract says `grid` there (`gridLaunch.ts`), and defines what+ * `grid` means in the SAME argv — so the name is persisted while its definition is not.+ *+ * Move the agent back to its own login and that asymmetry is the bug: the harness correctly stops+ * passing every `-c model_providers.grid.*`, `codex resume` loads the thread row, and resolving it+ * fails before the TUI is up —+ *+ * thread/resume failed: failed to load configuration: Model provider `grid` not found (code -32600)+ *+ * — which the daemon can only answer by giving up on the session and starting a fresh one+ * ("[restart] codex did not come back up resuming its session — retrying fresh"). The conversation+ * survives on disk and is never reached again, which is exactly what `subscriptionModel.ts` and+ * `portableHistory.ts` exist to prevent.+ *+ * So the move back names a provider too, rather than only un-naming the grid's. Measured against+ * codex-cli 0.155.1: argv OUTRANKS the stored row, so this repairs a thread that is already+ * poisoned rather than only keeping the next one clean — no database is read, written, or migrated.+ *+ * ## Why the user's own config is read first+ *+ * `openai` is Codex's default, not its only answer: a `model_provider` at the top of the user's+ * `config.toml` is their standing choice for every Codex they run, and a harness that overwrote it+ * with `openai` would move them off their own provider as the price of leaving a grid. So the file+ * is asked first and `openai` is the fallback — the same value Codex itself would have picked.+ */+import { readFileSync } from 'node:fs'+import { homedir } from 'node:os'+import { join } from 'node:path'+import type { AgentEngine } from '../../engines/types.js'++/** What Codex uses when nothing configures otherwise. */+export const CODEX_DEFAULT_PROVIDER = 'openai'++/**+ * The top-level `model_provider` in a Codex `config.toml`, or null.+ *+ * TOP-LEVEL only, and that is the whole subtlety: in TOML every key after a `[header]` belongs to+ * that table, so `model_provider` under `[profiles.work]` is that profile's and not the file's.+ * Reading it as the file's would hand Codex a provider the user selected for something else. Bare+ * keys stop at the first header for that reason.+ */+export function parseCodexModelProvider(toml: string): string | null {+ for (const raw of toml.split('\n')) {+ const line = stripComment(raw).trim()+ if (!line) continue+ // The first table header ends the top level; anything after it is scoped to that table.+ if (line.startsWith('[')) return null+ const match = /^model_provider\s*=\s*(?:"([^"]*)"|'([^']*)')\s*$/.exec(line)+ if (match) {+ const value = (match[1] ?? match[2] ?? '').trim()+ return value || null+ }+ }+ return null+}++/** Drop a trailing `#` comment, but not one inside a quoted value. */+function stripComment(line: string): string {+ let quote: string | null = null+ for (let i = 0; i < line.length; i++) {+ const ch = line[i]+ if (quote) { if (ch === quote) quote = null; continue }+ if (ch === '"' || ch === "'") { quote = ch; continue }+ if (ch === '#') return line.slice(0, i)+ }+ return line+}++/** Where Codex keeps its configuration — the same resolution `prepareCodexResume` uses. */+export function codexConfigPath(codexHome: string | null | undefined, env = process.env): string {+ return join(codexHome || env.CODEX_HOME || join(homedir(), '.codex'), 'config.toml')+}++/** Read a Codex `config.toml`; an unreadable or absent file is "nothing configured", not an error. */+function readCodexConfig(path: string): string | null {+ try { return readFileSync(path, 'utf8') } catch { return null }+}++/**+ * The argv that puts `engine` back on its own provider, or nothing when there is none to put back.+ *+ * Only Codex: it is the one engine here that persists a provider of its own accord. Claude Code and+ * Hermes read theirs from the environment or argv every launch, so dropping the grid's is already+ * the whole of the move, and OpenCode's lives in a configuration file this daemon writes and can+ * therefore stop writing.+ */+export function ownLoginProviderArgs(+ engine: AgentEngine,+ codexHome: string | null | undefined,+ deps: { read?: (path: string) => string | null; env?: NodeJS.ProcessEnv } = {},+): string[] {+ if (engine !== 'codex') return []+ const read = deps.read ?? readCodexConfig+ const toml = read(codexConfigPath(codexHome, deps.env ?? process.env))+ const configured = toml ? parseCodexModelProvider(toml) : null+ return ['-c', `model_provider="${configured ?? CODEX_DEFAULT_PROVIDER}"`]+}diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsindex 70ef1e894..0a66408d5 100644--- a/cli/src/lib/launchOverrides.spec.ts+++ b/cli/src/lib/launchOverrides.spec.ts@@ -17,6 +17,9 @@ function deps(overrides: Partial<LaunchOverridesDeps> = {}) {writeGridConfigDir: async (key) => { calls.push(`writeConfig:${key}`); return `/state/grid-engine-config/${key}` },tmuxSupportsSessionEnv: async () => true,installCodexHooks: (home) => { calls.push(`hooks:${home}`) },+ // No Codex configuration unless a test says so — otherwise every relaunch built here would+ // consult the config.toml of whoever is running the suite.+ readCodexConfig: () => null,...overrides,}return { d, calls }@@ -65,10 +68,20 @@ describe('buildLaunchOverrides — a relaunch comes back where the agent was', (expect(calls).toEqual([])})- it('a Codex profile gets its CODEX_HOME and its hooks, and clears nothing', async () => {+ it('a Codex profile gets its CODEX_HOME, its hooks and its own provider, and clears nothing', async () => {const { d, calls } = deps()const result = await buildLaunchOverrides(d, 'codex', { gridLaunch: null, codexHome: '/home/u/.codex-work' }, 'agent-2')- expect(result).toEqual({ ok: true, overrides: { env: { CODEX_HOME: '/home/u/.codex-work' }, extraArgs: [], clearEnv: [] } })+ // `model_provider` rides every own-login Codex launch, not only one that follows a grid: the+ // row does not record where the thread has been, and naming the provider Codex would have+ // picked anyway is what makes a poisoned thread resumable again.+ expect(result).toEqual({+ ok: true,+ overrides: {+ env: { CODEX_HOME: '/home/u/.codex-work' },+ extraArgs: ['-c', 'model_provider="openai"'],+ clearEnv: [],+ },+ })expect(calls).toEqual(['hooks:/home/u/.codex-work'])})@@ -99,7 +112,9 @@ describe('buildLaunchOverrides — coming back off a grid', () => {it('uses argv for an engine whose interactive CLI resolves the model there', async () => {const result = await buildLaunchOverrides(deps().d, 'codex', { subscriptionModel: 'gpt-5-codex' }, 'a')- expect(result).toMatchObject({ ok: true, overrides: { extraArgs: ['-m', 'gpt-5-codex'] } })+ // The provider comes FIRST: `-c` configures and `-m` selects, and Codex resolves the model+ // against the provider it was given.+ expect(result).toMatchObject({ ok: true, overrides: { extraArgs: ['-c', 'model_provider="openai"', '-m', 'gpt-5-codex'] } })})it('adds nothing when there is no model to come back to', async () => {@@ -107,6 +122,73 @@ describe('buildLaunchOverrides — coming back off a grid', () => {expect(result).toMatchObject({ ok: true, overrides: { env: {}, extraArgs: [] } })})+ // ── the provider, which Codex remembers on its own ────────────────────────────────────────────+ //+ // Codex records the provider per THREAD (`threads.model_provider` in its own state database),+ // written from the `-c model_provider=` the grid launch passed. Dropping that argv on the way back+ // leaves the NAME stored with nothing defining it, and `codex resume` dies before the TUI is up:+ // thread/resume failed: failed to load configuration: Model provider `grid` not found+ // The daemon's only answer was to abandon the conversation ("retrying fresh"). Reproduced against+ // codex-cli 0.155.1; see `engines/codex/ownLoginProvider.ts`.++ it('names a provider for Codex even when no model is remembered', async () => {+ // The case a model-shaped fix misses entirely: nothing to re-select, and the stale provider is+ // still what stops the resume.+ const result = await buildLaunchOverrides(deps().d, 'codex', {}, 'a')+ expect(result).toMatchObject({ ok: true, overrides: { extraArgs: ['-c', 'model_provider="openai"'] } })+ })++ it('keeps the user’s own model_provider instead of forcing them onto openai', async () => {+ const { d } = deps({ readCodexConfig: () => 'model = "gpt-6"\nmodel_provider = "azure"\n' })+ const result = await buildLaunchOverrides(d, 'codex', { subscriptionModel: 'gpt-6' }, 'a')+ expect(result).toMatchObject({ ok: true, overrides: { extraArgs: ['-c', 'model_provider="azure"', '-m', 'gpt-6'] } })+ })++ it('reads the AGENT’s Codex profile, not this machine’s default', async () => {+ const seen: string[] = []+ const { d } = deps({ readCodexConfig: (path) => { seen.push(path); return null } })+ await buildLaunchOverrides(d, 'codex', { codexHome: '/profiles/work' }, 'a')+ expect(seen).toEqual(['/profiles/work/config.toml'])+ })++ it('keeps the Codex profile AND its hooks while naming the provider', async () => {+ // Both used to be lost: a row with a remembered model returned before the profile branch, so it+ // came back on the default profile and fired no hook.+ const { d, calls } = deps()+ const result = await buildLaunchOverrides(d, 'codex', { codexHome: '/profiles/work', subscriptionModel: 'gpt-6' }, 'a')+ expect(result).toMatchObject({+ ok: true,+ overrides: { env: { CODEX_HOME: '/profiles/work' }, extraArgs: ['-c', 'model_provider="openai"', '-m', 'gpt-6'] },+ })+ expect(calls).toContain('hooks:/profiles/work')+ })++ it('leaves every other engine’s provider alone', async () => {+ // Only Codex persists one. Claude Code and Hermes read theirs fresh each launch, and OpenCode's+ // lives in a file this daemon writes and can simply stop writing.+ for (const engine of ['claude', 'hermes', 'opencode'] as const) {+ const result = await buildLaunchOverrides(deps().d, engine, { subscriptionModel: 'a/b' }, 'a')+ expect(result.ok).toBe(true)+ if (!result.ok) return+ expect(result.overrides.extraArgs.join(' ')).not.toContain('model_provider')+ }+ })++ it('never names a provider on a GRID launch — that launch names its own', async () => {+ // `-c model_provider="grid"` is the grid contract's, and a second one after it would decide the+ // launch. Nothing about coming back may reach the way out.+ let reads = 0+ const { d } = deps({ readCodexConfig: () => { reads++; return null } })+ const result = await buildLaunchOverrides(d, 'codex', { gridLaunch: GRID, subscriptionModel: 'gpt-6' }, 'a')+ expect(result.ok).toBe(true)+ if (!result.ok) return+ const providers = result.overrides.extraArgs.filter((arg) => arg.startsWith('model_provider='))+ expect(providers).toEqual(['model_provider="grid"'])+ // And it is not merely outvoted downstream: a launch going TO a grid has no reason to open the+ // user's Codex configuration at all, so the question is never asked.+ expect(reads).toBe(0)+ })+it('never lets a remembered model reach a GRID launch — that launch names its own', async () => {const result = await buildLaunchOverrides(deps().d, 'claude', { gridLaunch: GRID, subscriptionModel: 'opus' }, 'a',diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex aa1a3a4de..d17556f27 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -15,6 +15,7 @@import { join } from 'node:path'import type { AgentEngine } from '../engines/types.js'import { subscriptionModelLaunch } from './subscriptionModel.js'+import { ownLoginProviderArgs } from '../engines/codex/ownLoginProvider.js'import { namedAgentArgs, supportsNamedAgent } from './engineLaunch.js'import {buildGridEngineLaunch,@@ -59,6 +60,15 @@ export interface LaunchOverridesDeps {/** Install the daemon's hooks into a non-default Codex profile. The caller decides whether hook* installation is enabled at all. */installCodexHooks: (codexHome: string) => void+ /**+ * Read a Codex `config.toml`, for the provider an agent goes back to when it leaves a grid.+ *+ * A seam rather than a direct read: without it every relaunch built in a test would consult+ * whatever Codex configuration the machine running the test happens to have, and a developer who+ * had set `model_provider` would watch unrelated specs change their answer. Absent ⇒ the real+ * file. See `engines/codex/ownLoginProvider.ts`.+ */+ readCodexConfig?: (path: string) => string | null/** What a DSH adds to the launch (its env and argv), or null when it is not installed here any* more — in which case the agent relaunches as its plain base engine and says so in the log. */dshLaunch?: (dsh: string, workspace: string) => DshLaunch | null@@ -164,20 +174,30 @@ async function buildBaseLaunchOverrides(): Promise<LaunchOverridesResult> {const valid = await validateLaunchOverrides(deps, engine, source)if (!valid.ok) return valid+ // Coming back to the engine's own login undoes TWO things the grid launch set, and they are+ // undone separately because the engine remembers them differently.+ //+ // * The MODEL — re-selected so the engine does not fall back to a house default. See+ // `subscriptionModel.ts` for why an engine with no cited mechanism is given nothing rather+ // than a guess.+ // * The PROVIDER — named again, because Codex persists the grid's in state of its own that+ // outlives the argv defining it, and a resume then fails before the TUI is up. See+ // `engines/codex/ownLoginProvider.ts`.+ //+ // Accumulated rather than returned, because a Codex agent needs its profile (below) as well, and+ // an early return here used to drop it: a row with both a remembered model and a CODEX_HOME came+ // back on the DEFAULT profile, reading hooks from a folder that was not the one it writes to.+ let ownLogin: LaunchOverrides | null = nullif (!source.gridLaunch) {- // Coming back to the engine's own login: re-select the model this agent was on before it left,- // so the engine does not fall back to a house default. See `subscriptionModel.ts` for why an- // engine with no cited mechanism is given nothing rather than a guess.const restored = subscriptionModelLaunch(engine, source.subscriptionModel)- if (restored) {- const base = noOverrides()- return {- ok: true,- overrides: {- ...base,- env: { ...base.env, ...restored.env },- extraArgs: [...base.extraArgs, ...restored.args],- },+ // Ahead of the model on the command line: `-c` configures, `-m` selects, and Codex resolves the+ // model against the provider it has been given.+ const provider = ownLoginProviderArgs(engine, source.codexHome, { read: deps.readCodexConfig })+ if (restored || provider.length) {+ ownLogin = {+ env: { ...(restored?.env ?? {}) },+ extraArgs: [...provider, ...(restored?.args ?? [])],+ clearEnv: [],}}}@@ -212,7 +232,15 @@ async function buildBaseLaunchOverrides(// A Codex agent on a profile OTHER than this machine's default reads hooks.json from THAT folder,// not the one `harness login` installed into — without this it fires no hook at all. Idempotent.deps.installCodexHooks(source.codexHome)- return { ok: true, overrides: { env: { CODEX_HOME: source.codexHome }, extraArgs: [], clearEnv: [] } }+ return {+ ok: true,+ overrides: {+ env: { CODEX_HOME: source.codexHome, ...(ownLogin?.env ?? {}) },+ extraArgs: [...(ownLogin?.extraArgs ?? [])],+ clearEnv: [],+ },+ }}+ if (ownLogin) return { ok: true, overrides: ownLogin }return { ok: true, overrides: noOverrides() }}