Skip to content

Commit 4f9466a

Browse files
authored
fix(auth): make Codex logout recovery actionable (#130866)
Hard OpenAI OAuth failures now offer one shared login action across normal replies, returned provider errors, fallback summaries, Control UI guidance, and automation alerts. OAuth mode survives failure aggregation so API-key failures never receive the Codex pairing action. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent d62f0b8 commit 4f9466a

17 files changed

Lines changed: 458 additions & 104 deletions

‎scripts/e2e/mock-openai-server.mjs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,12 @@ function readResponseEntry(value, label) {
183183
if (value.fail.mode === "drop" && value.fail.status !== undefined) {
184184
throw new Error(`${label} fail cannot combine status and drop`);
185185
}
186+
const message = value.fail.message ?? "mantis injected fault";
187+
if (typeof message !== "string" || !message.trim() || message.length > 2_000) {
188+
throw new Error(`${label} fail message is invalid`);
189+
}
186190
return {
187-
fail: value.fail.mode === "drop" ? { mode: "drop" } : { status },
191+
fail: value.fail.mode === "drop" ? { mode: "drop" } : { status, message },
188192
chunkDelayMs,
189193
};
190194
}
@@ -276,7 +280,7 @@ function writeInjectedFailure(res, fail) {
276280
res.destroy();
277281
return;
278282
}
279-
writeJson(res, fail.status, { error: { message: "mantis injected fault" } });
283+
writeJson(res, fail.status, { error: { message: fail.message } });
280284
}
281285

282286
function splitResponseText(text) {

‎src/agents/auth-profiles/oauth-refresh-failure.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,34 @@ describe("oauth refresh failure hints", () => {
151151
});
152152
});
153153

154+
it("classifies provider requests to log in again", () => {
155+
expect(
156+
classifyOAuthRefreshFailure(
157+
"OAuth token refresh failed for openai: Your session ended. Please log in again.",
158+
),
159+
).toEqual({
160+
provider: "openai",
161+
reason: "sign_in_again",
162+
});
163+
});
164+
165+
it("classifies refresh failures preserved in failover raw error metadata", () => {
166+
expect(
167+
classifyOAuthRefreshFailureError(
168+
new FailoverError("Authentication refresh failed", {
169+
reason: "auth_permanent",
170+
provider: "openai",
171+
profileId: "openai:work",
172+
rawError: "OAuth token refresh failed for openai: refresh_token_invalidated",
173+
}),
174+
),
175+
).toEqual({
176+
provider: "openai",
177+
profileId: "openai:work",
178+
reason: "token_invalidated",
179+
});
180+
});
181+
154182
it("classifies claude-cli subprocess 401 OAuth expiry as a provider refresh failure", () => {
155183
// Error message format emitted by the claude subprocess when its stored
156184
// OAuth token has expired, forwarded through the FailoverError message.

‎src/agents/auth-profiles/oauth-refresh-failure.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { normalizeProviderId } from "@openclaw/model-catalog-core/provider-id";
2+
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
23
import { sanitizeForLog } from "../../../packages/terminal-core/src/ansi.js";
34
import { formatCliCommand } from "../../cli/command-format.js";
45
/**
@@ -153,7 +154,11 @@ export function classifyOAuthRefreshFailureReason(
153154
if (lower.includes("token_invalidated")) {
154155
return "token_invalidated";
155156
}
156-
if (lower.includes("signing in again") || lower.includes("sign in again")) {
157+
if (
158+
lower.includes("signing in again") ||
159+
lower.includes("sign in again") ||
160+
lower.includes("log in again")
161+
) {
157162
return "sign_in_again";
158163
}
159164
if (lower.includes("invalid refresh token")) {
@@ -203,6 +208,18 @@ export function classifyOAuthRefreshFailureError(err: unknown): OAuthRefreshFail
203208
reason: candidate.reason,
204209
};
205210
}
211+
const record = asOptionalRecord(candidate);
212+
const rawError = record?.rawError;
213+
if (typeof rawError === "string") {
214+
const classified = classifyOAuthRefreshFailure(rawError);
215+
if (classified) {
216+
const rawProfileId = record?.profileId;
217+
const profileId = sanitizeOAuthRefreshFailureProfileId(
218+
typeof rawProfileId === "string" ? rawProfileId : undefined,
219+
);
220+
return { ...classified, ...(profileId ? { profileId } : {}) };
221+
}
222+
}
206223
if (seen.has(candidate)) {
207224
return null;
208225
}

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

Lines changed: 34 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -605,42 +605,45 @@ describe("createEmbeddedRunAuthController", () => {
605605
});
606606
});
607607

608-
it("preserves OAuth mode when billing-disabled profiles are all unavailable", async () => {
609-
const harness = createMutableAuthControllerHarness();
610-
const profileId = "custom-openai:oauth";
611-
const controller = createMutableEmbeddedRunAuthController({
612-
harness,
613-
setRuntimeApiKey: vi.fn(),
614-
profileCandidates: [profileId],
615-
fallbackConfigured: true,
616-
authStore: {
617-
version: 1,
618-
profiles: {
619-
[profileId]: {
620-
type: "oauth",
621-
provider: "custom-openai",
622-
access: "access-token",
623-
refresh: "refresh-token",
624-
expires: Date.now() + 60_000,
608+
it.each(["billing", "auth_permanent"] as const)(
609+
"preserves OAuth mode when %s-disabled profiles are all unavailable",
610+
async (disabledReason) => {
611+
const harness = createMutableAuthControllerHarness();
612+
const profileId = "custom-openai:oauth";
613+
const controller = createMutableEmbeddedRunAuthController({
614+
harness,
615+
setRuntimeApiKey: vi.fn(),
616+
profileCandidates: [profileId],
617+
fallbackConfigured: true,
618+
authStore: {
619+
version: 1,
620+
profiles: {
621+
[profileId]: {
622+
type: "oauth",
623+
provider: "custom-openai",
624+
access: "access-token",
625+
refresh: "refresh-token",
626+
expires: Date.now() + 60_000,
627+
},
625628
},
626-
},
627-
usageStats: {
628-
[profileId]: {
629-
disabledUntil: Date.now() + 60_000,
630-
disabledReason: "billing",
629+
usageStats: {
630+
[profileId]: {
631+
disabledUntil: Date.now() + 60_000,
632+
disabledReason,
633+
},
631634
},
632635
},
633-
},
634-
});
636+
});
635637

636-
const error = await controller.initializeAuthProfile().catch((err: unknown) => err);
638+
const error = await controller.initializeAuthProfile().catch((err: unknown) => err);
637639

638-
expect(error).toBeInstanceOf(FailoverError);
639-
expect(error).toMatchObject({
640-
reason: "billing",
641-
authMode: "oauth",
642-
});
643-
});
640+
expect(error).toBeInstanceOf(FailoverError);
641+
expect(error).toMatchObject({
642+
reason: disabledReason,
643+
authMode: "oauth",
644+
});
645+
},
646+
);
644647

645648
it("only enables transient cooldown probing when every automatic profile is transiently cooled", () => {
646649
const now = Date.now();

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,10 @@ export function createEmbeddedRunAuthController(params: {
481481
});
482482
if (params.fallbackConfigured) {
483483
const authMode =
484-
reason === "billing"
484+
reason === "billing" ||
485+
reason === "auth" ||
486+
reason === "auth_permanent" ||
487+
reason === "session_expired"
485488
? resolveSubscriptionAuthModeForProfiles({
486489
store: params.authStore,
487490
profileIds: failoverParams.allInCooldown

‎src/agents/embedded-agent-runner/run/payloads.errors.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,37 @@ describe("buildEmbeddedRunPayloads", () => {
7777
expect(payloads.map((payload) => payload.text)).not.toContain(errorJson);
7878
});
7979

80+
it("turns returned OpenAI refresh failures into Codex login recovery", () => {
81+
const payloads = buildPayloads({
82+
provider: "openai",
83+
lastAssistant: makeAssistant({
84+
stopReason: "error",
85+
errorMessage: "OAuth token refresh failed for openai: refresh_token_invalidated",
86+
content: [],
87+
}),
88+
});
89+
90+
expect(payloads).toEqual([
91+
{
92+
text: expect.stringContaining("/login codex"),
93+
isError: true,
94+
presentation: {
95+
blocks: [
96+
{
97+
type: "buttons",
98+
buttons: [
99+
{
100+
label: "Log in to Codex",
101+
action: { type: "command", command: "/login codex" },
102+
},
103+
],
104+
},
105+
],
106+
},
107+
},
108+
]);
109+
});
110+
80111
it("suppresses mutating tool warnings when an assistant error reply already covers the turn", () => {
81112
const payloads = buildPayloads({
82113
assistantTexts: [errorJson],

‎src/agents/embedded-agent-runner/run/payloads.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* Builds embedded-agent payload objects from attempt inputs and outcomes.
33
*/
44
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
5+
import { buildCodexLoginRecovery } from "../../../auto-reply/codex-login-recovery.js";
56
import type { SourceReplyDeliveryMode } from "../../../auto-reply/get-reply-options.types.js";
67
import {
78
createHeartbeatToolResponsePayload,
@@ -33,6 +34,7 @@ import {
3334
sanitizeAssistantFinalAnswerText,
3435
sanitizeAssistantVisibleText,
3536
} from "../../../shared/text/assistant-visible-text.js";
37+
import { classifyOAuthRefreshFailure } from "../../auth-profiles/oauth-refresh-failure.js";
3638
import {
3739
BILLING_ERROR_USER_MESSAGE,
3840
formatAssistantErrorText,
@@ -219,19 +221,25 @@ export function buildEmbeddedRunPayloads(params: {
219221
const rawErrorMessage = lastAssistantNeedsErrorSurface
220222
? normalizeOptionalString(assistantForPayload?.errorMessage)
221223
: undefined;
224+
const oauthRefreshFailure = rawErrorMessage ? classifyOAuthRefreshFailure(rawErrorMessage) : null;
225+
const codexLoginRecovery = buildCodexLoginRecovery({
226+
provider: oauthRefreshFailure?.provider ?? params.provider,
227+
oauthReason: oauthRefreshFailure?.reason,
228+
});
222229
const errorText =
223230
assistantForPayload && lastAssistantNeedsErrorSurface
224231
? suppressFailureArtifacts
225232
? undefined
226233
: lastAssistantErrored || rawErrorMessage
227-
? formatUserFacingAssistantErrorText(assistantForPayload, {
234+
? (codexLoginRecovery?.hint ??
235+
formatUserFacingAssistantErrorText(assistantForPayload, {
228236
cfg: params.config,
229237
sessionKey: params.sessionKey,
230238
provider: params.provider,
231239
providerOwner: params.providerOwner,
232240
model: params.model,
233241
authMode: params.authMode,
234-
})
242+
}))
235243
: formatAssistantErrorText(assistantForPayload, {
236244
cfg: params.config,
237245
sessionKey: params.sessionKey,
@@ -262,7 +270,11 @@ export function buildEmbeddedRunPayloads(params: {
262270
isTimeoutErrorMessage(rawErrorMessage) &&
263271
errorText === SYNTHESIZED_TIMEOUT_ERROR_TEXT;
264272
if (errorText && !deferAssistantTimeoutError) {
265-
replyItems.push({ text: errorText, isError: true });
273+
replyItems.push({
274+
text: errorText,
275+
isError: true,
276+
...(codexLoginRecovery ? { presentation: codexLoginRecovery.presentation } : {}),
277+
});
266278
}
267279
const reasoningText =
268280
suppressAssistantArtifacts || runAborted || lastAssistantNeedsErrorSurface

‎src/agents/model-fallback-attempt.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,8 @@ export function throwFallbackFailureSummary(params: {
641641
reason: lastAttempt?.reason ?? "unknown",
642642
provider: lastAttempt?.provider,
643643
model: lastAttempt?.model,
644+
// Recovery must not infer OAuth from the provider after candidate errors collapse here.
645+
authMode: lastAttempt?.authMode,
644646
status: lastAttempt?.status,
645647
code: lastAttempt?.code,
646648
cause: params.lastError instanceof Error ? params.lastError : undefined,

‎src/agents/model-fallback-runner.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,10 @@ async function runWithModelFallbackInternal<T>(
400400
profileIds,
401401
});
402402
const authMode =
403-
decision.reason === "billing"
403+
decision.reason === "billing" ||
404+
decision.reason === "auth" ||
405+
decision.reason === "auth_permanent" ||
406+
decision.reason === "session_expired"
404407
? resolveSubscriptionAuthModeForProfiles({ store: authStore, profileIds })
405408
: undefined;
406409

0 commit comments

Comments
 (0)