Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

3.3 KB
Raw Blame
import path from "node:path";
import os from "node:os";
import fs from "node:fs";
import { parse, stringify } from "smol-toml";

import { readPrivateConfigFile } from "../privateConfigFile";

/**
 * Codex CLI config generator — TOML.
 *
 * Modern Codex (Rust CLI, v0.137+) reads `~/.codex/config.toml` exclusively;
 * the YAML `~/.codex/config.yaml` this generator used to emit belongs to the
 * legacy npm codex-cli and is silently ignored by current binaries. The shape
 * below matches the documented OmniRoute block
 * (docs/guides/CODEX-CLI-CONFIGURATION.md → "Ready-to-paste config.toml").
 *
 * Two deliberate safety properties:
 * - The API key is NEVER written into the file. Codex reads it from the env
 *   var named by `env_key` (`OMNIROUTE_API_KEY`), so the generated content is
 *   credential-free and safe to show in dry-run.
 * - An existing `config.toml` is merged conservatively: every unrelated key
 *   the operator already has is preserved; only `model`, `model_provider` and
 *   `[model_providers.omniroute]` are set. An existing file that fails TOML
 *   parsing aborts generation instead of clobbering the operator's config.
 */

export const CODEX_MODEL_PROVIDER_ID = "omniroute";

export function getCodexHome(): string {
  return path.join(os.homedir(), ".codex");
}

/** Path of the legacy YAML config, when one is left over from old generators. */
export function findLegacyCodexYaml(codexHome: string = getCodexHome()): string | null {
  const legacyPath = path.join(codexHome, "config.yaml");
  try {
    return fs.existsSync(legacyPath) ? legacyPath : null;
  } catch {
    return null;
  }
}

export async function generateCodexConfig(options: {
  baseUrl: string;
  apiKey: string;
  model?: string;
  /** Override for tests; production callers use ~/.codex/config.toml. */
  configPath?: string;
}): Promise<string> {
  let base = options.baseUrl;
  let end = base.length;
  while (end > 0 && base[end - 1] === "/") end--;
  base = end < base.length ? base.slice(0, end) : base;
  if (base.endsWith("/v1")) base = base.slice(0, -3);

  const configPath = options.configPath ?? path.join(getCodexHome(), "config.toml");

  let existing: Record<string, unknown> = {};
  if (fs.existsSync(configPath)) {
    const raw = readPrivateConfigFile(configPath);
    try {
      existing = parse(raw) as Record<string, unknown>;
    } catch {
      throw new Error(
        `Existing ${configPath} is not valid TOML; refusing to overwrite it. ` +
          "Fix or move the file, then retry."
      );
    }
  }

  const existingProviders =
    existing.model_providers && typeof existing.model_providers === "object"
      ? (existing.model_providers as Record<string, unknown>)
      : {};

  const merged: Record<string, unknown> = {
    ...existing,
    ...(options.model ? { model: options.model } : {}),
    model_provider: CODEX_MODEL_PROVIDER_ID,
    model_providers: {
      ...existingProviders,
      [CODEX_MODEL_PROVIDER_ID]: {
        name: "OmniRoute",
        base_url: `${base}/v1`,
        env_key: "OMNIROUTE_API_KEY",
        requires_openai_auth: false,
      },
    },
  };

  const header =
    "# Generated by OmniRoute. The API key is read from the OMNIROUTE_API_KEY\n" +
    "# environment variable (env_key) and is never stored in this file.\n";
  return header + stringify(merged) + "\n";
}