@bitkyc08/opencodex
Version:
Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code
427 lines (406 loc) • 22.1 kB
text/typescript
import * as readline from "node:readline";
import { modelSelectionGuidance } from "../cli/model-selection-guidance";
import { initializeProviderModelSelection } from "../providers/initial-model-selection";
import { openUrl } from "../lib/open-url";
import { createBrowserLaunchReport } from "../lib/browser-launch-notice";
import { isAgyAcpProvider } from "../config/schema/agy-acp-references";
import { loadConfig, saveConfig } from "../config";
import { findLiveProxy } from "../server/proxy-liveness";
import {
requestBoundLocalProviderReload,
type LocalProviderReloadResult,
} from "../server/local-provider-reload-client";
import { DEPRECATED_OAUTH_PROVIDER_ALIASES, isPublicOAuthProvider, listOAuthProviders, publicOAuthAuthenticationErrorMessage, runLogin, supportsCodeLoginMode, supportsDeviceLoginMode } from "./index";
import { classifyLoginCodeError } from "./login-flow-state";
import { KEY_LOGIN_PROVIDERS, isKeyLoginProvider, validateApiKey, type KeyLoginProvider } from "./key-providers";
import type { OcxConfig, OcxProviderConfig } from "../types";
import { configuredAdminToken } from "../lib/admin-secrets";
import { codexAccountNamespaceProviderCollisionError } from "../codex/account-namespace-match";
import { assertAnthropicInstanceLoginConfig } from "./store-anthropic-instance";
import { reportOAuthLoginError } from "./login-cli-errors";
import { terminalSafeText } from "../lib/terminal-safe-text";
import {
ANTIGRAVITY_RISK_CLI_FLAG,
antigravityRiskDecisionMessage,
requiresAntigravityRiskAcknowledgement,
resolveAntigravityRiskAcknowledgement,
} from "./antigravity-risk";
import { isAgentDriven } from "../cli/agent-driven";
/**
* Seams a test drives in place of a browser, a terminal and a real provider. Production passes
* none of them.
*
* They exist because the thing worth proving here is an ORDER — that a browser which did not
* open is on screen before the question that assumes it did — and an order is only observable
* from something that records both events. Spawning a launcher and attaching to stdin to find
* that out would test the operating system instead.
*/
export interface LoginCliDeps {
runLogin?: typeof runLogin;
openUrl?: typeof openUrl;
warn?: (message: string) => void;
/** Ask one question, read one line. Defaults to a readline prompt that owns its own lifetime. */
ask?: (question: string) => Promise<string>;
/** Whether a person can answer a prompt. Defaults to stdin and stdout both being terminals. */
isInteractive?: () => boolean;
/** Whether a coding agent or CI runner drives this process. Defaults to isAgentDriven(). */
agentDriven?: () => boolean;
}
/**
* Run `body` with a line reader, creating and closing a real one only when the caller did not
* supply its own. A readline interface attaches to stdin, so building one that nothing will ask
* a question keeps the process alive for no reason.
*/
async function withPrompt<T>(
supplied: ((question: string) => Promise<string>) | undefined,
body: (ask: (question: string) => Promise<string>) => Promise<T>,
): Promise<T> {
if (supplied) return await body(supplied);
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
try {
return await body(question => new Promise<string>(resolve => rl.question(question, resolve)));
} finally {
rl.close();
}
}
const LIVE_RELOAD_PROVIDERS = new Set<string>([
...listOAuthProviders(),
...Object.keys(KEY_LOGIN_PROVIDERS),
]);
export function runningProxyUpdateHeaders(): Headers {
const headers = new Headers({ "Content-Type": "application/json" });
const adminToken = configuredAdminToken();
if (adminToken) headers.set("X-OpenCodex-API-Key", adminToken);
return headers;
}
/**
* Ask the attested runtime to reload one already-persisted provider.
*
* Returns the outcome instead of swallowing it. A running proxy that predates
* attested reload — or one whose runtime record no longer matches — cannot adopt
* the new credential, and the caller has to say so: the credential is on disk, but
* the live process keeps routing with the old one until it restarts. Silently
* printing success there is how a login appears to work and then does not.
*/
export async function notifyRunningProxy(name: string): Promise<LocalProviderReloadResult | null> {
if (!LIVE_RELOAD_PROVIDERS.has(name)) return null;
const live = await findLiveProxy();
if (!live) return null;
return await requestBoundLocalProviderReload(live, name);
}
/**
* After `runLogin()` has persisted the merged provider (including preserved apiKey /
* apiKeyPool / authMode), ask the attested proxy to reload that exact on-disk entry.
*/
export async function notifyRunningProxyAfterOAuthLogin(name: string): Promise<LocalProviderReloadResult | null> {
if (!loadConfig().providers[name]) return null;
return await notifyRunningProxy(name);
}
/**
* A live proxy was found but could not adopt the credential. `null` means there was
* nothing to notify (no running proxy, or a provider that never reloads live), which
* is not a warning-worthy state.
*/
export function warnIfLiveReloadSkipped(result: LocalProviderReloadResult | null): void {
if (!result || result.kind === "reloaded") return;
console.warn(
`\n⚠️ A proxy is running but could not reload this provider (${result.reason}).`
+ `\n The credential is saved to disk; the running proxy keeps using the previous one.`
+ `\n Restart it to pick this up: ocx restart`,
);
}
/**
* The provider wall is the first thing an unfamiliar user sees, so it names the Codex
* route before the ~90 provider ids. 'codex' is not in either list on purpose: it is
* routed to the account-pool login in dispatch.ts, and 'chatgpt' stays off the public
* OAuth surface (isPublicOAuthProvider) because the pool owns that credential.
*
* It names 'openai-apikey' for the same reason it exists at all: 'openai' now routes to
* the pool, so someone who typed it looking for a platform key no longer sees the list
* that used to be their only pointer to it.
*/
export function loginUsageMessage(): string {
return `Usage: ocx login <provider> [--headless] [${ANTIGRAVITY_RISK_CLI_FLAG}]\n`
+ ` --headless: no browser and no local port — approve in any browser, then paste the code\n`
+ ` it shows or confirm the device code printed here\n`
+ ` (${listCodeLoginProviders().join(", ")})\n`
+ ` ${ANTIGRAVITY_RISK_CLI_FLAG}: google-antigravity only; accept the account-ban risk without\n`
+ ` the interactive prompt (the warning is still printed)\n`
+ ` Codex / ChatGPT: ocx login codex (account pool, needs a running proxy; 'chatgpt' and\n`
+ ` 'openai' are the same route. An OpenAI platform key is 'openai-apikey'.)\n`
+ ` OAuth login: ${listOAuthProviders().join(", ")}\n`
+ ` API-key login: ${Object.keys(KEY_LOGIN_PROVIDERS).join(", ")}`;
}
export interface LoginCliOptions {
/** `--headless`: no callback server, no browser launch — print the URL and read back the code. */
codeMode?: boolean;
/** `--accept-antigravity-risk`: accept the Antigravity warning without a prompt. */
acceptAntigravityRisk?: boolean;
}
const AGY_ACP_SIGN_IN = "Sign in on the proxy host with: agy acp --login";
export async function handleLogin(provider?: string, deps: LoginCliDeps = {}, opts: LoginCliOptions = {}): Promise<void> {
const name = (provider ?? "").trim().toLowerCase();
if (opts.acceptAntigravityRisk && !requiresAntigravityRiskAcknowledgement(DEPRECATED_OAUTH_PROVIDER_ALIASES[name] ?? name)) {
console.error(`${ANTIGRAVITY_RISK_CLI_FLAG} only applies to google-antigravity`);
process.exit(1);
}
try {
// Check raw ownership before tolerant loading can print diagnostics or fall back to defaults.
if (name === "anthropic2") assertAnthropicInstanceLoginConfig({ providers: {} }, name);
} catch (error) {
reportOAuthLoginError(error);
}
// A removed provider id reached through its alias still logs in — the merged
// successor owns the flow. Warn rather than silently reroute so scripts and
// docs that still say `devin-cli` surface the rename to whoever runs them.
const alias = DEPRECATED_OAUTH_PROVIDER_ALIASES[name];
if (alias) {
console.error(`${name} is deprecated; logging in as ${alias}`);
return handleOAuthLogin(alias, deps, opts);
}
if (isAgyAcpProvider(name, undefined)) {
console.log(AGY_ACP_SIGN_IN);
return;
}
if (isPublicOAuthProvider(name)) return handleOAuthLogin(name, deps, opts);
if (opts.codeMode) {
console.error(`--headless needs a provider with a code-display or device login: ${listCodeLoginProviders().join(", ")}`);
process.exit(1);
}
if (isKeyLoginProvider(name)) return handleKeyLogin(name, deps);
console.error(loginUsageMessage());
process.exit(1);
}
/** OAuth providers that accept `ocx login <provider> --headless`: a code-display or a device login. */
export function listCodeLoginProviders(): string[] {
return listOAuthProviders().filter(name => supportsCodeLoginMode(name) || supportsDeviceLoginMode(name));
}
/**
* `--headless`: nothing is launched and nothing listens, because the browser is on another machine.
* A code-display provider shows the authorization code to paste back here; a provider with only a
* device grant (xAI) shows a short code to confirm in that browser and settles on its own, so the
* same branch serves both and only the paste step differs (see `device` below).
*/
async function handleCodeLogin(name: string, deps: LoginCliDeps): Promise<void> {
const login = deps.runLogin ?? runLogin;
// A provider without a code-display page but with a device grant (xAI) is headless the same
// way: the browser is elsewhere and nothing listens here. It shows a code instead of asking for one.
const device = !supportsCodeLoginMode(name) && supportsDeviceLoginMode(name);
if (!device && !supportsCodeLoginMode(name)) {
console.error(`${name} has no headless login (code-display or device). Providers that have one: ${listCodeLoginProviders().join(", ")}`);
process.exit(1);
}
try {
await withPrompt(deps.ask, async (ask) => {
await login(name, {
onAuth: ({ url, instructions }) => {
// Both are provider-supplied. `--headless` for xAI is the device grant, whose instructions
// quote the provider's user code; a control sequence there would drive this tty.
console.log(`\n🔐 Open this URL in any browser to approve ${name}:\n${terminalSafeText(url)}\n`);
if (instructions) console.log(terminalSafeText(instructions));
},
// The Meta Muse device flow's last line quotes an action URL from the provider payload, so
// this is not a fixed sentence: it is provider-derived text on its way to a tty.
onProgress: (m) => console.log(` ${terminalSafeText(m)}`),
onManualCodeInput: async () => await ask("Paste the code shown after approval: "),
}, device ? { flow: "device" } : { codeMode: true });
});
} catch (error) {
// Never let the raw error reach stderr: a token endpoint's error body can quote the pasted
// code back. Only fixed, allowlisted text and the machine-readable reason are printed.
// The reason comes from the same classifier the management API reports, so a definitive
// refusal (a redirect the client will not follow) reads as `oauth_authentication_failed`
// here and in `GET /api/oauth/status` rather than as a bad code or a network fault.
const reason = classifyLoginCodeError(error);
console.error(`\n❌ ${name} login failed (${reason}): ${publicOAuthAuthenticationErrorMessage(error)}`);
process.exit(1);
}
const reload = await notifyRunningProxyAfterOAuthLogin(name);
console.log(`\n✅ Logged in to ${name}. Try: ocx sync`);
for (const line of modelSelectionGuidance(name)) console.log(line);
warnIfLiveReloadSkipped(reload);
}
export async function handleOAuthLogin(name: string, deps: LoginCliDeps = {}, opts: LoginCliOptions = {}): Promise<void> {
if (name === "anthropic2") assertAnthropicInstanceLoginConfig(loadConfig(), name);
// Runs in-process, so there is no management API check behind it: this prompt is the gate.
if (requiresAntigravityRiskAcknowledgement(name)) {
const decision = await resolveAntigravityRiskAcknowledgement({
flag: opts.acceptAntigravityRisk === true,
// readline writes the question to stdout, so both ends must be a terminal.
interactive: (deps.isInteractive ?? (() => process.stdin.isTTY === true && process.stdout.isTTY === true))(),
agentDriven: (deps.agentDriven ?? isAgentDriven)(),
warn: text => console.error(text),
ask: question => withPrompt(deps.ask, ask => ask(question)),
});
if (decision !== "accepted") {
console.error(antigravityRiskDecisionMessage(decision));
process.exit(1);
}
}
if (opts.codeMode) return handleCodeLogin(name, deps);
const login = deps.runLogin ?? runLogin;
const launch = deps.openUrl ?? openUrl;
const browser = createBrowserLaunchReport(deps.warn);
await withPrompt(deps.ask, async (ask) => {
await login(name, {
onAuth: ({ url, instructions }) => {
if (!url) {
if (instructions) console.log(terminalSafeText(instructions));
return;
}
console.log(`\n🔐 Opening browser for ${name} login...\n${terminalSafeText(url)}\n`);
if (instructions) console.log(terminalSafeText(instructions));
// The controller does not await onAuth, so the launcher's answer cannot be reported from
// here — this returns long before it arrives. It reports itself instead, and the one
// thing that could collide with it waits below (#5261).
browser.track(launch(url));
},
onProgress: (m) => console.log(` ${terminalSafeText(m)}`),
onManualCodeInput: async () => {
// "or wait for browser" is a lie if nothing opened, and a warning printed after readline
// has drawn the prompt lands on the line the user is typing on.
await browser.settled();
return await ask("Paste redirect URL or code (or wait for browser): ");
},
});
}).catch(reportOAuthLoginError);
// A device or polling provider never prompts, so nothing above waited on the launcher. It is
// still owed an answer before this claims the login worked.
await browser.settled();
const reload = await notifyRunningProxyAfterOAuthLogin(name);
console.log(`\n✅ Logged in to ${name}. Try: ocx sync`);
for (const line of modelSelectionGuidance(name)) console.log(line);
warnIfLiveReloadSkipped(reload);
}
export function providerConfigFromKeyLoginProvider(def: KeyLoginProvider, key: string, baseUrlOverride?: string): OcxProviderConfig {
return {
adapter: def.adapter,
baseUrl: baseUrlOverride ?? def.baseUrl,
apiKey: key,
...(def.apiKeyTransport !== undefined ? { apiKeyTransport: def.apiKeyTransport } : {}),
...(def.defaultModel ? { defaultModel: def.defaultModel } : {}),
...(def.models ? { models: [...def.models] } : {}),
...(def.contextWindow !== undefined ? { contextWindow: def.contextWindow } : {}),
...(def.modelContextWindows ? { modelContextWindows: { ...def.modelContextWindows } } : {}),
...(def.modelMaxInputTokens ? { modelMaxInputTokens: { ...def.modelMaxInputTokens } } : {}),
...(def.defaultMaxOutputTokens !== undefined ? { defaultMaxOutputTokens: def.defaultMaxOutputTokens } : {}),
...(def.modelMaxOutputTokens ? { modelMaxOutputTokens: { ...def.modelMaxOutputTokens } } : {}),
...(def.modelInputModalities ? { modelInputModalities: cloneRecordOfArrays(def.modelInputModalities) } : {}),
...(def.reasoningEfforts ? { reasoningEfforts: [...def.reasoningEfforts] } : {}),
...(def.modelReasoningEfforts ? { modelReasoningEfforts: cloneRecordOfArrays(def.modelReasoningEfforts) } : {}),
...(def.reasoningEffortMap ? { reasoningEffortMap: { ...def.reasoningEffortMap } } : {}),
...(def.modelReasoningEffortMap ? { modelReasoningEffortMap: cloneNestedRecord(def.modelReasoningEffortMap) } : {}),
...(def.noVisionModels ? { noVisionModels: [...def.noVisionModels] } : {}),
...(def.noReasoningModels ? { noReasoningModels: [...def.noReasoningModels] } : {}),
...(def.noTemperatureModels ? { noTemperatureModels: [...def.noTemperatureModels] } : {}),
...(def.noTopPModels ? { noTopPModels: [...def.noTopPModels] } : {}),
...(def.noStopModels ? { noStopModels: [...def.noStopModels] } : {}),
...(def.noPenaltyModels ? { noPenaltyModels: [...def.noPenaltyModels] } : {}),
...(def.autoToolChoiceOnlyModels ? { autoToolChoiceOnlyModels: [...def.autoToolChoiceOnlyModels] } : {}),
...(def.preserveReasoningContentModels ? { preserveReasoningContentModels: [...def.preserveReasoningContentModels] } : {}),
...(def.requiresReasoningPlaceholderModels ? { requiresReasoningPlaceholderModels: [...def.requiresReasoningPlaceholderModels] } : {}),
...(def.escapeBuiltinToolNames !== undefined ? { escapeBuiltinToolNames: def.escapeBuiltinToolNames } : {}),
};
}
/**
* Merge a freshly built key-login provider row with a previously saved row,
* carrying operator-owned fields the key-provider preset cannot know about.
* Currently that is the user-configured modelCosts overlay: rotating the API
* key must not silently revert Logs/Usage estimates to catalog prices.
*/
export function mergeKeyLoginProviderRow(
provider: OcxProviderConfig,
existing: OcxProviderConfig | undefined,
): OcxProviderConfig {
return {
...provider,
...(existing?.modelCosts !== undefined ? { modelCosts: existing.modelCosts } : {}),
};
}
/**
* Commit a fresh key-login provider row: merge operator-owned fields from the
* existing row (currently the modelCosts overlay), persist the merged row, and
* push the SAME merged row to a running proxy so its live config cannot diverge
* from disk (e.g. by replacing the overlay with catalog prices until reload).
* Returns the merged row that was persisted and notified.
*/
export async function commitKeyLoginProvider(
config: OcxConfig,
name: string,
provider: OcxProviderConfig,
onLiveReload?: (result: LocalProviderReloadResult | null) => void,
): Promise<OcxProviderConfig> {
const mergedProvider = mergeKeyLoginProviderRow(provider, config.providers[name]);
initializeProviderModelSelection(name, mergedProvider, config.providers[name], config);
config.providers[name] = mergedProvider;
saveConfig(config);
// Evaluate the reload BEFORE the optional call: `onLiveReload?.(await ...)` short-circuits
// the whole argument list when no callback is supplied, so the reload would never fire for
// callers that do not care about the outcome.
const reloadResult = await notifyRunningProxy(name);
onLiveReload?.(reloadResult);
return mergedProvider;
}
export async function handleKeyLogin(name: string, deps: LoginCliDeps = {}): Promise<void> {
const def = KEY_LOGIN_PROVIDERS[name];
const launch = deps.openUrl ?? openUrl;
const preflightConfig = loadConfig();
if (isAgyAcpProvider(name, preflightConfig.providers[name]) || isAgyAcpProvider(name, def)) {
console.log(AGY_ACP_SIGN_IN);
return;
}
const namespaceCollision = codexAccountNamespaceProviderCollisionError(preflightConfig.codexAccountNamespaces, name);
if (namespaceCollision) {
console.error(`Error: ${namespaceCollision}.`);
process.exit(1);
}
console.log(`\n🔑 ${def.label} — opening ${def.dashboardUrl} so you can create/copy an API key...`);
const browser = createBrowserLaunchReport(deps.warn);
browser.track(launch(def.dashboardUrl));
// The next question asks for a key the user gets FROM that page, so a page that never opened
// has to be on screen before the question rather than underneath it (#5261).
await browser.settled();
const { key, baseUrl } = await withPrompt(deps.ask, async (ask) => {
const entered = (await ask(`Paste your ${def.label} API key: `)).trim();
// Template URL with placeholders needs resolution before saving.
let resolvedBaseUrl = def.baseUrl;
if (/\{[^}]*\}/.test(resolvedBaseUrl)) {
const resolved = (await ask(`Your endpoint URL (${resolvedBaseUrl}): `)).trim();
if (!resolved) {
console.error("A resolved URL is required — replace the {placeholder} with your actual value.");
process.exit(1);
}
resolvedBaseUrl = resolved;
}
return { key: entered, baseUrl: resolvedBaseUrl };
});
if (!key) {
console.error("No key entered.");
process.exit(1);
}
process.stdout.write(" validating… ");
const valid = await validateApiKey(name, { ...def, baseUrl }, key);
console.log(valid === true ? "valid ✅" : valid === false ? "INVALID ❌" : "couldn't validate (may still work)");
if (valid === false) {
console.error("Provider rejected the key. Not saved.");
process.exit(1);
}
const provider = providerConfigFromKeyLoginProvider(def, key, baseUrl);
const config = loadConfig();
const commitCollision = codexAccountNamespaceProviderCollisionError(config.codexAccountNamespaces, name);
if (commitCollision) {
console.error(`Error: ${commitCollision}.`);
process.exit(1);
}
let reload: LocalProviderReloadResult | null = null;
await commitKeyLoginProvider(config, name, provider, result => { reload = result; });
console.log(`✅ ${def.label} added. Try: ocx sync`);
for (const line of modelSelectionGuidance(name)) console.log(line);
warnIfLiveReloadSkipped(reload);
}
function cloneRecordOfArrays(input: Record<string, string[]>): Record<string, string[]> {
return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, [...value]]));
}
function cloneNestedRecord(input: Record<string, Record<string, string>>): Record<string, Record<string, string>> {
return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, { ...value }]));
}