Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix: stream CLI validation prompts through stdin (#588)

faizan-oai47b6574d263b
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index ecb7ce4af..3a0acfd2b 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -965,6 +965,7 @@ interface CliDependencies {
args: readonly string[],
output?: SkillCommandOutput,
environment?: NodeJS.ProcessEnv,
+ input?: string,
): Promise<number>;
runRepositoryCommand(
command: "git" | "gh",
@@ -1031,12 +1032,13 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
writeSync(stream.fd, value);
},
forceExit: (signal) => process.kill(process.pid, signal),
- runCodex: (args, output, environment) =>
+ runCodex: (args, output, environment, input) =>
runCodexSkillCommand(
args,
output,
resolveCodexCommand(environment),
environment,
+ input,
),
runRepositoryCommand: async (command, args, repository) => {
const executable = await resolveTrustedExecutable(
@@ -1144,6 +1146,7 @@ export async function runCodexSkillCommand(
output?: SkillCommandOutput,
command: CodexCommand = resolveCodexCommand(),
processEnvironment: NodeJS.ProcessEnv = process.env,
+ input?: string,
): Promise<number> {
const configuredHome = processEnvironment["CODEX_HOME"];
const environment = { ...processEnvironment };
@@ -1160,10 +1163,22 @@ export async function runCodexSkillCommand(
cwd: output?.appServer?.directory ?? parse(process.execPath).root,
stdio:
output === undefined
- ? "inherit"
- : [output.appServer === undefined ? "ignore" : "pipe", "pipe", "pipe"],
+ ? input === undefined
+ ? "inherit"
+ : ["pipe", "inherit", "inherit"]
+ : [
+ output.appServer !== undefined || input !== undefined
+ ? "pipe"
+ : "ignore",
+ "pipe",
+ "pipe",
+ ],
windowsHide: true,
});
+ if (input !== undefined) {
+ invocation.stdin?.on("error", () => {});
+ invocation.stdin?.end(input);
+ }
let requestedSignal: SignalName | null = null;
let forcedTermination: ReturnType<typeof setTimeout> | undefined;
let forceStatusCompletion: (() => void) | null = null;
@@ -4392,7 +4407,7 @@ async function runSkill(
"--skip-git-repo-check",
"--cd",
directory,
- prompt,
+ "-",
]),
],
{
@@ -4413,6 +4428,7 @@ async function runSkill(
: {}),
},
options.environment,
+ appServer ? undefined : prompt,
);
}
diff --git a/sdk/typescript/tests-ts/cli-skills.test.ts b/sdk/typescript/tests-ts/cli-skills.test.ts
index 77dce5c80..1b0406e77 100644
--- a/sdk/typescript/tests-ts/cli-skills.test.ts
+++ b/sdk/typescript/tests-ts/cli-skills.test.ts
@@ -51,9 +51,10 @@ describe("CLI skill commands", () => {
stderr.stream,
dependencies({
currentDirectory: directory,
- onCodex: (args, output) => {
+ onCodex: (args, output, _environment, input) => {
invocation = args;
- prompt = output?.appServer?.prompt ?? args.at(-1)!;
+ prompt = output?.appServer?.prompt ?? input ?? "";
+ expect(input).toBe(command === "patch" ? undefined : prompt);
return status;
},
}),
@@ -84,7 +85,7 @@ describe("CLI skill commands", () => {
"--skip-git-repo-check",
"--cd",
directory,
- prompt,
+ "-",
]),
]);
expect(prompt).toContain(
@@ -422,9 +423,9 @@ describe("CLI skill commands", () => {
stderr.stream,
dependencies({
currentDirectory: repository,
- onCodex: (args, output) => {
+ onCodex: (args, output, _environment, input) => {
invocation = args;
- prompt = output?.appServer?.prompt ?? args.at(-1);
+ prompt = output?.appServer?.prompt ?? input;
return 0;
},
}),
@@ -446,9 +447,9 @@ describe("CLI skill commands", () => {
capture().stream,
dependencies({
currentDirectory: repository,
- onCodex: (args, output) => {
+ onCodex: (args, output, _environment, input) => {
invocation = args;
- prompt = output?.appServer?.prompt ?? args.at(-1);
+ prompt = output?.appServer?.prompt ?? input;
return 0;
},
}),
@@ -678,7 +679,7 @@ describe("CLI skill commands", () => {
}
}
- let invocation: readonly string[] = [];
+ let prompt = "";
const stdout = capture();
const stderr = capture();
expect(
@@ -694,14 +695,14 @@ describe("CLI skill commands", () => {
stderr.stream,
dependencies({
currentDirectory: directory,
- onCodex: (args) => {
- invocation = args;
+ onCodex: (_args, _output, _environment, input) => {
+ prompt = input ?? "";
return 0;
},
}),
),
).toBe(0);
- expect(JSON.parse(invocation.at(-1)!.split("\n").at(-1)!)).toEqual([
+ expect(JSON.parse(prompt.split("\n").at(-1)!)).toEqual([
"local finding contents\n",
...localDrivePaths.map(
(_, index) => `local drive ${index + 1} contents\n`,
@@ -749,7 +750,7 @@ describe("CLI skill commands", () => {
"This candidate finding has enough context to exceed a filesystem name. ".repeat(
8,
);
- let literalInvocation: readonly string[] = [];
+ let literalPrompt = "";
expect(
await main(
["validate", longLiteral],
@@ -757,14 +758,14 @@ describe("CLI skill commands", () => {
capture().stream,
dependencies({
currentDirectory: process.cwd(),
- onCodex: (args) => {
- literalInvocation = args;
+ onCodex: (_args, _output, _environment, input) => {
+ literalPrompt = input ?? "";
return 0;
},
}),
),
).toBe(0);
- expect(JSON.parse(literalInvocation.at(-1)!.split("\n").at(-1)!)).toEqual([
+ expect(JSON.parse(literalPrompt.split("\n").at(-1)!)).toEqual([
longLiteral,
]);
@@ -912,8 +913,9 @@ describe("CLI skill commands", () => {
capture().stream,
dependencies({
currentDirectory: directory,
- onCodex: (args) => {
- received = JSON.parse(args.at(-1)!.split("\n").at(-1)!);
+ onCodex: (args, _output, _environment, input) => {
+ expect(args.at(-1)).toBe("-");
+ received = JSON.parse(input!.split("\n").at(-1)!);
return 0;
},
}),
@@ -928,6 +930,30 @@ describe("CLI skill commands", () => {
}
});
+ test("streams oversized skill prompts to a real child process", async () => {
+ const input = "é日本語".repeat(256 * 1024 + 1);
+ const stdout = capture();
+ const stderr = capture();
+ const source = [
+ "let input = ''",
+ "process.stdin.setEncoding('utf8')",
+ "process.stdin.on('data', (chunk) => { input += chunk })",
+ "process.stdin.on('end', () => process.stdout.write(JSON.stringify({type:'item.completed',item:{type:'agent_message',text:input}}) + '\\n'))",
+ ].join(";");
+
+ await expect(
+ runCodexSkillCommand(
+ ["-e", source],
+ { command: "validate", stdout: stdout.stream, stderr: stderr.stream },
+ { command: process.execPath },
+ process.env,
+ input,
+ ),
+ ).resolves.toBe(0);
+ expect(stdout.text()).toBe(`${input}\n`);
+ expect(stderr.text()).toBe("");
+ });
+
test("extracts the final skill response without exposing intermediate events", async () => {
async function* events(): AsyncGenerator<Buffer> {
yield Buffer.from(
diff --git a/sdk/typescript/tests-ts/cli-verify-fix.test.ts b/sdk/typescript/tests-ts/cli-verify-fix.test.ts
index d25883334..db5bd33bc 100644
--- a/sdk/typescript/tests-ts/cli-verify-fix.test.ts
+++ b/sdk/typescript/tests-ts/cli-verify-fix.test.ts
@@ -37,8 +37,9 @@ describe("read-only finding verification", () => {
({
issue: async (id: string) => linearIssue(id),
}) as ReturnType<LinearClientFactory>,
- onCodex: (args, output, processEnvironment) => {
+ onCodex: (args, output, processEnvironment, input) => {
expect(args[0]).toBe("app-server");
+ expect(input).toBeUndefined();
expect(args).toContain('approval_policy="on-request"');
expect(args).toContain('approvals_reviewer="auto_review"');
expect(args).not.toContain('approval_policy="never"');
diff --git a/sdk/typescript/tests-ts/workbench-scan-history.test.ts b/sdk/typescript/tests-ts/workbench-scan-history.test.ts
index 7ce34afbb..fb2ca8a74 100644
--- a/sdk/typescript/tests-ts/workbench-scan-history.test.ts
+++ b/sdk/typescript/tests-ts/workbench-scan-history.test.ts
@@ -1,8 +1,7 @@
-import { spawnSync } from "node:child_process";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, test } from "bun:test";
-import { resolvePluginPython } from "../src/runtime.js";
+import { resolvePluginPython, runCodexCommand } from "../src/runtime.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
test("loads each scan's matching findings once across historical batches", async () => {
@@ -33,8 +32,8 @@ test("loads each scan's matching findings once across historical batches", async
"print(json.dumps({'result': result, 'backfilled': backfilled, 'findingQueries': sum('FROM finding_occurrences AS occurrences' in query for query in queries)}))",
].join("\n");
- const result = spawnSync(
- python,
+ const result = await runCodexCommand(
+ { command: python },
[
"-I",
"-B",
@@ -42,10 +41,12 @@ test("loads each scan's matching findings once across historical batches", async
join(PLUGIN_ROOT, "scripts"),
join(tmpdir(), "codex-security-matching-fixture"),
],
- { input: probe, encoding: "utf8", timeout: 10_000, windowsHide: true },
+ process.env,
+ probe,
+ AbortSignal.timeout(10_000),
);
- expect(result.status, result.stderr || result.error?.message).toBe(0);
+ expect(result.exitCode, result.stderr).toBe(0);
expect(result.stderr).toBe("");
expect(JSON.parse(result.stdout)).toMatchObject({
backfilled: ["scan-0", "scan-1", "scan-2"],
@@ -96,13 +97,15 @@ test("loads oversized comparison matches from stdin", async () => {
uncertain: [],
});
- const result = spawnSync(
- python,
+ const result = await runCodexCommand(
+ { command: python },
["-I", "-B", "-c", probe, join(PLUGIN_ROOT, "scripts")],
- { encoding: "utf8", input: payload, timeout: 10_000, windowsHide: true },
+ process.env,
+ payload,
+ AbortSignal.timeout(10_000),
);
- expect(result.status, result.stderr || result.error?.message).toBe(0);
+ expect(result.exitCode, result.stderr).toBe(0);
expect(result.stderr).toBe("");
expect(JSON.parse(result.stdout)).toEqual({ saved: true });
});