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(windows): support long Codex executable paths (#704)

faizan-oai1f8f84ff94ce
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executable-path.ts b/plugins/codex-security/mcp-app/src/deep-scan/executable-path.ts
new file mode 100644
index 000000000..48997b171
--- /dev/null
+++ b/plugins/codex-security/mcp-app/src/deep-scan/executable-path.ts
@@ -0,0 +1,10 @@
+import { win32 } from "node:path";
+
+export function executablePathForSpawn(command: string): string {
+ if (process.platform !== "win32" || !win32.isAbsolute(command)) return command;
+ // Root-relative paths still depend on the child's drive and working directory.
+ const root = win32.parse(command).root;
+ return root === "\\" || root === "/"
+ ? command
+ : win32.toNamespacedPath(command);
+}
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
index fbc9a8db8..2d1753ebe 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
@@ -2,6 +2,7 @@ import { accessSync, constants as fsConstants, existsSync, promises as fs, readd
import { createRequire } from "node:module";
import { delimiter, dirname, isAbsolute, join, resolve, win32 } from "node:path";
import { Codex } from "@openai/codex-sdk";
+import { executablePathForSpawn } from "./executable-path.js";
import {
classifyCodexWorkerError,
DeepScanNonRetryableError
@@ -68,7 +69,7 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
});
const prompt = await fs.readFile(request.promptPath, "utf8");
const codex = new Codex({
- codexPathOverride: codexPath,
+ codexPathOverride: executablePathForSpawn(codexPath),
env: childEnv,
config: {
// The CLI can add effort levels before the pinned SDK widens ThreadOptions.
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
index 0003eef5c..0e23712cf 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
@@ -3,6 +3,7 @@ import { createInterface, type Interface } from "node:readline";
import { isDeepStrictEqual } from "node:util";
import { MCP_APP_VERSION } from "../version.js";
import { classifyCodexWorkerError, DeepScanNonRetryableError } from "./errors.js";
+import { executablePathForSpawn } from "./executable-path.js";
export const DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID =
"codex_security_deep_scan_worker";
@@ -91,7 +92,7 @@ class AppServerPreflightClient {
}
args.push("app-server", "--stdio");
- this.child = spawn(options.codexPath, args, {
+ this.child = spawn(executablePathForSpawn(options.codexPath), args, {
cwd: options.cwd,
...(options.env === undefined ? {} : { env: options.env }),
stdio: ["pipe", "pipe", "pipe"]
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs
index 358c9f597..b703cd2bb 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
-import { spawnSync } from "node:child_process";
+import childProcess, { spawnSync } from "node:child_process";
import { chmod, copyFile, mkdir, mkdtemp, readFile, realpath, rm, symlink, utimes, writeFile } from "node:fs/promises";
+import { syncBuiltinESMExports } from "node:module";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -130,6 +131,7 @@ try {
await testWindowsNpmPackageResolution();
await testWindowsNpmPackageResolution("managed");
if (process.platform === "win32") {
+ await testWindowsLongExecutableLaunches();
await testWindowsRootRelativePathsStayBoundToOriginalDrive();
await testWindowsWorkerEnvironmentPreservesMixedCaseKeys();
await testWindowsLauncherSkipsExtensionlessNpmShim();
@@ -211,6 +213,84 @@ async function testWindowsRootRelativePathsStayBoundToOriginalDrive() {
}
}
+async function testWindowsLongExecutableLaunches() {
+ const fixture = await fakeCodexFixture();
+ const executable = path.join(
+ fixture.root,
+ ...Array(10).fill("nested executable directory"),
+ "node.exe"
+ );
+ const promptPath = path.join(fixture.root, "prompt.md");
+ const workingDirectory = path.join(fixture.root, "artifacts");
+ const codexHome = path.join(fixture.root, "codex-home");
+ await Promise.all([
+ mkdir(path.dirname(executable), { recursive: true }),
+ mkdir(workingDirectory),
+ mkdir(codexHome),
+ writeFile(promptPath, "fixture long executable worker\n")
+ ]);
+ await copyFile(process.execPath, executable);
+ assert.ok(executable.length > 260);
+ const previousCodexPath = process.env.CODEX_CLI_PATH;
+ const previousCodexHome = process.env.CODEX_HOME;
+ const originalSpawn = childProcess.spawn;
+ const launchedCommands = [];
+ const children = [];
+ childProcess.spawn = (command, args, options) => {
+ if (command !== executable && command !== path.toNamespacedPath(executable)) {
+ return originalSpawn(command, args, options);
+ }
+ // Keep the production executable argument intact at Node's Windows spawn boundary.
+ launchedCommands.push(command);
+ const child = originalSpawn(command, [fixture.executablePath, ...args], options);
+ children.push(child);
+ return child;
+ };
+ syncBuiltinESMExports();
+ try {
+ process.env.CODEX_HOME = codexHome;
+ for (const configured of [executable, path.toNamespacedPath(executable)]) {
+ process.env.CODEX_CLI_PATH = configured;
+ assert.equal((await snapshotWorkerEnvironment()).CODEX_CLI_PATH, configured);
+ const result = await new CodexSdkWorkerExecutor({
+ parentSandbox: trustedParentSandbox
+ }).run({
+ kind: "discovery",
+ promptPath,
+ workingDirectory,
+ subagents: 0,
+ signal: new AbortController().signal
+ });
+ assert.equal(result.threadId, "fixture-thread-id");
+ assert.equal(result.finalResponse, "fixture final response");
+ const invocation = JSON.parse(await readFile(fixture.markerPath, "utf8"));
+ assert.deepEqual(invocation.argv.slice(0, 2), ["exec", "--experimental-json"]);
+ assertReadOnlyWorkerPolicy(invocation.argv);
+ assert.equal(invocation.codexHome, await realpath(codexHome));
+ const preflight = JSON.parse(await readFile(fixture.preflightMarkerPath, "utf8"));
+ assert.deepEqual(preflight.requests.map((request) => request.method), [
+ "config/read", "permissionProfile/list"
+ ]);
+ assert.equal(process.env.CODEX_CLI_PATH, configured);
+ }
+ assert.deepEqual(launchedCommands, Array(4).fill(path.toNamespacedPath(executable)));
+ } finally {
+ childProcess.spawn = originalSpawn;
+ syncBuiltinESMExports();
+ // The SDK removes child listeners when its event iterator closes.
+ await Promise.all(children.map((child) => {
+ if (child.stdout.closed && child.stderr.closed
+ && (child.exitCode !== null || child.signalCode !== null)) return;
+ return new Promise((resolve) => {
+ child.once("close", resolve);
+ if (child.exitCode === null && child.signalCode === null) child.kill();
+ });
+ }));
+ restoreEnv("CODEX_CLI_PATH", previousCodexPath);
+ restoreEnv("CODEX_HOME", previousCodexHome);
+ }
+}
+
async function testWindowsWorkerEnvironmentPreservesMixedCaseKeys() {
const root = await mkdtemp(path.join(tmpdir(), "codex-security-windows-env-"));
temporaryRoots.push(root);
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjs b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjs
index c9113d75a..03fe8a821 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjs
@@ -1,5 +1,7 @@
import assert from "node:assert/strict";
-import { chmod, mkdtemp, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
+import childProcess from "node:child_process";
+import { chmod, copyFile, mkdir, mkdtemp, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
+import { syncBuiltinESMExports } from "node:module";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -97,7 +99,7 @@ async function testAllowedProfileAndRawArgv() {
assert.deepEqual(calls[0].params.capabilities, { experimentalApi: true });
assert.deepEqual(calls[2].params, { cwd, includeLayers: false });
assert.deepEqual(calls[3].params, { cwd });
- });
+ }, { longExecutable: true });
}
async function testProvidedEnvForwardedWithoutMutation() {
@@ -126,7 +128,7 @@ async function testPreflightStartsInWorkerCwd() {
await withFakeCodex({
configResult: configReadResult(expectedProfile),
catalogResults: [catalogResult(true)]
- }, async ({ codexPath, cwd, cwdPath, callsPath, terminatedPath }) => {
+ }, async ({ codexPath, cwd, cwdPath, callsPath, terminatedPath, children }) => {
assert.notEqual(cwd, process.cwd());
await preflight(codexPath, cwd);
@@ -140,7 +142,7 @@ async function testPreflightStartsInWorkerCwd() {
assert.deepEqual(calls.find((call) => call.method === "permissionProfile/list").params, {
cwd
});
- assert.ok(["SIGTERM", "stdin-end"].includes(await readFile(terminatedPath, "utf8")));
+ await assertPreflightStopped(children, terminatedPath);
});
}
@@ -176,13 +178,13 @@ async function testMalformedStreamFailsClosed() {
]) {
await withFakeCodex({
rawOutputByMethod: { initialize: output }
- }, async ({ codexPath, cwd, terminatedPath }) => {
+ }, async ({ codexPath, cwd, terminatedPath, children }) => {
await assert.rejects(
preflight(codexPath, cwd),
(error) => error?.name === "DeepScanNonRetryableError"
&& error.message.includes("with this Codex configuration")
);
- assert.ok(["SIGTERM", "stdin-end"].includes(await readFile(terminatedPath, "utf8")));
+ await assertPreflightStopped(children, terminatedPath);
});
}
}
@@ -316,7 +318,7 @@ async function testMalformedAndUnsupportedResponsesFailClosed() {
await assert.rejects(
preflight(codexPath, cwd),
(error) => error?.name === "DeepScanNonRetryableError"
- && error.message.includes(codexPath)
+ && error.message.includes(JSON.stringify(codexPath))
&& error.message.includes("permissionProfile/list.allowed")
&& error.message.includes("does not support")
&& error.message.includes("Update the Codex installation at that path")
@@ -333,7 +335,7 @@ async function testMalformedAndUnsupportedResponsesFailClosed() {
await assert.rejects(
preflight(codexPath, cwd),
(error) => error?.name === "DeepScanNonRetryableError"
- && error.message.includes(codexPath)
+ && error.message.includes(JSON.stringify(codexPath))
&& error.message.includes("permissionProfile/list")
&& error.message.includes("does not support")
&& error.message.includes("Update the Codex installation at that path")
@@ -352,7 +354,7 @@ async function testEarlyExecutableExitIsNotVersionError() {
await assert.rejects(
preflight(codexPath, cwd),
(error) => error?.name === "DeepScanNonRetryableError"
- && error.message.includes(codexPath)
+ && error.message.includes(JSON.stringify(codexPath))
&& error.message.includes("exited before permission-profile verification completed")
&& error.message.includes("code 17")
&& error.message.includes("with --version")
@@ -372,7 +374,7 @@ async function testNonVersionJsonRpcFailureIsSafe() {
await assert.rejects(
preflight(codexPath, cwd),
(error) => error?.name === "DeepScanNonRetryableError"
- && error.message.includes(codexPath)
+ && error.message.includes(JSON.stringify(codexPath))
&& error.message.includes("config/read")
&& error.message.includes("JSON-RPC code -32603")
&& !error.message.includes("SECRET_REPOSITORY_PATH")
@@ -386,7 +388,7 @@ async function testSpawnErrorFailsClosed() {
await assert.rejects(
preflight(missingCodex, tmpdir()),
(error) => error?.name === "DeepScanNonRetryableError"
- && error.message.includes(missingCodex)
+ && error.message.includes(JSON.stringify(missingCodex))
&& error.message.includes("could not start")
&& error.message.includes("with --version")
&& error.message.includes("CODEX_CLI_PATH/PATH")
@@ -422,7 +424,7 @@ async function testRuntimeFallbackWarningClassification() {
async function testAbortKillsPreflightChild() {
await withFakeCodex({
hangAt: "config/read"
- }, async ({ codexPath, cwd, readyPath, terminatedPath }) => {
+ }, async ({ codexPath, cwd, readyPath, terminatedPath, children }) => {
const controller = new AbortController();
const running = preflightDeepScanWorkerPermissionProfile({
codexPath,
@@ -435,9 +437,19 @@ async function testAbortKillsPreflightChild() {
await waitForFile(readyPath);
controller.abort(new DOMException("fixture aborted", "AbortError"));
await assert.rejects(running, (error) => error?.name === "AbortError");
+ await assertPreflightStopped(children, terminatedPath);
+ });
+}
+
+async function assertPreflightStopped(children, terminatedPath) {
+ if (process.platform === "win32") {
+ // Windows termination need not run the fixture's signal or stdin handlers.
+ assert.equal(children.length, 1);
+ assert.ok(children[0].exitCode !== null || children[0].signalCode !== null);
+ } else {
await waitForFile(terminatedPath);
assert.ok(["SIGTERM", "stdin-end"].includes(await readFile(terminatedPath, "utf8")));
- });
+ }
}
function preflight(codexPath, cwd, env) {
@@ -476,9 +488,10 @@ function catalogResult(allowed) {
};
}
-async function withFakeCodex(scenario, callback) {
+async function withFakeCodex(scenario, callback, { longExecutable = false } = {}) {
const root = await mkdtemp(path.join(tmpdir(), "deep-scan-profile-preflight-"));
- const codexPath = path.join(root, "fake-codex.mjs");
+ const scriptPath = path.join(root, "fake-codex.mjs");
+ let codexPath = scriptPath;
const argvPath = path.join(root, "argv.json");
const callsPath = path.join(root, "calls.jsonl");
const cwdPath = path.join(root, "cwd.json");
@@ -486,11 +499,34 @@ async function withFakeCodex(scenario, callback) {
const readyPath = path.join(root, "ready");
const terminatedPath = path.join(root, "terminated");
const fixture = { ...scenario, argvPath, callsPath, cwdPath, envPath, readyPath, terminatedPath };
- await writeFile(codexPath, fakeCodexSource(fixture), "utf8");
- await chmod(codexPath, 0o755);
+ await writeFile(scriptPath, fakeCodexSource(fixture), "utf8");
+ await chmod(scriptPath, 0o755);
+ const originalSpawn = childProcess.spawn;
+ const children = [];
try {
- await callback({ codexPath, cwd: root, argvPath, callsPath, cwdPath, envPath, readyPath, terminatedPath });
+ if (process.platform === "win32") {
+ codexPath = process.execPath;
+ if (longExecutable) {
+ codexPath = path.join(root, ...Array(10).fill("nested executable directory"), "node.exe");
+ await mkdir(path.dirname(codexPath), { recursive: true });
+ await copyFile(process.execPath, codexPath);
+ assert.ok(codexPath.length > 260);
+ }
+ childProcess.spawn = (command, args, options) => {
+ if (command !== codexPath && command !== path.toNamespacedPath(codexPath)) {
+ return originalSpawn(command, args, options);
+ }
+ // Reuse the protocol script without replacing or normalizing the executable.
+ const child = originalSpawn(command, [scriptPath, ...args], options);
+ children.push(child);
+ return child;
+ };
+ syncBuiltinESMExports();
+ }
+ await callback({ codexPath, cwd: root, argvPath, callsPath, cwdPath, envPath, readyPath, terminatedPath, children });
} finally {
+ childProcess.spawn = originalSpawn;
+ syncBuiltinESMExports();
await rm(root, { recursive: true, force: true });
}
}
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index ca308aadf..aa308ccd5 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -1,5 +1,6 @@
/// <reference lib="esnext.disposable" preserve="true" />
+import { statSync } from "node:fs";
import {
chmod,
lstat,
@@ -13,6 +14,7 @@ import { randomUUID } from "node:crypto";
import { homedir, tmpdir } from "node:os";
import {
basename,
+ delimiter,
dirname,
isAbsolute,
join,
@@ -127,6 +129,7 @@ import {
codexSecurityHasStoredFileCredentials,
codexSecurityStateDirectory,
createIsolatedHome,
+ executablePathForSpawn,
expandHome,
importAmbientAuth,
prepareCodexSecurityCredentialHome,
@@ -2019,15 +2022,27 @@ export class CodexSecurity {
)
? sdkCodexConfig["responses_api_metadata"]
: {};
- const codexPathOverride =
+ let codexPathOverride =
environmentValue(this.#dependencies.environment, "CODEX_CLI_PATH") ===
undefined
? undefined
: this.#codexCommand().command;
+ let sdkEnvironment = definedEnvironment(
+ selectedScanEnvironment(environment, "chatgpt"),
+ );
+ if (process.platform === "win32" && codexPathOverride === undefined) {
+ codexPathOverride = environment["CODEX_CLI_PATH"]!;
+ sdkEnvironment = bundledCodexSdkEnvironment(
+ codexPathOverride,
+ sdkEnvironment,
+ );
+ }
const codex = this.#dependencies.createCodex({
- ...(codexPathOverride === undefined ? {} : { codexPathOverride }),
+ ...(codexPathOverride === undefined
+ ? {}
+ : { codexPathOverride: executablePathForSpawn(codexPathOverride) }),
...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
- env: definedEnvironment(selectedScanEnvironment(environment, "chatgpt")),
+ env: sdkEnvironment,
config: {
...(sdkCodexConfig as NonNullable<CodexOptions["config"]>),
responses_api_metadata: {
@@ -3696,6 +3711,34 @@ function throwIfAborted(signal?: AbortSignal, scanDir = ""): void {
throw new ScanInterruptedError(message, scanDir, { cause: signal.reason });
}
+function bundledCodexSdkEnvironment(
+ command: string,
+ environment: Record<string, string>,
+): Record<string, string> {
+ // An SDK executable override disables its bundled-tool PATH setup.
+ const toolsDirectory = join(dirname(dirname(command)), "codex-path");
+ try {
+ if (!statSync(toolsDirectory).isDirectory()) return environment;
+ } catch {
+ return environment;
+ }
+ const result = { ...environment };
+ const pathKeys = Object.keys(result).filter(
+ (key) => key.toLowerCase() === "path",
+ );
+ const pathKey = pathKeys.includes("Path")
+ ? "Path"
+ : pathKeys.at(-1) ?? "PATH";
+ for (const key of pathKeys) {
+ if (key !== pathKey) delete result[key];
+ }
+ const entries = (result[pathKey] ?? "")
+ .split(delimiter)
+ .filter((entry) => entry.length > 0 && entry !== toolsDirectory);
+ result[pathKey] = [toolsDirectory, ...entries].join(delimiter);
+ return result;
+}
+
function definedEnvironment(
environment: ProcessEnvironment,
): Record<string, string> {
diff --git a/sdk/typescript/src/auth.ts b/sdk/typescript/src/auth.ts
index e45a0ea71..9637bf989 100644
--- a/sdk/typescript/src/auth.ts
+++ b/sdk/typescript/src/auth.ts
@@ -2,6 +2,7 @@ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { isIP } from "node:net";
import { PluginBootstrapError } from "./errors.js";
import {
+ executablePathForSpawn,
runCodexCommand,
type CodexCommand,
type ProcessEnvironment,
@@ -47,7 +48,7 @@ export class CodexLoginHandle {
) {
void this.#urlReady.promise.catch(() => undefined);
void this.#deviceReady.promise.catch(() => undefined);
- this.#child = spawn(command.command, [...args], {
+ this.#child = spawn(executablePathForSpawn(command.command), [...args], {
env: environment,
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 33bf8aca9..3a0b06c1a 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -134,6 +134,7 @@ import {
canonicalizeModelSafePath,
codexSecurityCredentialHome,
codexSecurityStateDirectory,
+ executablePathForSpawn,
expandHome,
prepareCodexSecurityCredentialHome,
pythonUtf8Environment,
@@ -1357,7 +1358,7 @@ export async function runCodexSkillCommand(
expandHome(configuredHome, processEnvironment),
);
}
- const invocation = spawn(command.command, [...args], {
+ const invocation = spawn(executablePathForSpawn(command.command), [...args], {
env: environment,
cwd: output?.appServer?.directory ?? parse(process.execPath).root,
stdio:
diff --git a/sdk/typescript/src/deduplication/codex-review.ts b/sdk/typescript/src/deduplication/codex-review.ts
index 00cd0ed67..833223bfc 100644
--- a/sdk/typescript/src/deduplication/codex-review.ts
+++ b/sdk/typescript/src/deduplication/codex-review.ts
@@ -15,6 +15,7 @@ import {
import {
codexSecurityCredentialHome,
codexSecurityStateDirectory,
+ executablePathForSpawn,
expandHome,
resolveCodexCommand,
} from "../runtime.js";
@@ -118,13 +119,17 @@ export class CodexReviewRunner {
if (apiKey)
args.push("--config", 'cli_auth_credentials_store="ephemeral"');
this.signal?.throwIfAborted();
- const child = this.startCodex(command.command, args, {
- cwd: this.workingDirectory,
- env: { ...environment, CODEX_SQLITE_HOME: directory },
- stdio: ["pipe", "pipe", "pipe"],
- windowsHide: true,
- signal: this.signal,
- });
+ const child = this.startCodex(
+ executablePathForSpawn(command.command),
+ args,
+ {
+ cwd: this.workingDirectory,
+ env: { ...environment, CODEX_SQLITE_HOME: directory },
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ signal: this.signal,
+ },
+ );
const closed = new Promise<void>((resolve) =>
child.once("close", () => resolve()),
);
diff --git a/sdk/typescript/src/publish.ts b/sdk/typescript/src/publish.ts
index eb8321ce9..00df65ae6 100644
--- a/sdk/typescript/src/publish.ts
+++ b/sdk/typescript/src/publish.ts
@@ -58,6 +58,7 @@ import {
} from "./publication-store.js";
import {
codexSecurityStateDirectory,
+ executablePathForSpawn,
resolveCodexCommand,
type CodexCommand,
} from "./runtime.js";
@@ -1527,7 +1528,7 @@ async function runPublicationCodex(
): Promise<PublicationCodexResult> {
signal?.throwIfAborted();
return new Promise((resolve, reject) => {
- const child = spawn(command.command, [...args], {
+ const child = spawn(executablePathForSpawn(command.command), [...args], {
env: environment,
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 59898f0a9..fd1dc70e0 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -38,6 +38,7 @@ import {
relative,
resolve,
sep,
+ win32,
} from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
@@ -2379,6 +2380,16 @@ export function resolveCodexCommand(
return { command };
}
+export function executablePathForSpawn(command: string): string {
+ if (process.platform !== "win32" || !win32.isAbsolute(command))
+ return command;
+ // Root-relative paths still depend on the child's drive and working directory.
+ const root = win32.parse(command).root;
+ return root === "\\" || root === "/"
+ ? command
+ : win32.toNamespacedPath(command);
+}
+
export async function bootstrapPlugin(
codexHome: string,
pluginRoot: string,
@@ -2630,7 +2641,7 @@ export async function runCodexCommand(
input?: string | Uint8Array,
signal?: AbortSignal,
): Promise<CodexCommandResult> {
- const child = spawn(command.command, [...args], {
+ const child = spawn(executablePathForSpawn(command.command), [...args], {
env: environment,
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
diff --git a/sdk/typescript/src/scan-comparison.ts b/sdk/typescript/src/scan-comparison.ts
index 5eb86725c..9b7224e97 100644
--- a/sdk/typescript/src/scan-comparison.ts
+++ b/sdk/typescript/src/scan-comparison.ts
@@ -20,6 +20,7 @@ import {
import { CodexSecurityError } from "./errors.js";
import {
codexSecurityCredentialHome,
+ executablePathForSpawn,
expandHome,
prepareCodexSecurityCredentialHome,
resolveCodexCommand,
@@ -179,7 +180,7 @@ export async function runReadOnlyCodex(
const codex =
options.codex ??
new Codex({
- codexPathOverride: command!.command,
+ codexPathOverride: executablePathForSpawn(command!.command),
env: environment,
config: {
...config,
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index af27c2b5a..54252be8c 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -15,7 +15,7 @@ import * as fsPromises from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync } from "node:fs";
-import { basename, join } from "node:path";
+import { basename, delimiter, dirname, join, win32 } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import {
Codex,
@@ -5385,8 +5385,10 @@ describe("CodexSecurity orchestration", () => {
const scopedSourceInput = join(scanDir, "scoped-source-input.jsonl");
const runScopedHelper = (command: string, args: string[]): void => {
if (process.platform === "win32") {
+ const powershell = Bun.which("powershell.exe");
+ expect(powershell).not.toBeNull();
execFileSync(
- "powershell.exe",
+ powershell!,
["-NoProfile", "-NonInteractive", "-Command", command],
{
cwd: root,
@@ -5808,36 +5810,147 @@ describe("CodexSecurity orchestration", () => {
await client.close();
});
- test("uses one spawnable Codex executable for scans and nested workers", async () => {
+ test.each(["native", "shim"])(
+ "uses one spawnable Codex executable for scans and nested workers (%s)",
+ async (kind) => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ const executable = join(
+ root,
+ process.platform === "win32"
+ ? kind === "shim"
+ ? "custom codex.cmd"
+ : "custom codex.exe"
+ : "custom codex",
+ );
+ const selectedExecutable =
+ process.platform === "win32" && kind === "shim"
+ ? resolveCodexCommand({}).command
+ : executable;
+ await mkdir(repository);
+ await mkdir(codexHome);
+ await mkdir(scanDir, { mode: 0o700 });
+ let codexOptions: CodexOptions | null = null;
+ const client = new TestClient(
+ {},
+ {
+ environment: {
+ OPENAI_API_KEY: "ambient-key",
+ CODEX_CLI_PATH: ` ${executable} `,
+ PATH: "custom search path",
+ },
+ prepareRuntime: async () => ({
+ ...preparedRuntime(codexHome),
+ environment: {
+ CODEX_HOME: codexHome,
+ CODEX_CLI_PATH: ` ${executable} `,
+ PATH: "custom search path",
+ },
+ }),
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ createCodex: (options: CodexOptions) => {
+ codexOptions = options;
+ return {
+ startThread: () => ({
+ id: null,
+ async runStreamed() {
+ await copyCompletedScan(root);
+ return { events: completedEvents() };
+ },
+ }),
+ };
+ },
+ },
+ );
+
+ await client.run(repository);
+ expect((codexOptions as CodexOptions | null)?.codexPathOverride).toBe(
+ process.platform === "win32"
+ ? win32.toNamespacedPath(selectedExecutable)
+ : selectedExecutable,
+ );
+ expect(
+ (codexOptions as CodexOptions | null)?.env?.["CODEX_CLI_PATH"],
+ ).toBe(selectedExecutable);
+ expect((codexOptions as CodexOptions | null)?.env?.["PATH"]).toBe(
+ "custom search path",
+ );
+ await client.close();
+ },
+ );
+
+ test.each([
+ "Path alias",
+ "last alias",
+ "no PATH",
+ "missing tools",
+ "non-directory tools",
+ "blank override",
+ ])("preserves default SDK bundled tools for %s", async (scenario) => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
const codexHome = join(root, "codex-home");
const scanDir = join(root, "scan");
const executable = join(
root,
- process.platform === "win32" ? "custom codex.cmd" : "custom codex",
- );
- const selectedExecutable =
- process.platform === "win32"
- ? resolveCodexCommand({}).command
- : executable;
- await mkdir(repository);
- await mkdir(codexHome);
- await mkdir(scanDir, { mode: 0o700 });
+ "vendor",
+ "synthetic-target",
+ "bin",
+ process.platform === "win32" ? "codex.exe" : "codex",
+ );
+ const toolsDirectory = join(dirname(dirname(executable)), "codex-path");
+ const otherTools = join(root, "other tools");
+ const pathEnvironment: Record<string, string> =
+ scenario === "no PATH"
+ ? {}
+ : scenario === "last alias"
+ ? { PATH: "discarded", pAtH: otherTools }
+ : {
+ PATH: "discarded",
+ Path: [
+ "",
+ toolsDirectory,
+ otherTools,
+ toolsDirectory,
+ otherTools.toUpperCase(),
+ "",
+ ].join(delimiter),
+ pAtH: "discarded-last",
+ };
+ await Promise.all([
+ mkdir(repository),
+ mkdir(codexHome),
+ mkdir(scanDir, { mode: 0o700 }),
+ mkdir(dirname(executable), { recursive: true }),
+ ]);
+ await writeFile(executable, "synthetic executable; never launched\n");
+ const hasTools =
+ scenario !== "missing tools" && scenario !== "non-directory tools";
+ if (hasTools) await mkdir(toolsDirectory);
+ else if (scenario === "non-directory tools")
+ await writeFile(toolsDirectory, "not a directory\n");
+ const callerEnvironment = {
+ OPENAI_API_KEY: "ambient-key",
+ ...(scenario === "blank override" ? { CODEX_CLI_PATH: " " } : {}),
+ };
+ const runtimeEnvironment = {
+ CODEX_HOME: codexHome,
+ CODEX_CLI_PATH: executable,
+ ...pathEnvironment,
+ };
+ const originalEnvironment = { ...runtimeEnvironment };
let codexOptions: CodexOptions | null = null;
const client = new TestClient(
{},
{
- environment: {
- OPENAI_API_KEY: "ambient-key",
- CODEX_CLI_PATH: ` ${executable} `,
- },
+ environment: callerEnvironment,
prepareRuntime: async () => ({
...preparedRuntime(codexHome),
- environment: {
- CODEX_HOME: codexHome,
- CODEX_CLI_PATH: ` ${executable} `,
- },
+ environment: runtimeEnvironment,
}),
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
@@ -5856,15 +5969,45 @@ describe("CodexSecurity orchestration", () => {
},
},
);
-
- await client.run(repository);
- expect((codexOptions as CodexOptions | null)?.codexPathOverride).toBe(
- selectedExecutable,
- );
- expect((codexOptions as CodexOptions | null)?.env?.["CODEX_CLI_PATH"]).toBe(
- selectedExecutable,
- );
- await client.close();
+ try {
+ await client.run(repository);
+ const options = codexOptions as CodexOptions | null;
+ expect(options?.codexPathOverride).toBe(
+ process.platform === "win32"
+ ? win32.toNamespacedPath(executable)
+ : undefined,
+ );
+ expect(options?.env?.["CODEX_CLI_PATH"]).toBe(executable);
+ const pathValues = Object.fromEntries(
+ Object.entries(options?.env ?? {}).filter(
+ ([key]) => key.toLowerCase() === "path",
+ ),
+ );
+ const pathKey =
+ scenario === "last alias"
+ ? "pAtH"
+ : scenario === "no PATH"
+ ? "PATH"
+ : "Path";
+ const expectedEntries =
+ scenario === "no PATH"
+ ? []
+ : scenario === "last alias"
+ ? [otherTools]
+ : [otherTools, otherTools.toUpperCase()];
+ expect(pathValues).toEqual(
+ process.platform === "win32" && hasTools
+ ? { [pathKey]: [toolsDirectory, ...expectedEntries].join(delimiter) }
+ : pathEnvironment,
+ );
+ expect(runtimeEnvironment).toEqual(originalEnvironment);
+ expect(callerEnvironment).toEqual({
+ OPENAI_API_KEY: "ambient-key",
+ ...(scenario === "blank override" ? { CODEX_CLI_PATH: " " } : {}),
+ });
+ } finally {
+ await client.close();
+ }
});
test("authenticates without initializing the plugin runtime", async () => {
@@ -5984,9 +6127,11 @@ process.exit(2);
verified: false,
});
expect((codexOptions as CodexOptions | null)?.apiKey).toBe("ambient-key");
- expect(
- (codexOptions as CodexOptions | null)?.codexPathOverride,
- ).toBeUndefined();
+ expect((codexOptions as CodexOptions | null)?.codexPathOverride).toBe(
+ process.platform === "win32"
+ ? win32.toNamespacedPath(resolveCodexCommand({}).command)
+ : undefined,
+ );
expect(
Object.keys((codexOptions as CodexOptions | null)?.env ?? {}).some(
(name) =>
diff --git a/sdk/typescript/tests-ts/codex-review.test.ts b/sdk/typescript/tests-ts/codex-review.test.ts
index 4c09ea556..613040ca6 100644
--- a/sdk/typescript/tests-ts/codex-review.test.ts
+++ b/sdk/typescript/tests-ts/codex-review.test.ts
@@ -2,10 +2,11 @@ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { existsSync } from "node:fs";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
-import { join, resolve } from "node:path";
+import { join, resolve, win32 } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, mock, test } from "bun:test";
import { CodexReviewRunner } from "../src/deduplication/codex-review.js";
+import { resolveCodexCommand } from "../src/runtime.js";
import { environmentEntry } from "../src/scan-comparison.js";
import { runTestInSubprocess } from "./support/test-subprocess.js";
@@ -83,7 +84,13 @@ for (const {
[ghName]: ghConfig,
...extraEnvironment,
},
- (_command, commandArgs, options) => {
+ (command, commandArgs, options) => {
+ const selected = resolveCodexCommand({}).command;
+ expect(command).toBe(
+ process.platform === "win32"
+ ? win32.toNamespacedPath(selected)
+ : selected,
+ );
args = commandArgs;
directory = options.env!["CODEX_SQLITE_HOME"];
expect(options.cwd).toBe(checkout);
diff --git a/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts b/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts
index 594ce173f..ddcda61fe 100644
--- a/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts
+++ b/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts
@@ -58,6 +58,7 @@ async function bundledWorkerExecutor(
"DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID",
"deepScanPermissionProfileFallbackError",
"resolveCodexPath",
+ "executablePathForSpawn",
"workerSubagentConfig",
"appendSafeItemDiagnostic",
"classifyCodexWorkerError",
@@ -72,6 +73,7 @@ async function bundledWorkerExecutor(
"codex_security_deep_scan_worker",
() => undefined,
() => "/fixture/codex",
+ (path: string) => path,
() => ({}),
() => {},
(error: unknown) => error,
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index 8317823a3..07c142f1f 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -30,6 +30,7 @@ import {
parse,
relative,
sep,
+ win32,
} from "node:path";
import { PassThrough } from "node:stream";
import { setImmediate as nextTurn } from "node:timers/promises";
@@ -38,6 +39,7 @@ import { fileURLToPath } from "node:url";
import { brotliDecompressSync } from "node:zlib";
import { afterEach, describe, expect, mock, spyOn, test } from "bun:test";
import { strToU8, zipSync } from "fflate";
+import { build } from "esbuild";
import {
BUNDLED_PLUGIN_VERSION,
bootstrapPlugin,
@@ -63,6 +65,7 @@ import {
codexSecurityCredentialHome,
codexSecurityHasStoredFileCredentials,
codexSecurityStateDirectory,
+ executablePathForSpawn,
inspectWindowsCredentialAcl,
inspectWindowsCredentialAclSnapshot,
isPythonPathCandidate,
@@ -2096,6 +2099,108 @@ describe("plugin runtime preparation", () => {
});
});
+ test.each([
+ [
+ "drive",
+ String.raw`C:\Program Files\codex.exe`,
+ String.raw`\\?\C:\Program Files\codex.exe`,
+ ],
+ [
+ "drive with forward slashes",
+ "C:/tools/codex.exe",
+ String.raw`\\?\C:\tools\codex.exe`,
+ ],
+ [
+ "UNC",
+ String.raw`\\server\share\codex.exe`,
+ String.raw`\\?\UNC\server\share\codex.exe`,
+ ],
+ [
+ "namespaced",
+ String.raw`\\?\C:\tools\codex.exe`,
+ String.raw`\\?\C:\tools\codex.exe`,
+ ],
+ ["bare", "codex.exe", "codex.exe"],
+ ["relative", String.raw`.\tools\codex.exe`, String.raw`.\tools\codex.exe`],
+ ["drive-relative", "C:codex.exe", "C:codex.exe"],
+ [
+ "root-relative",
+ String.raw`\tools\codex.exe`,
+ String.raw`\tools\codex.exe`,
+ ],
+ ["slash-root-relative", "/tools/codex.exe", "/tools/codex.exe"],
+ ["tilde", "~/tools/codex", "~/tools/codex"],
+ ])(
+ "preserves executable lookup semantics for %s paths",
+ (_name, command, windowsCommand) => {
+ expect(executablePathForSpawn(command!)).toBe(
+ process.platform === "win32" ? windowsCommand : command,
+ );
+ },
+ );
+
+ test.skipIf(process.platform !== "win32")(
+ "launches long Windows executable paths through the Node runtime",
+ async () => {
+ const root = await temporaryDirectory();
+ const { stdout } = await promisify(execFile)(
+ "node",
+ ["-p", "process.execPath"],
+ {
+ encoding: "utf8",
+ timeout: 10_000,
+ windowsHide: true,
+ },
+ );
+ const node = stdout.trim();
+ const executable = join(
+ root,
+ ...Array<string>(10).fill("nested executable directory"),
+ "node.exe",
+ );
+ await mkdir(dirname(executable), { recursive: true });
+ await copyFile(node, executable);
+ expect(executable.length).toBeGreaterThan(260);
+
+ const runtimeSource = new URL("../src/runtime.ts", import.meta.url);
+ const runtimeModule = join(root, "runtime.cjs");
+ await build({
+ entryPoints: [fileURLToPath(runtimeSource)],
+ outfile: runtimeModule,
+ bundle: true,
+ platform: "node",
+ format: "cjs",
+ define: { "import.meta.url": JSON.stringify(runtimeSource.href) },
+ });
+ const script = [
+ "const { runCodexCommand } = require(process.argv[1]);",
+ "runCodexCommand({ command: process.argv[2] }, ['--eval', \"process.stdout.write('synthetic launch')\"], process.env)",
+ " .then((result) => process.stdout.write(JSON.stringify(result)), (error) => { console.error(error); process.exitCode = 1; });",
+ ].join("\n");
+ for (const command of [
+ node,
+ executable,
+ win32.toNamespacedPath(executable),
+ ]) {
+ const result = await promisify(execFile)(
+ node,
+ ["--eval", script, runtimeModule, command],
+ {
+ encoding: "utf8",
+ timeout: 10_000,
+ windowsHide: true,
+ },
+ );
+ expect(JSON.parse(result.stdout)).toEqual({
+ success: true,
+ exitCode: 0,
+ stdout: "synthetic launch",
+ stderr: "",
+ });
+ }
+ },
+ );
+
test("replaces unspawnable Windows Codex shims with the bundled executable", () => {
const fallback = resolveCodexCommand({});
diff --git a/sdk/typescript/tests-ts/scan-comparison.test.ts b/sdk/typescript/tests-ts/scan-comparison.test.ts
index 077b1177c..5417ff9a4 100644
--- a/sdk/typescript/tests-ts/scan-comparison.test.ts
+++ b/sdk/typescript/tests-ts/scan-comparison.test.ts
@@ -8,7 +8,7 @@ import {
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { join, win32 } from "node:path";
import {
Codex,
type CodexOptions,
@@ -115,6 +115,7 @@ describe("semantic scan comparison", () => {
const { codex } = fakeCodex({ matches: [], uncertain: [] });
let config: CodexOptions["config"];
let codexPath: string | undefined;
+ let codexEnvironment: CodexOptions["env"];
const startThread = spyOn(
Codex.prototype,
"startThread",
@@ -122,6 +123,8 @@ describe("semantic scan comparison", () => {
config = (this as unknown as { options: CodexOptions }).options.config;
codexPath = (this as unknown as { options: CodexOptions }).options
.codexPathOverride;
+ codexEnvironment = (this as unknown as { options: CodexOptions }).options
+ .env;
return codex.startThread(options!) as ReturnType<Codex["startThread"]>;
});
try {
@@ -143,7 +146,12 @@ describe("semantic scan comparison", () => {
synthetic: { command: "synthetic-integration", enabled: false },
inherited: { enabled: false },
});
- expect(codexPath).toBe(executable);
+ expect(codexPath).toBe(
+ process.platform === "win32"
+ ? win32.toNamespacedPath(executable)
+ : executable,
+ );
+ expect(codexEnvironment?.["CODEX_CLI_PATH"]).toBe(executable);
const effective = await runCodexCommand(
resolveCodexCommand(environment),
[