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
Codex model switching works on Codex 0.160, and Max/Ultra follow Codex's own catalog (#848)
Dee1f0202c194d3
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjsindex 14c09c062..09da02bc5 100644--- a/cli/e2e/harness/fakeEngine.mjs+++ b/cli/e2e/harness/fakeEngine.mjs@@ -29,7 +29,9 @@// settings and `!center` (Codex) in its agent command center, screens the daemon has no name for,// `!permitnext <command>` keeps its turn open and asks permission to run the command the moment a// message is pasted, before its Enter (a request arriving mid-turn), `!exit` ends the process.-// Everything else is echoed as the answer.+// Everything else is echoed as the answer. Codex's `/model` is not a prompt: it opens 0.160's model+// picker over the `models_cache.json` in its CODEX_HOME, and a choice in it is applied to the turns+// that follow (see `openModelPicker`).//// Which release is installed is the config's business, so a test can update an engine in place by// rewriting its wrapper: `version` is what it reports and writes, `without` lists the flags and@@ -105,7 +107,7 @@ async function codexWrapper(config) {export async function run(engine, config = {}, { native = false } = {}) {if (engine === 'codex' && !native) return codexWrapper(config)const args = process.argv.slice(2)- const version = config.version ?? (engine === 'claude' ? '2.1.270' : '0.159.0')+ const version = config.version ?? (engine === 'claude' ? '2.1.270' : '0.160.0')const versionLine = engine === 'claude' ? `${version} (Claude Code)` : `codex-cli ${version}`const without = new Set(config.without ?? [])if (args.includes('--version') || args.includes('-V')) {@@ -151,7 +153,7 @@ export async function run(engine, config = {}, { native = false } = {}) {// (update_prompt.rs, snapshot `update_prompt_modal`). It drops a paste; Enter takes the highlighted row,// `Update now`, runs the update and asks to be restarted; Esc, 2 or ctrl+c skip it.if (engine === 'codex' && config.updateAvailable) {- process.stdout.write(`\r\n \x1b[1mUpdate available\x1b[0m\x1b[2m · \x1b[0m${config.version ?? '0.159.0'} → ${config.updateAvailable}\r\n`+ process.stdout.write(`\r\n \x1b[1mUpdate available\x1b[0m\x1b[2m · \x1b[0m${version} → ${config.updateAvailable}\r\n`+ ' \x1b[2mRelease notes: \x1b[0mhttps://github.com/openai/codex/releases/latest\r\n\r\n'+ '\x1b[36m› 1. Update now (runs `npm install -g @openai/codex`)\x1b[39m\r\n 2. Skip\r\n 3. Skip until next version\r\n\r\n'+ ' enter\x1b[2m continue · \x1b[0mesc\x1b[2m skip\x1b[0m\r\n')@@ -261,7 +263,9 @@ export async function run(engine, config = {}, { native = false } = {}) {? (args.includes('--dangerously-skip-permissions') ? 'bypassPermissions': args.includes('--permission-mode') ? args[args.indexOf('--permission-mode') + 1] ?? 'default' : 'default'): (args.includes('--dangerously-bypass-approvals-and-sandbox') ? 'bypassPermissions' : 'default')- const codexModel = config.codexModel ?? 'gpt-6'+ // The model and effort the thread runs on: what Codex writes in each turn's context, and what its+ // `/model` picker changes (below).+ let current = { model: config.codexModel ?? 'gpt-6', effort: 'high' }/*** The JSON an event hands its hooks on stdin, in each CLI's own shape: what notify.mjs reads (session,* transcript, folder, the event and its source, prompt or reason) and the rest of what the real CLIs@@ -273,7 +277,7 @@ export async function run(engine, config = {}, { native = false } = {}) {transcript_path: transcript,cwd,hook_event_name: event,- ...(engine === 'codex' ? { model: codexModel, permission_mode: permissionMode } : {}),+ ...(engine === 'codex' ? { model: current.model, permission_mode: permissionMode } : {}),...fields,})/**@@ -355,10 +359,13 @@ export async function run(engine, config = {}, { native = false } = {}) {// transcript view.let bottom = nulllet dialog = null+ // Codex's `/model` picker while it is open, in the composer's place (see `openModelPicker`).+ let picker = nullconst columns = () => Math.max(20, process.stdout.columns || 80)- // Cut to the pane's width, as Codex fits its status line to one row.- const statusLine = () => ` \x1b[2m${`gpt-6 high · ${cwd}`.slice(0, columns() - 3)}\x1b[0m`- const goalBottom = (goal) => ({ footer: ` gpt-6 high · ${cwd} \x1b[35m${goal}\x1b[0m` })+ // Cut to the pane's width, as Codex fits its status line to one row. It names the model and effort the+ // thread runs on, which `/model` changes.+ const statusLine = () => ` \x1b[2m${`${current.model} ${current.effort} · ${cwd}`.slice(0, columns() - 3)}\x1b[0m`+ const goalBottom = (goal) => ({ footer: ` ${current.model} ${current.effort} · ${cwd} \x1b[35m${goal}\x1b[0m` })const browsingFooter = '\x1b[36mBrowsing transcript\x1b[0m\x1b[2m · \x1b[0m↑↓/jk\x1b[2m scroll · \x1b[0m←→/hl\x1b[2m prompts · \x1b[0m↵\x1b[2m rewind · \x1b[0mesc\x1b[2m back\x1b[0m'const browsingBottom = { dim: true, footer: browsingFooter, browsing: true }const pagerBottom = (prompt, answer) => ({ browsing: true, pager: `\x1b[?1049h\x1b[H\x1b[2J\x1b[2m/ T R A N S C R I P T ${'/ '.repeat(30)}\x1b[0m`@@ -483,19 +490,24 @@ export async function run(engine, config = {}, { native = false } = {}) {}const drawComposer = () => {if (bottom?.pager) { process.stdout.write(bottom.pager); composerRows = 0; return }- // A dialog takes the composer's place, as the CLIs draw theirs, until it is answered.- if (dialog) return+ // A dialog takes the composer's place, as the CLIs draw theirs, until it is answered; so does Codex's+ // model picker, until a choice or Esc closes it.+ if (dialog || picker) returnconst rows = composerLines()process.stdout.write(rows.join('\r\n'))composerRows = rows.reduce((sum, row) => sum + rowsOf(row), 0)}const draw = () => { eraseComposer(); drawComposer() }- /** The conversation, written above the composer. `text` ends at the start of a line. */- const say = (text) => { eraseComposer(); process.stdout.write(text); drawComposer() }+ /** The conversation, written above the composer, or above Codex's model picker while it is open, as+ * its history cells are. `text` ends at the start of a line. */+ const say = (text) => {+ if (picker) { erasePicker(); process.stdout.write(text); drawPicker(); return }+ eraseComposer(); process.stdout.write(text); drawComposer()+ }// A resize redraws the whole frame, as the TUIs do: the composer measured at the old width cannot be// taken back row by row.process.stdout.on?.('resize', () => {- if (bottom?.pager || dialog) return+ if (bottom?.pager || dialog || picker) returnprocess.stdout.write('\x1b[H\x1b[2J')composerRows = 0drawComposer()@@ -587,6 +599,270 @@ export async function run(engine, config = {}, { native = false } = {}) {}}}+ // Codex 0.160's `/model` picker (tui/src/chatwidget/model_popups.rs, luna_reserve_model.rs,+ // model_popup_state.rs, bottom_pane/list_selection_view.rs at rust-v0.160.0), drawn as it draws it+ // and driven by the keys it takes. The quick menu of auto presets with `All models`, or the full list+ // when there are none; the chosen model's reasoning picker; Advanced Reasoning for Max and Ultra; and,+ // for a thread on the reserve model, the one-row picker that lends it an ordinary model's efforts.+ // Rows are the catalog's display names, from `models_cache.json` in this engine's CODEX_HOME. A digit+ // selects its row and accepts it, arrows move, Enter accepts, `s` takes the row for this session only,+ // Esc goes back a screen. A choice is applied with Codex's `thread_settings_applied` record.+ //+ // The list is redrawn in place when "the server" answers, as 0.160 refreshes it from the models+ // endpoint once it is open: `fake-models-server.json` beside the cache (`{ delayMs, models }`) is that+ // answer. Its models replace the cache's, are saved to `models_cache.json`, and renumber an open list,+ // its highlight kept on the same model, while a reasoning screen open over it stays as it is.+ const LUNA_RESERVE_MODEL = 'gpt-reserve'+ const LUNA_MODEL = 'gpt-6-luna'+ const ADVANCED = new Set(['max', 'ultra'])+ const EFFORT_LABELS = { none: 'None', minimal: 'Minimal', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'Extra high', max: 'Max', ultra: 'Ultra', persistent: 'Persistent' }+ const effortLabel = (effort) => EFFORT_LABELS[effort] ?? effort+ const MAX_POPUP_ROWS = 8+ const modelsCacheFile = join(codexHome, 'models_cache.json')+ const modelsServerFile = join(codexHome, 'fake-models-server.json')+ const readJson = (file) => { try { return JSON.parse(readFileSync(file, 'utf8')) } catch { return null } }+ /** The presets the picker lists, as Codex builds them from its catalog (models-manager+ * `build_available_models`): by priority, the first listed one the default. */+ const presetsOf = (models) => {+ const presets = (Array.isArray(models) ? models : []).filter((model) => model?.slug)+ .sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0))+ .map((model) => ({+ model: model.slug, displayName: model.display_name || model.slug, description: model.description ?? '',+ defaultEffort: model.default_reasoning_level ?? 'none', listed: model.visibility === 'list', isDefault: false,+ efforts: (model.supported_reasoning_levels ?? []).map((level) => ({ effort: level.effort, description: level.description ?? '' })),+ }))+ const first = presets.find((preset) => preset.listed) ?? presets[0]+ if (first) first.isDefault = true+ return presets+ }+ const isAuto = (slug) => slug.startsWith('codex-auto-')+ const autoOrder = (slug) => ({ 'codex-auto-fast': 0, 'codex-auto-balanced': 1, 'codex-auto-thorough': 2 })[slug] ?? 3+ const requiresAdvanced = (preset) => ADVANCED.has(preset.defaultEffort) || preset.efforts.some((option) => ADVANCED.has(option.effort))+ /** The effort a full-list row applies at once: its one ordinary effort, or none to choose. */+ const directEffort = (preset) => {+ const choices = preset.efforts.length ? preset.efforts.map((option) => option.effort) : [preset.defaultEffort]+ return choices.length === 1 && !ADVANCED.has(choices[0]) ? choices[0] : null+ }+ /** Words to lines of at most `width`, as ratatui wraps them; a word longer than a line is cut. */+ const wrapWords = (text, width) => {+ const lines = []+ let line = ''+ for (const word of String(text).split(/\s+/).filter(Boolean)) {+ let next = line ? `${line} ${word}` : word+ if (line && next.length > width) { lines.push(line); next = word }+ while (next.length > width) { lines.push(next.slice(0, width)); next = next.slice(width) }+ line = next+ }+ lines.push(line)+ return lines+ }+ /** One screen of the picker, as list_selection_view.rs renders it: header, two blank lines, the rows+ * (eight at most, scrolled to the highlight), a blank line and the key hints. */+ const renderView = (view) => {+ const cols = Math.max(20, process.stdout.columns || 80)+ const lines = []+ for (const { text, style } of view.header) {+ for (const part of wrapWords(text, cols - 2)) lines.push(` ${style}${part}${style ? '\x1b[0m' : ''}`)+ }+ lines.push('', '')+ const label = (item) => `${item.name}${item.current ? ' (current)' : item.isDefault ? ' (default)' : ''}`+ const prefixOf = (index) => `${index === view.selected ? '›' : ' '} ${index + 1}. `+ const nameWidth = Math.max(...view.items.map((item, index) => prefixOf(index).length + label(item).length))+ const descriptionColumn = nameWidth + 2+ // The picker's `HideWhenNarrow`: no descriptions when fewer than 24 columns are left for them.+ const descriptions = cols - descriptionColumn >= 24+ if (view.selected < view.top) view.top = view.selected+ if (view.selected >= view.top + MAX_POPUP_ROWS) view.top = view.selected - MAX_POPUP_ROWS + 1+ view.items.slice(view.top, view.top + MAX_POPUP_ROWS).forEach((item, offset) => {+ const index = view.top + offset+ const prefix = prefixOf(index)+ const selected = index === view.selected+ const rows = descriptions && item.description+ ? wrapWords(item.description, cols - descriptionColumn).map((part, line) => line === 0+ ? `${prefix}${label(item).padEnd(descriptionColumn - prefix.length)}${selected ? part : `\x1b[2m${part}\x1b[0m`}`+ : `${' '.repeat(descriptionColumn)}${selected ? part : `\x1b[2m${part}\x1b[0m`}`)+ : wrapWords(label(item), cols - prefix.length).map((part, line) => `${line === 0 ? prefix : ' '.repeat(prefix.length)}${part}`)+ for (const row of rows) lines.push(selected ? `\x1b[36m${row}\x1b[39m` : row)+ })+ lines.push('')+ const highlighted = view.items[view.selected]+ lines.push(highlighted?.secondary+ ? ` enter\x1b[2m ${highlighted.applies ?? 'default'} · \x1b[0ms\x1b[2m session · \x1b[0mesc\x1b[2m back\x1b[0m`+ : ' enter\x1b[2m select · \x1b[0mesc\x1b[2m back\x1b[0m')+ return lines+ }+ const erasePicker = () => {+ if (picker?.drawn) process.stdout.write(`\x1b[${picker.drawn}A\r\x1b[0J`)+ if (picker) picker.drawn = 0+ }+ const drawPicker = () => {+ erasePicker()+ const lines = renderView(picker.stack.at(-1))+ process.stdout.write(`${lines.join('\r\n')}\r\n`)+ picker.drawn = lines.length+ }+ const closePicker = () => { erasePicker(); picker = null; drawComposer() }+ /** Applies a model and effort to the thread, as Codex does once a choice is accepted: the settings+ * update its app server answers with `thread_settings_applied` (protocol.rs `ThreadSettingsAppliedEvent`). */+ const applyChoice = (model, effort) => {+ current = { model, effort }+ codex('event_msg', {+ type: 'thread_settings_applied',+ thread_id: sessionId,+ thread_settings: {+ model, model_provider_id: 'openai', approval_policy: 'on-request', cwd, runtime_workspace_roots: [cwd],+ reasoning_effort: effort, collaboration_mode: { mode: 'default', settings: { model, reasoning_effort: effort } },+ },+ })+ closePicker()+ }+ const view = (id, header, items, selected = items.findIndex((item) => item.current)) =>+ ({ id, header, items, selected: Math.max(0, selected), top: 0 })+ const title = (text) => ({ text, style: '\x1b[1m' })+ const subtitle = (text) => ({ text, style: '\x1b[2m' })+ /** The reasoning picker for a preset, or the choice applied at once when it has one ordinary effort. */+ const openReasoning = (preset) => {+ const choices = preset.efforts.length ? preset.efforts.map((option) => option.effort) : [preset.defaultEffort]+ const ordinary = choices.filter((effort) => !ADVANCED.has(effort))+ const advanced = choices.filter((effort) => ADVANCED.has(effort))+ if (ordinary.length === 1 && !advanced.length) { applyChoice(preset.model, ordinary[0]); return }+ const defaultChoice = ordinary.includes(preset.defaultEffort) ? preset.defaultEffort : null+ const onModel = current.model === preset.model+ const highlight = onModel ? current.effort : defaultChoice ?? ordinary[0]+ const describe = (effort) => preset.efforts.find((option) => option.effort === effort)?.description ?? ''+ const items = ordinary.map((effort) => ({+ name: `${effortLabel(effort)}${effort === defaultChoice ? ' (default)' : ''}`, description: describe(effort),+ current: onModel && effort === highlight, accept: () => applyChoice(preset.model, effort),+ secondary: preset.model === LUNA_RESERVE_MODEL ? null : () => applyChoice(preset.model, effort),+ }))+ if (advanced.length) {+ items.push({+ name: 'More reasoning…', description: `${advanced.map(effortLabel).join(' and ')} ${advanced.length === 1 ? 'consumes' : 'consume'} usage limits faster`,+ current: onModel && ADVANCED.has(highlight), accept: () => openAdvanced(preset),+ })+ }+ const selected = items.findIndex((item, index) => index < ordinary.length && ordinary[index] === highlight)+ picker.stack.push(view('reasoning', [title(`Select Reasoning Level for ${preset.displayName}`)], items, selected))+ drawPicker()+ }+ const openAdvanced = (preset) => {+ const choices = preset.efforts.map((option) => option.effort).filter((effort) => ADVANCED.has(effort))+ .sort((a, b) => (a === 'ultra') - (b === 'ultra'))+ const items = choices.map((effort) => ({+ name: effortLabel(effort),+ description: effort === 'max' ? 'For difficult problems when quality matters more than speed · higher usage' : 'For demanding work using multiple agents · highest usage',+ current: current.model === preset.model && current.effort === effort, applies: effort === 'ultra' ? 'apply' : 'default',+ accept: () => applyChoice(preset.model, effort), secondary: () => applyChoice(preset.model, effort),+ }))+ picker.stack.push(view('advanced', [title('Advanced Reasoning'), { text: '⚠ Consumes usage limits faster', style: '\x1b[36m' }], items))+ drawPicker()+ }+ /** The full list (`Select Model and Effort`), or null when it would be empty. */+ const allModelsView = (presets, id) => {+ const listed = presets.filter((preset) => preset.listed && !isAuto(preset.model))+ if (!listed.length) return null+ return view(id, [title('Select Model and Effort')], listed.map((preset) => {+ const effort = directEffort(preset)+ return {+ slug: preset.model, name: preset.displayName, description: preset.description, current: preset.model === current.model,+ isDefault: preset.isDefault, accept: () => openReasoning(preset),+ secondary: effort === null ? null : () => applyChoice(preset.model, effort),+ }+ }))+ }+ /** What `/model` opens on: the reserve picker, the quick menu, or the full list when no auto preset is listed. */+ const firstView = (presets) => {+ if (current.model === LUNA_RESERVE_MODEL) {+ const normal = presets.find((preset) => preset.model === LUNA_MODEL)+ if (!normal) return null+ const preset = { ...normal, model: LUNA_RESERVE_MODEL }+ return view('model-selection', [title('Select Model'), subtitle('Other models return when ordinary usage is available again.')],+ [{ slug: LUNA_RESERVE_MODEL, name: normal.displayName, description: normal.description, current: true, accept: () => openReasoning(preset) }])+ }+ const listed = presets.filter((preset) => preset.listed)+ const autos = listed.filter((preset) => isAuto(preset.model)).sort((a, b) => autoOrder(a.model) - autoOrder(b.model))+ if (!autos.length) return allModelsView(presets, 'model-selection')+ const items = autos.map((preset) => ({+ slug: preset.model, name: preset.displayName, description: preset.description, current: preset.model === current.model,+ isDefault: preset.isDefault,+ accept: requiresAdvanced(preset) ? () => openReasoning(preset) : () => applyChoice(preset.model, preset.defaultEffort),+ secondary: requiresAdvanced(preset) ? null : () => applyChoice(preset.model, preset.defaultEffort),+ }))+ if (listed.some((preset) => !isAuto(preset.model))) {+ const currentLabel = listed.find((preset) => preset.model === current.model)?.displayName ?? current.model+ items.push({+ slug: 'All models', name: 'All models', description: `Choose a specific model and reasoning level (current: ${currentLabel})`,+ current: !items.some((item) => item.current), accept: openAllModels,+ })+ }+ return view('model-selection', [title('Select Model'), subtitle('Pick a quick auto mode or browse all models.')], items)+ }+ // `All models` closes the quick menu and opens the full list in its place: Esc from it closes the picker.+ const openAllModels = () => {+ const next = allModelsView(picker.presets, 'all-models-selection')+ if (!next) { closePicker(); say('No additional models are available right now.\r\n'); return }+ picker.stack = [next]+ drawPicker()+ }+ const openModelPicker = () => {+ const presets = presetsOf(readJson(modelsCacheFile)?.models)+ eraseComposer()+ picker = { stack: [], drawn: 0, presets }+ const first = firstView(presets)+ if (!first) {+ picker = null+ say(current.model === LUNA_RESERVE_MODEL+ ? 'Luna model settings are unavailable; please try /model again in a moment.\r\n'+ : 'No additional models are available right now.\r\n')+ return+ }+ picker.stack = [first]+ drawPicker()+ // The server's answer, once it comes, for this opening only (model_popup_state.rs `on_models_loaded`).+ const server = readJson(modelsServerFile)+ if (!server || !Array.isArray(server.models)) return+ const opened = picker+ setTimeout(() => {+ writeFileSync(modelsCacheFile, JSON.stringify({ ...readJson(modelsCacheFile), fetched_at: new Date().toISOString(), models: server.models }, null, 2))+ if (picker !== opened) return+ const presets = presetsOf(server.models)+ if (JSON.stringify(presets) === JSON.stringify(picker.presets)) return+ picker.presets = presets+ const parent = picker.stack[0]+ if (parent.id !== 'model-selection' && parent.id !== 'all-models-selection') return+ const refreshed = parent.id === 'model-selection' ? firstView(presets) : allModelsView(presets, parent.id)+ if (!refreshed) { closePicker(); return }+ // The highlight stays on the same model, by slug, wherever its row moved to.+ const slug = parent.items[parent.selected]?.slug+ const kept = refreshed.items.findIndex((item) => item.slug === slug)+ if (kept >= 0) refreshed.selected = kept+ picker.stack[0] = refreshed+ if (picker.stack.length === 1) drawPicker()+ }, Number(server.delayMs) || 0)+ }+ /** Keys while the picker is up. Returns what is left once it closes, for the composer. */+ const pickerKeys = (chunk) => {+ let rest = ''+ for (const key of chunk.match(/\x1b\[200~[\s\S]*?(?:\x1b\[201~|$)|\x1b\[[0-9;]*[A-Za-z~]|\x1b|[\s\S]/g) ?? []) {+ if (!picker) { rest += key; continue }+ const top = picker.stack.at(-1)+ if (key === '\x1b' || key === '\x03') {+ picker.stack.pop()+ if (picker.stack.length) drawPicker()+ else closePicker()+ } else if (key === '\x1b[A' || key === '\x1b[B') {+ top.selected = (top.selected + (key === '\x1b[A' ? top.items.length - 1 : 1)) % top.items.length+ drawPicker()+ } else if (key === '\r' || key === '\n') top.items[top.selected]?.accept()+ else if (key === 's' && top.items[top.selected]?.secondary) top.items[top.selected].secondary()+ else if (/^[1-9]$/.test(key) && Number(key) <= top.items.length) {+ top.selected = Number(key) - 1+ top.items[top.selected].accept()+ }+ // Anything else, a paste included, is dropped: the list is not searchable.+ }+ return rest+ }const compact = () => {if (engine === 'claude') {claude({ type: 'system', subtype: 'compact_boundary', content: 'Conversation compacted', compactMetadata: { trigger: 'manual', preTokens: 4096 } })@@ -694,7 +970,7 @@ export async function run(engine, config = {}, { native = false } = {}) {claude({ type: 'assistant', message: { id: `msg_${turn}_t`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'thinking', thinking: `considering: ${prompt}` }], stop_reason: null } })} else {codex('event_msg', { type: 'task_started', turn_id: open })- codex('turn_context', { turn_id: open, model: config.codexModel ?? 'gpt-6', reasoning_effort: 'high', collaboration_mode: { mode: 'default' } })+ codex('turn_context', { turn_id: open, model: current.model, reasoning_effort: current.effort, collaboration_mode: { mode: 'default' } })codex('event_msg', { type: 'item_completed', turn_id: open, item: { type: 'UserMessage', id: open, content: [{ type: 'text', text: prompt, text_elements: [] }] } })codex('response_item', { type: 'reasoning', summary: [{ type: 'summary_text', text: `considering: ${prompt}` }] })}@@ -869,6 +1145,10 @@ export async function run(engine, config = {}, { native = false } = {}) {if (input.includes('\x1a') && !pasting && !input.includes('\x1b[200~')) { suspend(); return }if (dialog) { dialogKeys(input); return }let chunk = input+ if (picker) {+ chunk = pickerKeys(chunk)+ if (!chunk) return+ }if (bottom?.transcript) {// As Claude Code takes input in its transcript view: its Transcript keys only, where Esc, q and ctrl+c// close it; it has no Enter and no paste, so a message is lost there. Keys after the one that closes@@ -972,8 +1252,19 @@ export async function run(engine, config = {}, { native = false } = {}) {}if (part === '\x7f') { buffer = buffer.slice(0, -1); draw(); continue }if ((part === '\r' || part === '\n') && suggestions(buffer)) {- // Enter with suggestions open takes the highlighted one into the draft, and sends nothing.const popup = suggestions(buffer)+ // Codex runs the highlighted command on Enter (chat_composer/slash_input.rs), the draft cleared; of+ // its commands the fake carries out `/model`, whose picker takes the composer's place. The keys+ // after it in this read are the picker's.+ if (engine === 'codex' && popup.found[0][0] === '/model' && popup.token.startsWith('/')) {+ buffer = ''+ pastes.clear()+ openModelPicker()+ const rest = parts.slice(index + 1).join('')+ if (rest && picker) { const left = pickerKeys(rest); if (left) process.stdin.emit('data', left) }+ return+ }+ // Otherwise Enter with suggestions open takes the highlighted one into the draft, and sends nothing.buffer = `${buffer.slice(0, buffer.length - popup.token.length)}${popup.token.startsWith('@') ? '@' : ''}${popup.found[0][0]} `draw()continue@@ -993,6 +1284,14 @@ export async function run(engine, config = {}, { native = false } = {}) {// Taken off the composer at once, whatever the engine is doing: a prompt sent while a turn runs// waits its turn out of the composer, as both CLIs queue one.draw()+ // Codex's `/model` is a command, not a prompt: its picker takes the composer's place at once and+ // nothing is sent. The keys after it in this read are the picker's.+ if (engine === 'codex' && line.trim() === '/model') {+ openModelPicker()+ const rest = parts.slice(index + 1).join('')+ if (rest && picker) { const left = pickerKeys(rest); if (left) process.stdin.emit('data', left) }+ return+ }queue = queue.then(() => handle(line))} else if (part) {buffer += partdiff --git a/cli/e2e/models.e2e.ts b/cli/e2e/models.e2e.tsnew file mode 100644index 000000000..3e0d0a27c--- /dev/null+++ b/cli/e2e/models.e2e.ts@@ -0,0 +1,164 @@+/**+ * A Codex agent's model and effort switched from the app, on the real daemon: `agent_update` with a+ * `selectedModel` the agent's catalog offered, typed into the fake Codex's `/model` picker as 0.160+ * draws it (fakeEngine.mjs) and confirmed by the `thread_settings_applied` record Codex writes. Its rows+ * are the catalog's display names, read from `models_cache.json` in the agent's CODEX_HOME: the catalog+ * 0.160 ships (src/lib/__fixtures__/codex-home-0.160).+ *+ * Until this switch read rows by display name the daemon refused every Codex from 0.146 on, so no run+ * of this suite switched a Codex model at all: the fake reported 0.159.+ */+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient, type Frame } from './harness/client.js'+import { CLI_ROOT, IsolatedDaemon, until, type DaemonOptions } from './harness/daemon.js'++const CATALOG = JSON.parse(readFileSync(join(CLI_ROOT, 'src/lib/__fixtures__/codex-home-0.160/models_cache.json'), 'utf8'))++/** A `runtime-v1:` profile id as the daemon mints them (lib/runtimeProfile.ts), and its model and effort. */+const profile = (agentId: string, model: string, effort: string) =>+ `runtime-v1:${encodeURIComponent(agentId)}:codex:${encodeURIComponent(model)}@${effort}`+const parseProfile = (id: unknown): { model: string; effort: string } | null => {+ const match = typeof id === 'string' ? /^runtime-v1:[^:]+:codex:([^@]+)@([a-z0-9_-]+)$/.exec(id) : null+ return match ? { model: decodeURIComponent(match[1]), effort: match[2] } : null+}++const row = async (client: LocalClient, agentId: string) =>+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)+ .find((agent) => agent.id === agentId)+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId++async function create(daemon: IsolatedDaemon, client: LocalClient, folder: string): Promise<Record<string, any>> {+ const cwd = join(daemon.projectsDir, folder)+ mkdirSync(cwd, { recursive: true })+ const created = await client.request('agent_create', { engine: 'codex', cwd, bypassPermission: true }, 90_000)+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()+ return until(`${folder} to bind its conversation`, async () => {+ const agent = await row(client, created.agent.id)+ return agent?.sessionId && agent.status === 'active' ? agent : null+ }, 60_000, 500)+}++/** A turn, so the rollout names the model and effort the agent runs on (the fake's `turn_context`). */+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, 'turn_ended')+ client.send('message', { agentId, content })+ await ended+}++/** The agent's chip once it reads `model` at `effort`. */+const runningOn = (client: LocalClient, agentId: string, model: string, effort: string) =>+ until(`the agent to run on ${model} at ${effort}`, async () => {+ const running = parseProfile((await row(client, agentId))?.selectedModel)+ return running?.model === model && running.effort === effort ? running : null+ }, 30_000, 250)++/** The settings Codex applied, from its rollout: every `thread_settings_applied` record, in order. */+function applied(daemon: IsolatedDaemon, sessionId: string): Array<{ model: string; effort: string }> {+ const folder = join(daemon.engineConfig.codexHome, 'sessions', '2026', '10', '03')+ const file = readdirSync(folder).find((name) => name.endsWith(`${sessionId}.jsonl`))+ if (!file) return []+ return readFileSync(join(folder, file), 'utf8').split('\n').filter(Boolean).map((line) => JSON.parse(line))+ .filter((record) => record.type === 'event_msg' && record.payload?.type === 'thread_settings_applied')+ .map((record) => ({ model: record.payload.thread_settings.model, effort: record.payload.thread_settings.reasoning_effort }))+}++describe('switching a Codex agent model and effort', () => {+ let daemon: IsolatedDaemon | undefined+ afterEach(async () => { await daemon?.close(); daemon = undefined })+ /** A daemon whose Codex home holds a catalog (0.160's own unless told), and the server's answer when one is given. */+ const fresh = async (options: DaemonOptions, server?: { delayMs: number; models: unknown[] }, catalog = CATALOG) => {+ const d = await IsolatedDaemon.create(options)+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').filter((line) => /runtime-profile|codex/i.test(line)).slice(-60).join('\n')}`) })+ writeFileSync(join(d.engineConfig.codexHome, 'models_cache.json'), JSON.stringify(catalog))+ if (server) writeFileSync(join(d.engineConfig.codexHome, 'fake-models-server.json'), JSON.stringify(server))+ await d.start()+ return d+ }++ it('switches the model through All models by its display name, then the effort alone, then to a quick preset', async () => {+ // An auto preset makes `/model` open on the quick menu, with every other model behind `All models`+ // (the catalog of 0.160's own test `custom_model_display_name_in_pickers_preserves_selection_slug`).+ const luna = CATALOG.models.find((model: { slug: string }) => model.slug === 'gpt-6-luna')+ const autoFast = { ...luna, slug: 'codex-auto-fast', display_name: 'Auto Fast', description: 'Custom provider model', priority: 0,+ default_reasoning_level: 'high', supported_reasoning_levels: [{ effort: 'low', description: 'Quick answers' }, { effort: 'high', description: 'Deeper reasoning' }] }+ const d = await fresh({ codexModel: 'gpt-5.5' }, undefined, { ...CATALOG, models: [autoFast, ...CATALOG.models] })+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'switch')+ await turn(client, agent.id, 'hello')+ await runningOn(client, agent.id, 'gpt-5.5', 'high')++ // What the app offers is the catalog: a model and effort the picker lists.+ const offered = (await client.request<{ models: Array<{ id: string; displayName: string }> }>('models_list', { agentId: agent.id })).models+ const xhigh = profile(agent.id, 'gpt-6-luna', 'xhigh')+ expect(offered.find((option) => option.id === xhigh)?.displayName).toBe('GPT-6-Luna / XHigh')++ const switched = await client.request('agent_update', { agentId: agent.id, selectedModel: xhigh }, 60_000)+ expect(switched.error, JSON.stringify(switched)).toBeUndefined()+ expect(switched.agent.selectedModel).toBe(xhigh)+ expect(applied(d, agent.sessionId)).toEqual([{ model: 'gpt-6-luna', effort: 'xhigh' }])++ // The effort alone: the same model's row again, and Low in its reasoning picker.+ const low = profile(agent.id, 'gpt-6-luna', 'low')+ const lowered = await client.request('agent_update', { agentId: agent.id, selectedModel: low }, 60_000)+ expect(lowered.error, JSON.stringify(lowered)).toBeUndefined()+ expect(lowered.agent.selectedModel).toBe(low)+ expect(applied(d, agent.sessionId)).toEqual([{ model: 'gpt-6-luna', effort: 'xhigh' }, { model: 'gpt-6-luna', effort: 'low' }])++ // The picker closed behind it and the agent goes on, on the model it was moved to.+ expect(await d.capture(agent.tmuxPane)).not.toMatch(/Select Model|Select Reasoning Level/)+ await turn(client, agent.id, 'after the switch')+ await runningOn(client, agent.id, 'gpt-6-luna', 'low')++ // The quick preset's row applies its default effort, High, at once: one key.+ const quick = await client.request('agent_update', { agentId: agent.id, selectedModel: profile(agent.id, 'codex-auto-fast', 'auto') }, 60_000)+ expect(quick.error, JSON.stringify(quick)).toBeUndefined()+ expect(applied(d, agent.sessionId).at(-1)).toEqual({ model: 'codex-auto-fast', effort: 'high' })+ await runningOn(client, agent.id, 'codex-auto-fast', 'high')+ client.close()+ })++ it('presses the row the list shows once the server answer has renumbered it', async () => {+ // The server knows a model the cache does not, first in priority: when its answer reaches the open+ // picker every row moves down one, GPT-6-Luna from 4 to 5.+ const server = [{ ...CATALOG.models.find((model: { slug: string }) => model.slug === 'gpt-6.1-sol'), slug: 'gpt-6.2-sol', display_name: 'GPT-6.2-Sol', priority: 0 },+ ...CATALOG.models]+ const d = await fresh({ codexModel: 'gpt-5.5' }, { delayMs: 150, models: server })+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'refresh')+ await turn(client, agent.id, 'hello')+ await runningOn(client, agent.id, 'gpt-5.5', 'high')++ const target = profile(agent.id, 'gpt-6-luna', 'high')+ const answer = await client.request('agent_update', { agentId: agent.id, selectedModel: target }, 60_000)+ expect(answer.error, JSON.stringify(answer)).toBeUndefined()+ expect(applied(d, agent.sessionId)).toEqual([{ model: 'gpt-6-luna', effort: 'high' }])+ // Codex saved what the server answered, and the next picker opens on it.+ expect(JSON.parse(readFileSync(join(d.engineConfig.codexHome, 'models_cache.json'), 'utf8')).models[0].slug).toBe('gpt-6.2-sol')+ client.close()+ })++ it('offers an account held to the reserve model no other model, and changes the reserve effort', async () => {+ const d = await fresh({ codexModel: 'gpt-reserve' })+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'reserve')+ await turn(client, agent.id, 'hello')+ await runningOn(client, agent.id, 'gpt-reserve', 'high')++ // The catalog still lists GPT-6-Luna, but the picker has one row: the reserve model under its name.+ const refused = await client.request('agent_update', { agentId: agent.id, selectedModel: profile(agent.id, 'gpt-6-luna', 'high') }, 60_000)+ expect(refused.error).toBe('MODEL_UNAVAILABLE')+ expect(applied(d, agent.sessionId)).toEqual([])+ await until('the picker to close', async () => !/Select Model/.test(await d.capture(agent.tmuxPane)) || null, 10_000, 200)++ // Its default effort, Medium, through the one row and the reasoning picker it lends.+ const auto = profile(agent.id, 'gpt-reserve', 'auto')+ const answer = await client.request('agent_update', { agentId: agent.id, selectedModel: auto }, 60_000)+ expect(answer.error, JSON.stringify(answer)).toBeUndefined()+ expect(applied(d, agent.sessionId)).toEqual([{ model: 'gpt-reserve', effort: 'medium' }])+ await runningOn(client, agent.id, 'gpt-reserve', 'medium')+ client.close()+ })+})diff --git a/cli/e2e/updates.e2e.ts b/cli/e2e/updates.e2e.tsindex 9bbec5ed3..ef717b9c0 100644--- a/cli/e2e/updates.e2e.ts+++ b/cli/e2e/updates.e2e.ts@@ -19,8 +19,9 @@ const engines: Engine[] = ['claude', 'codex']/** A release of the fake engine, as e2e/harness/fakeEngine.mjs reads it from its config. */interface Release { version?: string; without?: string[]; startDelayMs?: number; updateAvailable?: string }-const OLD: Record<Engine, string> = { claude: '2.1.270', codex: '0.159.0' }-const NEW: Record<Engine, string> = { claude: '2.1.271', codex: '0.160.0' }+/** OLD is what the fake engines report unless told otherwise (fakeEngine.mjs); NEW is the next release. */+const OLD: Record<Engine, string> = { claude: '2.1.270', codex: '0.160.0' }+const NEW: Record<Engine, string> = { claude: '2.1.271', codex: '0.161.0' }const versionLine = (engine: Engine, version: string) => engine === 'claude' ? `${version} (Claude Code)` : `codex-cli ${version}`const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms))@@ -202,7 +203,7 @@ describe('engines updated in place', () => {expect((await row(client, agent.id))?.sessionId).toBe(renewed.sessionId)// A release that has resume again opens the kept conversation where it was.- install(d, 'codex', { version: '0.161.0' })+ install(d, 'codex', { version: '0.162.0' })const reopened = await client.request('agent_resume', { agentId: kept.id }, 90_000)expect(reopened.error, JSON.stringify(reopened)).toBeUndefined()await bound(client, kept.id, agent.sessionId)diff --git a/cli/src/engines/codex/modelPicker.spec.ts b/cli/src/engines/codex/modelPicker.spec.tsnew file mode 100644index 000000000..9db237886--- /dev/null+++ b/cli/src/engines/codex/modelPicker.spec.ts@@ -0,0 +1,210 @@+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import {+ CODEX_0145_ALL_MODELS, CODEX_0145_REASONING, CODEX_0160_ADVANCED, CODEX_0160_ALL_MODELS, CODEX_0160_ALL_MODELS_NARROW,+ CODEX_0160_ALL_MODELS_REFRESHED, CODEX_0160_ALL_MODELS_SPACED, CODEX_0160_COMPOSER, CODEX_0160_QUICK_MENU,+ CODEX_0160_QUICK_MENU_SHARED_NAME, CODEX_0160_REASONING, CODEX_0160_REASONING_SPACED, CODEX_0160_RESERVE,+ CODEX_0160_RESERVE_REASONING, CODEX_0160_SHARED_NAMES,+} from '../../lib/__fixtures__/codexModelPickers.js'+import {+ chooseCodexRow, codexDigitPressable, codexEffortRows, isCodexAutoModel, parseCodexCatalog, parseCodexPicker,+ sameCodexPicker, type CodexCatalogModel, type CodexPicker,+} from './modelPicker.js'++const FIXTURES = join(import.meta.dirname, '../../lib/__fixtures__')+/** Codex 0.160's own catalog, in the shape of its models_cache.json. */+const CATALOG = parseCodexCatalog(JSON.parse(readFileSync(join(FIXTURES, 'codex-home-0.160/models_cache.json'), 'utf8')))++const model = (slug: string, displayName: string, efforts: string[], defaultEffort = efforts[0] ?? 'none', listed = true): CodexCatalogModel =>+ ({ slug, displayName, listed, defaultEffort, efforts })+/** The catalog of 0.160's display-name test: an auto preset and a custom-provider model whose name has a space. */+const CUSTOM = [+ model('codex-auto-fast', 'Auto Fast', ['low', 'high'], 'high'),+ model('us.openai.gpt-5.6-luna', 'GPT-5.6 Luna', ['low', 'high'], 'high'),+]+const parsed = (capture: string): CodexPicker => {+ const picker = parseCodexPicker(capture)+ if (!picker) throw new Error('no picker')+ return picker+}+const names = (picker: CodexPicker) => picker.rows.map((row) => `${row.number}. ${row.name}${row.current ? ' *' : ''}${row.isDefault ? ' (d)' : ''}`)++describe('Codex model picker, read off the pane', () => {+ it('reads 0.160 rows by their whole display name, markers apart', () => {+ const list = parsed(CODEX_0160_ALL_MODELS)+ expect(list.kind).toBe('models')+ expect(names(list)).toEqual([+ '1. GPT-6.1-Sol (d)', '2. GPT-6-Astra', '3. GPT-6-Sol', '4. GPT-6-Luna', '5. GPT-5.6-Sol', '6. GPT-5.6-Terra',+ '7. GPT-5.6-Luna', '8. GPT-5.5 *',+ ])+ // A name with a space in it is one name; the old reader stopped at the space and found nothing.+ expect(names(parsed(CODEX_0160_ALL_MODELS_SPACED))).toEqual(['1. GPT-5.6 Luna *'])+ })++ it('reads the quick menu, the reserve picker and both reasoning screens', () => {+ expect(parsed(CODEX_0160_QUICK_MENU)).toMatchObject({ kind: 'quick', model: null })+ expect(names(parsed(CODEX_0160_QUICK_MENU))).toEqual(['1. Auto Fast', '2. All models *'])+ expect(parsed(CODEX_0160_RESERVE)).toMatchObject({ kind: 'reserve' })+ expect(names(parsed(CODEX_0160_RESERVE))).toEqual(['1. GPT-6-Luna *'])++ const reasoning = parsed(CODEX_0160_REASONING)+ expect(reasoning).toMatchObject({ kind: 'efforts', model: 'GPT-5.5' })+ expect(codexEffortRows(reasoning)).toEqual({+ efforts: new Map([['low', 1], ['medium', 2], ['high', 3], ['xhigh', 4], ['persistent', 5]]),+ defaultRow: 2,+ advancedRow: 6,+ })+ // `(default)` is part of an effort's name and `(current)` is Codex's marker; a row can carry both.+ const spaced = parsed(CODEX_0160_REASONING_SPACED)+ expect(spaced.model).toBe('GPT-5.6 Luna')+ expect(codexEffortRows(spaced)).toMatchObject({ efforts: new Map([['low', 1], ['high', 2]]), defaultRow: 2, advancedRow: null })+ const advanced = parsed(CODEX_0160_ADVANCED)+ expect(advanced.kind).toBe('advanced')+ expect(codexEffortRows(advanced).efforts).toEqual(new Map([['max', 1], ['ultra', 2]]))+ expect(parsed(CODEX_0160_RESERVE_REASONING).model).toBe('GPT-6-Luna')+ // An effort Codex does not know by name (its `Custom`) is drawn as itself, and is not one to pick.+ expect(codexEffortRows(parsed(' Select Reasoning Level for GPT-5.5\n\n 1. Low\n 2. future')).efforts).toEqual(new Map([['low', 1]]))+ })++ it('reads 0.145, which named its rows and its reasoning title by slug', () => {+ const list = parsed(CODEX_0145_ALL_MODELS)+ expect(list.kind).toBe('models')+ expect(names(list)).toEqual(['1. gpt-5.6-sol (d)', '2. gpt-5.6-terra', '3. gpt-5.6-luna', '4. gpt-5.5', '5. gpt-5.2 *'])+ expect(parsed(CODEX_0145_REASONING)).toMatchObject({ kind: 'efforts', model: 'gpt-5.4' })+ expect(codexEffortRows(parsed(CODEX_0145_REASONING))).toMatchObject({ defaultRow: 2, advancedRow: 5 })+ })++ it('joins a header and a name that wrapped in a narrow pane', () => {+ const list = parsed(CODEX_0160_ALL_MODELS_NARROW)+ expect(list.kind).toBe('models')+ expect(names(list)).toEqual(['1. GPT-6.1-Sol (d)', '2. GPT-6-Astra', '3. GPT-6-Sol', '4. GPT-5.6 Luna *'])+ })++ it('finds no picker under a newer composer, nor a screen it does not know', () => {+ expect(parseCodexPicker(CODEX_0160_COMPOSER)).toBeNull()+ expect(parseCodexPicker(`${CODEX_0160_ALL_MODELS}\n› \n gpt-5.5 high · /tmp`)).toBeNull()+ // A title with no rows under it, and one Codex does not draw.+ expect(parseCodexPicker(' Select Model and Effort\n\n enter select · esc back')).toBeNull()+ expect(parseCodexPicker(' Select Model\n Something else entirely\n\n› 1. GPT-5.5')).toBeNull()+ expect(parseCodexPicker(' Select Reasoning Level for\n\n› 1. Low')).toBeNull()+ })++ it('tells a list redrawn with its rows renumbered from the same list', () => {+ expect(sameCodexPicker(parsed(CODEX_0160_ALL_MODELS), parsed(CODEX_0160_ALL_MODELS))).toBe(true)+ expect(sameCodexPicker(parsed(CODEX_0160_ALL_MODELS), parsed(CODEX_0160_ALL_MODELS_REFRESHED))).toBe(false)+ expect(sameCodexPicker(parsed(CODEX_0160_ALL_MODELS), parsed(CODEX_0145_ALL_MODELS))).toBe(false)+ const current = parsed(CODEX_0160_ALL_MODELS)+ const moved = { ...current, rows: current.rows.map((row) => ({ ...row, current: row.number === 1 })) }+ expect(sameCodexPicker(current, moved)).toBe(false)+ })+})++describe('Codex catalog', () => {+ it('reads models_cache.json as Codex builds its picker from it', () => {+ expect(CATALOG.filter((entry) => entry.listed).map((entry) => entry.slug)).toEqual([+ 'gpt-6-astra', 'gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5',+ ])+ expect(CATALOG.find((entry) => entry.slug === 'gpt-5.5')).toEqual({+ slug: 'gpt-5.5', displayName: 'GPT-5.5', listed: true, defaultEffort: 'medium', efforts: ['low', 'medium', 'high', 'xhigh'],+ })+ expect(CATALOG.find((entry) => entry.slug === 'codex-auto-review')).toMatchObject({ listed: false })+ })++ it('takes what it can from a damaged cache, as Codex reads a missing default effort', () => {+ expect(parseCodexCatalog(null)).toEqual([])+ expect(parseCodexCatalog({ models: 'none' })).toEqual([])+ expect(parseCodexCatalog({ models: [null, { display_name: 'No slug' }, { slug: 'gpt-x', supported_reasoning_levels: [{}, { effort: 'High' }] }, { slug: 'gpt-y' }] }))+ .toEqual([+ { slug: 'gpt-x', displayName: 'gpt-x', listed: false, defaultEffort: 'none', efforts: ['high'] },+ { slug: 'gpt-y', displayName: 'gpt-y', listed: false, defaultEffort: 'none', efforts: [] },+ ])+ })++ it('knows the quick presets by their slug', () => {+ expect(isCodexAutoModel('codex-auto-fast')).toBe(true)+ expect(isCodexAutoModel('gpt-5.5')).toBe(false)+ })+})++describe('the row a target is reached through', () => {+ it('finds a 0.160 row by the target display name, and a 0.145 row by its slug', () => {+ expect(chooseCodexRow(parsed(CODEX_0160_ALL_MODELS), { model: 'gpt-6-luna', effort: 'high' }, CATALOG))+ .toMatchObject({ row: { number: 4, name: 'GPT-6-Luna' }, opens: 'efforts' })+ expect(chooseCodexRow(parsed(CODEX_0160_ALL_MODELS_SPACED), { model: 'us.openai.gpt-5.6-luna', effort: 'low' }, CUSTOM))+ .toMatchObject({ row: { number: 1 }, opens: 'efforts' })+ expect(chooseCodexRow(parsed(CODEX_0145_ALL_MODELS), { model: 'gpt-5.6-terra', effort: 'low' }, CATALOG))+ .toMatchObject({ row: { number: 2, name: 'gpt-5.6-terra' }, opens: 'efforts' })+ // Renumbered by a refresh: the same model, a row further down.+ expect(chooseCodexRow(parsed(CODEX_0160_ALL_MODELS_REFRESHED), { model: 'gpt-6-luna', effort: 'high' }, CATALOG))+ .toMatchObject({ row: { number: 5 } })+ })++ it('goes through All models from the quick menu for any model that is not a quick preset', () => {+ expect(chooseCodexRow(parsed(CODEX_0160_QUICK_MENU), { model: 'us.openai.gpt-5.6-luna', effort: 'low' }, CUSTOM))+ .toMatchObject({ row: { number: 2, name: 'All models' }, opens: 'list' })+ // The first row carries gpt-5.5's name but is an auto preset: gpt-5.5 itself is behind All models.+ const shared = [...CATALOG, model('codex-auto-test', 'GPT-5.5', ['low', 'medium', 'high'], 'medium')]+ expect(chooseCodexRow(parsed(CODEX_0160_QUICK_MENU_SHARED_NAME), { model: 'gpt-5.5', effort: 'high' }, shared))+ .toMatchObject({ row: { number: 2 }, opens: 'list' })+ expect(chooseCodexRow(parsed(CODEX_0160_QUICK_MENU_SHARED_NAME), { model: 'codex-auto-test', effort: 'auto' }, shared))+ .toMatchObject({ row: { number: 1 }, opens: 'applied', effort: 'medium' })+ expect(chooseCodexRow(parsed(' Select Model\n Pick a quick auto mode or browse all models.\n\n 1. Auto Fast'), { model: 'gpt-5.5', effort: 'high' }, CATALOG))+ .toEqual({ error: 'MODEL_UNAVAILABLE' })+ })++ it('knows which rows apply at once, and refuses an effort such a row cannot give', () => {+ // A quick preset without Max or Ultra applies its default effort, here High.+ const quick = parsed(CODEX_0160_QUICK_MENU)+ expect(chooseCodexRow(quick, { model: 'codex-auto-fast', effort: 'auto' }, CUSTOM)).toMatchObject({ row: { number: 1 }, opens: 'applied', effort: 'high' })+ expect(chooseCodexRow(quick, { model: 'codex-auto-fast', effort: 'high' }, CUSTOM)).toMatchObject({ opens: 'applied' })+ expect(chooseCodexRow(quick, { model: 'codex-auto-fast', effort: 'low' }, CUSTOM)).toEqual({ error: 'EFFORT_UNSUPPORTED' })+ // One with an advanced effort opens its reasoning picker instead.+ const advanced = [model('codex-auto-fast', 'Auto Fast', ['low', 'max'], 'low'), CUSTOM[1]]+ expect(chooseCodexRow(quick, { model: 'codex-auto-fast', effort: 'max' }, advanced)).toMatchObject({ opens: 'efforts' })+ // A listed model with one effort, or none (its default), applies it.+ const single = [model('gpt-solo', 'GPT Solo', ['medium']), model('gpt-bare', 'GPT Bare', [], 'low')]+ const list = parsed(' Select Model and Effort\n\n 1. GPT Solo\n 2. GPT Bare')+ expect(chooseCodexRow(list, { model: 'gpt-solo', effort: 'medium' }, single)).toMatchObject({ opens: 'applied', effort: 'medium' })+ expect(chooseCodexRow(list, { model: 'gpt-solo', effort: 'high' }, single)).toEqual({ error: 'EFFORT_UNSUPPORTED' })+ expect(chooseCodexRow(list, { model: 'gpt-bare', effort: 'auto' }, single)).toMatchObject({ opens: 'applied', effort: 'low' })+ // A model the catalog does not describe is pressed by its slug, and the pane says what happened.+ expect(chooseCodexRow(parsed(CODEX_0145_ALL_MODELS), { model: 'gpt-5.2', effort: 'auto' }, CATALOG)).toMatchObject({ row: { number: 5 }, opens: 'unknown' })+ })++ it('presses nothing for a name more than one model could carry', () => {+ const catalog = [model('gpt-5.5', 'Shared display name', ['low', 'high']), model('gpt-5.6-terra', 'Shared display name', ['low', 'high']),+ model('gpt-renamed', 'Renamed model', ['low', 'high'])]+ expect(chooseCodexRow(parsed(CODEX_0160_SHARED_NAMES), { model: 'gpt-5.5', effort: 'low' }, catalog)).toEqual({ error: 'MODEL_UNAVAILABLE' })+ expect(chooseCodexRow(parsed(CODEX_0160_SHARED_NAMES), { model: 'gpt-renamed', effort: 'low' }, catalog)).toMatchObject({ row: { number: 1 } })+ // Two rows naming it, whatever the catalog says.+ expect(chooseCodexRow(parsed(' Select Model and Effort\n\n 1. GPT-5.5\n 2. GPT-5.5'), { model: 'gpt-5.5', effort: 'low' }, CATALOG))+ .toEqual({ error: 'MODEL_UNAVAILABLE' })+ })++ it('presses nothing for a row it cannot find exactly, or reach with one digit', () => {+ const fail = { error: 'MODEL_UNAVAILABLE' }+ expect(chooseCodexRow(parsed(CODEX_0160_ALL_MODELS), { model: 'gpt-7', effort: 'low' }, CATALOG)).toEqual(fail)+ expect(chooseCodexRow(parsed(CODEX_0160_ALL_MODELS), { model: 'us.openai.gpt-5.6-luna', effort: 'low' }, CATALOG)).toEqual(fail)+ // A name cut short with an ellipsis is not the name.+ expect(chooseCodexRow(parsed(' Select Model and Effort\n\n 1. GPT-6.1-S… Latest'), { model: 'gpt-6.1-sol', effort: 'low' }, CATALOG)).toEqual(fail)+ // Row 10 has no key: `1` would accept row 1.+ const ten = [' Select Model and Effort', '', ...Array.from({ length: 10 }, (_, i) => ` ${i + 1}. Model ${i + 1}`)].join('\n')+ expect(chooseCodexRow(parsed(ten), { model: 'gpt-ten', effort: 'auto' }, [model('gpt-ten', 'Model 10', ['low', 'high'])])).toEqual(fail)+ expect(chooseCodexRow(parsed(ten), { model: 'gpt-nine', effort: 'auto' }, [model('gpt-nine', 'Model 9', ['low', 'high'])])).toMatchObject({ row: { number: 9 } })+ expect(codexDigitPressable(0)).toBe(false)+ expect(codexDigitPressable(1.5)).toBe(false)+ // A reasoning screen is not a list to choose a model from.+ expect(chooseCodexRow(parsed(CODEX_0160_REASONING), { model: 'gpt-5.5', effort: 'low' }, CATALOG)).toEqual(fail)+ expect(chooseCodexRow(parsed(' Select Model\n Pick a quick auto mode or browse all models.\n\n 1. Auto Fast\n 2. All models\n 3. All models'),+ { model: 'gpt-5.5', effort: 'low' }, CATALOG)).toEqual(fail)+ })++ it('offers nothing but the reserve model to an account held to it', () => {+ const reserve = parsed(CODEX_0160_RESERVE)+ expect(chooseCodexRow(reserve, { model: 'gpt-6-luna', effort: 'high' }, CATALOG)).toEqual({ error: 'MODEL_UNAVAILABLE' })+ expect(chooseCodexRow(reserve, { model: 'gpt-reserve', effort: 'high' }, CATALOG)).toMatchObject({ row: { number: 1, name: 'GPT-6-Luna' }, opens: 'unknown' })+ expect(chooseCodexRow({ ...reserve, rows: [...reserve.rows, { ...reserve.rows[0], number: 2 }] }, { model: 'gpt-reserve', effort: 'high' }, CATALOG))+ .toEqual({ error: 'MODEL_UNAVAILABLE' })+ })+})diff --git a/cli/src/engines/codex/modelPicker.ts b/cli/src/engines/codex/modelPicker.tsnew file mode 100644index 000000000..b288fd942--- /dev/null+++ b/cli/src/engines/codex/modelPicker.ts@@ -0,0 +1,324 @@+/**+ * Codex's `/model` picker, read off the pane, and the one row in it that names a model.+ *+ * Harness switches a Codex agent's model by typing into this picker (lib/runtimeProfileController.ts+ * `setCodex`), so everything here is read from how Codex draws it: `chatwidget/model_popups.rs`,+ * `luna_reserve_model.rs` and `bottom_pane/list_selection_view.rs` at rust-v0.145.0 and rust-v0.160.0,+ * and their insta snapshots. The screens it was built against are in+ * `lib/__fixtures__/codexModelPickers.ts`.+ *+ * What changed between the two, and why this file exists:+ * - 0.145 drew every model row as its slug (`gpt-5.6-terra`), and the reasoning picker's title named+ * the slug too. 0.160 draws the catalog's display name (`GPT-6.1-Sol`, `GPT-5.6 Luna`) in both+ * places. The controller keyed rows by their first slug-like token, so on 0.160 every lookup missed,+ * and a name with a space did not parse at all. A row is now matched by its whole name, against the+ * slug and the display name that Codex's own `models_cache.json` gives the target.+ * - Two models can share a display name (0.160's own test `model_picker_refresh_preserves_highlight`+ * gives two the same one), and an auto preset can carry an ordinary model's name (its+ * `model_picker_refreshes_auto_models`). A name that more than one model of the list could carry+ * picks nothing: pressing the wrong row saves the wrong model as the person's default.+ * - 0.160 shows its cached models at once and refreshes the list in place when the server answers+ * (`AppEvent::FetchModels`, model_popup_state.rs), so rows can be renumbered under a reader. The+ * controller reads the list twice before it presses a digit, and checks the reasoning picker that+ * opens names the model it pressed (see [chooseCodexRow] and setCodex).+ * - An account held to the reserve model (`gpt-reserve`, "Luna Reserve") gets a picker of one row,+ * borrowed from an ordinary model, whose efforts apply to the reserve model alone.+ * - A new effort, `persistent`, labelled `Persistent`.+ */++/** The reserve model an account out of ordinary usage is held to (tui/src/model_catalog.rs). */+export const CODEX_RESERVE_MODEL = 'gpt-reserve'++/** Max and Ultra are asked for on a second screen, never in the first effort list (model_popups.rs+ * `is_advanced_reasoning_effort`). */+const ADVANCED_EFFORTS = new Set(['max', 'ultra'])++/**+ * The words Codex labels each effort with (model_popups.rs `reasoning_effort_label`), as the effort+ * Harness calls it. `Extra high` is `xhigh` on the wire.+ */+const EFFORT_LABELS = new Map<string, string>([+ ['none', 'none'], ['minimal', 'minimal'], ['low', 'low'], ['medium', 'medium'], ['high', 'high'],+ ['extra high', 'xhigh'], ['max', 'max'], ['ultra', 'ultra'], ['persistent', 'persistent'],+])++/** One model of Codex's catalog, as `models_cache.json` keeps it (protocol/src/openai_models.rs `ModelInfo`). */+export interface CodexCatalogModel {+ slug: string+ displayName: string+ /** In Codex's own picker: `visibility: "list"` (ModelPreset `show_in_picker`). */+ listed: boolean+ /** `default_reasoning_level`; Codex reads a missing one as `none`. */+ defaultEffort: string+ /** `supported_reasoning_levels[].effort`, in the catalog's order. */+ efforts: string[]+}++function record(value: unknown): Record<string, unknown> | null {+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null+}++function text(value: unknown): string {+ return typeof value === 'string' ? value : ''+}++/** The models in a parsed `models_cache.json` (models-manager/src/cache.rs `ModelsCacheEntry`). */+export function parseCodexCatalog(cache: unknown): CodexCatalogModel[] {+ const models = record(cache)?.models+ const out: CodexCatalogModel[] = []+ for (const item of Array.isArray(models) ? models : []) {+ const model = record(item)+ const slug = text(model?.slug)+ if (!model || !slug) continue+ const levels = Array.isArray(model.supported_reasoning_levels) ? model.supported_reasoning_levels : []+ out.push({+ slug,+ displayName: text(model.display_name) || slug,+ listed: model.visibility === 'list',+ defaultEffort: text(model.default_reasoning_level).toLowerCase() || 'none',+ efforts: levels.map((level) => text(record(level)?.effort).toLowerCase()).filter(Boolean),+ })+ }+ return out+}++/** The quick presets the first menu lists (model_popups.rs `is_auto_model`). */+export function isCodexAutoModel(slug: string): boolean {+ return slug.startsWith('codex-auto-')+}++/** One numbered row of a Codex picker (list_selection_view.rs `build_rows`). */+export interface CodexPickerRow {+ /** The digit that selects it and accepts it. */+ number: number+ /** The item's name, without the ` (current)` and ` (default)` Codex appends. */+ name: string+ current: boolean+ isDefault: boolean+}++export type CodexPickerKind = 'quick' | 'models' | 'reserve' | 'efforts' | 'advanced'++export interface CodexPicker {+ kind: CodexPickerKind+ /** The model an effort picker is for, as its title names it: the display name on 0.160, the slug on 0.145. */+ model: string | null+ rows: CodexPickerRow[]+}++function plain(value: string): string {+ return value.replace(/\u001b\[[0-9;:?]*[A-Za-z]/g, '').replace(/ /g, ' ')+}++/**+ * The lines under the last composer prompt. Earlier pickers and prompts stay in tmux's history, and+ * only what is below the latest prompt is on screen now. Picker rows use `›` too, but a numbered row+ * is not a prompt.+ */+function currentLines(capture: string): string[] {+ const lines = plain(capture).split('\n')+ const prompt = lines.findLastIndex((line) => {+ const marker = line.search(/[›❯]/u)+ return marker >= 0 && !/^\s*\d+\.\s/.test(line.slice(marker + 1))+ })+ return prompt >= 0 ? lines.slice(prompt) : lines+}++/** The first line of a picker's title. Titles wrap at the pane's width like the rest of the header+ * (`Paragraph` with `Wrap`), so only their first words are looked for here. */+const TITLE = /^\s*(?:Select (?:Model|Reasoning)\b|Advanced Reasoning\b)/++/**+ * A numbered row: `› ` on the highlighted one, two spaces on the rest, then `<n>. ` and the name+ * (list_selection_view.rs `build_rows`). At most a few columns in: a description that wraps is indented+ * to its own column, far right of that, and may itself start with a number.+ */+const ROW = /^(\s{0,2}[›>]?\s{0,2})(\d+)\.\s(.*)$/++function kindOf(header: string): { kind: CodexPickerKind; model: string | null } | null {+ const effort = /^Select Reasoning Level for (.+)$/.exec(header)+ if (effort) return { kind: 'efforts', model: effort[1].trim() }+ if (header.startsWith('Advanced Reasoning')) return { kind: 'advanced', model: null }+ if (header.startsWith('Select Model and Effort')) return { kind: 'models', model: null }+ if (!header.startsWith('Select Model')) return null+ if (header.includes('Pick a quick auto mode or browse all models')) return { kind: 'quick', model: null }+ if (header.includes('Other models return when ordinary usage is available again')) return { kind: 'reserve', model: null }+ return null+}++/**+ * The rows under a picker's header. A row's name runs to the first gap of two spaces, where the+ * description column starts. In a narrow pane Codex hides the descriptions and wraps a long name onto+ * the next line, indented to where the name starts; that line is part of the name. A row that shows a+ * description truncates its name with `…` instead, which then matches nothing.+ */+function pickerRows(lines: string[]): CodexPickerRow[] {+ const raw: Array<{ number: number; name: string }> = []+ let open: { at: number; column: number } | null = null+ for (const line of lines) {+ const row = ROW.exec(line)+ if (row) {+ const label = row[3].trimEnd()+ const gap = /\s{2,}\S/.exec(label)+ raw.push({ number: Number(row[2]), name: (gap ? label.slice(0, gap.index) : label).trim() })+ open = gap ? null : { at: raw.length - 1, column: row[1].length + row[2].length + 2 }+ continue+ }+ const indent = /^ */.exec(line)![0].length+ if (open && line.trim() && indent === open.column && !/\s{2,}\S/.test(line.trim())) {+ raw[open.at].name += ` ${line.trim()}`+ continue+ }+ open = null+ }+ return raw.map(({ number, name }) => {+ let current = false+ let isDefault = false+ for (let marker = /\s\((current|default)\)$/.exec(name); marker; marker = /\s\((current|default)\)$/.exec(name)) {+ if (marker[1] === 'current') current = true+ else isDefault = true+ name = name.slice(0, marker.index)+ }+ return { number, name: name.trim(), current, isDefault }+ })+}++/**+ * The Codex picker on the pane now, or null when none is. Its header is the title, any subtitle under+ * it (wrapped at the pane's width, so its lines are joined) and the blank lines before the rows.+ */+export function parseCodexPicker(capture: string): CodexPicker | null {+ const lines = currentLines(capture)+ for (let title = lines.length - 1; title >= 0; title--) {+ if (!TITLE.test(lines[title])) continue+ let end = title + 1+ while (end < lines.length && lines[end].trim() && !ROW.test(lines[end])) end+++ const header = lines.slice(title, end).map((line) => line.trim()).join(' ').replace(/\s+/g, ' ')+ const kind = kindOf(header)+ if (!kind) continue+ const rows = pickerRows(lines.slice(end))+ if (!rows.length) continue+ return { ...kind, rows }+ }+ return null+}++/** Whether two reads show the same picker: the same kind and the same rows, numbered the same. */+export function sameCodexPicker(a: CodexPicker, b: CodexPicker): boolean {+ return a.kind === b.kind && a.model === b.model && a.rows.length === b.rows.length+ && a.rows.every((row, index) => {+ const other = b.rows[index]+ return row.number === other.number && row.name === other.name+ && row.current === other.current && row.isDefault === other.isDefault+ })+}++export interface CodexEffortRows {+ /** Effort → its row's digit. */+ efforts: Map<string, number>+ /** The ` (default)` row: what an `auto` profile asks for. */+ defaultRow: number | null+ /** `More reasoning…` (`More reasoning options` before 0.160), which opens Max and Ultra. */+ advancedRow: number | null+}++/** The rows of a reasoning picker or of its Advanced Reasoning screen. */+export function codexEffortRows(picker: CodexPicker): CodexEffortRows {+ const efforts = new Map<string, number>()+ let defaultRow: number | null = null+ let advancedRow: number | null = null+ for (const row of picker.rows) {+ const name = row.name.toLowerCase()+ if (/^more reasoning\b/.test(name)) advancedRow = row.number+ else if (EFFORT_LABELS.has(name)) efforts.set(EFFORT_LABELS.get(name)!, row.number)+ if (row.isDefault) defaultRow = row.number+ }+ return { efforts, defaultRow, advancedRow }+}++/**+ * Whether a digit can press this row. A digit selects AND accepts its row, and Codex reads one digit+ * per key (list_selection_view.rs: `c.to_digit(10)`), so `1` then `0` would accept row 1; the terminal+ * layer sends single digits only. Row 10 and beyond have no key.+ */+export function codexDigitPressable(row: number): boolean {+ return Number.isInteger(row) && row >= 1 && row <= 9+}++/** What pressing a row does. */+export type CodexRowChoice =+ /** `All models`: opens the full list. */+ | { row: CodexPickerRow; opens: 'list' }+ /** A model with a choice of efforts: opens its reasoning picker. */+ | { row: CodexPickerRow; opens: 'efforts' }+ /** A model with one effort: applied at once, with this effort, and saved as the default. */+ | { row: CodexPickerRow; opens: 'applied'; effort: string }+ /** A model the catalog does not describe: one of the two above, told apart by what the pane shows next. */+ | { row: CodexPickerRow; opens: 'unknown' }+ | { error: 'MODEL_UNAVAILABLE' | 'EFFORT_UNSUPPORTED' }++function names(row: CodexPickerRow, model: { slug: string; displayName: string | null }): boolean {+ return row.name === model.displayName || row.name === model.slug+}++/**+ * The effort a row applies without opening a reasoning picker, or null when it opens one. A quick+ * preset applies its default unless it has Max or Ultra (model_popups.rs `requires_advanced_selection`);+ * a model of the full list applies its only effort, when it has one ordinary effort and no advanced one+ * (`open_reasoning_popup`, the same in 0.145 and 0.160).+ */+function appliedAtOnce(entry: CodexCatalogModel, quick: boolean): string | null {+ if (quick) {+ const advanced = ADVANCED_EFFORTS.has(entry.defaultEffort) || entry.efforts.some((effort) => ADVANCED_EFFORTS.has(effort))+ return advanced ? null : entry.defaultEffort+ }+ const choices = entry.efforts.length ? entry.efforts : [entry.defaultEffort]+ const ordinary = choices.filter((effort) => !ADVANCED_EFFORTS.has(effort))+ return ordinary.length === 1 && ordinary.length === choices.length ? ordinary[0] : null+}++/**+ * The row of a model list that a target model and effort is reached through, or why there is none.+ *+ * Fails closed: a row is chosen only when exactly one row names the target, by its slug or by its+ * catalog display name, and no other model the list could hold carries that name. Anything less+ * answers MODEL_UNAVAILABLE and nothing is pressed, because a digit applies the row it lands on and+ * saves it as the person's default model.+ */+export function chooseCodexRow(+ picker: CodexPicker,+ target: { model: string; effort: string },+ catalog: CodexCatalogModel[],+): CodexRowChoice {+ if (picker.kind === 'reserve') {+ // One row, standing for the reserve model under an ordinary model's name; nothing else can be picked+ // until ordinary usage is back (backend_banners.rs `restrict_model_picker_to_luna_reserve`).+ const [row] = picker.rows+ if (target.model !== CODEX_RESERVE_MODEL || picker.rows.length !== 1 || !codexDigitPressable(row.number)) {+ return { error: 'MODEL_UNAVAILABLE' }+ }+ return { row, opens: 'unknown' }+ }+ if (picker.kind !== 'quick' && picker.kind !== 'models') return { error: 'MODEL_UNAVAILABLE' }+ const quick = picker.kind === 'quick'+ const entry = catalog.find((model) => model.slug === target.model) ?? null+ if (quick && !isCodexAutoModel(target.model)) {+ // The quick menu lists auto presets only; every other model is behind `All models`.+ const all = picker.rows.filter((row) => row.name === 'All models')+ return all.length === 1 && codexDigitPressable(all[0].number) ? { row: all[0], opens: 'list' } : { error: 'MODEL_UNAVAILABLE' }+ }+ const wanted = { slug: target.model, displayName: entry?.displayName ?? null }+ const hits = picker.rows.filter((row) => row.name !== 'All models' && names(row, wanted))+ if (hits.length !== 1 || !codexDigitPressable(hits[0].number)) return { error: 'MODEL_UNAVAILABLE' }+ const [row] = hits+ // The other models this list could show: the listed auto presets in the quick menu, the listed+ // ordinary models in the full one.+ const rivals = catalog.filter((model) => model.slug !== target.model && model.listed && isCodexAutoModel(model.slug) === quick)+ if (rivals.some((model) => names(row, model))) return { error: 'MODEL_UNAVAILABLE' }+ if (!entry) return { row, opens: 'unknown' }+ const effort = appliedAtOnce(entry, quick)+ if (effort === null) return { row, opens: 'efforts' }+ // Applied at once with its one effort: any other effort would be the wrong one, saved as the default.+ if (target.effort !== 'auto' && target.effort !== effort) return { error: 'EFFORT_UNSUPPORTED' }+ return { row, opens: 'applied', effort }+}diff --git a/cli/src/lib/__fixtures__/codex-home-0.160/models_cache.json b/cli/src/lib/__fixtures__/codex-home-0.160/models_cache.jsonnew file mode 100644index 000000000..ac465d495--- /dev/null+++ b/cli/src/lib/__fixtures__/codex-home-0.160/models_cache.json@@ -0,0 +1,1288 @@+{+ "fetched_at": "2026-10-05T09:00:00Z",+ "etag": "\"fixture-0.160.0\"",+ "client_version": "0.160.0",+ "models": [+ {+ "slug": "gpt-6-astra",+ "prefer_websockets": true,+ "support_verbosity": true,+ "default_verbosity": "low",+ "apply_patch_tool_type": "freeform",+ "web_search_tool_type": "text_and_image",+ "input_modalities": [+ "text",+ "image"+ ],+ "supports_image_detail_original": true,+ "truncation_policy": {+ "mode": "tokens",+ "limit": 10000+ },+ "supports_parallel_tool_calls": true,+ "tool_mode": "code_mode_only",+ "multi_agent_version": "v2",+ "multi_agent_reasoning_effort": "xhigh",+ "use_responses_lite": true,+ "supports_reasoning_effort_updates": true,+ "include_skills_usage_instructions": false,+ "include_apps_usage_instructions": false,+ "include_plugin_usage_instructions": false,+ "guardian": null,+ "node_repl_auto_review_required": true,+ "node_repl_disabled": false,+ "requires_sandboxed_review": false,+ "auto_review_model_override": null,+ "model_specialty": null,+ "context_window": 272000,+ "max_context_window": 872000,+ "auto_compact_token_limit": null,+ "comp_hash": "3000",+ "default_reasoning_summary": "none",+ "display_name": "GPT-6-Astra",+ "description": "Frontier intelligence for the most demanding work.",+ "default_reasoning_level": "low",+ "supported_reasoning_levels": [+ {+ "effort": "low",+ "description": "Fast responses with lighter reasoning"+ },+ {+ "effort": "medium",+ "description": "Balances speed and reasoning depth for everyday tasks"+ },+ {+ "effort": "high",+ "description": "Greater reasoning depth for complex problems"+ },+ {+ "effort": "xhigh",+ "description": "Extra high reasoning depth for complex problems"+ },+ {+ "effort": "max",+ "description": "Maximum reasoning depth for the hardest problems"+ },+ {+ "effort": "ultra",+ "description": "Maximum reasoning with automatic task delegation"+ }+ ],+ "shell_type": "shell_command",+ "visibility": "list",+ "minimal_client_version": "0.153.0",+ "supported_in_api": true,+ "availability_nux": null,+ "upgrade": null,+ "priority": 2,+ "model_messages": {+ "instructions_template": "You are Codex. (Trimmed for the fixture: the bundled instructions run to 60 KB per model.)"+ },+ "experimental_supported_tools": [+ "send_user_message_async",+ "clock"+ ],+ "available_in_plans": [+ "business",+ "edu",+ "edu_plus",+ "edu_pro",+ "education",+ "ent26",+ "enterprise",+ "enterprise_cbp_automation",+ "enterprise_cbp_trial",+ "enterprise_cbp_usage_based",+ "finserv",+ "free",+ "free_workspace",+ "go",+ "hc",+ "k12",+ "plus",+ "pro",+ "prolite",+ "promax",+ "quorum",+ "sci",+ "self_serve_business_prolite",+ "self_serve_business_usage_based",+ "team"+ ],+ "supports_search_tool": true,+ "supports_experimental_context": false,+ "default_service_tier": null,+ "service_tiers": [+ {+ "id": "priority",+ "name": "Fast",+ "description": "2x speed, increased usage"+ }+ ],+ "additional_speed_tiers": [+ "fast"+ ],+ "supports_reasoning_summary_parameter": true,+ "supports_reasoning_summaries": true+ },+ {+ "slug": "gpt-6.1-sol",+ "prefer_websockets": true,+ "support_verbosity": true,+ "default_verbosity": "low",+ "apply_patch_tool_type": "freeform",+ "web_search_tool_type": "text_and_image",+ "input_modalities": [+ "text",+ "image"+ ],+ "supports_image_detail_original": true,+ "truncation_policy": {+ "mode": "tokens",+ "limit": 10000+ },+ "supports_parallel_tool_calls": true,+ "tool_mode": "code_mode_only",+ "multi_agent_version": "v2",+ "multi_agent_reasoning_effort": "xhigh",+ "use_responses_lite": true,+ "include_skills_usage_instructions": false,+ "include_apps_usage_instructions": false,+ "include_plugin_usage_instructions": false,+ "guardian": null,+ "node_repl_auto_review_required": true,+ "node_repl_disabled": false,+ "requires_sandboxed_review": false,+ "auto_review_model_override": null,+ "model_specialty": null,+ "context_window": 272000,+ "max_context_window": 872000,+ "auto_compact_token_limit": null,+ "comp_hash": "3000",+ "default_reasoning_summary": "none",+ "display_name": "GPT-6.1-Sol",+ "description": "Latest workhorse model for coding and everyday work.",+ "default_reasoning_level": "low",+ "supported_reasoning_levels": [+ {+ "effort": "low",+ "description": "Fast responses with lighter reasoning"+ },+ {+ "effort": "medium",+ "description": "Balances speed and reasoning depth for everyday tasks"+ },+ {+ "effort": "high",+ "description": "Greater reasoning depth for complex problems"+ },+ {+ "effort": "xhigh",+ "description": "Extra high reasoning depth for complex problems"+ },+ {+ "effort": "max",+ "description": "Maximum reasoning depth for the hardest problems"+ },+ {+ "effort": "ultra",+ "description": "Maximum reasoning with automatic task delegation"+ }+ ],+ "shell_type": "shell_command",+ "visibility": "list",+ "minimal_client_version": "0.153.0",+ "supported_in_api": true,+ "availability_nux": {+ "message": "Maximize usage with GPT-6.1 Sol. Try it on complex work for near-Astra performance at a lower cost."+ },+ "upgrade": null,+ "priority": 1,+ "model_messages": {+ "instructions_template": "You are Codex. (Trimmed for the fixture: the bundled instructions run to 60 KB per model.)"+ },+ "experimental_supported_tools": [+ "send_user_message_async",+ "clock"+ ],+ "available_in_plans": [+ "business",+ "edu",+ "edu_plus",+ "edu_pro",+ "education",+ "ent26",+ "enterprise",+ "enterprise_cbp_automation",+ "enterprise_cbp_trial",+ "enterprise_cbp_usage_based",+ "finserv",+ "free",+ "free_workspace",+ "go",+ "hc",+ "k12",+ "law",+ "plus",+ "pro",+ "prolite",+ "promax",+ "quorum",+ "sci",+ "self_serve_business_prolite",+ "self_serve_business_usage_based",+ "team"+ ],+ "supports_search_tool": true,+ "supports_experimental_context": false,+ "default_service_tier": null,+ "service_tiers": [+ {+ "id": "priority",+ "name": "Fast",+ "description": "2x speed, increased usage"+ }+ ],+ "additional_speed_tiers": [+ "fast"+ ],+ "supports_reasoning_summary_parameter": true,+ "supports_reasoning_summaries": true,+ "supports_reasoning_effort_updates": true+ },+ {+ "slug": "gpt-6-sol",+ "prefer_websockets": true,+ "support_verbosity": true,+ "default_verbosity": "low",+ "apply_patch_tool_type": "freeform",+ "web_search_tool_type": "text_and_image",+ "input_modalities": [+ "text",+ "image"+ ],+ "supports_image_detail_original": true,+ "truncation_policy": {+ "mode": "tokens",+ "limit": 10000+ },+ "supports_parallel_tool_calls": true,+ "tool_mode": "code_mode_only",+ "multi_agent_version": "v2",+ "multi_agent_reasoning_effort": null,+ "use_responses_lite": true,+ "include_skills_usage_instructions": false,+ "include_apps_usage_instructions": false,+ "include_plugin_usage_instructions": false,+ "guardian": null,+ "node_repl_auto_review_required": true,+ "node_repl_disabled": false,+ "requires_sandboxed_review": false,+ "auto_review_model_override": null,+ "model_specialty": null,+ "context_window": 272000,+ "max_context_window": 872000,+ "auto_compact_token_limit": null,+ "comp_hash": "3000",+ "default_reasoning_summary": "none",+ "display_name": "GPT-6-Sol",+ "description": "Previous generation workhorse model.",+ "default_reasoning_level": "medium",+ "supported_reasoning_levels": [+ {+ "effort": "low",+ "description": "Fast responses with lighter reasoning"+ },+ {+ "effort": "medium",+ "description": "Balances speed and reasoning depth for everyday tasks"+ },+ {+ "effort": "high",+ "description": "Greater reasoning depth for complex problems"+ },+ {+ "effort": "xhigh",+ "description": "Extra high reasoning depth for complex problems"+ },+ {+ "effort": "max",+ "description": "Maximum reasoning depth for the hardest problems"+ },+ {+ "effort": "ultra",+ "description": "Maximum reasoning with automatic task delegation"+ }+ ],+ "shell_type": "shell_command",+ "visibility": "list",+ "minimal_client_version": "0.155.0",+ "supported_in_api": true,+ "availability_nux": null,+ "upgrade": null,+ "priority": 3,+ "model_messages": {+ "instructions_template": "You are Codex. (Trimmed for the fixture: the bundled instructions run to 60 KB per model.)"+ },+ "experimental_supported_tools": [+ "send_user_message_async",+ "clock"+ ],+ "available_in_plans": [+ "business",+ "edu",+ "edu_plus",+ "edu_pro",+ "education",+ "ent26",+ "enterprise",+ "enterprise_cbp_automation",+ "enterprise_cbp_trial",+ "enterprise_cbp_usage_based",+ "finserv",+ "free",+ "free_workspace",+ "go",+ "hc",+ "k12",+ "plus",+ "pro",+ "prolite",+ "quorum",+ "sci",+ "self_serve_business_prolite",+ "self_serve_business_usage_based",+ "team"+ ],+ "supports_search_tool": true,+ "supports_experimental_context": false,+ "default_service_tier": "priority",+ "service_tiers": [+ {+ "id": "priority",+ "name": "Fast",+ "description": "1.5x speed"+ }+ ],+ "additional_speed_tiers": [+ "fast"+ ],+ "supports_reasoning_summary_parameter": true,+ "supports_reasoning_summaries": true+ },+ {+ "slug": "gpt-6-luna",+ "prefer_websockets": true,+ "support_verbosity": true,+ "default_verbosity": "low",+ "apply_patch_tool_type": "freeform",+ "web_search_tool_type": "text_and_image",+ "input_modalities": [+ "text",+ "image"+ ],+ "supports_image_detail_original": true,+ "truncation_policy": {+ "mode": "tokens",+ "limit": 10000+ },+ "supports_parallel_tool_calls": true,+ "tool_mode": "code_mode_only",+ "multi_agent_version": "v2",+ "multi_agent_reasoning_effort": null,+ "use_responses_lite": true,+ "include_skills_usage_instructions": false,+ "include_apps_usage_instructions": false,+ "include_plugin_usage_instructions": false,+ "guardian": null,+ "node_repl_auto_review_required": false,+ "node_repl_disabled": false,+ "requires_sandboxed_review": false,+ "auto_review_model_override": null,+ "model_specialty": null,+ "context_window": 272000,+ "max_context_window": 872000,+ "auto_compact_token_limit": null,+ "comp_hash": "3000",+ "default_reasoning_summary": "none",+ "display_name": "GPT-6-Luna",+ "description": "Fast and affordable model for easier tasks.",+ "default_reasoning_level": "medium",+ "supported_reasoning_levels": [+ {+ "effort": "low",+ "description": "Fast responses with lighter reasoning"+ },+ {+ "effort": "medium",+ "description": "Balances speed and reasoning depth for everyday tasks"+ },+ {+ "effort": "high",+ "description": "Greater reasoning depth for complex problems"+ },+ {+ "effort": "xhigh",+ "description": "Extra high reasoning depth for complex problems"+ },+ {+ "effort": "max",+ "description": "Maximum reasoning depth for the hardest problems"+ }+ ],+ "shell_type": "shell_command",+ "visibility": "list",+ "minimal_client_version": "0.155.0",+ "supported_in_api": true,+ "availability_nux": null,+ "upgrade": null,+ "priority": 4,+ "model_messages": {+ "instructions_template": "You are Codex. (Trimmed for the fixture: the bundled instructions run to 60 KB per model.)"+ },+ "experimental_supported_tools": [+ "send_user_message_async",+ "clock"+ ],+ "available_in_plans": [+ "business",+ "edu",+ "edu_plus",+ "edu_pro",+ "education",+ "ent26",+ "enterprise",+ "enterprise_cbp_automation",+ "enterprise_cbp_trial",+ "enterprise_cbp_usage_based",+ "finserv",+ "free",+ "free_workspace",+ "go",+ "hc",+ "k12",+ "plus",+ "pro",+ "prolite",+ "quorum",+ "sci",+ "self_serve_business_prolite",+ "self_serve_business_usage_based",+ "team"+ ],+ "supports_search_tool": true,+ "supports_experimental_context": false,+ "default_service_tier": "priority",+ "service_tiers": [+ {+ "id": "priority",+ "name": "Fast",+ "description": "1.5x speed"+ }+ ],+ "additional_speed_tiers": [+ "fast"+ ],+ "supports_reasoning_summary_parameter": true,+ "supports_reasoning_summaries": true+ },+ {+ "slug": "gpt-5.6-sol",+ "prefer_websockets": true,+ "support_verbosity": true,+ "default_verbosity": "low",+ "apply_patch_tool_type": "freeform",+ "web_search_tool_type": "text_and_image",+ "input_modalities": [+ "text",+ "image"+ ],+ "supports_image_detail_original": true,+ "truncation_policy": {+ "mode": "tokens",+ "limit": 10000+ },+ "supports_parallel_tool_calls": true,+ "tool_mode": "code_mode_only",+ "multi_agent_version": "v2",+ "multi_agent_reasoning_effort": null,+ "use_responses_lite": true,+ "supports_reasoning_effort_updates": false,+ "include_skills_usage_instructions": false,+ "include_apps_usage_instructions": true,+ "include_plugin_usage_instructions": true,+ "guardian": null,+ "node_repl_auto_review_required": false,+ "node_repl_disabled": false,+ "requires_sandboxed_review": false,+ "auto_review_model_override": null,+ "model_specialty": null,+ "context_window": 272000,+ "max_context_window": 872000,+ "auto_compact_token_limit": null,+ "comp_hash": "3000",+ "default_reasoning_summary": "none",+ "display_name": "GPT-5.6-Sol",+ "description": "Older generation workhorse model.",+ "default_reasoning_level": "low",+ "supported_reasoning_levels": [+ {+ "effort": "low",+ "description": "Fast responses with lighter reasoning"+ },+ {+ "effort": "medium",+ "description": "Balances speed and reasoning depth for everyday tasks"+ },+ {+ "effort": "high",+ "description": "Greater reasoning depth for complex problems"+ },+ {+ "effort": "xhigh",+ "description": "Extra high reasoning depth for complex problems"+ },+ {+ "effort": "max",+ "description": "Maximum reasoning depth for the hardest problems"+ },+ {+ "effort": "ultra",+ "description": "Maximum reasoning with automatic task delegation"+ }+ ],+ "shell_type": "shell_command",+ "visibility": "list",+ "minimal_client_version": "0.144.0",+ "supported_in_api": true,+ "availability_nux": null,+ "upgrade": {+ "model": "gpt-6-sol",+ "migration_markdown": "Meet GPT-6 Sol\n\nOur latest Sol is more intelligent and more efficient so your usage limits go further. This model is a great daily driver for complex tasks, especially coding.\n",+ "retirement_at": null+ },+ "priority": 5,+ "model_messages": {+ "instructions_template": "You are Codex. (Trimmed for the fixture: the bundled instructions run to 60 KB per model.)"+ },+ "experimental_supported_tools": [],+ "available_in_plans": [+ "business",+ "edu",+ "edu_plus",+ "edu_pro",+ "education",+ "ent26",+ "enterprise",+ "enterprise_cbp_automation",+ "enterprise_cbp_trial",+ "enterprise_cbp_usage_based",+ "finserv",+ "free",+ "free_workspace",+ "go",+ "hc",+ "k12",+ "plus",+ "pro",+ "prolite",+ "promax",+ "quorum",+ "sci",+ "self_serve_business_prolite",+ "self_serve_business_usage_based",+ "team"+ ],+ "supports_search_tool": true,+ "supports_experimental_context": false,+ "default_service_tier": null,+ "service_tiers": [+ {+ "id": "priority",+ "name": "Fast",+ "description": "1.5x speed, increased usage"+ }+ ],+ "additional_speed_tiers": [+ "fast"+ ],+ "supports_reasoning_summary_parameter": true,+ "supports_reasoning_summaries": true+ },+ {+ "slug": "gpt-5.6-terra",+ "prefer_websockets": true,+ "support_verbosity": true,+ "default_verbosity": "low",+ "apply_patch_tool_type": "freeform",+ "web_search_tool_type": "text_and_image",+ "input_modalities": [+ "text",+ "image"+ ],+ "supports_image_detail_original": true,+ "truncation_policy": {+ "mode": "tokens",+ "limit": 10000+ },+ "supports_parallel_tool_calls": true,+ "tool_mode": "code_mode_only",+ "multi_agent_version": "v2",+ "multi_agent_reasoning_effort": null,+ "use_responses_lite": true,+ "supports_reasoning_effort_updates": false,+ "include_skills_usage_instructions": false,+ "include_apps_usage_instructions": true,+ "include_plugin_usage_instructions": true,+ "guardian": null,+ "node_repl_auto_review_required": false,+ "node_repl_disabled": false,+ "requires_sandboxed_review": false,+ "auto_review_model_override": null,+ "model_specialty": null,+ "context_window": 272000,+ "max_context_window": 872000,+ "auto_compact_token_limit": null,+ "comp_hash": "3000",+ "default_reasoning_summary": "none",+ "display_name": "GPT-5.6-Terra",+ "description": "Older balanced model for straightforward work.",+ "default_reasoning_level": "medium",+ "supported_reasoning_levels": [+ {+ "effort": "low",+ "description": "Fast responses with lighter reasoning"+ },+ {+ "effort": "medium",+ "description": "Balances speed and reasoning depth for everyday tasks"+ },+ {+ "effort": "high",+ "description": "Greater reasoning depth for complex problems"+ },+ {+ "effort": "xhigh",+ "description": "Extra high reasoning depth for complex problems"+ },+ {+ "effort": "max",+ "description": "Maximum reasoning depth for the hardest problems"+ },+ {+ "effort": "ultra",+ "description": "Maximum reasoning with automatic task delegation"+ }+ ],+ "shell_type": "shell_command",+ "visibility": "list",+ "minimal_client_version": "0.144.0",+ "supported_in_api": true,+ "availability_nux": null,+ "upgrade": {+ "model": "gpt-6-sol",+ "migration_markdown": "Meet GPT-6 Sol\n\nOur latest Sol is more intelligent and more efficient so your usage limits go further. This model is a great daily driver for complex tasks, especially coding.\n",+ "retirement_at": null+ },+ "priority": 8,+ "model_messages": {+ "instructions_template": "You are Codex. (Trimmed for the fixture: the bundled instructions run to 60 KB per model.)"+ },+ "experimental_supported_tools": [],+ "available_in_plans": [+ "business",+ "edu",+ "edu_plus",+ "edu_pro",+ "education",+ "ent26",+ "enterprise",+ "enterprise_cbp_automation",+ "enterprise_cbp_trial",+ "enterprise_cbp_usage_based",+ "finserv",+ "free",+ "free_workspace",+ "go",+ "hc",+ "k12",+ "plus",+ "pro",+ "prolite",+ "promax",+ "quorum",+ "sci",+ "self_serve_business_prolite",+ "self_serve_business_usage_based",+ "team"+ ],+ "supports_search_tool": true,+ "supports_experimental_context": false,+ "default_service_tier": null,+ "service_tiers": [+ {+ "id": "priority",+ "name": "Fast",+ "description": "1.5x speed, increased usage"+ }+ ],+ "additional_speed_tiers": [+ "fast"+ ],+ "supports_reasoning_summary_parameter": true,+ "supports_reasoning_summaries": true+ },+ {+ "slug": "gpt-5.6-luna",+ "prefer_websockets": true,+ "support_verbosity": true,+ "default_verbosity": "low",+ "apply_patch_tool_type": "freeform",+ "web_search_tool_type": "text_and_image",+ "input_modalities": [+ "text",+ "image"+ ],+ "supports_image_detail_original": true,+ "truncation_policy": {+ "mode": "tokens",+ "limit": 10000+ },+ "supports_parallel_tool_calls": true,+ "tool_mode": "code_mode_only",+ "multi_agent_version": "v1",+ "multi_agent_reasoning_effort": null,+ "use_responses_lite": true,+ "supports_reasoning_effort_updates": false,+ "include_skills_usage_instructions": false,+ "include_apps_usage_instructions": true,+ "include_plugin_usage_instructions": true,+ "guardian": null,+ "node_repl_auto_review_required": false,+ "node_repl_disabled": false,+ "requires_sandboxed_review": false,+ "auto_review_model_override": null,+ "model_specialty": null,+ "context_window": 272000,+ "max_context_window": 872000,+ "auto_compact_token_limit": null,+ "comp_hash": "3000",+ "default_reasoning_summary": "none",+ "display_name": "GPT-5.6-Luna",+ "description": "Older fast and efficient model.",+ "default_reasoning_level": "medium",+ "supported_reasoning_levels": [+ {+ "effort": "low",+ "description": "Fast responses with lighter reasoning"+ },+ {+ "effort": "medium",+ "description": "Balances speed and reasoning depth for everyday tasks"+ },+ {+ "effort": "high",+ "description": "Greater reasoning depth for complex problems"+ },+ {+ "effort": "xhigh",+ "description": "Extra high reasoning depth for complex problems"+ },+ {+ "effort": "max",+ "description": "Maximum reasoning depth for the hardest problems"+ }+ ],+ "shell_type": "shell_command",+ "visibility": "list",+ "minimal_client_version": "0.144.0",+ "supported_in_api": true,+ "availability_nux": null,+ "upgrade": {+ "model": "gpt-6-luna",+ "migration_markdown": "Meet GPT-6 Luna\n\nOur latest Luna is significantly more efficient, so your usage limits go even further. Reach for it for any job that doesn't require frontier intelligence.\n",+ "retirement_at": null+ },+ "priority": 9,+ "model_messages": {+ "instructions_template": "You are Codex. (Trimmed for the fixture: the bundled instructions run to 60 KB per model.)"+ },+ "experimental_supported_tools": [],+ "available_in_plans": [+ "business",+ "edu",+ "edu_plus",+ "edu_pro",+ "education",+ "ent26",+ "enterprise",+ "enterprise_cbp_automation",+ "enterprise_cbp_trial",+ "enterprise_cbp_usage_based",+ "finserv",+ "free",+ "free_workspace",+ "go",+ "hc",+ "k12",+ "plus",+ "pro",+ "prolite",+ "promax",+ "quorum",+ "sci",+ "self_serve_business_prolite",+ "self_serve_business_usage_based",+ "team"+ ],+ "supports_search_tool": true,+ "supports_experimental_context": false,+ "default_service_tier": null,+ "service_tiers": [+ {+ "id": "priority",+ "name": "Fast",+ "description": "1.5x speed, increased usage"+ }+ ],+ "additional_speed_tiers": [+ "fast"+ ],+ "supports_reasoning_summary_parameter": true,+ "supports_reasoning_summaries": true+ },+ {+ "slug": "gpt-daybreak-blue-latest",+ "prefer_websockets": true,+ "support_verbosity": true,+ "default_verbosity": "low",+ "apply_patch_tool_type": "freeform",+ "web_search_tool_type": "text_and_image",+ "input_modalities": [+ "text",+ "image"+ ],+ "supports_image_detail_original": true,+ "truncation_policy": {+ "mode": "tokens",+ "limit": 10000+ },+ "supports_parallel_tool_calls": true,+ "tool_mode": "code_mode_only",+ "multi_agent_version": "v2",+ "use_responses_lite": true,+ "include_skills_usage_instructions": false,+ "include_apps_usage_instructions": true,+ "include_plugin_usage_instructions": true,+ "node_repl_auto_review_required": false,+ "node_repl_disabled": false,+ "auto_review_model_override": null,+ "model_specialty": "cyber",+ "context_window": 272000,+ "max_context_window": 872000,+ "auto_compact_token_limit": null,+ "comp_hash": "3000",+ "default_reasoning_summary": "none",+ "display_name": "Daybreak Blue",+ "description": "Latest frontier agentic coding model for broad defensive cybersecurity work.",+ "default_reasoning_level": "low",+ "supported_reasoning_levels": [+ {+ "effort": "low",+ "description": "Fast responses with lighter reasoning"+ },+ {+ "effort": "medium",+ "description": "Balances speed and reasoning depth for everyday tasks"+ },+ {+ "effort": "high",+ "description": "Greater reasoning depth for complex problems"+ },+ {+ "effort": "xhigh",+ "description": "Extra high reasoning depth for complex problems"+ },+ {+ "effort": "max",+ "description": "Maximum reasoning depth for the hardest problems"+ },+ {+ "effort": "ultra",+ "description": "Maximum reasoning with automatic task delegation"+ }+ ],+ "shell_type": "shell_command",+ "visibility": "hide",+ "minimal_client_version": "0.142.2",+ "supported_in_api": true,+ "availability_nux": null,+ "upgrade": null,+ "priority": 11,+ "model_messages": {+ "instructions_template": "You are Codex. (Trimmed for the fixture: the bundled instructions run to 60 KB per model.)"+ },+ "experimental_supported_tools": [],+ "available_in_plans": [+ "business",+ "edu",+ "edu_plus",+ "edu_pro",+ "education",+ "enterprise",+ "enterprise_cbp_automation",+ "enterprise_cbp_usage_based",+ "finserv",+ "free",+ "free_workspace",+ "go",+ "hc",+ "k12",+ "plus",+ "pro",+ "prolite",+ "quorum",+ "sci",+ "self_serve_business_prolite",+ "self_serve_business_usage_based",+ "team"+ ],+ "supports_search_tool": true,+ "default_service_tier": null,+ "service_tiers": [],+ "additional_speed_tiers": [],+ "supports_reasoning_summary_parameter": true,+ "supports_reasoning_summaries": true+ },+ {+ "slug": "gpt-daybreak-red-latest",+ "prefer_websockets": true,+ "support_verbosity": true,+ "default_verbosity": "high",+ "apply_patch_tool_type": "freeform",+ "web_search_tool_type": "text_and_image",+ "input_modalities": [+ "text",+ "image"+ ],+ "supports_image_detail_original": true,+ "truncation_policy": {+ "mode": "tokens",+ "limit": 10000+ },+ "supports_parallel_tool_calls": true,+ "tool_mode": "code_mode_only",+ "multi_agent_version": "v2",+ "use_responses_lite": true,+ "include_skills_usage_instructions": false,+ "include_apps_usage_instructions": false,+ "include_plugin_usage_instructions": false,+ "node_repl_auto_review_required": false,+ "node_repl_disabled": false,+ "auto_review_model_override": null,+ "model_specialty": "cyber",+ "context_window": 372000,+ "max_context_window": 372000,+ "auto_compact_token_limit": null,+ "comp_hash": "3000",+ "default_reasoning_summary": "none",+ "display_name": "Daybreak Red",+ "description": "Cyber-permissive variant of our latest frontier agentic coding model for advanced, authorized cybersecurity research.",+ "default_reasoning_level": "medium",+ "supported_reasoning_levels": [+ {+ "effort": "low",+ "description": "Fast responses with lighter reasoning"+ },+ {+ "effort": "medium",+ "description": "Balances speed and reasoning depth for everyday tasks"+ },+ {+ "effort": "high",+ "description": "Greater reasoning depth for complex problems"+ },+ {+ "effort": "xhigh",+ "description": "Extra high reasoning depth for complex problems"+ },+ {+ "effort": "max",+ "description": "Maximum reasoning depth for the hardest problems"+ },+ {+ "effort": "ultra",+ "description": "Maximum reasoning with automatic task delegation"+ }+ ],+ "shell_type": "shell_command",+ "visibility": "hide",+ "minimal_client_version": "0.142.2",+ "supported_in_api": true,+ "availability_nux": null,+ "upgrade": null,+ "priority": 12,+ "model_messages": {+ "instructions_template": "You are Codex. (Trimmed for the fixture: the bundled instructions run to 60 KB per model.)"+ },+ "experimental_supported_tools": [],+ "available_in_plans": [+ "business",+ "edu",+ "edu_plus",+ "edu_pro",+ "education",+ "enterprise",+ "enterprise_cbp_automation",+ "enterprise_cbp_usage_based",+ "finserv",+ "free",+ "free_workspace",+ "go",+ "hc",+ "k12",+ "plus",+ "pro",+ "prolite",+ "quorum",+ "sci",+ "self_serve_business_prolite",+ "self_serve_business_usage_based",+ "team"+ ],+ "supports_search_tool": true,+ "default_service_tier": null,+ "service_tiers": [],+ "additional_speed_tiers": [],+ "supports_reasoning_summary_parameter": true,+ "supports_reasoning_summaries": true+ },+ {+ "slug": "gpt-5.5",+ "prefer_websockets": true,+ "support_verbosity": true,+ "default_verbosity": "low",+ "apply_patch_tool_type": "freeform",+ "web_search_tool_type": "text_and_image",+ "input_modalities": [+ "text",+ "image"+ ],+ "supports_image_detail_original": true,+ "truncation_policy": {+ "mode": "tokens",+ "limit": 10000+ },+ "supports_parallel_tool_calls": true,+ "tool_mode": null,+ "multi_agent_version": null,+ "multi_agent_reasoning_effort": null,+ "use_responses_lite": false,+ "supports_reasoning_effort_updates": false,+ "include_skills_usage_instructions": true,+ "include_apps_usage_instructions": true,+ "include_plugin_usage_instructions": true,+ "guardian": null,+ "node_repl_auto_review_required": false,+ "node_repl_disabled": false,+ "requires_sandboxed_review": false,+ "auto_review_model_override": null,+ "model_specialty": null,+ "context_window": 272000,+ "max_context_window": 272000,+ "auto_compact_token_limit": null,+ "comp_hash": "2911",+ "default_reasoning_summary": "none",+ "display_name": "GPT-5.5",+ "description": "Legacy coding model.",+ "default_reasoning_level": "medium",+ "supported_reasoning_levels": [+ {+ "effort": "low",+ "description": "Fast responses with lighter reasoning"+ },+ {+ "effort": "medium",+ "description": "Balances speed and reasoning depth for everyday tasks"+ },+ {+ "effort": "high",+ "description": "Greater reasoning depth for complex problems"+ },+ {+ "effort": "xhigh",+ "description": "Extra high reasoning depth for complex problems"+ }+ ],+ "shell_type": "shell_command",+ "visibility": "list",+ "minimal_client_version": "0.124.0",+ "supported_in_api": true,+ "availability_nux": null,+ "upgrade": {+ "model": "gpt-6-sol",+ "migration_markdown": "Meet GPT-6 Sol\n\nOur latest Sol is more intelligent and more efficient so your usage limits go further. This model is a great daily driver for complex tasks, especially coding.\n",+ "retirement_at": null+ },+ "priority": 13,+ "model_messages": {+ "instructions_template": "You are Codex. (Trimmed for the fixture: the bundled instructions run to 60 KB per model.)"+ },+ "experimental_supported_tools": [],+ "available_in_plans": [+ "business",+ "edu",+ "edu_plus",+ "edu_pro",+ "education",+ "ent26",+ "enterprise",+ "enterprise_cbp_automation",+ "enterprise_cbp_trial",+ "enterprise_cbp_usage_based",+ "finserv",+ "free",+ "free_workspace",+ "go",+ "hc",+ "k12",+ "plus",+ "pro",+ "prolite",+ "promax",+ "quorum",+ "sci",+ "self_serve_business_prolite",+ "self_serve_business_usage_based",+ "team"+ ],+ "supports_search_tool": true,+ "supports_experimental_context": false,+ "default_service_tier": null,+ "service_tiers": [+ {+ "id": "priority",+ "name": "Fast",+ "description": "1.5x speed, increased usage"+ }+ ],+ "additional_speed_tiers": [+ "fast"+ ],+ "supports_reasoning_summary_parameter": true,+ "supports_reasoning_summaries": true+ },+ {+ "slug": "codex-auto-review",+ "prefer_websockets": true,+ "support_verbosity": true,+ "default_verbosity": "low",+ "apply_patch_tool_type": "freeform",+ "web_search_tool_type": "text_and_image",+ "input_modalities": [+ "text",+ "image"+ ],+ "supports_image_detail_original": true,+ "truncation_policy": {+ "mode": "tokens",+ "limit": 10000+ },+ "supports_parallel_tool_calls": true,+ "tool_mode": "code_mode_only",+ "multi_agent_version": "v1",+ "multi_agent_reasoning_effort": null,+ "use_responses_lite": true,+ "supports_reasoning_effort_updates": false,+ "include_skills_usage_instructions": false,+ "include_apps_usage_instructions": false,+ "include_plugin_usage_instructions": false,+ "guardian": null,+ "node_repl_auto_review_required": false,+ "node_repl_disabled": false,+ "requires_sandboxed_review": false,+ "auto_review_model_override": null,+ "model_specialty": null,+ "context_window": 272000,+ "max_context_window": 872000,+ "auto_compact_token_limit": null,+ "comp_hash": "3000",+ "default_reasoning_summary": "none",+ "display_name": "Codex Auto Review",+ "description": "Automatic approval review model for Codex.",+ "default_reasoning_level": "medium",+ "supported_reasoning_levels": [+ {+ "effort": "low",+ "description": "Fast responses with lighter reasoning"+ },+ {+ "effort": "medium",+ "description": "Balances speed and reasoning depth for everyday tasks"+ },+ {+ "effort": "high",+ "description": "Greater reasoning depth for complex problems"+ },+ {+ "effort": "xhigh",+ "description": "Extra high reasoning depth for complex problems"+ },+ {+ "effort": "max",+ "description": "Maximum reasoning depth for the hardest problems"+ }+ ],+ "shell_type": "shell_command",+ "visibility": "hide",+ "minimal_client_version": "0.98.0",+ "supported_in_api": true,+ "availability_nux": null,+ "upgrade": null,+ "priority": 43,+ "model_messages": {+ "instructions_template": "You are Codex. (Trimmed for the fixture: the bundled instructions run to 60 KB per model.)"+ },+ "experimental_supported_tools": [],+ "available_in_plans": [+ "business",+ "edu",+ "edu_plus",+ "edu_pro",+ "education",+ "ent26",+ "enterprise",+ "enterprise_cbp_automation",+ "enterprise_cbp_trial",+ "enterprise_cbp_usage_based",+ "finserv",+ "go",+ "hc",+ "plus",+ "pro",+ "prolite",+ "promax",+ "quorum",+ "sci",+ "self_serve_business_prolite",+ "self_serve_business_usage_based",+ "team"+ ],+ "supports_search_tool": true,+ "supports_experimental_context": false,+ "default_service_tier": null,+ "service_tiers": [+ {+ "id": "priority",+ "name": "Fast",+ "description": "1.5x speed, increased usage"+ }+ ],+ "additional_speed_tiers": [+ "fast"+ ],+ "supports_reasoning_summary_parameter": true,+ "supports_reasoning_summaries": true+ }+ ]+}diff --git a/cli/src/lib/__fixtures__/codexModelPickers.ts b/cli/src/lib/__fixtures__/codexModelPickers.tsnew file mode 100644index 000000000..a441060f6--- /dev/null+++ b/cli/src/lib/__fixtures__/codexModelPickers.ts@@ -0,0 +1,242 @@+/**+ * Codex's `/model` pickers as 0.145 and 0.160 draw them. Built from Codex's own code, read only, not+ * captured (no Codex was run): the insta snapshots and render code at rust-v0.145.0 and rust-v0.160.0+ * (`tui/src/chatwidget/snapshots/`, `chatwidget/model_popups.rs`, `luna_reserve_model.rs`,+ * `bottom_pane/list_selection_view.rs`). The text and layout are theirs; the styling is the one+ * `selection_style` and the dim hints give it. Each screen names the snapshot or the code it is from.+ *+ * `codex-home-0.160/models_cache.json` beside this file is the catalog 0.160 ships+ * (`codex-rs/models-manager/models.json`) in the cache file's own shape (`ModelsCacheEntry`), with each+ * model's 60 KB of instructions cut short. The rows of CODEX_0160_ALL_MODELS are its listed models.+ */++const SELECTED = '\u001b[36m'+const DIM = '\u001b[2m'+const BOLD = '\u001b[1m'+const RESET = '\u001b[0m'++/** The composer and the conversation above a picker, as the pane holds them in its history. */+const ABOVE = [+ '\u001b[1m›\u001b[0m Write the release notes',+ '',+ '• Release notes are in NOTES.md.',+ '',+]++const picker = (lines: string[]): string => [...ABOVE, ...lines].join('\n')++/** 0.160, the account's full list: rows are the catalog's display names (snapshot `model_selection_popup`). */+export const CODEX_0160_ALL_MODELS = picker([+ ` ${BOLD}Select Model and Effort${RESET}`,+ '',+ '',+ ` 1. GPT-6.1-Sol (default) ${DIM}Latest workhorse model for coding and everyday work.${RESET}`,+ ` 2. GPT-6-Astra ${DIM}Frontier intelligence for the most demanding work.${RESET}`,+ ` 3. GPT-6-Sol ${DIM}Previous generation workhorse model.${RESET}`,+ ` 4. GPT-6-Luna ${DIM}Fast and affordable model for easier tasks.${RESET}`,+ ` 5. GPT-5.6-Sol ${DIM}Older generation workhorse model.${RESET}`,+ ` 6. GPT-5.6-Terra ${DIM}Older balanced model for straightforward work.${RESET}`,+ ` 7. GPT-5.6-Luna ${DIM}Older fast and efficient model.${RESET}`,+ `${SELECTED}› 8. GPT-5.5 (current) Legacy coding model.${RESET}`,+ '',+ ` enter${DIM} select · ${RESET}esc${DIM} back${RESET}`,+])++/**+ * The same list after the server's answer reached the open picker with a new model first: every row+ * below it moved down one (model_popup_state.rs `refresh_open_model_picker`, which keeps the highlight+ * on the same slug, not on the same row).+ */+export const CODEX_0160_ALL_MODELS_REFRESHED = picker([+ ` ${BOLD}Select Model and Effort${RESET}`,+ '',+ '',+ ` 1. GPT-6.2-Sol (default) ${DIM}Newest workhorse model for coding and everyday work.${RESET}`,+ ` 2. GPT-6.1-Sol ${DIM}Latest workhorse model for coding and everyday work.${RESET}`,+ ` 3. GPT-6-Astra ${DIM}Frontier intelligence for the most demanding work.${RESET}`,+ ` 4. GPT-6-Sol ${DIM}Previous generation workhorse model.${RESET}`,+ ` 5. GPT-6-Luna ${DIM}Fast and affordable model for easier tasks.${RESET}`,+ ` 6. GPT-5.6-Sol ${DIM}Older generation workhorse model.${RESET}`,+ ` 7. GPT-5.6-Terra ${DIM}Older balanced model for straightforward work.${RESET}`,+ ` 8. GPT-5.6-Luna ${DIM}Older fast and efficient model.${RESET}`,+ `${SELECTED}› 9. GPT-5.5 (current) Legacy coding model.${RESET}`,+ '',+ ` enter${DIM} select · ${RESET}esc${DIM} back${RESET}`,+])++/**+ * 0.160's quick menu over a catalog with an auto preset, and a display name with a space in it (snapshot+ * `custom_model_display_name_quick_picker`; its test gives `us.openai.gpt-5.6-luna` the name `GPT-5.6+ * Luna` and `codex-auto-fast` the name `Auto Fast`).+ */+export const CODEX_0160_QUICK_MENU = picker([+ ` ${BOLD}Select Model${RESET}`,+ ` ${DIM}Pick a quick auto mode or browse all models.${RESET}`,+ '',+ '',+ ` 1. Auto Fast ${DIM}Custom provider model${RESET}`,+ `${SELECTED}› 2. All models (current) Choose a specific model and reasoning level (current:${RESET}`,+ `${SELECTED} GPT-5.6 Luna)${RESET}`,+ '',+ ` enter${DIM} select · ${RESET}esc${DIM} back${RESET}`,+])++/** Its `All models` (snapshot `custom_model_display_name_all_models`). */+export const CODEX_0160_ALL_MODELS_SPACED = picker([+ ` ${BOLD}Select Model and Effort${RESET}`,+ '',+ '',+ `${SELECTED}› 1. GPT-5.6 Luna (current) Custom provider model${RESET}`,+ '',+ ` enter${DIM} select · ${RESET}esc${DIM} back${RESET}`,+])++/** Its reasoning picker: the title names the display name, and the default row is also the current one+ * (snapshot `custom_model_display_name_reasoning`). */+export const CODEX_0160_REASONING_SPACED = picker([+ ` ${BOLD}Select Reasoning Level for GPT-5.6 Luna${RESET}`,+ '',+ '',+ ` 1. Low ${DIM}Quick answers${RESET}`,+ `${SELECTED}› 2. High (default) (current) Deeper reasoning${RESET}`,+ '',+ ` enter${DIM} default · ${RESET}s${DIM} session · ${RESET}esc${DIM} back${RESET}`,+])++/** A reasoning picker with 0.160's new `Persistent` row (snapshot `model_reasoning_selection_popup`). */+export const CODEX_0160_REASONING = picker([+ ` ${BOLD}Select Reasoning Level for GPT-5.5${RESET}`,+ '',+ '',+ ` 1. Low ${DIM}Fast responses with lighter reasoning${RESET}`,+ ` 2. Medium (default) ${DIM}Balances speed and reasoning depth for everyday tasks${RESET}`,+ `${SELECTED}› 3. High (current) Greater reasoning depth for complex problems${RESET}`,+ ` 4. Extra high ${DIM}Extra high reasoning depth for complex problems${RESET}`,+ ` 5. Persistent ${DIM}Continue working until put to sleep${RESET}`,+ ` 6. More reasoning… ${DIM}Max and Ultra consume usage limits faster${RESET}`,+ '',+ ` enter${DIM} default · ${RESET}s${DIM} session · ${RESET}esc${DIM} back${RESET}`,+])++/** Max and Ultra, a screen of their own (snapshot `model_advanced_reasoning_selection_popup`). */+export const CODEX_0160_ADVANCED = picker([+ ` ${BOLD}Advanced Reasoning${RESET}`,+ ` \u001b[36m⚠ Consumes usage limits faster${RESET}`,+ '',+ '',+ ` 1. Max ${DIM}For difficult problems when quality matters more than${RESET}`,+ ` ${DIM}speed · higher usage${RESET}`,+ `${SELECTED}› 2. Ultra (current) For demanding work using multiple agents · highest usage${RESET}`,+ '',+ ` enter${DIM} apply · ${RESET}s${DIM} session · ${RESET}esc${DIM} back${RESET}`,+])++/**+ * The quick menu once a refresh brought an auto preset in, its name copied from `gpt-5.5`'s: the first+ * row is the preset, not the model (snapshot `model_picker_refreshes_auto_models`).+ */+export const CODEX_0160_QUICK_MENU_SHARED_NAME = picker([+ ` ${BOLD}Select Model${RESET}`,+ ` ${DIM}Pick a quick auto mode or browse all models.${RESET}`,+ '',+ '',+ ` 1. GPT-5.5 ${DIM}Auto model${RESET}`,+ `${SELECTED}› 2. All models (current) Choose a specific model and reasoning level (current:${RESET}`,+ `${SELECTED} GPT-5.5)${RESET}`,+ '',+ ` enter${DIM} select · ${RESET}esc${DIM} back${RESET}`,+])++/** Two models under one display name, one of them renamed by a refresh (snapshot+ * `model_picker_refresh_preserves_highlight`). */+export const CODEX_0160_SHARED_NAMES = picker([+ ` ${BOLD}Select Model and Effort${RESET}`,+ '',+ '',+ `${SELECTED}› 1. Renamed model Older balanced model for straightforward${RESET}`,+ `${SELECTED} work.${RESET}`,+ ` 2. Shared display name (current) ${DIM}Legacy coding model.${RESET}`,+ '',+ ` enter${DIM} select · ${RESET}esc${DIM} back${RESET}`,+])++/**+ * An account held to the reserve model: one row, the ordinary model's name and description standing for+ * `gpt-reserve`, always current (luna_reserve_model.rs `open_luna_reserve_model_popup`; no snapshot, its+ * header is `model_menu_header` and its footer `picker_hint_line_for_keymap`).+ */+export const CODEX_0160_RESERVE = picker([+ ` ${BOLD}Select Model${RESET}`,+ ` ${DIM}Other models return when ordinary usage is available again.${RESET}`,+ '',+ '',+ `${SELECTED}› 1. GPT-6-Luna (current) Fast and affordable model for easier tasks.${RESET}`,+ '',+ ` enter${DIM} select · ${RESET}esc${DIM} back${RESET}`,+])++/** Its reasoning picker: titled with the ordinary model's name, applied to the reserve model. */+export const CODEX_0160_RESERVE_REASONING = picker([+ ` ${BOLD}Select Reasoning Level for GPT-6-Luna${RESET}`,+ '',+ '',+ ` 1. Low ${DIM}Fast responses with lighter reasoning${RESET}`,+ `${SELECTED}› 2. Medium (default) Balances speed and reasoning depth for everyday tasks${RESET}`,+ ` 3. High ${DIM}Greater reasoning depth for complex problems${RESET}`,+ ` 4. Extra high ${DIM}Extra high reasoning depth for complex problems${RESET}`,+ ` 5. More reasoning… ${DIM}Max consumes usage limits faster${RESET}`,+ '',+ ` enter${DIM} default · ${RESET}s${DIM} session · ${RESET}esc${DIM} back${RESET}`,+])++/**+ * The full list in a pane 22 columns wide: the header wraps, the descriptions are hidden (the picker's+ * `HideWhenNarrow`, under 24 columns for them), and a name too long for its line wraps under where it+ * starts (snapshot `shared_menu_presentation_at_wide_and_narrow_sizes`, 40x16, for the same layout).+ */+export const CODEX_0160_ALL_MODELS_NARROW = picker([+ ` ${BOLD}Select Model and${RESET}`,+ ` ${BOLD}Effort${RESET}`,+ '',+ '',+ ' 1. GPT-6.1-Sol',+ ' (default)',+ ' 2. GPT-6-Astra',+ ' 3. GPT-6-Sol',+ `${SELECTED}› 4. GPT-5.6 Luna${RESET}`,+ `${SELECTED} (current)${RESET}`,+ '',+ ` enter${DIM} select · ${RESET}esc${DIM} back${RESET}`,+])++/** 0.145's full list: slugs, and a subtitle (its snapshot `model_selection_popup`). */+export const CODEX_0145_ALL_MODELS = picker([+ ` ${BOLD}Select Model and Effort${RESET}`,+ ` ${DIM}Access legacy models by running codex -m <model_name> or in your config.toml${RESET}`,+ '',+ ` 1. gpt-5.6-sol (default) ${DIM}Latest frontier agentic coding model.${RESET}`,+ ` 2. gpt-5.6-terra ${DIM}Balanced agentic coding model for everyday work.${RESET}`,+ ` 3. gpt-5.6-luna ${DIM}Fast and affordable agentic coding model.${RESET}`,+ ` 4. gpt-5.5 ${DIM}Frontier model for complex coding, research, and${RESET}`,+ ` ${DIM}real-world work.${RESET}`,+ `${SELECTED}› 5. gpt-5.2 (current) Optimized for professional work and long-running${RESET}`,+ `${SELECTED} agents.${RESET}`,+ '',+ ` ${DIM}Press enter to confirm or esc to go back${RESET}`,+])++/** 0.145's reasoning picker: the title names the slug (its snapshot `model_reasoning_selection_popup`). */+export const CODEX_0145_REASONING = picker([+ ` ${BOLD}Select Reasoning Level for gpt-5.4${RESET}`,+ '',+ ` 1. Low ${DIM}Fast responses with lighter reasoning${RESET}`,+ ` 2. Medium (default) ${DIM}Balances speed and reasoning depth for everyday tasks${RESET}`,+ `${SELECTED}› 3. High (current) Greater reasoning depth for complex problems${RESET}`,+ ` 4. Extra high ${DIM}Extra high reasoning depth for complex problems${RESET}`,+ ` 5. More reasoning… ${DIM}Max and Ultra consume usage limits faster${RESET}`,+ '',+ ` ${DIM}Press enter to confirm or esc to go back${RESET}`,+])++/** The composer back after a choice was applied. */+export const CODEX_0160_COMPOSER = [...ABOVE, `${BOLD}›${RESET} ${DIM}Ask Codex to do anything${RESET}`, '', ' gpt-6.1-sol low · /tmp/project'].join('\n')diff --git a/cli/src/lib/runtimeProfile.spec.ts b/cli/src/lib/runtimeProfile.spec.tsindex cae2823a9..c63dc5067 100644--- a/cli/src/lib/runtimeProfile.spec.ts+++ b/cli/src/lib/runtimeProfile.spec.ts@@ -55,7 +55,26 @@ describe('RuntimeProfileManager', () => {})})- it('limits Codex Max and Ultra to GPT-5.6 models', () => {+ it('takes Codex Max and Ultra where its catalog lists them', async () => {+ // 0.160's catalog lists them for the GPT-6 models the old slug list left out, and leaves Ultra off GPT-6-Luna.+ expect(codexEffortAllowed('gpt-6.1-sol', 'ultra', ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'])).toBe(true)+ expect(codexEffortAllowed('gpt-6-luna', 'ultra', ['low', 'medium', 'high', 'xhigh', 'max'])).toBe(false)+ // The catalog outranks the slug list both ways.+ expect(codexEffortAllowed('gpt-5.6-sol', 'max', ['low', 'high'])).toBe(false)+ expect(codexEffortAllowed('gpt-5.4', 'xhigh', [])).toBe(true)+ expect(codexEffortAllowed('gpt-6.1-sol', 'turbo', ['turbo'])).toBe(false)++ const manager = new RuntimeProfileManager()+ const value = { ...session('codex'), codexHome: join(import.meta.dirname, '__fixtures__', 'codex-home-0.160') }+ manager.hydrate(value, [JSON.stringify({ type: 'turn_context', payload: { model: 'gpt-6.1-sol', reasoning_effort: 'ultra' } })])+ const offered = (await manager.modelsForSession(value)).map((option) => parseRuntimeProfile(option.id))+ .map((profile) => `${profile?.model}@${profile?.effort}`)+ expect(offered).toEqual(expect.arrayContaining(['gpt-6.1-sol@max', 'gpt-6.1-sol@ultra', 'gpt-6-astra@ultra', 'gpt-6-luna@max']))+ expect(offered).not.toContain('gpt-6-luna@ultra')+ expect(offered).not.toContain('gpt-5.5@max')+ })++ it('limits Codex Max and Ultra to GPT-5.6 models when there is no catalog to ask', () => {expect(codexEffortAllowed('gpt-5.6-sol', 'max')).toBe(true)expect(codexEffortAllowed('gpt-5.6-terra', 'ultra')).toBe(true)expect(codexEffortAllowed('codex-auto-review', 'ultra')).toBe(true)@@ -153,13 +172,56 @@ describe('RuntimeProfileManager', () => {await expect(manager.modelsForSession(native)).resolves.not.toEqual([])})- it('supports both captured Codex picker generations', () => {+ it('switches Codex from 0.144 upward, not only the two releases first driven by hand', () => {+ // The gate allowed exactly 0.144 and 0.145, so a Codex kept up to date (0.160) could not be switched.+ const value = session('codex')+ for (const version of ['0.144.0', '0.144.5', '0.145.0', '0.146.0', '0.160.0', '0.161.2', '1.0.0']) {+ value.cliVersion = version+ expect(supportsNativeRuntimeControl(value), version).toBe(true)+ }+ for (const version of ['0.143.9', '0.99.0', null, 'not a version']) {+ value.cliVersion = version+ expect(supportsNativeRuntimeControl(value), String(version)).toBe(false)+ }+ })++ it('knows Codex 0.160 Persistent effort, from the rollout, the pane and the catalog', async () => {+ const manager = new RuntimeProfileManager()const value = session('codex')- expect(supportsNativeRuntimeControl(value)).toBe(true)- value.cliVersion = '0.145.0'- expect(supportsNativeRuntimeControl(value)).toBe(true)- value.cliVersion = '0.146.0'- expect(supportsNativeRuntimeControl(value)).toBe(false)+ manager.hydrate(value, [])+ manager.ingest(value, JSON.stringify({+ type: 'event_msg',+ payload: { type: 'thread_settings_applied', thread_settings: { model: 'gpt-5.5', reasoning_effort: 'persistent' } },+ }))+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'gpt-5.5', effort: 'persistent' })+ expect(codexEffortAllowed('gpt-5.5', 'persistent')).toBe(true)++ manager.ingestPane(value, '› \ngpt-6-luna high ·', true)+ manager.ingestPane(value, '› \ngpt-6-luna persistent · Context 100% left', true)+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'gpt-6-luna', effort: 'persistent' })++ const home = await mkdtemp(join(tmpdir(), 'codex-home-'))+ cleanup.push(home)+ await writeFile(join(home, 'models_cache.json'), JSON.stringify({ models: [{+ slug: 'gpt-5.5', display_name: 'GPT-5.5', visibility: 'list', default_reasoning_level: 'medium',+ supported_reasoning_levels: [{ effort: 'medium' }, { effort: 'persistent' }],+ }] }))+ const options = await manager.modelsForSession({ ...value, codexHome: home })+ expect(options).toContainEqual({ id: encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-5.5', effort: 'persistent' }), displayName: 'GPT-5.5 / Persistent' })+ expect(await manager.codexCatalog({ ...value, codexHome: home })).toEqual([+ { slug: 'gpt-5.5', displayName: 'GPT-5.5', listed: true, defaultEffort: 'medium', efforts: ['medium', 'persistent'] },+ ])+ })++ it('reads no Codex catalog where there is none, or none that parses', async () => {+ const manager = new RuntimeProfileManager()+ const home = await mkdtemp(join(tmpdir(), 'codex-home-'))+ cleanup.push(home)+ const value = { ...session('codex'), codexHome: home }+ await expect(manager.codexCatalog(value)).resolves.toEqual([])+ await writeFile(join(home, 'models_cache.json'), 'null')+ await expect(manager.codexCatalog(value)).resolves.toEqual([])+ await expect(manager.modelsForSession(value)).resolves.toEqual([])})it('surfaces a Cursor model from the transcript even before any effort is known', () => {diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.tsindex 6e7e2928e..9af5defd3 100644--- a/cli/src/lib/runtimeProfile.ts+++ b/cli/src/lib/runtimeProfile.ts@@ -46,6 +46,7 @@ import {} from '../engines/pi/runtimeProfile.js'import { parseGrokFooterProfile } from '../engines/grok/runtimeProfile.js'import { parseAgyFooterProfile } from '../engines/agy/runtimeProfile.js'+import { parseCodexCatalog, type CodexCatalogModel } from '../engines/codex/modelPicker.js'export interface RuntimeProfile {id: string@@ -131,7 +132,12 @@ interface CodexCache {}const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes|muse|amp|kilo|grok|agy|copilot):([^@]+)@([a-z0-9_-]+)$/i-const CODEX_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'])+/**+ * `persistent` came with Codex 0.160 (`ReasoningEffort::Persistent`, "Continue working until put to+ * sleep"): without it here a thread on it read as no effort at all, so its chip showed nothing and a+ * switch to it could never be confirmed.+ */+const CODEX_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra', 'persistent'])const CLAUDE_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])const CURSOR_EFFORTS = new Set(['auto', 'none', 'low', 'medium', 'high', 'xhigh', 'max'])const EFFORTS = new Set([@@ -170,6 +176,8 @@ const BASIC_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as constconst CLAUDE_ALIASES = ['default', 'opus', 'fable', 'sonnet', 'haiku'] as constconst CHANGE_DEBOUNCE_MS = 120const CLAUDE_ULTRACODE_MIN_VERSION: [number, number, number] = [2, 1, 209]+/** The first Codex whose `/model` picker was driven by hand (see supportsNativeRuntimeControl). */+const CODEX_CONTROL_MIN_VERSION: [number, number, number] = [0, 144, 0]const CURSOR_CONTROLLED_BUILD = '2026.07.20-8cc9c0b'const CURSOR_CATALOG_TTL_MS = 5 * 60_000/** Shared TTL for the stdout catalogs (devin, pi) — same rationale as the cursor one. */@@ -264,14 +272,27 @@ export function supportsNativeRuntimeControl(session: RegisteredSession): boolea// would otherwise still drive a CLI the owner took off the switchable list.if (session.engine === 'claude') return versionAtLeast(session.cliVersion, [2, 1, 153])if (session.engine !== 'codex') return false- if (session.engine !== 'codex') return false- const version = parseVersion(session.cliVersion)- return !!version && version[0] === 0 && (version[1] === 144 || version[1] === 145)+ // Open upward, like Claude Code's. It allowed exactly 0.144 and 0.145, the two releases whose picker+ // was driven by hand, so every Codex kept up to date (0.160 on 2026-10-05) could not be switched at+ // all. The controller now reads the picker by what it says rather than by release: rows by slug or+ // catalog display name, the rows read again before a digit, and nothing pressed when the row is not+ // found exactly (engines/codex/modelPicker.ts).+ return versionAtLeast(session.cliVersion, CODEX_CONTROL_MIN_VERSION)}-export function codexEffortAllowed(model: string, effort: string): boolean {+/**+ * Whether Codex can be asked for this effort on this model. `listed` is what Codex's own catalog+ * (`models_cache.json`) gives the model, or null when the catalog cannot be read or does not have it.+ *+ * Max and Ultra follow the catalog: Codex offers them in its picker exactly where the catalog lists them+ * (model_popups.rs), and 0.160's lists them for gpt-6-astra, gpt-6.1-sol and gpt-6-sol, which the slug+ * list below left out of reach (owner, 2026-10-05). The slug list is what was known from 0.145, kept for+ * when there is no catalog to ask.+ */+export function codexEffortAllowed(model: string, effort: string, listed: readonly string[] | null = null): boolean {if (!CODEX_EFFORTS.has(effort)) return falseif (effort !== 'max' && effort !== 'ultra') return true+ if (listed) return listed.includes(effort)return /^gpt-5\.6(?:-|$)/i.test(model) || model.toLowerCase() === 'codex-auto-review'}@@ -641,7 +662,7 @@ export async function readStartupProfile(session: RegisteredSession, pane: strin}if (session.engine === 'codex') {if (!/\bOpenAI Codex\b/.test(pane) || !/^\s*›(?!\s*\d+\.)[^\n]*$/mu.test(pane)) return null- const matches = [...pane.matchAll(/\b(gpt-[a-z0-9][a-z0-9._-]*)\s+(low|medium|high|xhigh|max|ultra|default)\s*[·│]/gi)]+ const matches = [...pane.matchAll(/\b(gpt-[a-z0-9][a-z0-9._-]*)\s+(low|medium|high|xhigh|max|ultra|persistent|default)\s*[·│]/gi)]const match = matches.at(-1)if (!match) return nullreturn encodeRuntimeProfile({ sessionId: session.agentId, engine: 'codex', model: match[1].toLowerCase(),@@ -866,7 +887,7 @@ export class RuntimeProfileManager {paneText = stripAnsi(paneText)const currentUi = currentPaneUi(paneText)if (session.engine === 'codex') {- const matches = [...paneText.matchAll(/\b(gpt-[a-z0-9][a-z0-9._-]*)\s+(low|medium|high|xhigh|max|ultra|default)\s*[·│]/gi)]+ const matches = [...paneText.matchAll(/\b(gpt-[a-z0-9][a-z0-9._-]*)\s+(low|medium|high|xhigh|max|ultra|persistent|default)\s*[·│]/gi)]const latest = matches[matches.length - 1]if (latest) {state.model = latest[1].toLowerCase()@@ -1339,30 +1360,48 @@ export class RuntimeProfileManager {return output}+ /**+ * The catalog Codex builds its own `/model` picker from, read fresh: what the controller matches the+ * picker's rows against (engines/codex/modelPicker.ts). Empty when there is no cache to read.+ */+ async codexCatalog(session: RegisteredSession): Promise<CodexCatalogModel[]> {+ return parseCodexCatalog(await this.readCodexCache(session))+ }++ /**+ * `models_cache.json` in this agent's own CODEX_HOME profile, when it has one other than the default+ * (see RegisteredSession.codexHome) — otherwise the picker would show the default profile's cached+ * models for an agent that is not actually running on it.+ */+ private async readCodexCache(session: RegisteredSession): Promise<CodexCache> {+ try {+ const cache: unknown = JSON.parse(await readFile(join(session.codexHome || env.CODEX_HOME, 'models_cache.json'), 'utf8'))+ return record(cache) ?? {}+ } catch {+ return {}+ }+ }+private async codexModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {const output: RuntimeModelOption[] = []const seen = new Set<string>()- let cache: CodexCache = {}- // This agent's own CODEX_HOME profile, when it has one other than the default (see- // RegisteredSession.codexHome) — otherwise the picker would show the default profile's cached- // models for an agent that is not actually running on it.- try { cache = JSON.parse(await readFile(join(session.codexHome || env.CODEX_HOME, 'models_cache.json'), 'utf8')) as CodexCache } catch { /* current state fallback below */ }+ const cache = await this.readCodexCache(session)+ const catalog = parseCodexCatalog(cache)for (const item of Array.isArray(cache.models) ? cache.models : []) {const model = text(item.slug)if (!model || item.visibility === 'hide') continueconst label = text(item.display_name) || runtimeModelLabel(model)addOption(output, seen, session, model, 'auto', label)- for (const level of Array.isArray(item.supported_reasoning_levels) ? item.supported_reasoning_levels : []) {- const effort = text(level.effort).toLowerCase()- if (CODEX_EFFORTS.has(effort) && effort !== 'auto' && codexEffortAllowed(model, effort)) {- addOption(output, seen, session, model, effort, label)- }+ const listed = catalog.find((entry) => entry.slug === model)?.efforts ?? []+ for (const effort of listed) {+ if (effort !== 'auto' && codexEffortAllowed(model, effort, listed)) addOption(output, seen, session, model, effort, label)}}const state = this.states.get(session.sessionId)if (state?.model) {addOption(output, seen, session, state.model, 'auto')- if (state.effort && codexEffortAllowed(state.model, state.effort)) {+ const listed = catalog.find((entry) => entry.slug === state.model)?.efforts ?? null+ if (state.effort && codexEffortAllowed(state.model, state.effort, listed)) {addOption(output, seen, session, state.model, state.effort)}}diff --git a/cli/src/lib/runtimeProfileController.spec.ts b/cli/src/lib/runtimeProfileController.spec.tsindex 91f1a2393..2514fe03a 100644--- a/cli/src/lib/runtimeProfileController.spec.ts+++ b/cli/src/lib/runtimeProfileController.spec.ts@@ -1,12 +1,12 @@-import { describe, expect, it, vi } from 'vitest'+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { codexEffortRows, parseCodexPicker } from '../engines/codex/modelPicker.js'import type { RegisteredSession } from './registry.js'import { encodeRuntimeProfile, parseRuntimeProfile, RuntimeProfileManager } from './runtimeProfile.js'import {inspectRuntimePane,- parseCodexAdvancedRows,- parseCodexEffortRows,- parseCodexModelMenuRows,- parseCodexModelRows,parseCursorModelPicker,parseCursorParameterRows,paneModal,@@ -17,6 +17,26 @@ import {CODEX_BROWSING_FULLSCREEN, CODEX_BROWSING_SCROLLBACK, CODEX_PROMPT,} from './__fixtures__/rewindPickers.js'import { CLAUDE_HISTORY_SEARCH, CLAUDE_TRUST_PROMPT, CODEX_TRANSCRIPT_FIND, CODEX_TRANSCRIPT_OVERLAY, CODEX_UPDATE_PROMPT } from './__fixtures__/takeoverScreens.js'+import {+ CODEX_0160_ADVANCED, CODEX_0160_ALL_MODELS, CODEX_0160_ALL_MODELS_REFRESHED, CODEX_0160_ALL_MODELS_SPACED, CODEX_0160_COMPOSER, CODEX_0160_QUICK_MENU,+ CODEX_0160_REASONING, CODEX_0160_REASONING_SPACED, CODEX_0160_RESERVE, CODEX_0160_RESERVE_REASONING,+} from './__fixtures__/codexModelPickers.js'++/**+ * Codex's own catalog, where the controller reads the display names its picker shows. Every Codex+ * session here points at it (or at a throwaway home): with no `codexHome`, the manager would read the+ * developer's real ~/.codex.+ */+const CODEX_HOME_0160 = join(import.meta.dirname, '__fixtures__', 'codex-home-0.160')+const homes: string[] = []+afterEach(async () => { await Promise.all(homes.splice(0).map((home) => rm(home, { recursive: true, force: true }))) })+/** A throwaway CODEX_HOME whose models_cache.json lists these models. */+async function codexHome(models: Array<Record<string, unknown>>): Promise<string> {+ const home = await mkdtemp(join(tmpdir(), 'codex-home-'))+ homes.push(home)+ await writeFile(join(home, 'models_cache.json'), JSON.stringify({ fetched_at: '2026-10-05T09:00:00Z', client_version: '0.160.0', models }))+ return home+}// The id inside a `runtime-v1:` string is the AGENT id ('h1' here) — a client only ever echoes back an id// the catalog minted, and the catalog is agent-scoped. `setProfile` is still addressed with either id.@@ -29,6 +49,7 @@ function session(engine: 'claude' | 'codex' | 'cursor' | 'opencode'): Registeredruntimes: [{ backend: 'tmux', paneId: '%1' }], primaryRuntimeKey: 'tmux\u0000%1',cliVersion: engine === 'codex' ? '0.144.5' : engine === 'cursor' ? '2026.07.20-8cc9c0b' : engine === 'opencode' ? '1.18.31' : '2.1.212', processIdentity: null,registeredAt: 1, touchedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,+ ...(engine === 'codex' ? { codexHome: CODEX_HOME_0160 } : {}),}}@@ -343,26 +364,23 @@ describe('runtime pane parsing', () => {})it('parses the version-gated Codex picker rows', () => {- const menu = parseCodexModelMenuRows([+ const menu = parseCodexPicker(['Select Model','Pick a quick auto mode or browse all models.',' 1. codex-auto-review Balanced agentic coding model for everyday work.','› 2. All models (current) Choose a specific model and reasoning level',].join('\n'))- expect(menu?.quickModels.get('codex-auto-review')).toBe('1')- expect(menu?.allModelsRow).toBe('2')-- const models = parseCodexModelRows('Select Model and Effort\n 1. gpt-5.6-sol (default) Latest frontier model.\n 2. gpt-5.6-terra\n› 3. gpt-5.6-luna (current) Fast model.')- expect(models?.get('gpt-5.6-sol')).toBe('1')- expect(models?.get('gpt-5.6-terra')).toBe('2')- expect(models?.get('gpt-5.6-luna')).toBe('3')- const efforts = parseCodexEffortRows('Select Reasoning Level for gpt-5.6-sol\n 1. Low\n 2. High (default)\n 3. Extra high\n 4. More reasoning options')- expect(efforts?.efforts.get('xhigh')).toBe('3')- expect(efforts?.defaultRow).toBe('2')- expect(efforts?.advancedRow).toBe('4')- const advanced = parseCodexAdvancedRows('Advanced Reasoning\n› 1. Max (current) Higher usage\n 2. Ultra Highest usage')- expect(advanced?.get('max')).toBe('1')- expect(advanced?.get('ultra')).toBe('2')+ expect(menu).toMatchObject({ kind: 'quick', rows: [{ number: 1, name: 'codex-auto-review' }, { number: 2, name: 'All models', current: true }] })++ const models = parseCodexPicker('Select Model and Effort\n 1. gpt-5.6-sol (default) Latest frontier model.\n 2. gpt-5.6-terra\n› 3. gpt-5.6-luna (current) Fast model.')+ expect(models?.rows.map((row) => [row.number, row.name])).toEqual([[1, 'gpt-5.6-sol'], [2, 'gpt-5.6-terra'], [3, 'gpt-5.6-luna']])+ const efforts = codexEffortRows(parseCodexPicker('Select Reasoning Level for gpt-5.6-sol\n 1. Low\n 2. High (default)\n 3. Extra high\n 4. More reasoning options')!)+ expect(efforts.efforts.get('xhigh')).toBe(3)+ expect(efforts.defaultRow).toBe(2)+ expect(efforts.advancedRow).toBe(4)+ const advanced = codexEffortRows(parseCodexPicker('Advanced Reasoning\n› 1. Max (current) Higher usage\n 2. Ultra Highest usage')!)+ expect(advanced.efforts.get('max')).toBe(1)+ expect(advanced.efforts.get('ultra')).toBe(2)})it('treats both Codex model picker generations as active dialogs', () => {@@ -378,7 +396,7 @@ describe('runtime pane parsing', () => {it('does not reuse picker rows left before a newer composer prompt', () => {const stale = 'Select Model and Effort\n 1. gpt-old\n› 1. gpt-old\n› \ngpt-current high ·'- expect(parseCodexModelRows(stale)).toBeNull()+ expect(parseCodexPicker(stale)).toBeNull()})it('parses the gated Cursor picker and parameter rows by meaning', () => {@@ -699,6 +717,268 @@ describe('RuntimeProfileController', () => {expect(manager.selectedModel(value)).toBe(target)})+ describe('Codex 0.160', () => {+ /** Codex's settings record once a choice is applied: what the switch is confirmed by. */+ const applied = (manager: RuntimeProfileManager, value: RegisteredSession, model: string, effort: string) =>+ manager.ingest(value, JSON.stringify({+ type: 'event_msg',+ payload: { type: 'thread_settings_applied', thread_settings: { model, reasoning_effort: effort, collaboration_mode: { mode: 'default' } } },+ }))+ const reasoningFor = (name: string) => CODEX_0160_REASONING.replace('Select Reasoning Level for GPT-5.5', `Select Reasoning Level for ${name}`)+ /** A 0.160 agent on `model` at `effort`, as its rollout says. */+ const agent = (model: string, effort: string, home = CODEX_HOME_0160) => {+ const value = { ...session('codex'), cliVersion: '0.160.0', codexHome: home }+ const manager = new RuntimeProfileManager()+ manager.hydrate(value, [JSON.stringify({ type: 'turn_context', payload: { model, reasoning_effort: effort } })])+ return { value, manager }+ }+ /**+ * A pane that answers as Codex's picker does: `/model` opens `opened`, and `press` says where each+ * key leads from the screen on show. The digits pressed are kept, in order.+ */+ const drive = (manager: RuntimeProfileManager, value: RegisteredSession, opened: string,+ press: (screen: string, key: string) => string, read: (screen: string) => string = (screen) => screen, ownEscape = false) => {+ let screen = CODEX_0160_COMPOSER+ const keys: string[] = []+ const controller = new RuntimeProfileController({+ manager,+ getSession: () => value,+ validateRuntime: async () => true,+ capture: async () => read(screen),+ sendText: async (_pane, text) => { if (text === '/model') screen = opened; return true },+ sendLiteral: async () => true,+ sendKey: async (_pane, key) => {+ keys.push(key)+ screen = key === 'Escape' && !ownEscape ? CODEX_0160_COMPOSER : press(read(screen), key)+ return true+ },+ acquireInput: () => () => undefined,+ })+ return { controller, keys }+ }++ it('switches the effort by the display-named rows, to the new Persistent', async () => {+ const models = JSON.parse(await readFile(join(CODEX_HOME_0160, 'models_cache.json'), 'utf8')).models+ // As Codex's own test gives gpt-5.5 the effort (popups_and_settings.rs `model_reasoning_selection_popup_snapshot`).+ for (const entry of models) {+ if (entry.slug === 'gpt-5.5') entry.supported_reasoning_levels.push({ effort: 'persistent', description: 'Continue working until put to sleep' })+ }+ const { value, manager } = agent('gpt-5.5', 'high', await codexHome(models))+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-5.5', effort: 'persistent' })+ // The catalog offers it: Harness lists persistent now that it knows the word.+ expect((await manager.modelsForSession(value)).map((option) => option.id)).toContain(target)+ const { controller, keys } = drive(manager, value, CODEX_0160_ALL_MODELS, (screen, key) => {+ if (screen === CODEX_0160_ALL_MODELS && key === '8') return CODEX_0160_REASONING+ if (screen === CODEX_0160_REASONING && key === '5') { applied(manager, value, 'gpt-5.5', 'persistent'); return CODEX_0160_COMPOSER }+ throw new Error(`unexpected ${key}`)+ })++ await controller.setProfile('s1', target)++ expect(keys).toEqual(['8', '5'])+ expect(manager.selectedModel(value)).toBe(target)+ })++ it('reaches a model whose name has a space through All models', async () => {+ const home = await codexHome([+ { slug: 'codex-auto-fast', display_name: 'Auto Fast', visibility: 'list', default_reasoning_level: 'high',+ supported_reasoning_levels: [{ effort: 'low' }, { effort: 'high' }] },+ { slug: 'us.openai.gpt-5.6-luna', display_name: 'GPT-5.6 Luna', visibility: 'list', default_reasoning_level: 'high',+ supported_reasoning_levels: [{ effort: 'low' }, { effort: 'high' }] },+ ])+ const { value, manager } = agent('us.openai.gpt-5.6-luna', 'high', home)+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'us.openai.gpt-5.6-luna', effort: 'low' })+ const { controller, keys } = drive(manager, value, CODEX_0160_QUICK_MENU, (screen, key) => {+ if (screen === CODEX_0160_QUICK_MENU && key === '2') return CODEX_0160_ALL_MODELS_SPACED+ if (screen === CODEX_0160_ALL_MODELS_SPACED && key === '1') return CODEX_0160_REASONING_SPACED+ if (screen === CODEX_0160_REASONING_SPACED && key === '1') { applied(manager, value, 'us.openai.gpt-5.6-luna', 'low'); return CODEX_0160_COMPOSER }+ throw new Error(`unexpected ${key}`)+ })++ await controller.setProfile('s1', target)++ expect(keys).toEqual(['2', '1', '1'])+ expect(manager.selectedModel(value)).toBe(target)+ })++ it('applies a quick preset with one press, and presses nothing for an effort it cannot give', async () => {+ const home = await codexHome([+ { slug: 'codex-auto-fast', display_name: 'Auto Fast', visibility: 'list', default_reasoning_level: 'high',+ supported_reasoning_levels: [{ effort: 'low' }, { effort: 'high' }] },+ { slug: 'us.openai.gpt-5.6-luna', display_name: 'GPT-5.6 Luna', visibility: 'list', default_reasoning_level: 'high',+ supported_reasoning_levels: [{ effort: 'low' }, { effort: 'high' }] },+ ])+ const { value, manager } = agent('us.openai.gpt-5.6-luna', 'high', home)+ const run = drive(manager, value, CODEX_0160_QUICK_MENU, (screen, key) => {+ // The row applies its default effort at once and saves it (model_popups.rs `model_selection_actions`).+ if (screen === CODEX_0160_QUICK_MENU && key === '1') { applied(manager, value, 'codex-auto-fast', 'high'); return CODEX_0160_COMPOSER }+ throw new Error(`unexpected ${key}`)+ })+ const auto = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'codex-auto-fast', effort: 'auto' })+ await run.controller.setProfile('s1', auto)+ expect(run.keys).toEqual(['1'])+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'codex-auto-fast', effort: 'high' })++ // Low: the preset can only apply High, so the switch is refused and the picker closed untouched.+ const again = drive(manager, value, CODEX_0160_QUICK_MENU, () => { throw new Error('no row may be pressed') })+ const low = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'codex-auto-fast', effort: 'low' })+ await expect(again.controller.setProfile('s1', low)).rejects.toMatchObject({ code: 'EFFORT_UNSUPPORTED' })+ expect(again.keys).toEqual(['Escape'])+ })++ it('presses the row the list shows once Codex has refreshed it, not the row it first drew', async () => {+ // Codex 0.160 draws its cached models at once and redraws the list when the server answers; here+ // the answer brings a new model first, and GPT-6-Luna moves from row 4 to row 5.+ const { value, manager } = agent('gpt-5.5', 'high')+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-6-luna', effort: 'high' })+ let reads = 0+ const { controller, keys } = drive(manager, value, CODEX_0160_ALL_MODELS, (screen, key) => {+ const row = parseCodexPicker(screen)?.rows.find((candidate) => String(candidate.number) === key)+ if (screen === CODEX_0160_ALL_MODELS_REFRESHED && row) return reasoningFor(row.name)+ if (screen === reasoningFor('GPT-6-Luna') && key === '3') { applied(manager, value, 'gpt-6-luna', 'high'); return CODEX_0160_COMPOSER }+ throw new Error(`unexpected ${key} on ${row?.name ?? 'a reasoning screen'}`)+ }, (screen) => (screen === CODEX_0160_ALL_MODELS && ++reads > 1 ? CODEX_0160_ALL_MODELS_REFRESHED : screen))++ await controller.setProfile('s1', target)++ expect(keys).toEqual(['5', '3'])+ expect(manager.selectedModel(value)).toBe(target)+ })++ it('stops when the reasoning picker that opens names another model than the row pressed', async () => {+ // The list read the same twice, and was renumbered between the second read and the digit.+ const { value, manager } = agent('gpt-5.5', 'high')+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-6-luna', effort: 'high' })+ const { controller, keys } = drive(manager, value, CODEX_0160_ALL_MODELS, (screen, key) => {+ const row = parseCodexPicker(CODEX_0160_ALL_MODELS_REFRESHED)?.rows.find((candidate) => String(candidate.number) === key)+ if (screen === CODEX_0160_ALL_MODELS && row) return reasoningFor(row.name)+ throw new Error(`unexpected ${key}`)+ })++ await expect(controller.setProfile('s1', target)).rejects.toMatchObject({ code: 'MODEL_UNAVAILABLE' })+ // Row 4 was GPT-6-Luna when read and GPT-6-Sol when pressed: no effort was chosen for it.+ expect(keys).toEqual(['4', 'Escape'])+ })++ it('presses nothing for a model the list does not show exactly', async () => {+ const { value, manager } = agent('gpt-5.5', 'high')+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-7', effort: 'high' })+ vi.spyOn(manager, 'modelsForSession').mockResolvedValue([{ id: target, displayName: 'GPT-7 / High' }])+ const catalog = vi.spyOn(manager, 'codexCatalog')+ const { controller, keys } = drive(manager, value, CODEX_0160_ALL_MODELS, () => { throw new Error('no row may be pressed') })++ await expect(controller.setProfile('s1', target)).rejects.toMatchObject({ code: 'MODEL_UNAVAILABLE' })+ expect(keys).toEqual(['Escape'])+ // The catalog is read again once before giving up: a refresh may have brought the name.+ expect(catalog).toHaveBeenCalledTimes(2)+ })++ it('offers an account held to the reserve model nothing else, and changes the reserve effort', async () => {+ const held = agent('gpt-reserve', 'medium')+ const other = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-6-luna', effort: 'high' })+ const refused = drive(held.manager, held.value, CODEX_0160_RESERVE, () => { throw new Error('no row may be pressed') })+ await expect(refused.controller.setProfile('s1', other)).rejects.toMatchObject({ code: 'MODEL_UNAVAILABLE' })+ // Neither its one row nor Enter: the picker is recognised, and closed.+ expect(refused.keys).toEqual(['Escape'])++ const high = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-reserve', effort: 'high' })+ vi.spyOn(held.manager, 'modelsForSession').mockResolvedValue([{ id: high, displayName: 'Luna Reserve / High' }])+ const { controller, keys } = drive(held.manager, held.value, CODEX_0160_RESERVE, (screen, key) => {+ if (screen === CODEX_0160_RESERVE && key === '1') return CODEX_0160_RESERVE_REASONING+ if (screen === CODEX_0160_RESERVE_REASONING && key === '3') { applied(held.manager, held.value, 'gpt-reserve', 'high'); return CODEX_0160_COMPOSER }+ throw new Error(`unexpected ${key}`)+ })+ await controller.setProfile('s1', high)+ expect(keys).toEqual(['1', '3'])+ expect(held.manager.selectedModel(held.value)).toBe(high)+ })++ it('reaches Max through Advanced Reasoning, from a picker that opened on a reasoning screen', async () => {+ const { value, manager } = agent('gpt-5.6-sol', 'high')+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-5.6-sol', effort: 'max' })+ const reasoning = reasoningFor('GPT-5.6-Sol')+ let opened = false+ const { controller, keys } = drive(manager, value, reasoning, (screen, key) => {+ if (key === 'Escape' && !opened) { opened = true; return CODEX_0160_ALL_MODELS }+ if (screen === CODEX_0160_ALL_MODELS && key === '5') return reasoning+ if (screen === reasoning && key === '6') return CODEX_0160_ADVANCED+ if (screen === CODEX_0160_ADVANCED && key === '1') { applied(manager, value, 'gpt-5.6-sol', 'max'); return CODEX_0160_COMPOSER }+ throw new Error(`unexpected ${key}`)+ }, undefined, true)++ await controller.setProfile('s1', target)++ expect(keys).toEqual(['Escape', '5', '6', '1'])+ expect(manager.selectedModel(value)).toBe(target)+ })++ it('reaches Ultra on a GPT-6 model, as Codex catalog lists it there, and refuses Max where it does not', async () => {+ const { value, manager } = agent('gpt-5.5', 'high')+ const ultra = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-6.1-sol', effort: 'ultra' })+ const reasoning = reasoningFor('GPT-6.1-Sol')+ const { controller, keys } = drive(manager, value, CODEX_0160_ALL_MODELS, (screen, key) => {+ if (screen === CODEX_0160_ALL_MODELS && key === '1') return reasoning+ if (screen === reasoning && key === '6') return CODEX_0160_ADVANCED+ if (screen === CODEX_0160_ADVANCED && key === '2') { applied(manager, value, 'gpt-6.1-sol', 'ultra'); return CODEX_0160_COMPOSER }+ throw new Error(`unexpected ${key}`)+ })+ await controller.setProfile('s1', ultra)+ expect(keys).toEqual(['1', '6', '2'])+ expect(manager.selectedModel(value)).toBe(ultra)++ // gpt-5.5 lists no Max: refused before `/model` is typed.+ const refused = drive(manager, value, CODEX_0160_ALL_MODELS, () => { throw new Error('no key may be pressed') })+ await expect(refused.controller.setProfile('s1', encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-5.5', effort: 'max' })))+ .rejects.toMatchObject({ code: 'EFFORT_UNSUPPORTED' })+ expect(refused.keys).toEqual([])+ })++ it('presses nothing on a list that never reads the same twice', async () => {+ const { value, manager } = agent('gpt-5.5', 'high')+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-6-luna', effort: 'high' })+ let reads = 0+ const { controller, keys } = drive(manager, value, CODEX_0160_ALL_MODELS, () => { throw new Error('no row may be pressed') },+ (screen) => (screen === CODEX_0160_ALL_MODELS && ++reads % 2 === 0 ? CODEX_0160_ALL_MODELS_REFRESHED : screen))++ await expect(controller.setProfile('s1', target)).rejects.toMatchObject({ code: 'MODEL_UNAVAILABLE' })+ expect(keys).toEqual(['Escape'])+ })++ it('takes the next switch after a refused one, when the app names the agent', async () => {+ // The apps address an agent by its agent id ('h1'), not by the engine session ('s1').+ const held = agent('gpt-reserve', 'medium')+ const refused = drive(held.manager, held.value, CODEX_0160_RESERVE, () => { throw new Error('no row may be pressed') })+ await expect(refused.controller.setProfile('h1', encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-6-luna', effort: 'high' })))+ .rejects.toMatchObject({ code: 'MODEL_UNAVAILABLE' })++ const high = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-reserve', effort: 'high' })+ vi.spyOn(held.manager, 'modelsForSession').mockResolvedValue([{ id: high, displayName: 'Luna Reserve / High' }])+ const { controller } = drive(held.manager, held.value, CODEX_0160_RESERVE, (screen, key) => {+ if (screen === CODEX_0160_RESERVE && key === '1') return CODEX_0160_RESERVE_REASONING+ if (screen === CODEX_0160_RESERVE_REASONING && key === '3') { applied(held.manager, held.value, 'gpt-reserve', 'high'); return CODEX_0160_COMPOSER }+ throw new Error(`unexpected ${key}`)+ })+ await controller.setProfile('h1', high)+ expect(held.manager.selectedModel(held.value)).toBe(high)+ })++ it('confirms a model the catalog does not describe that applied its one effort at once', async () => {+ const { value, manager } = agent('gpt-5.5', 'high', await codexHome([]))+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-6-luna', effort: 'auto' })+ vi.spyOn(manager, 'modelsForSession').mockResolvedValue([{ id: target, displayName: 'GPT-6-Luna / Auto' }])+ const list = ' Select Model and Effort\n\n› 1. gpt-6-luna Fast and affordable model for easier tasks.'+ const { controller, keys } = drive(manager, value, list, (screen, key) => {+ if (screen === list && key === '1') { applied(manager, value, 'gpt-6-luna', 'medium'); return CODEX_0160_COMPOSER }+ throw new Error(`unexpected ${key}`)+ })++ await controller.setProfile('s1', target)++ expect(keys).toEqual(['1'])+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'gpt-6-luna', effort: 'medium' })+ })+ })+it('refuses to drive an engine the owner made view-only', async () => {// Switching is Claude and Codex only (owner, 2026-07-31). This replaces two tests that drove Cursor's// picker end to end: setCursor and the other per-engine drivers are still in the code, deliberately —diff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.tsindex 16bfddce9..83259fbe8 100644--- a/cli/src/lib/runtimeProfileController.ts+++ b/cli/src/lib/runtimeProfileController.ts@@ -11,6 +11,15 @@ import {type OpencodeModelTarget,type OpencodePickerRow,} from '../engines/opencode/runtimeProfile.js'+import {+ chooseCodexRow,+ codexDigitPressable,+ codexEffortRows,+ parseCodexPicker,+ sameCodexPicker,+ type CodexCatalogModel,+ type CodexPicker,+} from '../engines/codex/modelPicker.js'import {codexEffortAllowed,parseRuntimeProfile,@@ -23,6 +32,12 @@ import {const COMMAND_CONFIRM_MS = 8_000const PICKER_OPEN_MS = 3_000const PICKER_STEP_MS = 2_000+/**+ * How far apart the two reads of a Codex model list are, which must agree before a digit is pressed on+ * it (see reachCodexEfforts): long enough for a redraw in flight to land, short beside the seconds a+ * switch takes to confirm.+ */+const CODEX_SETTLE_MS = 250/** Hard bound on ladder keystrokes — twice pi's seven levels, so a desynchronised walk still terminates. */const PI_LADDER_MAX_STEPS = 14/** Hermes' longest picker page is a provider's model list; twice its size still terminates. */@@ -267,18 +282,6 @@ function allVisibleTextIsMuted(value: string): boolean {return sawText}-function interactionText(capture: string): string {- const lines = capture.split('\n')- const promptIndex = lines.findLastIndex((line) => {- const visible = stripAnsi(line)- const marker = visible.search(/[›❯]/u)- if (marker < 0) return false- // Picker selection rows also use ›, but numbered rows are not composer prompts.- return !/^\s*\d+\.\s/.test(visible.slice(marker + 1))- })- return (promptIndex >= 0 ? lines.slice(promptIndex) : lines).join('\n')-}-/*** The glyph each CLI puts in front of its composer. They do not share one: cursor uses `→`, devin `❭`* (U+276D — close to, but not, claude's `❯` U+276F), and pi draws no marker at all. Getting this wrong is@@ -630,91 +633,6 @@ function inspectPiPane(capture: string): PaneInspection {return { idle: footer && !dialog && !draft, plan: false, dialog, draft }}-interface NumberedRow {- number: string- label: string- raw: string-}--function numberedRows(capture: string): NumberedRow[] {- const rows: NumberedRow[] = []- for (const raw of stripAnsi(capture).split('\n')) {- const match = /^\s*[›>]?[ ]*(\d+)\.\s+(.+?)\s*$/.exec(raw)- if (match) rows.push({ number: match[1], label: match[2], raw })- }- return rows-}--export interface CodexModelMenuRows {- quickModels: Map<string, string>- allModelsRow: string | null-}--/** Codex 0.145+ adds a quick-mode menu before the existing model and effort pickers. */-export function parseCodexModelMenuRows(capture: string): CodexModelMenuRows | null {- capture = interactionText(capture)- const visible = stripAnsi(capture)- if (!/Pick a quick auto mode or browse all models/i.test(visible)) return null- const quickModels = new Map<string, string>()- let allModelsRow: string | null = null- for (const row of numberedRows(capture)) {- if (/^All models\b/i.test(row.label)) {- allModelsRow = row.number- continue- }- const model = /^([a-z0-9][a-z0-9._-]*)(?:\s+\((?:current|default)\))?(?:\s{2,}|$)/i.exec(row.label)?.[1]- if (model) quickModels.set(model, row.number)- }- return { quickModels, allModelsRow }-}--export function parseCodexModelRows(capture: string): Map<string, string> | null {- capture = interactionText(capture)- if (!/Select Model and Effort/i.test(stripAnsi(capture))) return null- const result = new Map<string, string>()- for (const row of numberedRows(capture)) {- const model = /^([a-z0-9][a-z0-9._-]*)(?:\s+\((?:current|default)\))?(?:\s{2,}|$)/i.exec(row.label)?.[1]- if (model) result.set(model, row.number)- }- return result-}--export interface CodexEffortRows {- efforts: Map<string, string>- defaultRow: string | null- advancedRow: string | null-}--export function parseCodexEffortRows(capture: string): CodexEffortRows | null {- capture = interactionText(capture)- if (!/Select Reasoning Level for\s+/i.test(stripAnsi(capture))) return null- const efforts = new Map<string, string>()- let defaultRow: string | null = null- let advancedRow: string | null = null- for (const row of numberedRows(capture)) {- const label = row.label.toLowerCase()- if (label.startsWith('low')) efforts.set('low', row.number)- else if (label.startsWith('medium')) efforts.set('medium', row.number)- else if (label.startsWith('high')) efforts.set('high', row.number)- else if (label.startsWith('extra high')) efforts.set('xhigh', row.number)- else if (label.startsWith('max')) efforts.set('max', row.number)- else if (label.startsWith('more reasoning')) advancedRow = row.number- if (/\(default\)/i.test(row.label)) defaultRow = row.number- }- return { efforts, defaultRow, advancedRow }-}--export function parseCodexAdvancedRows(capture: string): Map<string, string> | null {- capture = interactionText(capture)- if (!/Advanced Reasoning/i.test(stripAnsi(capture))) return null- const efforts = new Map<string, string>()- for (const row of numberedRows(capture)) {- if (/^max\b/i.test(row.label)) efforts.set('max', row.number)- else if (/^ultra\b/i.test(row.label)) efforts.set('ultra', row.number)- }- return efforts-}-export interface CursorParameterRow {kind: 'context' | 'reasoning' | 'fast' | 'thinking'value: string@@ -776,6 +694,11 @@ export function parseCursorParameterRows(capture: string): CursorParameterRow[]return rows.length ? rows : null}+/** The lists a model is chosen from, as against the reasoning screens that follow them. */+function isCodexList(picker: CodexPicker): boolean {+ return picker.kind === 'quick' || picker.kind === 'models' || picker.kind === 'reserve'+}+function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms))}@@ -802,8 +725,11 @@ export class RuntimeProfileController {console.warn(`[runtime-profile] unsupported ${session.engine} CLI version ${session.cliVersion ?? 'unknown'} for ${sessionId.slice(0, 8)}`)throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')}- if (session.engine === 'codex' && !codexEffortAllowed(target.model, target.effort)) {- throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')+ // Codex's own catalog: which efforts each model takes, and the names its picker shows them by.+ const codexCatalog = session.engine === 'codex' ? await this.deps.manager.codexCatalog(session) : []+ if (session.engine === 'codex') {+ const listed = codexCatalog.find((entry) => entry.slug === target.model)?.efforts ?? null+ if (!codexEffortAllowed(target.model, target.effort, listed)) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')}const options = await this.deps.manager.modelsForSession(session)if (!options.some((option) => option.id === target.id)) {@@ -828,7 +754,7 @@ export class RuntimeProfileController {await this.setClaude(session, target, current, options)} else if (session.engine === 'codex') {pickerOpen = true- await this.setCodex(session, target)+ await this.setCodex(session, target, codexCatalog)pickerOpen = false} else if (session.engine === 'devin') {// No picker is ever opened — `/model <id>` is a single command — so there is nothing to Escape out@@ -865,7 +791,11 @@ export class RuntimeProfileController {if (!next || !inspectRuntimePane(session.engine, next).dialog) break}}- if (controlStarted) this.deps.manager.cancelControl(sessionId)+ // By the engine session, as beginControl keyed it. `sessionId` is whichever id the request named,+ // and the apps name the agent: cancelling under that left the control in place, and every later+ // switch of the agent answered BUSY until the daemon restarted (found by e2e/models.e2e.ts, a+ // refused switch followed by one that should have gone through).+ if (controlStarted) this.deps.manager.cancelControl(session.sessionId)// A failed switch used to leave NOTHING in the log — the picker just flashed open and shut on the// user's terminal and the device said nothing useful. Name the session, engine and reason.const code = error instanceof RuntimeProfileControlError ? error.code : 'TMUX_FAILED'@@ -1259,69 +1189,136 @@ export class RuntimeProfileController {return !!confirmed}- private async setCodex(session: RegisteredSession, target: RuntimeProfile): Promise<void> {+ /**+ * Codex's `/model`: a quick menu of auto presets with an `All models` row (0.145 and later), the full+ * list (`Select Model and Effort`), then the chosen model's reasoning picker, each row pressed by its+ * digit, which selects the row and accepts it. How a row is read and chosen, and why, is in+ * engines/codex/modelPicker.ts. Confirmed, as it always was, by the `thread_settings_applied` record+ * Codex writes once the choice is applied (RuntimeProfileManager `ingestCodex`).+ */+ private async setCodex(session: RegisteredSession, target: RuntimeProfile, catalog: CodexCatalogModel[]): Promise<void> {if (!await this.deps.sendText(session.agentId, '/model')) throw new RuntimeProfileControlError('TMUX_FAILED')- const isPicker = (value: string): boolean =>- !!parseCodexModelMenuRows(value) || !!parseCodexEffortRows(value) || !!parseCodexModelRows(value)- let capture = await this.waitPane(session.agentId, isPicker, 900)- if (!capture) {+ let picker = await this.waitCodexPicker(session, () => true, 900)+ if (!picker) {await this.deps.sendKey(session.agentId, 'Enter')- capture = await this.waitPane(session.agentId, isPicker, PICKER_OPEN_MS)+ picker = await this.waitCodexPicker(session, () => true, PICKER_OPEN_MS)+ }+ if (!picker) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')+ if (!isCodexList(picker)) {+ // Opened on a reasoning screen: back to the list it was opened from, so the model is chosen too.+ if (!await this.deps.sendKey(session.agentId, 'Escape')) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')+ if (!await this.waitCodexPicker(session, isCodexList, PICKER_STEP_MS)) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')}- if (!capture) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')+ const reached = await this.reachCodexEfforts(session, target, catalog)+ if (reached !== 'applied') await this.pickCodexEffort(session, target, reached)+ if (!await this.deps.manager.waitForProfile(session.sessionId, COMMAND_CONFIRM_MS)) {+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')+ }+ }- let efforts = parseCodexEffortRows(capture)- if (efforts) {- if (!await this.deps.sendKey(session.agentId, 'Escape')) {- throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')+ /**+ * From the list on screen to the target model's reasoning picker, through `All models` when the quick+ * menu is first; or 'applied' when the model's row applied it at once (a model with one effort).+ *+ * Every digit is pressed from a list read twice, CODEX_SETTLE_MS apart, the same both times. Codex+ * 0.160 draws the list from its cache and redraws it in place when the server answers, and a model+ * added or reordered then renumbers the rows: a digit read off the first drawing lands on another+ * model. The reasoning picker that opens names its model in its title, and a title naming any other+ * model than the row pressed means the list moved anyway, so nothing more is pressed.+ */+ private async reachCodexEfforts(+ session: RegisteredSession,+ target: RuntimeProfile,+ catalog: CodexCatalogModel[],+ ): Promise<CodexPicker | 'applied'> {+ let reread = false+ for (let lists = 0; lists < 2; lists++) {+ const list = await this.settledCodexList(session)+ if (!list) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')+ let choice = chooseCodexRow(list, target, catalog)+ if ('error' in choice && choice.error === 'MODEL_UNAVAILABLE' && !reread) {+ // Codex saves the catalog its picker refreshed from to models_cache.json, so a model or a name+ // that came with the refresh is there to read now.+ reread = true+ catalog = await this.deps.manager.codexCatalog(session)+ choice = chooseCodexRow(list, target, catalog)}- capture = await this.waitPane(- session.agentId,- (value) => !!parseCodexModelMenuRows(value) || !!parseCodexModelRows(value),- PICKER_STEP_MS,- )- if (!capture) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')- efforts = null+ if ('error' in choice) throw new RuntimeProfileControlError(choice.error)+ if (!await this.deps.sendKey(session.agentId, String(choice.row.number))) throw new RuntimeProfileControlError('TMUX_FAILED')+ if (choice.opens === 'list') {+ if (!await this.waitCodexPicker(session, (next) => next.kind === 'models', PICKER_STEP_MS)) {+ throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')+ }+ continue+ }+ if (choice.opens === 'applied') return 'applied'+ const next = await this.waitCodexAfterModelRow(session)+ if (next === 'closed') return 'applied'+ if (!next) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')+ if (next.model !== choice.row.name) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')+ return next}+ throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')+ }- const menu = parseCodexModelMenuRows(capture)- if (menu) {- const quickRow = menu.quickModels.get(target.model)- const row = quickRow ?? menu.allModelsRow- if (!row) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')- if (!await this.deps.sendKey(session.agentId, row)) throw new RuntimeProfileControlError('TMUX_FAILED')- capture = await this.waitPane(- session.agentId,- quickRow- ? (value) => !!parseCodexEffortRows(value)- : (value) => !!parseCodexModelRows(value),- PICKER_STEP_MS,- )- if (!capture) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')- efforts = parseCodexEffortRows(capture)+ /** The target's effort in its reasoning picker, through Advanced Reasoning for Max and Ultra. */+ private async pickCodexEffort(session: RegisteredSession, target: RuntimeProfile, picker: CodexPicker): Promise<void> {+ const rows = codexEffortRows(picker)+ let row = target.effort === 'auto' ? rows.defaultRow : rows.efforts.get(target.effort) ?? null+ if (row === null && (target.effort === 'max' || target.effort === 'ultra') && rows.advancedRow !== null+ && codexDigitPressable(rows.advancedRow)) {+ if (!await this.deps.sendKey(session.agentId, String(rows.advancedRow))) throw new RuntimeProfileControlError('TMUX_FAILED')+ const advanced = await this.waitCodexPicker(session, (next) => next.kind === 'advanced', PICKER_STEP_MS)+ row = advanced ? codexEffortRows(advanced).efforts.get(target.effort) ?? null : null}+ if (row === null || !codexDigitPressable(row)) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')+ if (!await this.deps.sendKey(session.agentId, String(row))) throw new RuntimeProfileControlError('TMUX_FAILED')+ }- if (!efforts) {- const models = parseCodexModelRows(capture)- const modelRow = models?.get(target.model)- if (!modelRow) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')- if (!await this.deps.sendKey(session.agentId, modelRow)) throw new RuntimeProfileControlError('TMUX_FAILED')- capture = await this.waitPane(session.agentId, (value) => !!parseCodexEffortRows(value), PICKER_STEP_MS)- efforts = capture ? parseCodexEffortRows(capture) : null- }+ /** The first Codex picker on the pane that `wanted` takes, polled until `timeoutMs`. */+ private async waitCodexPicker(+ session: RegisteredSession,+ wanted: (picker: CodexPicker) => boolean,+ timeoutMs: number,+ ): Promise<CodexPicker | null> {+ const capture = await this.waitPane(session.agentId, (value) => {+ const picker = parseCodexPicker(value)+ return !!picker && wanted(picker)+ }, timeoutMs)+ return capture ? parseCodexPicker(capture) : null+ }- if (!efforts) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')- let effortRow = target.effort === 'auto' ? efforts.defaultRow : efforts.efforts.get(target.effort) ?? null- if (!effortRow && (target.effort === 'max' || target.effort === 'ultra') && efforts.advancedRow) {- if (!await this.deps.sendKey(session.agentId, efforts.advancedRow)) throw new RuntimeProfileControlError('TMUX_FAILED')- capture = await this.waitPane(session.agentId, (value) => !!parseCodexAdvancedRows(value), PICKER_STEP_MS)- effortRow = capture ? parseCodexAdvancedRows(capture)?.get(target.effort) ?? null : null+ /** A model list that reads the same twice, CODEX_SETTLE_MS apart (see reachCodexEfforts). */+ private async settledCodexList(session: RegisteredSession): Promise<CodexPicker | null> {+ let previous: CodexPicker | null = null+ const deadline = Date.now() + PICKER_STEP_MS+ while (Date.now() < deadline) {+ const capture = await this.deps.capture(session.agentId, 100)+ const picker = capture ? parseCodexPicker(capture) : null+ const list = picker && isCodexList(picker) ? picker : null+ if (list && previous && sameCodexPicker(previous, list)) return list+ previous = list+ await sleep(CODEX_SETTLE_MS)}- if (!effortRow) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')- if (!await this.deps.sendKey(session.agentId, effortRow)) throw new RuntimeProfileControlError('TMUX_FAILED')- if (!await this.deps.manager.waitForProfile(session.sessionId, COMMAND_CONFIRM_MS)) {- throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')+ return null+ }++ /**+ * After a model's row: its reasoning picker, or 'closed' when the picker went away and the composer+ * is back, which is a model the catalog did not describe applying its one effort at once.+ */+ private async waitCodexAfterModelRow(session: RegisteredSession): Promise<CodexPicker | 'closed' | null> {+ const deadline = Date.now() + PICKER_STEP_MS+ while (Date.now() < deadline) {+ const capture = await this.deps.capture(session.agentId, 100)+ if (capture) {+ const picker = parseCodexPicker(capture)+ if (picker?.kind === 'efforts') return picker+ if (!picker && inspectRuntimePane('codex', capture).idle) return 'closed'+ }+ await sleep(100)}+ return null}private async setCursor(session: RegisteredSession, target: RuntimeProfile): Promise<void> {