Skip to content

Commit 20ac22f

Browse files
fix(codex): guide recovery from unimported agent auth (#116807)
* fix(codex): diagnose unimported agent auth Add agent-scoped Codex migration guidance and expose a validated --agent target so non-default credentials cannot be imported into the default agent store. Fixes #116763 * fix(codex): surface auth migration before route planning * fix(codex): scope auth migration recovery * fix(codex): preserve API key auth fallback * test: repair memory importer routing expectation * test: drop superseded memory routing repair * test(tui): report PTY progress verbosely --------- Co-authored-by: fuller-stack-dev <[email protected]>
1 parent fb9c8e7 commit 20ac22f

18 files changed

Lines changed: 464 additions & 38 deletions

‎docs/cli/migrate.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ Running `openclaw migrate <provider>` with no other flags plans, previews, and (
4747
<ParamField path="--from <path>" type="string">
4848
Override the source state directory. Hermes follows `$HERMES_HOME` and the active profile, then uses the platform default (`~/.hermes` or `%LOCALAPPDATA%\hermes`). Codex defaults to `~/.codex` (or `$CODEX_HOME`), Claude defaults to `~/.claude`.
4949
</ParamField>
50+
<ParamField path="--agent <id>" type="string">
51+
Import into a configured agent. Omit this only when the configured default agent is the intended owner. Invalid and unknown agent IDs are rejected.
52+
</ParamField>
5053
<ParamField path="--include-secrets" type="boolean">
5154
Import supported credentials without prompting. Interactive apply asks before importing detected auth credentials, with yes selected by default; non-interactive `--yes` requires `--include-secrets` to import them.
5255
</ParamField>
@@ -65,6 +68,9 @@ Running `openclaw migrate <provider>` with no other flags plans, previews, and (
6568
<ParamField path="--plugin <name>" type="string">
6669
Select one Codex plugin install item by plugin name or item id. Repeat the flag to migrate multiple Codex plugins. When omitted, interactive Codex migrations show a native Codex plugin checkbox selector and non-interactive migrations keep all planned plugins. Applies only to source-installed `openai-curated` Codex plugins discovered by the Codex app-server inventory.
6770
</ParamField>
71+
<ParamField path="--item <id>" type="string">
72+
Select one exact migration item by its plan ID. Repeat the flag to migrate multiple items. For example, `--item auth:openai` limits a Codex migration to the detected OpenAI credential item.
73+
</ParamField>
6874
<ParamField path="--verify-plugin-apps" type="boolean">
6975
Codex only. Forces a fresh source Codex app-server `app/installed` snapshot read before planning native plugin activation. Off by default to keep migration planning fast.
7076
</ParamField>
@@ -132,6 +138,16 @@ The bundled Codex provider detects Codex CLI state at `~/.codex` by default, or
132138

133139
Use this provider when moving to the OpenClaw Codex harness and you want to promote useful personal Codex CLI assets deliberately. Local Codex app-server launches use a per-agent `CODEX_HOME`, so they do not read your personal `~/.codex` by default. The normal process `HOME` is still inherited, so Codex can see shared `$HOME/.agents/*` skills/plugin marketplace entries and subprocesses can find user-home config and tokens.
134140

141+
Codex `auth.json` credentials are sensitive migration inputs. The default
142+
agent-scoped runtime does not consume a copied or mounted `auth.json` directly;
143+
import those credentials into the owning agent's OpenClaw auth store explicitly.
144+
Replace `<agent-id>` with that configured agent's ID:
145+
146+
```bash
147+
openclaw migrate plan codex --from <codex-home> --agent <agent-id> --include-secrets --item auth:openai
148+
openclaw migrate apply codex --from <codex-home> --agent <agent-id> --include-secrets --item auth:openai --yes
149+
```
150+
135151
Running `openclaw migrate codex` in an interactive terminal previews the full plan, then opens checkbox selectors before the final apply confirmation. Skill copy items are prompted first. Use `Toggle all on` or `Toggle all off` for bulk selection. Press Space to toggle rows, or Enter to activate the highlighted row and continue. Planned skills start checked, conflict skills start unchecked, and `Skip for now` skips skill copies for this run while still continuing to plugin selection. When source-installed curated Codex plugins are migratable and `--plugin` was not supplied, migration then prompts for native Codex plugin activation by plugin name. Plugin items start checked unless the target OpenClaw Codex plugin config already has that plugin. Existing target plugins start unchecked and show a conflict hint such as `conflict: plugin exists`; choose `Toggle all off` to migrate no native Codex plugins in that run, or `Skip for now` to stop before applying.
136152

137153
For scripted or exact runs, select one or more skills or plugins explicitly:
@@ -145,6 +161,9 @@ openclaw migrate apply codex --yes --plugin google-calendar
145161

146162
### What Codex imports
147163

164+
- ChatGPT OAuth or OpenAI API-key credentials from `$CODEX_HOME/auth.json`,
165+
imported into the agent's OpenClaw auth store only when `--include-secrets`
166+
is set.
148167
- Consolidated Codex `MEMORY.md` and `memory_summary.md` from
149168
`$CODEX_HOME/memories`, copied under `memory/imports/codex/` for indexed
150169
recall. Raw rollout memory is not imported.

‎docs/plugins/codex-harness-reference.md‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -418,13 +418,17 @@ rejects that combination.
418418

419419
## Auth and environment isolation
420420

421-
In the default per-agent home, auth is selected in this order:
421+
In the default per-agent home, managed stdio launches use Codex's ephemeral
422+
credential store. OpenClaw supplies auth in this order:
422423

423-
1. An explicit OpenClaw Codex auth profile for the agent.
424-
2. The app-server's existing account in that agent's Codex home.
425-
3. For local stdio app-server launches only, `CODEX_API_KEY`, then
426-
`OPENAI_API_KEY`, when no app-server account is present and OpenAI auth is
427-
still required.
424+
1. An explicit or ordered OpenClaw auth profile for the agent.
425+
2. For an API-key route only, a prepared key or local stdio fallback from
426+
`CODEX_API_KEY`, then `OPENAI_API_KEY`.
427+
428+
The managed app-server does not read an existing `codex-home/auth.json` in
429+
this mode. Import that file explicitly as described below. Set
430+
`appServer.homeScope: "user"` only when the app-server should instead own and
431+
use the operator's native Codex account.
428432

429433
When OpenClaw sees a ChatGPT subscription-style Codex auth profile (OAuth or
430434
token credential type), it removes `CODEX_API_KEY` and `OPENAI_API_KEY` from
@@ -485,6 +489,15 @@ openclaw migrate codex --dry-run
485489
openclaw migrate apply codex --yes
486490
```
487491

492+
Credentials need the sensitive migration path because the default agent scope
493+
does not consume a copied or mounted `codex-home/auth.json` directly. Replace
494+
`<agent-id>` with the configured agent that owns this Codex home:
495+
496+
```bash
497+
openclaw migrate plan codex --from <codex-home> --agent <agent-id> --include-secrets --item auth:openai
498+
openclaw migrate apply codex --from <codex-home> --agent <agent-id> --include-secrets --item auth:openai --yes
499+
```
500+
488501
If a deployment needs additional environment isolation, add those variables
489502
to `appServer.clearEnv`:
490503

‎docs/providers/openai.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -569,6 +569,16 @@ account-based. OpenClaw selects auth in this order:
569569
3. For local stdio app-server launches only, and only when the app-server
570570
reports no account: `CODEX_API_KEY`, then `OPENAI_API_KEY`.
571571

572+
The default per-agent `codex-home/auth.json` is not a runtime auth store. If
573+
you copied or mounted Codex CLI credentials there, import them into the agent's
574+
OpenClaw auth store before starting a native Codex turn. Replace `<agent-id>`
575+
with the configured agent that owns this Codex home:
576+
577+
```bash
578+
openclaw migrate plan codex --from <codex-home> --agent <agent-id> --include-secrets --item auth:openai
579+
openclaw migrate apply codex --from <codex-home> --agent <agent-id> --include-secrets --item auth:openai --yes
580+
```
581+
572582
A local ChatGPT/Codex subscription sign-in is not replaced just because the
573583
gateway process also has `OPENAI_API_KEY` for direct OpenAI models or
574584
embeddings. The env API-key fallback applies only to the local stdio no-account

‎extensions/codex/src/app-server/attempt-startup.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,29 @@ describe("startCodexAttemptThread", () => {
290290
expect(harness.process.stdin.destroyed).toBe(true);
291291
});
292292

293+
it("carries the session agent id into the startup client factory", async () => {
294+
const clientFactory = vi.fn(
295+
async (options: Parameters<CodexAppServerClientFactory>[0]) =>
296+
await getLeasedSharedCodexAppServerClient(options),
297+
);
298+
const { harness, run } = startThreadWithHarness(5_000, new AbortController().signal, {
299+
attemptClientFactory: () => clientFactory,
300+
});
301+
await answerInitialize(harness);
302+
const threadStart = await waitForThreadStart(harness);
303+
harness.send({
304+
id: threadStart.id,
305+
error: { code: -32000, message: "stop after startup" },
306+
});
307+
308+
await expect(run).rejects.toThrow("stop after startup");
309+
expect(clientFactory).toHaveBeenCalledWith(
310+
expect.objectContaining({
311+
agentId: "agent-1",
312+
}),
313+
);
314+
});
315+
293316
it("rejects an expected artifact mismatch before any native thread request", async () => {
294317
const paths = createAttemptPaths();
295318
await fs.mkdir(paths.workspaceDir, { recursive: true });

‎extensions/codex/src/app-server/attempt-startup.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,7 @@ export async function startCodexAttemptThread(params: {
242242
: {}),
243243
}
244244
: {}),
245+
agentId: params.sessionAgentId,
245246
agentDir: params.agentDir,
246247
config: params.config,
247248
onStartedClient: (client) => {

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

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,86 @@ describe("bridgeCodexAppServerStartOptions", () => {
253253
}
254254
});
255255

256+
it.each(["subscription", "api-key"] as const)(
257+
"rejects an unimported agent-scoped Codex auth file for a %s route without fallback",
258+
async (authRequirement) => {
259+
await withTempDir("openclaw-codex-unimported-auth-", async (agentDir) => {
260+
const codexHome = resolveCodexAppServerHomeDir(agentDir);
261+
await writeCodexCliAuthFile(codexHome);
262+
vi.stubEnv("CODEX_API_KEY", "");
263+
vi.stubEnv("OPENAI_API_KEY", "");
264+
265+
await expect(
266+
bridgeCodexAppServerStartOptions({
267+
startOptions: createStartOptions(),
268+
agentDir,
269+
agentId: "research",
270+
authRequirement,
271+
}),
272+
).rejects.toMatchObject({
273+
name: "AgentHarnessPreflightError",
274+
message: expect.stringContaining(
275+
"openclaw migrate apply codex --from <codex-home> --agent research --include-secrets --item auth:openai --yes",
276+
),
277+
});
278+
});
279+
},
280+
);
281+
282+
it.each(["CODEX_API_KEY", "OPENAI_API_KEY"] as const)(
283+
"preserves the %s fallback when a stale agent auth file remains",
284+
async (envVar) => {
285+
await withTempDir("openclaw-codex-stale-auth-api-key-", async (agentDir) => {
286+
await writeCodexCliAuthFile(resolveCodexAppServerHomeDir(agentDir));
287+
vi.stubEnv("CODEX_API_KEY", "");
288+
vi.stubEnv("OPENAI_API_KEY", "");
289+
vi.stubEnv(envVar, "platform-api-key");
290+
291+
const startOptions = await bridgeCodexAppServerStartOptions({
292+
startOptions: createStartOptions(),
293+
agentDir,
294+
agentId: "research",
295+
authRequirement: "api-key",
296+
});
297+
expect(startOptions).toMatchObject({
298+
args: EPHEMERAL_AUTH_ARGS,
299+
env: { CODEX_HOME: resolveCodexAppServerHomeDir(agentDir) },
300+
});
301+
302+
const request = vi.fn(async (method: string) =>
303+
method === "account/read"
304+
? { account: null, requiresOpenaiAuth: true }
305+
: { type: "apiKey" },
306+
);
307+
await applyCodexAppServerAuthProfile({
308+
client: { request } as never,
309+
agentDir,
310+
authRequirement: "api-key",
311+
startOptions,
312+
});
313+
expect(request).toHaveBeenNthCalledWith(1, "account/read", { refreshToken: false });
314+
expect(request).toHaveBeenNthCalledWith(2, "account/login/start", {
315+
type: "apiKey",
316+
apiKey: "platform-api-key",
317+
});
318+
});
319+
},
320+
);
321+
322+
it.each(["websocket", "unix"] as const)(
323+
"ignores an agent-scoped auth file for %s transports",
324+
async (transport) => {
325+
await withTempDir("openclaw-codex-remote-auth-", async (agentDir) => {
326+
await writeCodexCliAuthFile(resolveCodexAppServerHomeDir(agentDir));
327+
const startOptions = createStartOptions({ transport });
328+
329+
await expect(
330+
bridgeCodexAppServerStartOptions({ startOptions, agentDir, agentId: "research" }),
331+
).resolves.toBe(startOptions);
332+
});
333+
},
334+
);
335+
256336
it("provisions the native Computer Use client before auto-install startup", async () => {
257337
await withTempDir("openclaw-codex-computer-use-service-", async (agentDir) => {
258338
const startOptions = createStartOptions();
@@ -357,6 +437,7 @@ describe("bridgeCodexAppServerStartOptions", () => {
357437
commandSource: "config",
358438
args: [],
359439
});
440+
await writeCodexCliAuthFile(resolveCodexAppServerHomeDir(agentDir));
360441

361442
const bridged = await bridgeCodexAppServerStartOptions({ startOptions, agentDir });
362443

@@ -478,6 +559,7 @@ describe("bridgeCodexAppServerStartOptions", () => {
478559
accountId: "account-123",
479560
},
480561
});
562+
await writeCodexCliAuthFile(resolveCodexAppServerHomeDir(agentDir));
481563

482564
await expect(
483565
bridgeCodexAppServerStartOptions({

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

Lines changed: 63 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,29 +68,34 @@ const scopedOAuthRefreshQueues = new WeakMap<
6868

6969
export async function bridgeCodexAppServerStartOptions(params: {
7070
startOptions: CodexAppServerStartOptions;
71+
agentId?: string;
7172
agentDir: string;
7273
authProfileId?: string | null;
7374
authProfileStore?: AuthProfileStore;
7475
preparedAuth?: CodexAppServerPreparedAuth;
76+
authRequirement?: CodexAppServerAuthRequirement;
7577
config?: AuthProfileOrderConfig;
7678
pluginConfig?: unknown;
7779
}): Promise<CodexAppServerStartOptions> {
7880
if (params.startOptions.transport !== "stdio") {
7981
return params.startOptions;
8082
}
81-
const scopedStartOptions = await withCodexHomeEnvironment(
82-
withEphemeralCodexAuthStore(params),
83-
params.agentDir,
84-
params.pluginConfig,
85-
);
83+
const scopeStartOptions = () =>
84+
withCodexHomeEnvironment(
85+
withEphemeralCodexAuthStore(params),
86+
params.agentDir,
87+
params.pluginConfig,
88+
);
89+
8690
if (params.preparedAuth) {
91+
const scopedStartOptions = await scopeStartOptions();
8792
return withClearedEnvironmentVariables(
8893
scopedStartOptions,
8994
CODEX_APP_SERVER_PREPARED_AUTH_ENV_VARS,
9095
);
9196
}
9297
if (params.authProfileId === null) {
93-
return scopedStartOptions;
98+
return scopeStartOptions();
9499
}
95100
const store = resolveCodexAppServerAuthProfileStore({
96101
agentDir: params.agentDir,
@@ -103,6 +108,11 @@ export async function bridgeCodexAppServerStartOptions(params: {
103108
store,
104109
config: params.config,
105110
});
111+
if (!authProfileId) {
112+
assertNoUnimportedAgentCodexAuthFile(params);
113+
}
114+
115+
const scopedStartOptions = await scopeStartOptions();
106116
const shouldClearInheritedOpenAiApiKey = shouldClearOpenAiApiKeyForCodexAuthProfile({
107117
store,
108118
authProfileId,
@@ -112,6 +122,53 @@ export async function bridgeCodexAppServerStartOptions(params: {
112122
: scopedStartOptions;
113123
}
114124

125+
function assertNoUnimportedAgentCodexAuthFile(params: {
126+
startOptions: CodexAppServerStartOptions;
127+
agentId?: string;
128+
agentDir: string;
129+
authRequirement?: CodexAppServerAuthRequirement;
130+
}): void {
131+
// Ephemeral managed starts cannot load this stale file, and the shared-client key
132+
// separates auth requirements plus fallback identities. Preserve the supported
133+
// stdio API-key login instead of turning a leftover file into a hard failure.
134+
if (
135+
params.authRequirement === "api-key" &&
136+
resolveCodexAppServerFallbackApiKeyCacheKey({ startOptions: params.startOptions })
137+
) {
138+
return;
139+
}
140+
const message = resolveUnimportedAgentCodexAuthMessage(params);
141+
if (message) {
142+
throw new AgentHarnessPreflightError(message);
143+
}
144+
}
145+
146+
function resolveUnimportedAgentCodexAuthMessage(params: {
147+
startOptions: CodexAppServerStartOptions;
148+
agentId?: string;
149+
agentDir: string;
150+
}): string | undefined {
151+
const managedCodexCli =
152+
params.startOptions.commandSource === "managed" ||
153+
params.startOptions.commandSource === "resolved-managed";
154+
if (
155+
params.startOptions.transport !== "stdio" ||
156+
!managedCodexCli ||
157+
params.startOptions.homeScope === "user"
158+
) {
159+
return undefined;
160+
}
161+
const codexHome = resolveCodexAppServerHomeDir(params.agentDir);
162+
const authPath = path.join(codexHome, CODEX_AUTH_JSON_FILENAME);
163+
// Managed starts force ephemeral Codex auth, so this file would otherwise be
164+
// ignored and the operator would receive only the downstream authentication error.
165+
if (!fsSync.existsSync(authPath)) {
166+
return undefined;
167+
}
168+
const targetAgentId = params.agentId?.trim() || "<agent-id>";
169+
return `A Codex auth file exists at ${authPath}, but agent-scoped Codex runs use OpenClaw's auth store and do not read that file. Preview only that credential import with \`openclaw migrate plan codex --from <codex-home> --agent ${targetAgentId} --include-secrets --item auth:openai\`, then run \`openclaw migrate apply codex --from <codex-home> --agent ${targetAgentId} --include-secrets --item auth:openai --yes\`. If the plan finds no credentials, remove the stale auth file.`;
170+
}
171+
115172
export function resolveCodexAppServerAuthProfileId(params: {
116173
authProfileId?: string;
117174
store: ReturnType<typeof ensureAuthProfileStore>;

‎extensions/codex/src/app-server/shared-client.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ function firstMockArg(mock: unknown, label: string): unknown {
129129
function bridgeStartOptionsCall() {
130130
return firstMockArg(mocks.bridgeCodexAppServerStartOptions, "bridge start options") as {
131131
agentDir?: string;
132+
agentId?: string;
132133
authProfileId?: string;
133134
authProfileStore?: unknown;
134135
preparedAuth?:
@@ -1282,6 +1283,7 @@ describe("shared Codex app-server client", () => {
12821283
timeoutMs: 1000,
12831284
authProfileId: null,
12841285
agentDir: "/tmp/openclaw-target-agent",
1286+
agentId: "research",
12851287
config,
12861288
});
12871289
await sendInitializeResult(harness, "openclaw/0.146.0 (macOS; test)");
@@ -1290,6 +1292,7 @@ describe("shared Codex app-server client", () => {
12901292
expect(mocks.resolveCodexAppServerAuthProfileIdForAgent).not.toHaveBeenCalled();
12911293
const bridgeCall = bridgeStartOptionsCall();
12921294
expect(bridgeCall.agentDir).toBe("/tmp/openclaw-target-agent");
1295+
expect(bridgeCall.agentId).toBe("research");
12931296
expect(bridgeCall.authProfileId).toBeNull();
12941297
expect(bridgeCall.config).toBe(config);
12951298
const applyCall = applyAuthProfileCall();

‎extensions/codex/src/app-server/shared-client.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@ export type CodexAppServerClientOptions = {
265265
expectedRuntimeArtifact?: AgentHarnessRuntimeArtifactBinding;
266266
preparedAuth?: CodexAppServerPreparedAuth;
267267
authRequirement?: CodexAppServerAuthRequirement;
268+
agentId?: string;
268269
agentDir?: string;
269270
config?: Parameters<typeof resolveCodexAppServerAuthProfileIdForAgent>[0]["config"];
270271
onStartedClient?: (client: CodexAppServerClient) => void;
@@ -388,9 +389,11 @@ async function resolveCodexAppServerClientStartContext(
388389
const managedStartOptions = await resolveManagedCodexAppServerStartOptions(agentStartOptions);
389390
const startOptions = await bridgeCodexAppServerStartOptions({
390391
startOptions: managedStartOptions,
392+
agentId: options?.agentId,
391393
agentDir,
392394
authProfileId: usesNativeAuth || preparedAuth?.kind === "api-key" ? null : authProfileId,
393395
...(resolvedPreparedAuth ? { preparedAuth: resolvedPreparedAuth } : {}),
396+
authRequirement,
394397
config: options?.config,
395398
pluginConfig: options?.pluginConfig,
396399
...(authProfileStore ? { authProfileStore } : {}),

0 commit comments

Comments
 (0)