Skip to content

Commit dc3117f

Browse files
committed
fix(codex): explain unavailable selected auth profiles
1 parent 1505218 commit dc3117f

17 files changed

Lines changed: 575 additions & 43 deletions

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

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2664,13 +2664,18 @@ describe("bridgeCodexAppServerStartOptions", () => {
26642664
},
26652665
});
26662666

2667-
await expect(
2668-
applyCodexAppServerAuthProfile({
2669-
client: { request } as never,
2670-
agentDir,
2671-
authProfileId: "anthropic:work",
2672-
}),
2673-
).rejects.toThrow(
2667+
const rejection = await applyCodexAppServerAuthProfile({
2668+
client: { request } as never,
2669+
agentDir,
2670+
authProfileId: "anthropic:work",
2671+
}).catch((error: unknown) => error);
2672+
2673+
expect(rejection).toBeInstanceOf(Error);
2674+
expect(rejection).toMatchObject({
2675+
status: 401,
2676+
code: "selected_auth_profile_unavailable",
2677+
});
2678+
expect((rejection as Error).message).toBe(
26742679
'Codex app-server auth profile "anthropic:work" must use the canonical OpenAI auth provider; run "openclaw doctor --fix" to migrate legacy provider IDs.',
26752680
);
26762681
expect(oauthMocks.refreshOpenAICodexToken).not.toHaveBeenCalled();
@@ -2706,7 +2711,10 @@ describe("bridgeCodexAppServerStartOptions", () => {
27062711
}
27072712

27082713
expect(rejection).toBeInstanceOf(Error);
2709-
expect((rejection as { status?: unknown }).status).toBe(401);
2714+
expect(rejection).toMatchObject({
2715+
status: 401,
2716+
code: "selected_auth_profile_unavailable",
2717+
});
27102718
expect(request).not.toHaveBeenCalled();
27112719
});
27122720

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

Lines changed: 14 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -800,31 +800,17 @@ export async function applyCodexAppServerAuthProfile(params: {
800800
await assertNativeCodexAccountMatchesRoute(params.client, params.authRequirement);
801801
return;
802802
}
803-
let loginParams: CodexLoginAccountParams | undefined;
804-
try {
805-
loginParams =
806-
params.preparedAuth?.kind === "profile"
807-
? params.preparedAuth.snapshot.loginParams
808-
: params.preparedAuth?.kind === "api-key"
809-
? { type: "apiKey", apiKey: params.preparedAuth.apiKey }
810-
: await resolveCodexAppServerAuthProfileLoginParams({
811-
agentDir: params.agentDir,
812-
authProfileId: params.authProfileId ?? undefined,
813-
authProfileStore: params.authProfileStore,
814-
config: params.config,
815-
});
816-
} catch (error) {
817-
if (
818-
params.authRequirement === "subscription" &&
819-
error instanceof CodexAppServerAuthProfileUnavailableError
820-
) {
821-
throw createCodexAppServerAuthError(
822-
"Codex subscription auth profile could not produce login credentials. Sign in with `openclaw models auth login --provider openai`, select that profile, then retry.",
823-
error,
824-
);
825-
}
826-
throw error;
827-
}
803+
const loginParams =
804+
params.preparedAuth?.kind === "profile"
805+
? params.preparedAuth.snapshot.loginParams
806+
: params.preparedAuth?.kind === "api-key"
807+
? { type: "apiKey", apiKey: params.preparedAuth.apiKey }
808+
: await resolveCodexAppServerAuthProfileLoginParams({
809+
agentDir: params.agentDir,
810+
authProfileId: params.authProfileId ?? undefined,
811+
authProfileStore: params.authProfileStore,
812+
config: params.config,
813+
});
828814
if (params.authRequirement === "subscription" && loginParams?.type !== "chatgptAuthTokens") {
829815
throw createCodexAppServerAuthError(
830816
"Codex subscription auth profile could not produce login credentials. Sign in with `openclaw models auth login --provider openai`, select that profile, then retry.",
@@ -888,6 +874,7 @@ function createCodexAppServerAuthError(message: string, cause?: unknown): Error
888874

889875
class CodexAppServerAuthProfileUnavailableError extends Error {
890876
readonly status = 401;
877+
readonly code = "selected_auth_profile_unavailable";
891878
}
892879

893880
async function resolveCodexAppServerAuthProfileLoginParams(params: {
@@ -991,12 +978,12 @@ async function resolveCodexAppServerAuthProfileLoginParamsInternal(params: {
991978
}
992979
const credential = store.profiles[profileId];
993980
if (!credential) {
994-
throw new Error(
981+
throw new CodexAppServerAuthProfileUnavailableError(
995982
`Codex app-server auth profile "${profileId}" was not found. Select an existing OpenAI profile or sign in again with OpenClaw, then retry.`,
996983
);
997984
}
998985
if (!isCodexAppServerAuthProfileCredential(credential)) {
999-
throw new Error(
986+
throw new CodexAppServerAuthProfileUnavailableError(
1000987
`Codex app-server auth profile "${profileId}" must use the canonical OpenAI auth provider; run "openclaw doctor --fix" to migrate legacy provider IDs.`,
1001988
);
1002989
}

‎src/agents/command/lifecycle.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { describe, expect, it, vi } from "vitest";
22
import { buildAgentRunTerminalOutcome } from "../agent-run-terminal-outcome.js";
3+
import { FailoverError } from "../failover-error.js";
4+
import { renderFailoverCodeUserCopy } from "../failover/user-copy.js";
35
import { createAgentCommandLifecycle } from "./lifecycle.js";
46

57
const { emitAgentEvent, lifecycleLog } = vi.hoisted(() => ({
@@ -169,6 +171,47 @@ describe("createAgentCommandLifecycle", () => {
169171
},
170172
);
171173

174+
it.each(["basic", "post-turn"] as const)(
175+
"publishes bounded selected-profile recovery from %s lifecycle errors",
176+
(source) => {
177+
emitAgentEvent.mockClear();
178+
const profileId = "openai:private-profile";
179+
const rawCause = `Codex app-server auth profile "${profileId}" was not found`;
180+
const lifecycle = createAgentCommandLifecycle({
181+
runId: "missing-selected-profile",
182+
lifecycleGeneration: () => "test-generation",
183+
startedAt: 100,
184+
state: {
185+
currentTurnUserMessagePersisted: true,
186+
lifecycleFinishing: false,
187+
lifecycleEnded: false,
188+
},
189+
});
190+
const error = new FailoverError(rawCause, {
191+
reason: "auth",
192+
code: "selected_auth_profile_unavailable",
193+
profileId,
194+
cause: new Error(rawCause),
195+
});
196+
197+
if (source === "basic") {
198+
lifecycle.emitBasicError(error);
199+
} else {
200+
lifecycle.emitPostTurnError(error, {
201+
metadata: {},
202+
outcome: buildAgentRunTerminalOutcome({ status: "error", stopReason: "error" }),
203+
});
204+
}
205+
206+
const event = emitAgentEvent.mock.calls[0]?.[0];
207+
expect(event.data.error).toBe(
208+
renderFailoverCodeUserCopy("selected_auth_profile_unavailable"),
209+
);
210+
expect(JSON.stringify(event)).not.toContain(profileId);
211+
expect(JSON.stringify(event)).not.toContain(rawCause);
212+
},
213+
);
214+
172215
it("does not let generic abort metadata erase a superseded outcome", () => {
173216
emitAgentEvent.mockClear();
174217
const controller = new AbortController();

‎src/agents/command/lifecycle.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import { normalizeAgentRunTerminalDeliverySnapshot } from "../agent-run-terminal
55
import type { AgentRunTerminalOutcome } from "../agent-run-terminal-outcome.js";
66
import { normalizeAgentRunTerminalReceipt } from "../agent-run-terminal-receipt.js";
77
import type { EmbeddedAgentRunEntryTerminal } from "../embedded-agent-runner/run-entry.js";
8+
import { describeFailoverError } from "../failover-error.js";
9+
import { renderFailoverCodeUserCopy } from "../failover/user-copy.js";
810
import {
911
AGENT_RUN_SUPERSEDED_STOP_REASON,
1012
resolveAgentRunAbortLifecycleFields,
@@ -15,6 +17,9 @@ import type { AgentAttemptResult } from "./runtime-loaders.js";
1517

1618
const log = createSubsystemLogger("agents/agent-command");
1719

20+
const formatLifecycleError = (error: unknown): string =>
21+
renderFailoverCodeUserCopy(describeFailoverError(error).code) ?? formatErrorMessage(error);
22+
1823
function resolveTerminalLogLevel(
1924
outcome: AgentRunTerminalOutcome,
2025
): "info" | "warn" | "error" | undefined {
@@ -101,7 +106,7 @@ export function createAgentCommandLifecycle(params: {
101106
};
102107

103108
return {
104-
emitBasicError(error: string, extraData?: Record<string, unknown>) {
109+
emitBasicError(error: unknown, extraData?: Record<string, unknown>) {
105110
if (params.state.lifecycleEnded) {
106111
return;
107112
}
@@ -114,7 +119,7 @@ export function createAgentCommandLifecycle(params: {
114119
phase: "error",
115120
startedAt: params.startedAt,
116121
endedAt: Date.now(),
117-
error: formatErrorMessage(error),
122+
error: formatLifecycleError(error),
118123
...extraData,
119124
},
120125
});
@@ -174,7 +179,7 @@ export function createAgentCommandLifecycle(params: {
174179
phase: "error",
175180
startedAt: params.startedAt,
176181
endedAt: Date.now(),
177-
error: formatErrorMessage(error),
182+
error: formatLifecycleError(error),
178183
...(terminalDelivery ? { terminalDelivery } : {}),
179184
...resolveAgentRunErrorLifecycleFields(error, params.abortSignal),
180185
},

‎src/agents/command/run-embedded-attempt.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -670,7 +670,7 @@ export async function runEmbeddedAgentAttempt(params: {
670670
? { aborted: true as const, stopReason: "aborted" as const }
671671
: resolveAgentRunErrorLifecycleFields(err, params.opts.abortSignal);
672672
lifecycle.emitBasicError(
673-
err instanceof Error ? err.message : "Agent run failed",
673+
err instanceof Error ? err : new Error("Agent run failed"),
674674
errorLifecycleFields,
675675
);
676676
await fallbackTrajectoryRecorder?.flush();

‎src/agents/embedded-agent-runner/run/auth-controller.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,36 @@ describe("createEmbeddedRunAuthController", () => {
645645
},
646646
);
647647

648+
it("preserves selected-profile identity through auth exhaustion bookkeeping", async () => {
649+
const harness = createMutableAuthControllerHarness();
650+
mocks.getApiKeyForModelCore.mockRejectedValue(
651+
Object.assign(new Error("selected profile missing"), {
652+
status: 401,
653+
code: "selected_auth_profile_unavailable",
654+
}),
655+
);
656+
const controller = createMutableEmbeddedRunAuthController({
657+
harness,
658+
setRuntimeApiKey: vi.fn(),
659+
profileCandidates: ["first", "second"],
660+
fallbackConfigured: true,
661+
});
662+
663+
const error = await controller.initializeAuthProfile().catch((err: unknown) => err);
664+
665+
expect(error).toBeInstanceOf(FailoverError);
666+
expect(error).toMatchObject({
667+
reason: "auth",
668+
code: "selected_auth_profile_unavailable",
669+
authProfileFailure: { allInCooldown: false },
670+
});
671+
expect(mocks.getApiKeyForModelCore.mock.calls.map(([params]) => params.profileId)).toEqual([
672+
"first",
673+
"second",
674+
]);
675+
expect(harness.profileIndex).toBe(2);
676+
});
677+
648678
it("only enables transient cooldown probing when every automatic profile is transiently cooled", () => {
649679
const now = Date.now();
650680
const createStore = (

‎src/agents/embedded-agent-runner/run/auth-controller.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,11 @@ import {
2020
isFailoverErrorMessage,
2121
type FailoverReason,
2222
} from "../../embedded-agent-helpers.js";
23-
import { FailoverError, resolveFailoverStatus } from "../../failover-error.js";
23+
import {
24+
describeFailoverError,
25+
FailoverError,
26+
resolveFailoverStatus,
27+
} from "../../failover-error.js";
2428
import { shouldUseTransientCooldownProbeSlot } from "../../failover-policy.js";
2529
import { renderAuthProfileFailoverCopy } from "../../failover/user-copy.js";
2630
import {
@@ -498,6 +502,7 @@ export function createEmbeddedRunAuthController(params: {
498502
model: modelId,
499503
authMode,
500504
status: resolveFailoverStatus(reason),
505+
code: failoverParams.error ? describeFailoverError(failoverParams.error).code : undefined,
501506
authProfileFailure: { allInCooldown: failoverParams.allInCooldown },
502507
cause: failoverParams.error,
503508
});

‎src/agents/failover-error.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -758,6 +758,22 @@ describe("failover-error", () => {
758758
expect(err?.provider).toBe("anthropic");
759759
});
760760

761+
it("preserves a selected-profile error code in the auth failover lane", () => {
762+
const err = coerceToFailoverError(
763+
Object.assign(new Error("selected profile missing"), {
764+
status: 401,
765+
code: "selected_auth_profile_unavailable",
766+
}),
767+
{ provider: "openai", model: "gpt-5.6-sol" },
768+
);
769+
770+
expect(err).toMatchObject({
771+
reason: "auth",
772+
status: 401,
773+
code: "selected_auth_profile_unavailable",
774+
});
775+
});
776+
761777
it("permission_error with organization denial stays auth_permanent", () => {
762778
const err = coerceToFailoverError(
763779
"HTTP 403 permission_error: OAuth authentication is currently not allowed for this organization.",
@@ -794,6 +810,7 @@ describe("failover-error", () => {
794810
sessionId: "session:browser-abcd",
795811
lane: "answer",
796812
status: 429,
813+
code: "selected_auth_profile_unavailable",
797814
});
798815
expect(err.sessionId).toBe("session:browser-abcd");
799816
expect(err.lane).toBe("answer");
@@ -806,6 +823,7 @@ describe("failover-error", () => {
806823
expect(description.lane).toBe("answer");
807824
expect(description.reason).toBe("rate_limit");
808825
expect(description.status).toBe(429);
826+
expect(description.code).toBe("selected_auth_profile_unavailable");
809827
});
810828

811829
it("coerceToFailoverError carries sessionId/lane from context (#42713)", () => {

‎src/agents/failover/user-copy.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
renderFormatErrorCopy,
44
renderBillingReplyCopy,
55
renderCliTimeoutReplyCopy,
6+
renderFailoverCodeUserCopy,
67
renderMissingApiKeyReplyCopy,
78
renderRateLimitOrOverloadedCopy,
89
renderRateLimitReplyCopy,
@@ -11,6 +12,18 @@ import {
1112
describe("failover user copy", () => {
1213
const tokenLimitCopy =
1314
"LLM request rejected: configured maxTokens is 384000, above the provider maximum of 65536. Lower maxTokens and try again.";
15+
16+
it("renders only the allowlisted selected-profile code", () => {
17+
expect(renderFailoverCodeUserCopy("selected_auth_profile_unavailable")).toBe(
18+
"The selected auth profile is unavailable in this agent's OpenClaw credential store. " +
19+
"Import or migrate that credential into the agent, select another configured profile, or run `openclaw configure`, then retry.",
20+
);
21+
expect(renderFailoverCodeUserCopy("plugin_selected_profile_unavailable")).toBeUndefined();
22+
expect(
23+
renderFailoverCodeUserCopy({ code: "selected_auth_profile_unavailable" }),
24+
).toBeUndefined();
25+
});
26+
1427
it("renders transient copy from the classified reason", () => {
1528
const raw = "429 Too Many Requests: model overloaded";
1629
expect(renderRateLimitOrOverloadedCopy({ reason: "rate_limit", raw })).toBe(

‎src/agents/failover/user-copy.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,13 @@ export const AUTH_INVALID_TOKEN_USER_TEXT =
3838
"Authentication failed (provider returned HTTP 401). " +
3939
"Your provider token may have expired — try the request again in a moment. " +
4040
"If the failure persists, re-authenticate this provider.";
41+
const SELECTED_AUTH_PROFILE_UNAVAILABLE_USER_TEXT =
42+
"The selected auth profile is unavailable in this agent's OpenClaw credential store. " +
43+
"Import or migrate that credential into the agent, select another configured profile, or run `openclaw configure`, then retry.";
44+
export const renderFailoverCodeUserCopy = (code: unknown): string | undefined =>
45+
code === "selected_auth_profile_unavailable"
46+
? SELECTED_AUTH_PROFILE_UNAVAILABLE_USER_TEXT
47+
: undefined;
4148
const MODEL_CAPACITY_ERROR_USER_MESSAGE =
4249
"⚠️ Selected model is at capacity. Try a different model, or wait and retry.";
4350
const OVERLOADED_ERROR_USER_MESSAGE =

0 commit comments

Comments
 (0)