Skip to content

Commit 5f15bea

Browse files
committed
fix(codex): bootstrap app-server auth fallback
1 parent a1c88f3 commit 5f15bea

9 files changed

Lines changed: 254 additions & 49 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ Docs: https://docs.openclaw.ai
2727
- Providers/Codex: pass agent and workspace directories into provider stream wrappers so Codex native `web_search` activation can evaluate the correct auth context, and smoke-test the built status-message runtime by resolving the emitted bundle name. Carries forward #67843; refs #65909. Thanks @neilofneils404.
2828
- Cron/models: keep `payload.model` as a per-job primary that can use configured fallbacks, while still letting `payload.fallbacks: []` make cron runs strict and avoid hidden agent-primary retries. Refs #73023. Thanks @pavelyortho-cyber.
2929
- Models/fallbacks: treat user-selected session models as exact choices, so `/model ollama/...` and model-picker switches fail visibly when the selected provider is unreachable instead of answering from an unrelated configured fallback. Fixes #73023. Thanks @pavelyortho-cyber.
30-
- Codex harness: automatically clear inherited `OPENAI_API_KEY` from spawned Codex app-server processes when the harness is using ChatGPT subscription auth, while keeping explicit Codex API-key profiles and the manual `appServer.clearEnv` escape hatch available. Fixes #73057. Thanks @holgergruenhagen.
30+
- Codex harness: keep ChatGPT subscription app-server runs from inheriting `CODEX_API_KEY` or `OPENAI_API_KEY`, and fall back to `CODEX_API_KEY` / `OPENAI_API_KEY` app-server login only when no Codex account is available. Fixes #73057. Thanks @holgergruenhagen.
3131
- CLI/model probes: fail local `infer model run` probes when the provider returns no text output, so unreachable local providers and empty completions no longer look like successful smoke tests. Refs #73023. Thanks @pavelyortho-cyber.
3232
- CLI/Ollama: run local `infer model run` through the lean provider completion path and skip global model discovery for one-shot local probes, so Ollama smoke tests no longer pay full chat-agent/tool startup cost or hang before the native `/api/chat` request. Fixes #72851. Thanks @TotalRes2020.
3333
- Doctor/gateway services: ignore launchd/systemd companion services that only reference the gateway as a dependency, suppress inactive Linux extra-service warnings, and avoid rewriting a running systemd gateway command/entrypoint during doctor repair. Carries forward #39118. Thanks @therk.

‎docs/plugins/codex-harness.md‎

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -179,15 +179,15 @@ Codex after changing config.
179179
- Codex app-server `0.125.0` or newer. The bundled plugin manages a compatible
180180
Codex app-server binary by default, so local `codex` commands on `PATH` do
181181
not affect normal harness startup.
182-
- Codex auth available to the app-server process.
182+
- Codex auth available to the app-server process or to OpenClaw's Codex auth
183+
bridge.
183184

184185
The plugin blocks older or unversioned app-server handshakes. That keeps
185186
OpenClaw on the protocol surface it has been tested against.
186187

187-
For live and Docker smoke tests, auth usually comes from `OPENAI_API_KEY`, plus
188-
optional Codex CLI files such as `~/.codex/auth.json` and
189-
`~/.codex/config.toml`. Use the same auth material your local Codex app-server
190-
uses.
188+
For live and Docker smoke tests, auth usually comes from the Codex CLI account,
189+
an OpenClaw `openai-codex` auth profile, or `CODEX_API_KEY` /
190+
`OPENAI_API_KEY` as a fallback when no account is present.
191191

192192
## Minimal config
193193

@@ -508,16 +508,24 @@ For an already-running app-server, use WebSocket transport:
508508
}
509509
```
510510

511-
Stdio app-server launches inherit OpenClaw's process environment by default.
512-
When OpenClaw sees that the Codex harness is using a ChatGPT subscription-style
513-
auth profile, including the local Codex CLI login imported as
514-
`openai-codex:default`, it automatically removes `OPENAI_API_KEY` from the
515-
spawned Codex child process. That keeps Gateway-level API keys available for
516-
embeddings or direct OpenAI models without making native Codex app-server turns
517-
bill through the API by accident.
511+
Stdio app-server launches inherit OpenClaw's process environment by default,
512+
but OpenClaw owns the Codex app-server account bridge. Auth is selected in this
513+
order:
518514

519-
Explicit Codex API-key profiles are left alone. If a deployment needs additional
520-
environment isolation, add those variables to `appServer.clearEnv`:
515+
1. An explicit OpenClaw Codex auth profile for the agent.
516+
2. The app-server's existing account, such as a local Codex CLI ChatGPT sign-in.
517+
3. `CODEX_API_KEY`, then `OPENAI_API_KEY`, only when no app-server account is
518+
present and OpenAI auth is still required.
519+
520+
When OpenClaw sees a ChatGPT subscription-style Codex auth profile, it removes
521+
`CODEX_API_KEY` and `OPENAI_API_KEY` from the spawned Codex child process. That
522+
keeps Gateway-level API keys available for embeddings or direct OpenAI models
523+
without making native Codex app-server turns bill through the API by accident.
524+
Explicit Codex API-key profiles and env-key fallback use app-server login
525+
instead of inherited child-process env.
526+
527+
If a deployment needs additional environment isolation, add those variables to
528+
`appServer.clearEnv`:
521529

522530
```json5
523531
{
@@ -527,7 +535,7 @@ environment isolation, add those variables to `appServer.clearEnv`:
527535
enabled: true,
528536
config: {
529537
appServer: {
530-
clearEnv: ["OPENAI_API_KEY"],
538+
clearEnv: ["CODEX_API_KEY", "OPENAI_API_KEY"],
531539
},
532540
},
533541
},

‎docs/providers/openai.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,24 @@ Choose your preferred auth method and follow the setup steps.
285285
</Tab>
286286
</Tabs>
287287

288+
## Native Codex app-server auth
289+
290+
The native Codex app-server harness uses `openai/*` model refs plus
291+
`agentRuntime.id: "codex"`, but its auth is still account-based. OpenClaw
292+
selects auth in this order:
293+
294+
1. An explicit OpenClaw `openai-codex` auth profile bound to the agent.
295+
2. The app-server's existing account, such as a local Codex CLI ChatGPT sign-in.
296+
3. `CODEX_API_KEY`, then `OPENAI_API_KEY`, only when the app-server reports no
297+
account and still requires OpenAI auth.
298+
299+
That means a local ChatGPT/Codex subscription sign-in is not replaced just
300+
because the gateway process also has `OPENAI_API_KEY` for direct OpenAI models
301+
or embeddings. API-key fallback is only the no-account path. When a
302+
subscription-style Codex profile is selected, OpenClaw also keeps
303+
`CODEX_API_KEY` and `OPENAI_API_KEY` out of the spawned stdio app-server child
304+
and sends the selected credentials through the app-server login RPC.
305+
288306
## Image generation
289307

290308
The bundled `openai` plugin registers image generation through the `image_generate` tool.

‎extensions/codex/src/app-server/auth-bridge.test.ts‎

Lines changed: 116 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -109,31 +109,26 @@ function createStartOptions(
109109
};
110110
}
111111

112-
async function writeCodexCliAuthFile(codexHome: string): Promise<void> {
113-
await fs.mkdir(codexHome, { recursive: true });
114-
await fs.writeFile(
115-
path.join(codexHome, "auth.json"),
116-
JSON.stringify({
117-
tokens: {
118-
access_token: "cli-access-token",
119-
refresh_token: "cli-refresh-token",
120-
account_id: "cli-account-123",
121-
},
122-
}),
123-
);
124-
}
125-
126112
describe("bridgeCodexAppServerStartOptions", () => {
127-
it("clears an inherited OpenAI API key when local Codex CLI OAuth is available", async () => {
113+
it("clears inherited API-key env vars when the default Codex profile is subscription auth", async () => {
128114
const agentDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-codex-app-server-"));
129-
const codexHome = path.join(agentDir, "codex-home");
130115
const startOptions = createStartOptions({
131-
env: { CODEX_HOME: "/tmp/source-codex-home", EXISTING: "1" },
116+
env: { EXISTING: "1" },
132117
clearEnv: ["FOO"],
133118
});
134-
vi.stubEnv("CODEX_HOME", codexHome);
135119
try {
136-
await writeCodexCliAuthFile(codexHome);
120+
upsertAuthProfile({
121+
agentDir,
122+
profileId: "openai-codex:default",
123+
credential: {
124+
type: "oauth",
125+
provider: "openai-codex",
126+
access: "access-token",
127+
refresh: "refresh-token",
128+
expires: Date.now() + 24 * 60 * 60_000,
129+
accountId: "account-123",
130+
},
131+
});
137132

138133
await expect(
139134
bridgeCodexAppServerStartOptions({
@@ -142,7 +137,7 @@ describe("bridgeCodexAppServerStartOptions", () => {
142137
}),
143138
).resolves.toEqual({
144139
...startOptions,
145-
clearEnv: ["FOO", "OPENAI_API_KEY"],
140+
clearEnv: ["FOO", "CODEX_API_KEY", "OPENAI_API_KEY"],
146141
});
147142
expect(startOptions.clearEnv).toEqual(["FOO"]);
148143
await expect(fs.access(path.join(agentDir, "harness-auth"))).rejects.toMatchObject({
@@ -178,7 +173,7 @@ describe("bridgeCodexAppServerStartOptions", () => {
178173
}),
179174
).resolves.toEqual({
180175
...startOptions,
181-
clearEnv: ["FOO", "OPENAI_API_KEY"],
176+
clearEnv: ["FOO", "CODEX_API_KEY", "OPENAI_API_KEY"],
182177
});
183178
} finally {
184179
await fs.rm(agentDir, { recursive: true, force: true });
@@ -207,7 +202,7 @@ describe("bridgeCodexAppServerStartOptions", () => {
207202
}),
208203
).resolves.toEqual({
209204
...startOptions,
210-
clearEnv: ["FOO", "OPENAI_API_KEY"],
205+
clearEnv: ["FOO", "CODEX_API_KEY", "OPENAI_API_KEY"],
211206
});
212207
} finally {
213208
await fs.rm(agentDir, { recursive: true, force: true });
@@ -380,6 +375,105 @@ describe("bridgeCodexAppServerStartOptions", () => {
380375
}
381376
});
382377

378+
it("falls back to CODEX_API_KEY when no auth profile and no Codex account is available", async () => {
379+
const agentDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-codex-app-server-"));
380+
const request = vi.fn(async (method: string) => {
381+
if (method === "account/read") {
382+
return { account: null, requiresOpenaiAuth: true };
383+
}
384+
return { type: "apiKey" };
385+
});
386+
vi.stubEnv("CODEX_API_KEY", "codex-env-api-key");
387+
vi.stubEnv("OPENAI_API_KEY", "openai-env-api-key");
388+
try {
389+
await applyCodexAppServerAuthProfile({
390+
client: { request } as never,
391+
agentDir,
392+
});
393+
394+
expect(request).toHaveBeenNthCalledWith(1, "account/read", { refreshToken: false });
395+
expect(request).toHaveBeenNthCalledWith(2, "account/login/start", {
396+
type: "apiKey",
397+
apiKey: "codex-env-api-key",
398+
});
399+
} finally {
400+
await fs.rm(agentDir, { recursive: true, force: true });
401+
}
402+
});
403+
404+
it("falls back to OPENAI_API_KEY when CODEX_API_KEY is not set", async () => {
405+
const agentDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-codex-app-server-"));
406+
const request = vi.fn(async (method: string) => {
407+
if (method === "account/read") {
408+
return { account: null, requiresOpenaiAuth: true };
409+
}
410+
return { type: "apiKey" };
411+
});
412+
vi.stubEnv("CODEX_API_KEY", "");
413+
vi.stubEnv("OPENAI_API_KEY", "openai-env-api-key");
414+
try {
415+
await applyCodexAppServerAuthProfile({
416+
client: { request } as never,
417+
agentDir,
418+
});
419+
420+
expect(request).toHaveBeenNthCalledWith(1, "account/read", { refreshToken: false });
421+
expect(request).toHaveBeenNthCalledWith(2, "account/login/start", {
422+
type: "apiKey",
423+
apiKey: "openai-env-api-key",
424+
});
425+
} finally {
426+
await fs.rm(agentDir, { recursive: true, force: true });
427+
}
428+
});
429+
430+
it("keeps an existing app-server ChatGPT account over env API-key fallback", async () => {
431+
const agentDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-codex-app-server-"));
432+
const request = vi.fn(async (method: string) => {
433+
if (method === "account/read") {
434+
return {
435+
account: { type: "chatgpt", email: "[email protected]", planType: "plus" },
436+
requiresOpenaiAuth: true,
437+
};
438+
}
439+
return { type: "apiKey" };
440+
});
441+
vi.stubEnv("CODEX_API_KEY", "codex-env-api-key");
442+
try {
443+
await applyCodexAppServerAuthProfile({
444+
client: { request } as never,
445+
agentDir,
446+
});
447+
448+
expect(request).toHaveBeenCalledTimes(1);
449+
expect(request).toHaveBeenCalledWith("account/read", { refreshToken: false });
450+
} finally {
451+
await fs.rm(agentDir, { recursive: true, force: true });
452+
}
453+
});
454+
455+
it("skips env API-key fallback when app-server does not require OpenAI auth", async () => {
456+
const agentDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-codex-app-server-"));
457+
const request = vi.fn(async (method: string) => {
458+
if (method === "account/read") {
459+
return { account: null, requiresOpenaiAuth: false };
460+
}
461+
return { type: "apiKey" };
462+
});
463+
vi.stubEnv("CODEX_API_KEY", "codex-env-api-key");
464+
try {
465+
await applyCodexAppServerAuthProfile({
466+
client: { request } as never,
467+
agentDir,
468+
});
469+
470+
expect(request).toHaveBeenCalledTimes(1);
471+
expect(request).toHaveBeenCalledWith("account/read", { refreshToken: false });
472+
} finally {
473+
await fs.rm(agentDir, { recursive: true, force: true });
474+
}
475+
});
476+
383477
it("applies an OpenAI Codex token profile backed by a secret ref", async () => {
384478
const agentDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-codex-app-server-"));
385479
const request = vi.fn(async () => ({ type: "chatgptAuthTokens" }));

‎extensions/codex/src/app-server/auth-bridge.ts‎

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,14 @@ import {
1010
import type { CodexAppServerClient } from "./client.js";
1111
import type { CodexAppServerStartOptions } from "./config.js";
1212
import type { ChatgptAuthTokensRefreshResponse } from "./protocol-generated/typescript/v2/ChatgptAuthTokensRefreshResponse.js";
13+
import type { GetAccountResponse } from "./protocol-generated/typescript/v2/GetAccountResponse.js";
1314
import type { LoginAccountParams } from "./protocol-generated/typescript/v2/LoginAccountParams.js";
1415

1516
const CODEX_APP_SERVER_AUTH_PROVIDER = "openai-codex";
1617
const OPENAI_CODEX_DEFAULT_PROFILE_ID = "openai-codex:default";
18+
const CODEX_API_KEY_ENV_VAR = "CODEX_API_KEY";
1719
const OPENAI_API_KEY_ENV_VAR = "OPENAI_API_KEY";
20+
const CODEX_APP_SERVER_API_KEY_ENV_VARS = [CODEX_API_KEY_ENV_VAR, OPENAI_API_KEY_ENV_VAR];
1821

1922
export async function bridgeCodexAppServerStartOptions(params: {
2023
startOptions: CodexAppServerStartOptions;
@@ -30,7 +33,7 @@ export async function bridgeCodexAppServerStartOptions(params: {
3033
authProfileId: params.authProfileId,
3134
});
3235
return shouldClearInheritedOpenAiApiKey
33-
? withClearedEnvironmentVariable(params.startOptions, OPENAI_API_KEY_ENV_VAR)
36+
? withClearedEnvironmentVariables(params.startOptions, CODEX_APP_SERVER_API_KEY_ENV_VARS)
3437
: params.startOptions;
3538
}
3639

@@ -44,6 +47,13 @@ export async function applyCodexAppServerAuthProfile(params: {
4447
authProfileId: params.authProfileId,
4548
});
4649
if (!loginParams) {
50+
const fallbackLoginParams = await resolveCodexAppServerEnvApiKeyLoginParams({
51+
client: params.client,
52+
env: process.env,
53+
});
54+
if (fallbackLoginParams) {
55+
await params.client.request("account/login/start", fallbackLoginParams);
56+
}
4757
return;
4858
}
4959
await params.client.request("account/login/start", loginParams);
@@ -105,6 +115,23 @@ async function resolveCodexAppServerAuthProfileLoginParamsInternal(params: {
105115
return loginParams;
106116
}
107117

118+
async function resolveCodexAppServerEnvApiKeyLoginParams(params: {
119+
client: CodexAppServerClient;
120+
env: NodeJS.ProcessEnv;
121+
}): Promise<LoginAccountParams | undefined> {
122+
const apiKey = readFirstNonEmptyEnv(params.env, CODEX_APP_SERVER_API_KEY_ENV_VARS);
123+
if (!apiKey) {
124+
return undefined;
125+
}
126+
const response = await params.client.request<GetAccountResponse>("account/read", {
127+
refreshToken: false,
128+
});
129+
if (response.account || !response.requiresOpenaiAuth) {
130+
return undefined;
131+
}
132+
return { type: "apiKey", apiKey };
133+
}
134+
108135
async function resolveLoginParamsForCredential(
109136
profileId: string,
110137
credential: AuthProfileCredential,
@@ -189,20 +216,31 @@ function isCodexSubscriptionCredential(credential: AuthProfileCredential | undef
189216
return credential.type === "oauth" || credential.type === "token";
190217
}
191218

192-
function withClearedEnvironmentVariable(
219+
function withClearedEnvironmentVariables(
193220
startOptions: CodexAppServerStartOptions,
194-
envVar: string,
221+
envVars: readonly string[],
195222
): CodexAppServerStartOptions {
196223
const clearEnv = startOptions.clearEnv ?? [];
197-
if (clearEnv.includes(envVar)) {
224+
const missingEnvVars = envVars.filter((envVar) => !clearEnv.includes(envVar));
225+
if (missingEnvVars.length === 0) {
198226
return startOptions;
199227
}
200228
return {
201229
...startOptions,
202-
clearEnv: [...clearEnv, envVar],
230+
clearEnv: [...clearEnv, ...missingEnvVars],
203231
};
204232
}
205233

234+
function readFirstNonEmptyEnv(env: NodeJS.ProcessEnv, keys: readonly string[]): string | undefined {
235+
for (const key of keys) {
236+
const value = env[key]?.trim();
237+
if (value) {
238+
return value;
239+
}
240+
}
241+
return undefined;
242+
}
243+
206244
function buildChatgptAuthTokensParams(
207245
profileId: string,
208246
credential: AuthProfileCredential,

0 commit comments

Comments
 (0)