import { execFile } from "node:child_process"; import { access } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; import { promisify } from "node:util"; const execute = promisify(execFile); export const DEFAULT_CODEX_MODEL = "gpt-4.1-mini"; let invocation; /** Isolate background content jobs from the desktop model default and unrelated MCP servers. */ export function codexInvocation() { invocation ??= resolveInvocation(); return invocation; } async function resolveInvocation() { let bin = process.env.CODEX_BIN; if (!bin && process.platform === "win32") { const installed = path.join(process.env.LOCALAPPDATA || path.join(homedir(), "AppData", "Local"), "Programs", "OpenAI", "Codex", "bin", "codex.exe"); try { await access(installed); bin = installed; } catch { bin = "codex.exe"; } } bin ||= "codex"; const configArgs = []; try { const { stdout } = await execute(bin, ["mcp", "list", "--json"], { windowsHide: true, timeout: 15_000, maxBuffer: 1024 * 1024 }); const servers = JSON.parse(stdout); if (!Array.isArray(servers)) throw new Error("Invalid MCP list"); for (const server of servers) { if (typeof server.name !== "string" || !/^[A-Za-z0-9_-]+$/.test(server.name)) throw new Error("Unsupported MCP configuration key"); configArgs.push("-c", `mcp_servers.${server.name}.enabled=false`); } } catch { // Fail closed rather than loading external integrations while processing untrusted page content. throw new Error("Cannot inspect Codex MCP configuration; check CODEX_BIN and run codex mcp list --json."); } return { bin, args: ["-m", process.env.CODEX_MODEL || DEFAULT_CODEX_MODEL, ...configArgs] }; }