agent-console 1.3.2: Codex's picker lists model_catalog_json's models (#758)

With a custom Codex provider, listModels read only config.toml's `model`
and `[model_providers.<p>].models`, so a config whose models live in
`model_catalog_json` (as magpie writes it) showed one "Default" row
(wwenc6621, #758).

parseCodexConfig now reads `model_catalog_json` (a profile's first), and
the picker lists that file's models: slug as the id, display_name as the
label, supported_reasoning_levels/default_reasoning_level as the levels.
Entries whose visibility isn't "list" are left out, as Codex's own picker
does. The path is resolved as Codex's AbsolutePathBuf does it (checked in
openai/codex codex-rs/utils/absolute-path): "~" and "~/..." are home, a
relative path is taken from config.toml's folder. Codex doesn't expand
environment variables; a leading $HOME / ${HOME}, as in the reporter's
config, is expanded here too. The configured model stays the default;
`models = [...]` entries missing from the catalog are kept after it. A
missing or unparsable catalog logs a warning and keeps the old list.

Run (mote, macOS):
- vitest: 62 files, 466 passed / 17 skipped; `npm run check` OK.
- `npm run build`, then `verify:build`: committed dist identical.
- root `bun test packages/agent-console` 6/6; `bun scripts/check.mjs` OK.
- A real magpie-written catalog (33 entries, 31 listed): 31 rows with
  display names and levels.
Broken by hand: the new test file against main's provider.ts: 4 of 5
tests red (the reporter's config gives only the one model); the fifth,
missing/broken catalog, passes on both by design.
Not tried: the console UI itself with a live Codex, and Windows/Linux.
This commit is contained in:
yetone
2026-11-05 17:20:20 +08:00
parent 808f7a184d
commit 7e70a23ca3
6 changed files with 270 additions and 37 deletions
+81 -25
View File
@@ -4111,7 +4111,7 @@ var init_types = __esm({
// daemon/src/providers/codex/provider.ts
import { homedir as homedir7 } from "node:os";
import { join as join9 } from "node:path";
import { dirname as dirname3, isAbsolute as isAbsolute2, join as join9 } from "node:path";
import { readFile as readFile8 } from "node:fs/promises";
function runVersion2(r, args, timeoutMs = 5e3) {
return new Promise((resolvePromise, reject) => {
@@ -4138,7 +4138,8 @@ function runVersion2(r, args, timeoutMs = 5e3) {
function normalizeEfforts(raw) {
const out = [];
for (const e of raw ?? []) {
const v = typeof e === "string" ? e : e?.reasoningEffort;
const o = e;
const v = typeof e === "string" ? e : o?.reasoningEffort ?? o?.effort;
if (typeof v === "string" && v && !out.includes(v)) out.push(v);
}
return out;
@@ -4201,6 +4202,7 @@ function parseCodexConfig(text) {
const profileValue = (key) => profileName ? values.get(`profiles.${profileName}\0${key}`) : void 0;
const modelProvider = profileValue("model_provider") ?? top("model_provider");
const model = profileValue("model") ?? top("model");
const catalog = profileValue("model_catalog_json") ?? top("model_catalog_json");
const provider = typeof modelProvider === "string" ? modelProvider : null;
const models2 = /* @__PURE__ */ new Set();
if (typeof model === "string" && model) models2.add(model);
@@ -4209,15 +4211,69 @@ function parseCodexConfig(text) {
for (const m of value) models2.add(m);
}
}
return { modelProvider: provider, model: typeof model === "string" ? model : null, providerModels: [...models2] };
return {
modelProvider: provider,
model: typeof model === "string" ? model : null,
providerModels: [...models2],
catalogJson: typeof catalog === "string" && catalog.trim() ? catalog.trim() : null
};
}
function resolveCatalogPath(raw, configDir, home = homedir7()) {
let p = raw.trim();
const env = p.match(/^(?:\$HOME|\$\{HOME\})(?=$|[\\/])/);
if (env) p = home + p.slice(env[0].length);
else if (p === "~") p = home;
else if (/^~[\\/]/.test(p)) p = join9(home, p.slice(2));
return isAbsolute2(p) ? p : join9(configDir, p);
}
function parseCodexCatalog(text) {
const doc = JSON.parse(text);
if (!Array.isArray(doc?.models)) return [];
const out = [];
const seen = /* @__PURE__ */ new Set();
for (const raw of doc.models) {
const m = raw;
if (!m || typeof m.slug !== "string" || !m.slug || seen.has(m.slug)) continue;
if (typeof m.visibility === "string" && m.visibility !== "list") continue;
seen.add(m.slug);
const efforts = normalizeEfforts(Array.isArray(m.supported_reasoning_levels) ? m.supported_reasoning_levels : void 0);
const thinkingOptions = efforts.map((e) => ({ id: e, label: e }));
const def = typeof m.default_reasoning_level === "string" && efforts.includes(m.default_reasoning_level) ? m.default_reasoning_level : null;
const name = typeof m.display_name === "string" && m.display_name.trim() ? m.display_name.trim() : m.slug;
out.push({ id: m.slug, name, efforts, thinkingOptions, defaultThinking: def ?? thinkingOptions[0]?.id ?? null });
}
return out;
}
async function codexProviderModels(config, configDir, home = homedir7()) {
let rows = [];
if (config.catalogJson) {
const file = resolveCatalogPath(config.catalogJson, configDir, home);
try {
rows = parseCodexCatalog(await readFile8(file, "utf8"));
} catch (e) {
log("warn", "codex model_catalog_json \u8BFB\u53D6\u5931\u8D25", { file, err: String(e) });
}
}
const ids = new Set(rows.map((r) => r.id));
for (const id2 of config.providerModels) {
if (!ids.has(id2)) {
ids.add(id2);
rows.push({ id: id2, name: id2 });
}
}
if (config.model && !rows.some((r) => r.id === config.model)) rows.unshift({ id: config.model, name: config.model });
const def = config.model ?? rows[0]?.id;
return rows.map((r) => ({ ...r, isDefault: r.id === def }));
}
function codexConfigFile() {
const home = process.env.CODEX_HOME?.trim() || join9(homedir7(), ".codex");
return home.toLowerCase().endsWith(".toml") ? home : join9(home, "config.toml");
}
async function readCodexConfig() {
const home = process.env.CODEX_HOME?.trim() || join9(homedir7(), ".codex");
const file = home.toLowerCase().endsWith(".toml") ? home : join9(home, "config.toml");
try {
return parseCodexConfig(await readFile8(file, "utf8"));
return parseCodexConfig(await readFile8(codexConfigFile(), "utf8"));
} catch {
return { modelProvider: null, model: null, providerModels: [] };
return { modelProvider: null, model: null, providerModels: [], catalogJson: null };
}
}
function isChatGptProvider(id2) {
@@ -4243,7 +4299,7 @@ function createCodexProvider(version) {
async listModels(launch) {
const config = await readCodexConfig();
if (!isChatGptProvider(config.modelProvider)) {
const rows = config.providerModels.map((id2, i) => ({ id: id2, name: id2, isDefault: i === 0 }));
const rows = await codexProviderModels(config, dirname3(codexConfigFile()));
return rows.length ? rows : [{ id: "", name: `${PLACEHOLDER_MODEL_NAME} (${config.modelProvider})`, isDefault: true }];
}
if (!launch && modelCache && Date.now() - modelCache.at < MODEL_CACHE_MS) return modelCache.models;
@@ -5975,7 +6031,7 @@ var init_autoApprove13 = __esm({
// daemon/src/util/mentions.ts
import { realpath, stat as stat8 } from "node:fs/promises";
import { isAbsolute as isAbsolute2, resolve as resolve3, sep as sep2, win32 as win322, posix as posix2 } from "node:path";
import { isAbsolute as isAbsolute3, resolve as resolve3, sep as sep2, win32 as win322, posix as posix2 } from "node:path";
function insideRoot(root, child, platform = process.platform) {
const p = platform === "win32" ? win322 : posix2;
const norm2 = (s) => platform === "win32" ? p.resolve(s).toLowerCase() : p.resolve(s);
@@ -5995,7 +6051,7 @@ async function resolveMentions(projectPath, refs) {
}
for (const ref of refs.slice(0, MAX_MENTIONS)) {
const rel = String(ref.rel ?? "").replace(/\\/g, "/");
if (!rel || rel.includes("\0") || isAbsolute2(rel) || /^[a-zA-Z]:/.test(rel)) {
if (!rel || rel.includes("\0") || isAbsolute3(rel) || /^[a-zA-Z]:/.test(rel)) {
warnings.push(rel || "(empty)");
continue;
}
@@ -6834,7 +6890,7 @@ import { z } from "zod";
import { existsSync as existsSync9, statSync as statSync5 } from "node:fs";
import { mkdir as mkdir3, writeFile as writeFile4 } from "node:fs/promises";
import { homedir as homedir9 } from "node:os";
import { dirname as dirname3, join as join12, win32 as win32Path } from "node:path";
import { dirname as dirname4, join as join12, win32 as win32Path } from "node:path";
import { execFile as execFile4 } from "node:child_process";
function wrap(schema, fn) {
return (params, ctx) => {
@@ -7380,7 +7436,7 @@ function revealInFileManager(filePath) {
});
return;
}
execFile4("xdg-open", [dirname3(filePath)], () => {
execFile4("xdg-open", [dirname4(filePath)], () => {
}).on("error", () => {
});
}
@@ -7418,10 +7474,10 @@ var init_methods = __esm({
// daemon/src/util/atomic.ts
import { writeFile as writeFile5, rename, mkdir as mkdir4 } from "node:fs/promises";
import { dirname as dirname4 } from "node:path";
import { dirname as dirname5 } from "node:path";
async function writeJsonAtomic(file, obj) {
try {
await mkdir4(dirname4(file), { recursive: true });
await mkdir4(dirname5(file), { recursive: true });
const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
await writeFile5(tmp, JSON.stringify(obj, null, 2), "utf8");
await rename(tmp, file);
@@ -7553,7 +7609,7 @@ var init_settings = __esm({
// daemon/src/util/jsonl.ts
import { appendFile, readFile as readFile14, mkdir as mkdir5, rename as rename2, writeFile as writeFile6 } from "node:fs/promises";
import { dirname as dirname5 } from "node:path";
import { dirname as dirname6 } from "node:path";
async function readJsonl(file) {
let text = "";
try {
@@ -7576,7 +7632,7 @@ function appendJsonl(file, obj) {
const prev = writers.get(file) ?? Promise.resolve();
const next = prev.then(async () => {
try {
await mkdir5(dirname5(file), { recursive: true });
await mkdir5(dirname6(file), { recursive: true });
await appendFile(file, JSON.stringify(obj) + "\n", "utf8");
} catch (e) {
if (e instanceof ApiError) throw e;
@@ -7865,7 +7921,7 @@ var init_warm = __esm({
// daemon/src/main.ts
import { mkdirSync as mkdirSync2, rmSync as rmSync2, chmodSync as chmodSync2 } from "node:fs";
import { join as join21, dirname as dirname8 } from "node:path";
import { join as join21, dirname as dirname9 } from "node:path";
import { fileURLToPath as fileURLToPath4 } from "node:url";
// daemon/src/config.ts
@@ -9781,7 +9837,7 @@ import { spawn as spawn4, execFileSync as execFileSync2 } from "node:child_proce
import { accessSync as accessSync2, chmodSync, constants as fsc, existsSync as existsSync12, statSync as statSync7 } from "node:fs";
import { createRequire as moduleRequire } from "node:module";
import { release } from "node:os";
import { dirname as dirname6, join as join18 } from "node:path";
import { dirname as dirname7, join as join18 } from "node:path";
var MAX_TERMS_PER_PROJECT = 8;
var BUF_MAX = 2 * 1024 * 1024;
var SNAP_LINES = 5e3;
@@ -9824,7 +9880,7 @@ function fixSpawnHelper() {
if (process.platform !== "darwin") return;
try {
const req = moduleRequire(import.meta.url);
const root = dirname6(req.resolve("node-pty/package.json"));
const root = dirname7(req.resolve("node-pty/package.json"));
for (const sub of [`prebuilds/darwin-${process.arch}`, "build/Release"]) {
const f = join18(root, sub, "spawn-helper");
if (existsSync12(f) && !isExecFile(f)) {
@@ -10079,7 +10135,7 @@ init_proxy();
// daemon/src/preview/ports.ts
import { readFileSync as readFileSync2 } from "node:fs";
import { homedir as homedir10 } from "node:os";
import { basename as basename5, dirname as dirname7, isAbsolute as isAbsolute3, join as join19 } from "node:path";
import { basename as basename5, dirname as dirname8, isAbsolute as isAbsolute4, join as join19 } from "node:path";
import { fileURLToPath as fileURLToPath3 } from "node:url";
var MAGPIE_DEFAULT_PORTS = [3425, 3430];
var GATE_DEFAULT_PORT = 3488;
@@ -10098,7 +10154,7 @@ function magpieDirFromInstall(p) {
function magpieConfigDirs(env = process.env, where = {}) {
const out = [];
const add = (d) => {
if (d && isAbsolute3(d) && !out.includes(d)) out.push(d);
if (d && isAbsolute4(d) && !out.includes(d)) out.push(d);
};
let self = where.self;
if (self === void 0) {
@@ -10110,9 +10166,9 @@ function magpieConfigDirs(env = process.env, where = {}) {
}
add(magpieDirFromInstall(self));
const cwd = where.cwd ?? (env === process.env ? process.cwd() : "");
if (cwd && basename5(cwd) === "plugin-work") add(dirname7(cwd));
if (cwd && basename5(cwd) === "plugin-work") add(dirname8(cwd));
const x = env.XDG_CONFIG_HOME;
if (x && isAbsolute3(x)) add(join19(x, "magpie"));
if (x && isAbsolute4(x)) add(join19(x, "magpie"));
const platform = where.platform ?? process.platform;
const home = where.home ?? (env === process.env ? homedir10() : platform === "win32" ? env.USERPROFILE : env.HOME);
if (home) add(join19(home, ".config", "magpie"));
@@ -10159,7 +10215,7 @@ if (nodeMajor < 20) {
console.error(`[agent-console] \u9700\u8981 Node.js 20 \u6216\u66F4\u9AD8\u7248\u672C\uFF0C\u5F53\u524D ${process.version}\uFF08${process.execPath}\uFF09`);
process.exit(3);
}
process.env.PATH = augmentPath(process.env, dirname8(process.execPath));
process.env.PATH = augmentPath(process.env, dirname9(process.execPath));
var cfg = parseConfig(process.argv.slice(2));
process.on("uncaughtException", (e) => {
if (e?.code === "EPIPE") return;
@@ -10173,7 +10229,7 @@ async function main() {
for (const d of ["threads", "attachments", "trash", "logs"]) {
mkdirSync2(join21(cfg.dataDir, d), { recursive: true });
}
const appDir = join21(dirname8(fileURLToPath4(import.meta.url)), "..", "..", "app");
const appDir = join21(dirname9(fileURLToPath4(import.meta.url)), "..", "..", "app");
const attachments = new AttachmentStore(join21(cfg.dataDir, "attachments"));
const { bindAttachmentStore: bindAttachmentStore2 } = await Promise.resolve().then(() => (init_attachmentRefs(), attachmentRefs_exports));
bindAttachmentStore2(attachments);
File diff suppressed because one or more lines are too long
@@ -10,7 +10,7 @@ import { tr } from "../../util/i18n.js";
import { launchArgv, resolveLaunch } from "../launch.js";
import { PLACEHOLDER_MODEL_NAME } from "../types.js";
import { homedir } from "node:os";
import { join } from "node:path";
import { dirname, isAbsolute, join } from "node:path";
import { readFile } from "node:fs/promises";
import { OutputDecoder } from "../../util/decode.js";
@@ -60,7 +60,9 @@ function runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs =
export function normalizeEfforts(raw: unknown[] | undefined): string[] {
const out: string[] = [];
for (const e of raw ?? []) {
const v = typeof e === "string" ? e : (e as { reasoningEffort?: unknown } | null)?.reasoningEffort;
// model_catalog_json's supported_reasoning_levels are { effort, description }[]
const o = e as { reasoningEffort?: unknown; effort?: unknown } | null;
const v = typeof e === "string" ? e : o?.reasoningEffort ?? o?.effort;
if (typeof v === "string" && v && !out.includes(v)) out.push(v);
}
return out;
@@ -105,7 +107,7 @@ async function fetchModels(r: ResolveResult & { ok: true }, cwd: string, launch?
}
}
export type CodexConfig = { modelProvider: string | null; model: string | null; providerModels: string[] };
export type CodexConfig = { modelProvider: string | null; model: string | null; providerModels: string[]; catalogJson: string | null };
function tomlValue(raw: string): string | string[] | null {
const v = raw.trim().replace(/\s+#.*$/, "");
@@ -136,6 +138,7 @@ export function parseCodexConfig(text: string): CodexConfig {
const profileValue = (key: string) => profileName ? values.get(`profiles.${profileName}\0${key}`) : undefined;
const modelProvider = (profileValue("model_provider") ?? top("model_provider"));
const model = (profileValue("model") ?? top("model"));
const catalog = (profileValue("model_catalog_json") ?? top("model_catalog_json"));
const provider = typeof modelProvider === "string" ? modelProvider : null;
const models = new Set<string>();
if (typeof model === "string" && model) models.add(model);
@@ -144,13 +147,76 @@ export function parseCodexConfig(text: string): CodexConfig {
for (const m of value) models.add(m);
}
}
return { modelProvider: provider, model: typeof model === "string" ? model : null, providerModels: [...models] };
return {
modelProvider: provider,
model: typeof model === "string" ? model : null,
providerModels: [...models],
catalogJson: typeof catalog === "string" && catalog.trim() ? catalog.trim() : null,
};
}
/**
* Where Codex reads model_catalog_json from: "~" and "~/…" are the home folder, a relative
* path is taken from config.toml's folder (Codex's AbsolutePathBuf). Codex doesn't expand
* environment variables; a leading $HOME / ${HOME} is expanded here anyway (#758).
*/
export function resolveCatalogPath(raw: string, configDir: string, home = homedir()): string {
let p = raw.trim();
const env = p.match(/^(?:\$HOME|\$\{HOME\})(?=$|[\\/])/);
if (env) p = home + p.slice(env[0].length);
else if (p === "~") p = home;
else if (/^~[\\/]/.test(p)) p = join(home, p.slice(2));
return isAbsolute(p) ? p : join(configDir, p);
}
/** The picker's rows from a Codex models.json ({ models: [{ slug, display_name, … }] }); hidden entries are left out as Codex's picker does */
export function parseCodexCatalog(text: string): ModelInfo[] {
const doc = JSON.parse(text) as { models?: unknown };
if (!Array.isArray(doc?.models)) return [];
const out: ModelInfo[] = [];
const seen = new Set<string>();
for (const raw of doc.models) {
const m = raw as { slug?: unknown; display_name?: unknown; visibility?: unknown; supported_reasoning_levels?: unknown; default_reasoning_level?: unknown } | null;
if (!m || typeof m.slug !== "string" || !m.slug || seen.has(m.slug)) continue;
if (typeof m.visibility === "string" && m.visibility !== "list") continue;
seen.add(m.slug);
const efforts = normalizeEfforts(Array.isArray(m.supported_reasoning_levels) ? m.supported_reasoning_levels : undefined);
const thinkingOptions = efforts.map((e) => ({ id: e, label: e }));
const def = typeof m.default_reasoning_level === "string" && efforts.includes(m.default_reasoning_level) ? m.default_reasoning_level : null;
const name = typeof m.display_name === "string" && m.display_name.trim() ? m.display_name.trim() : m.slug;
out.push({ id: m.slug, name, efforts, thinkingOptions, defaultThinking: def ?? thinkingOptions[0]?.id ?? null });
}
return out;
}
/** A custom provider's models: model_catalog_json's list, then the provider's models = [...]; the configured model is the default */
export async function codexProviderModels(config: CodexConfig, configDir: string, home = homedir()): Promise<ModelInfo[]> {
let rows: ModelInfo[] = [];
if (config.catalogJson) {
const file = resolveCatalogPath(config.catalogJson, configDir, home);
try {
rows = parseCodexCatalog(await readFile(file, "utf8"));
} catch (e) {
// a missing or broken catalog keeps the list from config.toml
log("warn", "codex model_catalog_json 读取失败", { file, err: String(e) });
}
}
const ids = new Set(rows.map((r) => r.id));
for (const id of config.providerModels) {
if (!ids.has(id)) { ids.add(id); rows.push({ id, name: id }); }
}
if (config.model && !rows.some((r) => r.id === config.model)) rows.unshift({ id: config.model, name: config.model });
const def = config.model ?? rows[0]?.id;
return rows.map((r) => ({ ...r, isDefault: r.id === def }));
}
function codexConfigFile(): string {
const home = process.env.CODEX_HOME?.trim() || join(homedir(), ".codex");
return home.toLowerCase().endsWith(".toml") ? home : join(home, "config.toml");
}
async function readCodexConfig(): Promise<CodexConfig> {
const home = process.env.CODEX_HOME?.trim() || join(homedir(), ".codex");
const file = home.toLowerCase().endsWith(".toml") ? home : join(home, "config.toml");
try { return parseCodexConfig(await readFile(file, "utf8")); } catch { return { modelProvider: null, model: null, providerModels: [] }; }
try { return parseCodexConfig(await readFile(codexConfigFile(), "utf8")); } catch { return { modelProvider: null, model: null, providerModels: [], catalogJson: null }; }
}
function isChatGptProvider(id: string | null): boolean {
@@ -177,7 +243,7 @@ export function createCodexProvider(version: string): Provider {
async listModels(launch?: LaunchCommand): Promise<ModelInfo[]> {
const config = await readCodexConfig();
if (!isChatGptProvider(config.modelProvider)) {
const rows = config.providerModels.map((id, i) => ({ id, name: id, isDefault: i === 0 }));
const rows = await codexProviderModels(config, dirname(codexConfigFile()));
return rows.length ? rows : [{ id: "", name: `${PLACEHOLDER_MODEL_NAME} (${config.modelProvider})`, isDefault: true }];
}
if (!launch && modelCache && Date.now() - modelCache.at < MODEL_CACHE_MS) return modelCache.models;
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@magpie-community/page-agent-console",
"version": "1.3.1",
"version": "1.3.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@magpie-community/page-agent-console",
"version": "1.3.1",
"version": "1.3.2",
"license": "MIT",
"dependencies": {
"@agentclientprotocol/sdk": "2.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/page-agent-console",
"version": "1.3.1",
"version": "1.3.2",
"description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.",
"author": "qingnian108 (https://github.com/qingnian108)",
"homepage": "https://github.com/qingnian108/magpie-agent-console",
@@ -0,0 +1,111 @@
// #758: a custom Codex provider's models come from model_catalog_json, not only the top-level model.
import { describe, expect, it, beforeEach, afterEach } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createCodexProvider, parseCodexConfig, resolveCatalogPath } from "../../daemon/src/providers/codex/provider.js";
// The reporter's config.toml, as written in the issue
const REPORTER_CONFIG = `model_provider = "magpie"
model_catalog_json = "$HOME/.codex/magpie-models.json"
model = "group/deepseek-v4-1-flash"
[model_providers.magpie]
name = "magpie"
base_url = "http://127.0.0.1:3425/v1"
wire_api = "responses"
`;
const SLUGS = [
"group/deepseek-v4-1-flash",
"group/glm-5.3-flash",
"workbuddy/hy3",
"workbuddy/deepseek-v4.1-flash",
"workbuddy/glm-5.3-flash",
"trae-cn/glm-5.3-flashx-max",
"trae-cn/deepseek-v4.1-flash",
];
const NAMES = ["DeepSeek V4.1 Flash", "GLM 5.3 Flash", "HY3", "DeepSeek V4.1 Flash", "GLM 5.3 Flash", "GLM 5.3 FlashX Max", "DeepSeek V4.1 Flash"];
function catalog(extra: object[] = []): string {
const levels = ["low", "medium", "high"].map((effort) => ({ effort, description: effort }));
return JSON.stringify({
models: [
...SLUGS.map((slug, i) => ({
slug,
display_name: NAMES[i],
visibility: "list",
supported_reasoning_levels: levels,
default_reasoning_level: "medium",
priority: i + 1,
})),
...extra,
],
});
}
describe("Codex model_catalog_json (#758)", () => {
let home: string;
let codexHome: string;
const saved: Record<string, string | undefined> = {};
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "ac-758-"));
codexHome = join(home, ".codex");
mkdirSync(codexHome);
for (const k of ["HOME", "USERPROFILE", "CODEX_HOME"]) saved[k] = process.env[k];
process.env.HOME = home;
process.env.USERPROFILE = home;
process.env.CODEX_HOME = codexHome;
});
afterEach(() => {
for (const [k, v] of Object.entries(saved)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
rmSync(home, { recursive: true, force: true });
});
const list = () => createCodexProvider("0").listModels();
it("lists every model of the reporter's catalog, display_name as the label", async () => {
writeFileSync(join(codexHome, "config.toml"), REPORTER_CONFIG);
writeFileSync(join(codexHome, "magpie-models.json"), catalog([{ slug: "hidden/one", display_name: "Hidden", visibility: "hide" }]));
const rows = await list();
expect(rows.map((r) => r.id)).toEqual(SLUGS);
expect(rows.map((r) => r.name)).toEqual(NAMES);
expect(rows.filter((r) => r.isDefault).map((r) => r.id)).toEqual(["group/deepseek-v4-1-flash"]);
expect(rows[1].thinkingOptions?.map((o) => o.id)).toEqual(["low", "medium", "high"]);
expect(rows[1].defaultThinking).toBe("medium");
});
it("takes a relative path from config.toml's folder and ~/ from home, as Codex does", async () => {
writeFileSync(join(codexHome, "config.toml"), REPORTER_CONFIG.replace("$HOME/.codex/magpie-models.json", "magpie-models.json"));
writeFileSync(join(codexHome, "magpie-models.json"), catalog());
expect((await list()).map((r) => r.id)).toEqual(SLUGS);
expect(resolveCatalogPath("~/x/m.json", "/cfg", "/h")).toBe(join("/h", "x", "m.json"));
expect(resolveCatalogPath("${HOME}/m.json", "/cfg", "/h")).toBe(join("/h", "m.json"));
expect(resolveCatalogPath("m.json", "/cfg", "/h")).toBe(join("/cfg", "m.json"));
expect(resolveCatalogPath("$HOMEX/m.json", "/cfg", "/h")).toBe(join("/cfg", "$HOMEX", "m.json"));
});
it("a profile's model_catalog_json wins over the top-level one", () => {
const cfg = parseCodexConfig(REPORTER_CONFIG.replace('model = "group', 'profile = "p"\nmodel = "group') + '\n[profiles.p]\nmodel_catalog_json = "p.json"\n');
expect(cfg.catalogJson).toBe("p.json");
});
it("a missing or broken catalog keeps the configured model", async () => {
writeFileSync(join(codexHome, "config.toml"), REPORTER_CONFIG);
const only = [{ id: "group/deepseek-v4-1-flash", name: "group/deepseek-v4-1-flash", isDefault: true }];
expect(await list()).toEqual(only);
writeFileSync(join(codexHome, "magpie-models.json"), '{"models": [');
expect(await list()).toEqual(only);
writeFileSync(join(codexHome, "magpie-models.json"), '{"models": "nope"}');
expect(await list()).toEqual(only);
});
it("keeps the provider's models = [...] beside the catalog", async () => {
writeFileSync(join(codexHome, "config.toml"), REPORTER_CONFIG + 'models = ["extra/one", "group/glm-5.3-flash"]\n');
writeFileSync(join(codexHome, "magpie-models.json"), catalog());
expect((await list()).map((r) => r.id)).toEqual([...SLUGS, "extra/one"]);
});
});