codex.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. /**
  2. * OpenAI Codex CLI target.
  3. *
  4. * - MCP server entry to `~/.codex/config.toml` as the dotted-key
  5. * table `[mcp_servers.codegraph]`. TOML — not JSON — handled by
  6. * the narrow serializer in `./toml.ts`.
  7. * - Instructions to `~/.codex/AGENTS.md`.
  8. *
  9. * Codex CLI as of 2026-05 has no project-local config concept —
  10. * everything lives under `~/.codex/`. `supportsLocation('local')`
  11. * returns false; the orchestrator skips Codex when the user picks
  12. * the local install location.
  13. *
  14. * No permissions concept.
  15. */
  16. import * as fs from 'fs';
  17. import * as path from 'path';
  18. import * as os from 'os';
  19. import {
  20. AgentTarget,
  21. DetectionResult,
  22. InstallOptions,
  23. Location,
  24. WriteResult,
  25. } from './types';
  26. import {
  27. atomicWriteFileSync,
  28. getMcpServerConfig,
  29. removeMarkedSection,
  30. upsertInstructionsEntry,
  31. } from './shared';
  32. import {
  33. CODEGRAPH_SECTION_END,
  34. CODEGRAPH_SECTION_START,
  35. } from '../instructions-template';
  36. import { buildTomlTable, removeTomlTable, upsertTomlTable } from './toml';
  37. const TOML_HEADER = 'mcp_servers.codegraph';
  38. function configDir(): string {
  39. return path.join(os.homedir(), '.codex');
  40. }
  41. function tomlConfigPath(): string {
  42. return path.join(configDir(), 'config.toml');
  43. }
  44. function instructionsPath(): string {
  45. return path.join(configDir(), 'AGENTS.md');
  46. }
  47. class CodexTarget implements AgentTarget {
  48. readonly id = 'codex' as const;
  49. readonly displayName = 'Codex CLI';
  50. readonly docsUrl = 'https://github.com/openai/codex';
  51. supportsLocation(loc: Location): boolean {
  52. return loc === 'global';
  53. }
  54. detect(loc: Location): DetectionResult {
  55. if (loc !== 'global') {
  56. return { installed: false, alreadyConfigured: false };
  57. }
  58. const tomlPath = tomlConfigPath();
  59. let alreadyConfigured = false;
  60. if (fs.existsSync(tomlPath)) {
  61. try {
  62. const content = fs.readFileSync(tomlPath, 'utf-8');
  63. alreadyConfigured = content.includes(`[${TOML_HEADER}]`);
  64. } catch { /* ignore */ }
  65. }
  66. const installed = fs.existsSync(configDir());
  67. return { installed, alreadyConfigured, configPath: tomlPath };
  68. }
  69. install(loc: Location, _opts: InstallOptions): WriteResult {
  70. if (loc !== 'global') {
  71. return {
  72. files: [],
  73. notes: ['Codex CLI has no project-local config — re-run with --location=global to install.'],
  74. };
  75. }
  76. const files: WriteResult['files'] = [];
  77. files.push(writeMcpEntry());
  78. // AGENTS.md gets the short marker-fenced CodeGraph block (#704):
  79. // subagents and non-MCP harnesses read AGENTS.md but never the MCP
  80. // initialize instructions. Upsert self-heals a stale pre-#529 block.
  81. files.push(upsertInstructionsEntry(instructionsPath()));
  82. return { files };
  83. }
  84. uninstall(loc: Location): WriteResult {
  85. if (loc !== 'global') return { files: [] };
  86. const files: WriteResult['files'] = [];
  87. const tomlPath = tomlConfigPath();
  88. if (fs.existsSync(tomlPath)) {
  89. const content = fs.readFileSync(tomlPath, 'utf-8');
  90. const { content: nextContent, action } = removeTomlTable(content, TOML_HEADER);
  91. if (action === 'removed') {
  92. if (nextContent.trim() === '') {
  93. try { fs.unlinkSync(tomlPath); } catch { /* ignore */ }
  94. } else {
  95. atomicWriteFileSync(tomlPath, nextContent.trimEnd() + '\n');
  96. }
  97. files.push({ path: tomlPath, action: 'removed' });
  98. } else {
  99. files.push({ path: tomlPath, action: 'not-found' });
  100. }
  101. } else {
  102. files.push({ path: tomlPath, action: 'not-found' });
  103. }
  104. files.push(removeInstructionsEntry());
  105. return { files };
  106. }
  107. printConfig(loc: Location): string {
  108. if (loc !== 'global') {
  109. return '# Codex CLI has no project-local config — use --location=global.\n';
  110. }
  111. const block = buildCodegraphBlock();
  112. return `# Add to ${tomlConfigPath()}\n\n${block}\n`;
  113. }
  114. describePaths(loc: Location): string[] {
  115. if (loc !== 'global') return [];
  116. return [tomlConfigPath(), instructionsPath()];
  117. }
  118. }
  119. function buildCodegraphBlock(): string {
  120. const mcp = getMcpServerConfig();
  121. return buildTomlTable(TOML_HEADER, {
  122. command: mcp.command,
  123. args: mcp.args,
  124. });
  125. }
  126. function writeMcpEntry(): WriteResult['files'][number] {
  127. const file = tomlConfigPath();
  128. const dir = path.dirname(file);
  129. if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
  130. const block = buildCodegraphBlock();
  131. // Single read — `existing === ''` derives both "is the file empty
  132. // or absent" and "what was its content," avoiding a TOCTOU window
  133. // between two `fs.existsSync` calls.
  134. const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf-8') : '';
  135. const created = existing.length === 0;
  136. const { content: nextContent, action } = upsertTomlTable(existing, TOML_HEADER, block);
  137. if (action === 'unchanged') {
  138. return { path: file, action: 'unchanged' };
  139. }
  140. atomicWriteFileSync(file, nextContent);
  141. return { path: file, action: created ? 'created' : 'updated' };
  142. }
  143. /**
  144. * Strip the marker-delimited CodeGraph block from `~/.codex/AGENTS.md`
  145. * if a prior install wrote one. Used by both install (self-heal on
  146. * upgrade) and uninstall — see issue #529.
  147. */
  148. function removeInstructionsEntry(): WriteResult['files'][number] {
  149. const file = instructionsPath();
  150. const action = removeMarkedSection(file, CODEGRAPH_SECTION_START, CODEGRAPH_SECTION_END);
  151. return { path: file, action };
  152. }
  153. export const codexTarget: AgentTarget = new CodexTarget();