Skip to content

feat: add support for GitHub Copilot API integration and enhance exec… #1336

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 39 additions & 4 deletions codex-cli/src/cli.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
} from "./utils/config";
import {
getApiKey as fetchApiKey,
getGithubCopilotApiKey as fetchGithubCopilotApiKey,
maybeRedeemCredits,
} from "./utils/get-api-key";
import { createInputItem } from "./utils/input-utils";
Expand Down Expand Up @@ -322,13 +323,43 @@ try {
if (data.OPENAI_API_KEY && !expired) {
apiKey = data.OPENAI_API_KEY;
}
if (
data.GITHUBCOPILOT_API_KEY &&
provider.toLowerCase() === "githubcopilot"
) {
apiKey = data.GITHUBCOPILOT_API_KEY;
}
}
} catch {
// ignore errors
}

if (cli.flags.login) {
apiKey = await fetchApiKey(client.issuer, client.client_id);
if (provider.toLowerCase() === "githubcopilot" && !apiKey) {
apiKey = await fetchGithubCopilotApiKey();
try {
const home = os.homedir();
const authDir = path.join(home, ".codex");
const authFile = path.join(authDir, "auth.json");
fs.writeFileSync(
authFile,
JSON.stringify(
{
GITHUBCOPILOT_API_KEY: apiKey,
},
null,
2,
),
"utf-8",
);
} catch {
/* ignore */
}
} else if (cli.flags.login) {
if (provider.toLowerCase() === "githubcopilot") {
apiKey = await fetchGithubCopilotApiKey();
Comment on lines +338 to +359
Copy link
Preview

Copilot AI Jun 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The login flow for GitHub Copilot is duplicated in multiple branches, making the CLI logic hard to follow. Consider consolidating into a single helper or clearer conditional structure.

Suggested change
apiKey = await fetchGithubCopilotApiKey();
try {
const home = os.homedir();
const authDir = path.join(home, ".codex");
const authFile = path.join(authDir, "auth.json");
fs.writeFileSync(
authFile,
JSON.stringify(
{
GITHUBCOPILOT_API_KEY: apiKey,
},
null,
2,
),
"utf-8",
);
} catch {
/* ignore */
}
} else if (cli.flags.login) {
if (provider.toLowerCase() === "githubcopilot") {
apiKey = await fetchGithubCopilotApiKey();
apiKey = await handleGithubCopilotLogin();
} else if (cli.flags.login) {
if (provider.toLowerCase() === "githubcopilot") {
apiKey = await handleGithubCopilotLogin();

Copilot uses AI. Check for mistakes.

} else {
apiKey = await fetchApiKey(client.issuer, client.client_id);
}
try {
const home = os.homedir();
const authDir = path.join(home, ".codex");
Expand All @@ -341,10 +372,14 @@ if (cli.flags.login) {
/* ignore */
}
} else if (!apiKey) {
apiKey = await fetchApiKey(client.issuer, client.client_id);
if (provider.toLowerCase() === "githubcopilot") {
apiKey = await fetchGithubCopilotApiKey();
} else {
apiKey = await fetchApiKey(client.issuer, client.client_id);
}
}
// Ensure the API key is available as an environment variable for legacy code
process.env["OPENAI_API_KEY"] = apiKey;
process.env[`${provider.toUpperCase()}_API_KEY`] = apiKey;

if (cli.flags.free) {
// eslint-disable-next-line no-console
Expand Down
19 changes: 19 additions & 0 deletions codex-cli/src/utils/agent/agent-loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
} from "../session.js";
import { applyPatchToolInstructions } from "./apply-patch.js";
import { handleExecCommand } from "./handle-exec-command.js";
import { GithubCopilotClient } from "../openai-client.js";
import { HttpsProxyAgent } from "https-proxy-agent";
import { spawnSync } from "node:child_process";
import { randomUUID } from "node:crypto";
Expand Down Expand Up @@ -350,6 +351,24 @@ export class AgentLoop {
});
}

if (this.provider.toLowerCase() === "githubcopilot") {
Copy link
Preview

Copilot AI Jun 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This block re-instantiates oai for GitHub Copilot after it was already created by createOpenAIClient, leading to duplicated logic and potential configuration drift.

Copilot uses AI. Check for mistakes.

this.oai = new GithubCopilotClient({
...(apiKey ? { apiKey } : {}),
baseURL,
defaultHeaders: {
originator: ORIGIN,
version: CLI_VERSION,
session_id: this.sessionId,
...(OPENAI_ORGANIZATION
? { "OpenAI-Organization": OPENAI_ORGANIZATION }
: {}),
...(OPENAI_PROJECT ? { "OpenAI-Project": OPENAI_PROJECT } : {}),
},
httpAgent: PROXY_URL ? new HttpsProxyAgent(PROXY_URL) : undefined,
...(timeoutMs !== undefined ? { timeout: timeoutMs } : {}),
});
}

setSessionId(this.sessionId);
setCurrentModel(this.model);

Expand Down
2 changes: 2 additions & 0 deletions codex-cli/src/utils/agent/exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export function execApplyPatch(
stdout: result,
stderr: "",
exitCode: 0,
pid: 0,
};
} catch (error: unknown) {
// @ts-expect-error error might not be an object or have a message property.
Expand All @@ -128,6 +129,7 @@ export function execApplyPatch(
stdout: "",
stderr: stderr,
exitCode: 1,
pid: 0,
};
}
}
Expand Down
2 changes: 2 additions & 0 deletions codex-cli/src/utils/agent/sandbox/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ export type ExecResult = {
stdout: string;
stderr: string;
exitCode: number;
/** PID of the spawned process. 0 if spawn failed */
pid: number;
};

/**
Expand Down
8 changes: 6 additions & 2 deletions codex-cli/src/utils/agent/sandbox/raw-exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export function exec(
stdout: "",
stderr: "command[0] is not a string",
exitCode: 1,
pid: 0,
});
}

Expand Down Expand Up @@ -124,7 +125,7 @@ export function exec(
if (!child.killed) {
killTarget("SIGKILL");
}
}, 2000).unref();
}, 250).unref();
};
if (abortSignal.aborted) {
abortHandler();
Expand Down Expand Up @@ -186,6 +187,7 @@ export function exec(
stdout,
stderr,
exitCode,
pid: child.pid ?? 0,
};
resolve(
addTruncationWarningsIfNecessary(
Expand All @@ -201,6 +203,7 @@ export function exec(
stdout: "",
stderr: String(err),
exitCode: 1,
pid: child.pid ?? 0,
};
resolve(
addTruncationWarningsIfNecessary(
Expand All @@ -224,7 +227,7 @@ function addTruncationWarningsIfNecessary(
if (!hitMaxStdout && !hitMaxStderr) {
return execResult;
} else {
const { stdout, stderr, exitCode } = execResult;
const { stdout, stderr, exitCode, pid } = execResult;
return {
stdout: hitMaxStdout
? stdout + "\n\n[Output truncated: too many lines or bytes]"
Expand All @@ -233,6 +236,7 @@ function addTruncationWarningsIfNecessary(
? stderr + "\n\n[Output truncated: too many lines or bytes]"
: stderr,
exitCode,
pid,
};
}
}
29 changes: 28 additions & 1 deletion codex-cli/src/utils/get-api-key.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import type { Choice } from "./get-api-key-components";
import type { Request, Response } from "express";

import { ApiKeyPrompt, WaitingForAuth } from "./get-api-key-components";
import { GithubCopilotClient } from "./openai-client.js";
import Spinner from "../components/vendor/ink-spinner.js";
import chalk from "chalk";
import express from "express";
import fs from "fs/promises";
import { render } from "ink";
import { Box, Text, render } from "ink";
import crypto from "node:crypto";
import { URL } from "node:url";
import open from "open";
Expand Down Expand Up @@ -763,4 +765,29 @@ export async function getApiKey(
}
}

export async function getGithubCopilotApiKey(): Promise<string> {
const { device_code, user_code, verification_uri } =
await GithubCopilotClient.getLoginURL();
const spinner = render(
<Box flexDirection="row" marginTop={1}>
<Spinner type="ball" />
<Text>
{" "}
Please visit {verification_uri} and enter code {user_code}
</Text>
</Box>,
);
try {
const key = await GithubCopilotClient.pollForAccessToken(device_code);
spinner.clear();
spinner.unmount();
process.env["GITHUBCOPILOT_API_KEY"] = key;
return key;
} catch (err) {
spinner.clear();
spinner.unmount();
throw err;
}
}

export { maybeRedeemCredits };
Loading