Skip to content

Commit 48412ff

Browse files
authored
Allow spawning codex by passing cli subcommand (#127)
1 parent fac4afb commit 48412ff

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

src/CodexCli.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import type {ChildProcess, SpawnOptions} from "node:child_process";
2+
import {spawn} from "node:child_process";
3+
import {createRequire} from "node:module";
4+
5+
export function runCodexCli(codexPath: string | undefined, args: Array<string>): Promise<number> {
6+
const child = spawnCodexCli(codexPath, args);
7+
8+
return new Promise((resolve, reject) => {
9+
child.on("error", reject);
10+
child.on("exit", (code, signal) => {
11+
if (signal) {
12+
process.kill(process.pid, signal);
13+
return;
14+
}
15+
resolve(code ?? 1);
16+
});
17+
});
18+
}
19+
20+
function spawnCodexCli(codexPath: string | undefined, args: Array<string>): ChildProcess {
21+
const options: SpawnOptions = {
22+
env: process.env,
23+
stdio: "inherit",
24+
};
25+
26+
if (codexPath) {
27+
return spawn(codexPath, args, {...options, shell: process.platform === "win32"});
28+
}
29+
const bundledCodexPath = createRequire(import.meta.url).resolve("@openai/codex/bin/codex.js");
30+
return spawn(process.execPath, [bundledCodexPath, ...args], options);
31+
}

src/index.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {CodexAppServerClient} from "./CodexAppServerClient";
1010
import packageJson from "../package.json";
1111
import {logger} from "./Logger";
1212
import {runLoginCommand} from "./login";
13+
import {runCodexCli} from "./CodexCli";
1314

1415
if (process.argv.includes("--version")) {
1516
console.log(`${packageJson.name} ${packageJson.version}`);
@@ -24,6 +25,14 @@ if (process.argv[2] === "login") {
2425
console.error("Login error:", error.message);
2526
process.exit(1);
2627
});
28+
} else if (process.argv[2] === "cli") {
29+
const args = process.argv.slice(3);
30+
runCodexCli(process.env["CODEX_PATH"], args)
31+
.then((exitCode) => process.exit(exitCode))
32+
.catch((error) => {
33+
console.error("Codex CLI error:", error.message);
34+
process.exit(1);
35+
});
2736
} else {
2837
startAcpServer();
2938
}

0 commit comments

Comments
 (0)