openai/codex-action

Public

mirrored from https://github.com/openai/codex-actionAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/main.ts

442lines · modecode

1import { Command, Option } from "commander";
2import * as fs from "node:fs/promises";
3import * as os from "node:os";
4import * as path from "node:path";
5import pkg from "../package.json" assert { type: "json" };
6
7import { readServerInfo } from "./readServerInfo";
8import {
9 SandboxMode,
10 OutputSchemaSource,
11 PromptSource,
12 runCodexExec,
13 SafetyStrategy,
14} from "./runCodexExec";
15import { dropSudo } from "./dropSudo";
16import { ensureActorHasWriteAccess } from "./checkActorPermissions";
17import parseArgsStringToArgv from "string-argv";
18import { writeProxyConfig } from "./writeProxyConfig";
19import { checkOutput } from "./checkOutput";
20
21export async function main() {
22 const program = new Command();
23
24 program
25 .name("codex-action")
26 .version(pkg.version)
27 .description("Multitool to support openai/codex-action.");
28
29 program
30 .command("read-server-info")
31 .description("Read server info from the responses API proxy")
32 .argument("<serverInfoFile>", "Path to the server info file")
33 .action(async (serverInfoFile: string) => {
34 await readServerInfo(serverInfoFile);
35 });
36
37 program
38 .command("resolve-codex-home")
39 .description(
40 "Resolve the Codex home directory with precedence: input, env, default (~/.codex)"
41 )
42 .requiredOption(
43 "--codex-home-override <DIRECTORY>",
44 "Optional codex-home input value (may be empty)"
45 )
46 .requiredOption(
47 "--safety-strategy <strategy>",
48 "Safety strategy to take into account when picking defaults"
49 )
50 .requiredOption(
51 "--codex-user <user>",
52 "Codex user to consider when safety strategy is 'unprivileged-user'"
53 )
54 .requiredOption("--github-run-id <id>", "GitHub run ID")
55 .action(
56 async (options: {
57 codexHomeOverride: string;
58 safetyStrategy: string;
59 codexUser: string;
60 githubRunId: string;
61 }) => {
62 const safetyStrategy = toSafetyStrategy(options.safetyStrategy);
63 const codexUser = emptyAsNull(options.codexUser);
64 const resolved = await resolveCodexHome(
65 emptyAsNull(options.codexHomeOverride),
66 safetyStrategy,
67 codexUser,
68 options.githubRunId
69 );
70
71 const { setOutput } = await import("@actions/core");
72 setOutput("codex-home", resolved);
73 console.log(`Resolved Codex home: ${resolved}`);
74 }
75 );
76
77 program
78 .command("write-proxy-config")
79 .description(
80 "Write the OpenAI Proxy model provider config into CODEX_HOME/config.toml"
81 )
82 .requiredOption("--codex-home <DIRECTORY>", "Path to Codex home directory")
83 .requiredOption("--port <port>", "Proxy server port", parseIntStrict)
84 .requiredOption(
85 "--safety-strategy <strategy>",
86 "Safety strategy to use. One of 'drop-sudo', 'read-only', 'unprivileged-user', or 'unsafe'."
87 )
88 .action(
89 async (options: {
90 codexHome: string;
91 port: number;
92 safetyStrategy: string;
93 }) => {
94 const safetyStrategy = toSafetyStrategy(options.safetyStrategy);
95 await writeProxyConfig(options.codexHome, options.port, safetyStrategy);
96 }
97 );
98
99 program
100 .command("drop-sudo")
101 .description("Drops sudo privileges for the configured user.")
102 .addOption(new Option("--user <user>", "User to modify").default("runner"))
103 .addOption(
104 new Option("--group <group>", "Group granting sudo privileges").default(
105 "sudo"
106 )
107 )
108 .addOption(new Option("--root-phase", "internal").default(false).hideHelp())
109 .action(
110 async (options: { user: string; group: string; rootPhase: boolean }) => {
111 await dropSudo({
112 user: options.user,
113 group: options.group,
114 rootPhase: options.rootPhase,
115 });
116 }
117 );
118
119 program
120 .command("run-codex-exec")
121 .description("Invokes `codex exec` with the appropriate arguments")
122 .requiredOption("--prompt <prompt>", "Prompt to pass to `codex exec`.")
123 .requiredOption(
124 "--prompt-file <FILE>",
125 "File containing the prompt to pass to `codex exec`."
126 )
127 .requiredOption(
128 "--codex-home <DIRECTORY>",
129 "Path to the Codex CLI home directory (where config files are stored)."
130 )
131 .requiredOption("--cd <DIRECTORY>", "Working directory for Codex")
132 .requiredOption(
133 "--extra-args <args>",
134 "Additional args to pass through to `codex exec` as JSON array or shell string.",
135 parseExtraArgs
136 )
137 .requiredOption(
138 "--output-file <FILE>",
139 "Path where the final message from `codex exec` will be written."
140 )
141 .requiredOption(
142 "--output-schema-file <FILE>",
143 "Path to a schema file to pass to `codex exec --output-schema`."
144 )
145 .requiredOption(
146 "--output-schema <SCHEMA>",
147 "Inline schema contents to pass to `codex exec --output-schema`."
148 )
149 .requiredOption(
150 "--sandbox <SANDBOX>",
151 "Sandbox mode override to pass to `codex exec`."
152 )
153 .requiredOption("--model <model>", "Model the agent should use")
154 .requiredOption(
155 "--safety-strategy <strategy>",
156 "Safety strategy to use. One of 'drop-sudo', 'read-only', 'unprivileged-user', or 'unsafe'."
157 )
158 .requiredOption(
159 "--codex-user <user>",
160 "User to run codex exec as when using the 'unprivileged-user' safety strategy."
161 )
162 .action(
163 async (options: {
164 prompt: string;
165 promptFile: string;
166 codexHome: string;
167 cd: string;
168 extraArgs: Array<string>;
169 outputFile: string;
170 outputSchemaFile: string;
171 outputSchema: string;
172 sandbox: string;
173 model: string;
174 safetyStrategy: string;
175 codexUser: string;
176 }) => {
177 const {
178 prompt,
179 promptFile,
180 outputFile,
181 codexHome,
182 cd,
183 extraArgs,
184 outputSchema,
185 outputSchemaFile,
186 sandbox,
187 model,
188 safetyStrategy,
189 codexUser,
190 } = options;
191
192 const normalizedPrompt = emptyAsNull(prompt);
193 const normalizedPromptFile = emptyAsNull(promptFile);
194 if (normalizedPrompt != null && normalizedPromptFile != null) {
195 throw new Error(
196 "Only one of `prompt` or `prompt-file` may be specified."
197 );
198 }
199
200 let promptSource: PromptSource;
201 if (normalizedPrompt != null) {
202 promptSource = { type: "inline", content: normalizedPrompt };
203 } else if (normalizedPromptFile != null) {
204 promptSource = { type: "file", path: normalizedPromptFile };
205 } else {
206 throw new Error(
207 "Either `prompt` or `prompt-file` must be specified."
208 );
209 }
210
211 // Custom option processing to coerces to null does not work with
212 // Commander.js's requiredOption, so we have to post-process here.
213 const normalizedOutputSchemaFile = emptyAsNull(outputSchemaFile);
214 const normalizedOutputSchema = emptyAsNull(outputSchema);
215
216 if (
217 normalizedOutputSchemaFile != null &&
218 normalizedOutputSchema != null
219 ) {
220 throw new Error(
221 "Only one of `output-schema` or `output-schema-file` may be specified."
222 );
223 }
224
225 let outputSchemaSource: OutputSchemaSource | null = null;
226 if (normalizedOutputSchema != null) {
227 outputSchemaSource = {
228 type: "inline",
229 content: normalizedOutputSchema,
230 };
231 } else if (normalizedOutputSchemaFile != null) {
232 outputSchemaSource = {
233 type: "file",
234 path: normalizedOutputSchemaFile,
235 };
236 }
237
238 await runCodexExec({
239 prompt: promptSource,
240 codexHome: emptyAsNull(codexHome),
241 cd,
242 extraArgs,
243 explicitOutputFile: emptyAsNull(outputFile),
244 outputSchema: outputSchemaSource,
245 sandbox: toSandboxMode(sandbox),
246 model: emptyAsNull(model),
247 safetyStrategy: toSafetyStrategy(safetyStrategy),
248 codexUser: emptyAsNull(codexUser),
249 });
250 }
251 );
252
253 program
254 .command("check-write-access")
255 .description(
256 "Checks that the triggering actor has write access to the repository"
257 )
258 .option(
259 "--allow-bots <boolean>",
260 "Allow GitHub App and bot actors to bypass the write-access check (default: true).",
261 parseBoolean,
262 true
263 )
264 .option(
265 "--allow-users <users>",
266 "Comma-separated list of GitHub usernames who can run this action, or '*' to allow all users.",
267 ""
268 )
269 .action(
270 async ({
271 allowBots,
272 allowUsers,
273 }: {
274 allowBots: boolean;
275 allowUsers: string;
276 }) => {
277 const result = await ensureActorHasWriteAccess({
278 allowBotActors: allowBots,
279 allowUsers,
280 });
281 switch (result.status) {
282 case "approved": {
283 console.log(`Actor '${result.actor}' is permitted to continue.`);
284 break;
285 }
286 case "rejected": {
287 const message = `Actor '${result.actor}' is not permitted to run this action: ${result.reason}`;
288 console.error(message);
289 throw new Error(message);
290 }
291 }
292 }
293 );
294
295 program.parse();
296}
297
298function parseIntStrict(value: string): number {
299 const parsed = parseInt(value, 10);
300 if (isNaN(parsed)) {
301 throw new Error(`Invalid integer: ${value}`);
302 }
303 return parsed;
304}
305
306function parseExtraArgs(value: string): Array<string> {
307 if (value.length === 0) {
308 return [];
309 }
310
311 if (value.startsWith("[")) {
312 return JSON.parse(value);
313 } else {
314 return parseArgsStringToArgv(value);
315 }
316}
317
318function toSafetyStrategy(value: string): SafetyStrategy {
319 switch (value) {
320 case "drop-sudo":
321 case "read-only":
322 case "unprivileged-user":
323 case "unsafe":
324 return value;
325 default:
326 throw new Error(
327 `Invalid safety strategy: ${value}. Must be one of 'drop-sudo', 'read-only', 'unprivileged-user', or 'unsafe'.`
328 );
329 }
330}
331
332function toSandboxMode(value: string): SandboxMode {
333 switch (value) {
334 case "read-only":
335 case "workspace-write":
336 case "danger-full-access":
337 return value;
338 default:
339 throw new Error(
340 `Invalid sandbox: ${value}. Must be one of 'read-only', 'workspace-write', or 'danger-full-access'.`
341 );
342 }
343}
344
345function emptyAsNull(value: string): string | null {
346 return value.trim().length == 0 ? null : value;
347}
348
349function parseBoolean(value: string): boolean {
350 const normalized = value.trim().toLowerCase();
351 if (["true", "1", "yes", "y"].includes(normalized)) {
352 return true;
353 }
354 if (["false", "0", "no", "n"].includes(normalized)) {
355 return false;
356 }
357 throw new Error(`Invalid boolean value: ${value}`);
358}
359
360main();
361
362async function resolveCodexHome(
363 inputCodexHome: string | null,
364 safetyStrategy: SafetyStrategy,
365 codexUser: string | null,
366 githubRunId: string
367): Promise<string> {
368 if (inputCodexHome != null) {
369 return expandTilde(inputCodexHome);
370 }
371 const envHome = emptyAsNull(process.env.CODEX_HOME ?? "");
372 if (envHome != null) {
373 return envHome;
374 }
375
376 if (safetyStrategy === "unprivileged-user") {
377 if (codexUser == null) {
378 throw new Error(
379 "codex-user input must be provided when using 'unprivileged-user' safety strategy and no codex-home is specified."
380 );
381 }
382
383 return await deriveSharedCodexHomeForUnprivilegedUser(
384 codexUser,
385 githubRunId
386 );
387 } else {
388 const codexHome = path.join(os.homedir(), ".codex");
389 // Ensure directory exists for downstream steps that will write files here.
390 await fs.mkdir(codexHome, { recursive: true });
391 return codexHome;
392 }
393}
394
395async function deriveSharedCodexHomeForUnprivilegedUser(
396 user: string,
397 githubRunId: string
398): Promise<string> {
399 const home = (
400 await checkOutput(["sudo", "-u", user, "--", "printenv", "HOME"])
401 ).trim();
402 if (!home) {
403 throw new Error(`Could not determine home directory for user '${user}'.`);
404 }
405 const codexHome = path.join(home, ".codex");
406 try {
407 const stat = await fs.stat(codexHome);
408 if (stat.isDirectory()) {
409 // Directory already exists and may contain a config.toml created by the
410 // user (or a previous invocation of codex-action), so assume it's
411 // correctly permissioned.
412 return codexHome;
413 }
414 } catch {
415 // Ignore stat errors and try to create the directory.
416 }
417
418 // We must use sudo for the following file system operations because we
419 // are writing to the home directory of a different user.
420 await checkOutput(["sudo", "mkdir", codexHome]);
421 await checkOutput(["sudo", "chown", `${user}`, codexHome]);
422 await checkOutput(["sudo", "chmod", "755", codexHome]);
423
424 // codex-responses-api-proxy will need to write the server info file.
425 const serverInfoFile = path.join(codexHome, `${githubRunId}.json`);
426 await checkOutput(["sudo", "touch", serverInfoFile]);
427 // Make the file world-writable for the moment, but this will be locked down
428 // to read-only by root before the action completes.
429 await checkOutput(["sudo", "chmod", "666", serverInfoFile]);
430
431 return codexHome;
432}
433
434function expandTilde(p: string): string {
435 if (p === "~") {
436 return os.homedir();
437 }
438 if (p.startsWith("~/") || p.startsWith("~\\")) {
439 return path.join(os.homedir(), p.slice(2));
440 }
441 return p;
442}
443