-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathrunCodexExec.ts
More file actions
414 lines (376 loc) · 10.2 KB
/
Copy pathrunCodexExec.ts
File metadata and controls
414 lines (376 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import { spawn } from "child_process";
import { chmod, mkdtemp, readFile, rm, writeFile } from "fs/promises";
import path from "path";
import os from "os";
import { setOutput } from "@actions/core";
import { checkOutput } from "./checkOutput";
export type PromptSource =
| {
type: "inline";
content: string;
}
| {
type: "file";
path: string;
};
export type SafetyStrategy =
| "drop-sudo"
| "read-only"
| "unprivileged-user"
| "unsafe";
export type SandboxMode =
| "read-only"
| "workspace-write"
| "danger-full-access";
type PermissionSelection =
| { type: "sandbox"; mode: SandboxMode }
| { type: "profile"; name: string };
export type OutputSchemaSource =
| {
type: "file";
path: string;
}
| {
type: "inline";
content: string;
};
/**
* Builds and runs a `codex exec` command, writes the prompt to its standard input, and publishes
* the command's final message as the action output.
*
* Authentication is intentionally outside this function. The composite action starts or reuses
* the Responses API proxy and writes the corresponding Codex configuration before invoking this
* command. Keeping that setup separate also lets tests put a fake `codex` executable on `PATH` to
* verify command construction and output handling without an API key or network request.
*/
export async function runCodexExec({
prompt,
codexHome,
cd,
extraArgs,
explicitOutputFile,
outputSchema,
model,
effort,
safetyStrategy,
codexUser,
sandbox,
permissionProfile,
}: {
prompt: PromptSource;
codexHome: string | null;
cd: string;
extraArgs: Array<string>;
explicitOutputFile: string | null;
outputSchema: OutputSchemaSource | null;
model: string | null;
effort: string | null;
safetyStrategy: SafetyStrategy;
codexUser: string | null;
sandbox: SandboxMode | null;
permissionProfile: string | null;
}): Promise<void> {
let input: string;
switch (prompt.type) {
case "inline":
input = prompt.content;
break;
case "file":
input = await readFile(prompt.path, "utf8");
break;
}
const runAsUser: string | null =
safetyStrategy === "unprivileged-user" ? codexUser : null;
let outputFile: OutputFile;
if (explicitOutputFile != null) {
outputFile = { type: "explicit", file: explicitOutputFile };
} else {
outputFile = await createTempOutputFile({ runAsUser });
}
const resolvedOutputSchema = await resolveOutputSchema(
outputSchema,
runAsUser
);
const permissionSelection = determinePermissionSelection({
safetyStrategy,
requestedSandbox: sandbox,
permissionProfile,
extraArgs,
});
const command: Array<string> = [];
let pathToCodex = "codex";
if (safetyStrategy === "unprivileged-user") {
if (codexUser == null) {
throw new Error(
"codexUser must be specified when using the 'unprivileged-user' safety strategy."
);
}
if (process.platform === "win32") {
throw new Error(
"the 'unprivileged-user' safety strategy is not supported on Windows."
);
}
// We are currently running as a privileged user, but `codexUser` will run
// with a different $PATH variable, so we need to find the full path to
// `codex`.
pathToCodex = (await checkOutput(["which", "codex"])).trim();
if (!pathToCodex) {
throw new Error("could not find 'codex' in PATH");
}
command.push("sudo", "-u", codexUser, "--");
}
command.push(
pathToCodex,
"exec",
"--skip-git-repo-check",
"--cd",
cd,
"--output-last-message",
outputFile.file
);
if (resolvedOutputSchema != null) {
command.push("--output-schema", resolvedOutputSchema.file);
}
if (model != null) {
command.push("--model", model);
}
if (effort != null) {
// https://github.com/openai/codex/blob/00debb6399eb51c4b9273f0bc012912c42fe6c91/docs/config.md#config
// https://github.com/openai/codex/blob/00debb6399eb51c4b9273f0bc012912c42fe6c91/docs/config.md#model_reasoning_effort
command.push("--config", `model_reasoning_effort="${effort}"`);
}
command.push(...extraArgs);
switch (permissionSelection.type) {
case "sandbox":
command.push("--sandbox", permissionSelection.mode);
break;
case "profile":
command.push(
"--config",
`default_permissions=${JSON.stringify(permissionSelection.name)}`
);
break;
}
const env = { ...process.env };
if (!env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE) {
env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE = "codex_github_action";
}
let extraEnv = "";
if (codexHome != null) {
env.CODEX_HOME = codexHome;
extraEnv = `CODEX_HOME=${codexHome} `;
}
// Split the `program` from the `args` for `spawn()`.
const program = command.shift()!;
console.log(
`Running: ${extraEnv}${program} ${command
.map((a) => JSON.stringify(a))
.join(" ")}`
);
try {
await new Promise((resolve, reject) => {
const child = spawn(program, command, {
env,
stdio: ["pipe", "inherit", "inherit"],
});
child.stdin.write(input);
child.stdin.end();
child.on("error", reject);
child.on("close", async (code) => {
if (code !== 0) {
reject(new Error(`${program} exited with code ${code}`));
return;
}
try {
await finalizeExecution(outputFile, runAsUser);
resolve(undefined);
} catch (err) {
reject(err);
}
});
});
} finally {
await cleanupOutputSchema(resolvedOutputSchema);
}
}
async function finalizeExecution(
outputFile: OutputFile,
runAsUser: string | null
): Promise<void> {
try {
let lastMessage: string;
if (runAsUser == null) {
lastMessage = await readFile(outputFile.file, "utf8");
} else {
lastMessage = await checkOutput([
"sudo",
"-u",
runAsUser,
"cat",
outputFile.file,
]);
}
setOutput("final-message", lastMessage);
} finally {
await cleanupTempOutput(outputFile, runAsUser);
}
}
type OutputFile =
| {
type: "explicit";
file: string;
}
| {
type: "temp";
file: string;
};
type ResolvedOutputSchema =
| {
type: "explicit";
file: string;
}
| {
type: "temp";
file: string;
dir: string;
};
async function createTempOutputFile({
runAsUser,
}: {
runAsUser: string | null;
}): Promise<OutputFile> {
const dir = await createTempDir("codex-exec-", runAsUser);
return { type: "temp", file: path.join(dir, "output.md") };
}
async function cleanupTempOutput(
outputFile: OutputFile,
runAsUser: string | null
): Promise<void> {
switch (outputFile.type) {
case "explicit":
// Do not delete user-specified output files.
return;
case "temp": {
const { file } = outputFile;
if (runAsUser == null) {
const dir = path.dirname(file);
await rm(dir, { recursive: true, force: true });
} else {
await checkOutput(["sudo", "rm", "-rf", path.dirname(file)]);
}
break;
}
}
}
async function resolveOutputSchema(
schema: OutputSchemaSource | null,
runAsUser: string | null
): Promise<ResolvedOutputSchema | null> {
if (schema == null) {
return null;
}
switch (schema.type) {
case "file":
return { type: "explicit", file: schema.path };
case "inline": {
const dir = await createTempDir("codex-output-schema-", runAsUser);
const file = path.join(dir, "schema.json");
await writeFile(file, schema.content);
return { type: "temp", file, dir };
}
}
}
async function cleanupOutputSchema(
schema: ResolvedOutputSchema | null
): Promise<void> {
if (schema == null) {
return;
}
switch (schema.type) {
case "explicit":
return;
case "temp":
await rm(schema.dir, { recursive: true, force: true });
return;
}
}
async function createTempDir(
prefix: string,
runAsUser: string | null
): Promise<string> {
if (runAsUser == null) {
return await mkdtemp(path.join(os.tmpdir(), prefix));
} else {
return (
await checkOutput([
"sudo",
"-u",
runAsUser,
"mktemp",
"-d",
"-t",
`${prefix}.XXXXXX`,
])
).trim();
}
}
function determinePermissionSelection({
safetyStrategy,
requestedSandbox,
permissionProfile,
extraArgs,
}: {
safetyStrategy: SafetyStrategy;
requestedSandbox: SandboxMode | null;
permissionProfile: string | null;
extraArgs: Array<string>;
}): PermissionSelection {
if (permissionProfile != null && requestedSandbox != null) {
throw new Error(
"`permission-profile` and `sandbox` are mutually exclusive. Permission profiles do not compose with legacy sandbox settings."
);
}
if (permissionProfile != null && safetyStrategy === "read-only") {
throw new Error(
"`permission-profile` cannot be combined with the `read-only` safety strategy because that strategy forces the legacy read-only sandbox."
);
}
if (permissionProfile != null && extraArgsSelectSandbox(extraArgs)) {
throw new Error(
"`permission-profile` cannot be combined with a sandbox override in `codex-args`."
);
}
if (safetyStrategy === "read-only") {
return { type: "sandbox", mode: "read-only" };
}
if (permissionProfile != null) {
return { type: "profile", name: permissionProfile };
}
return { type: "sandbox", mode: requestedSandbox ?? "workspace-write" };
}
function extraArgsSelectSandbox(args: Array<string>): boolean {
return args.some((arg, index) => {
if (
arg === "--sandbox" ||
arg.startsWith("--sandbox=") ||
arg === "-s" ||
arg.startsWith("-s=")
) {
return true;
}
if (arg === "--config" || arg === "-c") {
return configOverrideSelectsSandbox(args[index + 1]);
}
if (arg.startsWith("--config=")) {
return configOverrideSelectsSandbox(arg.slice("--config=".length));
}
if (arg.startsWith("-c=")) {
return configOverrideSelectsSandbox(arg.slice("-c=".length));
}
return false;
});
}
function configOverrideSelectsSandbox(override: string | undefined): boolean {
const key = override?.trimStart().split(/[=.]/, 1)[0];
return key === "sandbox_mode" || key === "sandbox_workspace_write";
}