openai/codex-action
Publicmirrored from https://github.com/openai/codex-actionAvailable
src/writeProxyConfig.ts
55lines · modecode
| 1 | import * as fs from "node:fs/promises"; |
| 2 | import * as path from "node:path"; |
| 3 | import * as os from "node:os"; |
| 4 | import { SafetyStrategy } from "./runCodexExec"; |
| 5 | import { checkOutput } from "./checkOutput"; |
| 6 | |
| 7 | const MODEL_PROVIDER = "openai-proxy"; |
| 8 | |
| 9 | export async function writeProxyConfig( |
| 10 | codexHome: string, |
| 11 | port: number, |
| 12 | safetyStrategy: SafetyStrategy |
| 13 | ): Promise<void> { |
| 14 | const configPath = path.join(codexHome, "config.toml"); |
| 15 | |
| 16 | let existing = ""; |
| 17 | try { |
| 18 | existing = await fs.readFile(configPath, "utf8"); |
| 19 | } catch { |
| 20 | existing = ""; |
| 21 | } |
| 22 | |
| 23 | const header = `# Added by codex-action. |
| 24 | model_provider = "${MODEL_PROVIDER}" |
| 25 | |
| 26 | |
| 27 | `; |
| 28 | const table = ` |
| 29 | |
| 30 | # Added by codex-action. |
| 31 | [model_providers.${MODEL_PROVIDER}] |
| 32 | name = "OpenAI Proxy" |
| 33 | base_url = "http://127.0.0.1:${port}/v1" |
| 34 | wire_api = "responses" |
| 35 | `; |
| 36 | |
| 37 | // Prepend model_provider at the very top. |
| 38 | let output = `${header}${existing}${table}`; |
| 39 | |
| 40 | if (safetyStrategy === "unprivileged-user") { |
| 41 | // We know we have already created the CODEX_HOME directory, but it is owned |
| 42 | // by another user, so we need to use sudo to write the file. |
| 43 | const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "codex-config")); |
| 44 | try { |
| 45 | const tempConfigPath = path.join(tempDir, "config.toml"); |
| 46 | await fs.writeFile(tempConfigPath, output, "utf8"); |
| 47 | await checkOutput(["sudo", "mv", tempConfigPath, configPath]); |
| 48 | } finally { |
| 49 | await fs.rm(tempDir, { recursive: true, force: true }); |
| 50 | } |
| 51 | } else { |
| 52 | await fs.mkdir(codexHome, { recursive: true }); |
| 53 | await fs.writeFile(configPath, output, "utf8"); |
| 54 | } |
| 55 | } |