Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

48.4 KB
Raw Blame
// Codex config.toml 文本编辑工具函数

import type { CodexApiFormat } from "@/types";
import { normalizeTomlText } from "@/utils/textNormalization";
import { parse as parseToml } from "smol-toml";

const isPlainObject = (value: unknown): value is Record<string, any> => {
  return Object.prototype.toString.call(value) === "[object Object]";
};

// ========== Codex base_url utils ==========

const TOML_SECTION_HEADER_PATTERN =
  /^\s*\[{1,2}([^\]\r\n]+)\]{1,2}\s*(?:#.*)?$/;
const TOML_BARE_KEY_PATTERN = /^[A-Za-z0-9_-]+$/;
// 点分键的一段(基本字符串、字面字符串或裸键)及其后的 "." 或结尾
const TOML_DOTTED_KEY_SEGMENT_PATTERN =
  /\s*(?:"((?:\\.|[^"\\\r\n])*)"|'([^'\r\n]*)'|([A-Za-z0-9_-]+))\s*(\.|$)/y;
const TOML_BASE_URL_PATTERN =
  /^\s*base_url\s*=\s*(?:"((?:\\.|[^"\\\r\n])*)"|'([^'\r\n]*)')\s*(?:#.*)?$/;
const TOML_EXPERIMENTAL_BEARER_TOKEN_PATTERN =
  /^\s*experimental_bearer_token\s*=\s*(["'])([^"'\r\n]+)\1\s*(?:#.*)?$/;
const TOML_EXPERIMENTAL_BEARER_TOKEN_REPLACE_PATTERN =
  /^(\s*experimental_bearer_token\s*=\s*)(?:"(?:\\.|[^"\\\r\n])*"|'[^'\r\n]*')(\s*(?:#.*)?)$/;
// 双引号基本字符串(支持 \" \\ 等转义序列,识别 setCodexModelName 自己的
// 转义输出),提取后需反转义。刻意只做整行严格匹配、不做键名宽匹配——
// 宽匹配会误伤多行字符串里长得像赋值的文本;认不出的怪值由用户负责。
const TOML_MODEL_DOUBLE_QUOTED_PATTERN =
  /^\s*model\s*=\s*"((?:[^"\\\r\n]|\\.)*)"\s*(?:#.*)?$/;
// 单引号字面字符串(TOML 语义:无转义)
const TOML_MODEL_SINGLE_QUOTED_PATTERN =
  /^\s*model\s*=\s*'([^'\r\n]*)'\s*(?:#.*)?$/;
const TOML_WIRE_API_PATTERN =
  /^\s*wire_api\s*=\s*(["'])([^"'\r\n]+)\1\s*(?:#.*)?$/;
const TOML_MODEL_PROVIDER_LINE_PATTERN =
  /^\s*model_provider\s*=\s*(["'])([^"'\r\n]+)\1\s*(?:#.*)?$/;
// 任意值(含空串、非字符串)的顶层 model_provider 行:改选路时整行替换,免得写出重复键
const TOML_ANY_MODEL_PROVIDER_LINE_PATTERN = /^\s*model_provider\s*=/;
// 后端写 live 时用的路由表 id(ROUTE_ID)
const CODEX_CUSTOM_ROUTE_ID = "custom";
const TOML_PROVIDER_NAME_PATTERN =
  /^\s*name\s*=\s*(["'])([^"'\r\n]+)\1\s*(?:#.*)?$/;
const TOML_PROVIDER_NAME_REPLACE_PATTERN =
  /^(\s*name\s*=\s*)(?:"(?:\\.|[^"\\\r\n])*"|'[^'\r\n]*')(\s*(?:#.*)?)$/;
// Same list as the backend's CODEX_RESERVED_MODEL_PROVIDER_IDS
// (src-tauri/src/codex_config.rs); tests/config/backendConstants.test.ts checks both.
export const CODEX_RESERVED_MODEL_PROVIDER_IDS = new Set([
  "amazon-bedrock",
  "amazon-bedrock-runtime",
  "openai",
  "ollama",
  "lmstudio",
]);

interface TomlSectionRange {
  bodyEndIndex: number;
  bodyStartIndex: number;
  headerLineIndex: number;
}

interface TomlAssignmentMatch {
  index: number;
  sectionName?: string;
  value: string;
}

const finalizeTomlText = (lines: string[]): string =>
  lines
    .join("\n")
    .replace(/\n{3,}/g, "\n\n")
    .replace(/^\n+/, "");

// 表名的规范写法:能用裸键的段用裸键,其余用基本字符串
const tomlTableName = (...segments: string[]): string =>
  segments
    .map((segment) =>
      TOML_BARE_KEY_PATTERN.test(segment) ? segment : tomlBasicString(segment),
    )
    .join(".");

// `[model_providers."custom"]`、`[ model_providers . custom ]` 与
// `[model_providers.custom]` 是同一张表(#8271),比较表头前先统一成规范写法;
// 认不出的表头原样返回
const normalizeTomlTableName = (header: string): string => {
  const segments: string[] = [];
  let index = 0;
  for (;;) {
    TOML_DOTTED_KEY_SEGMENT_PATTERN.lastIndex = index;
    const match = TOML_DOTTED_KEY_SEGMENT_PATTERN.exec(header);
    if (!match) return header;
    const [, basic, literal, bare, separator] = match;
    segments.push(
      basic !== undefined ? unescapeTomlBasicString(basic) : (literal ?? bare),
    );
    if (separator !== ".") return tomlTableName(...segments);
    index = TOML_DOTTED_KEY_SEGMENT_PATTERN.lastIndex;
  }
};

// 标出以多行字符串(""" 或 ''')内部开头的行。这些行是字符串内容,像表头或赋值也不算:
// 说明文字里的 `[model_providers."custom"]` 示例不能被当成真正的 provider 表。
// 逐字符跟踪字符串和注释状态;单行字符串和注释到行尾为止。
const getTomlMultilineStringLines = (lines: string[]): boolean[] => {
  let delimiter: '"""' | "'''" | undefined;
  return lines.map((line) => {
    const insideString = delimiter !== undefined;
    let index = 0;
    while (index < line.length) {
      if (delimiter) {
        if (delimiter === '"""' && line[index] === "\\") {
          index += 2;
          continue;
        }
        if (line.startsWith(delimiter, index)) {
          // 结束符前最多可以再贴两个引号,它们属于字符串内容
          const quote = delimiter[0];
          let end = index + 3;
          while (end < index + 5 && line[end] === quote) end += 1;
          delimiter = undefined;
          index = end;
          continue;
        }
        index += 1;
        continue;
      }

      const ch = line[index];
      if (ch === "#") break;
      if (line.startsWith('"""', index) || line.startsWith("'''", index)) {
        delimiter = line.startsWith('"""', index) ? '"""' : "'''";
        index += 3;
        continue;
      }
      if (ch === '"') {
        index += 1;
        while (index < line.length && line[index] !== '"') {
          index += line[index] === "\\" ? 2 : 1;
        }
        index += 1;
        continue;
      }
      if (ch === "'") {
        const end = line.indexOf("'", index + 1);
        index = end === -1 ? line.length : end + 1;
        continue;
      }
      index += 1;
    }
    return insideString;
  });
};

const getTomlSectionRange = (
  lines: string[],
  sectionName: string,
): TomlSectionRange | undefined => {
  const targetName = normalizeTomlTableName(sectionName);
  const stringLines = getTomlMultilineStringLines(lines);
  let headerLineIndex = -1;

  for (let index = 0; index < lines.length; index += 1) {
    if (stringLines[index]) continue;
    const match = lines[index].match(TOML_SECTION_HEADER_PATTERN);
    if (!match) {
      continue;
    }

    if (headerLineIndex === -1) {
      if (normalizeTomlTableName(match[1]) === targetName) {
        headerLineIndex = index;
      }
      continue;
    }

    return {
      bodyStartIndex: headerLineIndex + 1,
      bodyEndIndex: index,
      headerLineIndex,
    };
  }

  if (headerLineIndex === -1) {
    return undefined;
  }

  return {
    bodyStartIndex: headerLineIndex + 1,
    bodyEndIndex: lines.length,
    headerLineIndex,
  };
};

const getTopLevelEndIndex = (lines: string[]): number => {
  const stringLines = getTomlMultilineStringLines(lines);
  const firstSectionIndex = lines.findIndex(
    (line, index) =>
      !stringLines[index] && TOML_SECTION_HEADER_PATTERN.test(line),
  );
  return firstSectionIndex === -1 ? lines.length : firstSectionIndex;
};

const getTomlSectionInsertIndex = (
  lines: string[],
  sectionRange: TomlSectionRange,
): number => {
  let insertIndex = sectionRange.bodyEndIndex;
  while (
    insertIndex > sectionRange.bodyStartIndex &&
    lines[insertIndex - 1].trim() === ""
  ) {
    insertIndex -= 1;
  }
  return insertIndex;
};

const getCodexModelProviderName = (configText: string): string | undefined => {
  const normalized = normalizeTomlText(configText);
  try {
    const parsed = parseToml(normalized) as Record<string, any>;
    const providerName =
      typeof parsed.model_provider === "string"
        ? parsed.model_provider.trim()
        : undefined;
    if (providerName) return providerName;
  } catch {
    // Fall back to a top-level line scan while the user is editing invalid TOML.
  }

  const lines = normalized.split("\n");
  const index = getTopLevelModelProviderLineIndex(lines);
  if (index === -1) return undefined;
  const match = lines[index].match(TOML_MODEL_PROVIDER_LINE_PATTERN);
  const providerName = match?.[2]?.trim();
  return providerName || undefined;
};

const isCodexUnifiedSessionProjection = (configText: string): boolean => {
  try {
    const parsed = parseToml(normalizeTomlText(configText)) as Record<
      string,
      any
    >;
    const custom = parsed.model_providers?.custom;
    return (
      parsed.model_provider === "custom" &&
      isPlainObject(custom) &&
      Object.keys(custom).length === 4 &&
      custom.name === "OpenAI" &&
      custom.requires_openai_auth === true &&
      custom.supports_websockets === true &&
      custom.wire_api === "responses"
    );
  } catch {
    return false;
  }
};

export const hasExplicitNonOpenAiCodexModelProvider = (
  configText: string | undefined | null,
): boolean => {
  if (typeof configText !== "string") return false;
  if (isCodexUnifiedSessionProjection(configText)) return false;
  const providerName = getCodexModelProviderName(configText);
  // Exact match, mirroring the backend: Codex's built-in lookup is
  // case-sensitive, so `OpenAI` routes to a custom table — a third-party
  // upstream, not the official provider.
  return Boolean(providerName && providerName.trim() !== "openai");
};

const getCodexProviderSectionName = (
  configText: string,
): string | undefined => {
  const providerName = getCodexModelProviderName(configText);
  return providerName
    ? tomlTableName("model_providers", providerName)
    : undefined;
};

const isCustomCodexModelProviderId = (providerName: string): boolean => {
  // Exact match, mirroring upstream Codex and the backend predicate: the
  // built-in provider lookup is case-sensitive, so "OpenAI" etc. are
  // legitimate custom ids whose tables carry the bearer token.
  const id = providerName.trim();
  return Boolean(id) && !CODEX_RESERVED_MODEL_PROVIDER_IDS.has(id);
};

const getCodexCustomProviderSectionName = (
  configText: string,
): string | undefined => {
  const providerName = getCodexModelProviderName(configText);
  return providerName && isCustomCodexModelProviderId(providerName)
    ? tomlTableName("model_providers", providerName)
    : undefined;
};

const findTomlAssignmentInRange = (
  lines: string[],
  pattern: RegExp,
  startIndex: number,
  endIndex: number,
  sectionName?: string,
): TomlAssignmentMatch | undefined => {
  const stringLines = getTomlMultilineStringLines(lines);
  for (let index = startIndex; index < endIndex; index += 1) {
    if (stringLines[index]) continue;
    const match = lines[index].match(pattern);
    const value = match?.[2] ?? match?.[1];
    if (value) {
      return {
        index,
        sectionName,
        value,
      };
    }
  }

  return undefined;
};

const findTomlAssignmentsInRange = (
  lines: string[],
  pattern: RegExp,
  startIndex: number,
  endIndex: number,
  sectionName?: string,
): TomlAssignmentMatch[] => {
  const matches: TomlAssignmentMatch[] = [];
  const stringLines = getTomlMultilineStringLines(lines);

  for (let index = startIndex; index < endIndex; index += 1) {
    if (stringLines[index]) continue;
    const match = lines[index].match(pattern);
    const value = match?.[2] ?? match?.[1];
    if (value) {
      matches.push({ index, sectionName, value });
    }
  }

  return matches;
};

const findTomlLineInRange = (
  lines: string[],
  pattern: RegExp,
  startIndex: number,
  endIndex: number,
): number => {
  const stringLines = getTomlMultilineStringLines(lines);
  for (let index = startIndex; index < endIndex; index += 1) {
    if (!stringLines[index] && pattern.test(lines[index])) {
      return index;
    }
  }

  return -1;
};

const findTomlAssignments = (
  lines: string[],
  pattern: RegExp,
): TomlAssignmentMatch[] => {
  const assignments: TomlAssignmentMatch[] = [];
  let currentSectionName: string | undefined;
  const stringLines = getTomlMultilineStringLines(lines);

  lines.forEach((line, index) => {
    if (stringLines[index]) return;
    const sectionMatch = line.match(TOML_SECTION_HEADER_PATTERN);
    if (sectionMatch) {
      currentSectionName = normalizeTomlTableName(sectionMatch[1]);
      return;
    }

    const match = line.match(pattern);
    const value = match?.[2] ?? match?.[1];
    if (!value) {
      return;
    }

    assignments.push({
      index,
      sectionName: currentSectionName,
      value,
    });
  });

  return assignments;
};

const isMcpServerSection = (sectionName?: string): boolean =>
  sectionName === "mcp_servers" ||
  sectionName?.startsWith("mcp_servers.") === true;

const isOtherProviderSection = (
  sectionName: string | undefined,
  targetSectionName: string | undefined,
): boolean =>
  Boolean(
    sectionName &&
      sectionName !== targetSectionName &&
      (sectionName === "model_providers" ||
        sectionName.startsWith("model_providers.")),
  );

const getRecoverableBaseUrlAssignments = (
  assignments: TomlAssignmentMatch[],
  targetSectionName: string | undefined,
): TomlAssignmentMatch[] =>
  assignments.filter(
    ({ sectionName }) =>
      sectionName !== targetSectionName &&
      !isMcpServerSection(sectionName) &&
      !isOtherProviderSection(sectionName, targetSectionName),
  );

const getRecoverableCodexProviderAssignments = getRecoverableBaseUrlAssignments;

const getTopLevelModelProviderLineIndex = (lines: string[]): number => {
  return findTomlLineInRange(
    lines,
    TOML_MODEL_PROVIDER_LINE_PATTERN,
    0,
    getTopLevelEndIndex(lines),
  );
};

const TOML_BASIC_STRING_ESCAPES: Record<string, string> = {
  '"': '\\"',
  "\\": "\\\\",
  "\b": "\\b",
  "\t": "\\t",
  "\n": "\\n",
  "\f": "\\f",
  "\r": "\\r",
};

const escapeTomlBasicString = (value: string): string =>
  value.replace(/["\\\u0000-\u001f]/g, (ch) => {
    const escaped = TOML_BASIC_STRING_ESCAPES[ch];
    if (escaped) return escaped;
    return `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`;
  });

const tomlBasicString = (value: string): string =>
  `"${escapeTomlBasicString(value)}"`;

const TOML_BASIC_STRING_UNESCAPES: Record<string, string> = {
  '"': '"',
  "\\": "\\",
  b: "\b",
  t: "\t",
  n: "\n",
  f: "\f",
  r: "\r",
};

// escapeTomlBasicString 的逆运算;未知转义序列原样保留
const unescapeTomlBasicString = (value: string): string =>
  value.replace(
    /\\(?:u([0-9a-fA-F]{4})|U([0-9a-fA-F]{8})|(.))/g,
    (match, u4, u8, ch) => {
      if (u4 || u8) return String.fromCodePoint(parseInt(u4 || u8, 16));
      return TOML_BASIC_STRING_UNESCAPES[ch] ?? match;
    },
  );

// 后端 codex_config::CHAT_WIRE_APIS / ANTHROPIC_WIRE_APIS 的前端副本,
// tests/config/backendConstants.test.ts 核对两边一致。
export const CODEX_CHAT_WIRE_API_VALUES: readonly string[] = [
  "chat",
  "chat_completions",
  "chat-completions",
  "openai_chat",
  "openai-chat",
  "openai_chat_completions",
];

export const CODEX_ANTHROPIC_WIRE_API_VALUES: readonly string[] = [
  "anthropic",
  "anthropic_messages",
  "anthropic-messages",
  "messages",
  "claude",
];

// 判断给定的 wire_api 字符串是否表示 Codex 的 Chat Completions 协议
export const isCodexChatWireApi = (
  wireApi: string | undefined | null,
): boolean =>
  CODEX_CHAT_WIRE_API_VALUES.includes((wireApi ?? "").trim().toLowerCase());

export const isCodexAnthropicWireApi = (
  wireApi: string | undefined | null,
): boolean =>
  CODEX_ANTHROPIC_WIRE_API_VALUES.includes(
    (wireApi ?? "").trim().toLowerCase(),
  );

export const codexApiFormatFromWireApi = (
  wireApi: string | undefined | null,
): CodexApiFormat | undefined => {
  if (isCodexChatWireApi(wireApi)) return "openai_chat";
  if (isCodexAnthropicWireApi(wireApi)) return "anthropic";
  switch ((wireApi ?? "").trim().toLowerCase()) {
    case "responses":
    case "openai_responses":
    case "openai-responses":
      return "openai_responses";
    default:
      return undefined;
  }
};

// 从 Codex 的 TOML 配置文本中提取 wire_api(支持单/双引号)
export const extractCodexWireApi = (
  configText: string | undefined | null,
): string | undefined => {
  try {
    const raw = typeof configText === "string" ? configText : "";
    const text = normalizeTomlText(raw);
    if (!text) return undefined;

    const lines = text.split("\n");
    const targetSectionName = getCodexProviderSectionName(text);

    if (targetSectionName) {
      const sectionRange = getTomlSectionRange(lines, targetSectionName);
      if (sectionRange) {
        const match = findTomlAssignmentInRange(
          lines,
          TOML_WIRE_API_PATTERN,
          sectionRange.bodyStartIndex,
          sectionRange.bodyEndIndex,
          targetSectionName,
        );
        if (match?.value) {
          return match.value;
        }
      }
    }

    const topLevelMatch = findTomlAssignmentInRange(
      lines,
      TOML_WIRE_API_PATTERN,
      0,
      getTopLevelEndIndex(lines),
    );
    if (topLevelMatch?.value) {
      return topLevelMatch.value;
    }

    const fallbackAssignments = getRecoverableCodexProviderAssignments(
      findTomlAssignments(lines, TOML_WIRE_API_PATTERN),
      targetSectionName,
    );
    return fallbackAssignments.length === 1
      ? fallbackAssignments[0].value
      : undefined;
  } catch {
    return undefined;
  }
};

// 在 Codex 的 TOML 配置文本中写入或更新 wire_api 字段
export const setCodexWireApi = (
  configText: string,
  wireApi: "responses" | "chat",
): string => {
  const normalizedText = normalizeTomlText(configText);
  const lines = normalizedText ? normalizedText.split("\n") : [];
  const targetSectionName = getCodexProviderSectionName(normalizedText);
  const replacementLine = `wire_api = "${wireApi}"`;
  const allAssignments = findTomlAssignments(lines, TOML_WIRE_API_PATTERN);
  const recoverableAssignments = getRecoverableCodexProviderAssignments(
    allAssignments,
    targetSectionName,
  );

  if (targetSectionName) {
    let targetSectionRange = getTomlSectionRange(lines, targetSectionName);
    const targetMatch = targetSectionRange
      ? findTomlAssignmentInRange(
          lines,
          TOML_WIRE_API_PATTERN,
          targetSectionRange.bodyStartIndex,
          targetSectionRange.bodyEndIndex,
          targetSectionName,
        )
      : undefined;

    if (targetMatch) {
      lines[targetMatch.index] = replacementLine;
      return finalizeTomlText(lines);
    }

    if (recoverableAssignments.length === 1) {
      lines.splice(recoverableAssignments[0].index, 1);
      targetSectionRange = getTomlSectionRange(lines, targetSectionName);
    }

    if (targetSectionRange) {
      const insertIndex = getTomlSectionInsertIndex(lines, targetSectionRange);
      lines.splice(insertIndex, 0, replacementLine);
      return finalizeTomlText(lines);
    }

    if (lines.length > 0 && lines[lines.length - 1].trim() !== "") {
      lines.push("");
    }
    lines.push(`[${targetSectionName}]`, replacementLine);
    return finalizeTomlText(lines);
  }

  const topLevelEndIndex = getTopLevelEndIndex(lines);
  const topLevelMatch = findTomlAssignmentInRange(
    lines,
    TOML_WIRE_API_PATTERN,
    0,
    topLevelEndIndex,
  );
  if (topLevelMatch) {
    lines[topLevelMatch.index] = replacementLine;
    return finalizeTomlText(lines);
  }

  const modelProviderIndex = getTopLevelModelProviderLineIndex(lines);
  if (modelProviderIndex !== -1) {
    lines.splice(modelProviderIndex + 1, 0, replacementLine);
    return finalizeTomlText(lines);
  }

  if (lines.length === 0) {
    return `${replacementLine}\n`;
  }

  lines.splice(topLevelEndIndex, 0, replacementLine);
  return finalizeTomlText(lines);
};

export const isCodexRemoteCompactionEnabled = (
  configText: string | undefined | null,
): boolean => {
  try {
    const raw = typeof configText === "string" ? configText : "";
    const text = normalizeTomlText(raw);
    if (!text) return false;

    try {
      const parsed = parseToml(text) as Record<string, any>;
      const providerId =
        typeof parsed.model_provider === "string"
          ? parsed.model_provider.trim()
          : "";
      if (!providerId || !isCustomCodexModelProviderId(providerId)) {
        return false;
      }

      return parsed.model_providers?.[providerId]?.name === "OpenAI";
    } catch {
      // Fall back to line scanning while the user is editing invalid TOML.
    }

    const lines = text.split("\n");
    const targetSectionName = getCodexCustomProviderSectionName(text);
    if (!targetSectionName) return false;

    const sectionRange = getTomlSectionRange(lines, targetSectionName);
    if (!sectionRange) return false;

    const nameAssignment = findTomlAssignmentInRange(
      lines,
      TOML_PROVIDER_NAME_PATTERN,
      sectionRange.bodyStartIndex,
      sectionRange.bodyEndIndex,
      targetSectionName,
    );

    return nameAssignment?.value === "OpenAI";
  } catch {
    return false;
  }
};

export const setCodexRemoteCompaction = (
  configText: string,
  enabled: boolean,
  fallbackProviderName?: string,
): string => {
  const normalizedText = normalizeTomlText(configText);
  const lines = normalizedText ? normalizedText.split("\n") : [];
  const targetSectionName = getCodexCustomProviderSectionName(normalizedText);

  if (!targetSectionName) {
    return normalizedText;
  }

  let targetSectionRange = getTomlSectionRange(lines, targetSectionName);
  const replacementName = enabled
    ? "OpenAI"
    : fallbackProviderName?.trim() ||
      getCodexModelProviderName(normalizedText) ||
      "custom";
  const replacementLine = `name = ${tomlBasicString(replacementName)}`;

  if (targetSectionRange) {
    const nameLine = findTomlLineInRange(
      lines,
      TOML_PROVIDER_NAME_REPLACE_PATTERN,
      targetSectionRange.bodyStartIndex,
      targetSectionRange.bodyEndIndex,
    );

    if (nameLine !== -1) {
      lines[nameLine] = lines[nameLine].replace(
        TOML_PROVIDER_NAME_REPLACE_PATTERN,
        `$1${tomlBasicString(replacementName)}$2`,
      );
      return finalizeTomlText(lines);
    }

    lines.splice(
      getTomlSectionInsertIndex(lines, targetSectionRange),
      0,
      replacementLine,
    );
    return finalizeTomlText(lines);
  }

  if (!enabled) return normalizedText;

  if (lines.length > 0 && lines[lines.length - 1].trim() !== "") {
    lines.push("");
  }

  lines.push(`[${targetSectionName}]`, replacementLine);
  targetSectionRange = getTomlSectionRange(lines, targetSectionName);
  return targetSectionRange ? finalizeTomlText(lines) : normalizedText;
};

// 从 Codex 的 TOML 配置文本中提取 base_url(支持单/双引号)
export const extractCodexBaseUrl = (
  configText: string | undefined | null,
): string | undefined => {
  try {
    const raw = typeof configText === "string" ? configText : "";
    const text = normalizeTomlText(raw);
    if (!text) return undefined;

    const lines = text.split("\n");
    const targetSectionName = getCodexProviderSectionName(text);

    if (targetSectionName) {
      const sectionRange = getTomlSectionRange(lines, targetSectionName);
      if (sectionRange) {
        const match = findTomlAssignmentInRange(
          lines,
          TOML_BASE_URL_PATTERN,
          sectionRange.bodyStartIndex,
          sectionRange.bodyEndIndex,
          targetSectionName,
        );
        if (match?.value) {
          return match.value;
        }
      }
    }

    const topLevelMatch = findTomlAssignmentInRange(
      lines,
      TOML_BASE_URL_PATTERN,
      0,
      getTopLevelEndIndex(lines),
    );
    if (topLevelMatch?.value) {
      return topLevelMatch.value;
    }

    const fallbackAssignments = getRecoverableBaseUrlAssignments(
      findTomlAssignments(lines, TOML_BASE_URL_PATTERN),
      targetSectionName,
    );
    return fallbackAssignments.length === 1
      ? fallbackAssignments[0].value
      : undefined;
  } catch {
    return undefined;
  }
};

// 从 Codex 的 TOML 配置文本中提取 experimental_bearer_token(兼容 Mobile 模式)
export const extractCodexExperimentalBearerToken = (
  configText: string | undefined | null,
): string | undefined => {
  try {
    const raw = typeof configText === "string" ? configText : "";
    const text = normalizeTomlText(raw);
    if (!text) return undefined;

    try {
      const parsed = parseToml(text) as Record<string, any>;
      const providerName =
        typeof parsed.model_provider === "string"
          ? parsed.model_provider.trim()
          : undefined;
      const providerToken =
        providerName &&
        isCustomCodexModelProviderId(providerName) &&
        parsed.model_providers &&
        typeof parsed.model_providers === "object" &&
        typeof parsed.model_providers[providerName]
          ?.experimental_bearer_token === "string"
          ? parsed.model_providers[
              providerName
            ].experimental_bearer_token.trim()
          : undefined;
      if (providerToken) return providerToken;
      const topLevelToken =
        typeof parsed.experimental_bearer_token === "string"
          ? parsed.experimental_bearer_token.trim()
          : undefined;
      if (topLevelToken) return topLevelToken;
    } catch {
      // Fall back to the line scanner for partially edited TOML.
    }

    const lines = text.split("\n");
    const targetSectionName = getCodexCustomProviderSectionName(text);

    if (targetSectionName) {
      const sectionRange = getTomlSectionRange(lines, targetSectionName);
      if (sectionRange) {
        const match = findTomlAssignmentInRange(
          lines,
          TOML_EXPERIMENTAL_BEARER_TOKEN_PATTERN,
          sectionRange.bodyStartIndex,
          sectionRange.bodyEndIndex,
          targetSectionName,
        );
        if (match?.value) {
          return match.value;
        }
      }
    }

    const topLevelMatch = findTomlAssignmentInRange(
      lines,
      TOML_EXPERIMENTAL_BEARER_TOKEN_PATTERN,
      0,
      getTopLevelEndIndex(lines),
    );
    return topLevelMatch?.value;
  } catch {
    return undefined;
  }
};

// 同步更新 Codex config.toml 中已有的 experimental_bearer_token
// 仅修改已存在的条目, 不主动新增——避免破坏未使用 Mobile 兼容模式的普通 third-party 配置
// token 为空时删除该行 (让用户能真正清空 API key, 而不是被 pickCodexApiKey 的 fallback 又填回去)
export const updateCodexExperimentalBearerToken = (
  configText: string,
  token: string,
): string => {
  const normalizedText = normalizeTomlText(configText);
  if (
    !normalizedText ||
    !normalizedText.includes("experimental_bearer_token")
  ) {
    return configText;
  }

  const lines = normalizedText.split("\n");
  const targetSectionName = getCodexCustomProviderSectionName(normalizedText);

  let tokenLineIndex = -1;
  if (targetSectionName) {
    const sectionRange = getTomlSectionRange(lines, targetSectionName);
    if (sectionRange) {
      const index = findTomlLineInRange(
        lines,
        TOML_EXPERIMENTAL_BEARER_TOKEN_REPLACE_PATTERN,
        sectionRange.bodyStartIndex,
        sectionRange.bodyEndIndex,
      );
      if (index !== -1) tokenLineIndex = index;
    }
  }
  if (tokenLineIndex === -1) {
    const topLevelIndex = findTomlLineInRange(
      lines,
      TOML_EXPERIMENTAL_BEARER_TOKEN_REPLACE_PATTERN,
      0,
      getTopLevelEndIndex(lines),
    );
    if (topLevelIndex !== -1) tokenLineIndex = topLevelIndex;
  }

  if (tokenLineIndex === -1) return configText;

  const trimmed = token.trim();
  if (!trimmed) {
    lines.splice(tokenLineIndex, 1);
  } else {
    const escaped = escapeTomlBasicString(trimmed);
    const existingLine = lines[tokenLineIndex];
    lines[tokenLineIndex] = TOML_EXPERIMENTAL_BEARER_TOKEN_REPLACE_PATTERN.test(
      existingLine,
    )
      ? existingLine.replace(
          TOML_EXPERIMENTAL_BEARER_TOKEN_REPLACE_PATTERN,
          `$1"${escaped}"$2`,
        )
      : `experimental_bearer_token = "${escaped}"`;
  }
  return finalizeTomlText(lines);
};

// 从任一应用的 settingsConfig 中取出请求地址:各应用存法不同(env 变量 / baseUrl /
// base_url / options.baseURL / models[].baseUrl / Codex 风格 TOML),按已知形态依次找
export const extractProviderBaseUrl = (
  settingsConfig: unknown,
): string | undefined => {
  if (!settingsConfig || typeof settingsConfig !== "object") return undefined;
  const object = settingsConfig as Record<string, any>;

  const envBase =
    object.env?.ANTHROPIC_BASE_URL || object.env?.GOOGLE_GEMINI_BASE_URL;
  if (typeof envBase === "string" && envBase.trim()) {
    return envBase;
  }

  const directBaseUrl =
    // Kimi 的 provider.base_url;Copilot CLI 自带模型卡的 provider.baseUrl
    (isPlainObject(object.provider)
      ? object.provider.base_url || object.provider.baseUrl
      : undefined) ||
    object.baseUrl ||
    object.base_url ||
    object.options?.baseURL ||
    // WorkBuddy models.json: full endpoint URL shared by the provider's models
    object.url ||
    (Array.isArray(object.models)
      ? object.models.find(
          (model: unknown) =>
            model &&
            typeof model === "object" &&
            typeof (model as Record<string, unknown>).baseUrl === "string",
        )?.baseUrl
      : undefined);
  if (typeof directBaseUrl === "string" && directBaseUrl.trim()) {
    return directBaseUrl;
  }

  if (typeof object.config === "string" && object.config.includes("base_url")) {
    return extractCodexBaseUrl(object.config) || undefined;
  }

  return undefined;
};

// 解析后的 TOML 值转成可比较的普通值:键排序,日期按文本比
const comparableTomlValue = (value: unknown): unknown => {
  if (value instanceof Date) return { $date: String(value) };
  if (Array.isArray(value)) return value.map(comparableTomlValue);
  if (value && typeof value === "object") {
    return Object.fromEntries(
      Object.keys(value)
        .sort()
        .map((key) => [
          key,
          comparableTomlValue((value as Record<string, unknown>)[key]),
        ]),
    );
  }
  return value;
};

// 没有选路时把地址写进选中的 custom 表:Codex 不认顶层 base_url(#8039)。逐行改写认不全
// TOML 的写法(内联表、带注释的表头、多行字符串里像赋值的行),所以改完按解析结果核对:
// 除了选路、地址和收进表里的顶层 wire_api,其余值都没变才采用;否则返回 undefined,由
// 调用方照旧写顶层 base_url(后端会把这种旧形态归一成 custom 表)。
const moveCodexBaseUrlIntoCustomTable = (
  text: string,
  url: string,
): string | undefined => {
  let before: Record<string, unknown>;
  try {
    before = parseToml(text) as Record<string, unknown>;
  } catch {
    return undefined;
  }

  const lines = text ? text.split("\n") : [];
  const topLevelEndIndex = getTopLevelEndIndex(lines);
  const topLevelWireApi = findTomlAssignmentInRange(
    lines,
    TOML_WIRE_API_PATTERN,
    0,
    topLevelEndIndex,
  )?.value;
  for (let index = topLevelEndIndex - 1; index >= 0; index -= 1) {
    if (
      TOML_BASE_URL_PATTERN.test(lines[index]) ||
      TOML_WIRE_API_PATTERN.test(lines[index]) ||
      TOML_ANY_MODEL_PROVIDER_LINE_PATTERN.test(lines[index])
    ) {
      lines.splice(index, 1);
    }
  }
  lines.unshift(`model_provider = "${CODEX_CUSTOM_ROUTE_ID}"`);

  const sectionName = `model_providers.${CODEX_CUSTOM_ROUTE_ID}`;
  const hadSection = Boolean(getTomlSectionRange(lines, sectionName));
  if (!hadSection) {
    if (lines[lines.length - 1].trim() !== "") {
      lines.push("");
    }
    lines.push(
      `[${sectionName}]`,
      `name = "${CODEX_CUSTOM_ROUTE_ID}"`,
      `wire_api = ${tomlBasicString(topLevelWireApi ?? "responses")}`,
    );
  }
  const candidate = setCodexBaseUrl(finalizeTomlText(lines), url);

  let after: unknown;
  try {
    after = parseToml(candidate);
  } catch {
    return undefined;
  }
  const expected = comparableTomlValue(before) as Record<string, any>;
  delete expected.base_url;
  delete expected.wire_api;
  expected.model_provider = CODEX_CUSTOM_ROUTE_ID;
  expected.model_providers ??= {};
  if (!hadSection) {
    expected.model_providers[CODEX_CUSTOM_ROUTE_ID] = {
      name: CODEX_CUSTOM_ROUTE_ID,
      wire_api: topLevelWireApi ?? "responses",
    };
  }
  if (typeof expected.model_providers[CODEX_CUSTOM_ROUTE_ID] !== "object") {
    return undefined;
  }
  expected.model_providers[CODEX_CUSTOM_ROUTE_ID].base_url = url;
  return JSON.stringify(comparableTomlValue(expected)) ===
    JSON.stringify(comparableTomlValue(after))
    ? candidate
    : undefined;
};

// 在 Codex 的 TOML 配置文本中写入或更新 base_url 字段
export const setCodexBaseUrl = (
  configText: string,
  baseUrl: string,
): string => {
  const trimmed = baseUrl.trim();
  const normalizedText = normalizeTomlText(configText);
  const lines = normalizedText ? normalizedText.split("\n") : [];
  const targetSectionName = getCodexProviderSectionName(normalizedText);
  const allAssignments = findTomlAssignments(lines, TOML_BASE_URL_PATTERN);
  const recoverableAssignments = getRecoverableBaseUrlAssignments(
    allAssignments,
    targetSectionName,
  );

  if (!trimmed) {
    if (!normalizedText) return normalizedText;

    if (targetSectionName) {
      const sectionRange = getTomlSectionRange(lines, targetSectionName);
      const targetMatches = sectionRange
        ? findTomlAssignmentsInRange(
            lines,
            TOML_BASE_URL_PATTERN,
            sectionRange.bodyStartIndex,
            sectionRange.bodyEndIndex,
            targetSectionName,
          )
        : [];

      if (targetMatches.length > 0) {
        for (const match of [...targetMatches].reverse()) {
          lines.splice(match.index, 1);
        }
        return finalizeTomlText(lines);
      }
    }

    if (recoverableAssignments.length === 1) {
      lines.splice(recoverableAssignments[0].index, 1);
      return finalizeTomlText(lines);
    }

    return finalizeTomlText(lines);
  }

  const normalizedUrl = trimmed.replace(/\s+/g, "");
  const replacementLine = `base_url = ${tomlBasicString(normalizedUrl)}`;

  if (targetSectionName) {
    let targetSectionRange = getTomlSectionRange(lines, targetSectionName);
    const targetMatches = targetSectionRange
      ? findTomlAssignmentsInRange(
          lines,
          TOML_BASE_URL_PATTERN,
          targetSectionRange.bodyStartIndex,
          targetSectionRange.bodyEndIndex,
          targetSectionName,
        )
      : [];

    if (targetMatches.length > 0) {
      const [firstMatch, ...duplicateMatches] = targetMatches;
      lines[firstMatch.index] = replacementLine;
      for (const match of [...duplicateMatches].reverse()) {
        lines.splice(match.index, 1);
      }
      return finalizeTomlText(lines);
    }

    if (recoverableAssignments.length === 1) {
      lines.splice(recoverableAssignments[0].index, 1);
      targetSectionRange = getTomlSectionRange(lines, targetSectionName);
    }

    if (targetSectionRange) {
      const insertIndex = getTomlSectionInsertIndex(lines, targetSectionRange);
      lines.splice(insertIndex, 0, replacementLine);
      return finalizeTomlText(lines);
    }

    if (lines.length > 0 && lines[lines.length - 1].trim() !== "") {
      lines.push("");
    }
    lines.push(`[${targetSectionName}]`, replacementLine);
    return finalizeTomlText(lines);
  }

  const moved = moveCodexBaseUrlIntoCustomTable(normalizedText, normalizedUrl);
  if (moved !== undefined) return moved;

  const topLevelEndIndex = getTopLevelEndIndex(lines);
  const topLevelMatches = findTomlAssignmentsInRange(
    lines,
    TOML_BASE_URL_PATTERN,
    0,
    topLevelEndIndex,
  );
  if (topLevelMatches.length > 0) {
    const [firstMatch, ...duplicateMatches] = topLevelMatches;
    lines[firstMatch.index] = replacementLine;
    for (const match of [...duplicateMatches].reverse()) {
      lines.splice(match.index, 1);
    }
    return finalizeTomlText(lines);
  }

  const modelProviderIndex = getTopLevelModelProviderLineIndex(lines);
  if (modelProviderIndex !== -1) {
    lines.splice(modelProviderIndex + 1, 0, replacementLine);
    return finalizeTomlText(lines);
  }

  if (lines.length === 0) {
    return `${replacementLine}\n`;
  }

  const insertIndex = topLevelEndIndex;
  lines.splice(insertIndex, 0, replacementLine);
  return finalizeTomlText(lines);
};

// ========== Codex model name utils ==========

// 顶层范围内第一个能被严格模式识别的 model 行;-1 表示没有
const findTopLevelModelLineIndex = (
  lines: string[],
  topLevelEndIndex: number,
): number => {
  for (let i = 0; i < topLevelEndIndex; i += 1) {
    if (
      TOML_MODEL_DOUBLE_QUOTED_PATTERN.test(lines[i]) ||
      TOML_MODEL_SINGLE_QUOTED_PATTERN.test(lines[i])
    ) {
      return i;
    }
  }
  return -1;
};

// 从 Codex 的 TOML 配置文本中提取 model 字段(支持单/双引号;
// 双引号串按 TOML 基本字符串反转义,保证与 setCodexModelName round-trip)
export const extractCodexModelName = (
  configText: string | undefined | null,
): string | undefined => {
  try {
    const raw = typeof configText === "string" ? configText : "";
    const text = normalizeTomlText(raw);
    if (!text) return undefined;
    const lines = text.split("\n");
    const topLevelEndIndex = getTopLevelEndIndex(lines);
    for (let i = 0; i < topLevelEndIndex; i += 1) {
      const doubleQuoted = lines[i].match(TOML_MODEL_DOUBLE_QUOTED_PATTERN);
      if (doubleQuoted) return unescapeTomlBasicString(doubleQuoted[1]);
      const singleQuoted = lines[i].match(TOML_MODEL_SINGLE_QUOTED_PATTERN);
      if (singleQuoted) return singleQuoted[1];
    }
    return undefined;
  } catch {
    return undefined;
  }
};

// 在 Codex 的 TOML 配置文本中写入或更新 model 字段
export const setCodexModelName = (
  configText: string,
  modelName: string,
): string => {
  const trimmed = modelName.trim();
  const normalizedText = normalizeTomlText(configText);
  const lines = normalizedText ? normalizedText.split("\n") : [];
  const topLevelEndIndex = getTopLevelEndIndex(lines);
  const modelLineIndex = findTopLevelModelLineIndex(lines, topLevelEndIndex);

  if (!trimmed) {
    if (!normalizedText) return normalizedText;
    if (modelLineIndex !== -1) {
      lines.splice(modelLineIndex, 1);
    }
    return finalizeTomlText(lines);
  }

  // 模型名可能来自远端 /models 响应(下拉选择),必须转义——裸插值会让
  // 含引号/控制字符的 id 破坏甚至注入 config.toml(如伪造 [mcp_servers.*])
  const replacementLine = `model = ${tomlBasicString(trimmed)}`;
  if (modelLineIndex !== -1) {
    lines[modelLineIndex] = replacementLine;
    return finalizeTomlText(lines);
  }

  const modelProviderIndex = getTopLevelModelProviderLineIndex(lines);
  if (modelProviderIndex !== -1) {
    lines.splice(modelProviderIndex + 1, 0, replacementLine);
    return finalizeTomlText(lines);
  }

  if (lines.length === 0) {
    return `${replacementLine}\n`;
  }

  lines.splice(topLevelEndIndex, 0, replacementLine);
  return finalizeTomlText(lines);
};

// ========== Codex [agents] subagent defaults ==========

// 子代理的默认模型和推理强度(Codex 的 `[agents]` 表)。后端把这两个键当关键字段,随供应商
// 切换;聚合模式下不写行里的,改用聚合页签「聚合设置」里的设备级设置。
export type CodexAgentsStringKey =
  | "default_subagent_model"
  | "default_subagent_reasoning_effort";

const CODEX_AGENTS_SECTION = "agents";

// 键的三种等价写法:`key`、`"key"`、`'key'`。
const tomlKeySource = (key: string): string => `(?:${key}|"${key}"|'${key}')`;

const tomlStringAssignmentPatterns = (key: string) => {
  const keySource = tomlKeySource(key);
  return {
    doubleQuoted: new RegExp(
      `^\\s*${keySource}\\s*=\\s*"((?:[^"\\\\\\r\\n]|\\\\.)*)"\\s*(?:#.*)?$`,
    ),
    singleQuoted: new RegExp(
      `^\\s*${keySource}\\s*=\\s*'([^'\\r\\n]*)'\\s*(?:#.*)?$`,
    ),
    anyValue: new RegExp(`^\\s*${keySource}\\s*=`),
  };
};

export const extractCodexAgentsString = (
  configText: string | undefined | null,
  key: CodexAgentsStringKey,
): string | undefined => {
  const text = normalizeTomlText(
    typeof configText === "string" ? configText : "",
  );
  if (!text) return undefined;
  try {
    const value = (parseToml(text) as Record<string, any>)[
      CODEX_AGENTS_SECTION
    ]?.[key];
    return typeof value === "string" ? value : undefined;
  } catch {
    // 编辑中的 TOML 解析不了时按行在 [agents] 里找。
  }
  const lines = text.split("\n");
  const range = getTomlSectionRange(lines, CODEX_AGENTS_SECTION);
  if (!range) return undefined;
  const patterns = tomlStringAssignmentPatterns(key);
  for (let i = range.bodyStartIndex; i < range.bodyEndIndex; i += 1) {
    const doubleQuoted = lines[i].match(patterns.doubleQuoted);
    if (doubleQuoted) return unescapeTomlBasicString(doubleQuoted[1]);
    const singleQuoted = lines[i].match(patterns.singleQuoted);
    if (singleQuoted) return singleQuoted[1];
  }
  return undefined;
};

// 在 `[agents]` 里写入一个键(valueText 为 undefined 时删除),并删掉 dropKeys 里的同义写法;
// 删完表里没别的就连表头一起删。用户把 agents 写成行内表或点号键时按行改不了:改完解析失败
// 就原样返回。
const writeCodexAgentsLine = (
  configText: string,
  key: string,
  valueText: string | undefined,
  dropKeys: string[] = [],
): string => {
  const normalizedText = normalizeTomlText(configText);
  const lines = normalizedText ? normalizedText.split("\n") : [];
  const range = getTomlSectionRange(lines, CODEX_AGENTS_SECTION);
  const replacementLine = `${key} = ${valueText}`;

  if (range) {
    let bodyEndIndex = range.bodyEndIndex;
    const findLine = (name: string) =>
      findTomlLineInRange(
        lines,
        tomlStringAssignmentPatterns(name).anyValue,
        range.bodyStartIndex,
        bodyEndIndex,
      );
    let removed = false;
    for (const name of valueText === undefined
      ? [key, ...dropKeys]
      : dropKeys) {
      const index = findLine(name);
      if (index === -1) continue;
      lines.splice(index, 1);
      bodyEndIndex -= 1;
      removed = true;
    }
    if (valueText === undefined) {
      if (!removed) return normalizedText;
      const bodyEmpty = lines
        .slice(range.bodyStartIndex, bodyEndIndex)
        .every((line) => line.trim() === "");
      if (bodyEmpty) {
        lines.splice(
          range.headerLineIndex,
          bodyEndIndex - range.headerLineIndex,
        );
      }
    } else {
      const lineIndex = findLine(key);
      if (lineIndex !== -1) {
        lines[lineIndex] = replacementLine;
      } else {
        lines.splice(
          getTomlSectionInsertIndex(lines, { ...range, bodyEndIndex }),
          0,
          replacementLine,
        );
      }
    }
  } else {
    if (valueText === undefined) return normalizedText;
    if (lines.length > 0 && lines[lines.length - 1].trim() !== "") {
      lines.push("");
    }
    lines.push(`[${CODEX_AGENTS_SECTION}]`, replacementLine, "");
  }

  const candidate = finalizeTomlText(lines);
  try {
    parseToml(normalizedText);
  } catch {
    return candidate;
  }
  try {
    parseToml(candidate);
    return candidate;
  } catch {
    return normalizedText;
  }
};

// 写入或删除 `[agents]` 里的一个字符串键;空值删除。
export const setCodexAgentsString = (
  configText: string,
  key: CodexAgentsStringKey,
  value: string,
): string => {
  const trimmed = value.trim();
  return writeCodexAgentsLine(
    configText,
    key,
    trimmed ? tomlBasicString(trimmed) : undefined,
  );
};

// ========== Codex [agents] sub-agent concurrency limit ==========

// 子代理并发上限(不含主线程)。Codex 的全局设置,不随供应商切换。codex-rs 0.150 起改名
// max_concurrent_threads_per_session,旧名 max_threads 留作别名:新写入用旧名(各版本都认),
// 已经写了新名就改新名。两种写法同时出现 Codex 报重复字段,所以只留一个。
const CODEX_AGENTS_MAX_THREADS_KEY = "max_threads";
const CODEX_AGENTS_MAX_THREADS_CANONICAL_KEY =
  "max_concurrent_threads_per_session";

const positiveInteger = (value: unknown): number | undefined =>
  typeof value === "number" && Number.isInteger(value) && value > 0
    ? value
    : undefined;

export const extractCodexAgentsMaxThreads = (
  configText: string | undefined | null,
): number | undefined => {
  const text = normalizeTomlText(
    typeof configText === "string" ? configText : "",
  );
  if (!text) return undefined;
  try {
    const agents = (parseToml(text) as Record<string, any>)[
      CODEX_AGENTS_SECTION
    ];
    return (
      positiveInteger(agents?.[CODEX_AGENTS_MAX_THREADS_CANONICAL_KEY]) ??
      positiveInteger(agents?.[CODEX_AGENTS_MAX_THREADS_KEY])
    );
  } catch {
    // 编辑中的 TOML 解析不了时按行在 [agents] 里找。
  }
  const lines = text.split("\n");
  const range = getTomlSectionRange(lines, CODEX_AGENTS_SECTION);
  if (!range) return undefined;
  for (const key of [
    CODEX_AGENTS_MAX_THREADS_CANONICAL_KEY,
    CODEX_AGENTS_MAX_THREADS_KEY,
  ]) {
    const pattern = new RegExp(
      `^\\s*${tomlKeySource(key)}\\s*=\\s*(\\d+)\\s*(?:#.*)?$`,
    );
    for (let i = range.bodyStartIndex; i < range.bodyEndIndex; i += 1) {
      const match = lines[i].match(pattern);
      if (match) return positiveInteger(Number(match[1]));
    }
  }
  return undefined;
};

// 写入上限;undefined 删掉两种写法,回到 Codex 默认值。
export const setCodexAgentsMaxThreads = (
  configText: string,
  maxThreads: number | undefined,
): string => {
  const lines = normalizeTomlText(configText).split("\n");
  const range = getTomlSectionRange(lines, CODEX_AGENTS_SECTION);
  const hasCanonical =
    !!range &&
    findTomlLineInRange(
      lines,
      tomlStringAssignmentPatterns(CODEX_AGENTS_MAX_THREADS_CANONICAL_KEY)
        .anyValue,
      range.bodyStartIndex,
      range.bodyEndIndex,
    ) !== -1;
  const [key, other] = hasCanonical
    ? [CODEX_AGENTS_MAX_THREADS_CANONICAL_KEY, CODEX_AGENTS_MAX_THREADS_KEY]
    : [CODEX_AGENTS_MAX_THREADS_KEY, CODEX_AGENTS_MAX_THREADS_CANONICAL_KEY];
  return writeCodexAgentsLine(
    configText,
    key,
    positiveInteger(maxThreads)?.toString(),
    [other],
  );
};

// `[features.multi_agent_v2]` 里含主线程的总数:写了就盖过新版子 agent 工具的上限。
export const extractCodexMultiAgentV2Total = (
  configText: string | undefined | null,
): number | undefined => {
  const text = normalizeTomlText(
    typeof configText === "string" ? configText : "",
  );
  if (!text) return undefined;
  try {
    const v2 = (parseToml(text) as Record<string, any>).features
      ?.multi_agent_v2;
    return typeof v2 === "object" && v2 !== null
      ? positiveInteger(v2[CODEX_AGENTS_MAX_THREADS_CANONICAL_KEY])
      : undefined;
  } catch {
    return undefined;
  }
};

// ========== Codex top-level integer field utils ==========

const tomlTopLevelIntPattern = (field: string) =>
  new RegExp(`^\\s*${field}\\s*=\\s*(\\d+)\\s*(?:#.*)?$`);

const findTopLevelIntMatch = (
  lines: string[],
  fieldName: string,
  topLevelEndIndex: number,
): { index: number; value: number } | undefined => {
  const pattern = tomlTopLevelIntPattern(fieldName);
  for (let i = 0; i < topLevelEndIndex; i += 1) {
    const m = lines[i].match(pattern);
    if (m) {
      return { index: i, value: Number(m[1]) };
    }
  }
  return undefined;
};

// 从 Codex TOML 配置中提取顶级整数字段
export const extractCodexTopLevelInt = (
  configText: string | undefined | null,
  fieldName: string,
): number | undefined => {
  try {
    const raw = typeof configText === "string" ? configText : "";
    const text = normalizeTomlText(raw);
    if (!text) return undefined;
    const lines = text.split("\n");
    return findTopLevelIntMatch(lines, fieldName, getTopLevelEndIndex(lines))
      ?.value;
  } catch {
    return undefined;
  }
};

// 在 Codex TOML 配置中设置或更新顶级整数字段
export const setCodexTopLevelInt = (
  configText: string,
  fieldName: string,
  value: number,
): string => {
  const normalizedText = normalizeTomlText(configText);
  const lines = normalizedText ? normalizedText.split("\n") : [];
  const topLevelEndIndex = getTopLevelEndIndex(lines);
  const existing = findTopLevelIntMatch(lines, fieldName, topLevelEndIndex);
  const replacementLine = `${fieldName} = ${value}`;

  if (existing) {
    lines[existing.index] = replacementLine;
    return finalizeTomlText(lines);
  }

  // 插入位置:顶级区域末尾(section header 之前)
  if (lines.length === 0) {
    return `${replacementLine}\n`;
  }

  lines.splice(topLevelEndIndex, 0, replacementLine);
  return finalizeTomlText(lines);
};

// 从 Codex TOML 配置中移除顶级字段行
export const removeCodexTopLevelField = (
  configText: string,
  fieldName: string,
): string => {
  const normalizedText = normalizeTomlText(configText);
  if (!normalizedText) return normalizedText;
  const lines = normalizedText.split("\n");
  const topLevelEndIndex = getTopLevelEndIndex(lines);
  const existing = findTopLevelIntMatch(lines, fieldName, topLevelEndIndex);
  if (existing) {
    lines.splice(existing.index, 1);
  }
  return finalizeTomlText(lines);
};