mastra-ai/mastra · error · ProviderAuthRequiredError
Failed to refresh the OpenAI Codex token.
Error message
Failed to refresh the OpenAI Codex token.
What it means
getCodexBearer checks the stored access token's expiry (Date.now() >= cred.expires) and, when expired, calls storage.getApiKey('openai-codex') to perform a refresh. If the refresh yields no token, it throws ProviderAuthRequiredError('Failed to refresh the OpenAI Codex token.'), since a valid bearer cannot be produced for the request.
Source
Thrown at mastracode/sdk/src/providers/openai-codex.ts:142
* the main agent's fetch (`buildOpenAICodexOAuthFetch`) and the Stagehand
* fetch (`buildCodexStagehandFetch`).
*/
async function getCodexBearer(
authStorage?: CredentialStore,
): Promise<{ accessToken: string; accountId: string | undefined }> {
const storage = authStorage ?? getAuthStorage();
storage.reload();
const cred = storage.get('openai-codex');
if (!cred || cred.type !== 'oauth') {
throw new ProviderAuthRequiredError('Not logged in to OpenAI Codex.');
}
let accessToken = cred.access;
if (Date.now() >= cred.expires) {
const refreshedToken = await storage.getApiKey('openai-codex');
if (!refreshedToken) {
throw new ProviderAuthRequiredError('Failed to refresh the OpenAI Codex token.');
}
accessToken = refreshedToken;
storage.reload();
}
return { accessToken, accountId: (cred as any).accountId as string | undefined };
}
/**
* Build a fetch function that handles OpenAI Codex OAuth.
* Preserves non-authorization headers from init.
* When rewriteUrl is true (default), rewrites /v1/responses and /chat/completions
* to the Codex API endpoint. Set rewriteUrl: false for gateway usage where the
* SDK already targets the correct URL.
*/
export function buildOpenAICodexOAuthFetch(
opts: { authStorage?: CredentialStore; rewriteUrl?: boolean } = {},
): typeof fetch {View on GitHub (pinned to 75dd419e61)
Solutions
- Re-run the OpenAI Codex OAuth login to get a fresh access/refresh token pair.
- Verify network connectivity to OpenAI's token endpoint (proxy/firewall).
- Check that the stored credential includes a refresh token field.
- Catch ProviderAuthRequiredError and trigger interactive re-login automatically.
Example fix
// before
const { accessToken } = await getCodexBearer(storage); // throws when refresh fails
// after
let bearer;
try {
bearer = await getCodexBearer(storage);
} catch (e) {
if (e instanceof ProviderAuthRequiredError) await codexLogin();
bearer = await getCodexBearer(storage);
} Defensive patterns
Strategy: retry
Validate before calling
const cred = storage.get('openai-codex');
if (cred?.type === 'oauth' && Date.now() >= cred.expires) {
const refreshed = await storage.getApiKey('openai-codex');
if (!refreshed) console.warn('Codex refresh failed; re-login required');
} Type guard
null
Try / catch
try {
return await codexFetch(url, init);
} catch (e) {
if (e instanceof ProviderAuthRequiredError && /refresh/.test(e.message)) {
await codexLogin(); // refresh token is dead; full re-auth
return await codexFetch(url, init);
}
throw e;
} Prevention
- Refresh tokens before expiry in long-running processes.
- Monitor network reachability to OpenAI's token endpoint.
- Treat refresh failure as requiring full re-authentication, not just retry.
When it happens
Trigger: A request through the Codex OAuth fetch when the stored access token is expired AND storage.getApiKey('openai-codex') returns null/undefined — the refresh-token exchange fails or no refresh token is stored.
Common situations: Refresh token revoked or expired (long offline period, re-auth elsewhere invalidating the session); network failure reaching the OpenAI token endpoint; missing refresh-token field in the stored credential; clock skew.
Related errors
- Failed to refresh the GitHub Copilot token.
- No Copilot bearer token
- Failed to refresh the Kimi For Coding token.
- Not logged in to OpenAI Codex.
- Failed to refresh the xAI token.
AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30).
Data as JSON: /api/errors/4cbad5d28bb56ff7.
Report an issue: GitHub.